From 5b0ad07b0e76820faa39a39444a12fa46bf8063e Mon Sep 17 00:00:00 2001 From: Patrick Scheid Date: Thu, 3 Dec 2026 22:41:53 +0100 Subject: [PATCH 1/3] Refuse to encrypt to more recipient stanzas than a header holds A header holds at most 1024 recipient stanzas: go-age reads no more, and neither does AgeSharp by default. AgeSharp still wrote more, a file it then refused to read. go-age refuses to write one since v1.4.0 (2fceb23). Encrypting to more is now an AgeException, by every way of encrypting and before anything is written. More than 1024 recipients are refused before any of them is asked to wrap, so no plugin is started for a file that will not be written; fewer recipients that write too many stanzas between them are refused once they have. --- Age.Tests/StanzaLimitOnWriteTests.cs | 112 +++++++++++++++++++++++++++ Age/AgeLimits.cs | 6 +- Age/Recipients.cs | 33 +++++--- README.md | 4 +- TODO.md | 2 +- 5 files changed, 144 insertions(+), 13 deletions(-) create mode 100644 Age.Tests/StanzaLimitOnWriteTests.cs diff --git a/Age.Tests/StanzaLimitOnWriteTests.cs b/Age.Tests/StanzaLimitOnWriteTests.cs new file mode 100644 index 0000000..ae7da66 --- /dev/null +++ b/Age.Tests/StanzaLimitOnWriteTests.cs @@ -0,0 +1,112 @@ +using AgeSharp; +using Xunit; + +namespace Age.Tests; + +/// +/// 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. +/// +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> 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 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(() => 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(() => 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(() => 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); + } + + /// A recipient that writes so many stanzas of a type no identity here knows. + private sealed class Fake(int stanzas = 1, Action? onWrap = null) : IRecipient + { + public IReadOnlyList Wrap(ReadOnlySpan fileKey) + { + onWrap?.Invoke(); + return [.. Enumerable.Range(0, stanzas).Select(_ => new Stanza("fake", ["arg"], [1, 2, 3]))]; + } + } +} diff --git a/Age/AgeLimits.cs b/Age/AgeLimits.cs index 12c7451..6f9be55 100644 --- a/Age/AgeLimits.cs +++ b/Age/AgeLimits.cs @@ -23,7 +23,11 @@ internal static class AgeLimits /// public const int MaxHeaderBytes = 2 * 1024 * 1024; - /// Maximum number of recipient stanzas in a header. 1024, as in go-age. + /// + /// Maximum number of recipient stanzas in a header. 1024, as in go-age. Reading refuses + /// more unless says otherwise; + /// encrypting never writes more. + /// public const int MaxRecipientStanzas = 1024; /// Maximum number of arguments on one stanza line. 128, as in go-age. diff --git a/Age/Recipients.cs b/Age/Recipients.cs index ab3c002..f01c120 100644 --- a/Age/Recipients.cs +++ b/Age/Recipients.cs @@ -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. /// /// The two kinds of refusal are told apart by type. Misusing the .NET API (no recipients, a /// null one) is an ; breaking one of age's own rules (a -/// passphrase not alone, recipients whose labels differ) is an , as -/// go-age returns an error for it. +/// passphrase not alone, recipients whose labels differ, too many stanzas) is an +/// , as go-age returns an error for it. /// /// /// Encrypting does not dispose the streams it is given, nor the recipients. @@ -179,7 +181,7 @@ internal static IRecipient ParseSsh(string authorizedKeysLine) /// Read once, start to end. /// Where the file is written. /// Whether to armor; binary by default. - /// The recipients declare different security labels. + /// The recipients declare different security labels, or write more stanzas than a header holds (1024). public void Encrypt(Stream plaintext, Stream ciphertext, AgeEncryptOptions? options = null) { ArgumentNullException.ThrowIfNull(ciphertext); @@ -193,7 +195,7 @@ public void Encrypt(Stream plaintext, Stream ciphertext, AgeEncryptOptions? opti /// such as secrets or database fields. /// /// The copy of the plaintext this makes on the way in is cleared before returning. - /// The recipients declare different security labels. + /// The recipients declare different security labels, or write more stanzas than a header holds (1024). public byte[] Encrypt(ReadOnlySpan plaintext, AgeEncryptOptions? options = null) { var copy = plaintext.ToArray(); @@ -218,7 +220,7 @@ public byte[] Encrypt(ReadOnlySpan 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. /// - /// The recipients declare different security labels. + /// The recipients declare different security labels, or write more stanzas than a header holds (1024). public async Task EncryptAsync(Stream plaintext, Stream ciphertext, AgeEncryptOptions? options = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(ciphertext); @@ -235,7 +237,7 @@ public async Task EncryptAsync(Stream plaintext, Stream ciphertext, AgeEncryptOp /// synchronously or asynchronously. Dispose it when done; that leaves /// open. /// - /// The recipients declare different security labels. + /// The recipients declare different security labels, or write more stanzas than a header holds (1024). public Stream EncryptReader(Stream plaintext, AgeEncryptOptions? options = null) { ArgumentNullException.ThrowIfNull(plaintext); @@ -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. /// - /// The recipients declare different security labels. + /// The recipients declare different security labels, or write more stanzas than a header holds (1024). public Stream EncryptWriter(Stream ciphertext, AgeEncryptOptions? options = null) { ArgumentNullException.ThrowIfNull(ciphertext); @@ -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. /// - /// The recipients declare different security labels. + /// The recipients declare different security labels, or write more stanzas than a header holds (1024). public void EncryptDetached(Stream plaintext, Stream header, Stream payload) { ArgumentNullException.ThrowIfNull(plaintext); @@ -304,7 +306,7 @@ public void EncryptDetached(Stream plaintext, Stream header, Stream payload) } /// The asynchronous form of . - /// The recipients declare different security labels. + /// The recipients declare different security labels, or write more stanzas than a header holds (1024). public async Task EncryptDetachedAsync(Stream plaintext, Stream header, Stream payload, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(plaintext); @@ -352,6 +354,13 @@ private static (byte[] Nonce, PayloadKey Key) NewPayloadKey(FileKey fileKey) /// private Header BuildHeader(ReadOnlySpan 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? firstLabels = null; @@ -378,6 +387,10 @@ private Header BuildHeader(ReadOnlySpan 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 diff --git a/README.md b/README.md index a616a99..4ba2d6b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/TODO.md b/TODO.md index 4c4cfe0..b6aa4f1 100644 --- a/TODO.md +++ b/TODO.md @@ -49,7 +49,7 @@ The rebuild is done and the public API frozen (rebuild step 8d): `PublicAPI.Ship the surface as frozen, and any change to it from here is a breaking change. Additions since (`AgePlugin`, `PluginIdentity.Recipient`) are in `PublicAPI.Unshipped.txt` until a release. -- [ ] Release notes for the next release, on behaviour changed since the freeze: a payload cut off in its nonce is now `AgeAuthenticationException` (was `AgeFormatException`), as Decrypt documented; a wrong passphrase for an `EncryptedIdentityFile` or a protected SSH key is `AgeAuthenticationException` (was the base `AgeException`, so `catch (AgeException)` still catches it); the SSH identities' `Recipient` throws `ObjectDisposedException` after `Dispose`, as the interface says; an `EncryptedIdentityFile` whose decrypted contents are not an identity file is `AgeFormatException` (was a raw `FormatException`); and, as go-age decides them, an indented armor begin line and non-ASCII in a Bech32 key are refused, an `ssh-ed25519` stanza's share is checked before its tag, and one whose body is not 32 bytes is no match rather than an error; `AgePlugin` refuses a labelled recipient for a client without label support, and takes `unsupported` as a refusal, as rage does; from the 2026-11-30 review: `Recipients.Parse` names a line that is no recipient by its number and no longer repeats it (`ParseOne` still names its argument), and a protected SSH key that decrypts to something unusable says only that, with no text and no inner exception from SSH.NET (a wrong passphrase for a legacy PEM key carries no inner exception either); text an error repeats from a file, a key or a plugin is quoted and cut to a length (`unexpected line in header: "…"`), a plugin's error message and stderr have their control characters written out, a byte in an armor body that is not base64 is named by its value (`0xE9`, was `'?'`), and `NoIdentityMatchException.Message` shows at most eight stanza types of 32 characters each (`StanzaTypes` holds them whole); a null argument to a `Parse` method or to `TryUnwrap` is an `ArgumentNullException` everywhere (ten parsers and every identity threw `NullReferenceException`); an SSH RSA identity under 2048 bits has a `Recipient`, and encrypting to it is an `AgeException` (the property threw `ArgumentException`), and a passphrase-protected one now parses and decrypts (it was refused when read), as go-age decrypts with both; a file key of the wrong size from a plugin is `AgePluginException` (was `AgeFormatException`); an `AgePlugin` handler that returns null, or a recipient that wraps to a null stanza, is that key's error and exit code 3 (was an exception out of `Run`); the plugin protocol's stanzas are read by the header's parser and line rules, in the client and in `AgePlugin`, as go-age reads both with one: a CR anywhere (so CRLF line endings too), a byte outside ASCII, more than 130 arguments, or output that ends partway through a line are refused, where they were accepted or misread, and a malformed stanza is reported as `plugin sent a malformed stanza: …` (or `client sent …`) in the parser's words; `PluginRecipient.Parse` refuses an uppercase recipient and `PluginIdentity.Parse` a lowercase identity, and `AgePlugin` reports either as that key's error, as go-age does; a plugin's stderr is read in a fixed amount of memory, the last 20 lines as far as an error shows them (one line without an end grew the client by as much as the plugin wrote), and a last line the plugin did not end is shown even while something else holds its stderr open +- [ ] Release notes for the next release, on behaviour changed since the freeze: a payload cut off in its nonce is now `AgeAuthenticationException` (was `AgeFormatException`), as Decrypt documented; a wrong passphrase for an `EncryptedIdentityFile` or a protected SSH key is `AgeAuthenticationException` (was the base `AgeException`, so `catch (AgeException)` still catches it); the SSH identities' `Recipient` throws `ObjectDisposedException` after `Dispose`, as the interface says; an `EncryptedIdentityFile` whose decrypted contents are not an identity file is `AgeFormatException` (was a raw `FormatException`); and, as go-age decides them, an indented armor begin line and non-ASCII in a Bech32 key are refused, an `ssh-ed25519` stanza's share is checked before its tag, and one whose body is not 32 bytes is no match rather than an error; `AgePlugin` refuses a labelled recipient for a client without label support, and takes `unsupported` as a refusal, as rage does; from the 2026-11-30 review: `Recipients.Parse` names a line that is no recipient by its number and no longer repeats it (`ParseOne` still names its argument), and a protected SSH key that decrypts to something unusable says only that, with no text and no inner exception from SSH.NET (a wrong passphrase for a legacy PEM key carries no inner exception either); text an error repeats from a file, a key or a plugin is quoted and cut to a length (`unexpected line in header: "…"`), a plugin's error message and stderr have their control characters written out, a byte in an armor body that is not base64 is named by its value (`0xE9`, was `'?'`), and `NoIdentityMatchException.Message` shows at most eight stanza types of 32 characters each (`StanzaTypes` holds them whole); a null argument to a `Parse` method or to `TryUnwrap` is an `ArgumentNullException` everywhere (ten parsers and every identity threw `NullReferenceException`); an SSH RSA identity under 2048 bits has a `Recipient`, and encrypting to it is an `AgeException` (the property threw `ArgumentException`), and a passphrase-protected one now parses and decrypts (it was refused when read), as go-age decrypts with both; a file key of the wrong size from a plugin is `AgePluginException` (was `AgeFormatException`); an `AgePlugin` handler that returns null, or a recipient that wraps to a null stanza, is that key's error and exit code 3 (was an exception out of `Run`); the plugin protocol's stanzas are read by the header's parser and line rules, in the client and in `AgePlugin`, as go-age reads both with one: a CR anywhere (so CRLF line endings too), a byte outside ASCII, more than 130 arguments, or output that ends partway through a line are refused, where they were accepted or misread, and a malformed stanza is reported as `plugin sent a malformed stanza: …` (or `client sent …`) in the parser's words; `PluginRecipient.Parse` refuses an uppercase recipient and `PluginIdentity.Parse` a lowercase identity, and `AgePlugin` reports either as that key's error, as go-age does; a plugin's stderr is read in a fixed amount of memory, the last 20 lines as far as an error shows them (one line without an end grew the client by as much as the plugin wrote), and a last line the plugin did not end is shown even while something else holds its stderr open; encrypting to more than 1024 recipient stanzas is an `AgeException`, as go-age refuses it from v1.4.0 on (AgeSharp wrote the file, and then refused to read it) - [x] Async entry points for encrypt and decrypt: `EncryptAsync`, `DecryptAsync`, `DecryptReaderAsync`, the detached forms and the writers (rebuild steps 4b to 4d) - [x] Before the freeze, a review of the whole surface: plugin callbacks name the plugin and may decline, `PluginRecipient.Parse`/`PluginIdentity.Parse`, plugin labels, one `Func` shape for passphrase sources (rebuild steps 8a to 8c) - [x] Peeking armor detection, so armored input is recognised on non-seekable streams too (pipes, network streams) — rebuild step 3c: `PeekableStream`; `Decrypt`, `DecryptReader` and `AgeHeader.Read` read ahead instead of seeking From a2135a8f2d2ce3828673ada2007d666670f3eaf8 Mon Sep 17 00:00:00 2001 From: Patrick Scheid Date: Thu, 3 Dec 2026 22:43:51 +0100 Subject: [PATCH 2/3] Name the stanza limit among the README's AgeException cases --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ba2d6b..d97fcd8 100644 --- a/README.md +++ b/README.md @@ -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. From 3aac363e7ec9597c3109d035898998cb40e3e6e6 Mon Sep 17 00:00:00 2001 From: Patrick Scheid Date: Thu, 3 Dec 2026 22:47:21 +0100 Subject: [PATCH 3/3] Tick the stanza limit in the go-age 1.4.0 list --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 7878795..7e3e5c2 100644 --- a/TODO.md +++ b/TODO.md @@ -38,7 +38,7 @@ AgeSharp is a library; the command-line tool was removed (use `age` or `rage`). go-age v1.4.0 was released on 2026-12-01, and CI runs against it. Already the same in AgeSharp: the bound on an armor line when reading (go-age 1228921; AgeSharp refuses a line over 1024 bytes after reading 4 KiB of it), control characters in a plugin's error (620b91b; AgeSharp writes them out where go-age replaces them), and the SSH recipients' string form (c602496). The payload reader's change (69eda84) has no counterpart: AgeSharp tells a final chunk by reading one byte ahead and never decrypts a chunk twice. - [ ] Tagged recipients write `p256tagv2` and `mlkem768p256tagv2` stanzas (C2SP/C2SP#402; go-age 1ea02ee, 3b1dac5): the tag is computed from the whole hash of the whole recipient, where the legacy tag used four bytes of the hash (of the P-256 point alone, for the hybrid), so that files to one recipient cannot be linked by trying 2^32 values. AgeSharp writes the legacy `p256tag` and `mlkem768p256tag`, which go-age no longer writes. A change of what AgeSharp writes: an identity that knows only the legacy stanzas ignores the new ones -- [ ] Refuse to write a header with more than 1024 stanzas (go-age 2fceb23). Checked 2026-12-03: AgeSharp encrypts to 1025 recipients, and then refuses to read the file (`header contains more than 1024 recipient stanzas`), as go-age does +- [x] Refuse to write a header with more than 1024 stanzas (go-age 2fceb23) — #151: more is an `AgeException` when encrypting, before anything is written; more than 1024 recipients are refused before any of them wraps. AgeSharp encrypted to 1025 recipients, and then refused to read the file - [ ] `Passphrase` declares no labels; go-age's passphrase recipient now declares `postquantum` beside its random one (29ead69). No effect on a file, since a passphrase is never mixed with another recipient; it matters to code that reads a recipient's labels - [ ] A way to accept post-quantum recipients only, as `age.ParsePostQuantumRecipients` and `tag.ParseHybridRecipient` do, and whether to mark the others obsolete as go-age deprecates its own (b2e1f43). New public API - [ ] A plugin's error of several lines: go-age keeps its line breaks and tabs (620b91b), AgeSharp writes them out as `\n` and `\t` on one line