Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions Age.Tests/StanzaLimitOnWriteTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using AgeSharp;
using Xunit;

namespace Age.Tests;

/// <summary>
/// A header holds at most 1024 recipient stanzas: go-age reads no more, and neither does
/// AgeSharp unless told to. Since v1.4.0 go-age refuses to write more as well (internal/format,
/// commit 2fceb23), and so does AgeSharp, which used to write a file it then refused to read.
/// </summary>
public class StanzaLimitOnWriteTests
{
private const int Most = AgeLimits.MaxRecipientStanzas;
private static readonly byte[] Plaintext = "attack at dawn"u8.ToArray();

// --- up to the limit: written, and read back with the default limits -------------------------

[Fact]
public void AsManyRecipientsAsAHeaderHolds_AreEncryptedTo_AndTheFileIsRead()
{
using var identity = X25519Identity.Generate();
var recipients = new Recipients([identity.Recipient, .. Enumerable.Range(0, Most - 1).Select(_ => new Fake())]);

var file = recipients.Encrypt(Plaintext);

Assert.Equal(Plaintext, new Identities(identity).Decrypt(file));
}

[Fact]
public void OneRecipientWithAsManyStanzasAsAHeaderHolds_IsEncryptedTo_AndTheFileIsRead()
{
using var identity = X25519Identity.Generate();
var recipients = new Recipients(identity.Recipient, new Fake(stanzas: Most - 1));

var file = recipients.Encrypt(Plaintext);

Assert.Equal(Plaintext, new Identities(identity).Decrypt(file));
}

// --- beyond it: refused when encrypting, by every way of encrypting --------------------------

public static TheoryData<string, Action<Recipients, MemoryStream, MemoryStream>> EveryWayToEncrypt => new()
{
{ "Encrypt(bytes)", (to, _, _) => to.Encrypt(Plaintext) },
{ "Encrypt(streams)", (to, a, _) => to.Encrypt(new MemoryStream(Plaintext), a) },
{ "EncryptAsync", (to, a, _) => to.EncryptAsync(new MemoryStream(Plaintext), a).GetAwaiter().GetResult() },
{ "EncryptReader", (to, _, _) => to.EncryptReader(new MemoryStream(Plaintext)) },
{ "EncryptWriter", (to, a, _) => to.EncryptWriter(a) },
{ "EncryptDetached", (to, a, b) => to.EncryptDetached(new MemoryStream(Plaintext), a, b) },
{ "EncryptDetachedAsync", (to, a, b) => to.EncryptDetachedAsync(new MemoryStream(Plaintext), a, b).GetAwaiter().GetResult() },
};

// The set itself may be built, as go-age parses a recipients file of any length: it is
// encrypting to it that is refused, at the call, and before anything is written.
[Theory]
[MemberData(nameof(EveryWayToEncrypt))]
public void OneRecipientTooMany_IsRefused_BeforeAnythingIsWritten(string which, Action<Recipients, MemoryStream, MemoryStream> encrypt)
{
Assert.True(which.Length > 0);
var recipients = new Recipients([.. Enumerable.Range(0, Most + 1).Select(_ => new Fake())]);
var first = new MemoryStream();
var second = new MemoryStream();

var ex = Assert.Throws<AgeException>(() => encrypt(recipients, first, second));

Assert.Equal("too many recipients: 1025, and a header holds at most 1024 recipient stanzas", ex.Message);
Assert.Equal(0, first.Length);
Assert.Equal(0, second.Length);
}

// Each recipient writes at least one stanza, so their number alone settles it. None is
// asked to wrap: a plugin is not started, and no hardware key asks to be touched.
[Fact]
public void WithTooManyRecipients_NoneIsAskedToWrap()
{
var wraps = 0;
var recipients = new Recipients([.. Enumerable.Range(0, Most + 1).Select(_ => new Fake(onWrap: () => wraps++))]);

Assert.Throws<AgeException>(() => recipients.Encrypt(Plaintext));

Assert.Equal(0, wraps);
}

// A recipient may write several stanzas, as a plugin may, so few recipients can be too many
// stanzas. That is known only once they have wrapped.
[Theory]
[InlineData(1, 1025)]
[InlineData(2, 513)]
[InlineData(1024, 2)]
public void FewRecipientsWithTooManyStanzas_AreRefused(int recipientCount, int stanzasOfTheLast)
{
var members = Enumerable.Range(0, recipientCount - 1).Select(_ => new Fake(stanzas: recipientCount == 2 ? 512 : 1))
.Append(new Fake(stanzas: stanzasOfTheLast));
var recipients = new Recipients([.. members]);
var output = new MemoryStream();

var ex = Assert.Throws<AgeException>(() => recipients.Encrypt(new MemoryStream(Plaintext), output));

Assert.Equal("too many recipient stanzas: a header holds at most 1024", ex.Message);
Assert.Equal(0, output.Length);
}

/// <summary>A recipient that writes so many stanzas of a type no identity here knows.</summary>
private sealed class Fake(int stanzas = 1, Action? onWrap = null) : IRecipient
{
public IReadOnlyList<Stanza> Wrap(ReadOnlySpan<byte> fileKey)
{
onWrap?.Invoke();
return [.. Enumerable.Range(0, stanzas).Select(_ => new Stanza("fake", ["arg"], [1, 2, 3]))];
}
}
}
6 changes: 5 additions & 1 deletion Age/AgeLimits.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ internal static class AgeLimits
/// </summary>
public const int MaxHeaderBytes = 2 * 1024 * 1024;

/// <summary>Maximum number of recipient stanzas in a header. 1024, as in go-age.</summary>
/// <summary>
/// Maximum number of recipient stanzas in a header. 1024, as in go-age. Reading refuses
/// more unless <see cref="AgeDecryptOptions.MaxRecipientStanzas"/> says otherwise;
/// encrypting never writes more.
/// </summary>
public const int MaxRecipientStanzas = 1024;

/// <summary>Maximum number of arguments on one stanza line. 128, as in go-age.</summary>
Expand Down
33 changes: 23 additions & 10 deletions Age/Recipients.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ namespace AgeSharp;
/// Building a set checks what can be checked without a file key: it is not empty, holds no
/// null, and a passphrase is not mixed with anything else. The security labels a recipient
/// declares (post-quantum, a plugin's own) come with its stanzas, so they are compared when
/// encrypting, and a mix is refused before anything is written.
/// encrypting, and a mix is refused before anything is written. So is a set that writes more
/// stanzas than a header holds (1024, as in go-age): by default no implementation would read
/// the file.
/// <para>
/// The two kinds of refusal are told apart by type. Misusing the .NET API (no recipients, a
/// null one) is an <see cref="ArgumentException"/>; breaking one of age's own rules (a
/// passphrase not alone, recipients whose labels differ) is an <see cref="AgeException"/>, as
/// go-age returns an error for it.
/// passphrase not alone, recipients whose labels differ, too many stanzas) is an
/// <see cref="AgeException"/>, as go-age returns an error for it.
/// </para>
/// <para>
/// Encrypting does not dispose the streams it is given, nor the recipients.
Expand Down Expand Up @@ -179,7 +181,7 @@ internal static IRecipient ParseSsh(string authorizedKeysLine)
/// <param name="plaintext">Read once, start to end.</param>
/// <param name="ciphertext">Where the file is written.</param>
/// <param name="options">Whether to armor; binary by default.</param>
/// <exception cref="AgeException">The recipients declare different security labels.</exception>
/// <exception cref="AgeException">The recipients declare different security labels, or write more stanzas than a header holds (1024).</exception>
public void Encrypt(Stream plaintext, Stream ciphertext, AgeEncryptOptions? options = null)
{
ArgumentNullException.ThrowIfNull(ciphertext);
Expand All @@ -193,7 +195,7 @@ public void Encrypt(Stream plaintext, Stream ciphertext, AgeEncryptOptions? opti
/// such as secrets or database fields.
/// </summary>
/// <remarks>The copy of the plaintext this makes on the way in is cleared before returning.</remarks>
/// <exception cref="AgeException">The recipients declare different security labels.</exception>
/// <exception cref="AgeException">The recipients declare different security labels, or write more stanzas than a header holds (1024).</exception>
public byte[] Encrypt(ReadOnlySpan<byte> plaintext, AgeEncryptOptions? options = null)
{
var copy = plaintext.ToArray();
Expand All @@ -218,7 +220,7 @@ public byte[] Encrypt(ReadOnlySpan<byte> plaintext, AgeEncryptOptions? options =
/// Wrapping the file key happens before the first read. For a plugin recipient that is a
/// synchronous exchange with the plugin's process.
/// </remarks>
/// <exception cref="AgeException">The recipients declare different security labels.</exception>
/// <exception cref="AgeException">The recipients declare different security labels, or write more stanzas than a header holds (1024).</exception>
public async Task EncryptAsync(Stream plaintext, Stream ciphertext, AgeEncryptOptions? options = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(ciphertext);
Expand All @@ -235,7 +237,7 @@ public async Task EncryptAsync(Stream plaintext, Stream ciphertext, AgeEncryptOp
/// synchronously or asynchronously. Dispose it when done; that leaves
/// <paramref name="plaintext"/> open.
/// </summary>
/// <exception cref="AgeException">The recipients declare different security labels.</exception>
/// <exception cref="AgeException">The recipients declare different security labels, or write more stanzas than a header holds (1024).</exception>
public Stream EncryptReader(Stream plaintext, AgeEncryptOptions? options = null)
{
ArgumentNullException.ThrowIfNull(plaintext);
Expand Down Expand Up @@ -263,7 +265,7 @@ public Stream EncryptReader(Stream plaintext, AgeEncryptOptions? options = null)
/// Once a write has thrown, every later write throws the same exception and disposing writes
/// nothing more, so a failed file is never completed.
/// </remarks>
/// <exception cref="AgeException">The recipients declare different security labels.</exception>
/// <exception cref="AgeException">The recipients declare different security labels, or write more stanzas than a header holds (1024).</exception>
public Stream EncryptWriter(Stream ciphertext, AgeEncryptOptions? options = null)
{
ArgumentNullException.ThrowIfNull(ciphertext);
Expand All @@ -288,7 +290,7 @@ public Stream EncryptWriter(Stream ciphertext, AgeEncryptOptions? options = null
/// Takes no options: armor wraps a whole age file, which a detached header and payload are
/// not.
/// </remarks>
/// <exception cref="AgeException">The recipients declare different security labels.</exception>
/// <exception cref="AgeException">The recipients declare different security labels, or write more stanzas than a header holds (1024).</exception>
public void EncryptDetached(Stream plaintext, Stream header, Stream payload)
{
ArgumentNullException.ThrowIfNull(plaintext);
Expand All @@ -304,7 +306,7 @@ public void EncryptDetached(Stream plaintext, Stream header, Stream payload)
}

/// <summary>The asynchronous form of <see cref="EncryptDetached"/>.</summary>
/// <exception cref="AgeException">The recipients declare different security labels.</exception>
/// <exception cref="AgeException">The recipients declare different security labels, or write more stanzas than a header holds (1024).</exception>
public async Task EncryptDetachedAsync(Stream plaintext, Stream header, Stream payload, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plaintext);
Expand Down Expand Up @@ -352,6 +354,13 @@ private static (byte[] Nonce, PayloadKey Key) NewPayloadKey(FileKey fileKey)
/// </remarks>
private Header BuildHeader(ReadOnlySpan<byte> fileKey)
{
// A header holds so many stanzas and no more: go-age reads no more and, since v1.4.0,
// writes no more. Each recipient writes at least one, so their number alone can settle
// it, before any of them is asked to wrap: a plugin is not started for a file that
// will not be written.
if (_members.Length > AgeLimits.MaxRecipientStanzas)
throw new AgeException($"too many recipients: {_members.Length}, and a header holds at most {AgeLimits.MaxRecipientStanzas} recipient stanzas");

var header = new Header();
HashSet<string>? firstLabels = null;

Expand All @@ -378,6 +387,10 @@ private Header BuildHeader(ReadOnlySpan<byte> fileKey)
throw new AgeException(IncompatibleLabels(firstLabels, labelSet));

header.Stanzas.AddRange(stanzas);

// A recipient may write several stanzas, as a plugin may, so this is known only now.
if (header.Stanzas.Count > AgeLimits.MaxRecipientStanzas)
throw new AgeException($"too many recipient stanzas: a header holds at most {AgeLimits.MaxRecipientStanzas}");
}

// Checked again after wrapping, for a custom recipient that writes a scrypt stanza, or
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ Everything this library throws while reading or writing a file is an `AgeExcepti
| `AgeAuthenticationException` | A cryptographic check failed: the header MAC, a payload chunk, or a truncated or extended file. Tampered with or damaged |
| `NoIdentityMatchException` | None of the identities opened any of the file's stanzas |
| `AgePluginException` | A plugin failed to start, misbehaved, or reported an error |
| `AgeException` itself | A caller's mistake found only mid-way, such as recipients with different security labels |
| `AgeException` itself | A caller's mistake found only mid-way, such as recipients with different security labels, or more recipient stanzas than a header holds |

Parsing a key, recipient or identity from text throws `FormatException`, as .NET's own
`Parse` methods do.
Expand Down Expand Up @@ -511,7 +511,9 @@ exhaust memory. The limits are options of `AgeDecryptOptions`:
with.Decrypt(input, output, new AgeDecryptOptions { MaxRecipientStanzas = 4096 });
```

Exceeding a limit throws `AgeFormatException`. The age
Exceeding a limit throws `AgeFormatException`. Encrypting never writes a header past
the stanza limit: more than 1024 recipient stanzas is an `AgeException`, as in go-age
from v1.4.0 on, whatever limit a reader might be given. The age
[specification](https://github.com/C2SP/C2SP/blob/main/age.md) sets no such
bounds. The three header limits are the ones the Go implementation applies from
v1.3.2 on, so both accept and reject the same files; the armor line limit is
Expand Down
Loading
Loading