Imported Upstream version 6.0.0.172

Former-commit-id: f3cc9b82f3e5bd8f0fd3ebc098f789556b44e9cd
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2019-04-12 14:10:50 +00:00
parent 8016999e4d
commit 64ac736ec5
32155 changed files with 3981439 additions and 75368 deletions

View File

@@ -25,6 +25,8 @@
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Text;
using System.Collections.Generic;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography.X509Certificates
@@ -35,12 +37,12 @@ namespace System.Security.Cryptography.X509Certificates
get; set;
}
public abstract X509ExtensionCollection Extensions {
public abstract IEnumerable<X509Extension> Extensions {
get;
}
public abstract bool HasPrivateKey {
get;
public abstract string FriendlyName {
get; set;
}
public abstract X500DistinguishedName IssuerName {
@@ -55,7 +57,7 @@ namespace System.Security.Cryptography.X509Certificates
get;
}
public abstract Oid SignatureAlgorithm {
public abstract string SignatureAlgorithm {
get;
}
@@ -77,10 +79,10 @@ namespace System.Security.Cryptography.X509Certificates
public abstract string GetNameInfo (X509NameType nameType, bool forIssuer);
public abstract void Import (byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags);
public abstract bool Verify (X509Certificate2 thisCertificate);
public abstract void AppendPrivateKeyInfo (StringBuilder sb);
public abstract void Reset ();
}
}

View File

@@ -43,19 +43,15 @@ using MX = Mono.Security.X509;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography.X509Certificates
{
internal class X509Certificate2ImplMono : X509Certificate2Impl
internal class X509Certificate2ImplMono : X509Certificate2ImplUnix
{
bool _archived;
X509ExtensionCollection _extensions;
PublicKey _publicKey;
X500DistinguishedName issuer_name;
X500DistinguishedName subject_name;
Oid signature_algorithm;
X509CertificateImplCollection intermediateCerts;
MX.X509Certificate _cert;
@@ -89,6 +85,24 @@ namespace System.Security.Cryptography.X509Certificates
intermediateCerts = other.intermediateCerts.Clone ();
}
public X509Certificate2ImplMono (byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
switch (X509Certificate2.GetCertContentType (rawData)) {
case X509ContentType.Pkcs12:
_cert = ImportPkcs12 (rawData, password);
break;
case X509ContentType.Cert:
case X509ContentType.Pkcs7:
_cert = new MX.X509Certificate (rawData);
break;
default:
string msg = Locale.GetText ("Unable to decode certificate.");
throw new CryptographicException (msg);
}
}
public override X509CertificateImpl Clone ()
{
ThrowIfContextInvalid ();
@@ -105,28 +119,12 @@ namespace System.Security.Cryptography.X509Certificates
#region Implemented X509CertificateImpl members
public override string Issuer => MX.X501.ToString (Cert.GetIssuerName (), true, ", ", true);
public override string Subject => MX.X501.ToString (Cert.GetSubjectName (), true, ", ", true);
public override string LegacyIssuer => Cert.IssuerName;
public override string LegacySubject => Cert.SubjectName;
public override byte[] RawData => Cert.RawData;
public override byte[] Thumbprint {
get {
ThrowIfContextInvalid ();
SHA1 sha = SHA1.Create ();
return sha.ComputeHash (_cert.RawData);
}
protected override byte[] GetRawCertData ()
{
ThrowIfContextInvalid ();
return Cert.RawData;
}
public override DateTime NotBefore => Cert.ValidFrom.ToLocalTime ();
public override DateTime NotAfter => Cert.ValidUntil.ToLocalTime ();
public override bool Equals (X509CertificateImpl other, out bool result)
{
// Use default implementation
@@ -134,21 +132,6 @@ namespace System.Security.Cryptography.X509Certificates
return false;
}
public override string KeyAlgorithm => Cert.KeyAlgorithm;
public override byte[] KeyAlgorithmParameters => Cert.KeyAlgorithmParameters ?? throw new CryptographicException ();
public override byte[] PublicKeyValue => Cert.PublicKey;
public override byte[] SerialNumber {
get {
ThrowIfContextInvalid ();
var serial = Cert.SerialNumber;
Array.Reverse (serial);
return serial;
}
}
#endregion
// constructors
@@ -160,44 +143,11 @@ namespace System.Security.Cryptography.X509Certificates
// properties
public override bool Archived {
get {
if (_cert == null)
throw new CryptographicException (empty_error);
return _archived;
}
set {
if (_cert == null)
throw new CryptographicException (empty_error);
_archived = value;
}
}
public override X509ExtensionCollection Extensions {
get {
if (_cert == null)
throw new CryptographicException (empty_error);
if (_extensions == null)
_extensions = new X509ExtensionCollection (_cert);
return _extensions;
}
}
// FIXME - Could be more efficient
public override bool HasPrivateKey {
get { return PrivateKey != null; }
}
public override X500DistinguishedName IssuerName {
get {
if (_cert == null)
throw new CryptographicException (empty_error);
if (issuer_name == null)
issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
return issuer_name;
}
}
public override AsymmetricAlgorithm PrivateKey {
get {
if (_cert == null)
@@ -246,6 +196,16 @@ namespace System.Security.Cryptography.X509Certificates
}
}
public override RSA GetRSAPrivateKey ()
{
return PrivateKey as RSA;
}
public override DSA GetDSAPrivateKey ()
{
return PrivateKey as DSA;
}
public override PublicKey PublicKey {
get {
if (_cert == null)
@@ -263,129 +223,8 @@ namespace System.Security.Cryptography.X509Certificates
}
}
public override Oid SignatureAlgorithm {
get {
if (_cert == null)
throw new CryptographicException (empty_error);
if (signature_algorithm == null)
signature_algorithm = new Oid (_cert.SignatureAlgorithm);
return signature_algorithm;
}
}
public override X500DistinguishedName SubjectName {
get {
if (_cert == null)
throw new CryptographicException (empty_error);
if (subject_name == null)
subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
return subject_name;
}
}
public override int Version {
get {
if (_cert == null)
throw new CryptographicException (empty_error);
return _cert.Version;
}
}
// methods
[MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
public override string GetNameInfo (X509NameType nameType, bool forIssuer)
{
switch (nameType) {
case X509NameType.SimpleName:
if (_cert == null)
throw new CryptographicException (empty_error);
// return CN= or, if missing, the first part of the DN
ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
ASN1 dn = Find (commonName, sn);
if (dn != null)
return GetValueAsString (dn);
if (sn.Count == 0)
return String.Empty;
ASN1 last_entry = sn[sn.Count - 1];
if (last_entry.Count == 0)
return String.Empty;
return GetValueAsString (last_entry[0]);
case X509NameType.EmailName:
// return the E= part of the DN (if present)
ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
if (e != null)
return GetValueAsString (e);
return String.Empty;
case X509NameType.UpnName:
// FIXME - must find/create test case
return String.Empty;
case X509NameType.DnsName:
// return the CN= part of the DN (if present)
ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
if (cn != null)
return GetValueAsString (cn);
return String.Empty;
case X509NameType.DnsFromAlternativeName:
// FIXME - must find/create test case
return String.Empty;
case X509NameType.UrlName:
// FIXME - must find/create test case
return String.Empty;
default:
throw new ArgumentException ("nameType");
}
}
static byte[] commonName = { 0x55, 0x04, 0x03 };
static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
private ASN1 Find (byte[] oid, ASN1 dn)
{
if (dn.Count == 0)
return null;
// process SET
for (int i = 0; i < dn.Count; i++) {
ASN1 set = dn[i];
for (int j = 0; j < set.Count; j++) {
ASN1 pair = set[j];
if (pair.Count != 2)
continue;
ASN1 poid = pair[0];
if (poid == null)
continue;
if (poid.CompareValue (oid))
return pair;
}
}
return null;
}
private string GetValueAsString (ASN1 pair)
{
if (pair.Count != 2)
return String.Empty;
ASN1 value = pair[1];
if ((value.Value == null) || (value.Length == 0))
return String.Empty;
if (value.Tag == 0x1E) {
// BMPSTRING
StringBuilder sb = new StringBuilder ();
for (int j = 1; j < value.Value.Length; j += 2)
sb.Append ((char)value.Value[j]);
return sb.ToString ();
} else {
return Encoding.UTF8.GetString (value.Value);
}
}
MX.X509Certificate ImportPkcs12 (byte[] rawData, SafePasswordHandle password)
{
if (password == null || password.IsInvalid)
@@ -446,85 +285,10 @@ namespace System.Security.Cryptography.X509Certificates
}
}
[MonoTODO ("missing KeyStorageFlags support")]
public override void Import (byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
Reset ();
switch (X509Certificate2.GetCertContentType (rawData)) {
case X509ContentType.Pkcs12:
_cert = ImportPkcs12 (rawData, password);
break;
case X509ContentType.Cert:
case X509ContentType.Pkcs7:
_cert = new MX.X509Certificate (rawData);
break;
default:
string msg = Locale.GetText ("Unable to decode certificate.");
throw new CryptographicException (msg);
}
}
[MonoTODO ("X509ContentType.SerializedCert is not supported")]
public override byte[] Export (X509ContentType contentType, SafePasswordHandle password)
{
if (_cert == null)
throw new CryptographicException (empty_error);
switch (contentType) {
case X509ContentType.Cert:
return _cert.RawData;
case X509ContentType.Pfx: // this includes Pkcs12
return ExportPkcs12 (password);
case X509ContentType.SerializedCert:
// TODO
throw new NotSupportedException ();
default:
string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
throw new CryptographicException (msg);
}
}
byte[] ExportPkcs12 (SafePasswordHandle password)
{
if (password == null || password.IsInvalid)
return ExportPkcs12 ((string)null);
var passwordString = password.Mono_DangerousGetString ();
return ExportPkcs12 (passwordString);
}
byte[] ExportPkcs12 (string password)
{
var pfx = new MX.PKCS12 ();
try {
var attrs = new Hashtable ();
var localKeyId = new ArrayList ();
localKeyId.Add (new byte[] { 1, 0, 0, 0 });
attrs.Add (MX.PKCS9.localKeyId, localKeyId);
if (password != null)
pfx.Password = password;
pfx.AddCertificate (_cert, attrs);
var privateKey = PrivateKey;
if (privateKey != null)
pfx.AddPkcs8ShroudedKeyBag (privateKey, attrs);
return pfx.GetBytes ();
} finally {
pfx.Password = null;
}
}
public override void Reset ()
{
_cert = null;
_archived = false;
_extensions = null;
_publicKey = null;
issuer_name = null;
subject_name = null;
signature_algorithm = null;
if (intermediateCerts != null) {
intermediateCerts.Dispose ();
intermediateCerts = null;

View File

@@ -0,0 +1,259 @@
//
// X509Certificate2ImplUnix.cs
//
// Authors:
// Martin Baulig <mabaul@microsoft.com>
//
// Copyright (C) 2018 Xamarin, Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
#endif
using System.Text;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using Internal.Cryptography;
using Internal.Cryptography.Pal;
using Microsoft.Win32.SafeHandles;
#if MONO_SECURITY_ALIAS
using MX = MonoSecurity::Mono.Security.X509;
#else
using MX = Mono.Security.X509;
#endif
namespace System.Security.Cryptography.X509Certificates
{
internal abstract class X509Certificate2ImplUnix : X509Certificate2Impl
{
bool readCertData;
CertificateData certData;
void EnsureCertData ()
{
if (readCertData)
return;
ThrowIfContextInvalid ();
certData = new CertificateData (GetRawCertData ());
readCertData = true;
}
protected abstract byte[] GetRawCertData ();
public sealed override bool Archived {
get {
return false;
}
set {
throw new PlatformNotSupportedException (
SR.Format (SR.Cryptography_Unix_X509_PropertyNotSettable, nameof (Archived)));
}
}
public sealed override string KeyAlgorithm {
get {
EnsureCertData ();
return certData.PublicKeyAlgorithm.AlgorithmId;
}
}
public sealed override byte[] KeyAlgorithmParameters {
get {
EnsureCertData ();
return certData.PublicKeyAlgorithm.Parameters;
}
}
public sealed override byte[] PublicKeyValue {
get {
EnsureCertData ();
return certData.PublicKey;
}
}
public sealed override byte[] SerialNumber {
get {
EnsureCertData ();
return certData.SerialNumber;
}
}
public sealed override string SignatureAlgorithm {
get {
EnsureCertData ();
return certData.SignatureAlgorithm.AlgorithmId;
}
}
public sealed override string FriendlyName {
get { return ""; }
set {
throw new PlatformNotSupportedException (
SR.Format (SR.Cryptography_Unix_X509_PropertyNotSettable, nameof (FriendlyName)));
}
}
public sealed override int Version {
get {
EnsureCertData ();
return certData.Version + 1;
}
}
public sealed override X500DistinguishedName SubjectName {
get {
EnsureCertData ();
return certData.Subject;
}
}
public sealed override X500DistinguishedName IssuerName {
get {
EnsureCertData ();
return certData.Issuer;
}
}
public sealed override string Subject => SubjectName.Name;
public sealed override string Issuer => IssuerName.Name;
public sealed override string LegacySubject => SubjectName.Decode (X500DistinguishedNameFlags.None);
public sealed override string LegacyIssuer => IssuerName.Decode (X500DistinguishedNameFlags.None);
public sealed override byte[] RawData {
get {
EnsureCertData ();
return certData.RawData;
}
}
public sealed override byte[] Thumbprint {
get {
EnsureCertData ();
using (SHA1 hash = SHA1.Create ()) {
return hash.ComputeHash (certData.RawData);
}
}
}
public sealed override string GetNameInfo (X509NameType nameType, bool forIssuer)
{
EnsureCertData ();
return certData.GetNameInfo (nameType, forIssuer);
}
public sealed override IEnumerable<X509Extension> Extensions {
get {
EnsureCertData ();
return certData.Extensions;
}
}
public sealed override DateTime NotAfter {
get {
EnsureCertData ();
return certData.NotAfter.ToLocalTime ();
}
}
public sealed override DateTime NotBefore {
get {
EnsureCertData ();
return certData.NotBefore.ToLocalTime ();
}
}
public sealed override void AppendPrivateKeyInfo (StringBuilder sb)
{
if (!HasPrivateKey)
return;
// There's nothing really to say about the key, just acknowledge there is one.
sb.AppendLine ();
sb.AppendLine ();
sb.AppendLine ("[Private Key]");
}
public override void Reset ()
{
readCertData = false;
}
public sealed override byte[] Export (X509ContentType contentType, SafePasswordHandle password)
{
ThrowIfContextInvalid ();
Debug.Assert (password != null);
switch (contentType) {
case X509ContentType.Cert:
return RawData;
case X509ContentType.Pkcs12:
return ExportPkcs12 (password);
case X509ContentType.Pkcs7:
return ExportPkcs12 ((string)null);
case X509ContentType.SerializedCert:
case X509ContentType.SerializedStore:
throw new PlatformNotSupportedException (SR.Cryptography_Unix_X509_SerializedExport);
default:
throw new CryptographicException (SR.Cryptography_X509_InvalidContentType);
}
}
byte[] ExportPkcs12 (SafePasswordHandle password)
{
if (password == null || password.IsInvalid)
return ExportPkcs12 ((string)null);
var passwordString = password.Mono_DangerousGetString ();
return ExportPkcs12 (passwordString);
}
byte[] ExportPkcs12 (string password)
{
var pfx = new MX.PKCS12 ();
try {
var attrs = new Hashtable ();
var localKeyId = new ArrayList ();
localKeyId.Add (new byte[] { 1, 0, 0, 0 });
attrs.Add (MX.PKCS9.localKeyId, localKeyId);
if (password != null)
pfx.Password = password;
pfx.AddCertificate (new MX.X509Certificate (RawData), attrs);
if (IntermediateCertificates != null) {
for (int i = 0; i < IntermediateCertificates.Count; i++)
pfx.AddCertificate (new MX.X509Certificate (IntermediateCertificates[i].RawData));
}
var privateKey = PrivateKey;
if (privateKey != null)
pfx.AddPkcs8ShroudedKeyBag (privateKey, attrs);
return pfx.GetBytes ();
} finally {
pfx.Password = null;
}
}
}
}

View File

@@ -521,12 +521,13 @@ namespace System.Security.Cryptography.X509Certificates {
{
X509ChainElement element = elements [n];
X509Certificate2 certificate = element.Certificate;
var monoCertificate = X509Helper2.GetMonoCertificate (certificate);
// pre-step: DSA certificates may inherit the parameters of their CA
if ((n != elements.Count - 1) && (certificate.MonoCertificate.KeyAlgorithm == "1.2.840.10040.4.1")) {
if (certificate.MonoCertificate.KeyAlgorithmParameters == null) {
X509Certificate2 parent = elements [n+1].Certificate;
certificate.MonoCertificate.KeyAlgorithmParameters = parent.MonoCertificate.KeyAlgorithmParameters;
if ((n != elements.Count - 1) && (monoCertificate.KeyAlgorithm == "1.2.840.10040.4.1")) {
if (monoCertificate.KeyAlgorithmParameters == null) {
var parent = X509Helper2.GetMonoCertificate (elements [n+1].Certificate);
monoCertificate.KeyAlgorithmParameters = parent.KeyAlgorithmParameters;
}
}
@@ -703,7 +704,7 @@ namespace System.Security.Cryptography.X509Certificates {
if (pubkey == null)
return false;
// Sadly X509Certificate2 doesn't expose the signature nor the tbs (to be signed) structure
var mx = signed.MonoCertificate;
var mx = X509Helper2.GetMonoCertificate (signed);
return (mx.VerifySignature (pubkey));
}
@@ -716,7 +717,8 @@ namespace System.Security.Cryptography.X509Certificates {
// System.dll v2 doesn't have a class to deal with the AuthorityKeyIdentifier extension
static string GetAuthorityKeyIdentifier (X509Certificate2 certificate)
{
return GetAuthorityKeyIdentifier (certificate.MonoCertificate.Extensions ["2.5.29.35"]);
var monoCertificate = X509Helper2.GetMonoCertificate (certificate);
return GetAuthorityKeyIdentifier (monoCertificate.Extensions ["2.5.29.35"]);
}
// but anyway System.dll v2 doesn't expose CRL in any way so...
@@ -853,7 +855,8 @@ namespace System.Security.Cryptography.X509Certificates {
return X509ChainStatusFlags.RevocationStatusUnknown;
}
MX.X509Crl.X509CrlEntry entry = crl.GetCrlEntry (certificate.MonoCertificate);
var monoCertificate = X509Helper2.GetMonoCertificate (certificate);
MX.X509Crl.X509CrlEntry entry = crl.GetCrlEntry (monoCertificate);
if (entry != null) {
// We have an entry for this CRL that includes an unknown CRITICAL extension
// See [X.509 7.3] NOTE 4

View File

@@ -62,13 +62,7 @@ namespace System.Security.Cryptography.X509Certificates
{
if (certificate.Impl is X509Certificate2ImplMono monoImpl)
return monoImpl.MonoCertificate;
if (certificate.Impl is X509Certificate2Impl impl2 && impl2.FallbackImpl is X509Certificate2ImplMono fallbackImpl)
return fallbackImpl.MonoCertificate;
var impl = SystemDependencyProvider.Instance.CertificateProvider.Import (certificate, CertificateImportFlags.DisableNativeBackend);
if (impl is X509Certificate2ImplMono fallbackImpl2)
return fallbackImpl2.MonoCertificate;
throw new NotSupportedException ();
return new MX.X509Certificate (certificate.RawData);
}
internal static X509ChainImpl CreateChainImpl (bool useMachineContext)