X509Certificate.cs 17 KB

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