Debian Codegraph @

mcs/class/Mono.Security/Mono.Security.X509/X509Certificate.cs

raw symbols SCIP
1 //
2 // X509Certificates.cs: Handles X.509 certificates.
3 //
4 // Author:
5 // Sebastien Pouliot <[email protected]>
6 //
7 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
9 // Copyright 2013 Xamarin Inc. (http://www.xamarin.com)
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.Runtime.Serialization;
33 using System.Security.Cryptography;
34 using SSCX = System.Security.Cryptography.X509Certificates;
35 using System.Security.Permissions;
36 using System.Text;
37 using Mono.Security.Cryptography;
38
39 namespace Mono.Security.X509 {
40
41 // References:
42 // a. Internet X.509 Public Key Infrastructure Certificate and CRL Profile
43 // http://www.ietf.org/rfc/rfc3280.txt
44 // b. ITU ASN.1 standards (free download)
45 // http://www.itu.int/ITU-T/studygroups/com17/languages/
46
47 #if INSIDE_CORLIB || INSIDE_SYSTEM
48 internal class X509Certificate : ISerializable {
49 #else
50 public class X509Certificate : ISerializable {
51 #endif
52
53 private ASN1 decoder;
54
55 private byte[] m_encodedcert;
56 private DateTime m_from;
57 private DateTime m_until;
58 private ASN1 issuer;
59 private string m_issuername;
60 private string m_keyalgo;
61 private byte[] m_keyalgoparams;
62 private ASN1 subject;
63 private string m_subject;
64 private byte[] m_publickey;
65 private byte[] signature;
66 private string m_signaturealgo;
67 private byte[] m_signaturealgoparams;
68 private byte[] certhash;
69 private RSA _rsa;
70 private DSA _dsa;
71
72 // from http://msdn.microsoft.com/en-gb/library/ff635835.aspx
73 internal const string OID_DSA = "1.2.840.10040.4.1";
74 internal const string OID_RSA = "1.2.840.113549.1.1.1";
75 internal const string OID_ECC = "1.2.840.10045.2.1";
76
77 // from http://www.ietf.org/rfc/rfc2459.txt
78 //
79 //Certificate ::= SEQUENCE {
80 // tbsCertificate TBSCertificate,
81 // signatureAlgorithm AlgorithmIdentifier,
82 // signature BIT STRING }
83 //
84 //TBSCertificate ::= SEQUENCE {
85 // version [0] Version DEFAULT v1,
86 // serialNumber CertificateSerialNumber,
87 // signature AlgorithmIdentifier,
88 // issuer Name,
89 // validity Validity,
90 // subject Name,
91 // subjectPublicKeyInfo SubjectPublicKeyInfo,
92 // issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
93 // -- If present, version shall be v2 or v3
94 // subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
95 // -- If present, version shall be v2 or v3
96 // extensions [3] Extensions OPTIONAL
97 // -- If present, version shall be v3 -- }
98 private int version;
99 private byte[] serialnumber;
100
101 private byte[] issuerUniqueID;
102 private byte[] subjectUniqueID;
103 private X509ExtensionCollection extensions;
104
105 private static string encoding_error = Locale.GetText ("Input data cannot be coded as a valid certificate.");
106
107
108 // that's were the real job is!
109 private void Parse (byte[] data)
110 {
111 try {
112 decoder = new ASN1 (data);
113 // Certificate
114 if (decoder.Tag != 0x30)
115 throw new CryptographicException (encoding_error);
116 // Certificate / TBSCertificate
117 if (decoder [0].Tag != 0x30)
118 throw new CryptographicException (encoding_error);
119
120 ASN1 tbsCertificate = decoder [0];
121
122 int tbs = 0;
123 // Certificate / TBSCertificate / Version
124 ASN1 v = decoder [0][tbs];
125 version = 1; // DEFAULT v1
126 if ((v.Tag == 0xA0) && (v.Count > 0)) {
127 // version (optional) is present only in v2+ certs
128 version += v [0].Value [0]; // zero based
129 tbs++;
130 }
131
132 // Certificate / TBSCertificate / CertificateSerialNumber
133 ASN1 sn = decoder [0][tbs++];
134 if (sn.Tag != 0x02)
135 throw new CryptographicException (encoding_error);
136 serialnumber = sn.Value;
137 Array.Reverse (serialnumber, 0, serialnumber.Length);
138
139 // Certificate / TBSCertificate / AlgorithmIdentifier
140 tbs++;
141 // ASN1 signatureAlgo = tbsCertificate.Element (tbs++, 0x30);
142
143 issuer = tbsCertificate.Element (tbs++, 0x30);
144 m_issuername = X501.ToString (issuer);
145
146 ASN1 validity = tbsCertificate.Element (tbs++, 0x30);
147 ASN1 notBefore = validity [0];
148 m_from = ASN1Convert.ToDateTime (notBefore);
149 ASN1 notAfter = validity [1];
150 m_until = ASN1Convert.ToDateTime (notAfter);
151
152 subject = tbsCertificate.Element (tbs++, 0x30);
153 m_subject = X501.ToString (subject);
154
155 ASN1 subjectPublicKeyInfo = tbsCertificate.Element (tbs++, 0x30);
156
157 ASN1 algorithm = subjectPublicKeyInfo.Element (0, 0x30);
158 ASN1 algo = algorithm.Element (0, 0x06);
159 m_keyalgo = ASN1Convert.ToOid (algo);
160 // parameters ANY DEFINED BY algorithm OPTIONAL
161 // so we dont ask for a specific (Element) type and return DER
162 ASN1 parameters = algorithm [1];
163 m_keyalgoparams = ((algorithm.Count > 1) ? parameters.GetBytes () : null);
164
165 ASN1 subjectPublicKey = subjectPublicKeyInfo.Element (1, 0x03);
166 // we must drop th first byte (which is the number of unused bits
167 // in the BITSTRING)
168 int n = subjectPublicKey.Length - 1;
169 m_publickey = new byte [n];
170 Buffer.BlockCopy (subjectPublicKey.Value, 1, m_publickey, 0, n);
171
172 // signature processing
173 byte[] bitstring = decoder [2].Value;
174 // first byte contains unused bits in first byte
175 signature = new byte [bitstring.Length - 1];
176 Buffer.BlockCopy (bitstring, 1, signature, 0, signature.Length);
177
178 algorithm = decoder [1];
179 algo = algorithm.Element (0, 0x06);
180 m_signaturealgo = ASN1Convert.ToOid (algo);
181 parameters = algorithm [1];
182 if (parameters != null)
183 m_signaturealgoparams = parameters.GetBytes ();
184 else
185 m_signaturealgoparams = null;
186
187 // Certificate / TBSCertificate / issuerUniqueID
188 ASN1 issuerUID = tbsCertificate.Element (tbs, 0x81);
189 if (issuerUID != null) {
190 tbs++;
191 issuerUniqueID = issuerUID.Value;
192 }
193
194 // Certificate / TBSCertificate / subjectUniqueID
195 ASN1 subjectUID = tbsCertificate.Element (tbs, 0x82);
196 if (subjectUID != null) {
197 tbs++;
198 subjectUniqueID = subjectUID.Value;
199 }
200
201 // Certificate / TBSCertificate / Extensions
202 ASN1 extns = tbsCertificate.Element (tbs, 0xA3);
203 if ((extns != null) && (extns.Count == 1))
204 extensions = new X509ExtensionCollection (extns [0]);
205 else
206 extensions = new X509ExtensionCollection (null);
207
208 // keep a copy of the original data
209 m_encodedcert = (byte[]) data.Clone ();
210 }
211 catch (Exception ex) {
212 throw new CryptographicException (encoding_error, ex);
213 }
214 }
215
216 // constructors
217
218 public X509Certificate (byte[] data)
219 {
220 if (data != null) {
221 // does it looks like PEM ?
222 if ((data.Length > 0) && (data [0] != 0x30)) {
223 try {
224 data = PEM ("CERTIFICATE", data);
225 }
226 catch (Exception ex) {
227 throw new CryptographicException (encoding_error, ex);
228 }
229 }
230 Parse (data);
231 }
232 }
233
234 private byte[] GetUnsignedBigInteger (byte[] integer)
235 {
236 if (integer [0] == 0x00) {
237 // this first byte is added so we're sure it's an unsigned integer
238 // however we can't feed it into RSAParameters or DSAParameters
239 int length = integer.Length - 1;
240 byte[] uinteger = new byte [length];
241 Buffer.BlockCopy (integer, 1, uinteger, 0, length);
242 return uinteger;
243 }
244 else
245 return integer;
246 }
247
248 // public methods
249
250 public DSA DSA {
251 get {
252 if (m_keyalgoparams == null)
253 throw new CryptographicException ("Missing key algorithm parameters.");
254
255 if (_dsa == null && m_keyalgo == OID_DSA) {
256 DSAParameters dsaParams = new DSAParameters ();
257 // for DSA m_publickey contains 1 ASN.1 integer - Y
258 ASN1 pubkey = new ASN1 (m_publickey);
259 if ((pubkey == null) || (pubkey.Tag != 0x02))
260 return null;
261 dsaParams.Y = GetUnsignedBigInteger (pubkey.Value);
262
263 ASN1 param = new ASN1 (m_keyalgoparams);
264 if ((param == null) || (param.Tag != 0x30) || (param.Count < 3))
265 return null;
266 if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02))
267 return null;
268 dsaParams.P = GetUnsignedBigInteger (param [0].Value);
269 dsaParams.Q = GetUnsignedBigInteger (param [1].Value);
270 dsaParams.G = GetUnsignedBigInteger (param [2].Value);
271
272 // BUG: MS BCL 1.0 can't import a key which
273 // isn't the same size as the one present in
274 // the container.
275 _dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
276 _dsa.ImportParameters (dsaParams);
277 }
278 return _dsa;
279 }
280
281 set {
282 _dsa = value;
283 if (value != null)
284 _rsa = null;
285 }
286 }
287
288 public X509ExtensionCollection Extensions {
289 get { return extensions; }
290 }
291
292 public byte[] Hash {
293 get {
294 if (certhash == null) {
295 if ((decoder == null) || (decoder.Count < 1))
296 return null;
297 string algo = PKCS1.HashNameFromOid (m_signaturealgo, false);
298 if (algo == null)
299 return null;
300 byte[] toBeSigned = decoder [0].GetBytes ();
301 using (var hash = PKCS1.CreateFromName (algo))
302 certhash = hash.ComputeHash (toBeSigned, 0, toBeSigned.Length);
303 }
304 return (byte[]) certhash.Clone ();
305 }
306 }
307
308 public virtual string IssuerName {
309 get { return m_issuername; }
310 }
311
312 public virtual string KeyAlgorithm {
313 get { return m_keyalgo; }
314 }
315
316 public virtual byte[] KeyAlgorithmParameters {
317 get {
318 if (m_keyalgoparams == null)
319 return null;
320 return (byte[]) m_keyalgoparams.Clone ();
321 }
322 set { m_keyalgoparams = value; }
323 }
324
325 public virtual byte[] PublicKey {
326 get {
327 if (m_publickey == null)
328 return null;
329 return (byte[]) m_publickey.Clone ();
330 }
331 }
332
333 public virtual RSA RSA {
334 get {
335 if (_rsa == null && m_keyalgo == OID_RSA) {
336 RSAParameters rsaParams = new RSAParameters ();
337 // for RSA m_publickey contains 2 ASN.1 integers
338 // the modulus and the public exponent
339 ASN1 pubkey = new ASN1 (m_publickey);
340 ASN1 modulus = pubkey [0];
341 if ((modulus == null) || (modulus.Tag != 0x02))
342 return null;
343 ASN1 exponent = pubkey [1];
344 if (exponent.Tag != 0x02)
345 return null;
346
347 rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
348 rsaParams.Exponent = exponent.Value;
349
350 // BUG: MS BCL 1.0 can't import a key which
351 // isn't the same size as the one present in
352 // the container.
353 int keySize = (rsaParams.Modulus.Length << 3);
354 _rsa = (RSA) new RSACryptoServiceProvider (keySize);
355 _rsa.ImportParameters (rsaParams);
356 }
357 return _rsa;
358 }
359
360 set {
361 if (value != null)
362 _dsa = null;
363 _rsa = value;
364 }
365 }
366
367 public virtual byte[] RawData {
368 get {
369 if (m_encodedcert == null)
370 return null;
371 return (byte[]) m_encodedcert.Clone ();
372 }
373 }
374
375 public virtual byte[] SerialNumber {
376 get {
377 if (serialnumber == null)
378 return null;
379 return (byte[]) serialnumber.Clone ();
380 }
381 }
382
383 public virtual byte[] Signature {
384 get {
385 if (signature == null)
386 return null;
387
388 switch (m_signaturealgo) {
389 case "1.2.840.113549.1.1.2": // MD2 with RSA encryption
390 case "1.2.840.113549.1.1.3": // MD4 with RSA encryption
391 case "1.2.840.113549.1.1.4": // MD5 with RSA encryption
392 case "1.2.840.113549.1.1.5": // SHA-1 with RSA Encryption
393 case "1.3.14.3.2.29": // SHA1 with RSA signature
394 case "1.2.840.113549.1.1.11": // SHA-256 with RSA Encryption
395 case "1.2.840.113549.1.1.12": // SHA-384 with RSA Encryption
396 case "1.2.840.113549.1.1.13": // SHA-512 with RSA Encryption
397 case "1.3.36.3.3.1.2": // RIPEMD160 with RSA Encryption
398 return (byte[]) signature.Clone ();
399
400 case "1.2.840.10040.4.3": // SHA-1 with DSA
401 ASN1 sign = new ASN1 (signature);
402 if ((sign == null) || (sign.Count != 2))
403 return null;
404 byte[] part1 = sign [0].Value;
405 byte[] part2 = sign [1].Value;
406 byte[] sig = new byte [40];
407 // parts may be less than 20 bytes (i.e. first bytes were 0x00)
408 // parts may be more than 20 bytes (i.e. first byte > 0x80, negative)
409 int s1 = System.Math.Max (0, part1.Length - 20);
410 int e1 = System.Math.Max (0, 20 - part1.Length);
411 Buffer.BlockCopy (part1, s1, sig, e1, part1.Length - s1);
412 int s2 = System.Math.Max (0, part2.Length - 20);
413 int e2 = System.Math.Max (20, 40 - part2.Length);
414 Buffer.BlockCopy (part2, s2, sig, e2, part2.Length - s2);
415 return sig;
416
417 default:
418 throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
419 }
420 }
421 }
422
423 public virtual string SignatureAlgorithm {
424 get { return m_signaturealgo; }
425 }
426
427 public virtual byte[] SignatureAlgorithmParameters {
428 get {
429 if (m_signaturealgoparams == null)
430 return m_signaturealgoparams;
431 return (byte[]) m_signaturealgoparams.Clone ();
432 }
433 }
434
435 public virtual string SubjectName {
436 get { return m_subject; }
437 }
438
439 public virtual DateTime ValidFrom {
440 get { return m_from; }
441 }
442
443 public virtual DateTime ValidUntil {
444 get { return m_until; }
445 }
446
447 public int Version {
448 get { return version; }
449 }
450
451 public bool IsCurrent {
452 get { return WasCurrent (DateTime.UtcNow); }
453 }
454
455 public bool WasCurrent (DateTime instant)
456 {
457 return ((instant > ValidFrom) && (instant <= ValidUntil));
458 }
459
460 // uncommon v2 "extension"
461 public byte[] IssuerUniqueIdentifier {
462 get {
463 if (issuerUniqueID == null)
464 return null;
465 return (byte[]) issuerUniqueID.Clone ();
466 }
467 }
468
469 // uncommon v2 "extension"
470 public byte[] SubjectUniqueIdentifier {
471 get {
472 if (subjectUniqueID == null)
473 return null;
474 return (byte[]) subjectUniqueID.Clone ();
475 }
476 }
477
478 internal bool VerifySignature (DSA dsa)
479 {
480 // signatureOID is check by both this.Hash and this.Signature
481 DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
482 // only SHA-1 is supported
483 v.SetHashAlgorithm ("SHA1");
484 return v.VerifySignature (this.Hash, this.Signature);
485 }
486
487 internal bool VerifySignature (RSA rsa)
488 {
489 // SHA1-1 with DSA
490 if (m_signaturealgo == "1.2.840.10040.4.3")
491 return false;
492 RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
493 v.SetHashAlgorithm (PKCS1.HashNameFromOid (m_signaturealgo));
494 return v.VerifySignature (this.Hash, this.Signature);
495 }
496
497 public bool VerifySignature (AsymmetricAlgorithm aa)
498 {
499 if (aa == null)
500 throw new ArgumentNullException ("aa");
501
502 if (aa is RSA)
503 return VerifySignature (aa as RSA);
504 else if (aa is DSA)
505 return VerifySignature (aa as DSA);
506 else
507 throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
508 }
509
510 public bool CheckSignature (byte[] hash, string hashAlgorithm, byte[] signature)
511 {
512 RSACryptoServiceProvider r = (RSACryptoServiceProvider) RSA;
513 return r.VerifyHash (hash, hashAlgorithm, signature);
514 }
515
516 public bool IsSelfSigned {
517 get {
518 if (m_issuername != m_subject)
519 return false;
520
521 try {
522 if (RSA != null)
523 return VerifySignature (RSA);
524 else if (DSA != null)
525 return VerifySignature (DSA);
526 else
527 return false; // e.g. a certificate with only DSA parameters
528 }
529 catch (CryptographicException) {
530 return false;
531 }
532 }
533 }
534
535 public ASN1 GetIssuerName ()
536 {
537 return issuer;
538 }
539
540 public ASN1 GetSubjectName ()
541 {
542 return subject;
543 }
544
545 protected X509Certificate (SerializationInfo info, StreamingContext context)
546 {
547 Parse ((byte[]) info.GetValue ("raw", typeof (byte[])));
548 }
549
550 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
551 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
552 {
553 info.AddValue ("raw", m_encodedcert);
554 // note: we NEVER serialize the private key
555 }
556
557 static byte[] PEM (string type, byte[] data)
558 {
559 string pem = Encoding.ASCII.GetString (data);
560 string header = String.Format ("-----BEGIN {0}-----", type);
561 string footer = String.Format ("-----END {0}-----", type);
562 int start = pem.IndexOf (header) + header.Length;
563 int end = pem.IndexOf (footer, start);
564 string base64 = pem.Substring (start, (end - start));
565 return Convert.FromBase64String (base64);
566 }
567 }
568 }