X509Certificate.cs 17 KB

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