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
229 changes: 229 additions & 0 deletions Age.Tests/DocumentedExceptionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
using System.Security.Cryptography;
using AgeSharp;
using AgeSharp.Crypto;
using Xunit;

namespace Age.Tests;

/// <summary>
/// Failures that used to come out as an exception nobody documented, or as one that blamed the
/// wrong party: a caller's null as a <see cref="NullReferenceException"/>, a plugin's mistake as
/// a malformed file, a small RSA key as a bad argument to a constructor the caller never called.
/// </summary>
public class DocumentedExceptionsTests
{
// --- a caller's null is an ArgumentNullException -------------------------------------------

public static TheoryData<string, Action> ParsersGivenNull => new()
{
{ "Identities.Parse", () => Identities.Parse(null!) },
{ "Identities.ParseOne", () => Identities.ParseOne(null!) },
{ "Recipients.Parse", () => Recipients.Parse(null!) },
{ "Recipients.ParseOne", () => Recipients.ParseOne(null!) },
{ "X25519Identity.Parse", () => X25519Identity.Parse(null!) },
{ "X25519Recipient.Parse", () => X25519Recipient.Parse(null!) },
{ "MlKem768X25519Identity.Parse", () => MlKem768X25519Identity.Parse(null!) },
{ "MlKem768X25519Recipient.Parse", () => MlKem768X25519Recipient.Parse(null!) },
{ "P256TagRecipient.Parse", () => P256TagRecipient.Parse(null!) },
{ "MlKem768P256TagRecipient.Parse", () => MlKem768P256TagRecipient.Parse(null!) },
{ "PluginRecipient.Parse", () => PluginRecipient.Parse(null!) },
{ "PluginIdentity.Parse", () => PluginIdentity.Parse(null!) },
{ "SshIdentity.Parse(pem)", () => SshIdentity.Parse(null!) },
{ "SshIdentity.Parse(pem, passphrase)", () => SshIdentity.Parse(null!, () => []) },
{ "SshIdentity.Parse(pem, publicKey, passphrase)", () => SshIdentity.Parse(null!, "ssh-rsa AAAA", () => []) },
{ "SshEd25519Identity.Parse", () => SshEd25519Identity.Parse(null!) },
{ "SshRsaIdentity.Parse", () => SshRsaIdentity.Parse(null!) },
{ "SshEd25519Recipient.Parse", () => SshEd25519Recipient.Parse(null!) },
{ "SshRsaRecipient.Parse", () => SshRsaRecipient.Parse(null!) },
};

[Theory]
[MemberData(nameof(ParsersGivenNull))]
public void AParserGivenNull_ThrowsArgumentNullException(string which, Action parse)
{
Assert.True(which.Length > 0);
Assert.Throws<ArgumentNullException>(parse);
}

public static TheoryData<string, Func<IIdentity>> EveryIdentity => new()
{
{ "X25519", X25519Identity.Generate },
{ "ML-KEM-768-X25519", MlKem768X25519Identity.Generate },
{ "passphrase", () => new Passphrase("pw") },
{ "SSH Ed25519", () => SshEd25519Identity.Parse(SshKeys.Ed25519Pem()) },
{ "SSH RSA", () => SshRsaIdentity.Parse(SshKeys.RsaPem()) },
{ "plugin", () => PluginIdentity.Parse(Bech32.Encode("AGE-PLUGIN-FROOD-", [1]).ToUpperInvariant()) },
{ "file key", () => new FileKeyIdentity(FileKey.From(new byte[FileKey.Size])) },
};

[Theory]
[MemberData(nameof(EveryIdentity))]
public void AnIdentityGivenANullStanza_ThrowsArgumentNullException(string which, Func<IIdentity> make)
{
Assert.True(which.Length > 0);
using var identity = make();

Assert.Throws<ArgumentNullException>(() => identity.TryUnwrap((Stanza)null!, new byte[FileKey.Size]));
Assert.Throws<ArgumentNullException>(() => identity.TryUnwrap((IReadOnlyList<Stanza>)null!, new byte[FileKey.Size]));
}

// --- a small RSA key is refused where it would be used, as go-age refuses it ----------------

// go-age decrypts with an RSA key of any size, and so does AgeSharp; neither encrypts to one
// under 2048 bits. The identity still has a recipient, as the interface says it has: it is
// wrapping to it that is refused.
[Fact]
public void ASmallRsaIdentity_HasARecipient_WhichRefusesToWrap()
{
using var rsa = RSA.Create(1024);
using var identity = SshRsaIdentity.Parse(rsa.ExportRSAPrivateKeyPem());

var recipient = identity.Recipient;
Assert.Same(recipient, ((IIdentityWithRecipient)identity).Recipient);
Assert.StartsWith("ssh-rsa ", recipient.ToString(), StringComparison.Ordinal);

var ex = Assert.Throws<AgeException>(() => new Recipients(recipient).Encrypt("x"u8));
Assert.Equal("RSA key must be at least 2048 bits, got 1024", ex.Message);
}

// The same key read as a recipient is refused at once, as before.
[Fact]
public void ASmallRsaRecipientLine_IsStillRefusedWhenParsed()
{
using var rsa = RSA.Create(1024);
using var identity = SshRsaIdentity.Parse(rsa.ExportRSAPrivateKeyPem());

var ex = Assert.Throws<FormatException>(() => Recipients.ParseOne(identity.Recipient.ToString()));
Assert.Equal("RSA key must be at least 2048 bits, got 1024", ex.Message);
}

// A passphrase-protected key is no different: it used to be refused when it was read, so a
// file made for it long ago could not be opened at all.
[Fact]
public void ASmallProtectedRsaIdentity_Decrypts_AndRefusesToWrap()
{
var asked = 0;
var pem = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "TestData", "EncryptedSsh", "rsa_1024_aes256ctr"));

using var identity = SshIdentity.Parse(pem, () =>
{
asked++;
return "hunter2".ToCharArray();
});

var recipient = ((IIdentityWithRecipient)identity).Recipient;
var refused = Assert.Throws<AgeException>(() => new Recipients(recipient).Encrypt("x"u8));
Assert.Equal("RSA key must be at least 2048 bits, got 1024", refused.Message);
Assert.Equal(0, asked);

// Neither AgeSharp nor go-age writes such a stanza any more, so the test makes one: the
// file key under RSA-OAEP with SHA-256 and age's label, tagged with the key's fingerprint.
byte[] fileKey = [.. Enumerable.Range(1, 16).Select(i => (byte)i)];
var wire = Convert.FromBase64String(recipient.ToString()!.Split(' ')[1]);
var oaep = new Org.BouncyCastle.Crypto.Encodings.OaepEncoding(
new Org.BouncyCastle.Crypto.Engines.RsaBlindedEngine(),
new Org.BouncyCastle.Crypto.Digests.Sha256Digest(), new Org.BouncyCastle.Crypto.Digests.Sha256Digest(),
"age-encryption.org/v1/ssh-rsa"u8.ToArray());
oaep.Init(true, Org.BouncyCastle.Crypto.Utilities.OpenSshPublicKeyUtilities.ParsePublicKey(wire));
var stanza = new Stanza("ssh-rsa", [Base64Unpadded.Encode(SHA256.HashData(wire).AsSpan(0, 4))], oaep.ProcessBlock(fileKey, 0, fileKey.Length));

var unwrapped = new byte[FileKey.Size];
Assert.True(identity.TryUnwrap(stanza, unwrapped));
Assert.Equal(fileKey, unwrapped);
Assert.Equal(1, asked);
}

// --- a plugin's mistake is the plugin's -----------------------------------------------------

[Theory]
[InlineData("QUFB", 3)]
[InlineData("", 0)]
[InlineData("AAAAAAAAAAAAAAAAAAAAAAA", 17)]
public void AFileKeyOfTheWrongSizeFromAPlugin_IsAPluginException(string body, int size)
{
var identity = PluginIdentity.Parse(Bech32.Encode("AGE-PLUGIN-FROOD-", [1]).ToUpperInvariant());
var conn = new PluginConnection(new StringReader($"-> file-key 0\n{body}\n-> done\n\n"), new StringWriter());

var ex = Assert.Throws<AgePluginException>(() => identity.UnwrapWithConnection(conn, [new Stanza("frood", [], [1])]));

Assert.Equal($"the plugin sent a file key of {size} bytes; a file key is 16 bytes", ex.Message);
}

// --- a plugin author's mistake still ends in an exit code -----------------------------------

private static readonly string FroodRecipient = Bech32.Encode("age1frood", [1]);
private static readonly string FroodIdentity = Bech32.Encode("AGE-PLUGIN-FROOD-", [1]).ToUpperInvariant();

[Fact]
public void AnIdentityHandlerThatReturnsNull_IsThatIdentitysError()
{
var plugin = new AgePlugin("frood");
plugin.HandleIdentity(_ => null!);

var outcome = InProcessPlugin.Run(plugin, "identity-v1", conn =>
{
conn.WriteStanza("add-identity", [FroodIdentity], []);
conn.WriteStanza("recipient-stanza", ["0", "frood"], [1]);
conn.WriteStanza("done", [], []);
var reply = conn.ReadStanza();
conn.WriteStanza("ok", [], []);
return reply;
});

AssertItsError(outcome, "identity");
}

[Fact]
public void ARecipientHandlerThatReturnsNull_IsThatRecipientsError()
{
var plugin = new AgePlugin("frood");
plugin.HandleRecipient(_ => null!);

var outcome = InProcessPlugin.Run(plugin, "recipient-v1", conn =>
{
conn.WriteStanza("add-recipient", [FroodRecipient], []);
conn.WriteStanza("wrap-file-key", [], new byte[16]);
conn.WriteStanza("done", [], []);
var reply = conn.ReadStanza();
conn.WriteStanza("ok", [], []);
return reply;
});

AssertItsError(outcome, "recipient");
}

[Fact]
public void ARecipientThatWrapsToANullStanza_IsThatRecipientsError()
{
var plugin = new AgePlugin("frood");
plugin.HandleRecipient(_ => new WrapsToNull());

var outcome = InProcessPlugin.Run(plugin, "recipient-v1", conn =>
{
conn.WriteStanza("add-recipient", [FroodRecipient], []);
conn.WriteStanza("wrap-file-key", [], new byte[16]);
conn.WriteStanza("done", [], []);
var reply = conn.ReadStanza();
conn.WriteStanza("ok", [], []);
return reply;
});

AssertItsError(outcome, "recipient");
}

// The plugin told the client which key failed, and exited as go-age's plugins do for one.
private static void AssertItsError(InProcessPlugin.Outcome<(string Type, string[] Args, byte[] Body)?> outcome, string kind)
{
Assert.Null(outcome.ClientFailure);
Assert.Equal(3, outcome.ExitCode);

var reply = Assert.NotNull(outcome.Result);
Assert.Equal("error", reply.Type);
Assert.Equal([kind, "0"], reply.Args);
}

private sealed class WrapsToNull : IRecipient
{
public IReadOnlyList<Stanza> Wrap(ReadOnlySpan<byte> fileKey) => [null!];
}
}
6 changes: 4 additions & 2 deletions Age.Tests/SshTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -595,8 +595,10 @@ public void RejectsSmallKey()

var wireBytes = OpenSshPublicKeyUtilities.EncodePublicKey(kp.Public);

Assert.Throws<ArgumentException>(() =>
new SshRsaRecipient((RsaKeyParameters)kp.Public, wireBytes));
// Refused where it is read; an identity's own recipient is refused when it wraps
// (DocumentedExceptionsTests).
var ex = Assert.Throws<FormatException>(() => SshRsaRecipient.Parse($"ssh-rsa {Convert.ToBase64String(wireBytes)}"));
Assert.Equal("RSA key must be at least 2048 bits, got 1024", ex.Message);
}

[Fact]
Expand Down
17 changes: 17 additions & 0 deletions Age.Tests/TestData/EncryptedSsh/rsa_1024_aes256ctr
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABDsVt/7Eh
7FD2fFwvbQ+ADzAAAAGAAAAAEAAACXAAAAB3NzaC1yc2EAAAADAQABAAAAgQCxcHikmV9i
HMBB+CBgY4FScAT1GgxCIeFVvOoUanFTYJ4SgQtA12hffimq+UgkIWiArMkWu1zEvX7EAc
dZ1U/KNi/FkLoq6VA6yzXDHS1YBNpIV8WxAnOaa7JpJXlPBrF3L35L8Y1dlDEY4HT6ujBx
dDCAx88Wx1SbBii/AsA8EQAAAgBVdrSjHK6nKWPedKjrcrcpU3raAfK0ksy9Nh0hJE0MTN
/2WzMg7viLt2T7JuaHuoB3gYuQVnEYF7uLuBsm4udL4j5pFNLopwJxXPjFuAlDCSuipT0v
pO9gwQtaEZjh9OGJFHeXhsuQWcaQf/agD7ZervDx24Vje64zK1TWsziUKKYakagtV9fPl3
pgzlw5oEzwqIseDAT7SASx3MXwv17uaUzC0g8+UWef90G9AYfM/NSn6LHvItE2jvLR/SAR
1ZjST1Bi0xYOjO7vf4uI6cSpbmaRUfy+pFDbA8Xl6ANC7pVRw+A2QNquMjjwe+VcNMXM9P
fEYtRMzs4o3yds5GR4bLrAhWId1yvAYcUWh2gSVtUzDgUGKQtkOq4gNjWJ1VfTNsQCq+uy
uf05UQgTCghPjmYhpGS3290eIN7Pnn0WkE0Yeux3km8O1kcVLHqJFG+29arsXafYGhRi9B
TfAzJ+nWMf2RfUNsGDC15awry2BzRqqn2jTQAwrJyDwA4Ozn2vi6r8xyylLQuTs7jDbufB
UPRHBizcdRgEDph/rg7U/bvmjL7IBRs8POAdDLMi9oAKlymzbqVHKhAYtgTI4o41ZYbcCb
VHH6hrPuTVMfp0XFFD/WYZo/fm2l6HgtH9uFe8GsjiH8mmxE4XxmOAApQFDuLS3VdEzXm1
cdTRS50KAQ==
-----END OPENSSH PRIVATE KEY-----
7 changes: 6 additions & 1 deletion Age/Plugin/AgePlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,9 @@ private int WrapAll(List<string> recipientStrings, List<string> identityStrings,
if (wrapped.Stanzas is not { Count: > 0 })
return KeyError(kind, index, $"recipient {recipient.GetType().Name} produced no stanzas");

if (wrapped.Stanzas.Contains(null!))
return KeyError(kind, index, $"recipient {recipient.GetType().Name} produced a null stanza");

stanzas[f].AddRange(wrapped.Stanzas);
}
}
Expand Down Expand Up @@ -696,7 +699,9 @@ private bool TryParse<T>(string encoded, string kind, int index, Func<string, (s
if (handler is null)
throw new FormatException(unsupported);

value = handler(data);
// A handler that returns nothing is the plugin author's mistake, and still this
// key's error to the client rather than an exception out of Run.
value = handler(data) ?? throw new InvalidOperationException($"the plugin's {kind} handler returned null");
return true;
}
catch (Exception ex)
Expand Down
2 changes: 2 additions & 0 deletions Age/Recipients/EncryptedIdentityFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ public IReadOnlyList<IRecipient> GetRecipients()
/// <exception cref="ObjectDisposedException">The file has been disposed.</exception>
public bool TryUnwrap(Stanza stanza, Span<byte> fileKey)
{
ArgumentNullException.ThrowIfNull(stanza);

lock (_lock)
{
foreach (var identity in Unlocked())
Expand Down
10 changes: 8 additions & 2 deletions Age/Recipients/EncryptedSshIdentity.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Security.Cryptography;
using AgeSharp.Crypto;
using AgeSharp;
using Org.BouncyCastle.Crypto.Parameters;

namespace AgeSharp;

Expand Down Expand Up @@ -30,8 +31,13 @@ internal EncryptedSshIdentity(IProtectedSshKey protectedKey, Func<char[]?> passp
_keyType = SshKeyParser.KeyTypeOfWireBytes(protectedKey.PublicKey);
_tag = SshKeyParser.ComputeTag(protectedKey.PublicKey);

var authorizedKeysLine = $"{_keyType} {Convert.ToBase64String(protectedKey.PublicKey)}";
_recipient = Recipients.ParseSsh(authorizedKeysLine);
var (_, wireBytes, publicKey) = SshKeyParser.ParsePublicKey($"{_keyType} {Convert.ToBase64String(protectedKey.PublicKey)}");

// An identity's recipient, so an RSA key of any size has one, as SshRsaIdentity's has:
// go-age decrypts with a small RSA key, protected or not, and refuses only to wrap to it.
_recipient = publicKey is Ed25519PublicKeyParameters ed25519
? SshEd25519Recipient.From(wireBytes, ed25519)
: new SshRsaRecipient((RsaKeyParameters)publicKey, wireBytes);
}

private readonly IRecipient _recipient;
Expand Down
2 changes: 2 additions & 0 deletions Age/Recipients/FileKeyIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public FileKeyIdentity(FileKey fileKey)
/// <exception cref="ObjectDisposedException">The identity has been disposed.</exception>
public bool TryUnwrap(Stanza stanza, Span<byte> fileKey)
{
ArgumentNullException.ThrowIfNull(stanza);

var key = _fileKey.Bytes;

if (fileKey.Length != FileKey.Size)
Expand Down
2 changes: 2 additions & 0 deletions Age/Recipients/IIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ void IDisposable.Dispose()
/// </summary>
bool TryUnwrap(IReadOnlyList<Stanza> stanzas, Span<byte> fileKey)
{
ArgumentNullException.ThrowIfNull(stanzas);

foreach (var stanza in stanzas)
{
if (TryUnwrap(stanza, fileKey))
Expand Down
2 changes: 2 additions & 0 deletions Age/Recipients/MlKem768P256TagRecipient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ private MlKem768P256TagRecipient(byte[] publicKey) =>
/// <exception cref="FormatException">The string is not a valid tagged post-quantum recipient.</exception>
public static MlKem768P256TagRecipient Parse(string s)
{
ArgumentNullException.ThrowIfNull(s);

var (hrp, data) = Bech32.Decode(s);

if (hrp != Hrp)
Expand Down
3 changes: 3 additions & 0 deletions Age/Recipients/MlKem768X25519Identity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public static MlKem768X25519Identity Generate()
/// <exception cref="FormatException">The string is not a valid ML-KEM-768-X25519 secret key.</exception>
public static MlKem768X25519Identity Parse(string s)
{
ArgumentNullException.ThrowIfNull(s);

if (s != s.ToUpperInvariant())
throw new FormatException("age secret key must be uppercase");

Expand Down Expand Up @@ -116,6 +118,7 @@ public bool TryUnwrap(Stanza stanza, Span<byte> fileKey) =>
// The file key is never in an array of ours: it is decrypted on the stack.
private bool UnwrapInto(Stanza stanza, Span<byte> fileKey)
{
ArgumentNullException.ThrowIfNull(stanza);
FileKey.RequireBuffer(fileKey);

ObjectDisposedException.ThrowIf(_disposed, this);
Expand Down
2 changes: 2 additions & 0 deletions Age/Recipients/MlKem768X25519Recipient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ internal MlKem768X25519Recipient(byte[] publicKey)
/// <exception cref="FormatException">The string is not a valid ML-KEM-768-X25519 recipient.</exception>
public static MlKem768X25519Recipient Parse(string s)
{
ArgumentNullException.ThrowIfNull(s);

var (hrp, data) = Bech32.Decode(s);

if (hrp != Hrp)
Expand Down
2 changes: 2 additions & 0 deletions Age/Recipients/P256TagRecipient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ private P256TagRecipient(byte[] compressedPoint, byte[] point)
/// <exception cref="FormatException">The string is not a valid tagged P-256 recipient.</exception>
public static P256TagRecipient Parse(string s)
{
ArgumentNullException.ThrowIfNull(s);

var (hrp, data) = Bech32.Decode(s);

if (hrp != Hrp)
Expand Down
1 change: 1 addition & 0 deletions Age/Recipients/Passphrase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ public bool TryUnwrap(Stanza stanza, Span<byte> fileKey) =>
// The file key is never in an array of ours: it is decrypted on the stack.
private bool UnwrapInto(Stanza stanza, Span<byte> fileKey)
{
ArgumentNullException.ThrowIfNull(stanza);
FileKey.RequireBuffer(fileKey);

if (stanza.Type != StanzaType)
Expand Down
Loading
Loading