copying the latest Sys.Web.Services from trunk.
[mono.git] / mcs / class / Mono.Security / Mono.Security.X509 / X509CRL.cs
1 //
2 // X509CRL.cs: Handles X.509 certificates revocation lists.
3 //
4 // Author:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //
7 // (C) 2004 Novell (http://www.novell.com)
8 //
9
10 //
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:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
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.
29 //
30
31 using System;
32 using System.Collections;
33 using System.Globalization;
34 using System.IO;
35 using System.Security.Cryptography;
36
37 using Mono.Security.X509.Extensions;
38
39 namespace Mono.Security.X509 {
40         /*
41          * CertificateList  ::=  SEQUENCE  {
42          *      tbsCertList          TBSCertList,
43          *      signatureAlgorithm   AlgorithmIdentifier,
44          *      signature            BIT STRING  
45          * }
46          * 
47          * TBSCertList  ::=  SEQUENCE  {
48          *      version                 Version OPTIONAL,
49          *              -- if present, MUST be v2
50          *      signature               AlgorithmIdentifier,
51          *      issuer                  Name,
52          *      thisUpdate              Time,
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
59          *      }  OPTIONAL,
60          *      crlExtensions           [0] Extensions OPTIONAL }
61          *              -- if present, MUST be v2
62          */
63 #if INSIDE_CORLIB
64         internal
65 #else
66         public 
67 #endif
68         class X509Crl {
69
70                 public class X509CrlEntry {
71
72                         private byte[] sn;
73                         private DateTime revocationDate;
74                         private X509ExtensionCollection extensions;
75
76                         internal X509CrlEntry (byte[] serialNumber, DateTime revocationDate, X509ExtensionCollection extensions) 
77                         {
78                                 sn = serialNumber;
79                                 this.revocationDate = revocationDate;
80                                 if (extensions == null)
81                                         this.extensions = new X509ExtensionCollection ();
82                                 else
83                                         this.extensions = extensions;
84                         }
85
86                         internal X509CrlEntry (ASN1 entry) 
87                         {
88                                 sn = entry [0].Value;
89                                 Array.Reverse (sn);
90                                 revocationDate = ASN1Convert.ToDateTime (entry [1]);
91                                 extensions = new X509ExtensionCollection (entry [2]);
92                         }
93
94                         public byte[] SerialNumber {
95                                 get { return (byte[]) sn.Clone (); }
96                         }
97
98                         public DateTime RevocationDate {
99                                 get { return revocationDate; }
100                         }
101
102                         public X509ExtensionCollection Extensions {
103                                 get { return extensions; }
104                         }
105
106                         public byte[] GetBytes () 
107                         {
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 ();
114                         }
115                 }
116
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;
126
127                 public X509Crl (byte[] crl) 
128                 {
129                         if (crl == null)
130                                 throw new ArgumentNullException ("crl");
131                         encoded = (byte[]) crl.Clone ();
132                         Parse (encoded);
133                 }
134
135                 private void Parse (byte[] crl) 
136                 {
137                         string e = "Input data cannot be coded as a valid CRL.";
138                         try {
139                                 // CertificateList  ::=  SEQUENCE  {
140                                 ASN1 encodedCRL = new ASN1 (encoded);
141                                 if ((encodedCRL.Tag != 0x30) || (encodedCRL.Count != 3))
142                                         throw new CryptographicException (e);
143
144                                 // CertificateList / TBSCertList,
145                                 ASN1 toBeSigned = encodedCRL [0];
146                                 if ((toBeSigned.Tag != 0x30) || (toBeSigned.Count < 3))
147                                         throw new CryptographicException (e);
148
149                                 int n = 0;
150                                 // CertificateList / TBSCertList / Version OPTIONAL, -- if present, MUST be v2
151                                 if (toBeSigned [n].Tag == 0x02) {
152                                         version = (byte) (toBeSigned [n++].Value [0] + 1);
153                                 }
154                                 else
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++];
167                                 }
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]));
173                                 }
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]);
178                                 else
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]");
184
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);
190                         }
191                         catch {
192                                 throw new CryptographicException (e);
193                         }
194                 }
195
196                 public ArrayList Entries {
197                         get { return ArrayList.ReadOnly (entries); }
198                 }
199
200                 public X509CrlEntry this [int index] {
201                         get { return (X509CrlEntry) entries [index]; }
202                 }
203
204                 public X509CrlEntry this [byte[] serialNumber] {
205                         get { return GetCrlEntry (serialNumber); }
206                 }
207
208                 public X509ExtensionCollection Extensions {
209                         get { return extensions; }
210                 }
211
212                 public string IssuerName {
213                         get { return issuer; }
214                 }
215
216                 public DateTime NextUpdate {
217                         get { return nextUpdate; }
218                 }
219
220                 public DateTime ThisUpdate {
221                         get { return thisUpdate; }
222                 }
223
224                 public string SignatureAlgorithm {
225                         get { return signatureOID; }
226                 }
227
228                 public byte[] Signature {
229                         get { 
230                                 if (signature == null)
231                                         return null;
232                                 return (byte[]) signature.Clone ();
233                         }
234                 }
235
236                 public byte Version {
237                         get { return version; }
238                 }
239
240                 public bool IsCurrent {
241                         get { return WasCurrent (DateTime.UtcNow); }
242                 }
243
244                 public bool WasCurrent (DateTime instant) 
245                 {
246                         if (nextUpdate == DateTime.MinValue)
247                                 return (instant >= thisUpdate);
248                         else
249                                 return ((instant >= thisUpdate) && (instant <= nextUpdate));
250                 }
251
252                 public byte[] GetBytes () 
253                 {
254                         return (byte[]) encoded.Clone ();
255                 }
256
257                 private bool Compare (byte[] array1, byte[] array2) 
258                 {
259                         if ((array1 == null) && (array2 == null))
260                                 return true;
261                         if ((array1 == null) || (array2 == null))
262                                 return false;
263                         if (array1.Length != array2.Length)
264                                 return false;
265                         for (int i=0; i < array1.Length; i++) {
266                                 if (array1 [i] != array2 [i])
267                                         return false;
268                         }
269                         return true;
270                 }
271
272                 public X509CrlEntry GetCrlEntry (X509Certificate x509) 
273                 {
274                         if (x509 == null)
275                                 throw new ArgumentNullException ("x509");
276
277                         return GetCrlEntry (x509.SerialNumber);
278                 }
279
280                 public X509CrlEntry GetCrlEntry (byte[] serialNumber) 
281                 {
282                         if (serialNumber == null)
283                                 throw new ArgumentNullException ("serialNumber");
284
285                         for (int i=0; i < entries.Count; i++) {
286                                 X509CrlEntry entry = (X509CrlEntry) entries [i];
287                                 if (Compare (serialNumber, entry.SerialNumber))
288                                         return entry;
289                         }
290                         return null;
291                 }
292
293                 public bool VerifySignature (X509Certificate x509) 
294                 {
295                         if (x509 == null)
296                                 throw new ArgumentNullException ("x509");
297
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"];
302                                 if (ext != null) {
303                                         KeyUsageExtension keyUsage = new KeyUsageExtension (ext);
304                                         if (!keyUsage.Support (KeyUsages.cRLSign))
305                                                 return false;
306                                 }
307                                 // 1.2. Check for ca = true in BasicConstraint
308                                 ext = x509.Extensions ["2.5.29.19"];
309                                 if (ext != null) {
310                                         BasicConstraintsExtension basicConstraints = new BasicConstraintsExtension (ext);
311                                         if (!basicConstraints.CertificateAuthority)
312                                                 return false;
313                                 }
314                         }
315                         // 2. CRL issuer must match CA subject name
316                         if (issuer != x509.SubjectName)
317                                 return false;
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);
322                                 default:
323                                         return VerifySignature (x509.RSA);
324                         }
325                 }
326
327                 private byte[] GetHash (string hashName) 
328                 {
329                         ASN1 encodedCRL = new ASN1 (encoded);
330                         byte[] toBeSigned = encodedCRL [0].GetBytes ();
331                         HashAlgorithm ha = HashAlgorithm.Create (hashName);
332                         return ha.ComputeHash (toBeSigned);
333                 }
334
335                 internal bool VerifySignature (DSA dsa) 
336                 {
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))
345                                 return false;
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);
353                 }
354
355                 internal bool VerifySignature (RSA rsa) 
356                 {
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 ?
363                                         hashName = "MD2";
364                                         break;
365                                 // MD5 with RSA encryption 
366                                 case "1.2.840.113549.1.1.4":
367                                         hashName = "MD5";
368                                         break;
369                                 // SHA-1 with RSA Encryption 
370                                 case "1.2.840.113549.1.1.5":
371                                         hashName = "SHA1";
372                                         break;
373                                 default:
374                                         throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
375                         }
376                         v.SetHashAlgorithm (hashName);
377                         return v.VerifySignature (GetHash (hashName), signature);
378                 }
379
380                 public bool VerifySignature (AsymmetricAlgorithm aa) 
381                 {
382                         if (aa == null)
383                                 throw new ArgumentNullException ("aa");
384
385                         // only validate the signature (in case we don't have the CA certificate)
386                         if (aa is RSA)
387                                 return VerifySignature (aa as RSA);
388                         else if (aa is DSA)
389                                 return VerifySignature (aa as DSA);
390                         else
391                                 throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
392                 }
393
394                 static public X509Crl CreateFromFile (string filename) 
395                 {
396                         byte[] crl = null;
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);
400                                 fs.Close ();
401                         }
402                         return new X509Crl (crl);
403                 }
404         }
405 }