summary refs log tree commit diff
path: root/crypto/src/pkix/PkixAttrCertPathBuilder.cs
blob: 2d671a58534ca48d15564cbce74fe1b5cf7c2c85 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
using System;
using System.Collections.Generic;

using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;

namespace Org.BouncyCastle.Pkix
{
	public class PkixAttrCertPathBuilder
	{
		/**
		* Build and validate a CertPath using the given parameter.
		*
		* @param params PKIXBuilderParameters object containing all information to
		*            build the CertPath
		*/
		public virtual PkixCertPathBuilderResult Build(PkixBuilderParameters pkixParams)
		{
			// search target certificates

			if (!(pkixParams.GetTargetConstraintsAttrCert() is X509AttrCertStoreSelector attrCertSelector))
			{
				throw new PkixCertPathBuilderException(
					"TargetConstraints must be an instance of "
					+ typeof(X509AttrCertStoreSelector).FullName
					+ " for "
					+ typeof(PkixAttrCertPathBuilder).FullName + " class.");
			}

			HashSet<X509V2AttributeCertificate> targets;
			try
			{
				targets = FindAttributeCertificates(attrCertSelector, pkixParams.GetStoresAttrCert());
			}
			catch (Exception e)
			{
				throw new PkixCertPathBuilderException("Error finding target attribute certificate.", e);
			}

			if (targets.Count == 0)
				throw new PkixCertPathBuilderException("No attribute certificate found matching targetConstraints.");

			PkixCertPathBuilderResult result = null;

			// check all potential target certificates
			foreach (var target in targets)
			{
				X509CertStoreSelector certSelector = new X509CertStoreSelector();
				X509Name[] principals = target.Issuer.GetPrincipals();
				var issuers = new HashSet<X509Certificate>();
				for (int i = 0; i < principals.Length; i++)
				{
					// TODO Replace loop with a single multiprincipal selector (or don't even use selector)
					try
					{
						certSelector.Subject = principals[i];

						CollectionUtilities.CollectMatches(issuers, certSelector, pkixParams.GetStoresCert());
					}
					catch (Exception e)
					{
						throw new PkixCertPathBuilderException(
							"Public key certificate for attribute certificate cannot be searched.",
							e);
					}
				}

				if (issuers.Count < 1)
					throw new PkixCertPathBuilderException("Public key certificate for attribute certificate cannot be found.");

                var certPathList = new List<X509Certificate>();

				foreach (X509Certificate issuer in issuers)
				{
					result = Build(target, issuer, pkixParams, certPathList);

					if (result != null)
						break;
				}

				if (result != null)
					break;
			}

			if (result == null && certPathException != null)
				throw new PkixCertPathBuilderException("Possible certificate chain could not be validated.",
					certPathException);

			if (result == null && certPathException == null)
				throw new PkixCertPathBuilderException("Unable to find certificate chain.");

			return result;
		}

		private Exception certPathException;

		private PkixCertPathBuilderResult Build(
			X509V2AttributeCertificate  attrCert,
			X509Certificate				tbvCert,
			PkixBuilderParameters		pkixParams,
			IList<X509Certificate>      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.IsIssuerTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()))
				{
					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
					HashSet<X509Certificate> issuers;
					try
					{
						issuers = PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams);
					}
					catch (Exception e)
					{
						throw new Exception("Cannot find issuer certificate for certificate in certification path.", e);
					}

					if (issuers.Count < 1)
						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;
		}

		internal static HashSet<X509V2AttributeCertificate> FindAttributeCertificates(
			ISelector<X509V2AttributeCertificate> attrCertSelector,
			IList<IStore<X509V2AttributeCertificate>> attrCertStores)
		{
			var attrCerts = new HashSet<X509V2AttributeCertificate>();

			foreach (var attrCertStore in attrCertStores)
			{
				try
				{
					attrCerts.UnionWith(attrCertStore.EnumerateMatches(attrCertSelector));
				}
				catch (Exception e)
				{
					throw new Exception("Problem while picking certificates from X.509 store.", e);
				}
			}

			return attrCerts;
		}
	}
}