X509Certificate.cs 17 KB

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