Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Import PEM keys #34086

Merged
merged 20 commits into from
Apr 9, 2020
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
1 change: 1 addition & 0 deletions .config/CredScanSuppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs",
"/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.LimitedPrivate.cs",
"/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs",
"/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyPemTests.cs",
"/src/libraries/System.Data.Common/tests/System/Data/Common/DbConnectionStringBuilderTest.cs",
"/src/libraries/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs",
"/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/constants.cs",
Expand Down
170 changes: 170 additions & 0 deletions src/libraries/Common/src/Internal/Cryptography/PemKeyImportHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable
using System;
using System.Diagnostics;
using System.Security.Cryptography;

namespace Internal.Cryptography
{
internal static class PemKeyImportHelpers
{
public delegate void ImportKeyAction(ReadOnlySpan<byte> source, out int bytesRead);
public delegate ImportKeyAction? FindImportActionFunc(ReadOnlySpan<char> label);
public delegate void ImportEncryptedKeyAction<TPass>(
ReadOnlySpan<TPass> password,
ReadOnlySpan<byte> source,
out int bytesRead);

public static void ImportEncryptedPem<TPass>(
ReadOnlySpan<char> input,
ReadOnlySpan<TPass> password,
ImportEncryptedKeyAction<TPass> importAction)
{
bool foundEncryptedPem = false;
PemFields foundFields = default;
ReadOnlySpan<char> foundSlice = default;

ReadOnlySpan<char> pem = input;
while (PemEncoding.TryFind(pem, out PemFields fields))
{
ReadOnlySpan<char> label = pem[fields.Label];

if (label.SequenceEqual(PemLabels.EncryptedPkcs8PrivateKey))
{
if (foundEncryptedPem)
{
throw new ArgumentException(SR.Argument_PemImport_AmbiguousPem, nameof(input));
}

foundEncryptedPem = true;
foundFields = fields;
foundSlice = pem;
}

Index offset = fields.Location.End;
pem = pem[offset..];
}

if (!foundEncryptedPem)
{
throw new ArgumentException(SR.Argument_PemImport_NoPemFound, nameof(input));
}

ReadOnlySpan<char> base64Contents = foundSlice[foundFields.Base64Data];
int base64size = foundFields.DecodedDataLength;
byte[] decodeBuffer = CryptoPool.Rent(base64size);
int bytesWritten = 0;

try
{
if (!Convert.TryFromBase64Chars(base64Contents, decodeBuffer, out bytesWritten))
{
// Couldn't decode base64. We shouldn't get here since the
// contents are pre-validated.
Debug.Fail("Base64 decoding failed on already validated contents.");
throw new ArgumentException();
}

Debug.Assert(bytesWritten == base64size);
Span<byte> decodedBase64 = decodeBuffer.AsSpan(0, bytesWritten);

// Don't need to check the bytesRead here. We're already operating
// on an input which is already a parsed subset of the input.
importAction(password, decodedBase64, out _);
}
finally
{
CryptoPool.Return(decodeBuffer, clearSize: bytesWritten);
}
}

public static void ImportPem(ReadOnlySpan<char> input, FindImportActionFunc callback)
{
ImportKeyAction? importAction = null;
PemFields foundFields = default;
ReadOnlySpan<char> foundSlice = default;
bool containsEncryptedPem = false;

ReadOnlySpan<char> pem = input;
while (PemEncoding.TryFind(pem, out PemFields fields))
{
ReadOnlySpan<char> label = pem[fields.Label];
ImportKeyAction? action = callback(label);

// Caller knows how to handle this PEM by label.
if (action != null)
{
// There was a previous PEM that could have been handled,
// which means this is ambiguous and contains multiple
// importable keys. Or, this contained an encrypted PEM.
// For purposes of encrypted PKCS8 with another actionable
// PEM, we will throw a duplicate exception.
if (importAction != null || containsEncryptedPem)
{
throw new ArgumentException(SR.Argument_PemImport_AmbiguousPem, nameof(input));
}

importAction = action;
foundFields = fields;
foundSlice = pem;
}
else if (label.SequenceEqual(PemLabels.EncryptedPkcs8PrivateKey))
{
if (importAction != null || containsEncryptedPem)
{
throw new ArgumentException(SR.Argument_PemImport_AmbiguousPem, nameof(input));
}

containsEncryptedPem = true;
}

Index offset = fields.Location.End;
pem = pem[offset..];
}

// The only PEM found that could potentially be used is encrypted PKCS8,
// but we won't try to import it with a null or blank password, so
// throw.
if (containsEncryptedPem)
{
throw new ArgumentException(SR.Argument_PemImport_EncryptedPem, nameof(input));
bartonjs marked this conversation as resolved.
Show resolved Hide resolved
}

// We went through the PEM and found nothing that could be handled.
if (importAction is null)
{
throw new ArgumentException(SR.Argument_PemImport_NoPemFound, nameof(input));
}

ReadOnlySpan<char> base64Contents = foundSlice[foundFields.Base64Data];
int base64size = foundFields.DecodedDataLength;
byte[] decodeBuffer = CryptoPool.Rent(base64size);
int bytesWritten = 0;

try
{
if (!Convert.TryFromBase64Chars(base64Contents, decodeBuffer, out bytesWritten))
{
// Couldn't decode base64. We shouldn't get here since the
// contents are pre-validated.
Debug.Fail("Base64 decoding failed on already validated contents.");
throw new ArgumentException();
}

Debug.Assert(bytesWritten == base64size);
Span<byte> decodedBase64 = decodeBuffer.AsSpan(0, bytesWritten);

// Don't need to check the bytesRead here. We're already operating
// on an input which is already a parsed subset of the input.
importAction(decodedBase64, out _);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume that you've made a conscious choice to say it's OK to ignore trailing bytes here, since there's no check that the import action reports bytesRead == base64Size.

I can accept that... but a comment saying so would be nice. (Reasonable justification includes that the key has already been modified, so throwing and not have the same object modification effect)

}
finally
{
CryptoPool.Return(decodeBuffer, clearSize: bytesWritten);
}
}
}
}
16 changes: 16 additions & 0 deletions src/libraries/Common/src/System/Security/Cryptography/PemLabels.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace System.Security.Cryptography
{
internal static class PemLabels
{
internal const string Pkcs8PrivateKey = "PRIVATE KEY";
internal const string EncryptedPkcs8PrivateKey = "ENCRYPTED PRIVATE KEY";
internal const string SpkiPublicKey = "PUBLIC KEY";
internal const string RsaPublicKey = "RSA PUBLIC KEY";
internal const string RsaPrivateKey = "RSA PRIVATE KEY";
internal const string EcPrivateKey = "EC PRIVATE KEY";
}
}
Loading