Imported Upstream version 5.18.0.142

Former-commit-id: 7467d4b717762eeaf652d77f1486dd11ffb1ff1f
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2018-10-09 08:20:59 +00:00
parent e52655b4dc
commit 0abdbe5a7d
1547 changed files with 93792 additions and 47893 deletions

View File

@ -1,35 +0,0 @@
//
// INativeCertificateHelper.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2016 Xamarin, Inc.
//
// 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.
namespace System.Security.Cryptography.X509Certificates
{
internal interface INativeCertificateHelper
{
X509CertificateImpl Import (byte[] data, string password, X509KeyStorageFlags flags);
X509CertificateImpl Import (X509Certificate cert);
}
}

View File

@ -1,262 +0,0 @@
//
// X509Certificate20.cs: Partial class to handle new 2.0-only stuff
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006,2008 Novell, Inc (http://www.novell.com)
// Copyright 2013 Xamarin Inc.
//
// 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.
//
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using Mono.Security;
using Mono.Security.X509;
using System.Runtime.Serialization;
namespace System.Security.Cryptography.X509Certificates {
[ComVisible (true)]
[MonoTODO ("X509ContentType.SerializedCert isn't supported (anywhere in the class)")]
public partial class X509Certificate : IDeserializationCallback, ISerializable, IDisposable {
private string issuer_name;
private string subject_name;
public X509Certificate ()
{
// this allows an empty certificate to exists
}
public X509Certificate (byte[] rawData, string password)
{
Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
}
[MonoTODO ("SecureString support is incomplete")]
public X509Certificate (byte[] rawData, SecureString password)
{
Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
}
public X509Certificate (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
Import (rawData, password, keyStorageFlags);
}
[MonoTODO ("SecureString support is incomplete")]
public X509Certificate (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
{
Import (rawData, password, keyStorageFlags);
}
public X509Certificate (string fileName)
{
Import (fileName, (string)null, X509KeyStorageFlags.DefaultKeySet);
}
public X509Certificate (string fileName, string password)
{
Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
}
[MonoTODO ("SecureString support is incomplete")]
public X509Certificate (string fileName, SecureString password)
{
Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
}
public X509Certificate (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
Import (fileName, password, keyStorageFlags);
}
[MonoTODO ("SecureString support is incomplete")]
public X509Certificate (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
{
Import (fileName, password, keyStorageFlags);
}
public X509Certificate (SerializationInfo info, StreamingContext context)
{
byte[] raw = (byte[]) info.GetValue ("RawData", typeof (byte[]));
Import (raw, (string)null, X509KeyStorageFlags.DefaultKeySet);
}
public string Issuer {
get {
X509Helper.ThrowIfContextInvalid (impl);
if (issuer_name == null)
issuer_name = impl.GetIssuerName (false);
return issuer_name;
}
}
public string Subject {
get {
X509Helper.ThrowIfContextInvalid (impl);
if (subject_name == null)
subject_name = impl.GetSubjectName (false);
return subject_name;
}
}
[ComVisible (false)]
public IntPtr Handle {
get {
if (X509Helper.IsValid (impl))
return impl.Handle;
return IntPtr.Zero;
}
}
[ComVisible (false)]
public override bool Equals (object obj)
{
X509Certificate x = (obj as X509Certificate);
if (x != null)
return this.Equals (x);
return false;
}
[MonoTODO ("X509ContentType.Pfx/Pkcs12 and SerializedCert are not supported")]
[ComVisible (false)]
public virtual byte[] Export (X509ContentType contentType)
{
return Export (contentType, (byte[])null);
}
[MonoTODO ("X509ContentType.Pfx/Pkcs12 and SerializedCert are not supported")]
[ComVisible (false)]
public virtual byte[] Export (X509ContentType contentType, string password)
{
byte[] pwd = (password == null) ? null : Encoding.UTF8.GetBytes (password);
return Export (contentType, pwd);
}
[MonoTODO ("X509ContentType.Pfx/Pkcs12 and SerializedCert are not supported. SecureString support is incomplete.")]
public virtual byte[] Export (X509ContentType contentType, SecureString password)
{
byte[] pwd = (password == null) ? null : password.GetBuffer ();
return Export (contentType, pwd);
}
internal byte[] Export (X509ContentType contentType, byte[] password)
{
try {
X509Helper.ThrowIfContextInvalid (impl);
return impl.Export (contentType, password);
} finally {
// protect password
if (password != null)
Array.Clear (password, 0, password.Length);
}
}
[ComVisible (false)]
public virtual void Import (byte[] rawData)
{
Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
}
[MonoTODO ("missing KeyStorageFlags support")]
[ComVisible (false)]
public virtual void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
Reset ();
impl = X509Helper.Import (rawData, password, keyStorageFlags);
}
[MonoTODO ("SecureString support is incomplete")]
public virtual void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
{
Import (rawData, (string)null, keyStorageFlags);
}
[ComVisible (false)]
public virtual void Import (string fileName)
{
byte[] rawData = File.ReadAllBytes (fileName);
Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
}
[MonoTODO ("missing KeyStorageFlags support")]
[ComVisible (false)]
public virtual void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
byte[] rawData = File.ReadAllBytes (fileName);
Import (rawData, password, keyStorageFlags);
}
[MonoTODO ("SecureString support is incomplete, missing KeyStorageFlags support")]
public virtual void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
{
byte[] rawData = File.ReadAllBytes (fileName);
Import (rawData, (string)null, keyStorageFlags);
}
void IDeserializationCallback.OnDeserialization (object sender)
{
}
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
{
if (!X509Helper.IsValid (impl))
throw new NullReferenceException ();
// will throw a NRE if info is null (just like MS implementation)
info.AddValue ("RawData", impl.GetRawCertData ());
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing)
Reset ();
}
[ComVisible (false)]
public virtual void Reset ()
{
if (impl != null) {
impl.Dispose ();
impl = null;
}
issuer_name = null;
subject_name = null;
hideDates = false;
}
}
}

View File

@ -25,6 +25,7 @@
// 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 Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography.X509Certificates
{
internal abstract class X509CertificateImpl : IDisposable
@ -50,57 +51,71 @@ namespace System.Security.Cryptography.X509Certificates
public abstract X509CertificateImpl Clone ();
public abstract string GetIssuerName (bool legacyV1Mode);
public abstract string GetSubjectName (bool legacyV1Mode);
public abstract byte[] GetRawCertData ();
public abstract DateTime GetValidFrom ();
public abstract DateTime GetValidUntil ();
byte[] cachedCertificateHash;
public byte[] GetCertHash ()
{
ThrowIfContextInvalid ();
if (cachedCertificateHash == null)
cachedCertificateHash = GetCertHash (false);
return cachedCertificateHash;
public abstract string Issuer {
get;
}
protected abstract byte[] GetCertHash (bool lazy);
public abstract string Subject {
get;
}
public override int GetHashCode ()
public abstract string LegacyIssuer {
get;
}
public abstract string LegacySubject {
get;
}
public abstract byte[] RawData {
get;
}
public abstract DateTime NotAfter {
get;
}
public abstract DateTime NotBefore {
get;
}
public abstract byte[] Thumbprint {
get;
}
public sealed override int GetHashCode ()
{
if (!IsValid)
return 0;
if (cachedCertificateHash == null)
cachedCertificateHash = GetCertHash (true);
// return the integer of the first 4 bytes of the cert hash
if ((cachedCertificateHash != null) && (cachedCertificateHash.Length >= 4))
return ((cachedCertificateHash [0] << 24) | (cachedCertificateHash [1] << 16) |
(cachedCertificateHash [2] << 8) | cachedCertificateHash [3]);
else
return 0;
byte[] thumbPrint = Thumbprint;
int value = 0;
for (int i = 0; i < thumbPrint.Length && i < 4; ++i) {
value = value << 8 | thumbPrint[i];
}
return value;
}
public abstract bool Equals (X509CertificateImpl other, out bool result);
public abstract string GetKeyAlgorithm ();
public abstract string KeyAlgorithm {
get;
}
public abstract byte[] GetKeyAlgorithmParameters ();
public abstract byte[] KeyAlgorithmParameters {
get;
}
public abstract byte[] GetPublicKey ();
public abstract byte[] PublicKeyValue {
get;
}
public abstract byte[] GetSerialNumber ();
public abstract byte[] SerialNumber {
get;
}
public abstract byte[] Export (X509ContentType contentType, byte[] password);
public abstract byte[] Export (X509ContentType contentType, SafePasswordHandle password);
public abstract string ToString (bool full);
public override bool Equals (object obj)
public sealed override bool Equals (object obj)
{
var other = obj as X509CertificateImpl;
if (other == null)
@ -109,23 +124,16 @@ namespace System.Security.Cryptography.X509Certificates
if (!IsValid || !other.IsValid)
return false;
bool result;
if (Equals (other, out result))
return result;
var ourRaw = GetRawCertData ();
var theirRaw = other.GetRawCertData ();
if (ourRaw == null)
return theirRaw == null;
else if (theirRaw == null)
if (!Issuer.Equals (other.Issuer))
return false;
if (ourRaw.Length != theirRaw.Length)
return false;
byte[] thisSerialNumber = SerialNumber;
byte[] otherSerialNumber = other.SerialNumber;
for (int i = 0; i < ourRaw.Length; i++) {
if (ourRaw [i] != theirRaw [i])
if (thisSerialNumber.Length != otherSerialNumber.Length)
return false;
for (int i = 0; i < thisSerialNumber.Length; i++) {
if (thisSerialNumber[i] != otherSerialNumber[i])
return false;
}
@ -140,7 +148,6 @@ namespace System.Security.Cryptography.X509Certificates
protected virtual void Dispose (bool disposing)
{
cachedCertificateHash = null;
}
~X509CertificateImpl ()

View File

@ -1,201 +0,0 @@
#if MONO_FEATURE_APPLETLS || MONO_FEATURE_APPLE_X509
using System;
using System.Text;
using System.Runtime.InteropServices;
using XamMac.CoreFoundation;
using MX = Mono.Security.X509;
namespace System.Security.Cryptography.X509Certificates
{
class X509CertificateImplApple : X509CertificateImpl
{
IntPtr handle;
X509CertificateImpl fallback;
public X509CertificateImplApple (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CFHelpers.CFRetain (handle);
}
public override bool IsValid {
get { return handle != IntPtr.Zero; }
}
public override IntPtr Handle {
get { return handle; }
}
public override IntPtr GetNativeAppleCertificate ()
{
ThrowIfContextInvalid ();
return handle;
}
public override X509CertificateImpl Clone ()
{
ThrowIfContextInvalid ();
return new X509CertificateImplApple (handle, false);
}
[DllImport (CFHelpers.SecurityLibrary)]
extern static IntPtr SecCertificateCopySubjectSummary (IntPtr cert);
[DllImport (CFHelpers.SecurityLibrary)]
extern static IntPtr SecCertificateCopyData (IntPtr cert);
public override byte[] GetRawCertData ()
{
ThrowIfContextInvalid ();
var data = SecCertificateCopyData (handle);
if (data == IntPtr.Zero)
throw new ArgumentException ("Not a valid certificate");
try {
return CFHelpers.FetchDataBuffer (data);
} finally {
CFHelpers.CFRelease (data);
}
}
public string GetSubjectSummary ()
{
ThrowIfContextInvalid ();
IntPtr cfstr = SecCertificateCopySubjectSummary (handle);
string ret = CFHelpers.FetchString (cfstr);
CFHelpers.CFRelease (cfstr);
return ret;
}
protected override byte[] GetCertHash (bool lazy)
{
// FIXME: might just return 'null' when 'lazy' is true.
ThrowIfContextInvalid ();
SHA1 sha = SHA1.Create ();
return sha.ComputeHash (GetRawCertData ());
}
public override bool Equals (X509CertificateImpl other, out bool result)
{
var otherAppleImpl = other as X509CertificateImplApple;
if (otherAppleImpl != null && otherAppleImpl.handle == handle) {
result = true;
return true;
}
result = false;
return false;
}
void MustFallback ()
{
ThrowIfContextInvalid ();
if (fallback != null)
return;
var mxCert = new MX.X509Certificate (GetRawCertData ());
fallback = new X509CertificateImplMono (mxCert);
}
public X509CertificateImpl FallbackImpl {
get {
MustFallback ();
return fallback;
}
}
public override string GetSubjectName (bool legacyV1Mode)
{
return FallbackImpl.GetSubjectName (legacyV1Mode);
}
public override string GetIssuerName (bool legacyV1Mode)
{
return FallbackImpl.GetIssuerName (legacyV1Mode);
}
public override DateTime GetValidFrom ()
{
return FallbackImpl.GetValidFrom ();
}
public override DateTime GetValidUntil ()
{
return FallbackImpl.GetValidUntil ();
}
public override string GetKeyAlgorithm ()
{
return FallbackImpl.GetKeyAlgorithm ();
}
public override byte[] GetKeyAlgorithmParameters ()
{
return FallbackImpl.GetKeyAlgorithmParameters ();
}
public override byte[] GetPublicKey ()
{
return FallbackImpl.GetPublicKey ();
}
public override byte[] GetSerialNumber ()
{
return FallbackImpl.GetSerialNumber ();
}
public override byte[] Export (X509ContentType contentType, byte[] password)
{
ThrowIfContextInvalid ();
switch (contentType) {
case X509ContentType.Cert:
return GetRawCertData ();
case X509ContentType.Pfx: // this includes Pkcs12
// TODO
throw new NotSupportedException ();
case X509ContentType.SerializedCert:
// TODO
throw new NotSupportedException ();
default:
string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
throw new CryptographicException (msg);
}
}
public override string ToString (bool full)
{
ThrowIfContextInvalid ();
if (!full || fallback == null) {
var summary = GetSubjectSummary ();
return string.Format ("[X509Certificate: {0}]", summary);
}
string nl = Environment.NewLine;
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, GetSubjectName (false));
sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, GetIssuerName (false));
sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, GetValidFrom ().ToLocalTime ());
sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, GetValidUntil ().ToLocalTime ());
sb.AppendFormat ("[Thumbprint]{0} {1}{0}", nl, X509Helper.ToHexString (GetCertHash ()));
sb.Append (nl);
return sb.ToString ();
}
protected override void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFHelpers.CFRelease (handle);
handle = IntPtr.Zero;
}
if (fallback != null) {
fallback.Dispose ();
fallback = null;
}
}
}
}
#endif

View File

@ -1,178 +0,0 @@
//
// X509CertificateImplMono.cs: X.509 implementation using Mono.Security.X509.
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
// Martin Baulig <martin.baulig@xamarin.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
// Copyright (C) 2015 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.
//
using System;
using System.Text;
using MX = Mono.Security.X509;
namespace System.Security.Cryptography.X509Certificates
{
sealed class X509CertificateImplMono : X509CertificateImpl
{
MX.X509Certificate x509;
public X509CertificateImplMono (MX.X509Certificate x509)
{
this.x509 = x509;
}
public override bool IsValid {
get { return x509 != null; }
}
public override IntPtr Handle {
get { return IntPtr.Zero; }
}
public override IntPtr GetNativeAppleCertificate ()
{
return IntPtr.Zero;
}
public override X509CertificateImpl Clone ()
{
ThrowIfContextInvalid ();
return new X509CertificateImplMono (x509);
}
public override string GetIssuerName (bool legacyV1Mode)
{
ThrowIfContextInvalid ();
if (legacyV1Mode)
return x509.IssuerName;
else
return MX.X501.ToString (x509.GetIssuerName (), true, ", ", true);
}
public override string GetSubjectName (bool legacyV1Mode)
{
ThrowIfContextInvalid ();
if (legacyV1Mode)
return x509.SubjectName;
else
return MX.X501.ToString (x509.GetSubjectName (), true, ", ", true);
}
public override byte[] GetRawCertData ()
{
ThrowIfContextInvalid ();
return x509.RawData;
}
protected override byte[] GetCertHash (bool lazy)
{
ThrowIfContextInvalid ();
SHA1 sha = SHA1.Create ();
return sha.ComputeHash (x509.RawData);
}
public override DateTime GetValidFrom ()
{
ThrowIfContextInvalid ();
return x509.ValidFrom;
}
public override DateTime GetValidUntil ()
{
ThrowIfContextInvalid ();
return x509.ValidUntil;
}
public override bool Equals (X509CertificateImpl other, out bool result)
{
// Use default implementation
result = false;
return false;
}
public override string GetKeyAlgorithm ()
{
ThrowIfContextInvalid ();
return x509.KeyAlgorithm;
}
public override byte[] GetKeyAlgorithmParameters ()
{
ThrowIfContextInvalid ();
return x509.KeyAlgorithmParameters;
}
public override byte[] GetPublicKey ()
{
ThrowIfContextInvalid ();
return x509.PublicKey;
}
public override byte[] GetSerialNumber ()
{
ThrowIfContextInvalid ();
return x509.SerialNumber;
}
public override byte[] Export (X509ContentType contentType, byte[] password)
{
ThrowIfContextInvalid ();
switch (contentType) {
case X509ContentType.Cert:
return GetRawCertData ();
case X509ContentType.Pfx: // this includes Pkcs12
// TODO
throw new NotSupportedException ();
case X509ContentType.SerializedCert:
// TODO
throw new NotSupportedException ();
default:
string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
throw new CryptographicException (msg);
}
}
public override string ToString (bool full)
{
ThrowIfContextInvalid ();
string nl = Environment.NewLine;
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, GetSubjectName (false));
sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, GetIssuerName (false));
sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, GetValidFrom ().ToLocalTime ());
sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, GetValidUntil ().ToLocalTime ());
sb.AppendFormat ("[Thumbprint]{0} {1}{0}", nl, X509Helper.ToHexString (GetCertHash ()));
sb.Append (nl);
return sb.ToString ();
}
protected override void Dispose (bool disposing)
{
x509 = null;
}
}
}

View File

@ -1,39 +0,0 @@
#if MONO_FEATURE_APPLETLS || MONO_FEATURE_APPLE_X509
using System;
using System.Runtime.InteropServices;
using MX = Mono.Security.X509;
using XamMac.CoreFoundation;
namespace System.Security.Cryptography.X509Certificates
{
static partial class X509Helper
{
public static X509CertificateImpl InitFromHandleApple (IntPtr handle)
{
return new X509CertificateImplApple (handle, false);
}
static X509CertificateImpl ImportApple (byte[] rawData)
{
var handle = CFHelpers.CreateCertificateFromData (rawData);
if (handle != IntPtr.Zero)
return new X509CertificateImplApple (handle, true);
MX.X509Certificate x509;
try {
x509 = new MX.X509Certificate (rawData);
} catch (Exception e) {
try {
x509 = ImportPkcs12 (rawData, null);
} catch {
string msg = Locale.GetText ("Unable to decode certificate.");
// inner exception is the original (not second) exception
throw new CryptographicException (msg, e);
}
}
return new X509CertificateImplMono (x509);
}
}
}
#endif

View File

@ -32,123 +32,26 @@ using System;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
#if !MOBILE
using System.Security.Permissions;
#endif
using MX = Mono.Security.X509;
using Mono;
namespace System.Security.Cryptography.X509Certificates
{
static partial class X509Helper
{
static INativeCertificateHelper nativeHelper;
internal static void InstallNativeHelper (INativeCertificateHelper helper)
{
if (nativeHelper == null)
Interlocked.CompareExchange (ref nativeHelper, helper, null);
}
#if MONO_FEATURE_APPLETLS
static bool ShouldUseAppleTls
{
get
{
if (!System.Environment.IsMacOS)
return false;
// MONO_TLS_PROVIDER values default or apple (not legacy or btls) and must be on MacOS
var variable = Environment.GetEnvironmentVariable ("MONO_TLS_PROVIDER");
return string.IsNullOrEmpty (variable) || variable == "default" || variable == "apple"; // On Platform.IsMacOS default is AppleTlsProvider
}
}
#endif
public static X509CertificateImpl InitFromHandle (IntPtr handle)
{
#if (MONO_FEATURE_APPLETLS && ONLY_APPLETLS) || MONO_FEATURE_APPLE_X509 // ONLY_APPLETLS should not support any other option
return InitFromHandleApple (handle);
#else
#if MONO_FEATURE_APPLETLS // If we support AppleTls, which is the default, and not overriding to legacy
if (ShouldUseAppleTls)
return InitFromHandleApple (handle);
#endif
#if !MOBILE
return InitFromHandleCore (handle);
#elif !MONOTOUCH && !XAMMAC
throw new NotSupportedException ();
#endif
#endif
}
static X509CertificateImpl Import (byte[] rawData)
{
#if (MONO_FEATURE_APPLETLS && ONLY_APPLETLS) || MONO_FEATURE_APPLE_X509 // ONLY_APPLETLS should not support any other option
return ImportApple (rawData);
#else
#if MONO_FEATURE_APPLETLS
if (ShouldUseAppleTls)
return ImportApple (rawData);
#endif
return ImportCore (rawData);
#endif
}
#if !MOBILE
// typedef struct _CERT_CONTEXT {
// DWORD dwCertEncodingType;
// BYTE *pbCertEncoded;
// DWORD cbCertEncoded;
// PCERT_INFO pCertInfo;
// HCERTSTORE hCertStore;
// } CERT_CONTEXT, *PCERT_CONTEXT;
// typedef const CERT_CONTEXT *PCCERT_CONTEXT;
[StructLayout (LayoutKind.Sequential)]
internal struct CertificateContext {
public UInt32 dwCertEncodingType;
public IntPtr pbCertEncoded;
public UInt32 cbCertEncoded;
public IntPtr pCertInfo;
public IntPtr hCertStore;
}
// NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
// so we don't create any dependencies on Windows DLL in corlib
[SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
public static X509CertificateImpl InitFromHandleCore (IntPtr handle)
{
// both Marshal.PtrToStructure and Marshal.Copy use LinkDemand (so they will always success from here)
CertificateContext cc = (CertificateContext) Marshal.PtrToStructure (handle, typeof (CertificateContext));
byte[] data = new byte [cc.cbCertEncoded];
Marshal.Copy (cc.pbCertEncoded, data, 0, (int)cc.cbCertEncoded);
var x509 = new MX.X509Certificate (data);
return new X509CertificateImplMono (x509);
}
#endif
static ISystemCertificateProvider CertificateProvider => DependencyInjector.SystemProvider.CertificateProvider;
public static X509CertificateImpl InitFromCertificate (X509Certificate cert)
{
if (nativeHelper != null)
return nativeHelper.Import (cert);
return InitFromCertificate (cert.Impl);
return CertificateProvider.Import (cert, CertificateImportFlags.None);
}
public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
{
if (impl == null)
return null;
var copy = impl.Clone ();
if (copy != null)
return copy;
var data = impl.GetRawCertData ();
if (data == null)
return null;
var x509 = new MX.X509Certificate (data);
return new X509CertificateImplMono (x509);
return impl?.Clone ();
}
public static bool IsValid (X509CertificateImpl impl)
@ -167,95 +70,17 @@ namespace System.Security.Cryptography.X509Certificates
return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
}
internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
public static X509CertificateImpl Import (byte[] rawData)
{
var pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
if (pfx.Certificates.Count == 0) {
// no certificate was found
return null;
} else if (pfx.Keys.Count == 0) {
// no key were found - pick the first certificate
return pfx.Certificates [0];
} else {
// find the certificate that match the first key
var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
string pubkey = keypair.ToXmlString (false);
foreach (var c in pfx.Certificates) {
if ((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false)))
return c;
if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
return c;
}
return pfx.Certificates [0]; // no match, pick first certificate without keys
}
return CertificateProvider.Import (rawData);
}
static byte[] PEM (string type, byte[] data)
public static X509CertificateImpl Import (byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
string pem = Encoding.ASCII.GetString (data);
string header = String.Format ("-----BEGIN {0}-----", type);
string footer = String.Format ("-----END {0}-----", type);
int start = pem.IndexOf (header) + header.Length;
int end = pem.IndexOf (footer, start);
string base64 = pem.Substring (start, (end - start));
return Convert.FromBase64String (base64);
return CertificateProvider.Import (rawData, password, keyStorageFlags);
}
static byte[] ConvertData (byte[] data)
{
if (data == null || data.Length == 0)
return data;
// does it looks like PEM ?
if (data [0] != 0x30) {
try {
return PEM ("CERTIFICATE", data);
} catch {
// let the implementation take care of it.
}
}
return data;
}
static X509CertificateImpl ImportCore (byte[] rawData)
{
MX.X509Certificate x509;
try {
x509 = new MX.X509Certificate (rawData);
} catch (Exception e) {
try {
x509 = ImportPkcs12 (rawData, null);
} catch {
string msg = Locale.GetText ("Unable to decode certificate.");
// inner exception is the original (not second) exception
throw new CryptographicException (msg, e);
}
}
return new X509CertificateImplMono (x509);
}
public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
if (password == null) {
rawData = ConvertData (rawData);
return Import (rawData);
}
MX.X509Certificate x509;
// try PKCS#12
try {
x509 = ImportPkcs12 (rawData, password);
} catch {
// it's possible to supply a (unrequired/unusued) password
// fix bug #79028
x509 = new MX.X509Certificate (rawData);
}
return new X509CertificateImplMono (x509);
}
public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, SafePasswordHandle password)
{
ThrowIfContextInvalid (impl);
return impl.Export (contentType, password);
@ -270,8 +95,8 @@ namespace System.Security.Cryptography.X509Certificates
if (first.Equals (second, out result))
return result;
var firstRaw = first.GetRawCertData ();
var secondRaw = second.GetRawCertData ();
var firstRaw = first.RawData;
var secondRaw = second.RawData;
if (firstRaw == null)
return secondRaw == null;