2 // X509CRL.cs: Handles X.509 certificates revocation lists.
5 // Sebastien Pouliot <sebastien@ximian.com>
7 // (C) 2004 Novell (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Globalization;
35 using System.Security.Cryptography;
37 using Mono.Security.X509.Extensions;
39 namespace Mono.Security.X509 {
41 * CertificateList ::= SEQUENCE {
42 * tbsCertList TBSCertList,
43 * signatureAlgorithm AlgorithmIdentifier,
44 * signature BIT STRING
47 * TBSCertList ::= SEQUENCE {
48 * version Version OPTIONAL,
49 * -- if present, MUST be v2
50 * signature AlgorithmIdentifier,
53 * nextUpdate Time OPTIONAL,
54 * revokedCertificates SEQUENCE OF SEQUENCE {
55 * userCertificate CertificateSerialNumber,
56 * revocationDate Time,
57 * crlEntryExtensions Extensions OPTIONAL
58 * -- if present, MUST be v2
60 * crlExtensions [0] Extensions OPTIONAL }
61 * -- if present, MUST be v2
70 public class X509CrlEntry {
73 private DateTime revocationDate;
74 private X509ExtensionCollection extensions;
76 internal X509CrlEntry (byte[] serialNumber, DateTime revocationDate, X509ExtensionCollection extensions)
79 this.revocationDate = revocationDate;
80 if (extensions == null)
81 this.extensions = new X509ExtensionCollection ();
83 this.extensions = extensions;
86 internal X509CrlEntry (ASN1 entry)
90 revocationDate = ASN1Convert.ToDateTime (entry [1]);
91 extensions = new X509ExtensionCollection (entry [2]);
94 public byte[] SerialNumber {
95 get { return (byte[]) sn.Clone (); }
98 public DateTime RevocationDate {
99 get { return revocationDate; }
102 public X509ExtensionCollection Extensions {
103 get { return extensions; }
106 public byte[] GetBytes ()
108 ASN1 sequence = new ASN1 (0x30);
109 sequence.Add (new ASN1 (0x02, sn));
110 sequence.Add (ASN1Convert.FromDateTime (revocationDate));
111 if (extensions.Count > 0)
112 sequence.Add (new ASN1 (extensions.GetBytes ()));
113 return sequence.GetBytes ();
117 private string issuer;
118 private byte version;
119 private DateTime thisUpdate;
120 private DateTime nextUpdate;
121 private ArrayList entries;
122 private string signatureOID;
123 private byte[] signature;
124 private X509ExtensionCollection extensions;
125 private byte[] encoded;
127 public X509Crl (byte[] crl)
130 throw new ArgumentNullException ("crl");
131 encoded = (byte[]) crl.Clone ();
135 private void Parse (byte[] crl)
137 string e = "Input data cannot be coded as a valid CRL.";
139 // CertificateList ::= SEQUENCE {
140 ASN1 encodedCRL = new ASN1 (encoded);
141 if ((encodedCRL.Tag != 0x30) || (encodedCRL.Count != 3))
142 throw new CryptographicException (e);
144 // CertificateList / TBSCertList,
145 ASN1 toBeSigned = encodedCRL [0];
146 if ((toBeSigned.Tag != 0x30) || (toBeSigned.Count < 3))
147 throw new CryptographicException (e);
150 // CertificateList / TBSCertList / Version OPTIONAL, -- if present, MUST be v2
151 if (toBeSigned [n].Tag == 0x02) {
152 version = (byte) (toBeSigned [n++].Value [0] + 1);
155 version = 1; // DEFAULT
156 // CertificateList / TBSCertList / AlgorithmIdentifier,
157 signatureOID = ASN1Convert.ToOid (toBeSigned [n++][0]);
158 // CertificateList / TBSCertList / Name,
159 issuer = X501.ToString (toBeSigned [n++]);
160 // CertificateList / TBSCertList / Time,
161 thisUpdate = ASN1Convert.ToDateTime (toBeSigned [n++]);
162 // CertificateList / TBSCertList / Time OPTIONAL,
163 ASN1 next = toBeSigned [n++];
164 if ((next.Tag == 0x17) || (next.Tag == 0x18)) {
165 nextUpdate = ASN1Convert.ToDateTime (next);
166 next = toBeSigned [n++];
168 // CertificateList / TBSCertList / revokedCertificates SEQUENCE OF SEQUENCE {
169 entries = new ArrayList ();
170 ASN1 revokedCertificates = next;
171 for (int i=0; i < revokedCertificates.Count; i++) {
172 entries.Add (new X509CrlEntry (revokedCertificates [i]));
174 // CertificateList / TBSCertList / crlExtensions [0] Extensions OPTIONAL }
175 ASN1 extns = toBeSigned [n];
176 if ((extns != null) && (extns.Tag == 0xA0) && (extns.Count == 1))
177 extensions = new X509ExtensionCollection (extns [0]);
179 extensions = new X509ExtensionCollection (null); // result in a read only object
180 // CertificateList / AlgorithmIdentifier
181 string signatureAlgorithm = ASN1Convert.ToOid (encodedCRL [1][0]);
182 if (signatureOID != signatureAlgorithm)
183 throw new CryptographicException (e + " [Non-matching signature algorithms in CRL]");
185 // CertificateList / BIT STRING
186 byte[] bitstring = encodedCRL [2].Value;
187 // first byte contains unused bits in first byte
188 signature = new byte [bitstring.Length - 1];
189 Buffer.BlockCopy (bitstring, 1, signature, 0, signature.Length);
192 throw new CryptographicException (e);
196 public ArrayList Entries {
197 get { return ArrayList.ReadOnly (entries); }
200 public X509CrlEntry this [int index] {
201 get { return (X509CrlEntry) entries [index]; }
204 public X509CrlEntry this [byte[] serialNumber] {
205 get { return GetCrlEntry (serialNumber); }
208 public X509ExtensionCollection Extensions {
209 get { return extensions; }
212 public string IssuerName {
213 get { return issuer; }
216 public DateTime NextUpdate {
217 get { return nextUpdate; }
220 public DateTime ThisUpdate {
221 get { return thisUpdate; }
224 public string SignatureAlgorithm {
225 get { return signatureOID; }
228 public byte[] Signature {
230 if (signature == null)
232 return (byte[]) signature.Clone ();
236 public byte Version {
237 get { return version; }
240 public bool IsCurrent {
241 get { return WasCurrent (DateTime.UtcNow); }
244 public bool WasCurrent (DateTime instant)
246 if (nextUpdate == DateTime.MinValue)
247 return (instant >= thisUpdate);
249 return ((instant >= thisUpdate) && (instant <= nextUpdate));
252 public byte[] GetBytes ()
254 return (byte[]) encoded.Clone ();
257 private bool Compare (byte[] array1, byte[] array2)
259 if ((array1 == null) && (array2 == null))
261 if ((array1 == null) || (array2 == null))
263 if (array1.Length != array2.Length)
265 for (int i=0; i < array1.Length; i++) {
266 if (array1 [i] != array2 [i])
272 public X509CrlEntry GetCrlEntry (X509Certificate x509)
275 throw new ArgumentNullException ("x509");
277 return GetCrlEntry (x509.SerialNumber);
280 public X509CrlEntry GetCrlEntry (byte[] serialNumber)
282 if (serialNumber == null)
283 throw new ArgumentNullException ("serialNumber");
285 for (int i=0; i < entries.Count; i++) {
286 X509CrlEntry entry = (X509CrlEntry) entries [i];
287 if (Compare (serialNumber, entry.SerialNumber))
293 public bool VerifySignature (X509Certificate x509)
296 throw new ArgumentNullException ("x509");
298 // 1. x509 certificate must be a CA certificate (unknown for v1 or v2 certs)
299 if (x509.Version >= 3) {
300 // 1.1. Check for "cRLSign" bit in KeyUsage extension
301 X509Extension ext = x509.Extensions ["2.5.29.15"];
303 KeyUsageExtension keyUsage = new KeyUsageExtension (ext);
304 if (!keyUsage.Support (KeyUsages.cRLSign))
307 // 1.2. Check for ca = true in BasicConstraint
308 ext = x509.Extensions ["2.5.29.19"];
310 BasicConstraintsExtension basicConstraints = new BasicConstraintsExtension (ext);
311 if (!basicConstraints.CertificateAuthority)
315 // 2. CRL issuer must match CA subject name
316 if (issuer != x509.SubjectName)
318 // 3. Check the CRL signature with the CA certificate public key
319 switch (signatureOID) {
320 case "1.2.840.10040.4.3":
321 return VerifySignature (x509.DSA);
323 return VerifySignature (x509.RSA);
327 private byte[] GetHash (string hashName)
329 ASN1 encodedCRL = new ASN1 (encoded);
330 byte[] toBeSigned = encodedCRL [0].GetBytes ();
331 HashAlgorithm ha = HashAlgorithm.Create (hashName);
332 return ha.ComputeHash (toBeSigned);
335 internal bool VerifySignature (DSA dsa)
337 if (signatureOID != "1.2.840.10040.4.3")
338 throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
339 DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
340 // only SHA-1 is supported
341 string hashName = "SHA1";
342 v.SetHashAlgorithm (hashName);
343 ASN1 sign = new ASN1 (signature);
344 if ((sign == null) || (sign.Count != 2))
346 // parts may be less than 20 bytes (i.e. first bytes were 0x00)
347 byte[] part1 = sign [0].Value;
348 byte[] part2 = sign [1].Value;
349 byte[] sig = new byte [40];
350 Buffer.BlockCopy (part1, 0, sig, (20 - part1.Length), part1.Length);
351 Buffer.BlockCopy (part2, 0, sig, (40 - part2.Length), part2.Length);
352 return v.VerifySignature (GetHash (hashName), sig);
355 internal bool VerifySignature (RSA rsa)
357 RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
358 string hashName = null;
359 switch (signatureOID) {
360 // MD2 with RSA encryption
361 case "1.2.840.113549.1.1.2":
362 // maybe someone installed MD2 ?
365 // MD5 with RSA encryption
366 case "1.2.840.113549.1.1.4":
369 // SHA-1 with RSA Encryption
370 case "1.2.840.113549.1.1.5":
374 throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
376 v.SetHashAlgorithm (hashName);
377 return v.VerifySignature (GetHash (hashName), signature);
380 public bool VerifySignature (AsymmetricAlgorithm aa)
383 throw new ArgumentNullException ("aa");
385 // only validate the signature (in case we don't have the CA certificate)
387 return VerifySignature (aa as RSA);
389 return VerifySignature (aa as DSA);
391 throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
394 static public X509Crl CreateFromFile (string filename)
397 using (FileStream fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
398 crl = new byte [fs.Length];
399 fs.Read (crl, 0, crl.Length);
402 return new X509Crl (crl);