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 8 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 @@ -16,6 +16,7 @@
"/src/libraries/Common/tests/System/Net/Prerequisites/Deployment/setup_certificates.ps1",
"/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.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
157 changes: 157 additions & 0 deletions src/libraries/Common/src/Internal/Cryptography/PemKeyImportHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// 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("ENCRYPTED PRIVATE KEY"))
{
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);

try
{
if (!Convert.TryFromBase64Chars(base64Contents, decodeBuffer, out int 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, base64size);
Copy link
Member

Choose a reason for hiding this comment

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

In bizarro-world, where TryFromBase64Chars reports a different answer in a release build, let's use the answer it gave.

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

importAction(password, decodedBase64, out _);
}
finally
{
CryptoPool.Return(decodeBuffer, clearSize: base64size);
}
}

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("ENCRYPTED PRIVATE KEY"))
Copy link
Member

Choose a reason for hiding this comment

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

I don't know if we need a PemHeaders constants class; but at least using a const string in this class would be better than repeating the literal across methods.

{
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);

try
{
if (!Convert.TryFromBase64Chars(base64Contents, decodeBuffer, out int 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, base64size);
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: base64size);
}
}
}
}
Loading