cert.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. /*
  2. * Embedded Linux library
  3. *
  4. * Copyright (C) 2018 Intel Corporation. All rights reserved.
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #ifdef HAVE_CONFIG_H
  21. #include <config.h>
  22. #endif
  23. #include <string.h>
  24. #include <stdio.h>
  25. #include <errno.h>
  26. #include "private.h"
  27. #include "useful.h"
  28. #include "key.h"
  29. #include "queue.h"
  30. #include "asn1-private.h"
  31. #include "cipher.h"
  32. #include "pem-private.h"
  33. #include "cert.h"
  34. #include "cert-private.h"
  35. #include "tls.h"
  36. #include "tls-private.h"
  37. #include "missing.h"
  38. #define X509_CERTIFICATE_POS 0
  39. #define X509_TBSCERTIFICATE_POS 0
  40. #define X509_TBSCERT_VERSION_POS ASN1_CONTEXT_EXPLICIT(0)
  41. #define X509_TBSCERT_SERIAL_POS 0
  42. #define X509_TBSCERT_SIGNATURE_POS 1
  43. #define X509_ALGORITHM_ID_ALGORITHM_POS 0
  44. #define X509_ALGORITHM_ID_PARAMS_POS 1
  45. #define X509_TBSCERT_ISSUER_DN_POS 2
  46. #define X509_TBSCERT_VALIDITY_POS 3
  47. #define X509_TBSCERT_SUBJECT_DN_POS 4
  48. #define X509_TBSCERT_SUBJECT_KEY_POS 5
  49. #define X509_SUBJECT_KEY_ALGORITHM_POS 0
  50. #define X509_SUBJECT_KEY_VALUE_POS 1
  51. #define X509_TBSCERT_ISSUER_UID_POS ASN1_CONTEXT_IMPLICIT(1)
  52. #define X509_TBSCERT_SUBJECT_UID_POS ASN1_CONTEXT_IMPLICIT(2)
  53. #define X509_TBSCERT_EXTENSIONS_POS ASN1_CONTEXT_EXPLICIT(3)
  54. #define X509_SIGNATURE_ALGORITHM_POS 1
  55. #define X509_SIGNATURE_VALUE_POS 2
  56. struct l_cert {
  57. enum l_cert_key_type pubkey_type;
  58. struct l_cert *issuer;
  59. struct l_cert *issued;
  60. size_t asn1_len;
  61. uint8_t asn1[0];
  62. };
  63. struct l_certchain {
  64. struct l_cert *leaf; /* Bottom of the doubly-linked list */
  65. struct l_cert *ca; /* Top of the doubly-linked list */
  66. };
  67. static const struct pkcs1_encryption_oid {
  68. enum l_cert_key_type key_type;
  69. struct asn1_oid oid;
  70. } pkcs1_encryption_oids[] = {
  71. { /* rsaEncryption */
  72. L_CERT_KEY_RSA,
  73. { 9, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 } },
  74. },
  75. };
  76. static bool cert_set_pubkey_type(struct l_cert *cert)
  77. {
  78. const uint8_t *key_type;
  79. size_t key_type_len;
  80. int i;
  81. key_type = asn1_der_find_elem_by_path(cert->asn1, cert->asn1_len,
  82. ASN1_ID_OID, &key_type_len,
  83. X509_CERTIFICATE_POS,
  84. X509_TBSCERTIFICATE_POS,
  85. X509_TBSCERT_SUBJECT_KEY_POS,
  86. X509_SUBJECT_KEY_ALGORITHM_POS,
  87. X509_ALGORITHM_ID_ALGORITHM_POS,
  88. -1);
  89. if (!key_type)
  90. return false;
  91. for (i = 0; i < (int) L_ARRAY_SIZE(pkcs1_encryption_oids); i++)
  92. if (asn1_oid_eq(&pkcs1_encryption_oids[i].oid,
  93. key_type_len, key_type))
  94. break;
  95. if (i == L_ARRAY_SIZE(pkcs1_encryption_oids))
  96. cert->pubkey_type = L_CERT_KEY_UNKNOWN;
  97. else
  98. cert->pubkey_type = pkcs1_encryption_oids[i].key_type;
  99. return true;
  100. }
  101. LIB_EXPORT struct l_cert *l_cert_new_from_der(const uint8_t *buf,
  102. size_t buf_len)
  103. {
  104. const uint8_t *seq = buf;
  105. size_t seq_len = buf_len;
  106. size_t content_len;
  107. struct l_cert *cert;
  108. /* Sanity check: outer element is a SEQUENCE */
  109. if (seq_len-- < 1 || *seq++ != ASN1_ID_SEQUENCE)
  110. return NULL;
  111. /* Sanity check: the SEQUENCE spans the whole buffer */
  112. content_len = asn1_parse_definite_length(&seq, &seq_len);
  113. if (content_len < 64 || content_len != seq_len)
  114. return NULL;
  115. /*
  116. * We could require the signature algorithm and the key algorithm
  117. * to be one of our supported types here but instead we only
  118. * require that when the user wants to verify this certificate or
  119. * get the public key respectively.
  120. */
  121. cert = l_malloc(sizeof(struct l_cert) + buf_len);
  122. cert->issuer = NULL;
  123. cert->issued = NULL;
  124. cert->asn1_len = buf_len;
  125. memcpy(cert->asn1, buf, buf_len);
  126. /* Sanity check: structure is correct up to the Public Key Algorithm */
  127. if (!cert_set_pubkey_type(cert)) {
  128. l_free(cert);
  129. return NULL;
  130. }
  131. return cert;
  132. }
  133. LIB_EXPORT void l_cert_free(struct l_cert *cert)
  134. {
  135. l_free(cert);
  136. }
  137. LIB_EXPORT const uint8_t *l_cert_get_der_data(struct l_cert *cert,
  138. size_t *out_len)
  139. {
  140. if (unlikely(!cert))
  141. return NULL;
  142. *out_len = cert->asn1_len;
  143. return cert->asn1;
  144. }
  145. LIB_EXPORT const uint8_t *l_cert_get_dn(struct l_cert *cert, size_t *out_len)
  146. {
  147. if (unlikely(!cert))
  148. return NULL;
  149. return asn1_der_find_elem_by_path(cert->asn1, cert->asn1_len,
  150. ASN1_ID_SEQUENCE, out_len,
  151. X509_CERTIFICATE_POS,
  152. X509_TBSCERTIFICATE_POS,
  153. X509_TBSCERT_SUBJECT_DN_POS,
  154. -1);
  155. }
  156. const uint8_t *cert_get_extension(struct l_cert *cert,
  157. const struct asn1_oid *ext_id,
  158. bool *out_critical, size_t *out_len)
  159. {
  160. const uint8_t *ext, *end;
  161. size_t ext_len;
  162. if (unlikely(!cert))
  163. return NULL;
  164. ext = asn1_der_find_elem_by_path(cert->asn1, cert->asn1_len,
  165. ASN1_ID_SEQUENCE, &ext_len,
  166. X509_CERTIFICATE_POS,
  167. X509_TBSCERTIFICATE_POS,
  168. X509_TBSCERT_EXTENSIONS_POS,
  169. -1);
  170. if (unlikely(!ext))
  171. return NULL;
  172. end = ext + ext_len;
  173. while (ext < end) {
  174. const uint8_t *seq, *oid, *data;
  175. uint8_t tag;
  176. size_t len, oid_len, data_len;
  177. bool critical;
  178. seq = asn1_der_find_elem(ext, end - ext, 0, &tag, &len);
  179. if (unlikely(!seq || tag != ASN1_ID_SEQUENCE))
  180. return false;
  181. ext = seq + len;
  182. oid = asn1_der_find_elem(seq, len, 0, &tag, &oid_len);
  183. if (unlikely(!oid || tag != ASN1_ID_OID))
  184. return false;
  185. if (!asn1_oid_eq(ext_id, oid_len, oid))
  186. continue;
  187. data = asn1_der_find_elem(seq, len, 1, &tag, &data_len);
  188. critical = false;
  189. if (data && tag == ASN1_ID_BOOLEAN) {
  190. if (data_len != 1)
  191. return false;
  192. critical = *data != 0; /* Tolerate BER booleans */
  193. data = asn1_der_find_elem(seq, len, 2, &tag, &data_len);
  194. }
  195. if (unlikely(!data || tag != ASN1_ID_OCTET_STRING))
  196. return false;
  197. if (out_critical)
  198. *out_critical = critical;
  199. if (out_len)
  200. *out_len = data_len;
  201. return data;
  202. }
  203. return NULL;
  204. }
  205. LIB_EXPORT enum l_cert_key_type l_cert_get_pubkey_type(struct l_cert *cert)
  206. {
  207. if (unlikely(!cert))
  208. return L_CERT_KEY_UNKNOWN;
  209. return cert->pubkey_type;
  210. }
  211. /*
  212. * Note: Returns a new l_key object to be freed by the caller.
  213. */
  214. LIB_EXPORT struct l_key *l_cert_get_pubkey(struct l_cert *cert)
  215. {
  216. if (unlikely(!cert))
  217. return NULL;
  218. /* Use kernel's ASN.1 certificate parser to find the key data for us */
  219. if (cert->pubkey_type == L_CERT_KEY_RSA)
  220. return l_key_new(L_KEY_RSA, cert->asn1, cert->asn1_len);
  221. return NULL;
  222. }
  223. /*
  224. * Note: takes ownership of the certificate. The certificate is
  225. * assumed to be new and not linked into any certchain object.
  226. */
  227. struct l_certchain *certchain_new_from_leaf(struct l_cert *leaf)
  228. {
  229. struct l_certchain *chain;
  230. chain = l_new(struct l_certchain, 1);
  231. chain->leaf = leaf;
  232. chain->ca = leaf;
  233. return chain;
  234. }
  235. /*
  236. * Note: takes ownership of the certificate. The certificate is
  237. * assumed to be new and not linked into any certchain object.
  238. */
  239. void certchain_link_issuer(struct l_certchain *chain, struct l_cert *ca)
  240. {
  241. ca->issued = chain->ca;
  242. chain->ca->issuer = ca;
  243. chain->ca = ca;
  244. }
  245. static struct l_cert *certchain_pop_ca(struct l_certchain *chain)
  246. {
  247. struct l_cert *ca = chain->ca;
  248. if (!ca)
  249. return NULL;
  250. if (ca->issued) {
  251. chain->ca = ca->issued;
  252. ca->issued->issuer = NULL;
  253. ca->issued = NULL;
  254. } else {
  255. chain->ca = NULL;
  256. chain->leaf = NULL;
  257. }
  258. return ca;
  259. }
  260. LIB_EXPORT void l_certchain_free(struct l_certchain *chain)
  261. {
  262. while (chain && chain->ca)
  263. l_cert_free(certchain_pop_ca(chain));
  264. l_free(chain);
  265. }
  266. LIB_EXPORT struct l_cert *l_certchain_get_leaf(struct l_certchain *chain)
  267. {
  268. if (unlikely(!chain))
  269. return NULL;
  270. return chain->leaf;
  271. }
  272. /*
  273. * Call @cb for each certificate in the chain starting from the leaf
  274. * certificate. Stop if a call returns @true.
  275. */
  276. LIB_EXPORT void l_certchain_walk_from_leaf(struct l_certchain *chain,
  277. l_cert_walk_cb_t cb,
  278. void *user_data)
  279. {
  280. struct l_cert *cert;
  281. if (unlikely(!chain))
  282. return;
  283. for (cert = chain->leaf; cert; cert = cert->issuer)
  284. if (cb(cert, user_data))
  285. break;
  286. }
  287. /*
  288. * Call @cb for each certificate in the chain starting from the root
  289. * certificate. Stop if a call returns @true.
  290. */
  291. LIB_EXPORT void l_certchain_walk_from_ca(struct l_certchain *chain,
  292. l_cert_walk_cb_t cb,
  293. void *user_data)
  294. {
  295. struct l_cert *cert;
  296. if (unlikely(!chain))
  297. return;
  298. for (cert = chain->ca; cert; cert = cert->issued)
  299. if (cb(cert, user_data))
  300. break;
  301. }
  302. static struct l_keyring *cert_set_to_keyring(struct l_queue *certs, char *error)
  303. {
  304. struct l_keyring *ring;
  305. const struct l_queue_entry *entry;
  306. int i = 1;
  307. ring = l_keyring_new();
  308. if (!ring)
  309. return NULL;
  310. for (entry = l_queue_get_entries(certs); entry; entry = entry->next) {
  311. struct l_cert *cert = entry->data;
  312. struct l_key *key = l_cert_get_pubkey(cert);
  313. if (!key) {
  314. sprintf(error, "Can't get public key from certificate "
  315. "%i / %i in certificate set", i,
  316. l_queue_length(certs));
  317. goto cleanup;
  318. }
  319. if (!l_keyring_link(ring, key)) {
  320. l_key_free(key);
  321. sprintf(error, "Can't link the public key from "
  322. "certificate %i / %i to target keyring",
  323. i, l_queue_length(certs));
  324. goto cleanup;
  325. }
  326. l_key_free_norevoke(key);
  327. i++;
  328. }
  329. return ring;
  330. cleanup:
  331. l_keyring_free(ring);
  332. return NULL;
  333. }
  334. static bool cert_is_in_set(struct l_cert *cert, struct l_queue *set)
  335. {
  336. const struct l_queue_entry *entry;
  337. for (entry = l_queue_get_entries(set); entry; entry = entry->next) {
  338. struct l_cert *cert2 = entry->data;
  339. if (cert == cert2)
  340. return true;
  341. if (cert->asn1_len == cert2->asn1_len &&
  342. !memcmp(cert->asn1, cert2->asn1,
  343. cert->asn1_len))
  344. return true;
  345. }
  346. return false;
  347. }
  348. static struct l_key *cert_try_link(struct l_cert *cert, struct l_keyring *ring)
  349. {
  350. struct l_key *key;
  351. key = l_key_new(L_KEY_RSA, cert->asn1, cert->asn1_len);
  352. if (!key)
  353. return NULL;
  354. if (l_keyring_link(ring, key))
  355. return key;
  356. l_key_free(key);
  357. return NULL;
  358. }
  359. #define RETURN_ERROR(msg, args...) \
  360. do { \
  361. if (error) { \
  362. *error = error_buf; \
  363. snprintf(error_buf, sizeof(error_buf), msg, ## args); \
  364. } \
  365. return false; \
  366. } while (0)
  367. LIB_EXPORT bool l_certchain_verify(struct l_certchain *chain,
  368. struct l_queue *ca_certs,
  369. const char **error)
  370. {
  371. struct l_keyring *ca_ring = NULL;
  372. _auto_(l_keyring_free) struct l_keyring *verify_ring = NULL;
  373. struct l_cert *cert;
  374. struct l_key *prev_key = NULL;
  375. int verified = 0;
  376. int ca_match = 0;
  377. int i = 0;
  378. static char error_buf[200];
  379. if (unlikely(!chain || !chain->leaf))
  380. RETURN_ERROR("Chain empty");
  381. verify_ring = l_keyring_new();
  382. if (!verify_ring)
  383. RETURN_ERROR("Can't create verify keyring");
  384. for (cert = chain->ca; cert; cert = cert->issued, i++)
  385. if (cert_is_in_set(cert, ca_certs)) {
  386. ca_match = i + 1;
  387. break;
  388. }
  389. cert = chain->ca;
  390. /*
  391. * For TLS compatibility the trusted root CA certificate is
  392. * optionally present in the chain.
  393. *
  394. * RFC5246 7.4.2:
  395. * "Because certificate validation requires that root keys be
  396. * distributed independently, the self-signed certificate that
  397. * specifies the root certificate authority MAY be omitted from
  398. * the chain, under the assumption that the remote end must
  399. * already possess it in order to validate it in any case."
  400. *
  401. * The following is an optimization to skip verifying the root
  402. * cert in the chain if it is bitwise-identical to one of the
  403. * trusted CA certificates. In that case we don't have to load
  404. * all of the trusted certificates into the kernel, link them
  405. * to @ca_ring or link @ca_ring to @verify_ring, instead we
  406. * load the first certificate into @verify_ring before we set
  407. * the restric mode on it, same as when no trusted CAs are
  408. * provided.
  409. *
  410. * Note this happens to work around a kernel issue preventing
  411. * self-signed certificates missing the optional AKID extension
  412. * from being linked to a restricted keyring. That issue would
  413. * have affected us if the trusted CA set included such
  414. * certificate and the same certificate was at the root of
  415. * the chain.
  416. */
  417. if (ca_certs && !ca_match) {
  418. ca_ring = cert_set_to_keyring(ca_certs, error_buf);
  419. if (!ca_ring) {
  420. if (error)
  421. *error = error_buf;
  422. return false;
  423. }
  424. if (!l_keyring_link_nested(verify_ring, ca_ring)) {
  425. l_keyring_free(ca_ring);
  426. RETURN_ERROR("Can't link CA ring to verify ring");
  427. }
  428. } else
  429. prev_key = cert_try_link(cert, verify_ring);
  430. /*
  431. * The top, unverified certificate(s) are linked to the keyring and
  432. * we can now force verification of any new certificates linked.
  433. */
  434. if (!l_keyring_restrict(verify_ring, L_KEYRING_RESTRICT_ASYM_CHAIN,
  435. NULL)) {
  436. l_key_free(prev_key);
  437. l_keyring_free(ca_ring);
  438. RETURN_ERROR("Can't restrict verify keyring");
  439. }
  440. if (ca_ring) {
  441. /*
  442. * Verify the first certificate outside of the loop, then
  443. * revoke the trusted CAs' keys so that only the newly
  444. * verified cert's public key remains in the ring.
  445. */
  446. prev_key = cert_try_link(cert, verify_ring);
  447. l_keyring_free(ca_ring);
  448. }
  449. cert = cert->issued;
  450. /* Verify the rest of the chain */
  451. while (prev_key && cert) {
  452. struct l_key *new_key = cert_try_link(cert, verify_ring);
  453. /*
  454. * Free and revoke the issuer's public key again leaving only
  455. * new_key in verify_ring to ensure the next certificate linked
  456. * is signed by the owner of this key.
  457. */
  458. l_key_free(prev_key);
  459. prev_key = new_key;
  460. cert = cert->issued;
  461. verified++;
  462. }
  463. if (!prev_key) {
  464. int total = 0;
  465. char str[100];
  466. for (cert = chain->ca; cert; cert = cert->issued, total++);
  467. if (ca_match)
  468. snprintf(str, sizeof(str), "%i / %i matched a trusted "
  469. "certificate, root not verified",
  470. ca_match, total);
  471. else
  472. snprintf(str, sizeof(str), "root %sverified against "
  473. "trusted CA(s)",
  474. ca_certs && !ca_match && verified ? "" :
  475. "not ");
  476. RETURN_ERROR("Linking certificate %i / %i failed, %s",
  477. verified + 1, total, str);
  478. }
  479. l_key_free(prev_key);
  480. return true;
  481. }
  482. struct l_key *cert_key_from_pkcs8_private_key_info(const uint8_t *der,
  483. size_t der_len)
  484. {
  485. return l_key_new(L_KEY_RSA, der, der_len);
  486. }
  487. /*
  488. * The passphrase, if given, must have been validated as UTF-8 unless the
  489. * caller knows that PKCS#12 encryption algorithms are not used.
  490. * Use l_utf8_validate.
  491. */
  492. struct l_key *cert_key_from_pkcs8_encrypted_private_key_info(const uint8_t *der,
  493. size_t der_len,
  494. const char *passphrase)
  495. {
  496. const uint8_t *key_info, *alg_id, *data;
  497. uint8_t tag;
  498. size_t key_info_len, alg_id_len, data_len, tmp_len;
  499. struct l_cipher *alg;
  500. uint8_t *decrypted;
  501. struct l_key *pkey;
  502. bool r;
  503. bool is_block;
  504. size_t decrypted_len;
  505. /* Technically this is BER, not limited to DER */
  506. key_info = asn1_der_find_elem(der, der_len, 0, &tag, &key_info_len);
  507. if (!key_info || tag != ASN1_ID_SEQUENCE)
  508. return NULL;
  509. alg_id = asn1_der_find_elem(key_info, key_info_len, 0, &tag,
  510. &alg_id_len);
  511. if (!alg_id || tag != ASN1_ID_SEQUENCE)
  512. return NULL;
  513. data = asn1_der_find_elem(key_info, key_info_len, 1, &tag, &data_len);
  514. if (!data || tag != ASN1_ID_OCTET_STRING || data_len < 8 ||
  515. (data_len & 7) != 0)
  516. return NULL;
  517. if (asn1_der_find_elem(der, der_len, 2, &tag, &tmp_len))
  518. return NULL;
  519. alg = cert_cipher_from_pkcs_alg_id(alg_id, alg_id_len, passphrase,
  520. &is_block);
  521. if (!alg)
  522. return NULL;
  523. decrypted = l_malloc(data_len);
  524. r = l_cipher_decrypt(alg, data, decrypted, data_len);
  525. l_cipher_free(alg);
  526. if (!r) {
  527. l_free(decrypted);
  528. return NULL;
  529. }
  530. decrypted_len = data_len;
  531. /*
  532. * For block ciphers strip padding as defined in RFC8018
  533. * (for PKCS#5 v1) or RFC1423 / RFC5652 (for v2).
  534. */
  535. if (is_block) {
  536. uint8_t pad = decrypted[data_len - 1];
  537. pkey = NULL;
  538. if (pad > data_len || pad > 16 || pad == 0)
  539. goto cleanup;
  540. if (!l_secure_memeq(decrypted + data_len - pad, pad - 1U, pad))
  541. goto cleanup;
  542. decrypted_len -= pad;
  543. }
  544. pkey = cert_key_from_pkcs8_private_key_info(decrypted, decrypted_len);
  545. cleanup:
  546. explicit_bzero(decrypted, data_len);
  547. l_free(decrypted);
  548. return pkey;
  549. }
  550. struct l_key *cert_key_from_pkcs1_rsa_private_key(const uint8_t *der,
  551. size_t der_len)
  552. {
  553. const uint8_t *data;
  554. uint8_t tag;
  555. size_t data_len;
  556. const uint8_t *key_data;
  557. size_t key_data_len;
  558. int i;
  559. uint8_t *private_key;
  560. size_t private_key_len;
  561. uint8_t *one_asymmetric_key;
  562. uint8_t *ptr;
  563. struct l_key *pkey;
  564. static const uint8_t version0[] = {
  565. ASN1_ID_INTEGER, 0x01, 0x00
  566. };
  567. static const uint8_t pkcs1_rsa_encryption[] = {
  568. ASN1_ID_SEQUENCE, 0x0d,
  569. ASN1_ID_OID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  570. 0x01, 0x01, 0x01,
  571. ASN1_ID_NULL, 0x00,
  572. };
  573. /*
  574. * Sanity check that it's a version 0 or 1 RSAPrivateKey structure
  575. * with the 8 integers.
  576. */
  577. key_data = asn1_der_find_elem(der, der_len, 0, &tag, &key_data_len);
  578. if (!key_data || tag != ASN1_ID_SEQUENCE)
  579. return NULL;
  580. data = asn1_der_find_elem(key_data, key_data_len, 0, &tag,
  581. &data_len);
  582. if (!data || tag != ASN1_ID_INTEGER || data_len != 1 ||
  583. (data[0] != 0x00 && data[0] != 0x01))
  584. return NULL;
  585. for (i = 1; i < 9; i++) {
  586. data = asn1_der_find_elem(key_data, key_data_len, i, &tag,
  587. &data_len);
  588. if (!data || tag != ASN1_ID_INTEGER || data_len < 1)
  589. return NULL;
  590. }
  591. private_key = l_malloc(10 + der_len);
  592. ptr = private_key;
  593. *ptr++ = ASN1_ID_OCTET_STRING;
  594. asn1_write_definite_length(&ptr, der_len);
  595. memcpy(ptr, der, der_len);
  596. ptr += der_len;
  597. private_key_len = ptr - private_key;
  598. one_asymmetric_key = l_malloc(32 + private_key_len);
  599. ptr = one_asymmetric_key;
  600. *ptr++ = ASN1_ID_SEQUENCE;
  601. asn1_write_definite_length(&ptr, sizeof(version0) +
  602. sizeof(pkcs1_rsa_encryption) +
  603. private_key_len);
  604. memcpy(ptr, version0, sizeof(version0));
  605. ptr += sizeof(version0);
  606. memcpy(ptr, pkcs1_rsa_encryption, sizeof(pkcs1_rsa_encryption));
  607. ptr += sizeof(pkcs1_rsa_encryption);
  608. memcpy(ptr, private_key, private_key_len);
  609. ptr += private_key_len;
  610. explicit_bzero(private_key, private_key_len);
  611. l_free(private_key);
  612. pkey = cert_key_from_pkcs8_private_key_info(one_asymmetric_key,
  613. ptr - one_asymmetric_key);
  614. explicit_bzero(one_asymmetric_key, ptr - one_asymmetric_key);
  615. l_free(one_asymmetric_key);
  616. return pkey;
  617. }
  618. static const uint8_t *cert_unpack_pkcs7_content_info(const uint8_t *container,
  619. size_t container_len, int pos,
  620. const struct asn1_oid *expected_oid,
  621. struct asn1_oid *out_oid,
  622. uint8_t *out_tag, size_t *out_len)
  623. {
  624. const uint8_t *content_info;
  625. size_t content_info_len;
  626. const uint8_t *type;
  627. size_t type_len;
  628. const uint8_t *ret;
  629. uint8_t tag;
  630. if (!(content_info = asn1_der_find_elem(container, container_len, pos,
  631. &tag, &content_info_len)) ||
  632. tag != ASN1_ID_SEQUENCE)
  633. return NULL;
  634. if (!(type = asn1_der_find_elem(content_info, content_info_len, 0,
  635. &tag, &type_len)) ||
  636. tag != ASN1_ID_OID ||
  637. type_len > sizeof(out_oid->asn1))
  638. return NULL;
  639. if (expected_oid && !asn1_oid_eq(expected_oid, type_len, type))
  640. return NULL;
  641. if (!(ret = asn1_der_find_elem(content_info, content_info_len,
  642. ASN1_CONTEXT_EXPLICIT(0),
  643. out_tag, out_len)) ||
  644. ret + *out_len != content_info + content_info_len)
  645. return NULL;
  646. if (out_oid) {
  647. out_oid->asn1_len = type_len;
  648. memcpy(out_oid->asn1, type, type_len);
  649. }
  650. return ret;
  651. }
  652. /* RFC5652 Section 8 */
  653. static uint8_t *cert_decrypt_pkcs7_encrypted_data(const uint8_t *data,
  654. size_t data_len,
  655. const char *password,
  656. struct asn1_oid *out_oid,
  657. size_t *out_len)
  658. {
  659. const uint8_t *version;
  660. size_t version_len;
  661. const uint8_t *encrypted_info;
  662. size_t encrypted_info_len;
  663. const uint8_t *type;
  664. size_t type_len;
  665. const uint8_t *alg_id;
  666. size_t alg_id_len;
  667. const uint8_t *encrypted;
  668. size_t encrypted_len;
  669. uint8_t tag;
  670. struct l_cipher *alg;
  671. uint8_t *plaintext;
  672. int i;
  673. bool ok;
  674. bool is_block;
  675. if (!(version = asn1_der_find_elem(data, data_len, 0, &tag,
  676. &version_len)) ||
  677. tag != ASN1_ID_INTEGER || version_len != 1 ||
  678. !L_IN_SET(version[0], 0, 2))
  679. return NULL;
  680. if (!(encrypted_info = asn1_der_find_elem(data, data_len, 1, &tag,
  681. &encrypted_info_len)) ||
  682. tag != ASN1_ID_SEQUENCE)
  683. return NULL;
  684. if (!(type = asn1_der_find_elem(encrypted_info, encrypted_info_len, 0,
  685. &tag, &type_len)) ||
  686. tag != ASN1_ID_OID ||
  687. type_len > sizeof(out_oid->asn1))
  688. return NULL;
  689. if (!(alg_id = asn1_der_find_elem(encrypted_info, encrypted_info_len, 1,
  690. &tag, &alg_id_len)) ||
  691. tag != ASN1_ID_SEQUENCE)
  692. return NULL;
  693. /* Not optional in our case, defined [0] IMPLICIT OCTET STRING */
  694. if (!(encrypted = asn1_der_find_elem(encrypted_info, encrypted_info_len,
  695. ASN1_CONTEXT_IMPLICIT(0),
  696. &tag, &encrypted_len)) ||
  697. tag != ASN1_ID(ASN1_CLASS_CONTEXT, 0, 0) ||
  698. encrypted_len < 8)
  699. return NULL;
  700. if (!(alg = cert_cipher_from_pkcs_alg_id(alg_id, alg_id_len, password,
  701. &is_block)))
  702. return NULL;
  703. plaintext = l_malloc(encrypted_len);
  704. ok = l_cipher_decrypt(alg, encrypted, plaintext, encrypted_len);
  705. l_cipher_free(alg);
  706. if (!ok) {
  707. l_free(plaintext);
  708. return NULL;
  709. }
  710. if (is_block) {
  711. bool ok = true;
  712. /* Also validate the padding */
  713. if (encrypted_len < plaintext[encrypted_len - 1] ||
  714. plaintext[encrypted_len - 1] > 16) {
  715. plaintext[encrypted_len - 1] = 1;
  716. ok = false;
  717. }
  718. for (i = 1; i < plaintext[encrypted_len - 1]; i++)
  719. if (plaintext[encrypted_len - 1 - i] !=
  720. plaintext[encrypted_len - 1])
  721. ok = false;
  722. if (!ok) {
  723. explicit_bzero(plaintext, encrypted_len);
  724. l_free(plaintext);
  725. return NULL;
  726. }
  727. encrypted_len -= plaintext[encrypted_len - 1];
  728. }
  729. if (out_oid) {
  730. out_oid->asn1_len = type_len;
  731. memcpy(out_oid->asn1, type, type_len);
  732. }
  733. *out_len = encrypted_len;
  734. return plaintext;
  735. }
  736. /* RFC7292 Appendix A. */
  737. static const struct cert_pkcs12_hash pkcs12_mac_algs[] = {
  738. {
  739. L_CHECKSUM_MD5, 16, 16, 64,
  740. { 8, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0f, 0x02, 0x05 } }
  741. },
  742. {
  743. L_CHECKSUM_SHA1, 20, 20, 64,
  744. { 5, { 0x2b, 0x0e, 0x03, 0x02, 0x1a } }
  745. },
  746. {
  747. L_CHECKSUM_SHA224, 28, 28, 64,
  748. { 9, { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04 } }
  749. },
  750. {
  751. L_CHECKSUM_SHA256, 32, 32, 64,
  752. { 9, { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01 } }
  753. },
  754. {
  755. L_CHECKSUM_SHA384, 48, 48, 128,
  756. { 9, { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02 } }
  757. },
  758. {
  759. L_CHECKSUM_SHA512, 64, 64, 128,
  760. { 9, { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03 } }
  761. },
  762. {
  763. L_CHECKSUM_SHA512, 64, 28, 128,
  764. { 9, { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x05 } }
  765. },
  766. {
  767. L_CHECKSUM_SHA512, 64, 32, 128,
  768. { 9, { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x06 } }
  769. },
  770. };
  771. static const struct asn1_oid pkcs12_key_bag_oid = {
  772. 11, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x01 }
  773. };
  774. static const struct asn1_oid pkcs12_pkcs8_shrouded_key_bag_oid = {
  775. 11, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02 }
  776. };
  777. static const struct asn1_oid pkcs12_cert_bag_oid = {
  778. 11, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x03 }
  779. };
  780. static const struct asn1_oid pkcs12_safe_contents_bag_oid = {
  781. 11, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x06 }
  782. };
  783. static const struct asn1_oid pkcs9_x509_certificate_oid = {
  784. 10, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x16, 0x01 }
  785. };
  786. /* RFC7292 Section 4.2.3 */
  787. static bool cert_parse_pkcs12_cert_bag(const uint8_t *data, size_t data_len,
  788. struct l_certchain **out_certchain)
  789. {
  790. const uint8_t *cert_bag;
  791. size_t cert_bag_len;
  792. const uint8_t *cert_id;
  793. size_t cert_id_len;
  794. const uint8_t *cert_value;
  795. size_t cert_value_len;
  796. uint8_t tag;
  797. struct l_cert *cert;
  798. if (!(cert_bag = asn1_der_find_elem(data, data_len, 0,
  799. &tag, &cert_bag_len)) ||
  800. tag != ASN1_ID_SEQUENCE)
  801. return false;
  802. if (!(cert_id = asn1_der_find_elem(cert_bag, cert_bag_len, 0,
  803. &tag, &cert_id_len)) ||
  804. tag != ASN1_ID_OID)
  805. return false;
  806. if (!(cert_value = asn1_der_find_elem(cert_bag, cert_bag_len,
  807. ASN1_CONTEXT_EXPLICIT(0),
  808. &tag, &cert_value_len)) ||
  809. tag != ASN1_ID_OCTET_STRING ||
  810. cert_value + cert_value_len != data + data_len)
  811. return false;
  812. /* Skip unsupported certificate types */
  813. if (!asn1_oid_eq(&pkcs9_x509_certificate_oid, cert_id_len, cert_id))
  814. return true;
  815. if (!(cert = l_cert_new_from_der(cert_value, cert_value_len)))
  816. return false;
  817. if (!*out_certchain)
  818. *out_certchain = certchain_new_from_leaf(cert);
  819. else
  820. certchain_link_issuer(*out_certchain, cert);
  821. return true;
  822. }
  823. static bool cert_parse_pkcs12_safe_contents(const uint8_t *data,
  824. size_t data_len, const char *password,
  825. struct l_certchain **out_certchain,
  826. struct l_key **out_privkey)
  827. {
  828. const uint8_t *safe_contents;
  829. size_t safe_contents_len;
  830. uint8_t tag;
  831. if (!(safe_contents = asn1_der_find_elem(data, data_len, 0, &tag,
  832. &safe_contents_len)) ||
  833. tag != ASN1_ID_SEQUENCE ||
  834. data + data_len != safe_contents + safe_contents_len)
  835. return false;
  836. /* RFC7292 Section 4.2 */
  837. while (safe_contents_len) {
  838. const uint8_t *safe_bag;
  839. size_t safe_bag_len;
  840. const uint8_t *bag_id;
  841. size_t bag_id_len;
  842. const uint8_t *bag_value;
  843. int bag_value_len;
  844. /* RFC7292 Section 4.2 */
  845. if (!(safe_bag = asn1_der_find_elem(safe_contents,
  846. safe_contents_len, 0,
  847. &tag, &safe_bag_len)) ||
  848. tag != ASN1_ID_SEQUENCE)
  849. return false;
  850. if (!(bag_id = asn1_der_find_elem(safe_bag, safe_bag_len, 0,
  851. &tag, &bag_id_len)) ||
  852. tag != ASN1_ID_OID)
  853. return false;
  854. /*
  855. * The bagValue is EXPLICITly tagged but we don't want to
  856. * unpack the inner TLV yet so don't use asn1_der_find_elem.
  857. */
  858. safe_bag_len -= bag_id + bag_id_len - safe_bag;
  859. safe_bag = bag_id + bag_id_len;
  860. if (safe_bag_len < 4)
  861. return false;
  862. tag = *safe_bag++;
  863. safe_bag_len--;
  864. bag_value_len = asn1_parse_definite_length(&safe_bag,
  865. &safe_bag_len);
  866. bag_value = safe_bag;
  867. if (bag_value_len < 0 || bag_value_len > (int) safe_bag_len ||
  868. tag != ASN1_ID(ASN1_CLASS_CONTEXT, 1, 0))
  869. return false;
  870. /* PKCS#9 attributes ignored */
  871. safe_contents_len -= (safe_bag + safe_bag_len - safe_contents);
  872. safe_contents = safe_bag + safe_bag_len;
  873. if (asn1_oid_eq(&pkcs12_key_bag_oid, bag_id_len, bag_id)) {
  874. if (!out_privkey || *out_privkey)
  875. continue;
  876. *out_privkey =
  877. cert_key_from_pkcs8_private_key_info(bag_value,
  878. bag_value_len);
  879. if (!*out_privkey)
  880. return false;
  881. } else if (asn1_oid_eq(&pkcs12_pkcs8_shrouded_key_bag_oid,
  882. bag_id_len, bag_id)) {
  883. if (!out_privkey || *out_privkey)
  884. continue;
  885. *out_privkey =
  886. cert_key_from_pkcs8_encrypted_private_key_info(
  887. bag_value,
  888. bag_value_len,
  889. password);
  890. if (!*out_privkey)
  891. return false;
  892. } else if (asn1_oid_eq(&pkcs12_cert_bag_oid,
  893. bag_id_len, bag_id)) {
  894. if (!out_certchain)
  895. continue;
  896. if (!cert_parse_pkcs12_cert_bag(bag_value, bag_value_len,
  897. out_certchain))
  898. return false;
  899. } else if (asn1_oid_eq(&pkcs12_safe_contents_bag_oid,
  900. bag_id_len, bag_id)) {
  901. /* TODO: depth check */
  902. if (!(cert_parse_pkcs12_safe_contents(bag_value,
  903. bag_value_len,
  904. password,
  905. out_certchain,
  906. out_privkey)))
  907. return false;
  908. }
  909. }
  910. return true;
  911. }
  912. static bool cert_check_pkcs12_integrity(const uint8_t *mac_data,
  913. size_t mac_data_len,
  914. const uint8_t *auth_safe,
  915. size_t auth_safe_len,
  916. const char *password)
  917. {
  918. const uint8_t *mac;
  919. size_t mac_len;
  920. const uint8_t *mac_salt;
  921. size_t mac_salt_len;
  922. const uint8_t *iterations_data;
  923. size_t iterations_len;
  924. unsigned int iterations;
  925. const uint8_t *digest_alg;
  926. size_t digest_alg_len;
  927. const uint8_t *digest;
  928. size_t digest_len;
  929. const uint8_t *alg_id;
  930. size_t alg_id_len;
  931. const struct cert_pkcs12_hash *mac_hash;
  932. L_AUTO_FREE_VAR(uint8_t *, key) = NULL;
  933. struct l_checksum *hmac;
  934. uint8_t hmac_val[64];
  935. uint8_t tag;
  936. bool ok;
  937. unsigned int i;
  938. if (!(mac = asn1_der_find_elem(mac_data, mac_data_len, 0, &tag,
  939. &mac_len)) ||
  940. tag != ASN1_ID_SEQUENCE)
  941. return false;
  942. if (!(mac_salt = asn1_der_find_elem(mac_data, mac_data_len, 1, &tag,
  943. &mac_salt_len)) ||
  944. tag != ASN1_ID_OCTET_STRING || mac_salt_len > 1024)
  945. return false;
  946. if (!(iterations_data = asn1_der_find_elem(mac_data, mac_data_len, 2,
  947. &tag,
  948. &iterations_len)) ||
  949. tag != ASN1_ID_INTEGER || iterations_len > 4)
  950. return false;
  951. for (iterations = 0; iterations_len; iterations_len--)
  952. iterations = (iterations << 8) | *iterations_data++;
  953. if (iterations < 1 || iterations > 8192)
  954. return false;
  955. /* RFC2315 Section 9.4 */
  956. if (!(digest_alg = asn1_der_find_elem(mac, mac_len, 0, &tag,
  957. &digest_alg_len)) ||
  958. tag != ASN1_ID_SEQUENCE)
  959. return false;
  960. if (!(digest = asn1_der_find_elem(mac, mac_len, 1, &tag,
  961. &digest_len)) ||
  962. tag != ASN1_ID_OCTET_STRING)
  963. return false;
  964. if (!(alg_id = asn1_der_find_elem(digest_alg, digest_alg_len,
  965. 0, &tag, &alg_id_len)) ||
  966. tag != ASN1_ID_OID)
  967. return false;
  968. /* This is going to be used for both the MAC and its key derivation */
  969. for (i = 0; i < L_ARRAY_SIZE(pkcs12_mac_algs); i++)
  970. if (asn1_oid_eq(&pkcs12_mac_algs[i].oid, alg_id_len, alg_id)) {
  971. mac_hash = &pkcs12_mac_algs[i];
  972. break;
  973. }
  974. if (i == L_ARRAY_SIZE(pkcs12_mac_algs) || digest_len != mac_hash->u)
  975. return false;
  976. if (!(key = cert_pkcs12_pbkdf(password, mac_hash,
  977. mac_salt, mac_salt_len,
  978. iterations, 3, mac_hash->u)))
  979. return false;
  980. hmac = l_checksum_new_hmac(mac_hash->alg, key, mac_hash->u);
  981. explicit_bzero(key, mac_hash->u);
  982. if (!hmac)
  983. return false;
  984. ok = l_checksum_update(hmac, auth_safe, auth_safe_len) &&
  985. l_checksum_get_digest(hmac, hmac_val, mac_hash->len) > 0;
  986. l_checksum_free(hmac);
  987. if (!ok)
  988. return false;
  989. /*
  990. * SHA-512/224 and SHA-512/256 are not supported. We can truncate the
  991. * output for key derivation but we can't do this inside the HMAC
  992. * algorithms based on these hashes. We skip the MAC verification
  993. * if one of these hashes is used (identified by .u != .len)
  994. */
  995. if (mac_hash->u != mac_hash->len)
  996. return true;
  997. return l_secure_memcmp(hmac_val, digest, digest_len) == 0;
  998. }
  999. /* RFC5652 Section 4 */
  1000. static const struct asn1_oid pkcs7_data_oid = {
  1001. 9, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01 }
  1002. };
  1003. /* RFC5652 Section 8 */
  1004. static const struct asn1_oid pkcs7_encrypted_data_oid = {
  1005. 9, { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x06 }
  1006. };
  1007. static bool cert_parse_auth_safe_content(const uint8_t *data, size_t data_len,
  1008. uint8_t tag,
  1009. const struct asn1_oid *data_oid,
  1010. const char *password,
  1011. struct l_certchain **out_certchain,
  1012. struct l_key **out_privkey)
  1013. {
  1014. if (asn1_oid_eq(&pkcs7_encrypted_data_oid,
  1015. data_oid->asn1_len, data_oid->asn1)) {
  1016. uint8_t *plaintext;
  1017. size_t plaintext_len;
  1018. struct asn1_oid oid;
  1019. bool ok;
  1020. if (tag != ASN1_ID_SEQUENCE)
  1021. return false;
  1022. /*
  1023. * This is same as PKCS#7 encryptedData but the ciphers
  1024. * used are from PKCS#12 (broken but still the default
  1025. * everywhere) and PKCS#5 (recommended).
  1026. */
  1027. plaintext = cert_decrypt_pkcs7_encrypted_data(data,
  1028. data_len,
  1029. password, &oid,
  1030. &plaintext_len);
  1031. if (!plaintext)
  1032. return false;
  1033. /*
  1034. * Since we only support PKCS#7 data and encryptedData
  1035. * types, and there's no point re-encrypting
  1036. * encryptedData, the plaintext must be a PKCS#7
  1037. * "data".
  1038. */
  1039. ok = asn1_oid_eq(&pkcs7_data_oid,
  1040. oid.asn1_len, oid.asn1) &&
  1041. cert_parse_pkcs12_safe_contents(plaintext,
  1042. plaintext_len,
  1043. password,
  1044. out_certchain,
  1045. out_privkey);
  1046. explicit_bzero(plaintext, plaintext_len);
  1047. l_free(plaintext);
  1048. if (!ok)
  1049. return false;
  1050. } else if (asn1_oid_eq(&pkcs7_data_oid,
  1051. data_oid->asn1_len, data_oid->asn1)) {
  1052. if (tag != ASN1_ID_OCTET_STRING)
  1053. return false;
  1054. if (!cert_parse_pkcs12_safe_contents(data, data_len,
  1055. password,
  1056. out_certchain,
  1057. out_privkey))
  1058. return false;
  1059. }
  1060. /* envelopedData support not needed */
  1061. return true;
  1062. }
  1063. static bool cert_parse_pkcs12_pfx(const uint8_t *ptr, size_t len,
  1064. const char *password,
  1065. struct l_certchain **out_certchain,
  1066. struct l_key **out_privkey)
  1067. {
  1068. const uint8_t *version;
  1069. size_t version_len;
  1070. const uint8_t *auth_safe;
  1071. size_t auth_safe_len;
  1072. const uint8_t *mac_data;
  1073. size_t mac_data_len;
  1074. const uint8_t *auth_safe_seq;
  1075. size_t auth_safe_seq_len;
  1076. uint8_t tag;
  1077. unsigned int i;
  1078. struct l_certchain *certchain = NULL;
  1079. struct l_key *privkey = NULL;
  1080. /* RFC7292 Section 4 */
  1081. if (!(version = asn1_der_find_elem(ptr, len, 0, &tag, &version_len)) ||
  1082. tag != ASN1_ID_INTEGER)
  1083. return false;
  1084. if (version_len != 1 || version[0] != 3)
  1085. return false;
  1086. /*
  1087. * Since we only support the password-based integrity mode, the
  1088. * authSafe must be of PKCS#7 type "data" and not "signedData".
  1089. */
  1090. if (!(auth_safe = cert_unpack_pkcs7_content_info(ptr, len, 1,
  1091. &pkcs7_data_oid, NULL,
  1092. &tag,
  1093. &auth_safe_len)) ||
  1094. tag != ASN1_ID_OCTET_STRING)
  1095. return false;
  1096. /*
  1097. * openssl can generate PFX structures without macData not signed
  1098. * with a public key so handle this case, otherwise the macData
  1099. * would not be optional.
  1100. */
  1101. if (auth_safe + auth_safe_len == ptr + len)
  1102. goto integrity_check_done;
  1103. if (!(mac_data = asn1_der_find_elem(ptr, len, 2, &tag,
  1104. &mac_data_len)) ||
  1105. tag != ASN1_ID_SEQUENCE)
  1106. return false;
  1107. if (!cert_check_pkcs12_integrity(mac_data, mac_data_len,
  1108. auth_safe, auth_safe_len,
  1109. password))
  1110. return false;
  1111. integrity_check_done:
  1112. if (!(auth_safe_seq = asn1_der_find_elem(auth_safe, auth_safe_len, 0,
  1113. &tag, &auth_safe_seq_len)) ||
  1114. tag != ASN1_ID_SEQUENCE ||
  1115. auth_safe + auth_safe_len !=
  1116. auth_safe_seq + auth_safe_seq_len)
  1117. return false;
  1118. i = 0;
  1119. while (1) {
  1120. struct asn1_oid data_oid;
  1121. const uint8_t *data;
  1122. size_t data_len;
  1123. if (!(data = cert_unpack_pkcs7_content_info(auth_safe_seq,
  1124. auth_safe_seq_len, i++,
  1125. NULL, &data_oid, &tag,
  1126. &data_len)))
  1127. goto error;
  1128. if (!cert_parse_auth_safe_content(data, data_len, tag,
  1129. &data_oid, password,
  1130. out_certchain ?
  1131. &certchain : NULL,
  1132. out_privkey ?
  1133. &privkey : NULL))
  1134. goto error;
  1135. if (data + data_len == auth_safe_seq + auth_safe_seq_len)
  1136. break;
  1137. }
  1138. if (out_certchain)
  1139. *out_certchain = certchain;
  1140. if (out_privkey)
  1141. *out_privkey = privkey;
  1142. return true;
  1143. error:
  1144. if (certchain)
  1145. l_certchain_free(certchain);
  1146. if (privkey)
  1147. l_key_free(privkey);
  1148. return false;
  1149. }
  1150. static int cert_try_load_der_format(const uint8_t *content, size_t content_len,
  1151. const char *password,
  1152. struct l_certchain **out_certchain,
  1153. struct l_key **out_privkey,
  1154. bool *out_encrypted)
  1155. {
  1156. const uint8_t *seq;
  1157. size_t seq_len;
  1158. const uint8_t *elem_data;
  1159. size_t elem_len;
  1160. uint8_t tag;
  1161. if (!(seq = asn1_der_find_elem(content, content_len,
  1162. 0, &tag, &seq_len)))
  1163. /* May not have been a DER file after all */
  1164. return -ENOMSG;
  1165. /*
  1166. * See if the first sub-element is another sequence, then, out of
  1167. * the formats that we currently support this can only be a raw
  1168. * certificate. If integer, it's going to be PKCS#12. If we wish
  1169. * to add any more formats we'll probably need to start guessing
  1170. * from the filename suffix.
  1171. */
  1172. if (!(elem_data = asn1_der_find_elem(seq, seq_len,
  1173. 0, &tag, &elem_len)))
  1174. return -ENOMSG;
  1175. if (tag == ASN1_ID_SEQUENCE) {
  1176. if (out_certchain) {
  1177. struct l_cert *cert;
  1178. if (!(cert = l_cert_new_from_der(content, content_len)))
  1179. return -EINVAL;
  1180. *out_certchain = certchain_new_from_leaf(cert);
  1181. if (out_privkey)
  1182. *out_privkey = NULL;
  1183. if (out_encrypted)
  1184. *out_encrypted = false;
  1185. return 0;
  1186. }
  1187. return -EINVAL;
  1188. }
  1189. if (tag == ASN1_ID_INTEGER) {
  1190. /*
  1191. * Since we don't support public key-protected PKCS#12
  1192. * modes, we always require the password at least for the
  1193. * integrity check. Strictly speaking encryption may not
  1194. * actually be in use. We also don't support files with
  1195. * different integrity and privacy passwords, they must
  1196. * be identical if privacy is enabled.
  1197. */
  1198. if (out_encrypted)
  1199. *out_encrypted = true;
  1200. if (!password) {
  1201. if (!out_encrypted)
  1202. return -EINVAL;
  1203. if (out_certchain)
  1204. *out_certchain = NULL;
  1205. if (out_privkey)
  1206. *out_privkey = NULL;
  1207. return 0;
  1208. }
  1209. if (cert_parse_pkcs12_pfx(seq, seq_len, password,
  1210. out_certchain, out_privkey))
  1211. return 0;
  1212. else
  1213. return -EINVAL;
  1214. }
  1215. return -ENOMSG;
  1216. }
  1217. static bool cert_try_load_pem_format(const char *content, size_t content_len,
  1218. const char *password,
  1219. struct l_certchain **out_certchain,
  1220. struct l_key **out_privkey,
  1221. bool *out_encrypted)
  1222. {
  1223. bool error = false;
  1224. bool done = false;
  1225. struct l_certchain *certchain = NULL;
  1226. struct l_key *privkey = NULL;
  1227. bool encrypted = false;
  1228. while (!done && !error && content_len) {
  1229. uint8_t *der;
  1230. size_t der_len;
  1231. char *type_label;
  1232. char *headers;
  1233. const char *endp;
  1234. if (!(der = pem_load_buffer(content, content_len, &type_label,
  1235. &der_len, &headers, &endp)))
  1236. break;
  1237. content_len -= endp - content;
  1238. content = endp;
  1239. if (out_certchain && L_IN_STRSET(type_label, "CERTIFICATE")) {
  1240. struct l_cert *cert;
  1241. if (!(cert = l_cert_new_from_der(der, der_len))) {
  1242. error = true;
  1243. goto next;
  1244. }
  1245. if (!certchain)
  1246. certchain = certchain_new_from_leaf(cert);
  1247. else
  1248. certchain_link_issuer(certchain, cert);
  1249. goto next;
  1250. }
  1251. /* Only use the first private key found */
  1252. if (out_privkey && !privkey && L_IN_STRSET(type_label,
  1253. "PRIVATE KEY",
  1254. "ENCRYPTED PRIVATE KEY",
  1255. "RSA PRIVATE KEY")) {
  1256. privkey = pem_load_private_key(der, der_len, type_label,
  1257. password, headers,
  1258. &encrypted);
  1259. if (!privkey) {
  1260. if (certchain) {
  1261. l_certchain_free(certchain);
  1262. certchain = NULL;
  1263. }
  1264. if (password)
  1265. error = true;
  1266. else
  1267. error = !encrypted || !out_encrypted;
  1268. done = true;
  1269. }
  1270. continue;
  1271. }
  1272. /* Cisco/gnutls-type PEM-encoded PKCS#12, probably rare */
  1273. if (L_IN_STRSET(type_label, "PKCS12")) {
  1274. encrypted = true;
  1275. if (!password) {
  1276. if (certchain && out_privkey) {
  1277. l_certchain_free(certchain);
  1278. certchain = NULL;
  1279. }
  1280. error = !out_encrypted;
  1281. done = true;
  1282. goto next;
  1283. }
  1284. error = !cert_parse_pkcs12_pfx(der, der_len, password,
  1285. out_certchain ?
  1286. &certchain : NULL,
  1287. out_privkey ?
  1288. &privkey : NULL);
  1289. goto next;
  1290. }
  1291. next:
  1292. explicit_bzero(der, der_len);
  1293. l_free(der);
  1294. l_free(type_label);
  1295. l_free(headers);
  1296. }
  1297. if (error) {
  1298. if (certchain)
  1299. l_certchain_free(certchain);
  1300. if (privkey)
  1301. l_key_free(privkey);
  1302. return false;
  1303. }
  1304. if (out_certchain)
  1305. *out_certchain = certchain;
  1306. if (out_privkey)
  1307. *out_privkey = privkey;
  1308. if (out_encrypted)
  1309. *out_encrypted = encrypted;
  1310. return true;
  1311. }
  1312. /*
  1313. * Look at a file, try to detect which of the few X.509 certificate and/or
  1314. * private key container formats it uses and load any certificates in it as
  1315. * a certificate chain object, and load the first private key as an l_key
  1316. * object.
  1317. *
  1318. * Currently supported are:
  1319. * PEM X.509 certificates
  1320. * PEM PKCS#8 encrypted and unencrypted private keys
  1321. * PEM legacy PKCS#1 encrypted and unencrypted private keys
  1322. * Raw X.509 certificates (.cer, .der, .crt)
  1323. * PKCS#12 certificates
  1324. * PKCS#12 encrypted private keys
  1325. *
  1326. * The raw format contains exactly one certificate, PEM and PKCS#12 files
  1327. * can contain any combination of certificates and private keys.
  1328. *
  1329. * The password must have been validated as UTF-8 (use l_utf8_validate)
  1330. * unless the caller knows that no PKCS#12-defined encryption algorithm
  1331. * or MAC is used.
  1332. *
  1333. * Returns false on "unrecoverable" errors, and *out_certchain,
  1334. * *out_privkey and *out_encrypted (if provided) are not modified. However
  1335. * when true is returned, *out_certchain and *out_privkey (if provided) may
  1336. * be set to NULL when nothing could be loaded only due to missing password,
  1337. * and *out_encrypted (if provided) will be set accordingly. It will also
  1338. * be set on success to indicate whether the password was used.
  1339. * *out_certchain and/or *out_privkey will also be NULL if the container
  1340. * was loaded but there were no certificates or private keys in it.
  1341. */
  1342. LIB_EXPORT bool l_cert_load_container_file(const char *filename,
  1343. const char *password,
  1344. struct l_certchain **out_certchain,
  1345. struct l_key **out_privkey,
  1346. bool *out_encrypted)
  1347. {
  1348. struct pem_file_info file;
  1349. bool error = true;
  1350. if (unlikely(!filename))
  1351. return false;
  1352. if (pem_file_open(&file, filename) < 0)
  1353. return false;
  1354. if (file.st.st_size < 1)
  1355. goto close;
  1356. /* See if we have a DER sequence tag at the start */
  1357. if (file.data[0] == ASN1_ID_SEQUENCE) {
  1358. int err;
  1359. err = cert_try_load_der_format(file.data, file.st.st_size,
  1360. password, out_certchain,
  1361. out_privkey, out_encrypted);
  1362. if (!err) {
  1363. error = false;
  1364. goto close;
  1365. }
  1366. if (err != -ENOMSG)
  1367. goto close;
  1368. /* Try other formats */
  1369. }
  1370. /*
  1371. * For backwards compatibility try the TLS internal struct Certificate
  1372. * format as may be captured by PCAP (no future support guaranteed).
  1373. */
  1374. if (out_certchain && !password && file.st.st_size &&
  1375. tls_parse_certificate_list(file.data, file.st.st_size,
  1376. out_certchain) == 0) {
  1377. error = false;
  1378. if (out_privkey)
  1379. *out_privkey = NULL;
  1380. if (out_encrypted)
  1381. *out_encrypted = false;
  1382. goto close;
  1383. }
  1384. /*
  1385. * RFC 7486 allows whitespace and possibly other data before the
  1386. * PEM "encapsulation boundary" so rather than check if the start
  1387. * of the data looks like PEM, we fall back to this format if the
  1388. * data didn't look like anything else we knew about. Note this
  1389. * succeeds for empty files and files without any PEM markers,
  1390. * returning NULL chain and privkey.
  1391. */
  1392. if (cert_try_load_pem_format((const char *) file.data, file.st.st_size,
  1393. password, out_certchain, out_privkey,
  1394. out_encrypted))
  1395. error = false;
  1396. close:
  1397. pem_file_close(&file);
  1398. return !error;
  1399. }