public DistributionPoint[] GetDistributionPoints() { DistributionPoint[] pointArray = new DistributionPoint[this.seq.Count]; for (int i = 0; i != this.seq.Count; i++) { pointArray[i] = DistributionPoint.GetInstance(this.seq[i]); } return(pointArray); }
public DistributionPoint[] GetDistributionPoints() { DistributionPoint[] array = new DistributionPoint[this.seq.Count]; for (int num = 0; num != this.seq.Count; num++) { array[num] = DistributionPoint.GetInstance(this.seq[num]); } return(array); }
public DistributionPoint[] GetDistributionPoints() { DistributionPoint[] array = new DistributionPoint[seq.Count]; for (int i = 0; i != seq.Count; i++) { array[i] = DistributionPoint.GetInstance(seq[i]); } return(array); }
/** * Return the distribution points making up the sequence. * * @return DistributionPoint[] */ public DistributionPoint[] GetDistributionPoints() { DistributionPoint[] dp = new DistributionPoint[seq.Count]; for (int i = 0; i != seq.Count; ++i) { dp[i] = DistributionPoint.GetInstance(seq[i]); } return(dp); }
/** * Return the distribution points making up the sequence. * * @return DistributionPoint[] */ public DistributionPoint[] GetDistributionPoints() { DistributionPoint[] dp = new DistributionPoint[seq.Count]; for (int i = 0; i != seq.Count; ++i) { dp[i] = DistributionPoint.GetInstance(seq[i]); } return dp; }
/** * If the complete CRL includes an issuing distribution point (IDP) CRL * extension check the following: * <p> * (i) If the distribution point name is present in the IDP CRL extension * and the distribution field is present in the DP, then verify that one of * the names in the IDP matches one of the names in the DP. If the * distribution point name is present in the IDP CRL extension and the * distribution field is omitted from the DP, then verify that one of the * names in the IDP matches one of the names in the cRLIssuer field of the * DP. * </p> * <p> * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL * extension, verify that the certificate does not include the basic * constraints extension with the cA boolean asserted. * </p> * <p> * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL * extension, verify that the certificate includes the basic constraints * extension with the cA boolean asserted. * </p> * <p> * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted. * </p> * * @param dp The distribution point. * @param cert The certificate. * @param crl The CRL. * @throws AnnotatedException if one of the conditions is not met or an error occurs. */ internal static void ProcessCrlB2( DistributionPoint dp, object cert, X509Crl crl) { IssuingDistributionPoint idp = null; try { idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint)); } catch (Exception e) { throw new Exception("0 Issuing distribution point extension could not be decoded.", e); } // (b) (2) (i) // distribution point name is present if (idp != null) { if (idp.DistributionPoint != null) { // make list of names DistributionPointName dpName = IssuingDistributionPoint.GetInstance(idp).DistributionPoint; IList names = Platform.CreateArrayList(); if (dpName.PointType == DistributionPointName.FullName) { GeneralName[] genNames = GeneralNames.GetInstance(dpName.Name).GetNames(); for (int j = 0; j < genNames.Length; j++) { names.Add(genNames[j]); } } if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer) { Asn1EncodableVector vec = new Asn1EncodableVector(); try { IEnumerator e = Asn1Sequence.GetInstance( Asn1Sequence.FromByteArray(crl.IssuerDN.GetEncoded())).GetEnumerator(); while (e.MoveNext()) { vec.Add((Asn1Encodable)e.Current); } } catch (IOException e) { throw new Exception("Could not read CRL issuer.", e); } vec.Add(dpName.Name); names.Add(new GeneralName(X509Name.GetInstance(new DerSequence(vec)))); } bool matches = false; // verify that one of the names in the IDP matches one // of the names in the DP. if (dp.DistributionPointName != null) { dpName = dp.DistributionPointName; GeneralName[] genNames = null; if (dpName.PointType == DistributionPointName.FullName) { genNames = GeneralNames.GetInstance(dpName.Name).GetNames(); } if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer) { if (dp.CrlIssuer != null) { genNames = dp.CrlIssuer.GetNames(); } else { genNames = new GeneralName[1]; try { genNames[0] = new GeneralName( PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert)); } catch (IOException e) { throw new Exception("Could not read certificate issuer.", e); } } for (int j = 0; j < genNames.Length; j++) { IEnumerator e = Asn1Sequence.GetInstance(genNames[j].Name.ToAsn1Object()).GetEnumerator(); Asn1EncodableVector vec = new Asn1EncodableVector(); while (e.MoveNext()) { vec.Add((Asn1Encodable)e.Current); } vec.Add(dpName.Name); genNames[j] = new GeneralName(X509Name.GetInstance(new DerSequence(vec))); } } if (genNames != null) { for (int j = 0; j < genNames.Length; j++) { if (names.Contains(genNames[j])) { matches = true; break; } } } if (!matches) { throw new Exception( "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point."); } } // verify that one of the names in // the IDP matches one of the names in the cRLIssuer field of // the DP else { if (dp.CrlIssuer == null) { throw new Exception("Either the cRLIssuer or the distributionPoint field must " + "be contained in DistributionPoint."); } GeneralName[] genNames = dp.CrlIssuer.GetNames(); for (int j = 0; j < genNames.Length; j++) { if (names.Contains(genNames[j])) { matches = true; break; } } if (!matches) { throw new Exception( "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point."); } } } BasicConstraints bc = null; try { bc = BasicConstraints.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue( (IX509Extension)cert, X509Extensions.BasicConstraints)); } catch (Exception e) { throw new Exception("Basic constraints extension could not be decoded.", e); } //if (cert is X509Certificate) { // (b) (2) (ii) if (idp.OnlyContainsUserCerts && ((bc != null) && bc.IsCA())) { throw new Exception("CA Cert CRL only contains user certificates."); } // (b) (2) (iii) if (idp.OnlyContainsCACerts && (bc == null || !bc.IsCA())) { throw new Exception("End CRL only contains CA certificates."); } } // (b) (2) (iv) if (idp.OnlyContainsAttributeCerts) { throw new Exception("onlyContainsAttributeCerts boolean is asserted."); } } }
/** * If the DP includes cRLIssuer, then verify that the issuer field in the * complete CRL matches cRLIssuer in the DP and that the complete CRL * contains an * g distribution point extension with the indirectCRL * boolean asserted. Otherwise, verify that the CRL issuer matches the * certificate issuer. * * @param dp The distribution point. * @param cert The certificate ot attribute certificate. * @param crl The CRL for <code>cert</code>. * @throws AnnotatedException if one of the above conditions does not apply or an error * occurs. */ internal static void ProcessCrlB1( DistributionPoint dp, object cert, X509Crl crl) { Asn1Object idp = PkixCertPathValidatorUtilities.GetExtensionValue( crl, X509Extensions.IssuingDistributionPoint); bool isIndirect = false; if (idp != null) { if (IssuingDistributionPoint.GetInstance(idp).IsIndirectCrl) { isIndirect = true; } } byte[] issuerBytes = crl.IssuerDN.GetEncoded(); bool matchIssuer = false; if (dp.CrlIssuer != null) { GeneralName[] genNames = dp.CrlIssuer.GetNames(); for (int j = 0; j < genNames.Length; j++) { if (genNames[j].TagNo == GeneralName.DirectoryName) { try { if (Org.BouncyCastle.Utilities.Arrays.AreEqual(genNames[j].Name.ToAsn1Object().GetEncoded(), issuerBytes)) { matchIssuer = true; } } catch (IOException e) { throw new Exception( "CRL issuer information from distribution point cannot be decoded.", e); } } } if (matchIssuer && !isIndirect) { throw new Exception("Distribution point contains cRLIssuer field but CRL is not indirect."); } if (!matchIssuer) { throw new Exception("CRL issuer of CRL does not match CRL issuer of distribution point."); } } else { if (crl.IssuerDN.Equivalent(PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert), true)) { matchIssuer = true; } } if (!matchIssuer) { throw new Exception("Cannot find matching CRL issuer for certificate."); } }
/** * Checks a certificate if it is revoked. * * @param paramsPKIX PKIX parameters. * @param cert Certificate to check if it is revoked. * @param validDate The date when the certificate revocation status should be * checked. * @param sign The issuer certificate of the certificate <code>cert</code>. * @param workingPublicKey The public key of the issuer certificate <code>sign</code>. * @param certPathCerts The certificates of the certification path. * @throws AnnotatedException if the certificate is revoked or the status cannot be checked * or some error occurs. */ protected static void CheckCrls( PkixParameters paramsPKIX, X509Certificate cert, DateTime validDate, X509Certificate sign, AsymmetricKeyParameter workingPublicKey, IList certPathCerts) { Exception lastException = null; CrlDistPoint crldp = null; try { crldp = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CrlDistributionPoints)); } catch (Exception e) { throw new Exception("CRL distribution point extension could not be read.", e); } try { PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX); } catch (Exception e) { throw new Exception( "No additional CRL locations could be decoded from CRL distribution point extension.", e); } CertStatus certStatus = new CertStatus(); ReasonsMask reasonsMask = new ReasonsMask(); bool validCrlFound = false; // for each distribution point if (crldp != null) { DistributionPoint[] dps = null; try { dps = crldp.GetDistributionPoints(); } catch (Exception e) { throw new Exception("Distribution points could not be read.", e); } if (dps != null) { for (int i = 0; i < dps.Length && certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons; i++) { PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone(); try { CheckCrl(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (Exception e) { lastException = e; } } } } /* * If the revocation status has not been determined, repeat the process * above with any available CRLs not specified in a distribution point * but issued by the certificate issuer. */ if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons) { try { /* * assume a DP with both the reasons and the cRLIssuer fields * omitted and a distribution point name of the certificate * issuer. */ Asn1Object issuer = null; try { issuer = new Asn1InputStream(cert.IssuerDN.GetEncoded()).ReadObject(); } catch (Exception e) { throw new Exception("Issuer from certificate for CRL could not be reencoded.", e); } DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames( new GeneralName(GeneralName.DirectoryName, issuer))), null, null); PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone(); CheckCrl(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (Exception e) { lastException = e; } } if (!validCrlFound) { throw lastException; } if (certStatus.Status != CertStatus.Unrevoked) { // TODO This format is forced by the NistCertPath tests string formattedDate = certStatus.RevocationDate.Value.ToString( "G", System.util.Util.GetStandartEnUSLocale()); string message = "Certificate revocation after " + formattedDate; message += ", reason: " + CrlReasons[certStatus.Status]; throw new Exception(message); } if (!reasonsMask.IsAllReasons && certStatus.Status == CertStatus.Unrevoked) { certStatus.Status = CertStatus.Undetermined; } if (certStatus.Status == CertStatus.Undetermined) { throw new Exception("Certificate status could not be determined."); } }
/** * Checks if an attribute certificate is revoked. * * @param attrCert Attribute certificate to check if it is revoked. * @param paramsPKIX PKIX parameters. * @param issuerCert The issuer certificate of the attribute certificate * <code>attrCert</code>. * @param validDate The date when the certificate revocation status should * be checked. * @param certPathCerts The certificates of the certification path to be * checked. * * @throws CertPathValidatorException if the certificate is revoked or the * status cannot be checked or some error occurs. */ internal static void CheckCrls( IX509AttributeCertificate attrCert, PkixParameters paramsPKIX, X509Certificate issuerCert, DateTime validDate, IList certPathCerts) { if (paramsPKIX.IsRevocationEnabled) { // check if revocation is available if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) == null) { CrlDistPoint crldp = null; try { crldp = CrlDistPoint.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue( attrCert, X509Extensions.CrlDistributionPoints)); } catch (Exception e) { throw new PkixCertPathValidatorException( "CRL distribution point extension could not be read.", e); } try { PkixCertPathValidatorUtilities .AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX); } catch (Exception e) { throw new PkixCertPathValidatorException( "No additional CRL locations could be decoded from CRL distribution point extension.", e); } CertStatus certStatus = new CertStatus(); ReasonsMask reasonsMask = new ReasonsMask(); Exception lastException = null; bool validCrlFound = false; // for each distribution point if (crldp != null) { DistributionPoint[] dps = null; try { dps = crldp.GetDistributionPoints(); } catch (Exception e) { throw new PkixCertPathValidatorException( "Distribution points could not be read.", e); } try { for (int i = 0; i < dps.Length && certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons; i++) { PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX .Clone(); CheckCrl(dps[i], attrCert, paramsPKIXClone, validDate, issuerCert, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } } catch (Exception e) { lastException = new Exception( "No valid CRL for distribution point found.", e); } } /* * If the revocation status has not been determined, repeat the * process above with any available CRLs not specified in a * distribution point but issued by the certificate issuer. */ if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons) { try { /* * assume a DP with both the reasons and the cRLIssuer * fields omitted and a distribution point name of the * certificate issuer. */ Asn1Object issuer = null; try { issuer = new Asn1InputStream( attrCert.Issuer.GetPrincipals()[0].GetEncoded()).ReadObject(); } catch (Exception e) { throw new Exception( "Issuer from certificate for CRL could not be reencoded.", e); } DistributionPoint dp = new DistributionPoint( new DistributionPointName(0, new GeneralNames( new GeneralName(GeneralName.DirectoryName, issuer))), null, null); PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX.Clone(); CheckCrl(dp, attrCert, paramsPKIXClone, validDate, issuerCert, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (Exception e) { lastException = new Exception( "No valid CRL for distribution point found.", e); } } if (!validCrlFound) { throw new PkixCertPathValidatorException( "No valid CRL found.", lastException); } if (certStatus.Status != CertStatus.Unrevoked) { // TODO This format is forced by the NistCertPath tests string formattedDate = certStatus.RevocationDate.Value.ToString( "G", new CultureInfo("en-us")); string message = "Attribute certificate revocation after " + formattedDate; message += ", reason: " + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status]; throw new PkixCertPathValidatorException(message); } if (!reasonsMask.IsAllReasons && certStatus.Status == CertStatus.Unrevoked) { certStatus.Status = CertStatus.Undetermined; } if (certStatus.Status == CertStatus.Undetermined) { throw new PkixCertPathValidatorException( "Attribute certificate status could not be determined."); } } else { if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null || attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null) { throw new PkixCertPathValidatorException( "No rev avail extension is set, but also an AC revocation pointer."); } } } }
/** * * Checks a distribution point for revocation information for the * certificate <code>attrCert</code>. * * @param dp The distribution point to consider. * @param attrCert The attribute certificate which should be checked. * @param paramsPKIX PKIX parameters. * @param validDate The date when the certificate revocation status should * be checked. * @param issuerCert Certificate to check if it is revoked. * @param reasonMask The reasons mask which is already checked. * @param certPathCerts The certificates of the certification path to be * checked. * @throws Exception if the certificate is revoked or the status * cannot be checked or some error occurs. */ private static void CheckCrl( DistributionPoint dp, IX509AttributeCertificate attrCert, PkixParameters paramsPKIX, DateTime validDate, X509Certificate issuerCert, CertStatus certStatus, ReasonsMask reasonMask, IList certPathCerts) { /* * 4.3.6 No Revocation Available * * The noRevAvail extension, defined in [X.509-2000], allows an AC * issuer to indicate that no revocation information will be made * available for this AC. */ if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null) { return; } DateTime currentDate = DateTime.UtcNow; if (validDate.CompareTo(currentDate) > 0) { throw new Exception("Validation time is in future."); } // (a) /* * We always get timely valid CRLs, so there is no step (a) (1). * "locally cached" CRLs are assumed to be in getStore(), additional * CRLs must be enabled in the ExtendedPkixParameters and are in * getAdditionalStore() */ ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert, currentDate, paramsPKIX); bool validCrlFound = false; Exception lastException = null; IEnumerator crl_iter = crls.GetEnumerator(); while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons) { try { X509Crl crl = (X509Crl) crl_iter.Current; // (d) ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp); // (e) /* * The reasons mask is updated at the end, so only valid CRLs * can update it. If this CRL does not contain new reasons it * must be ignored. */ if (!interimReasonsMask.HasNewReasons(reasonMask)) { continue; } // (f) ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert, null, null, paramsPKIX, certPathCerts); // (g) AsymmetricKeyParameter pubKey = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys); X509Crl deltaCRL = null; if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRLs ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls( currentDate, paramsPKIX, crl); // we only want one valid delta CRL // (h) deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, pubKey); } /* * CRL must be be valid at the current time, not the validation * time. If a certificate is revoked with reason keyCompromise, * cACompromise, it can be used for forgery, also for the past. * This reason may not be contained in older CRLs. */ /* * in the chain model signatures stay valid also after the * certificate has been expired, so they do not have to be in * the CRL vality time */ if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel) { /* * if a certificate has expired, but was revoked, it is not * more in the CRL, so it would be regarded as valid if the * first check is not done */ if (attrCert.NotAfter.CompareTo(crl.ThisUpdate) < 0) { throw new Exception( "No valid CRL for current time found."); } } Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, crl); // (b) (2) Rfc3280CertPathUtilities.ProcessCrlB2(dp, attrCert, crl); // (c) Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX); // (i) Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL, attrCert, certStatus, paramsPKIX); // (j) Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, attrCert, certStatus); // (k) if (certStatus.Status == CrlReason.RemoveFromCrl) { certStatus.Status = CertStatus.Unrevoked; } // update reasons mask reasonMask.AddReasons(interimReasonsMask); validCrlFound = true; } catch (Exception e) { lastException = e; } } if (!validCrlFound) { throw lastException; } }
/** * Fetches complete CRLs according to RFC 3280. * * @param dp The distribution point for which the complete CRL * @param cert The <code>X509Certificate</code> or * {@link org.bouncycastle.x509.X509AttributeCertificate} for * which the CRL should be searched. * @param currentDate The date for which the delta CRLs must be valid. * @param paramsPKIX The extended PKIX parameters. * @return A <code>Set</code> of <code>X509CRL</code>s with complete * CRLs. * @throws Exception if an exception occurs while picking the CRLs * or no CRLs are found. */ internal static ISet GetCompleteCrls( DistributionPoint dp, object cert, DateTime currentDate, PkixParameters paramsPKIX) { X509CrlStoreSelector crlselect = new X509CrlStoreSelector(); try { ISet issuers = new HashSet(); if (cert is X509V2AttributeCertificate) { issuers.Add(((X509V2AttributeCertificate)cert) .Issuer.GetPrincipals()[0]); } else { issuers.Add(GetIssuerPrincipal(cert)); } PkixCertPathValidatorUtilities.GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX); } catch (Exception e) { throw new Exception("Could not get issuer information from distribution point.", e); } if (cert is X509Certificate) { crlselect.CertificateChecking = (X509Certificate)cert; } else if (cert is X509V2AttributeCertificate) { crlselect.AttrCertChecking = (IX509AttributeCertificate)cert; } crlselect.CompleteCrlEnabled = true; ISet crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate); if (crls.IsEmpty) { if (cert is IX509AttributeCertificate) { IX509AttributeCertificate aCert = (IX509AttributeCertificate)cert; throw new Exception("No CRLs found for issuer \"" + aCert.Issuer.GetPrincipals()[0] + "\""); } else { X509Certificate xCert = (X509Certificate)cert; throw new Exception("No CRLs found for issuer \"" + xCert.IssuerDN + "\""); } } return crls; }
// Only the ctor should be calling with isAuthority = true // if isAuthority, value for isMachineCert doesn't matter private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings) { if (certificateCreationSettings == null) { if (isAuthority) { certificateCreationSettings = new CertificateCreationSettings(); } else { throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false"); } } // Set to default cert creation settings if not set if (certificateCreationSettings.ValidityNotBefore == default(DateTime)) { certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore; } if (certificateCreationSettings.ValidityNotAfter == default(DateTime)) { certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter; } string[] subjects = certificateCreationSettings.Subjects; if (!isAuthority ^ (signingCertificate != null)) { throw new ArgumentException("Either isAuthority == true or signingCertificate is not null"); } if (!isAuthority && (subjects == null || subjects.Length == 0)) { throw new ArgumentException("If not creating an authority, must specify at least one Subject", "subjects"); } if (!isAuthority && string.IsNullOrWhiteSpace(subjects[0])) { throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subjects"); } EnsureInitialized(); _certGenerator.Reset(); _certGenerator.SetSignatureAlgorithm(_signatureAlthorithm); X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName); var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair(); if (isAuthority) { _certGenerator.SetIssuerDN(authorityX509Name); _certGenerator.SetSubjectDN(authorityX509Name); var authorityKeyIdentifier = new AuthorityKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public), new GeneralNames(new GeneralName(authorityX509Name)), new BigInteger(7, _random).Abs()); _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, authorityKeyIdentifier); _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign)); } else { X509Name subjectName = CreateX509Name(subjects[0]); _certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate)); _certGenerator.SetSubjectDN(subjectName); _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public)); _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment)); } _certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public)); _certGenerator.SetSerialNumber(new BigInteger(64 /*sizeInBits*/, _random).Abs()); _certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore); _certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter); _certGenerator.SetPublicKey(keyPair.Public); _certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority)); _certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth)); if (!isAuthority) { if (isMachineCert) { List<Asn1Encodable> subjectAlternativeNames = new List<Asn1Encodable>(); // All endpoints should also be in the Subject Alt Names for (int i = 0; i < subjects.Length; i++) { if (!string.IsNullOrWhiteSpace(subjects[i])) { // Machine certs can have additional DNS names subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subjects[i])); } } _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames.ToArray())); } else { if (subjects.Length > 1) { var subjectAlternativeNames = new Asn1EncodableVector(); // Only add a SAN for the user if there are any for (int i = 1; i < subjects.Length; i++) { if (!string.IsNullOrWhiteSpace(subjects[i])) { Asn1EncodableVector otherNames = new Asn1EncodableVector(); otherNames.Add(new DerObjectIdentifier(_upnObjectId)); otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjects[i]))); Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames)); subjectAlternativeNames.Add(genName); } } _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames)); } } } var crlDistributionPoints = new DistributionPoint[1] { new DistributionPoint(new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, _crlUri))), null, new GeneralNames(new GeneralName(authorityX509Name))) }; var revocationListExtension = new CrlDistPoint(crlDistributionPoints); _certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension); X509Certificate cert = _certGenerator.Generate(_authorityKeyPair.Private, _random); if (certificateCreationSettings.IsValidCert) { EnsureCertificateValidity(cert); } // For now, given that we don't know what format to return it in, preserve the formats so we have // the flexibility to do what we need to X509CertificateContainer container = new X509CertificateContainer(); X509CertificateEntry[] chain = new X509CertificateEntry[1]; chain[0] = new X509CertificateEntry(cert); Pkcs12Store store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry("", new AsymmetricKeyEntry(keyPair.Private), chain); using (MemoryStream stream = new MemoryStream()) { store.Save(stream, _password.ToCharArray(), _random); container.Pfx = stream.ToArray(); } X509Certificate2 outputCert; if (isAuthority) { // don't hand out the private key for the cert when it's the authority outputCert = new X509Certificate2(cert.GetEncoded()); } else { // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key // you will have to re-export this cert if needed outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); } container.Subject = subjects[0]; container.InternalCertificate = cert; container.Certificate = outputCert; container.Thumbprint = outputCert.Thumbprint; Trace.WriteLine("[CertificateGenerator] generated a certificate:"); Trace.WriteLine(string.Format(" {0} = {1}", "isAuthority", isAuthority)); if (!isAuthority) { Trace.WriteLine(string.Format(" {0} = {1}", "Signed by", signingCertificate.SubjectDN)); Trace.WriteLine(string.Format(" {0} = {1}", "Subject (CN) ", subjects[0])); Trace.WriteLine(string.Format(" {0} = {1}", "Alt names ", string.Join(", ", subjects))); } Trace.WriteLine(string.Format(" {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey)); Trace.WriteLine(string.Format(" {0} = {1}", "Thumbprint", outputCert.Thumbprint)); return container; }
public CrlDistPoint( DistributionPoint[] points) { seq = new DerSequence(points); }
public static DistributionPoint GetInstance(Asn1TaggedObject obj, bool explicitly) { return(DistributionPoint.GetInstance(Asn1Sequence.GetInstance(obj, explicitly))); }
internal static ReasonsMask ProcessCrlD( X509Crl crl, DistributionPoint dp) //throws AnnotatedException { IssuingDistributionPoint idp = null; try { idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint)); } catch (Exception e) { throw new Exception("issuing distribution point extension could not be decoded.", e); } // (d) (1) if (idp != null && idp.OnlySomeReasons != null && dp.Reasons != null) { return new ReasonsMask(dp.Reasons.IntValue).Intersect(new ReasonsMask(idp.OnlySomeReasons .IntValue)); } // (d) (4) if ((idp == null || idp.OnlySomeReasons == null) && dp.Reasons == null) { return ReasonsMask.AllReasons; } // (d) (2) and (d)(3) ReasonsMask dpReasons = null; if (dp.Reasons == null) { dpReasons = ReasonsMask.AllReasons; } else { dpReasons = new ReasonsMask(dp.Reasons.IntValue); } ReasonsMask idpReasons = null; if (idp == null) { idpReasons = ReasonsMask.AllReasons; } else { idpReasons = new ReasonsMask(idp.OnlySomeReasons.IntValue); } return dpReasons.Intersect(idpReasons); }
/** * Add the CRL issuers from the cRLIssuer field of the distribution point or * from the certificate if not given to the issuer criterion of the * <code>selector</code>. * <p> * The <code>issuerPrincipals</code> are a collection with a single * <code>X500Principal</code> for <code>X509Certificate</code>s. For * {@link X509AttributeCertificate}s the issuer may contain more than one * <code>X500Principal</code>. * </p> * * @param dp The distribution point. * @param issuerPrincipals The issuers of the certificate or attribute * certificate which contains the distribution point. * @param selector The CRL selector. * @param pkixParams The PKIX parameters containing the cert stores. * @throws Exception if an exception occurs while processing. * @throws ClassCastException if <code>issuerPrincipals</code> does not * contain only <code>X500Principal</code>s. */ internal static void GetCrlIssuersFromDistributionPoint( DistributionPoint dp, ICollection issuerPrincipals, X509CrlStoreSelector selector, PkixParameters pkixParams) { IList issuers = Platform.CreateArrayList(); // indirect CRL if (dp.CrlIssuer != null) { GeneralName[] genNames = dp.CrlIssuer.GetNames(); // look for a DN for (int j = 0; j < genNames.Length; j++) { if (genNames[j].TagNo == GeneralName.DirectoryName) { try { issuers.Add(X509Name.GetInstance(genNames[j].Name.ToAsn1Object())); } catch (IOException e) { throw new Exception( "CRL issuer information from distribution point cannot be decoded.", e); } } } } else { /* * certificate issuer is CRL issuer, distributionPoint field MUST be * present. */ if (dp.DistributionPointName == null) { throw new Exception( "CRL issuer is omitted from distribution point but no distributionPoint field present."); } // add and check issuer principals for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext(); ) { issuers.Add((X509Name)it.Current); } } // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid // distributionPoint // if (dp.getDistributionPoint() != null) // { // // look for nameRelativeToCRLIssuer // if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) // { // // append fragment to issuer, only one // // issuer can be there, if this is given // if (issuers.size() != 1) // { // throw new AnnotatedException( // "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given."); // } // DEREncodable relName = dp.getDistributionPoint().getName(); // Iterator it = issuers.iterator(); // List issuersTemp = new ArrayList(issuers.size()); // while (it.hasNext()) // { // Enumeration e = null; // try // { // e = ASN1Sequence.getInstance( // new ASN1InputStream(((X500Principal) it.next()) // .getEncoded()).readObject()).getObjects(); // } // catch (IOException ex) // { // throw new AnnotatedException( // "Cannot decode CRL issuer information.", ex); // } // ASN1EncodableVector v = new ASN1EncodableVector(); // while (e.hasMoreElements()) // { // v.add((DEREncodable) e.nextElement()); // } // v.add(relName); // issuersTemp.add(new X500Principal(new DERSequence(v) // .getDEREncoded())); // } // issuers.clear(); // issuers.addAll(issuersTemp); // } // } selector.Issuers = issuers; }
/** * Checks a distribution point for revocation information for the * certificate <code>cert</code>. * * @param dp The distribution point to consider. * @param paramsPKIX PKIX parameters. * @param cert Certificate to check if it is revoked. * @param validDate The date when the certificate revocation status should be * checked. * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>. * @param defaultCRLSignKey The public key of the issuer certificate * <code>defaultCRLSignCert</code>. * @param certStatus The current certificate revocation status. * @param reasonMask The reasons mask which is already checked. * @param certPathCerts The certificates of the certification path. * @throws AnnotatedException if the certificate is revoked or the status cannot be checked * or some error occurs. */ private static void CheckCrl( DistributionPoint dp, PkixParameters paramsPKIX, X509Certificate cert, DateTime validDate, X509Certificate defaultCRLSignCert, AsymmetricKeyParameter defaultCRLSignKey, CertStatus certStatus, ReasonsMask reasonMask, IList certPathCerts) //throws AnnotatedException { DateTime currentDate = DateTime.UtcNow; if (validDate.Ticks > currentDate.Ticks) { throw new Exception("Validation time is in future."); } // (a) /* * We always get timely valid CRLs, so there is no step (a) (1). * "locally cached" CRLs are assumed to be in getStore(), additional * CRLs must be enabled in the ExtendedPKIXParameters and are in * getAdditionalStore() */ ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, cert, currentDate, paramsPKIX); bool validCrlFound = false; Exception lastException = null; IEnumerator crl_iter = crls.GetEnumerator(); while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons) { try { X509Crl crl = (X509Crl)crl_iter.Current; // (d) ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp); // (e) /* * The reasons mask is updated at the end, so only valid CRLs * can update it. If this CRL does not contain new reasons it * must be ignored. */ if (!interimReasonsMask.HasNewReasons(reasonMask)) { continue; } // (f) ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, paramsPKIX, certPathCerts); // (g) AsymmetricKeyParameter key = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys); X509Crl deltaCRL = null; if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRLs ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl); // we only want one valid delta CRL // (h) deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, key); } /* * CRL must be be valid at the current time, not the validation * time. If a certificate is revoked with reason keyCompromise, * cACompromise, it can be used for forgery, also for the past. * This reason may not be contained in older CRLs. */ /* * in the chain model signatures stay valid also after the * certificate has been expired, so they do not have to be in * the CRL validity time */ if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel) { /* * if a certificate has expired, but was revoked, it is not * more in the CRL, so it would be regarded as valid if the * first check is not done */ if (cert.NotAfter.Ticks < crl.ThisUpdate.Ticks) { throw new Exception("No valid CRL for current time found."); } } Rfc3280CertPathUtilities.ProcessCrlB1(dp, cert, crl); // (b) (2) Rfc3280CertPathUtilities.ProcessCrlB2(dp, cert, crl); // (c) Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX); // (i) Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL, cert, certStatus, paramsPKIX); // (j) Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, cert, certStatus); // (k) if (certStatus.Status == CrlReason.RemoveFromCrl) { certStatus.Status = CertStatus.Unrevoked; } // update reasons mask reasonMask.AddReasons(interimReasonsMask); ISet criticalExtensions = crl.GetCriticalExtensionOids(); if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); if (!criticalExtensions.IsEmpty) throw new Exception("CRL contains unsupported critical extensions."); } if (deltaCRL != null) { criticalExtensions = deltaCRL.GetCriticalExtensionOids(); if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); if (!criticalExtensions.IsEmpty) throw new Exception("Delta CRL contains unsupported critical extension."); } } validCrlFound = true; } catch (Exception e) { lastException = e; } } if (!validCrlFound) { throw lastException; } }
/** * Fetches complete CRLs according to RFC 3280. * * @param dp The distribution point for which the complete CRL * @param cert The <code>X509Certificate</code> or * {@link org.bouncycastle.x509.X509AttributeCertificate} for * which the CRL should be searched. * @param currentDate The date for which the delta CRLs must be valid. * @param paramsPKIX The extended PKIX parameters. * @return A <code>Set</code> of <code>X509CRL</code>s with complete * CRLs. * @throws Exception if an exception occurs while picking the CRLs * or no CRLs are found. */ internal static ISet GetCompleteCrls( DistributionPoint dp, object cert, DateTime currentDate, PkixParameters paramsPKIX) { X509CrlStoreSelector crlselect = new X509CrlStoreSelector(); try { ISet issuers = new HashSet(); if (cert is X509V2AttributeCertificate) { issuers.Add(((X509V2AttributeCertificate)cert) .Issuer.GetPrincipals()[0]); } else { issuers.Add(GetIssuerPrincipal(cert)); } PkixCertPathValidatorUtilities.GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX); } catch (Exception e) { new Exception("Could not get issuer information from distribution point.", e); } if (cert is X509Certificate) { crlselect.CertificateChecking = (X509Certificate)cert; } else if (cert is X509V2AttributeCertificate) { crlselect.AttrCertChecking = (IX509AttributeCertificate)cert; } if (paramsPKIX.Date != null) { crlselect.DateAndTime = paramsPKIX.Date; } else { crlselect.DateAndTime = new DateTimeObject(currentDate); } crlselect.CompleteCrlEnabled = true; ISet crls = new HashSet(); try { crls.AddAll(PkixCertPathValidatorUtilities.FindCrls(crlselect, paramsPKIX.GetStores())); crls.AddAll(PkixCertPathValidatorUtilities.FindCrls(crlselect, paramsPKIX.GetAdditionalStores())); } catch (Exception e) { throw new Exception("Could not search for CRLs.", e); } if (crls.IsEmpty) throw new Exception("No CRLs found."); return crls; }