x509_cert_parser.c 16 KB

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