x509_cert_parser.c 16 KB

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