private X509AttrCertStoreSelector(
			X509AttrCertStoreSelector o)
        {
            this.attributeCert = o.attributeCert;
            this.attributeCertificateValid = o.attributeCertificateValid;
            this.holder = o.holder;
            this.issuer = o.issuer;
            this.serialNumber = o.serialNumber;
        }
		private X509AttrCertStoreSelector(
			X509AttrCertStoreSelector o)
		{
			this.attributeCert = o.attributeCert;
			this.attributeCertificateValid = o.attributeCertificateValid;
			this.holder = o.holder;
			this.issuer = o.issuer;
			this.serialNumber = o.serialNumber;
			this.targetGroups = new HashSet(o.targetGroups);
			this.targetNames = new HashSet(o.targetNames);
		}
		public X509CrlStoreSelector(
			X509CrlStoreSelector o)
		{
			this.certificateChecking = o.CertificateChecking;
			this.dateAndTime = o.DateAndTime;
			this.issuers = o.Issuers;
			this.maxCrlNumber = o.MaxCrlNumber;
			this.minCrlNumber = o.MinCrlNumber;

			this.deltaCrlIndicatorEnabled = o.DeltaCrlIndicatorEnabled;
			this.completeCrlEnabled = o.CompleteCrlEnabled;
			this.maxBaseCrlNumber = o.MaxBaseCrlNumber;
			this.attrCertChecking = o.AttrCertChecking;
			this.issuingDistributionPointEnabled = o.IssuingDistributionPointEnabled;
			this.issuingDistributionPoint = o.IssuingDistributionPoint;
		}
		internal static void ProcessAttrCert7(
			IX509AttributeCertificate	attrCert,
			PkixCertPath				certPath,
			PkixCertPath				holderCertPath,
			PkixParameters				pkixParams)
		{
			// TODO:
			// AA Controls
			// Attribute encryption
			// Proxy
			ISet critExtOids = attrCert.GetCriticalExtensionOids();

			// 7.1
			// process extensions

			// target information checked in step 6 / X509AttributeCertStoreSelector
			if (critExtOids.Contains(X509Extensions.TargetInformation.Id))
			{
				try
				{
					TargetInformation.GetInstance(PkixCertPathValidatorUtilities
						.GetExtensionValue(attrCert, X509Extensions.TargetInformation));
				}
				catch (Exception e)
				{
					throw new PkixCertPathValidatorException(
						"Target information extension could not be read.", e);
				}
			}
			critExtOids.Remove(X509Extensions.TargetInformation.Id);
			foreach (PkixAttrCertChecker checker in pkixParams.GetAttrCertCheckers())
			{
				checker.Check(attrCert, certPath, holderCertPath, critExtOids);
			}
			if (!critExtOids.IsEmpty)
			{
				throw new PkixCertPathValidatorException(
					"Attribute certificate contains unsupported critical extensions: "
						+ critExtOids);
			}
		}
        internal static void ProcessAttrCert7(IX509AttributeCertificate attrCert, PkixCertPath certPath, PkixCertPath holderCertPath, PkixParameters pkixParams)
        {
            ISet criticalExtensionOids = attrCert.GetCriticalExtensionOids();

            if (criticalExtensionOids.Contains(X509Extensions.TargetInformation.Id))
            {
                try
                {
                    TargetInformation.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(attrCert, X509Extensions.TargetInformation));
                }
                catch (global::System.Exception cause)
                {
                    throw new PkixCertPathValidatorException("Target information extension could not be read.", cause);
                }
            }
            criticalExtensionOids.Remove(X509Extensions.TargetInformation.Id);
            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)pkixParams.GetAttrCertCheckers()).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    PkixAttrCertChecker pkixAttrCertChecker = (PkixAttrCertChecker)enumerator.get_Current();
                    pkixAttrCertChecker.Check(attrCert, certPath, holderCertPath, criticalExtensionOids);
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            if (!criticalExtensionOids.IsEmpty)
            {
                throw new PkixCertPathValidatorException(string.Concat((object)"Attribute certificate contains unsupported critical extensions: ", (object)criticalExtensionOids));
            }
        }
        /**
         * Validates an attribute certificate with the given certificate path.
         *
         * <p>
         * <code>params</code> must be an instance of
         * <code>ExtendedPkixParameters</code>.
         * </p><p>
         * The target constraints in the <code>params</code> must be an
         * <code>X509AttrCertStoreSelector</code> with at least the attribute
         * certificate criterion set. Obey that also target informations may be
         * necessary to correctly validate this attribute certificate.
         * </p><p>
         * The attribute certificate issuer must be added to the trusted attribute
         * issuers with {@link ExtendedPkixParameters#setTrustedACIssuers(Set)}.
         * </p>
         * @param certPath The certificate path which belongs to the attribute
         *            certificate issuer public key certificate.
         * @param params The PKIX parameters.
         * @return A <code>PKIXCertPathValidatorResult</code> of the result of
         *         validating the <code>certPath</code>.
         * @throws InvalidAlgorithmParameterException if <code>params</code> is
         *             inappropriate for this validator.
         * @throws CertPathValidatorException if the verification fails.
         */
        public virtual PkixCertPathValidatorResult Validate(
            PkixCertPath certPath,
            PkixParameters pkixParams)
        {
            IX509Selector certSelect = pkixParams.GetTargetConstraints();

            if (!(certSelect is X509AttrCertStoreSelector))
            {
                throw new ArgumentException(
                          "TargetConstraints must be an instance of " + typeof(X509AttrCertStoreSelector).FullName,
                          "pkixParams");
            }
            IX509AttributeCertificate attrCert = ((X509AttrCertStoreSelector)certSelect).AttributeCert;

            PkixCertPath holderCertPath            = Rfc3281CertPathUtilities.ProcessAttrCert1(attrCert, pkixParams);
            PkixCertPathValidatorResult result     = Rfc3281CertPathUtilities.ProcessAttrCert2(certPath, pkixParams);
            X509Certificate             issuerCert = (X509Certificate)certPath.Certificates[0];

            Rfc3281CertPathUtilities.ProcessAttrCert3(issuerCert, pkixParams);
            Rfc3281CertPathUtilities.ProcessAttrCert4(issuerCert, pkixParams);
            Rfc3281CertPathUtilities.ProcessAttrCert5(attrCert, pkixParams);
            // 6 already done in X509AttrCertStoreSelector
            Rfc3281CertPathUtilities.ProcessAttrCert7(attrCert, certPath, holderCertPath, pkixParams);
            Rfc3281CertPathUtilities.AdditionalChecks(attrCert, pkixParams);
            DateTime date;

            try
            {
                date = PkixCertPathValidatorUtilities.GetValidCertDateFromValidityModel(pkixParams, null, -1);
            }
            catch (Exception e)
            {
                throw new PkixCertPathValidatorException(
                          "Could not get validity date from attribute certificate.", e);
            }
            Rfc3281CertPathUtilities.CheckCrls(attrCert, pkixParams, issuerCert, date, certPath.Certificates);
            return(result);
        }
Exemple #7
0
        public void TestWithAttributeCertificate()
        {
            IX509Store x509Certs = CmsTestUtil.MakeCertStore(SignCert);

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);
            gen.AddCertificates(x509Certs);

            IX509AttributeCertificate attrCert = CmsTestUtil.GetAttributeCertificate();

            IX509Store store = CmsTestUtil.MakeAttrCertStore(attrCert);

            gen.AddAttributeCertificates(store);

            MemoryStream bOut = new MemoryStream();

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);

            Stream sigOut = gen.Open(bOut, true);

            sigOut.Write(testBytes, 0, testBytes.Length);
            sigOut.Close();

            CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());

            sp.GetSignedContent().Drain();

            Assert.AreEqual(4, sp.Version);

            store = sp.GetAttributeCertificates("Collection");

            ArrayList coll = new ArrayList(store.GetMatches(null));

            Assert.AreEqual(1, coll.Count);

            Assert.IsTrue(coll.Contains(attrCert));
        }
        internal static void AdditionalChecks(
			IX509AttributeCertificate	attrCert,
			PkixParameters				pkixParams)
        {
            // 1
            foreach (string oid in pkixParams.GetProhibitedACAttributes())
            {
                if (attrCert.GetAttributes(oid) != null)
                {
                    throw new PkixCertPathValidatorException(
                        "Attribute certificate contains prohibited attribute: "
                            + oid + ".");
                }
            }
            foreach (string oid in pkixParams.GetNecessaryACAttributes())
            {
                if (attrCert.GetAttributes(oid) == null)
                {
                    throw new PkixCertPathValidatorException(
                        "Attribute certificate does not contain necessary attribute: "
                            + oid + ".");
                }
            }
        }
		/**
		* 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.");
					}
				}
			}
		}
		/**
		* Searches for a holder public key certificate and verifies its
		* certification path.
		* 
		* @param attrCert the attribute certificate.
		* @param pkixParams The PKIX parameters.
		* @return The certificate path of the holder certificate.
		* @throws Exception if
		*             <ul>
		*             <li>no public key certificate can be found although holder
		*             information is given by an entity name or a base certificate
		*             ID</li>
		*             <li>support classes cannot be created</li>
		*             <li>no certification path for the public key certificate can
		*             be built</li>
		*             </ul>
		*/
		internal static PkixCertPath ProcessAttrCert1(
			IX509AttributeCertificate	attrCert,
			PkixParameters				pkixParams)
		{
			PkixCertPathBuilderResult result = null;
			// find holder PKCs
			ISet holderPKCs = new HashSet();
			if (attrCert.Holder.GetIssuer() != null)
			{
				X509CertStoreSelector selector = new X509CertStoreSelector();
				selector.SerialNumber = attrCert.Holder.SerialNumber;
				X509Name[] principals = attrCert.Holder.GetIssuer();
				for (int i = 0; i < principals.Length; i++)
				{
					try
					{
//						if (principals[i] is X500Principal)
						{
							selector.Issuer = principals[i];
						}
						holderPKCs.AddAll(PkixCertPathValidatorUtilities
							.FindCertificates(selector, pkixParams.GetStores()));
					}
					catch (Exception e)
					{
						throw new PkixCertPathValidatorException(
							"Public key certificate for attribute certificate cannot be searched.",
							e);
					}
				}
				if (holderPKCs.IsEmpty)
				{
					throw new PkixCertPathValidatorException(
						"Public key certificate specified in base certificate ID for attribute certificate cannot be found.");
				}
			}
			if (attrCert.Holder.GetEntityNames() != null)
			{
				X509CertStoreSelector selector = new X509CertStoreSelector();
				X509Name[] principals = attrCert.Holder.GetEntityNames();
				for (int i = 0; i < principals.Length; i++)
				{
					try
					{
//						if (principals[i] is X500Principal)
						{
							selector.Issuer = principals[i];
						}
						holderPKCs.AddAll(PkixCertPathValidatorUtilities
							.FindCertificates(selector, pkixParams.GetStores()));
					}
					catch (Exception e)
					{
						throw new PkixCertPathValidatorException(
							"Public key certificate for attribute certificate cannot be searched.",
							e);
					}
				}
				if (holderPKCs.IsEmpty)
				{
					throw new PkixCertPathValidatorException(
						"Public key certificate specified in entity name for attribute certificate cannot be found.");
				}
			}

			// verify cert paths for PKCs
			PkixBuilderParameters parameters = (PkixBuilderParameters)
				PkixBuilderParameters.GetInstance(pkixParams);

			PkixCertPathValidatorException lastException = null;
			foreach (X509Certificate cert in holderPKCs)
			{
				X509CertStoreSelector selector = new X509CertStoreSelector();
				selector.Certificate = cert;
				parameters.SetTargetConstraints(selector);

				PkixCertPathBuilder builder = new PkixCertPathBuilder();

				try
				{
					result = builder.Build(PkixBuilderParameters.GetInstance(parameters));
				}
				catch (PkixCertPathBuilderException e)
				{
					lastException = new PkixCertPathValidatorException(
						"Certification path for public key certificate of attribute certificate could not be build.",
						e);
				}
			}
			if (lastException != null)
			{
				throw lastException;
			}
			return result.CertPath;
		}
		/**
		* 
		* 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;
			}
		}
        internal static PkixCertPath ProcessAttrCert1(IX509AttributeCertificate attrCert, PkixParameters pkixParams)
        {
            PkixCertPathBuilderResult pkixCertPathBuilderResult = null;
            ISet set = new HashSet();

            if (attrCert.Holder.GetIssuer() != null)
            {
                X509CertStoreSelector x509CertStoreSelector = new X509CertStoreSelector();
                x509CertStoreSelector.SerialNumber = attrCert.Holder.SerialNumber;
                X509Name[] issuer = attrCert.Holder.GetIssuer();
                for (int i = 0; i < issuer.Length; i++)
                {
                    try
                    {
                        x509CertStoreSelector.Issuer = issuer[i];
                        set.AddAll((global::System.Collections.IEnumerable)PkixCertPathValidatorUtilities.FindCertificates(x509CertStoreSelector, pkixParams.GetStores()));
                    }
                    catch (global::System.Exception cause)
                    {
                        throw new PkixCertPathValidatorException("Public key certificate for attribute certificate cannot be searched.", cause);
                    }
                }
                if (set.IsEmpty)
                {
                    throw new PkixCertPathValidatorException("Public key certificate specified in base certificate ID for attribute certificate cannot be found.");
                }
            }
            if (attrCert.Holder.GetEntityNames() != null)
            {
                X509CertStoreSelector x509CertStoreSelector2 = new X509CertStoreSelector();
                X509Name[]            entityNames            = attrCert.Holder.GetEntityNames();
                for (int j = 0; j < entityNames.Length; j++)
                {
                    try
                    {
                        x509CertStoreSelector2.Issuer = entityNames[j];
                        set.AddAll((global::System.Collections.IEnumerable)PkixCertPathValidatorUtilities.FindCertificates(x509CertStoreSelector2, pkixParams.GetStores()));
                    }
                    catch (global::System.Exception cause2)
                    {
                        throw new PkixCertPathValidatorException("Public key certificate for attribute certificate cannot be searched.", cause2);
                    }
                }
                if (set.IsEmpty)
                {
                    throw new PkixCertPathValidatorException("Public key certificate specified in entity name for attribute certificate cannot be found.");
                }
            }
            PkixBuilderParameters          instance = PkixBuilderParameters.GetInstance(pkixParams);
            PkixCertPathValidatorException ex       = null;

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)set).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    X509Certificate       certificate            = (X509Certificate)enumerator.get_Current();
                    X509CertStoreSelector x509CertStoreSelector3 = new X509CertStoreSelector();
                    x509CertStoreSelector3.Certificate = certificate;
                    instance.SetTargetConstraints(x509CertStoreSelector3);
                    PkixCertPathBuilder pkixCertPathBuilder = new PkixCertPathBuilder();
                    try
                    {
                        pkixCertPathBuilderResult = pkixCertPathBuilder.Build(PkixBuilderParameters.GetInstance(instance));
                    }
                    catch (PkixCertPathBuilderException cause3)
                    {
                        ex = new PkixCertPathValidatorException("Certification path for public key certificate of attribute certificate could not be build.", cause3);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            if (ex != null)
            {
                throw ex;
            }
            return(pkixCertPathBuilderResult.CertPath);
        }
		internal static void ProcessAttrCert5(
			IX509AttributeCertificate	attrCert,
			PkixParameters				pkixParams)
		{
			try
			{
				attrCert.CheckValidity(PkixCertPathValidatorUtilities.GetValidDate(pkixParams));
			}
			catch (CertificateExpiredException e)
			{
				throw new PkixCertPathValidatorException(
					"Attribute certificate is not valid.", e);
			}
			catch (CertificateNotYetValidException e)
			{
				throw new PkixCertPathValidatorException(
					"Attribute certificate is not valid.", e);
			}
		}
		/**
		* Performs checks on the specified attribute certificate. Every handled
		* extension is rmeoved from the <code>unresolvedCritExts</code>
		* collection.
		* 
		* @param attrCert The attribute certificate to be checked.
		* @param certPath The certificate path which belongs to the attribute
		*            certificate issuer public key certificate.
		* @param holderCertPath The certificate path which belongs to the holder
		*            certificate.
		* @param unresolvedCritExts a <code>Collection</code> of OID strings
		*            representing the current set of unresolved critical extensions
		* @throws CertPathValidatorException if the specified attribute certificate
		*             does not pass the check.
		*/
		public abstract void Check(IX509AttributeCertificate attrCert, PkixCertPath certPath,
			PkixCertPath holderCertPath, ICollection unresolvedCritExts);
        /**
         * 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)
            {
                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);
        }
		private PkixCertPathBuilderResult Build(
			IX509AttributeCertificate	attrCert,
			X509Certificate				tbvCert,
			PkixBuilderParameters		pkixParams,
			IList						tbvPath)
		{
			// If tbvCert is readily present in tbvPath, it indicates having run
			// into a cycle in the
			// PKI graph.
			if (tbvPath.Contains(tbvCert))
				return null;

			// step out, the certificate is not allowed to appear in a certification
			// chain
			if (pkixParams.GetExcludedCerts().Contains(tbvCert))
				return null;

			// test if certificate path exceeds maximum length
			if (pkixParams.MaxPathLength != -1)
			{
				if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
					return null;
			}

			tbvPath.Add(tbvCert);

			PkixCertPathBuilderResult builderResult = null;

//			X509CertificateParser certParser = new X509CertificateParser();
			PkixAttrCertPathValidator validator = new PkixAttrCertPathValidator();

			try
			{
				// check whether the issuer of <tbvCert> is a TrustAnchor
				if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null)
				{
					PkixCertPath certPath = new PkixCertPath(tbvPath);
					PkixCertPathValidatorResult result;

					try
					{
						result = validator.Validate(certPath, pkixParams);
					}
					catch (Exception e)
					{
						throw new Exception("Certification path could not be validated.", e);
					}

					return new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
						result.PolicyTree, result.SubjectPublicKey);
				}
				else
				{
					// add additional X.509 stores from locations in certificate
					try
					{
						PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(tbvCert, pkixParams);
					}
					catch (CertificateParsingException e)
					{
						throw new Exception("No additional X.509 stores can be added from certificate locations.", e);
					}

					// try to get the issuer certificate from one of the stores
					ISet issuers = new HashSet();
					try
					{
						issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
					}
					catch (Exception e)
					{
						throw new Exception("Cannot find issuer certificate for certificate in certification path.", e);
					}

					if (issuers.IsEmpty)
						throw new Exception("No issuer certificate for certificate in certification path found.");

					foreach (X509Certificate issuer in issuers)
					{
						// if untrusted self signed certificate continue
						if (PkixCertPathValidatorUtilities.IsSelfIssued(issuer))
							continue;

						builderResult = Build(attrCert, issuer, pkixParams, tbvPath);

						if (builderResult != null)
							break;
					}
				}
			}
			catch (Exception e)
			{
				certPathException = new Exception("No valid certification path could be build.", e);
			}

			if (builderResult == null)
			{
				tbvPath.Remove(tbvCert);
			}

			return builderResult;
		}
Exemple #17
0
		private void equalityAndHashCodeTest(
			IX509AttributeCertificate	attrCert,
			byte[]						encoding)
		{
			if (!attrCert.Equals(attrCert))
			{
				Fail("same certificate not equal");
			}

			if (!attrCert.Holder.Equals(attrCert.Holder))
			{
				Fail("same holder not equal");
			}

			if (!attrCert.Issuer.Equals(attrCert.Issuer))
			{
				Fail("same issuer not equal");
			}

			if (attrCert.Holder.Equals(attrCert.Issuer))
			{
				Fail("wrong holder equal");
			}

			if (attrCert.Issuer.Equals(attrCert.Holder))
			{
				Fail("wrong issuer equal");
			}

			IX509AttributeCertificate attrCert2 = new X509V2AttributeCertificate(encoding);

			if (attrCert2.Holder.GetHashCode() != attrCert.Holder.GetHashCode())
			{
				Fail("holder hashCode test failed");
			}

			if (!attrCert2.Holder.Equals(attrCert.Holder))
			{
				Fail("holder Equals test failed");
			}

			if (attrCert2.Issuer.GetHashCode() != attrCert.Issuer.GetHashCode())
			{
				Fail("issuer hashCode test failed");
			}

			if (!attrCert2.Issuer.Equals(attrCert.Issuer))
			{
				Fail("issuer Equals test failed");
			}
		}
Exemple #18
0
        public bool Match(object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            IX509AttributeCertificate iX509AttributeCertificate = obj as IX509AttributeCertificate;

            if (iX509AttributeCertificate == null)
            {
                return(false);
            }
            if (this.attributeCert != null && !this.attributeCert.Equals(iX509AttributeCertificate))
            {
                return(false);
            }
            if (this.serialNumber != null && !iX509AttributeCertificate.SerialNumber.Equals(this.serialNumber))
            {
                return(false);
            }
            if (this.holder != null && !iX509AttributeCertificate.Holder.Equals(this.holder))
            {
                return(false);
            }
            if (this.issuer != null && !iX509AttributeCertificate.Issuer.Equals(this.issuer))
            {
                return(false);
            }
            if (this.attributeCertificateValid != null && !iX509AttributeCertificate.IsValid(this.attributeCertificateValid.Value))
            {
                return(false);
            }
            if (this.targetNames.Count > 0 || this.targetGroups.Count > 0)
            {
                Asn1OctetString extensionValue = iX509AttributeCertificate.GetExtensionValue(X509Extensions.TargetInformation);
                if (extensionValue != null)
                {
                    TargetInformation instance;
                    try
                    {
                        instance = TargetInformation.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
                    }
                    catch (Exception)
                    {
                        bool result = false;
                        return(result);
                    }
                    Targets[] targetsObjects = instance.GetTargetsObjects();
                    if (this.targetNames.Count > 0)
                    {
                        bool flag = false;
                        int  num  = 0;
                        while (num < targetsObjects.Length && !flag)
                        {
                            Target[] targets = targetsObjects[num].GetTargets();
                            for (int i = 0; i < targets.Length; i++)
                            {
                                GeneralName targetName = targets[i].TargetName;
                                if (targetName != null && this.targetNames.Contains(targetName))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            num++;
                        }
                        if (!flag)
                        {
                            return(false);
                        }
                    }
                    if (this.targetGroups.Count <= 0)
                    {
                        return(true);
                    }
                    bool flag2 = false;
                    int  num2  = 0;
                    while (num2 < targetsObjects.Length && !flag2)
                    {
                        Target[] targets2 = targetsObjects[num2].GetTargets();
                        for (int j = 0; j < targets2.Length; j++)
                        {
                            GeneralName targetGroup = targets2[j].TargetGroup;
                            if (targetGroup != null && this.targetGroups.Contains(targetGroup))
                            {
                                flag2 = true;
                                break;
                            }
                        }
                        num2++;
                    }
                    if (!flag2)
                    {
                        return(false);
                    }
                    return(true);
                }
            }
            return(true);
        }
    public bool Match(object obj)
    {
        if (obj == null)
        {
            throw new ArgumentNullException("obj");
        }
        IX509AttributeCertificate iX509AttributeCertificate = obj as IX509AttributeCertificate;

        if (iX509AttributeCertificate == null)
        {
            return(false);
        }
        if (attributeCert != null && !attributeCert.Equals(iX509AttributeCertificate))
        {
            return(false);
        }
        if (serialNumber != null && !iX509AttributeCertificate.SerialNumber.Equals(serialNumber))
        {
            return(false);
        }
        if (holder != null && !iX509AttributeCertificate.Holder.Equals(holder))
        {
            return(false);
        }
        if (issuer != null && !iX509AttributeCertificate.Issuer.Equals(issuer))
        {
            return(false);
        }
        if (attributeCertificateValid != null && !iX509AttributeCertificate.IsValid(attributeCertificateValid.Value))
        {
            return(false);
        }
        if (targetNames.Count > 0 || targetGroups.Count > 0)
        {
            Asn1OctetString extensionValue = iX509AttributeCertificate.GetExtensionValue(X509Extensions.TargetInformation);
            if (extensionValue != null)
            {
                TargetInformation instance;
                try
                {
                    instance = TargetInformation.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
                }
                catch (Exception)
                {
                    return(false);
                }
                Targets[] targetsObjects = instance.GetTargetsObjects();
                if (targetNames.Count > 0)
                {
                    bool flag = false;
                    for (int i = 0; i < targetsObjects.Length; i++)
                    {
                        if (flag)
                        {
                            break;
                        }
                        Target[] targets = targetsObjects[i].GetTargets();
                        for (int j = 0; j < targets.Length; j++)
                        {
                            GeneralName targetName = targets[j].TargetName;
                            if (targetName != null && targetNames.Contains(targetName))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)
                    {
                        return(false);
                    }
                }
                if (targetGroups.Count > 0)
                {
                    bool flag2 = false;
                    for (int k = 0; k < targetsObjects.Length; k++)
                    {
                        if (flag2)
                        {
                            break;
                        }
                        Target[] targets2 = targetsObjects[k].GetTargets();
                        for (int l = 0; l < targets2.Length; l++)
                        {
                            GeneralName targetGroup = targets2[l].TargetGroup;
                            if (targetGroup != null && targetGroups.Contains(targetGroup))
                            {
                                flag2 = true;
                                break;
                            }
                        }
                    }
                    if (!flag2)
                    {
                        return(false);
                    }
                }
            }
        }
        return(true);
    }
Exemple #20
0
        private void doTestGenerateWithPrincipal()
        {
            X509CertificateParser fact  = new X509CertificateParser();
            X509Certificate       iCert = fact.ReadCertificate(signCert);

            //
            // a sample key pair.
            //
            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16));

            //
            // set up the keys
            //
//			PrivateKey          privKey;
//			PublicKey           pubKey;
//
//			KeyFactory  kFact = KeyFactory.getInstance("RSA");
//
//			privKey = kFact.generatePrivate(RSA_PRIVATE_KEY_SPEC);
//			pubKey = kFact.generatePublic(pubKeySpec);
            AsymmetricKeyParameter privKey = RSA_PRIVATE_KEY_SPEC;

            X509V2AttributeCertificateGenerator gen = new X509V2AttributeCertificateGenerator();

            // the actual attributes
            GeneralName roleName = new GeneralName(GeneralName.Rfc822Name, "DAU123456789");

            // roleSyntax OID: 2.5.24.72
            X509Attribute attributes = new X509Attribute("2.5.24.72",
                                                         new DerSequence(roleName));

            gen.AddAttribute(attributes);
            gen.SetHolder(new AttributeCertificateHolder(iCert.SubjectDN));
            gen.SetIssuer(new AttributeCertificateIssuer(new X509Name("cn=test")));
            gen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            gen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            gen.SetSerialNumber(BigInteger.One);
            gen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            IX509AttributeCertificate aCert = gen.Generate(privKey);

            aCert.CheckValidity();

            aCert.Verify(pubKey);

            AttributeCertificateHolder holder = aCert.Holder;

            if (holder.GetEntityNames() == null)
            {
                Fail("entity names not set when expected");
            }

            if (holder.SerialNumber != null)
            {
                Fail("holder serial number found when none expected");
            }

            if (holder.GetIssuer() != null)
            {
                Fail("holder issuer found when none expected");
            }

            if (!holder.Match(iCert))
            {
                Fail("generated holder not matching holder certificate");
            }

            X509Certificate sCert = fact.ReadCertificate(holderCertWithBaseCertificateID);

            if (holder.Match(sCert))
            {
                Fail("principal generated holder matching wrong certificate");
            }

            equalityAndHashCodeTest(aCert, aCert.GetEncoded());
        }