x509_cert_parser.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /* X.509 certificate parser
  2. *
  3. * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
  4. * Written by David Howells (dhowells@redhat.com)
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public Licence
  8. * as published by the Free Software Foundation; either version
  9. * 2 of the Licence, or (at your option) any later version.
  10. */
  11. #define pr_fmt(fmt) "X.509: "fmt
  12. #include <linux/kernel.h>
  13. #include <linux/export.h>
  14. #include <linux/slab.h>
  15. #include <linux/err.h>
  16. #include <linux/oid_registry.h>
  17. #include <crypto/public_key.h>
  18. #include "x509_parser.h"
  19. #include "x509-asn1.h"
  20. #include "x509_akid-asn1.h"
  21. struct x509_parse_context {
  22. struct x509_certificate *cert; /* Certificate being constructed */
  23. unsigned long data; /* Start of data */
  24. const void *cert_start; /* Start of cert content */
  25. const void *key; /* Key data */
  26. size_t key_size; /* Size of key data */
  27. enum OID last_oid; /* Last OID encountered */
  28. enum OID algo_oid; /* Algorithm OID */
  29. unsigned char nr_mpi; /* Number of MPIs stored */
  30. u8 o_size; /* Size of organizationName (O) */
  31. u8 cn_size; /* Size of commonName (CN) */
  32. u8 email_size; /* Size of emailAddress */
  33. u16 o_offset; /* Offset of organizationName (O) */
  34. u16 cn_offset; /* Offset of commonName (CN) */
  35. u16 email_offset; /* Offset of emailAddress */
  36. unsigned raw_akid_size;
  37. const void *raw_akid; /* Raw authorityKeyId in ASN.1 */
  38. const void *akid_raw_issuer; /* Raw directoryName in authorityKeyId */
  39. unsigned akid_raw_issuer_size;
  40. };
  41. /*
  42. * Free an X.509 certificate
  43. */
  44. void x509_free_certificate(struct x509_certificate *cert)
  45. {
  46. if (cert) {
  47. public_key_free(cert->pub);
  48. public_key_signature_free(cert->sig);
  49. kfree(cert->issuer);
  50. kfree(cert->subject);
  51. kfree(cert->id);
  52. kfree(cert->skid);
  53. kfree(cert);
  54. }
  55. }
  56. EXPORT_SYMBOL_GPL(x509_free_certificate);
  57. /*
  58. * Parse an X.509 certificate
  59. */
  60. struct x509_certificate *x509_cert_parse(const void *data, size_t datalen)
  61. {
  62. struct x509_certificate *cert;
  63. struct x509_parse_context *ctx;
  64. struct asymmetric_key_id *kid;
  65. long ret;
  66. ret = -ENOMEM;
  67. cert = kzalloc(sizeof(struct x509_certificate), GFP_KERNEL);
  68. if (!cert)
  69. goto error_no_cert;
  70. cert->pub = kzalloc(sizeof(struct public_key), GFP_KERNEL);
  71. if (!cert->pub)
  72. goto error_no_ctx;
  73. cert->sig = kzalloc(sizeof(struct public_key_signature), GFP_KERNEL);
  74. if (!cert->sig)
  75. goto error_no_ctx;
  76. ctx = kzalloc(sizeof(struct x509_parse_context), GFP_KERNEL);
  77. if (!ctx)
  78. goto error_no_ctx;
  79. ctx->cert = cert;
  80. ctx->data = (unsigned long)data;
  81. /* Attempt to decode the certificate */
  82. ret = asn1_ber_decoder(&x509_decoder, ctx, data, datalen);
  83. if (ret < 0)
  84. goto error_decode;
  85. /* Decode the AuthorityKeyIdentifier */
  86. if (ctx->raw_akid) {
  87. pr_devel("AKID: %u %*phN\n",
  88. ctx->raw_akid_size, ctx->raw_akid_size, ctx->raw_akid);
  89. ret = asn1_ber_decoder(&x509_akid_decoder, ctx,
  90. ctx->raw_akid, ctx->raw_akid_size);
  91. if (ret < 0) {
  92. pr_warn("Couldn't decode AuthKeyIdentifier\n");
  93. goto error_decode;
  94. }
  95. }
  96. cert->pub->key = kmemdup(ctx->key, ctx->key_size, GFP_KERNEL);
  97. if (!cert->pub->key)
  98. goto error_decode;
  99. cert->pub->keylen = ctx->key_size;
  100. /* Grab the signature bits */
  101. ret = x509_get_sig_params(cert);
  102. if (ret < 0)
  103. goto error_decode;
  104. /* Generate cert issuer + serial number key ID */
  105. kid = asymmetric_key_generate_id(cert->raw_serial,
  106. cert->raw_serial_size,
  107. cert->raw_issuer,
  108. cert->raw_issuer_size);
  109. if (IS_ERR(kid)) {
  110. ret = PTR_ERR(kid);
  111. goto error_decode;
  112. }
  113. cert->id = kid;
  114. /* Detect self-signed certificates */
  115. ret = x509_check_for_self_signed(cert);
  116. if (ret < 0)
  117. goto error_decode;
  118. kfree(ctx);
  119. return cert;
  120. error_decode:
  121. kfree(ctx);
  122. error_no_ctx:
  123. x509_free_certificate(cert);
  124. error_no_cert:
  125. return ERR_PTR(ret);
  126. }
  127. EXPORT_SYMBOL_GPL(x509_cert_parse);
  128. /*
  129. * Note an OID when we find one for later processing when we know how
  130. * to interpret it.
  131. */
  132. int x509_note_OID(void *context, size_t hdrlen,
  133. unsigned char tag,
  134. const void *value, size_t vlen)
  135. {
  136. struct x509_parse_context *ctx = context;
  137. ctx->last_oid = look_up_OID(value, vlen);
  138. if (ctx->last_oid == OID__NR) {
  139. char buffer[50];
  140. sprint_oid(value, vlen, buffer, sizeof(buffer));
  141. pr_debug("Unknown OID: [%lu] %s\n",
  142. (unsigned long)value - ctx->data, buffer);
  143. }
  144. return 0;
  145. }
  146. /*
  147. * Save the position of the TBS data so that we can check the signature over it
  148. * later.
  149. */
  150. int x509_note_tbs_certificate(void *context, size_t hdrlen,
  151. unsigned char tag,
  152. const void *value, size_t vlen)
  153. {
  154. struct x509_parse_context *ctx = context;
  155. pr_debug("x509_note_tbs_certificate(,%zu,%02x,%ld,%zu)!\n",
  156. hdrlen, tag, (unsigned long)value - ctx->data, vlen);
  157. ctx->cert->tbs = value - hdrlen;
  158. ctx->cert->tbs_size = vlen + hdrlen;
  159. return 0;
  160. }
  161. /*
  162. * Record the public key algorithm
  163. */
  164. int x509_note_pkey_algo(void *context, size_t hdrlen,
  165. unsigned char tag,
  166. const void *value, size_t vlen)
  167. {
  168. struct x509_parse_context *ctx = context;
  169. pr_debug("PubKey Algo: %u\n", ctx->last_oid);
  170. switch (ctx->last_oid) {
  171. case OID_md2WithRSAEncryption:
  172. case OID_md3WithRSAEncryption:
  173. default:
  174. return -ENOPKG; /* Unsupported combination */
  175. case OID_md4WithRSAEncryption:
  176. ctx->cert->sig->hash_algo = "md4";
  177. ctx->cert->sig->pkey_algo = "rsa";
  178. break;
  179. case OID_sha1WithRSAEncryption:
  180. ctx->cert->sig->hash_algo = "sha1";
  181. ctx->cert->sig->pkey_algo = "rsa";
  182. break;
  183. case OID_sha256WithRSAEncryption:
  184. ctx->cert->sig->hash_algo = "sha256";
  185. ctx->cert->sig->pkey_algo = "rsa";
  186. break;
  187. case OID_sha384WithRSAEncryption:
  188. ctx->cert->sig->hash_algo = "sha384";
  189. ctx->cert->sig->pkey_algo = "rsa";
  190. break;
  191. case OID_sha512WithRSAEncryption:
  192. ctx->cert->sig->hash_algo = "sha512";
  193. ctx->cert->sig->pkey_algo = "rsa";
  194. break;
  195. case OID_sha224WithRSAEncryption:
  196. ctx->cert->sig->hash_algo = "sha224";
  197. ctx->cert->sig->pkey_algo = "rsa";
  198. break;
  199. }
  200. ctx->algo_oid = ctx->last_oid;
  201. return 0;
  202. }
  203. /*
  204. * Note the whereabouts and type of the signature.
  205. */
  206. int x509_note_signature(void *context, size_t hdrlen,
  207. unsigned char tag,
  208. const void *value, size_t vlen)
  209. {
  210. struct x509_parse_context *ctx = context;
  211. pr_debug("Signature type: %u size %zu\n", ctx->last_oid, vlen);
  212. if (ctx->last_oid != ctx->algo_oid) {
  213. pr_warn("Got cert with pkey (%u) and sig (%u) algorithm OIDs\n",
  214. ctx->algo_oid, ctx->last_oid);
  215. return -EINVAL;
  216. }
  217. ctx->cert->raw_sig = value;
  218. ctx->cert->raw_sig_size = vlen;
  219. return 0;
  220. }
  221. /*
  222. * Note the certificate serial number
  223. */
  224. int x509_note_serial(void *context, size_t hdrlen,
  225. unsigned char tag,
  226. const void *value, size_t vlen)
  227. {
  228. struct x509_parse_context *ctx = context;
  229. ctx->cert->raw_serial = value;
  230. ctx->cert->raw_serial_size = vlen;
  231. return 0;
  232. }
  233. /*
  234. * Note some of the name segments from which we'll fabricate a name.
  235. */
  236. int x509_extract_name_segment(void *context, size_t hdrlen,
  237. unsigned char tag,
  238. const void *value, size_t vlen)
  239. {
  240. struct x509_parse_context *ctx = context;
  241. switch (ctx->last_oid) {
  242. case OID_commonName:
  243. ctx->cn_size = vlen;
  244. ctx->cn_offset = (unsigned long)value - ctx->data;
  245. break;
  246. case OID_organizationName:
  247. ctx->o_size = vlen;
  248. ctx->o_offset = (unsigned long)value - ctx->data;
  249. break;
  250. case OID_email_address:
  251. ctx->email_size = vlen;
  252. ctx->email_offset = (unsigned long)value - ctx->data;
  253. break;
  254. default:
  255. break;
  256. }
  257. return 0;
  258. }
  259. /*
  260. * Fabricate and save the issuer and subject names
  261. */
  262. static int x509_fabricate_name(struct x509_parse_context *ctx, size_t hdrlen,
  263. unsigned char tag,
  264. char **_name, size_t vlen)
  265. {
  266. const void *name, *data = (const void *)ctx->data;
  267. size_t namesize;
  268. char *buffer;
  269. if (*_name)
  270. return -EINVAL;
  271. /* Empty name string if no material */
  272. if (!ctx->cn_size && !ctx->o_size && !ctx->email_size) {
  273. buffer = kmalloc(1, GFP_KERNEL);
  274. if (!buffer)
  275. return -ENOMEM;
  276. buffer[0] = 0;
  277. goto done;
  278. }
  279. if (ctx->cn_size && ctx->o_size) {
  280. /* Consider combining O and CN, but use only the CN if it is
  281. * prefixed by the O, or a significant portion thereof.
  282. */
  283. namesize = ctx->cn_size;
  284. name = data + ctx->cn_offset;
  285. if (ctx->cn_size >= ctx->o_size &&
  286. memcmp(data + ctx->cn_offset, data + ctx->o_offset,
  287. ctx->o_size) == 0)
  288. goto single_component;
  289. if (ctx->cn_size >= 7 &&
  290. ctx->o_size >= 7 &&
  291. memcmp(data + ctx->cn_offset, data + ctx->o_offset, 7) == 0)
  292. goto single_component;
  293. buffer = kmalloc(ctx->o_size + 2 + ctx->cn_size + 1,
  294. GFP_KERNEL);
  295. if (!buffer)
  296. return -ENOMEM;
  297. memcpy(buffer,
  298. data + ctx->o_offset, ctx->o_size);
  299. buffer[ctx->o_size + 0] = ':';
  300. buffer[ctx->o_size + 1] = ' ';
  301. memcpy(buffer + ctx->o_size + 2,
  302. data + ctx->cn_offset, ctx->cn_size);
  303. buffer[ctx->o_size + 2 + ctx->cn_size] = 0;
  304. goto done;
  305. } else if (ctx->cn_size) {
  306. namesize = ctx->cn_size;
  307. name = data + ctx->cn_offset;
  308. } else if (ctx->o_size) {
  309. namesize = ctx->o_size;
  310. name = data + ctx->o_offset;
  311. } else {
  312. namesize = ctx->email_size;
  313. name = data + ctx->email_offset;
  314. }
  315. single_component:
  316. buffer = kmalloc(namesize + 1, GFP_KERNEL);
  317. if (!buffer)
  318. return -ENOMEM;
  319. memcpy(buffer, name, namesize);
  320. buffer[namesize] = 0;
  321. done:
  322. *_name = buffer;
  323. ctx->cn_size = 0;
  324. ctx->o_size = 0;
  325. ctx->email_size = 0;
  326. return 0;
  327. }
  328. int x509_note_issuer(void *context, size_t hdrlen,
  329. unsigned char tag,
  330. const void *value, size_t vlen)
  331. {
  332. struct x509_parse_context *ctx = context;
  333. ctx->cert->raw_issuer = value;
  334. ctx->cert->raw_issuer_size = vlen;
  335. return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->issuer, vlen);
  336. }
  337. int x509_note_subject(void *context, size_t hdrlen,
  338. unsigned char tag,
  339. const void *value, size_t vlen)
  340. {
  341. struct x509_parse_context *ctx = context;
  342. ctx->cert->raw_subject = value;
  343. ctx->cert->raw_subject_size = vlen;
  344. return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->subject, vlen);
  345. }
  346. /*
  347. * Extract the data for the public key algorithm
  348. */
  349. int x509_extract_key_data(void *context, size_t hdrlen,
  350. unsigned char tag,
  351. const void *value, size_t vlen)
  352. {
  353. struct x509_parse_context *ctx = context;
  354. if (ctx->last_oid != OID_rsaEncryption)
  355. return -ENOPKG;
  356. ctx->cert->pub->pkey_algo = "rsa";
  357. /* Discard the BIT STRING metadata */
  358. ctx->key = value + 1;
  359. ctx->key_size = vlen - 1;
  360. return 0;
  361. }
  362. /* The keyIdentifier in AuthorityKeyIdentifier SEQUENCE is tag(CONT,PRIM,0) */
  363. #define SEQ_TAG_KEYID (ASN1_CONT << 6)
  364. /*
  365. * Process certificate extensions that are used to qualify the certificate.
  366. */
  367. int x509_process_extension(void *context, size_t hdrlen,
  368. unsigned char tag,
  369. const void *value, size_t vlen)
  370. {
  371. struct x509_parse_context *ctx = context;
  372. struct asymmetric_key_id *kid;
  373. const unsigned char *v = value;
  374. pr_debug("Extension: %u\n", ctx->last_oid);
  375. if (ctx->last_oid == OID_subjectKeyIdentifier) {
  376. /* Get hold of the key fingerprint */
  377. if (ctx->cert->skid || vlen < 3)
  378. return -EBADMSG;
  379. if (v[0] != ASN1_OTS || v[1] != vlen - 2)
  380. return -EBADMSG;
  381. v += 2;
  382. vlen -= 2;
  383. ctx->cert->raw_skid_size = vlen;
  384. ctx->cert->raw_skid = v;
  385. kid = asymmetric_key_generate_id(v, vlen, "", 0);
  386. if (IS_ERR(kid))
  387. return PTR_ERR(kid);
  388. ctx->cert->skid = kid;
  389. pr_debug("subjkeyid %*phN\n", kid->len, kid->data);
  390. return 0;
  391. }
  392. if (ctx->last_oid == OID_authorityKeyIdentifier) {
  393. /* Get hold of the CA key fingerprint */
  394. ctx->raw_akid = v;
  395. ctx->raw_akid_size = vlen;
  396. return 0;
  397. }
  398. return 0;
  399. }
  400. /**
  401. * x509_decode_time - Decode an X.509 time ASN.1 object
  402. * @_t: The time to fill in
  403. * @hdrlen: The length of the object header
  404. * @tag: The object tag
  405. * @value: The object value
  406. * @vlen: The size of the object value
  407. *
  408. * Decode an ASN.1 universal time or generalised time field into a struct the
  409. * kernel can handle and check it for validity. The time is decoded thus:
  410. *
  411. * [RFC5280 §4.1.2.5]
  412. * CAs conforming to this profile MUST always encode certificate validity
  413. * dates through the year 2049 as UTCTime; certificate validity dates in
  414. * 2050 or later MUST be encoded as GeneralizedTime. Conforming
  415. * applications MUST be able to process validity dates that are encoded in
  416. * either UTCTime or GeneralizedTime.
  417. */
  418. int x509_decode_time(time64_t *_t, size_t hdrlen,
  419. unsigned char tag,
  420. const unsigned char *value, size_t vlen)
  421. {
  422. static const unsigned char month_lengths[] = { 31, 28, 31, 30, 31, 30,
  423. 31, 31, 30, 31, 30, 31 };
  424. const unsigned char *p = value;
  425. unsigned year, mon, day, hour, min, sec, mon_len;
  426. #define dec2bin(X) ({ unsigned char x = (X) - '0'; if (x > 9) goto invalid_time; x; })
  427. #define DD2bin(P) ({ unsigned x = dec2bin(P[0]) * 10 + dec2bin(P[1]); P += 2; x; })
  428. if (tag == ASN1_UNITIM) {
  429. /* UTCTime: YYMMDDHHMMSSZ */
  430. if (vlen != 13)
  431. goto unsupported_time;
  432. year = DD2bin(p);
  433. if (year >= 50)
  434. year += 1900;
  435. else
  436. year += 2000;
  437. } else if (tag == ASN1_GENTIM) {
  438. /* GenTime: YYYYMMDDHHMMSSZ */
  439. if (vlen != 15)
  440. goto unsupported_time;
  441. year = DD2bin(p) * 100 + DD2bin(p);
  442. if (year >= 1950 && year <= 2049)
  443. goto invalid_time;
  444. } else {
  445. goto unsupported_time;
  446. }
  447. mon = DD2bin(p);
  448. day = DD2bin(p);
  449. hour = DD2bin(p);
  450. min = DD2bin(p);
  451. sec = DD2bin(p);
  452. if (*p != 'Z')
  453. goto unsupported_time;
  454. if (year < 1970 ||
  455. mon < 1 || mon > 12)
  456. goto invalid_time;
  457. mon_len = month_lengths[mon - 1];
  458. if (mon == 2) {
  459. if (year % 4 == 0) {
  460. mon_len = 29;
  461. if (year % 100 == 0) {
  462. mon_len = 28;
  463. if (year % 400 == 0)
  464. mon_len = 29;
  465. }
  466. }
  467. }
  468. if (day < 1 || day > mon_len ||
  469. hour > 24 || /* ISO 8601 permits 24:00:00 as midnight tomorrow */
  470. min > 59 ||
  471. sec > 60) /* ISO 8601 permits leap seconds [X.680 46.3] */
  472. goto invalid_time;
  473. *_t = mktime64(year, mon, day, hour, min, sec);
  474. return 0;
  475. unsupported_time:
  476. pr_debug("Got unsupported time [tag %02x]: '%*phN'\n",
  477. tag, (int)vlen, value);
  478. return -EBADMSG;
  479. invalid_time:
  480. pr_debug("Got invalid time [tag %02x]: '%*phN'\n",
  481. tag, (int)vlen, value);
  482. return -EBADMSG;
  483. }
  484. EXPORT_SYMBOL_GPL(x509_decode_time);
  485. int x509_note_not_before(void *context, size_t hdrlen,
  486. unsigned char tag,
  487. const void *value, size_t vlen)
  488. {
  489. struct x509_parse_context *ctx = context;
  490. return x509_decode_time(&ctx->cert->valid_from, hdrlen, tag, value, vlen);
  491. }
  492. int x509_note_not_after(void *context, size_t hdrlen,
  493. unsigned char tag,
  494. const void *value, size_t vlen)
  495. {
  496. struct x509_parse_context *ctx = context;
  497. return x509_decode_time(&ctx->cert->valid_to, hdrlen, tag, value, vlen);
  498. }
  499. /*
  500. * Note a key identifier-based AuthorityKeyIdentifier
  501. */
  502. int x509_akid_note_kid(void *context, size_t hdrlen,
  503. unsigned char tag,
  504. const void *value, size_t vlen)
  505. {
  506. struct x509_parse_context *ctx = context;
  507. struct asymmetric_key_id *kid;
  508. pr_debug("AKID: keyid: %*phN\n", (int)vlen, value);
  509. if (ctx->cert->sig->auth_ids[1])
  510. return 0;
  511. kid = asymmetric_key_generate_id(value, vlen, "", 0);
  512. if (IS_ERR(kid))
  513. return PTR_ERR(kid);
  514. pr_debug("authkeyid %*phN\n", kid->len, kid->data);
  515. ctx->cert->sig->auth_ids[1] = kid;
  516. return 0;
  517. }
  518. /*
  519. * Note a directoryName in an AuthorityKeyIdentifier
  520. */
  521. int x509_akid_note_name(void *context, size_t hdrlen,
  522. unsigned char tag,
  523. const void *value, size_t vlen)
  524. {
  525. struct x509_parse_context *ctx = context;
  526. pr_debug("AKID: name: %*phN\n", (int)vlen, value);
  527. ctx->akid_raw_issuer = value;
  528. ctx->akid_raw_issuer_size = vlen;
  529. return 0;
  530. }
  531. /*
  532. * Note a serial number in an AuthorityKeyIdentifier
  533. */
  534. int x509_akid_note_serial(void *context, size_t hdrlen,
  535. unsigned char tag,
  536. const void *value, size_t vlen)
  537. {
  538. struct x509_parse_context *ctx = context;
  539. struct asymmetric_key_id *kid;
  540. pr_debug("AKID: serial: %*phN\n", (int)vlen, value);
  541. if (!ctx->akid_raw_issuer || ctx->cert->sig->auth_ids[0])
  542. return 0;
  543. kid = asymmetric_key_generate_id(value,
  544. vlen,
  545. ctx->akid_raw_issuer,
  546. ctx->akid_raw_issuer_size);
  547. if (IS_ERR(kid))
  548. return PTR_ERR(kid);
  549. pr_debug("authkeyid %*phN\n", kid->len, kid->data);
  550. ctx->cert->sig->auth_ids[0] = kid;
  551. return 0;
  552. }