static bool ValidateCertAgainstBaseline(IDictionary<string, string> certVals, X509Certificate cer) { bool retVal = true; long effectiveDateFound, expiryDateFound, effectiveDateBsl, expiryDateBsl; byte[] bytes; string str; int hash; IntPtr handle; // now validate against the actual cert if (!certVals["HashString"].Equals(cer.GetCertHashString())) { TestFramework.LogError("001", "Expected hash string: " + certVals["HashString"] + ", found: " + cer.GetCertHashString()); retVal = false; } // check the dates try { effectiveDateBsl = Convert.ToInt64(certVals["EffectiveDateStringInTicks"]); effectiveDateFound = DateTime.Parse(cer.GetEffectiveDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks; expiryDateBsl = Convert.ToInt64(certVals["ExpirationDateStringInTicks"]); expiryDateFound = DateTime.Parse(cer.GetExpirationDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks; if (effectiveDateBsl != effectiveDateFound) { TestFramework.LogError("002", "Expected \"Valid From\": [" + (new DateTime(effectiveDateBsl, DateTimeKind.Utc)).ToString() + "], found: [" + cer.GetEffectiveDateString() +" nonUTC]"); TestFramework.LogError("002", " ticks(" + effectiveDateBsl + ") found ticks(" + effectiveDateFound + ")"); retVal = false; } if (expiryDateBsl != expiryDateFound) { TestFramework.LogError("003", "Expected \"Valid To\": [" + (new DateTime(expiryDateBsl)).ToString() + "], found: [" + cer.GetExpirationDateString() + " nonUTC]"); TestFramework.LogError("003", " ticks(" + expiryDateBsl + ") found ticks(" + expiryDateFound + ")"); retVal = false; } } catch (Exception e) { TestFramework.LogError("103", "Unexpected exception: " + e); retVal = false; } TestFramework.LogInformation(" Validating field: Format"); if (!certVals["Format"].Equals(cer.GetFormat())) { TestFramework.LogError("004", "Expected format: " + certVals["Format"] + ", found: " + cer.GetFormat()); retVal = false; } TestFramework.LogInformation(" Validating field: Issuer"); if (!certVals["Issuer"].Equals(cer.Issuer)) { TestFramework.LogError("005", "Expected issuer: " + certVals["Issuer"] + ", found: " + cer.Issuer); retVal = false; } TestFramework.LogInformation(" Validating field: KeyAlgorithm"); if (!certVals["KeyAlgorithm"].Equals(cer.GetKeyAlgorithm())) { TestFramework.LogError("006", "Expected key algorithm: " + certVals["KeyAlgorithm"] + ", found: " + cer.GetKeyAlgorithm()); retVal = false; } TestFramework.LogInformation(" Validating field: KeyAlgorithmParameters"); if (!certVals["KeyAlgorithmParameters"].Equals(cer.GetKeyAlgorithmParametersString())) { TestFramework.LogError("007", "Expected key alg parameters :" + certVals["KeyAlgorithmParameters"] + ", found :" + cer.GetKeyAlgorithmParametersString()); retVal = false; } TestFramework.LogInformation(" Validating field: PublicKeyString"); if (!certVals["PublicKeyString"].Equals(cer.GetPublicKeyString())) { TestFramework.LogError("008", "Expected public key: " + certVals["PublicKeyString"] + ", found: " + cer.GetPublicKeyString()); retVal = false; } TestFramework.LogInformation(" Validating field: SerialNumberString"); if (!certVals["SerialNumberString"].Equals(cer.GetSerialNumberString())) { TestFramework.LogError("009", "Expected serial number: " + certVals["SerialNumberString"] + ", found: " + cer.GetSerialNumberString()); retVal = false; } TestFramework.LogInformation(" Validating field: Subject"); if (!certVals["Subject"].Equals(cer.Subject)) { TestFramework.LogError("010", "Expected subject: " + certVals["Subject"] + ", found: " + cer.Subject); retVal = false; } TestFramework.LogInformation(" Retrieving field: CertHash"); bytes = cer.GetCertHash(); TestFramework.LogInformation(" Retrieving field: HashCode"); hash = cer.GetHashCode(); TestFramework.LogInformation(" Retrieving field: RawCertHash"); bytes = cer.GetRawCertData(); TestFramework.LogInformation(" Retrieving field: RawCertDataString"); str = cer.GetRawCertDataString(); TestFramework.LogInformation(" Retrieving field: SerialNumber"); bytes = cer.GetSerialNumber(); TestFramework.LogInformation(" Retrieving field: ToString()"); str = cer.ToString(); TestFramework.LogInformation(" Retrieving field: ToString(true)"); str = cer.ToString(true); TestFramework.LogInformation(" Retrieving field: Handle"); handle = GetHandle(cer); TestFramework.LogInformation(" Testing: Equality with a string"); if (cer.Equals(str)) { TestFramework.LogError("110", "X509Certificate \"equals\" a string?"); retVal = false; } TestFramework.LogInformation(" Testing: Equality with itself(1)"); if (!cer.Equals((object)cer)) { TestFramework.LogError("120", "X509Certificate does not equal itself"); retVal = false; } TestFramework.LogInformation(" Testing: Equality with itself(2)"); if (!cer.Equals(cer)) { TestFramework.LogError("130", "X509Certificate does not equal itself"); retVal = false; } return retVal; }
public void PartialTrust_DenyUnrestricted() { X509Certificate x509 = new X509Certificate(cert); X509Certificate clone = new X509Certificate(x509); Assert.IsTrue(x509.Equals(clone), "Equals 1"); Assert.IsTrue(clone.Equals(x509), "Equals 2"); byte[] hash = { 0xD6, 0x2F, 0x48, 0xD0, 0x13, 0xEE, 0x7F, 0xB5, 0x8B, 0x79, 0x07, 0x45, 0x12, 0x67, 0x0D, 0x9C, 0x5B, 0x3A, 0x5D, 0xA9 }; Assert.AreEqual(hash, x509.GetCertHash(), "GetCertHash"); Assert.AreEqual("D62F48D013EE7FB58B79074512670D9C5B3A5DA9", x509.GetCertHashString(), "GetCertHashString"); #if NET_2_0 DateTime from = DateTime.ParseExact(x509.GetEffectiveDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime(); Assert.AreEqual("03/12/1996 18:38:47", from.ToString(), "GetEffectiveDateString"); DateTime until = DateTime.ParseExact(x509.GetExpirationDateString(), "MM/dd/yyyy HH:mm:ss", null).ToUniversalTime(); Assert.AreEqual("03/12/1997 18:38:46", until.ToString(), "GetExpirationDateString"); #else // fx 1.x has a bug where the returned dates were always in the Seattle time zone Assert.AreEqual("03/12/1996 10:38:47", x509.GetEffectiveDateString(), "GetEffectiveDateString"); Assert.AreEqual("03/12/1997 10:38:46", x509.GetExpirationDateString(), "GetExpirationDateString"); #endif Assert.AreEqual("X509", x509.GetFormat(), "GetFormat"); Assert.AreEqual(-701544240, x509.GetHashCode(), "GetHashCode"); Assert.AreEqual("C=US, O=\"RSA Data Security, Inc.\", OU=Secure Server Certification Authority", x509.GetIssuerName(), "GetIssuerName"); Assert.AreEqual("1.2.840.113549.1.1.1", x509.GetKeyAlgorithm(), "GetKeyAlgorithm"); byte[] keyparams = { 0x05, 0x00 }; Assert.AreEqual(keyparams, x509.GetKeyAlgorithmParameters(), "GetKeyAlgorithmParameters"); Assert.AreEqual("0500", x509.GetKeyAlgorithmParametersString(), "GetKeyAlgorithmParametersString"); Assert.AreEqual("C=US, S=California, O=CommerceNet, OU=Server Certification Authority", x509.GetName(), "GetName"); byte[] pubkey = { 0x30, 0x5C, 0x02, 0x55, 0x2D, 0x58, 0xE9, 0xBF, 0xF0, 0x31, 0xCD, 0x79, 0x06, 0x50, 0x5A, 0xD5, 0x9E, 0x0E, 0x2C, 0xE6, 0xC2, 0xF7, 0xF9, 0xD2, 0xCE, 0x55, 0x64, 0x85, 0xB1, 0x90, 0x9A, 0x92, 0xB3, 0x36, 0xC1, 0xBC, 0xEA, 0xC8, 0x23, 0xB7, 0xAB, 0x3A, 0xA7, 0x64, 0x63, 0x77, 0x5F, 0x84, 0x22, 0x8E, 0xE5, 0xB6, 0x45, 0xDD, 0x46, 0xAE, 0x0A, 0xDD, 0x00, 0xC2, 0x1F, 0xBA, 0xD9, 0xAD, 0xC0, 0x75, 0x62, 0xF8, 0x95, 0x82, 0xA2, 0x80, 0xB1, 0x82, 0x69, 0xFA, 0xE1, 0xAF, 0x7F, 0xBC, 0x7D, 0xE2, 0x7C, 0x76, 0xD5, 0xBC, 0x2A, 0x80, 0xFB, 0x02, 0x03, 0x01, 0x00, 0x01 }; Assert.AreEqual(pubkey, x509.GetPublicKey(), "GetPublicKey"); Assert.AreEqual("305C02552D58E9BFF031CD7906505AD59E0E2CE6C2F7F9D2CE556485B1909A92B336C1BCEAC823B7AB3AA76463775F84228EE5B645DD46AE0ADD00C21FBAD9ADC07562F89582A280B18269FAE1AF7FBC7DE27C76D5BC2A80FB0203010001", x509.GetPublicKeyString(), "GetPublicKeyString"); Assert.AreEqual(cert, x509.GetRawCertData(), "GetRawCertData"); Assert.IsNotNull(x509.GetRawCertDataString(), "GetRawCertDataString"); byte[] serial = { 0xE8, 0x06, 0x00, 0x72, 0x02 }; Assert.AreEqual(serial, x509.GetSerialNumber(), "GetSerialNumber"); #if NET_2_0 Assert.AreEqual("02720006E8", x509.GetSerialNumberString(), "GetSerialNumberString"); #else Assert.AreEqual("E806007202", x509.GetSerialNumberString(), "GetSerialNumberString"); #endif Assert.IsNotNull(x509.ToString(true), "ToString"); }
static bool ServerCallback(LdapConnection connection, X509Certificate certificate) { try { X509Certificate expectedCert = X509Certificate.CreateFromCertFile(_certFile); if (expectedCert.Equals(certificate)) { return(true); } else { return(false); } } catch (Exception ex) { MessageBox.Show("[Certificate Error] " + ex.Message); return(false); } }
public void PartialTrust_PermitOnlyFileIOPermission() { X509Certificate x509 = new X509Certificate(cert); X509Certificate disk = X509Certificate.CreateFromCertFile(certfile); Assert.IsTrue(disk.Equals(x509), "Equals 1"); Assert.IsTrue(x509.Equals(disk), "Equals 2"); try { X509Certificate spc = X509Certificate.CreateFromSignedFile(signedfile); Assert.IsFalse(spc.Equals(x509), "!Equals 1"); Assert.IsFalse(x509.Equals(spc), "!Equals 2"); } catch (COMException) { // most likely the root certificate isn't available // anyway this indicates that the security check is ok } }
public override bool IsSubsetOf(IPermission target) { if (target == null) { return(certificate == null); } else if (!(target is PublisherIdentityPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } else if (certificate != null && !certificate.Equals (((PublisherIdentityPermission)target).certificate)) { return(false); } else { return(true); } }
/// <summary> /// Handler per l'evento VerifyServerCertificateCallback per la verifica /// delle credenziali per l'accesso al server LDAP tramite certificato /// </summary> /// <param name="connection"></param> /// <param name="certificate"></param> /// <returns></returns> protected virtual bool OnServerAuthenticate(LdapConnection connection, X509Certificate certificate) { string certPath = this.CertificatePath; if ((certPath.ToLower() == "false") || (certPath.ToLower() == "0")) { return(true); } try { // Reperimento del certificato configurato X509Certificate expectedCert = X509Certificate.CreateFromCertFile(this.CertificatePath); if (expectedCert.Equals(certificate)) { return(true); } else { // certificate.ToString(true) provides verbose information about the certificate string errorMessage = String.Format( "Il certificato non corrisponde con quello restituito dal server: {0}", certificate.ToString(true)); logger.Debug(errorMessage); return(false); } } catch (Exception ex) { logger.Debug("Cannot validate certificate: " + ex.Message); return(false); } }
internal static void ProcessAttrCert4( X509Certificate acIssuerCert, PkixParameters pkixParams) { ISet set = pkixParams.GetTrustedACIssuers(); bool trusted = false; foreach (TrustAnchor anchor in set) { IDictionary symbols = X509Name.RFC2253Symbols; if (acIssuerCert.SubjectDN.ToString(false, symbols).Equals(anchor.CAName) || acIssuerCert.Equals(anchor.TrustedCert)) { trusted = true; } } if (!trusted) { throw new PkixCertPathValidatorException( "Attribute certificate issuer is not directly trusted."); } }
bool CertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); if (Directory.Exists(sslCertFolder)) { foreach (string file in Directory.GetFiles(sslCertFolder)) { X509Certificate cert = new X509Certificate(file); if (cert.Equals(certificate)) { return(true); } } return(false); } else { Directory.CreateDirectory(sslCertFolder); File.WriteAllBytes(sslCertFolder + Path.DirectorySeparatorChar + "cert", certificate.Export(X509ContentType.Cert)); return(true); } }
/** * Helper method that creates the collection of certificates * used for the main signature based on the complete list * of certificates and the sign certificate. */ private void CalcSignCertificateChain() { List <X509Certificate> cc = new List <X509Certificate>(); cc.Add(signCert); List <X509Certificate> oc = new List <X509Certificate>(certs); for (int k = 0; k < oc.Count; ++k) { if (signCert.Equals(oc[k])) { oc.RemoveAt(k); --k; continue; } } bool found = true; while (found) { X509Certificate v = cc[cc.Count - 1]; found = false; for (int k = 0; k < oc.Count; ++k) { try { v.Verify(oc[k].GetPublicKey()); found = true; cc.Add(oc[k]); oc.RemoveAt(k); break; } catch { } } } signCerts = cc; }
/// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>Returns true if two objects are equal.</returns> public override bool Equals(object obj) { if (obj == null) { return(false); } if (!(obj is IPBindInfo)) { return(false); } IPBindInfo bInfo = (IPBindInfo)obj; if (bInfo.HostName != m_HostName) { return(false); } if (bInfo.Protocol != m_Protocol) { return(false); } if (!bInfo.EndPoint.Equals(m_pEndPoint)) { return(false); } if (bInfo.SslMode != m_SslMode) { return(false); } if (!X509Certificate.Equals(bInfo.Certificate, m_pCertificate)) { return(false); } return(true); }
public virtual bool Match( object obj) { X509Certificate c = obj as X509Certificate; if (c == null) { return(false); } if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier)) { return(false); } if (basicConstraints != -1) { int bc = c.GetBasicConstraints(); if (basicConstraints == -2) { if (bc != -1) { return(false); } } else { if (bc < basicConstraints) { return(false); } } } if (certificate != null && !certificate.Equals(c)) { return(false); } if (certificateValid != null && !c.IsValid(certificateValid.Value)) { return(false); } if (extendedKeyUsage != null) { IList eku = c.GetExtendedKeyUsage(); // Note: if no extended key usage set, all key purposes are implicitly allowed if (eku != null) { foreach (DerObjectIdentifier oid in extendedKeyUsage) { if (!eku.Contains(oid.Id)) { return(false); } } } } if (issuer != null && !issuer.Equivalent(c.IssuerDN, !ignoreX509NameOrdering)) { return(false); } if (keyUsage != null) { bool[] ku = c.GetKeyUsage(); // Note: if no key usage set, all key purposes are implicitly allowed if (ku != null) { for (int i = 0; i < 9; ++i) { if (keyUsage[i] && !ku[i]) { return(false); } } } } if (policy != null) { Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies); if (extVal == null) { return(false); } Asn1Sequence certPolicies = Asn1Sequence.GetInstance( X509ExtensionUtilities.FromExtensionValue(extVal)); if (policy.Count < 1 && certPolicies.Count < 1) { return(false); } bool found = false; foreach (PolicyInformation pi in certPolicies) { if (policy.Contains(pi.PolicyIdentifier)) { found = true; break; } } if (!found) { return(false); } } if (privateKeyValid != null) { Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod); if (extVal == null) { return(false); } PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance( X509ExtensionUtilities.FromExtensionValue(extVal)); DateTime dt = privateKeyValid.Value; DateTime notAfter = pkup.NotAfter.ToDateTime(); DateTime notBefore = pkup.NotBefore.ToDateTime(); if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0) { return(false); } } if (serialNumber != null && !serialNumber.Equals(c.SerialNumber)) { return(false); } if (subject != null && !subject.Equivalent(c.SubjectDN, !ignoreX509NameOrdering)) { return(false); } if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier)) { return(false); } if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c))) { return(false); } if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID)) { return(false); } return(true); }
public virtual PkixCertPathValidatorResult Validate( PkixCertPath certPath, PkixParameters paramsPkix) { if (paramsPkix.GetTrustAnchors() == null) { throw new ArgumentException( "trustAnchors is null, this is not allowed for certification path validation.", "parameters"); } // // 6.1.1 - inputs // // // (a) // IList certs = certPath.Certificates; int n = certs.Count; if (certs.Count == 0) { throw new PkixCertPathValidatorException("Certification path is empty.", null, certPath, 0); } // // (b) // // DateTime validDate = PkixCertPathValidatorUtilities.GetValidDate(paramsPkix); // // (c) // ISet userInitialPolicySet = paramsPkix.GetInitialPolicies(); // // (d) // TrustAnchor trust; try { trust = PkixCertPathValidatorUtilities.FindTrustAnchor( (X509Certificate)certs[certs.Count - 1], paramsPkix.GetTrustAnchors()); if (trust == null) { throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1); } CheckCertificate(trust.TrustedCert); } catch (Exception e) { throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, certs.Count - 1); } // // (e), (f), (g) are part of the paramsPkix object. // IEnumerator certIter; int index = 0; int i; // Certificate for each interation of the validation loop // Signature information for each iteration of the validation loop // // 6.1.2 - setup // // // (a) // IList[] policyNodes = new IList[n + 1]; for (int j = 0; j < policyNodes.Length; j++) { policyNodes[j] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); } ISet policySet = new HashSet(); policySet.Add(Rfc3280CertPathUtilities.ANY_POLICY); PkixPolicyNode validPolicyTree = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), 0, policySet, null, new HashSet(), Rfc3280CertPathUtilities.ANY_POLICY, false); policyNodes[0].Add(validPolicyTree); // // (b) and (c) // PkixNameConstraintValidator nameConstraintValidator = new PkixNameConstraintValidator(); // (d) // int explicitPolicy; ISet acceptablePolicies = new HashSet(); if (paramsPkix.IsExplicitPolicyRequired) { explicitPolicy = 0; } else { explicitPolicy = n + 1; } // // (e) // int inhibitAnyPolicy; if (paramsPkix.IsAnyPolicyInhibited) { inhibitAnyPolicy = 0; } else { inhibitAnyPolicy = n + 1; } // // (f) // int policyMapping; if (paramsPkix.IsPolicyMappingInhibited) { policyMapping = 0; } else { policyMapping = n + 1; } // // (g), (h), (i), (j) // AsymmetricKeyParameter workingPublicKey; X509Name workingIssuerName; X509Certificate sign = trust.TrustedCert; try { if (sign != null) { workingIssuerName = sign.SubjectDN; workingPublicKey = sign.GetPublicKey(); } else { workingIssuerName = new X509Name(trust.CAName); workingPublicKey = trust.CAPublicKey; } } catch (ArgumentException ex) { throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1); } AlgorithmIdentifier workingAlgId = null; try { workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey); } catch (PkixCertPathValidatorException e) { throw new PkixCertPathValidatorException( "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1); } // DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.Algorithm; // Asn1Encodable workingPublicKeyParameters = workingAlgId.Parameters; // // (k) // int maxPathLength = n; // // 6.1.3 // X509CertStoreSelector certConstraints = paramsPkix.GetTargetCertConstraints(); if (certConstraints != null && !certConstraints.Match((X509Certificate)certs[0])) { throw new PkixCertPathValidatorException( "Target certificate in certification path does not match targetConstraints.", null, certPath, 0); } // // initialize CertPathChecker's // IList pathCheckers = paramsPkix.GetCertPathCheckers(); certIter = pathCheckers.GetEnumerator(); while (certIter.MoveNext()) { ((PkixCertPathChecker)certIter.Current).Init(false); } X509Certificate cert = null; for (index = certs.Count - 1; index >= 0; index--) { // try // { // // i as defined in the algorithm description // i = n - index; // // set certificate to be checked in this round // sign and workingPublicKey and workingIssuerName are set // at the end of the for loop and initialized the // first time from the TrustAnchor // cert = (X509Certificate)certs[index]; try { CheckCertificate(cert); } catch (Exception e) { throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, index); } // // 6.1.3 // Rfc3280CertPathUtilities.ProcessCertA(certPath, paramsPkix, index, workingPublicKey, workingIssuerName, sign); Rfc3280CertPathUtilities.ProcessCertBC(certPath, index, nameConstraintValidator); validPolicyTree = Rfc3280CertPathUtilities.ProcessCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy); validPolicyTree = Rfc3280CertPathUtilities.ProcessCertE(certPath, index, validPolicyTree); Rfc3280CertPathUtilities.ProcessCertF(certPath, index, validPolicyTree, explicitPolicy); // // 6.1.4 // if (i != n) { if (cert != null && cert.Version == 1) { // we've found the trust anchor at the top of the path, ignore and keep going if ((i == 1) && cert.Equals(trust.TrustedCert)) { continue; } throw new PkixCertPathValidatorException( "Version 1 certificates can't be used as CA ones.", null, certPath, index); } Rfc3280CertPathUtilities.PrepareNextCertA(certPath, index); validPolicyTree = Rfc3280CertPathUtilities.PrepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping); Rfc3280CertPathUtilities.PrepareNextCertG(certPath, index, nameConstraintValidator); // (h) explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertH1(certPath, index, explicitPolicy); policyMapping = Rfc3280CertPathUtilities.PrepareNextCertH2(certPath, index, policyMapping); inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertH3(certPath, index, inhibitAnyPolicy); // // (i) // explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertI1(certPath, index, explicitPolicy); policyMapping = Rfc3280CertPathUtilities.PrepareNextCertI2(certPath, index, policyMapping); // (j) inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertJ(certPath, index, inhibitAnyPolicy); // (k) Rfc3280CertPathUtilities.PrepareNextCertK(certPath, index); // (l) maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertL(certPath, index, maxPathLength); // (m) maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertM(certPath, index, maxPathLength); // (n) Rfc3280CertPathUtilities.PrepareNextCertN(certPath, index); ISet criticalExtensions1 = cert.GetCriticalExtensionOids(); if (criticalExtensions1 != null) { criticalExtensions1 = new HashSet(criticalExtensions1); // these extensions are handled by the algorithm criticalExtensions1.Remove(X509Extensions.KeyUsage.Id); criticalExtensions1.Remove(X509Extensions.CertificatePolicies.Id); criticalExtensions1.Remove(X509Extensions.PolicyMappings.Id); criticalExtensions1.Remove(X509Extensions.InhibitAnyPolicy.Id); criticalExtensions1.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions1.Remove(X509Extensions.DeltaCrlIndicator.Id); criticalExtensions1.Remove(X509Extensions.PolicyConstraints.Id); criticalExtensions1.Remove(X509Extensions.BasicConstraints.Id); criticalExtensions1.Remove(X509Extensions.SubjectAlternativeName.Id); criticalExtensions1.Remove(X509Extensions.NameConstraints.Id); } else { criticalExtensions1 = new HashSet(); } // (o) Rfc3280CertPathUtilities.PrepareNextCertO(certPath, index, criticalExtensions1, pathCheckers); // set signing certificate for next round sign = cert; // (c) workingIssuerName = sign.SubjectDN; // (d) try { workingPublicKey = PkixCertPathValidatorUtilities.GetNextWorkingKey(certPath.Certificates, index); } catch (PkixCertPathValidatorException e) { throw new PkixCertPathValidatorException("Next working key could not be retrieved.", e, certPath, index); } workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey); // (f) // workingPublicKeyAlgorithm = workingAlgId.Algorithm; // (e) // workingPublicKeyParameters = workingAlgId.Parameters; } } // // 6.1.5 Wrap-up procedure // explicitPolicy = Rfc3280CertPathUtilities.WrapupCertA(explicitPolicy, cert); explicitPolicy = Rfc3280CertPathUtilities.WrapupCertB(certPath, index + 1, explicitPolicy); // // (c) (d) and (e) are already done // // // (f) // ISet criticalExtensions = cert.GetCriticalExtensionOids(); if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); // Requires .Id // these extensions are handled by the algorithm criticalExtensions.Remove(X509Extensions.KeyUsage.Id); criticalExtensions.Remove(X509Extensions.CertificatePolicies.Id); criticalExtensions.Remove(X509Extensions.PolicyMappings.Id); criticalExtensions.Remove(X509Extensions.InhibitAnyPolicy.Id); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); criticalExtensions.Remove(X509Extensions.PolicyConstraints.Id); criticalExtensions.Remove(X509Extensions.BasicConstraints.Id); criticalExtensions.Remove(X509Extensions.SubjectAlternativeName.Id); criticalExtensions.Remove(X509Extensions.NameConstraints.Id); criticalExtensions.Remove(X509Extensions.CrlDistributionPoints.Id); } else { criticalExtensions = new HashSet(); } Rfc3280CertPathUtilities.WrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions); PkixPolicyNode intersection = Rfc3280CertPathUtilities.WrapupCertG(certPath, paramsPkix, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies); if ((explicitPolicy > 0) || (intersection != null)) { return(new PkixCertPathValidatorResult(trust, intersection, cert.GetPublicKey())); } throw new PkixCertPathValidatorException("Path processing failed on policy.", null, certPath, index); }
public override void PerformTest() { string signDN = "O=Bouncy Castle, C=AU"; AsymmetricCipherKeyPair signKP = OcspTestUtil.MakeKeyPair(); X509Certificate testCert = OcspTestUtil.MakeCertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; GeneralName origName = new GeneralName(new X509Name(origDN)); // // general id value for our test issuer cert and a serial number. // CertificateID id = new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One); // // basic request generation // OcspReqGenerator gen = new OcspReqGenerator(); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); OcspReq req = gen.Generate(); if (req.IsSigned) { Fail("signed but shouldn't be"); } X509Certificate[] certs = req.GetCerts(); if (certs != null) { Fail("null certs expected, but not found"); } Req[] requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // request generation with signing // X509Certificate[] chain = new X509Certificate[1]; gen = new OcspReqGenerator(); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } certs = req.GetCerts(); if (certs == null) { Fail("null certs found"); } if (certs.Length != 1 || !testCert.Equals(certs[0])) { Fail("incorrect certs found in request"); } // // encoding test // byte[] reqEnc = req.GetEncoded(); OcspReq newReq = new OcspReq(reqEnc); if (!newReq.Verify(signKP.Public)) { Fail("newReq signature failed to Verify"); } // // request generation with signing and nonce // chain = new X509Certificate[1]; gen = new OcspReqGenerator(); IList oids = new ArrayList(); IList values = new ArrayList(); byte[] sampleNonce = new byte[16]; Random rand = new Random(); rand.NextBytes(sampleNonce); gen.SetRequestorName(new GeneralName(GeneralName.DirectoryName, new X509Name("CN=fred"))); oids.Add(OcspObjectIdentifiers.PkixOcspNonce); values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(sampleNonce)))); gen.SetRequestExtensions(new X509Extensions(oids, values)); gen.AddRequest( new CertificateID(CertificateID.HashSha1, testCert, BigInteger.One)); chain[0] = testCert; req = gen.Generate("SHA1withRSA", signKP.Private, chain); if (!req.IsSigned) { Fail("not signed but should be"); } if (!req.Verify(signKP.Public)) { Fail("signature failed to Verify"); } // // extension check. // ISet extOids = req.GetCriticalExtensionOids(); if (extOids.Count != 0) { Fail("wrong number of critical extensions in OCSP request."); } extOids = req.GetNonCriticalExtensionOids(); if (extOids.Count != 1) { Fail("wrong number of non-critical extensions in OCSP request."); } Asn1OctetString extValue = req.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce); Asn1Object extObj = X509ExtensionUtilities.FromExtensionValue(extValue); if (!(extObj is Asn1OctetString)) { Fail("wrong extension type found."); } byte[] compareNonce = ((Asn1OctetString)extObj).GetOctets(); if (!AreEqual(compareNonce, sampleNonce)) { Fail("wrong extension value found."); } // // request list check // requests = req.GetRequestList(); if (!requests[0].GetCertID().Equals(id)) { Fail("Failed isFor test"); } // // response parsing - test 1 // OcspResp response = new OcspResp(testResp1); if (response.Status != 0) { Fail("response status not zero."); } BasicOcspResp brep = (BasicOcspResp)response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 1 failed to Verify."); } // // test 2 // SingleResp[] singleResp = brep.Responses; response = new OcspResp(testResp2); if (response.Status != 0) { Fail("response status not zero."); } brep = (BasicOcspResp)response.GetResponseObject(); chain = brep.GetCerts(); if (!brep.Verify(chain[0].GetPublicKey())) { Fail("response 2 failed to Verify."); } singleResp = brep.Responses; // // simple response generation // OCSPRespGenerator respGen = new OCSPRespGenerator(); OcspResp resp = respGen.Generate(OCSPRespGenerator.Successful, response.GetResponseObject()); if (!resp.GetResponseObject().Equals(response.GetResponseObject())) { Fail("response fails to match"); } doTestECDsa(); doTestRsa(); doTestIrregularVersionReq(); }
public virtual bool Match(object obj) { X509Certificate x509Certificate = obj as X509Certificate; if (x509Certificate == null) { return(false); } if (!MatchExtension(authorityKeyIdentifier, x509Certificate, X509Extensions.AuthorityKeyIdentifier)) { return(false); } if (basicConstraints != -1) { int num = x509Certificate.GetBasicConstraints(); if (basicConstraints == -2) { if (num != -1) { return(false); } } else if (num < basicConstraints) { return(false); } } if (certificate != null && !certificate.Equals(x509Certificate)) { return(false); } if (certificateValid != null && !x509Certificate.IsValid(certificateValid.Value)) { return(false); } if (extendedKeyUsage != null) { global::System.Collections.IList list = x509Certificate.GetExtendedKeyUsage(); if (list != null) { { global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)extendedKeyUsage).GetEnumerator(); try { while (enumerator.MoveNext()) { DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current(); if (!list.Contains((object)derObjectIdentifier.Id)) { return(false); } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } } } } if (issuer != null && !issuer.Equivalent(x509Certificate.IssuerDN, inOrder: true)) { return(false); } if (keyUsage != null) { bool[] array = x509Certificate.GetKeyUsage(); if (array != null) { for (int i = 0; i < 9; i++) { if (keyUsage[i] && !array[i]) { return(false); } } } } if (policy != null) { Asn1OctetString extensionValue = x509Certificate.GetExtensionValue(X509Extensions.CertificatePolicies); if (extensionValue == null) { return(false); } Asn1Sequence instance = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)); if (((global::System.Collections.ICollection)policy).get_Count() < 1 && instance.Count < 1) { return(false); } bool flag = false; { global::System.Collections.IEnumerator enumerator = instance.GetEnumerator(); try { while (enumerator.MoveNext()) { PolicyInformation policyInformation = (PolicyInformation)enumerator.get_Current(); if (policy.Contains(policyInformation.PolicyIdentifier)) { flag = true; break; } } } finally { global::System.IDisposable disposable2 = enumerator as global::System.IDisposable; if (disposable2 != null) { disposable2.Dispose(); } } } if (!flag) { return(false); } } if (privateKeyValid != null) { Asn1OctetString extensionValue2 = x509Certificate.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod); if (extensionValue2 == null) { return(false); } PrivateKeyUsagePeriod instance2 = PrivateKeyUsagePeriod.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2)); global::System.DateTime value = privateKeyValid.Value; global::System.DateTime dateTime = instance2.NotAfter.ToDateTime(); global::System.DateTime dateTime2 = instance2.NotBefore.ToDateTime(); if (value.CompareTo((object)dateTime) > 0 || value.CompareTo((object)dateTime2) < 0) { return(false); } } if (serialNumber != null && !serialNumber.Equals(x509Certificate.SerialNumber)) { return(false); } if (subject != null && !subject.Equivalent(x509Certificate.SubjectDN, inOrder: true)) { return(false); } if (!MatchExtension(subjectKeyIdentifier, x509Certificate, X509Extensions.SubjectKeyIdentifier)) { return(false); } if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(x509Certificate))) { return(false); } if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(x509Certificate).AlgorithmID)) { return(false); } return(true); }
private void ResignIPA(IPAFile ipaFile, byte[] mobileProvisionBytes, byte[] signingCertificateBytes, string certificatePassword, string outputIPAPath) { // Validate that the mobileprovision match the given certificate MobileProvisionFile mobileProvision; if (mobileProvisionBytes == null) { mobileProvision = ipaFile.GetMobileProvision(); } else { mobileProvision = new MobileProvisionFile(mobileProvisionBytes); } List <byte[]> developerCertificates = mobileProvision.PList.DeveloperCertificates; if (developerCertificates.Count == 0) { MessageBox.Show("Mobile Provision does not contain developer certificate information", "Error"); return; } AsymmetricKeyEntry privateKey; X509Certificate signingCertificate = CertificateHelper.GetCertificateAndKeyFromBytes(signingCertificateBytes, certificatePassword, out privateKey); if (signingCertificate == null) { MessageBox.Show("Failed to parse the given signing certificate", "Error"); return; } bool foundMatchingCertificate = false; for (int index = 0; index < developerCertificates.Count; index++) { X509Certificate provisionedCertificate = CertificateHelper.GetCertificatesFromBytes(developerCertificates[index]); if (provisionedCertificate.Equals(signingCertificate)) { foundMatchingCertificate = true; } } if (!foundMatchingCertificate) { MessageBox.Show("The signing certificate given does not match any specified in the Mobile Provision file", "Error"); return; } List <X509Certificate> certificateStore; try { certificateStore = ReadCertificatesDirectory(); } catch { MessageBox.Show("Failed to read certificate directory", "Error"); return; } List <X509Certificate> certificateChain = CertificateHelper.BuildCertificateChain(signingCertificate, certificateStore); if (mobileProvisionBytes != null) { ipaFile.ReplaceMobileProvision(mobileProvisionBytes); } if (ipaFile.HasFrameworksFolder) { MessageBox.Show("Signing an IPA containing a framework is not supported", "Not supported"); return; } ipaFile.ResignIPA(certificateChain, privateKey); try { ipaFile.Save(outputIPAPath); } catch (IOException ex) { MessageBox.Show("Failed to save output IPA: " + ex.Message, "Error"); return; } MessageBox.Show("Done!"); }
private void ResignIPA(IPAFile ipaFile, byte[] mobileProvisionBytes, byte[] signingCertificateBytes, string certificatePassword, string outputIPAPath) { // Validate that the mobileprovision match the given certificate MobileProvisionFile mobileProvision; if (mobileProvisionBytes == null) { mobileProvision = ipaFile.GetMobileProvision(); } else { mobileProvision = new MobileProvisionFile(mobileProvisionBytes); } if (mobileProvision.PList.DeveloperCertificates.Count == 0) { MessageBox.Show("Mobile Provision does not contain developer certificate information", "Error"); return; } X509Certificate provisionedCertificate = CertificateHelper.GetCertificatesFromBytes(mobileProvision.PList.DeveloperCertificates[0]); AsymmetricKeyEntry privateKey; X509Certificate signingCertificate = CertificateHelper.GetCertificateAndKeyFromBytes(signingCertificateBytes, certificatePassword, out privateKey); if (signingCertificate == null) { MessageBox.Show("Failed to parse the given signing certificate", "Error"); return; } if (!provisionedCertificate.Equals(signingCertificate)) { MessageBox.Show("The signing certificate given does not match the one specified in the Mobile Provision file", "Error"); return; } List <X509Certificate> certificateStore; try { certificateStore = ReadCertificatesDirectory(); } catch { MessageBox.Show("Failed to read certificate directory", "Error"); return; } List <X509Certificate> certificateChain = CertificateHelper.BuildCertificateChain(signingCertificate, certificateStore); if (mobileProvisionBytes != null) { ipaFile.ReplaceMobileProvision(mobileProvisionBytes); } ipaFile.ResignIPA(certificateChain, privateKey); try { ipaFile.Save(outputIPAPath); } catch (IOException ex) { MessageBox.Show("Failed to save output IPA: " + ex.Message, "Error"); return; } MessageBox.Show("Done!"); }
public virtual bool Match(object obj) { X509Certificate x509Certificate = obj as X509Certificate; if (x509Certificate == null) { return(false); } if (!MatchExtension(authorityKeyIdentifier, x509Certificate, X509Extensions.AuthorityKeyIdentifier)) { return(false); } if (basicConstraints != -1) { int num = x509Certificate.GetBasicConstraints(); if (basicConstraints == -2) { if (num != -1) { return(false); } } else if (num < basicConstraints) { return(false); } } if (certificate != null && !certificate.Equals(x509Certificate)) { return(false); } if (certificateValid != null && !x509Certificate.IsValid(certificateValid.Value)) { return(false); } if (extendedKeyUsage != null) { IList list = x509Certificate.GetExtendedKeyUsage(); if (list != null) { foreach (DerObjectIdentifier item in extendedKeyUsage) { if (!list.Contains(item.Id)) { return(false); } } } } if (issuer != null && !issuer.Equivalent(x509Certificate.IssuerDN, inOrder: true)) { return(false); } if (keyUsage != null) { bool[] array = x509Certificate.GetKeyUsage(); if (array != null) { for (int i = 0; i < 9; i++) { if (keyUsage[i] && !array[i]) { return(false); } } } } if (policy != null) { Asn1OctetString extensionValue = x509Certificate.GetExtensionValue(X509Extensions.CertificatePolicies); if (extensionValue == null) { return(false); } Asn1Sequence instance = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)); if (policy.Count < 1 && instance.Count < 1) { return(false); } bool flag = false; foreach (PolicyInformation item2 in instance) { if (policy.Contains(item2.PolicyIdentifier)) { flag = true; break; } } if (!flag) { return(false); } } if (privateKeyValid != null) { Asn1OctetString extensionValue2 = x509Certificate.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod); if (extensionValue2 == null) { return(false); } PrivateKeyUsagePeriod instance2 = PrivateKeyUsagePeriod.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2)); DateTime value = privateKeyValid.Value; DateTime dateTime = instance2.NotAfter.ToDateTime(); DateTime dateTime2 = instance2.NotBefore.ToDateTime(); if (value.CompareTo((object)dateTime) > 0 || value.CompareTo((object)dateTime2) < 0) { return(false); } } if (serialNumber != null && !serialNumber.Equals(x509Certificate.SerialNumber)) { return(false); } if (subject != null && !subject.Equivalent(x509Certificate.SubjectDN, inOrder: true)) { return(false); } if (!MatchExtension(subjectKeyIdentifier, x509Certificate, X509Extensions.SubjectKeyIdentifier)) { return(false); } if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(x509Certificate))) { return(false); } if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(x509Certificate).AlgorithmID)) { return(false); } return(true); }
private bool ValidateServerCert(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (certificate is X509Certificate2 c2) { PeerCertificateReceived?.Invoke(this, new TlsCertificateReceivedEventArgs(c2)); } if (_options.PinnedServerCertificate != null) { var retVal = certificate.Equals(_options.PinnedServerCertificate); if (!retVal) { WriteLog.To.Sync.W(Tag, "Server certificate did not match the pinned one!"); _validationException = new TlsCertificateException("The certificate does not match the pinned certificate", C4NetworkErrorCode.TLSCertUnknownRoot, X509ChainStatusFlags.ExplicitDistrust); } return(retVal); } // Mono doesn't pass chain information? if (chain?.ChainElements?.Count == 0 && certificate is X509Certificate2 cert2) { chain = X509Chain.Create(); chain.Build(cert2); } #if COUCHBASE_ENTERPRISE var onlySelfSigned = _options.AcceptOnlySelfSignedServerCertificate; #else var onlySelfSigned = false; #endif if (!onlySelfSigned && sslPolicyErrors != SslPolicyErrors.None) { WriteLog.To.Sync.W(Tag, $"Error validating TLS chain: {sslPolicyErrors}"); if (chain.ChainElements != null) { foreach (var element in chain.ChainElements) { if (element.ChainElementStatus != null) { foreach (var status in element.ChainElementStatus) { if (status.Status != X509ChainStatusFlags.NoError) { WriteLog.To.Sync.V(Tag, $"Error {status.Status} ({status.StatusInformation}) for certificate:{Environment.NewLine}{element.Certificate}"); if (status.Status == X509ChainStatusFlags.UntrustedRoot) { _validationException = new TlsCertificateException("The certificate does not terminate in a trusted root CA.", C4NetworkErrorCode.TLSCertUnknownRoot, X509ChainStatusFlags.UntrustedRoot); return(false); } } } } } } if (chain.ChainStatus != null) { foreach (var status in chain.ChainStatus) { if (status.Status == X509ChainStatusFlags.PartialChain) { _validationException = new TlsCertificateException("The certificate does not terminate in a trusted root CA.", C4NetworkErrorCode.TLSCertUnknownRoot, X509ChainStatusFlags.PartialChain); return(false); } } } } else if (onlySelfSigned) { if (chain.ChainElements.Count != 1) { _validationException = new TlsCertificateException("A non self-signed certificate was received in self-signed mode.", C4NetworkErrorCode.TLSCertUnknownRoot, X509ChainStatusFlags.ExplicitDistrust); return(false); } if (chain.ChainStatus[0].Status != X509ChainStatusFlags.UntrustedRoot && chain.ChainStatus[0].Status != X509ChainStatusFlags.PartialChain && chain.ChainStatus[0].Status != X509ChainStatusFlags.NoError) { _validationException = new TlsCertificateException("Certificate verification failed", C4NetworkErrorCode.TLSCertUnknownRoot, chain.ChainStatus[0].Status); return(false); } if (chain.ChainElements[0].Certificate.IssuerName.Name != chain.ChainElements[0].Certificate.SubjectName.Name) { _validationException = new TlsCertificateException("A non self-signed certificate was received in self-signed mode.", C4NetworkErrorCode.TLSCertUnknownRoot, X509ChainStatusFlags.ExplicitDistrust); return(false); } return(true); } if (sslPolicyErrors == SslPolicyErrors.None) { return(true); } _validationException = new TlsCertificateException("Certificate verification failed", C4NetworkErrorCode.TLSCertUntrusted, sslPolicyErrors); return(false); }
// // Acquire Server Side Certificate information and set it on the class. // private bool AcquireServerCredentials(ref byte[] thumbPrint) { GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials"); X509Certificate localCertificate = null; bool cachedCred = false; if (_certSelectionDelegate != null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); tempCollection.Add(_serverCertificate); localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty <string>()); GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert"); } else { localCertificate = _serverCertificate; } if (localCertificate == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate); if (selectedCert == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } GlobalLog.Assert(localCertificate.Equals(selectedCert), "AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'."); // // Note selectedCert is a safe ref possibly cloned from the user passed Cert object // byte[] guessedThumbPrint = selectedCert.GetCertHash(); try { SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); if (cachedCredentialHandle != null) { _credentialsHandle = cachedCredentialHandle; _serverCertificate = localCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode); thumbPrint = guessedThumbPrint; _serverCertificate = localCertificate; } } finally { // An extra cert could have been created, dispose it now. if ((object)localCertificate != (object)selectedCert) { selectedCert.Dispose(); } } GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), Logging.ObjectToString(_credentialsHandle)); return(cachedCred); }
/*++ * AcquireCredentials - Attempts to find Client Credential * Information, that can be sent to the server. In our case, * this is only Client Certificates, that we have Credential Info. * * How it works: * case 0: Cert Selection delegate is present * Always use its result as the client cert answer. * Try to use cached credential handle whenever feasible. * Do not use cached anonymous creds if the delegate has returned null * and the collection is not empty (allow responding with the cert later). * * case 1: Certs collection is empty * Always use the same statically acquired anonymous SSL Credential * * case 2: Before our Connection with the Server * If we have a cached credential handle keyed by first X509Certificate **content** in the passed collection, then we use that cached * credential and hoping to restart a session. * * Otherwise create a new anonymous (allow responding with the cert later). * * case 3: After our Connection with the Server (i.e. during handshake or re-handshake) * The server has requested that we send it a Certificate then * we Enumerate a list of server sent Issuers trying to match against * our list of Certificates, the first match is sent to the server. * * Once we got a cert we again try to match cached credential handle if possible. * This will not restart a session but helps minimizing the number of handles we create. * * In the case of an error getting a Certificate or checking its private Key we fall back * to the behavior of having no certs, case 1. * * Returns: True if cached creds were used, false otherwise. * * --*/ private bool AcquireClientCredentials(ref byte[] thumbPrint) { GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials"); // Acquire possible Client Certificate information and set it on the handle. X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart. ArrayList filteredCerts = new ArrayList(); // This is an intermediate client certs collection that try to use if no selectedCert is available yet. string[] issuers = null; // This is a list of issuers sent by the server, only valid is we do know what the server cert is. bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds. if (_certSelectionDelegate != null) { issuers = GetRequestCertificateAuthorities(); GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() calling CertificateSelectionCallback"); X509Certificate2 remoteCert = null; try { X509Certificate2Collection dummyCollection; remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext, out dummyCollection); clientCertificate = _certSelectionDelegate(_hostName, ClientCertificates, remoteCert, issuers); } finally { if (remoteCert != null) { remoteCert.Dispose(); } } if (clientCertificate != null) { if (_credentialsHandle == null) { sessionRestartAttempt = true; } filteredCerts.Add(clientCertificate); if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.net_log_got_certificate_from_delegate); } } else { if (ClientCertificates.Count == 0) { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.net_log_no_delegate_and_have_no_client_cert); } sessionRestartAttempt = true; } else { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.net_log_no_delegate_but_have_client_cert); } } } } else if (_credentialsHandle == null && _clientCertificates != null && _clientCertificates.Count > 0) { // This is where we attempt to restart a session by picking the FIRST cert from the collection. // Otherwise it is either server sending a client cert request or the session is renegotiated. clientCertificate = ClientCertificates[0]; sessionRestartAttempt = true; if (clientCertificate != null) { filteredCerts.Add(clientCertificate); } if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_attempting_restart_using_cert, (clientCertificate == null ? "null" : clientCertificate.ToString(true)))); } } else if (_clientCertificates != null && _clientCertificates.Count > 0) { // // This should be a server request for the client cert sent over currently anonymous sessions. // issuers = GetRequestCertificateAuthorities(); if (Logging.On) { if (issuers == null || issuers.Length == 0) { Logging.PrintInfo(Logging.Web, this, SR.net_log_no_issuers_try_all_certs); } else { Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_server_issuers_look_for_matching_certs, issuers.Length)); } } for (int i = 0; i < _clientCertificates.Count; ++i) { // // Make sure we add only if the cert matches one of the issuers. // If no issuers were sent and then try all client certs starting with the first one. // if (issuers != null && issuers.Length != 0) { X509Certificate2 certificateEx = null; X509Chain chain = null; try { certificateEx = MakeEx(_clientCertificates[i]); if (certificateEx == null) { continue; } GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() root cert:" + certificateEx.Issuer); chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName; chain.Build(certificateEx); bool found = false; // // We ignore any errors happened with chain. // if (chain.ChainElements.Count > 0) { for (int ii = 0; ii < chain.ChainElements.Count; ++ii) { string issuer = chain.ChainElements[ii].Certificate.Issuer; found = Array.IndexOf(issuers, issuer) != -1; if (found) { GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() matched:" + issuer); break; } GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() no match:" + issuer); } } if (!found) { continue; } } finally { if (chain != null) { chain.Dispose(); } if (certificateEx != null && (object)certificateEx != (object)_clientCertificates[i]) { certificateEx.Dispose(); } } } if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_selected_cert, _clientCertificates[i].ToString(true))); } filteredCerts.Add(_clientCertificates[i]); } } bool cachedCred = false; // This is a return result from this method. X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it). clientCertificate = null; if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_n_certs_after_filtering, filteredCerts.Count)); if (filteredCerts.Count != 0) { Logging.PrintInfo(Logging.Web, this, SR.net_log_finding_matching_certs); } } // // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key, // THEN anonymous (no client cert) credential will be used. // // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. for (int i = 0; i < filteredCerts.Count; ++i) { clientCertificate = filteredCerts[i] as X509Certificate; if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null) { break; } clientCertificate = null; selectedCert = null; } GlobalLog.Assert(((object)clientCertificate == (object)selectedCert) || clientCertificate.Equals(selectedCert), "AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'."); GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() Selected Cert = " + (selectedCert == null ? "null" : selectedCert.Subject)); try { // Try to locate cached creds first. // // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type. // byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash(); SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); // We can probably do some optimization here. If the selectedCert is returned by the delegate // we can always go ahead and use the certificate to create our credential // (instead of going anonymous as we do here). if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null) { GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() Reset to anonymous session."); // IIS does not renegotiate a restarted session if client cert is needed. // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate. // The following block happens if client did specify a certificate but no cached creds were found in the cache. // Since we don't restart a session the server side can still challenge for a client cert. if ((object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } guessedThumbPrint = null; selectedCert = null; clientCertificate = null; } if (cachedCredentialHandle != null) { if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.net_log_using_cached_credential); } _credentialsHandle = cachedCredentialHandle; _selectedClientCertificate = clientCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode); thumbPrint = guessedThumbPrint; // Delay until here in case something above threw. _selectedClientCertificate = clientCertificate; } } finally { // An extra cert could have been created, dispose it now. if (selectedCert != null && (object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } } GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials, cachedCreds = " + cachedCred.ToString(), Logging.ObjectToString(_credentialsHandle)); return(cachedCred); }
static bool ValidateCertAgainstBaseline(IDictionary <string, string> certVals, X509Certificate cer) { bool retVal = true; long effectiveDateFound, expiryDateFound, effectiveDateBsl, expiryDateBsl; byte[] bytes; string str; int hash; IntPtr handle; // now validate against the actual cert if (!certVals["HashString"].Equals(cer.GetCertHashString())) { TestFramework.LogError("001", "Expected hash string: " + certVals["HashString"] + ", found: " + cer.GetCertHashString()); retVal = false; } // check the dates try { effectiveDateBsl = Convert.ToInt64(certVals["EffectiveDateStringInTicks"]); effectiveDateFound = DateTime.Parse(cer.GetEffectiveDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks; expiryDateBsl = Convert.ToInt64(certVals["ExpirationDateStringInTicks"]); expiryDateFound = DateTime.Parse(cer.GetExpirationDateString(), CultureInfo.InvariantCulture).ToUniversalTime().Ticks; if (effectiveDateBsl != effectiveDateFound) { TestFramework.LogError("002", "Expected \"Valid From\": [" + (new DateTime(effectiveDateBsl, DateTimeKind.Utc)).ToString() + "], found: [" + cer.GetEffectiveDateString() + " nonUTC]"); TestFramework.LogError("002", " ticks(" + effectiveDateBsl + ") found ticks(" + effectiveDateFound + ")"); retVal = false; } if (expiryDateBsl != expiryDateFound) { TestFramework.LogError("003", "Expected \"Valid To\": [" + (new DateTime(expiryDateBsl)).ToString() + "], found: [" + cer.GetExpirationDateString() + " nonUTC]"); TestFramework.LogError("003", " ticks(" + expiryDateBsl + ") found ticks(" + expiryDateFound + ")"); retVal = false; } } catch (Exception e) { TestFramework.LogError("103", "Unexpected exception: " + e); retVal = false; } TestFramework.LogInformation(" Validating field: Format"); if (!certVals["Format"].Equals(cer.GetFormat())) { TestFramework.LogError("004", "Expected format: " + certVals["Format"] + ", found: " + cer.GetFormat()); retVal = false; } TestFramework.LogInformation(" Validating field: Issuer"); if (!certVals["Issuer"].Equals(cer.Issuer)) { TestFramework.LogError("005", "Expected issuer: " + certVals["Issuer"] + ", found: " + cer.Issuer); retVal = false; } TestFramework.LogInformation(" Validating field: KeyAlgorithm"); if (!certVals["KeyAlgorithm"].Equals(cer.GetKeyAlgorithm())) { TestFramework.LogError("006", "Expected key algorithm: " + certVals["KeyAlgorithm"] + ", found: " + cer.GetKeyAlgorithm()); retVal = false; } TestFramework.LogInformation(" Validating field: KeyAlgorithmParameters"); if (!certVals["KeyAlgorithmParameters"].Equals(cer.GetKeyAlgorithmParametersString())) { TestFramework.LogError("007", "Expected key alg parameters :" + certVals["KeyAlgorithmParameters"] + ", found :" + cer.GetKeyAlgorithmParametersString()); retVal = false; } TestFramework.LogInformation(" Validating field: PublicKeyString"); if (!certVals["PublicKeyString"].Equals(cer.GetPublicKeyString())) { TestFramework.LogError("008", "Expected public key: " + certVals["PublicKeyString"] + ", found: " + cer.GetPublicKeyString()); retVal = false; } TestFramework.LogInformation(" Validating field: SerialNumberString"); if (!certVals["SerialNumberString"].Equals(cer.GetSerialNumberString())) { TestFramework.LogError("009", "Expected serial number: " + certVals["SerialNumberString"] + ", found: " + cer.GetSerialNumberString()); retVal = false; } TestFramework.LogInformation(" Validating field: Subject"); if (!certVals["Subject"].Equals(cer.Subject)) { TestFramework.LogError("010", "Expected subject: " + certVals["Subject"] + ", found: " + cer.Subject); retVal = false; } TestFramework.LogInformation(" Retrieving field: CertHash"); bytes = cer.GetCertHash(); TestFramework.LogInformation(" Retrieving field: HashCode"); hash = cer.GetHashCode(); TestFramework.LogInformation(" Retrieving field: RawCertHash"); bytes = cer.GetRawCertData(); TestFramework.LogInformation(" Retrieving field: RawCertDataString"); str = cer.GetRawCertDataString(); TestFramework.LogInformation(" Retrieving field: SerialNumber"); bytes = cer.GetSerialNumber(); TestFramework.LogInformation(" Retrieving field: ToString()"); str = cer.ToString(); TestFramework.LogInformation(" Retrieving field: ToString(true)"); str = cer.ToString(true); TestFramework.LogInformation(" Retrieving field: Handle"); handle = GetHandle(cer); TestFramework.LogInformation(" Testing: Equality with a string"); if (cer.Equals(str)) { TestFramework.LogError("110", "X509Certificate \"equals\" a string?"); retVal = false; } TestFramework.LogInformation(" Testing: Equality with itself(1)"); if (!cer.Equals((object)cer)) { TestFramework.LogError("120", "X509Certificate does not equal itself"); retVal = false; } TestFramework.LogInformation(" Testing: Equality with itself(2)"); if (!cer.Equals(cer)) { TestFramework.LogError("130", "X509Certificate does not equal itself"); retVal = false; } return(retVal); }
internal static void ProcessAttrCert4(X509Certificate acIssuerCert, PkixParameters pkixParams) { ISet trustedACIssuers = pkixParams.GetTrustedACIssuers(); bool flag = false; global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)trustedACIssuers).GetEnumerator(); try { while (enumerator.MoveNext()) { TrustAnchor trustAnchor = (TrustAnchor)enumerator.get_Current(); IDictionary rFC2253Symbols = (IDictionary)(object)X509Name.RFC2253Symbols; if (acIssuerCert.SubjectDN.ToString(reverse: false, rFC2253Symbols).Equals(trustAnchor.CAName) || acIssuerCert.Equals(trustAnchor.TrustedCert)) { flag = true; } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } if (!flag) { throw new PkixCertPathValidatorException("Attribute certificate issuer is not directly trusted."); } }
private bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors) { return(certificate.Equals(Certificate)); }
internal static void ProcessAttrCert4(X509Certificate acIssuerCert, PkixParameters pkixParams) { ISet trustedACIssuers = pkixParams.GetTrustedACIssuers(); bool flag = false; foreach (TrustAnchor item in trustedACIssuers) { IDictionary rFC2253Symbols = X509Name.RFC2253Symbols; if (acIssuerCert.SubjectDN.ToString(reverse: false, rFC2253Symbols).Equals(item.CAName) || acIssuerCert.Equals(item.TrustedCert)) { flag = true; } } if (!flag) { throw new PkixCertPathValidatorException("Attribute certificate issuer is not directly trusted."); } }