e_loader_attic.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  1. /*
  2. * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /* THIS ENGINE IS FOR TESTING PURPOSES ONLY. */
  10. /* This file has quite some overlap with providers/implementations/storemgmt/file_store.c */
  11. /* We need to use some engine deprecated APIs */
  12. #define OPENSSL_SUPPRESS_DEPRECATED
  13. #include <string.h>
  14. #include <sys/stat.h>
  15. #include <ctype.h>
  16. #include <assert.h>
  17. #include <openssl/bio.h>
  18. #include <openssl/dsa.h> /* For d2i_DSAPrivateKey */
  19. #include <openssl/err.h>
  20. #include <openssl/evp.h>
  21. #include <openssl/pem.h>
  22. #include <openssl/pkcs12.h> /* For the PKCS8 stuff o.O */
  23. #include <openssl/rsa.h> /* For d2i_RSAPrivateKey */
  24. #include <openssl/safestack.h>
  25. #include <openssl/store.h>
  26. #include <openssl/ui.h>
  27. #include <openssl/engine.h>
  28. #include <openssl/x509.h> /* For the PKCS8 stuff o.O */
  29. #include "internal/asn1.h" /* For asn1_d2i_read_bio */
  30. #include "internal/o_dir.h"
  31. #include "internal/cryptlib.h"
  32. #include "crypto/ctype.h" /* For ossl_isdigit */
  33. #include "crypto/pem.h" /* For PVK and "blob" PEM headers */
  34. #include "e_loader_attic_err.c"
  35. DEFINE_STACK_OF(OSSL_STORE_INFO)
  36. #ifdef _WIN32
  37. # define stat _stat
  38. #endif
  39. #ifndef S_ISDIR
  40. # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
  41. #endif
  42. /*-
  43. * Password prompting
  44. * ------------------
  45. */
  46. static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
  47. size_t maxsize, const char *desc, const char *info,
  48. void *data)
  49. {
  50. UI *ui = UI_new();
  51. char *prompt = NULL;
  52. if (ui == NULL) {
  53. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  54. return NULL;
  55. }
  56. if (ui_method != NULL)
  57. UI_set_method(ui, ui_method);
  58. UI_add_user_data(ui, data);
  59. if ((prompt = UI_construct_prompt(ui, desc, info)) == NULL) {
  60. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  61. pass = NULL;
  62. } else if (UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
  63. pass, 0, maxsize - 1) <= 0) {
  64. ATTICerr(0, ERR_R_UI_LIB);
  65. pass = NULL;
  66. } else {
  67. switch (UI_process(ui)) {
  68. case -2:
  69. ATTICerr(0, ATTIC_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
  70. pass = NULL;
  71. break;
  72. case -1:
  73. ATTICerr(0, ERR_R_UI_LIB);
  74. pass = NULL;
  75. break;
  76. default:
  77. break;
  78. }
  79. }
  80. OPENSSL_free(prompt);
  81. UI_free(ui);
  82. return pass;
  83. }
  84. struct pem_pass_data {
  85. const UI_METHOD *ui_method;
  86. void *data;
  87. const char *prompt_desc;
  88. const char *prompt_info;
  89. };
  90. static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
  91. const char *desc, const char *info,
  92. const UI_METHOD *ui_method, void *ui_data)
  93. {
  94. if (pass_data == NULL)
  95. return 0;
  96. pass_data->ui_method = ui_method;
  97. pass_data->data = ui_data;
  98. pass_data->prompt_desc = desc;
  99. pass_data->prompt_info = info;
  100. return 1;
  101. }
  102. /* This is used anywhere a pem_password_cb is needed */
  103. static int file_get_pem_pass(char *buf, int num, int w, void *data)
  104. {
  105. struct pem_pass_data *pass_data = data;
  106. char *pass = file_get_pass(pass_data->ui_method, buf, num,
  107. pass_data->prompt_desc, pass_data->prompt_info,
  108. pass_data->data);
  109. return pass == NULL ? 0 : strlen(pass);
  110. }
  111. /*
  112. * Check if |str| ends with |suffix| preceded by a space, and if it does,
  113. * return the index of that space. If there is no such suffix in |str|,
  114. * return -1.
  115. * For |str| == "FOO BAR" and |suffix| == "BAR", the returned value is 3.
  116. */
  117. static int check_suffix(const char *str, const char *suffix)
  118. {
  119. int str_len = strlen(str);
  120. int suffix_len = strlen(suffix) + 1;
  121. const char *p = NULL;
  122. if (suffix_len >= str_len)
  123. return -1;
  124. p = str + str_len - suffix_len;
  125. if (*p != ' '
  126. || strcmp(p + 1, suffix) != 0)
  127. return -1;
  128. return p - str;
  129. }
  130. /*
  131. * EMBEDDED is a special type of OSSL_STORE_INFO, specially for the file
  132. * handlers, so we define it internally. This uses the possibility to
  133. * create an OSSL_STORE_INFO with a generic data pointer and arbitrary
  134. * type number.
  135. *
  136. * This is used by a FILE_HANDLER's try_decode function to signal that it
  137. * has decoded the incoming blob into a new blob, and that the attempted
  138. * decoding should be immediately restarted with the new blob, using the
  139. * new PEM name.
  140. */
  141. /* Negative numbers are never used for public OSSL_STORE_INFO types */
  142. #define STORE_INFO_EMBEDDED -1
  143. /* This is the embedded data */
  144. struct embedded_st {
  145. BUF_MEM *blob;
  146. char *pem_name;
  147. };
  148. /* Helper functions */
  149. static struct embedded_st *get0_EMBEDDED(OSSL_STORE_INFO *info)
  150. {
  151. return OSSL_STORE_INFO_get0_data(STORE_INFO_EMBEDDED, info);
  152. }
  153. static void store_info_free(OSSL_STORE_INFO *info)
  154. {
  155. struct embedded_st *data;
  156. if (info != NULL && (data = get0_EMBEDDED(info)) != NULL) {
  157. BUF_MEM_free(data->blob);
  158. OPENSSL_free(data->pem_name);
  159. OPENSSL_free(data);
  160. }
  161. OSSL_STORE_INFO_free(info);
  162. }
  163. static OSSL_STORE_INFO *new_EMBEDDED(const char *new_pem_name,
  164. BUF_MEM *embedded)
  165. {
  166. OSSL_STORE_INFO *info = NULL;
  167. struct embedded_st *data = NULL;
  168. if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL
  169. || (info = OSSL_STORE_INFO_new(STORE_INFO_EMBEDDED, data)) == NULL) {
  170. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  171. OPENSSL_free(data);
  172. return NULL;
  173. }
  174. data->blob = embedded;
  175. data->pem_name =
  176. new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name);
  177. if (new_pem_name != NULL && data->pem_name == NULL) {
  178. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  179. store_info_free(info);
  180. info = NULL;
  181. }
  182. return info;
  183. }
  184. /*-
  185. * The file scheme decoders
  186. * ------------------------
  187. *
  188. * Each possible data type has its own decoder, which either operates
  189. * through a given PEM name, or attempts to decode to see if the blob
  190. * it's given is decodable for its data type. The assumption is that
  191. * only the correct data type will match the content.
  192. */
  193. /*-
  194. * The try_decode function is called to check if the blob of data can
  195. * be used by this handler, and if it can, decodes it into a supported
  196. * OpenSSL type and returns an OSSL_STORE_INFO with the decoded data.
  197. * Input:
  198. * pem_name: If this blob comes from a PEM file, this holds
  199. * the PEM name. If it comes from another type of
  200. * file, this is NULL.
  201. * pem_header: If this blob comes from a PEM file, this holds
  202. * the PEM headers. If it comes from another type of
  203. * file, this is NULL.
  204. * blob: The blob of data to match with what this handler
  205. * can use.
  206. * len: The length of the blob.
  207. * handler_ctx: For a handler marked repeatable, this pointer can
  208. * be used to create a context for the handler. IT IS
  209. * THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
  210. * THIS CONTEXT APPROPRIATELY, i.e. create on first call
  211. * and destroy when about to return NULL.
  212. * matchcount: A pointer to an int to count matches for this data.
  213. * Usually becomes 0 (no match) or 1 (match!), but may
  214. * be higher in the (unlikely) event that the data matches
  215. * more than one possibility. The int will always be
  216. * zero when the function is called.
  217. * ui_method: Application UI method for getting a password, pin
  218. * or any other interactive data.
  219. * ui_data: Application data to be passed to ui_method when
  220. * it's called.
  221. * libctx: The library context to be used if applicable
  222. * propq: The property query string for any algorithm fetches
  223. * Output:
  224. * an OSSL_STORE_INFO
  225. */
  226. typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
  227. const char *pem_header,
  228. const unsigned char *blob,
  229. size_t len, void **handler_ctx,
  230. int *matchcount,
  231. const UI_METHOD *ui_method,
  232. void *ui_data, const char *uri,
  233. OSSL_LIB_CTX *libctx,
  234. const char *propq);
  235. /*
  236. * The eof function should return 1 if there's no more data to be found
  237. * with the handler_ctx, otherwise 0. This is only used when the handler is
  238. * marked repeatable.
  239. */
  240. typedef int (*file_eof_fn)(void *handler_ctx);
  241. /*
  242. * The destroy_ctx function is used to destroy the handler_ctx that was
  243. * initiated by a repeatable try_decode function. This is only used when
  244. * the handler is marked repeatable.
  245. */
  246. typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
  247. typedef struct file_handler_st {
  248. const char *name;
  249. file_try_decode_fn try_decode;
  250. file_eof_fn eof;
  251. file_destroy_ctx_fn destroy_ctx;
  252. /* flags */
  253. int repeatable;
  254. } FILE_HANDLER;
  255. /*
  256. * PKCS#12 decoder. It operates by decoding all of the blob content,
  257. * extracting all the interesting data from it and storing them internally,
  258. * then serving them one piece at a time.
  259. */
  260. static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
  261. const char *pem_header,
  262. const unsigned char *blob,
  263. size_t len, void **pctx,
  264. int *matchcount,
  265. const UI_METHOD *ui_method,
  266. void *ui_data, const char *uri,
  267. OSSL_LIB_CTX *libctx,
  268. const char *propq)
  269. {
  270. OSSL_STORE_INFO *store_info = NULL;
  271. STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
  272. if (ctx == NULL) {
  273. /* Initial parsing */
  274. PKCS12 *p12;
  275. if (pem_name != NULL)
  276. /* No match, there is no PEM PKCS12 tag */
  277. return NULL;
  278. if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
  279. char *pass = NULL;
  280. char tpass[PEM_BUFSIZE];
  281. EVP_PKEY *pkey = NULL;
  282. X509 *cert = NULL;
  283. STACK_OF(X509) *chain = NULL;
  284. *matchcount = 1;
  285. if (!PKCS12_mac_present(p12)
  286. || PKCS12_verify_mac(p12, "", 0)
  287. || PKCS12_verify_mac(p12, NULL, 0)) {
  288. pass = "";
  289. } else {
  290. if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
  291. "PKCS12 import", uri,
  292. ui_data)) == NULL) {
  293. ATTICerr(0, ATTIC_R_PASSPHRASE_CALLBACK_ERROR);
  294. goto p12_end;
  295. }
  296. if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
  297. ATTICerr(0, ATTIC_R_ERROR_VERIFYING_PKCS12_MAC);
  298. goto p12_end;
  299. }
  300. }
  301. if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
  302. OSSL_STORE_INFO *osi_pkey = NULL;
  303. OSSL_STORE_INFO *osi_cert = NULL;
  304. OSSL_STORE_INFO *osi_ca = NULL;
  305. int ok = 1;
  306. if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL) {
  307. if (pkey != NULL) {
  308. if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
  309. /* clearing pkey here avoids case distinctions */
  310. && (pkey = NULL) == NULL
  311. && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0)
  312. osi_pkey = NULL;
  313. else
  314. ok = 0;
  315. }
  316. if (ok && cert != NULL) {
  317. if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
  318. /* clearing cert here avoids case distinctions */
  319. && (cert = NULL) == NULL
  320. && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0)
  321. osi_cert = NULL;
  322. else
  323. ok = 0;
  324. }
  325. while (ok && sk_X509_num(chain) > 0) {
  326. X509 *ca = sk_X509_value(chain, 0);
  327. if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL
  328. && sk_X509_shift(chain) != NULL
  329. && sk_OSSL_STORE_INFO_push(ctx, osi_ca) != 0)
  330. osi_ca = NULL;
  331. else
  332. ok = 0;
  333. }
  334. }
  335. EVP_PKEY_free(pkey);
  336. X509_free(cert);
  337. sk_X509_pop_free(chain, X509_free);
  338. store_info_free(osi_pkey);
  339. store_info_free(osi_cert);
  340. store_info_free(osi_ca);
  341. if (!ok) {
  342. sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
  343. ctx = NULL;
  344. }
  345. *pctx = ctx;
  346. }
  347. }
  348. p12_end:
  349. PKCS12_free(p12);
  350. if (ctx == NULL)
  351. return NULL;
  352. }
  353. *matchcount = 1;
  354. store_info = sk_OSSL_STORE_INFO_shift(ctx);
  355. return store_info;
  356. }
  357. static int eof_PKCS12(void *ctx_)
  358. {
  359. STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
  360. return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
  361. }
  362. static void destroy_ctx_PKCS12(void **pctx)
  363. {
  364. STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
  365. sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
  366. *pctx = NULL;
  367. }
  368. static FILE_HANDLER PKCS12_handler = {
  369. "PKCS12",
  370. try_decode_PKCS12,
  371. eof_PKCS12,
  372. destroy_ctx_PKCS12,
  373. 1 /* repeatable */
  374. };
  375. /*
  376. * Encrypted PKCS#8 decoder. It operates by just decrypting the given blob
  377. * into a new blob, which is returned as an EMBEDDED STORE_INFO. The whole
  378. * decoding process will then start over with the new blob.
  379. */
  380. static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
  381. const char *pem_header,
  382. const unsigned char *blob,
  383. size_t len, void **pctx,
  384. int *matchcount,
  385. const UI_METHOD *ui_method,
  386. void *ui_data,
  387. const char *uri,
  388. OSSL_LIB_CTX *libctx,
  389. const char *propq)
  390. {
  391. X509_SIG *p8 = NULL;
  392. char kbuf[PEM_BUFSIZE];
  393. char *pass = NULL;
  394. const X509_ALGOR *dalg = NULL;
  395. const ASN1_OCTET_STRING *doct = NULL;
  396. OSSL_STORE_INFO *store_info = NULL;
  397. BUF_MEM *mem = NULL;
  398. unsigned char *new_data = NULL;
  399. int new_data_len;
  400. if (pem_name != NULL) {
  401. if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
  402. return NULL;
  403. *matchcount = 1;
  404. }
  405. if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
  406. return NULL;
  407. *matchcount = 1;
  408. if ((mem = BUF_MEM_new()) == NULL) {
  409. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  410. goto nop8;
  411. }
  412. if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
  413. "PKCS8 decrypt pass phrase", uri,
  414. ui_data)) == NULL) {
  415. ATTICerr(0, ATTIC_R_BAD_PASSWORD_READ);
  416. goto nop8;
  417. }
  418. X509_SIG_get0(p8, &dalg, &doct);
  419. if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
  420. &new_data, &new_data_len, 0))
  421. goto nop8;
  422. mem->data = (char *)new_data;
  423. mem->max = mem->length = (size_t)new_data_len;
  424. X509_SIG_free(p8);
  425. p8 = NULL;
  426. store_info = new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
  427. if (store_info == NULL) {
  428. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  429. goto nop8;
  430. }
  431. return store_info;
  432. nop8:
  433. X509_SIG_free(p8);
  434. BUF_MEM_free(mem);
  435. return NULL;
  436. }
  437. static FILE_HANDLER PKCS8Encrypted_handler = {
  438. "PKCS8Encrypted",
  439. try_decode_PKCS8Encrypted
  440. };
  441. /*
  442. * Private key decoder. Decodes all sorts of private keys, both PKCS#8
  443. * encoded ones and old style PEM ones (with the key type is encoded into
  444. * the PEM name).
  445. */
  446. static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
  447. const char *pem_header,
  448. const unsigned char *blob,
  449. size_t len, void **pctx,
  450. int *matchcount,
  451. const UI_METHOD *ui_method,
  452. void *ui_data, const char *uri,
  453. OSSL_LIB_CTX *libctx,
  454. const char *propq)
  455. {
  456. OSSL_STORE_INFO *store_info = NULL;
  457. EVP_PKEY *pkey = NULL;
  458. const EVP_PKEY_ASN1_METHOD *ameth = NULL;
  459. if (pem_name != NULL) {
  460. if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
  461. PKCS8_PRIV_KEY_INFO *p8inf =
  462. d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
  463. *matchcount = 1;
  464. if (p8inf != NULL)
  465. pkey = EVP_PKCS82PKEY_ex(p8inf, libctx, propq);
  466. PKCS8_PRIV_KEY_INFO_free(p8inf);
  467. } else {
  468. int slen;
  469. int pkey_id;
  470. if ((slen = check_suffix(pem_name, "PRIVATE KEY")) > 0
  471. && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
  472. slen)) != NULL
  473. && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
  474. ameth)) {
  475. *matchcount = 1;
  476. pkey = d2i_PrivateKey_ex(pkey_id, NULL, &blob, len,
  477. libctx, propq);
  478. }
  479. }
  480. } else {
  481. int i;
  482. #ifndef OPENSSL_NO_ENGINE
  483. ENGINE *curengine = ENGINE_get_first();
  484. while (curengine != NULL) {
  485. ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
  486. ENGINE_get_pkey_asn1_meths(curengine);
  487. if (asn1meths != NULL) {
  488. const int *nids = NULL;
  489. int nids_n = asn1meths(curengine, NULL, &nids, 0);
  490. for (i = 0; i < nids_n; i++) {
  491. EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
  492. EVP_PKEY *tmp_pkey = NULL;
  493. const unsigned char *tmp_blob = blob;
  494. int pkey_id, pkey_flags;
  495. if (!asn1meths(curengine, &ameth2, NULL, nids[i])
  496. || !EVP_PKEY_asn1_get0_info(&pkey_id, NULL,
  497. &pkey_flags, NULL, NULL,
  498. ameth2)
  499. || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
  500. continue;
  501. ERR_set_mark(); /* prevent flooding error queue */
  502. tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL,
  503. &tmp_blob, len,
  504. libctx, propq);
  505. if (tmp_pkey != NULL) {
  506. if (pkey != NULL)
  507. EVP_PKEY_free(tmp_pkey);
  508. else
  509. pkey = tmp_pkey;
  510. (*matchcount)++;
  511. }
  512. ERR_pop_to_mark();
  513. }
  514. }
  515. curengine = ENGINE_get_next(curengine);
  516. }
  517. #endif
  518. for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
  519. EVP_PKEY *tmp_pkey = NULL;
  520. const unsigned char *tmp_blob = blob;
  521. int pkey_id, pkey_flags;
  522. ameth = EVP_PKEY_asn1_get0(i);
  523. if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
  524. NULL, ameth)
  525. || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
  526. continue;
  527. ERR_set_mark(); /* prevent flooding error queue */
  528. tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL, &tmp_blob, len,
  529. libctx, propq);
  530. if (tmp_pkey != NULL) {
  531. if (pkey != NULL)
  532. EVP_PKEY_free(tmp_pkey);
  533. else
  534. pkey = tmp_pkey;
  535. (*matchcount)++;
  536. }
  537. ERR_pop_to_mark();
  538. }
  539. if (*matchcount > 1) {
  540. EVP_PKEY_free(pkey);
  541. pkey = NULL;
  542. }
  543. }
  544. if (pkey == NULL)
  545. /* No match */
  546. return NULL;
  547. store_info = OSSL_STORE_INFO_new_PKEY(pkey);
  548. if (store_info == NULL)
  549. EVP_PKEY_free(pkey);
  550. return store_info;
  551. }
  552. static FILE_HANDLER PrivateKey_handler = {
  553. "PrivateKey",
  554. try_decode_PrivateKey
  555. };
  556. /*
  557. * Public key decoder. Only supports SubjectPublicKeyInfo formatted keys.
  558. */
  559. static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
  560. const char *pem_header,
  561. const unsigned char *blob,
  562. size_t len, void **pctx,
  563. int *matchcount,
  564. const UI_METHOD *ui_method,
  565. void *ui_data, const char *uri,
  566. OSSL_LIB_CTX *libctx,
  567. const char *propq)
  568. {
  569. OSSL_STORE_INFO *store_info = NULL;
  570. EVP_PKEY *pkey = NULL;
  571. if (pem_name != NULL) {
  572. if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
  573. /* No match */
  574. return NULL;
  575. *matchcount = 1;
  576. }
  577. if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
  578. *matchcount = 1;
  579. store_info = OSSL_STORE_INFO_new_PUBKEY(pkey);
  580. }
  581. return store_info;
  582. }
  583. static FILE_HANDLER PUBKEY_handler = {
  584. "PUBKEY",
  585. try_decode_PUBKEY
  586. };
  587. /*
  588. * Key parameter decoder.
  589. */
  590. static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
  591. const char *pem_header,
  592. const unsigned char *blob,
  593. size_t len, void **pctx,
  594. int *matchcount,
  595. const UI_METHOD *ui_method,
  596. void *ui_data, const char *uri,
  597. OSSL_LIB_CTX *libctx,
  598. const char *propq)
  599. {
  600. OSSL_STORE_INFO *store_info = NULL;
  601. EVP_PKEY *pkey = NULL;
  602. const EVP_PKEY_ASN1_METHOD *ameth = NULL;
  603. if (pem_name != NULL) {
  604. int slen;
  605. int pkey_id;
  606. if ((slen = check_suffix(pem_name, "PARAMETERS")) > 0
  607. && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL
  608. && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
  609. ameth)) {
  610. *matchcount = 1;
  611. pkey = d2i_KeyParams(pkey_id, NULL, &blob, len);
  612. }
  613. } else {
  614. int i;
  615. for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
  616. EVP_PKEY *tmp_pkey = NULL;
  617. const unsigned char *tmp_blob = blob;
  618. int pkey_id, pkey_flags;
  619. ameth = EVP_PKEY_asn1_get0(i);
  620. if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
  621. NULL, ameth)
  622. || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
  623. continue;
  624. ERR_set_mark(); /* prevent flooding error queue */
  625. tmp_pkey = d2i_KeyParams(pkey_id, NULL, &tmp_blob, len);
  626. if (tmp_pkey != NULL) {
  627. if (pkey != NULL)
  628. EVP_PKEY_free(tmp_pkey);
  629. else
  630. pkey = tmp_pkey;
  631. (*matchcount)++;
  632. }
  633. ERR_pop_to_mark();
  634. }
  635. if (*matchcount > 1) {
  636. EVP_PKEY_free(pkey);
  637. pkey = NULL;
  638. }
  639. }
  640. if (pkey == NULL)
  641. /* No match */
  642. return NULL;
  643. store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
  644. if (store_info == NULL)
  645. EVP_PKEY_free(pkey);
  646. return store_info;
  647. }
  648. static FILE_HANDLER params_handler = {
  649. "params",
  650. try_decode_params
  651. };
  652. /*
  653. * X.509 certificate decoder.
  654. */
  655. static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
  656. const char *pem_header,
  657. const unsigned char *blob,
  658. size_t len, void **pctx,
  659. int *matchcount,
  660. const UI_METHOD *ui_method,
  661. void *ui_data,
  662. const char *uri,
  663. OSSL_LIB_CTX *libctx,
  664. const char *propq)
  665. {
  666. OSSL_STORE_INFO *store_info = NULL;
  667. X509 *cert = NULL;
  668. /*
  669. * In most cases, we can try to interpret the serialized data as a trusted
  670. * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
  671. * (just X509), but if the PEM name specifically declares it as a trusted
  672. * cert, then no fallback should be engaged. |ignore_trusted| tells if
  673. * the fallback can be used (1) or not (0).
  674. */
  675. int ignore_trusted = 1;
  676. if (pem_name != NULL) {
  677. if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
  678. ignore_trusted = 0;
  679. else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
  680. && strcmp(pem_name, PEM_STRING_X509) != 0)
  681. /* No match */
  682. return NULL;
  683. *matchcount = 1;
  684. }
  685. cert = X509_new_ex(libctx, propq);
  686. if (cert == NULL)
  687. return NULL;
  688. if ((d2i_X509_AUX(&cert, &blob, len)) != NULL
  689. || (ignore_trusted && (d2i_X509(&cert, &blob, len)) != NULL)) {
  690. *matchcount = 1;
  691. store_info = OSSL_STORE_INFO_new_CERT(cert);
  692. }
  693. if (store_info == NULL)
  694. X509_free(cert);
  695. return store_info;
  696. }
  697. static FILE_HANDLER X509Certificate_handler = {
  698. "X509Certificate",
  699. try_decode_X509Certificate
  700. };
  701. /*
  702. * X.509 CRL decoder.
  703. */
  704. static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
  705. const char *pem_header,
  706. const unsigned char *blob,
  707. size_t len, void **pctx,
  708. int *matchcount,
  709. const UI_METHOD *ui_method,
  710. void *ui_data, const char *uri,
  711. OSSL_LIB_CTX *libctx,
  712. const char *propq)
  713. {
  714. OSSL_STORE_INFO *store_info = NULL;
  715. X509_CRL *crl = NULL;
  716. if (pem_name != NULL) {
  717. if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
  718. /* No match */
  719. return NULL;
  720. *matchcount = 1;
  721. }
  722. if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
  723. *matchcount = 1;
  724. store_info = OSSL_STORE_INFO_new_CRL(crl);
  725. }
  726. if (store_info == NULL)
  727. X509_CRL_free(crl);
  728. return store_info;
  729. }
  730. static FILE_HANDLER X509CRL_handler = {
  731. "X509CRL",
  732. try_decode_X509CRL
  733. };
  734. /*
  735. * To finish it all off, we collect all the handlers.
  736. */
  737. static const FILE_HANDLER *file_handlers[] = {
  738. &PKCS12_handler,
  739. &PKCS8Encrypted_handler,
  740. &X509Certificate_handler,
  741. &X509CRL_handler,
  742. &params_handler,
  743. &PUBKEY_handler,
  744. &PrivateKey_handler,
  745. };
  746. /*-
  747. * The loader itself
  748. * -----------------
  749. */
  750. struct ossl_store_loader_ctx_st {
  751. char *uri; /* The URI we currently try to load */
  752. enum {
  753. is_raw = 0,
  754. is_pem,
  755. is_dir
  756. } type;
  757. int errcnt;
  758. #define FILE_FLAG_SECMEM (1<<0)
  759. #define FILE_FLAG_ATTACHED (1<<1)
  760. unsigned int flags;
  761. union {
  762. struct { /* Used with is_raw and is_pem */
  763. BIO *file;
  764. /*
  765. * The following are used when the handler is marked as
  766. * repeatable
  767. */
  768. const FILE_HANDLER *last_handler;
  769. void *last_handler_ctx;
  770. } file;
  771. struct { /* Used with is_dir */
  772. OPENSSL_DIR_CTX *ctx;
  773. int end_reached;
  774. /*
  775. * When a search expression is given, these are filled in.
  776. * |search_name| contains the file basename to look for.
  777. * The string is exactly 8 characters long.
  778. */
  779. char search_name[9];
  780. /*
  781. * The directory reading utility we have combines opening with
  782. * reading the first name. To make sure we can detect the end
  783. * at the right time, we read early and cache the name.
  784. */
  785. const char *last_entry;
  786. int last_errno;
  787. } dir;
  788. } _;
  789. /* Expected object type. May be unspecified */
  790. int expected_type;
  791. OSSL_LIB_CTX *libctx;
  792. char *propq;
  793. };
  794. static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
  795. {
  796. if (ctx == NULL)
  797. return;
  798. OPENSSL_free(ctx->propq);
  799. OPENSSL_free(ctx->uri);
  800. if (ctx->type != is_dir) {
  801. if (ctx->_.file.last_handler != NULL) {
  802. ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
  803. ctx->_.file.last_handler_ctx = NULL;
  804. ctx->_.file.last_handler = NULL;
  805. }
  806. }
  807. OPENSSL_free(ctx);
  808. }
  809. static int file_find_type(OSSL_STORE_LOADER_CTX *ctx)
  810. {
  811. BIO *buff = NULL;
  812. char peekbuf[4096] = { 0, };
  813. if ((buff = BIO_new(BIO_f_buffer())) == NULL)
  814. return 0;
  815. ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
  816. if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
  817. peekbuf[sizeof(peekbuf) - 1] = '\0';
  818. if (strstr(peekbuf, "-----BEGIN ") != NULL)
  819. ctx->type = is_pem;
  820. }
  821. return 1;
  822. }
  823. static OSSL_STORE_LOADER_CTX *file_open_ex
  824. (const OSSL_STORE_LOADER *loader, const char *uri,
  825. OSSL_LIB_CTX *libctx, const char *propq,
  826. const UI_METHOD *ui_method, void *ui_data)
  827. {
  828. OSSL_STORE_LOADER_CTX *ctx = NULL;
  829. struct stat st;
  830. struct {
  831. const char *path;
  832. unsigned int check_absolute:1;
  833. } path_data[2];
  834. size_t path_data_n = 0, i;
  835. const char *path;
  836. /*
  837. * First step, just take the URI as is.
  838. */
  839. path_data[path_data_n].check_absolute = 0;
  840. path_data[path_data_n++].path = uri;
  841. /*
  842. * Second step, if the URI appears to start with the 'file' scheme,
  843. * extract the path and make that the second path to check.
  844. * There's a special case if the URI also contains an authority, then
  845. * the full URI shouldn't be used as a path anywhere.
  846. */
  847. if (OPENSSL_strncasecmp(uri, "file:", 5) == 0) {
  848. const char *p = &uri[5];
  849. if (strncmp(&uri[5], "//", 2) == 0) {
  850. path_data_n--; /* Invalidate using the full URI */
  851. if (OPENSSL_strncasecmp(&uri[7], "localhost/", 10) == 0) {
  852. p = &uri[16];
  853. } else if (uri[7] == '/') {
  854. p = &uri[7];
  855. } else {
  856. ATTICerr(0, ATTIC_R_URI_AUTHORITY_UNSUPPORTED);
  857. return NULL;
  858. }
  859. }
  860. path_data[path_data_n].check_absolute = 1;
  861. #ifdef _WIN32
  862. /* Windows file: URIs with a drive letter start with a / */
  863. if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
  864. char c = tolower(p[1]);
  865. if (c >= 'a' && c <= 'z') {
  866. p++;
  867. /* We know it's absolute, so no need to check */
  868. path_data[path_data_n].check_absolute = 0;
  869. }
  870. }
  871. #endif
  872. path_data[path_data_n++].path = p;
  873. }
  874. for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
  875. /*
  876. * If the scheme "file" was an explicit part of the URI, the path must
  877. * be absolute. So says RFC 8089
  878. */
  879. if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
  880. ATTICerr(0, ATTIC_R_PATH_MUST_BE_ABSOLUTE);
  881. ERR_add_error_data(1, path_data[i].path);
  882. return NULL;
  883. }
  884. if (stat(path_data[i].path, &st) < 0) {
  885. ERR_raise_data(ERR_LIB_SYS, errno,
  886. "calling stat(%s)",
  887. path_data[i].path);
  888. } else {
  889. path = path_data[i].path;
  890. }
  891. }
  892. if (path == NULL) {
  893. return NULL;
  894. }
  895. /* Successfully found a working path */
  896. ctx = OPENSSL_zalloc(sizeof(*ctx));
  897. if (ctx == NULL) {
  898. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  899. return NULL;
  900. }
  901. ctx->uri = OPENSSL_strdup(uri);
  902. if (ctx->uri == NULL) {
  903. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  904. goto err;
  905. }
  906. if (S_ISDIR(st.st_mode)) {
  907. ctx->type = is_dir;
  908. ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
  909. ctx->_.dir.last_errno = errno;
  910. if (ctx->_.dir.last_entry == NULL) {
  911. if (ctx->_.dir.last_errno != 0) {
  912. ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
  913. goto err;
  914. }
  915. ctx->_.dir.end_reached = 1;
  916. }
  917. } else if ((ctx->_.file.file = BIO_new_file(path, "rb")) == NULL
  918. || !file_find_type(ctx)) {
  919. BIO_free_all(ctx->_.file.file);
  920. goto err;
  921. }
  922. if (propq != NULL) {
  923. ctx->propq = OPENSSL_strdup(propq);
  924. if (ctx->propq == NULL) {
  925. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  926. goto err;
  927. }
  928. }
  929. ctx->libctx = libctx;
  930. return ctx;
  931. err:
  932. OSSL_STORE_LOADER_CTX_free(ctx);
  933. return NULL;
  934. }
  935. static OSSL_STORE_LOADER_CTX *file_open
  936. (const OSSL_STORE_LOADER *loader, const char *uri,
  937. const UI_METHOD *ui_method, void *ui_data)
  938. {
  939. return file_open_ex(loader, uri, NULL, NULL, ui_method, ui_data);
  940. }
  941. static OSSL_STORE_LOADER_CTX *file_attach
  942. (const OSSL_STORE_LOADER *loader, BIO *bp,
  943. OSSL_LIB_CTX *libctx, const char *propq,
  944. const UI_METHOD *ui_method, void *ui_data)
  945. {
  946. OSSL_STORE_LOADER_CTX *ctx = NULL;
  947. if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL
  948. || (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)) {
  949. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  950. OSSL_STORE_LOADER_CTX_free(ctx);
  951. return NULL;
  952. }
  953. ctx->libctx = libctx;
  954. ctx->flags |= FILE_FLAG_ATTACHED;
  955. ctx->_.file.file = bp;
  956. if (!file_find_type(ctx)) {
  957. /* Safety measure */
  958. ctx->_.file.file = NULL;
  959. goto err;
  960. }
  961. return ctx;
  962. err:
  963. OSSL_STORE_LOADER_CTX_free(ctx);
  964. return NULL;
  965. }
  966. static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
  967. {
  968. int ret = 1;
  969. switch (cmd) {
  970. case OSSL_STORE_C_USE_SECMEM:
  971. {
  972. int on = *(va_arg(args, int *));
  973. switch (on) {
  974. case 0:
  975. ctx->flags &= ~FILE_FLAG_SECMEM;
  976. break;
  977. case 1:
  978. ctx->flags |= FILE_FLAG_SECMEM;
  979. break;
  980. default:
  981. ATTICerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
  982. ret = 0;
  983. break;
  984. }
  985. }
  986. break;
  987. default:
  988. break;
  989. }
  990. return ret;
  991. }
  992. static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
  993. {
  994. ctx->expected_type = expected;
  995. return 1;
  996. }
  997. static int file_find(OSSL_STORE_LOADER_CTX *ctx,
  998. const OSSL_STORE_SEARCH *search)
  999. {
  1000. /*
  1001. * If ctx == NULL, the library is looking to know if this loader supports
  1002. * the given search type.
  1003. */
  1004. if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
  1005. unsigned long hash = 0;
  1006. if (ctx == NULL)
  1007. return 1;
  1008. if (ctx->type != is_dir) {
  1009. ATTICerr(0, ATTIC_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
  1010. return 0;
  1011. }
  1012. hash = X509_NAME_hash_ex(OSSL_STORE_SEARCH_get0_name(search),
  1013. NULL, NULL, NULL);
  1014. BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
  1015. "%08lx", hash);
  1016. return 1;
  1017. }
  1018. if (ctx != NULL)
  1019. ATTICerr(0, ATTIC_R_UNSUPPORTED_SEARCH_TYPE);
  1020. return 0;
  1021. }
  1022. static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
  1023. const char *pem_name,
  1024. const char *pem_header,
  1025. unsigned char *data, size_t len,
  1026. const UI_METHOD *ui_method,
  1027. void *ui_data, int *matchcount)
  1028. {
  1029. OSSL_STORE_INFO *result = NULL;
  1030. BUF_MEM *new_mem = NULL;
  1031. char *new_pem_name = NULL;
  1032. int t = 0;
  1033. again:
  1034. {
  1035. size_t i = 0;
  1036. void *handler_ctx = NULL;
  1037. const FILE_HANDLER **matching_handlers =
  1038. OPENSSL_zalloc(sizeof(*matching_handlers)
  1039. * OSSL_NELEM(file_handlers));
  1040. if (matching_handlers == NULL) {
  1041. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  1042. goto err;
  1043. }
  1044. *matchcount = 0;
  1045. for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
  1046. const FILE_HANDLER *handler = file_handlers[i];
  1047. int try_matchcount = 0;
  1048. void *tmp_handler_ctx = NULL;
  1049. OSSL_STORE_INFO *tmp_result;
  1050. unsigned long err;
  1051. ERR_set_mark();
  1052. tmp_result =
  1053. handler->try_decode(pem_name, pem_header, data, len,
  1054. &tmp_handler_ctx, &try_matchcount,
  1055. ui_method, ui_data, ctx->uri,
  1056. ctx->libctx, ctx->propq);
  1057. /* avoid flooding error queue with low-level ASN.1 parse errors */
  1058. err = ERR_peek_last_error();
  1059. if (ERR_GET_LIB(err) == ERR_LIB_ASN1
  1060. && ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR)
  1061. ERR_pop_to_mark();
  1062. else
  1063. ERR_clear_last_mark();
  1064. if (try_matchcount > 0) {
  1065. matching_handlers[*matchcount] = handler;
  1066. if (handler_ctx)
  1067. handler->destroy_ctx(&handler_ctx);
  1068. handler_ctx = tmp_handler_ctx;
  1069. if ((*matchcount += try_matchcount) > 1) {
  1070. /* more than one match => ambiguous, kill any result */
  1071. store_info_free(result);
  1072. store_info_free(tmp_result);
  1073. if (handler->destroy_ctx != NULL)
  1074. handler->destroy_ctx(&handler_ctx);
  1075. handler_ctx = NULL;
  1076. tmp_result = NULL;
  1077. result = NULL;
  1078. }
  1079. if (result == NULL)
  1080. result = tmp_result;
  1081. if (result == NULL) /* e.g., PKCS#12 file decryption error */
  1082. break;
  1083. }
  1084. }
  1085. if (result != NULL
  1086. && *matchcount == 1 && matching_handlers[0]->repeatable) {
  1087. ctx->_.file.last_handler = matching_handlers[0];
  1088. ctx->_.file.last_handler_ctx = handler_ctx;
  1089. }
  1090. OPENSSL_free(matching_handlers);
  1091. }
  1092. err:
  1093. OPENSSL_free(new_pem_name);
  1094. BUF_MEM_free(new_mem);
  1095. if (result != NULL
  1096. && (t = OSSL_STORE_INFO_get_type(result)) == STORE_INFO_EMBEDDED) {
  1097. struct embedded_st *embedded = get0_EMBEDDED(result);
  1098. /* "steal" the embedded data */
  1099. pem_name = new_pem_name = embedded->pem_name;
  1100. new_mem = embedded->blob;
  1101. data = (unsigned char *)new_mem->data;
  1102. len = new_mem->length;
  1103. embedded->pem_name = NULL;
  1104. embedded->blob = NULL;
  1105. store_info_free(result);
  1106. result = NULL;
  1107. goto again;
  1108. }
  1109. return result;
  1110. }
  1111. static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
  1112. const UI_METHOD *ui_method,
  1113. void *ui_data)
  1114. {
  1115. OSSL_STORE_INFO *result = NULL;
  1116. int try_matchcount = 0;
  1117. if (ctx->_.file.last_handler != NULL) {
  1118. result =
  1119. ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
  1120. &ctx->_.file.last_handler_ctx,
  1121. &try_matchcount,
  1122. ui_method, ui_data, ctx->uri,
  1123. ctx->libctx, ctx->propq);
  1124. if (result == NULL) {
  1125. ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
  1126. ctx->_.file.last_handler_ctx = NULL;
  1127. ctx->_.file.last_handler = NULL;
  1128. }
  1129. }
  1130. return result;
  1131. }
  1132. static void pem_free_flag(void *pem_data, int secure, size_t num)
  1133. {
  1134. if (secure)
  1135. OPENSSL_secure_clear_free(pem_data, num);
  1136. else
  1137. OPENSSL_free(pem_data);
  1138. }
  1139. static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
  1140. unsigned char **data, long *len,
  1141. const UI_METHOD *ui_method, void *ui_data,
  1142. const char *uri, int secure)
  1143. {
  1144. int i = secure
  1145. ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
  1146. PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
  1147. : PEM_read_bio(bp, pem_name, pem_header, data, len);
  1148. if (i <= 0)
  1149. return 0;
  1150. /*
  1151. * 10 is the number of characters in "Proc-Type:", which
  1152. * PEM_get_EVP_CIPHER_INFO() requires to be present.
  1153. * If the PEM header has less characters than that, it's
  1154. * not worth spending cycles on it.
  1155. */
  1156. if (strlen(*pem_header) > 10) {
  1157. EVP_CIPHER_INFO cipher;
  1158. struct pem_pass_data pass_data;
  1159. if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
  1160. || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
  1161. ui_method, ui_data)
  1162. || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
  1163. &pass_data)) {
  1164. return 0;
  1165. }
  1166. }
  1167. return 1;
  1168. }
  1169. static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
  1170. {
  1171. OSSL_STORE_INFO *result = NULL;
  1172. int ispub = -1;
  1173. {
  1174. unsigned int magic = 0, bitlen = 0;
  1175. int isdss = 0;
  1176. unsigned char peekbuf[16] = { 0, };
  1177. const unsigned char *p = peekbuf;
  1178. if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
  1179. return 0;
  1180. if (ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
  1181. &isdss, &ispub) <= 0)
  1182. return 0;
  1183. }
  1184. (*matchcount)++;
  1185. {
  1186. EVP_PKEY *tmp = ispub
  1187. ? b2i_PublicKey_bio(bp)
  1188. : b2i_PrivateKey_bio(bp);
  1189. if (tmp == NULL
  1190. || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
  1191. EVP_PKEY_free(tmp);
  1192. return 0;
  1193. }
  1194. }
  1195. return result;
  1196. }
  1197. static OSSL_STORE_INFO *file_try_read_PVK(BIO *bp, const UI_METHOD *ui_method,
  1198. void *ui_data, const char *uri,
  1199. int *matchcount)
  1200. {
  1201. OSSL_STORE_INFO *result = NULL;
  1202. {
  1203. unsigned int saltlen = 0, keylen = 0;
  1204. unsigned char peekbuf[24] = { 0, };
  1205. const unsigned char *p = peekbuf;
  1206. if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
  1207. return 0;
  1208. if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
  1209. return 0;
  1210. }
  1211. (*matchcount)++;
  1212. {
  1213. EVP_PKEY *tmp = NULL;
  1214. struct pem_pass_data pass_data;
  1215. if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
  1216. ui_method, ui_data)
  1217. || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
  1218. || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
  1219. EVP_PKEY_free(tmp);
  1220. return 0;
  1221. }
  1222. }
  1223. return result;
  1224. }
  1225. static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
  1226. {
  1227. BUF_MEM *mem = NULL;
  1228. if (asn1_d2i_read_bio(bp, &mem) < 0)
  1229. return 0;
  1230. *data = (unsigned char *)mem->data;
  1231. *len = (long)mem->length;
  1232. OPENSSL_free(mem);
  1233. return 1;
  1234. }
  1235. static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
  1236. char **data)
  1237. {
  1238. assert(name != NULL);
  1239. assert(data != NULL);
  1240. {
  1241. const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
  1242. long calculated_length = strlen(ctx->uri) + strlen(pathsep)
  1243. + strlen(name) + 1 /* \0 */;
  1244. *data = OPENSSL_zalloc(calculated_length);
  1245. if (*data == NULL) {
  1246. ATTICerr(0, ERR_R_MALLOC_FAILURE);
  1247. return 0;
  1248. }
  1249. OPENSSL_strlcat(*data, ctx->uri, calculated_length);
  1250. OPENSSL_strlcat(*data, pathsep, calculated_length);
  1251. OPENSSL_strlcat(*data, name, calculated_length);
  1252. }
  1253. return 1;
  1254. }
  1255. static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
  1256. {
  1257. const char *p = NULL;
  1258. size_t len = strlen(ctx->_.dir.search_name);
  1259. /* If there are no search criteria, all names are accepted */
  1260. if (ctx->_.dir.search_name[0] == '\0')
  1261. return 1;
  1262. /* If the expected type isn't supported, no name is accepted */
  1263. if (ctx->expected_type != 0
  1264. && ctx->expected_type != OSSL_STORE_INFO_CERT
  1265. && ctx->expected_type != OSSL_STORE_INFO_CRL)
  1266. return 0;
  1267. /*
  1268. * First, check the basename
  1269. */
  1270. if (OPENSSL_strncasecmp(name, ctx->_.dir.search_name, len) != 0
  1271. || name[len] != '.')
  1272. return 0;
  1273. p = &name[len + 1];
  1274. /*
  1275. * Then, if the expected type is a CRL, check that the extension starts
  1276. * with 'r'
  1277. */
  1278. if (*p == 'r') {
  1279. p++;
  1280. if (ctx->expected_type != 0
  1281. && ctx->expected_type != OSSL_STORE_INFO_CRL)
  1282. return 0;
  1283. } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
  1284. return 0;
  1285. }
  1286. /*
  1287. * Last, check that the rest of the extension is a decimal number, at
  1288. * least one digit long.
  1289. */
  1290. if (!isdigit((unsigned char)*p))
  1291. return 0;
  1292. while (isdigit((unsigned char)*p))
  1293. p++;
  1294. #ifdef __VMS
  1295. /*
  1296. * One extra step here, check for a possible generation number.
  1297. */
  1298. if (*p == ';')
  1299. for (p++; *p != '\0'; p++)
  1300. if (!ossl_isdigit(*p))
  1301. break;
  1302. #endif
  1303. /*
  1304. * If we've reached the end of the string at this point, we've successfully
  1305. * found a fitting file name.
  1306. */
  1307. return *p == '\0';
  1308. }
  1309. static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
  1310. static int file_error(OSSL_STORE_LOADER_CTX *ctx);
  1311. static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
  1312. const UI_METHOD *ui_method,
  1313. void *ui_data)
  1314. {
  1315. OSSL_STORE_INFO *result = NULL;
  1316. ctx->errcnt = 0;
  1317. if (ctx->type == is_dir) {
  1318. do {
  1319. char *newname = NULL;
  1320. if (ctx->_.dir.last_entry == NULL) {
  1321. if (!ctx->_.dir.end_reached) {
  1322. assert(ctx->_.dir.last_errno != 0);
  1323. ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
  1324. ctx->errcnt++;
  1325. }
  1326. return NULL;
  1327. }
  1328. if (ctx->_.dir.last_entry[0] != '.'
  1329. && file_name_check(ctx, ctx->_.dir.last_entry)
  1330. && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
  1331. return NULL;
  1332. /*
  1333. * On the first call (with a NULL context), OPENSSL_DIR_read()
  1334. * cares about the second argument. On the following calls, it
  1335. * only cares that it isn't NULL. Therefore, we can safely give
  1336. * it our URI here.
  1337. */
  1338. ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
  1339. ctx->_.dir.last_errno = errno;
  1340. if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
  1341. ctx->_.dir.end_reached = 1;
  1342. if (newname != NULL
  1343. && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
  1344. OPENSSL_free(newname);
  1345. ATTICerr(0, ERR_R_OSSL_STORE_LIB);
  1346. return NULL;
  1347. }
  1348. } while (result == NULL && !file_eof(ctx));
  1349. } else {
  1350. int matchcount = -1;
  1351. again:
  1352. result = file_load_try_repeat(ctx, ui_method, ui_data);
  1353. if (result != NULL)
  1354. return result;
  1355. if (file_eof(ctx))
  1356. return NULL;
  1357. do {
  1358. char *pem_name = NULL; /* PEM record name */
  1359. char *pem_header = NULL; /* PEM record header */
  1360. unsigned char *data = NULL; /* DER encoded data */
  1361. long len = 0; /* DER encoded data length */
  1362. matchcount = -1;
  1363. if (ctx->type == is_pem) {
  1364. if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
  1365. &data, &len, ui_method, ui_data, ctx->uri,
  1366. (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
  1367. ctx->errcnt++;
  1368. goto endloop;
  1369. }
  1370. } else {
  1371. if ((result = file_try_read_msblob(ctx->_.file.file,
  1372. &matchcount)) != NULL
  1373. || (result = file_try_read_PVK(ctx->_.file.file,
  1374. ui_method, ui_data, ctx->uri,
  1375. &matchcount)) != NULL)
  1376. goto endloop;
  1377. if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
  1378. ctx->errcnt++;
  1379. goto endloop;
  1380. }
  1381. }
  1382. result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
  1383. ui_method, ui_data, &matchcount);
  1384. if (result != NULL)
  1385. goto endloop;
  1386. /*
  1387. * If a PEM name matches more than one handler, the handlers are
  1388. * badly coded.
  1389. */
  1390. if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
  1391. ctx->errcnt++;
  1392. goto endloop;
  1393. }
  1394. if (matchcount > 1) {
  1395. ATTICerr(0, ATTIC_R_AMBIGUOUS_CONTENT_TYPE);
  1396. } else if (matchcount == 1) {
  1397. /*
  1398. * If there are other errors on the stack, they already show
  1399. * what the problem is.
  1400. */
  1401. if (ERR_peek_error() == 0) {
  1402. ATTICerr(0, ATTIC_R_UNSUPPORTED_CONTENT_TYPE);
  1403. if (pem_name != NULL)
  1404. ERR_add_error_data(3, "PEM type is '", pem_name, "'");
  1405. }
  1406. }
  1407. if (matchcount > 0)
  1408. ctx->errcnt++;
  1409. endloop:
  1410. pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
  1411. pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
  1412. pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
  1413. } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
  1414. /* We bail out on ambiguity */
  1415. if (matchcount > 1) {
  1416. store_info_free(result);
  1417. return NULL;
  1418. }
  1419. if (result != NULL
  1420. && ctx->expected_type != 0
  1421. && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
  1422. store_info_free(result);
  1423. goto again;
  1424. }
  1425. }
  1426. return result;
  1427. }
  1428. static int file_error(OSSL_STORE_LOADER_CTX *ctx)
  1429. {
  1430. return ctx->errcnt > 0;
  1431. }
  1432. static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
  1433. {
  1434. if (ctx->type == is_dir)
  1435. return ctx->_.dir.end_reached;
  1436. if (ctx->_.file.last_handler != NULL
  1437. && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
  1438. return 0;
  1439. return BIO_eof(ctx->_.file.file);
  1440. }
  1441. static int file_close(OSSL_STORE_LOADER_CTX *ctx)
  1442. {
  1443. if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
  1444. if (ctx->type == is_dir)
  1445. OPENSSL_DIR_end(&ctx->_.dir.ctx);
  1446. else
  1447. BIO_free_all(ctx->_.file.file);
  1448. } else {
  1449. /*
  1450. * Because file_attach() called file_find_type(), we know that a
  1451. * BIO_f_buffer() has been pushed on top of the regular BIO.
  1452. */
  1453. BIO *buff = ctx->_.file.file;
  1454. /* Detach buff */
  1455. (void)BIO_pop(ctx->_.file.file);
  1456. /* Safety measure */
  1457. ctx->_.file.file = NULL;
  1458. BIO_free(buff);
  1459. }
  1460. OSSL_STORE_LOADER_CTX_free(ctx);
  1461. return 1;
  1462. }
  1463. /*-
  1464. * ENGINE management
  1465. */
  1466. static const char *loader_attic_id = "loader_attic";
  1467. static const char *loader_attic_name = "'file:' loader";
  1468. static OSSL_STORE_LOADER *loader_attic = NULL;
  1469. static int loader_attic_init(ENGINE *e)
  1470. {
  1471. return 1;
  1472. }
  1473. static int loader_attic_finish(ENGINE *e)
  1474. {
  1475. return 1;
  1476. }
  1477. static int loader_attic_destroy(ENGINE *e)
  1478. {
  1479. OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader("file");
  1480. if (loader == NULL)
  1481. return 0;
  1482. ERR_unload_ATTIC_strings();
  1483. OSSL_STORE_LOADER_free(loader);
  1484. return 1;
  1485. }
  1486. static int bind_loader_attic(ENGINE *e)
  1487. {
  1488. /* Ensure the ATTIC error handling is set up on best effort basis */
  1489. ERR_load_ATTIC_strings();
  1490. if (/* Create the OSSL_STORE_LOADER */
  1491. (loader_attic = OSSL_STORE_LOADER_new(e, "file")) == NULL
  1492. || !OSSL_STORE_LOADER_set_open_ex(loader_attic, file_open_ex)
  1493. || !OSSL_STORE_LOADER_set_open(loader_attic, file_open)
  1494. || !OSSL_STORE_LOADER_set_attach(loader_attic, file_attach)
  1495. || !OSSL_STORE_LOADER_set_ctrl(loader_attic, file_ctrl)
  1496. || !OSSL_STORE_LOADER_set_expect(loader_attic, file_expect)
  1497. || !OSSL_STORE_LOADER_set_find(loader_attic, file_find)
  1498. || !OSSL_STORE_LOADER_set_load(loader_attic, file_load)
  1499. || !OSSL_STORE_LOADER_set_eof(loader_attic, file_eof)
  1500. || !OSSL_STORE_LOADER_set_error(loader_attic, file_error)
  1501. || !OSSL_STORE_LOADER_set_close(loader_attic, file_close)
  1502. /* Init the engine itself */
  1503. || !ENGINE_set_id(e, loader_attic_id)
  1504. || !ENGINE_set_name(e, loader_attic_name)
  1505. || !ENGINE_set_destroy_function(e, loader_attic_destroy)
  1506. || !ENGINE_set_init_function(e, loader_attic_init)
  1507. || !ENGINE_set_finish_function(e, loader_attic_finish)
  1508. /* Finally, register the method with libcrypto */
  1509. || !OSSL_STORE_register_loader(loader_attic)) {
  1510. OSSL_STORE_LOADER_free(loader_attic);
  1511. loader_attic = NULL;
  1512. ATTICerr(0, ATTIC_R_INIT_FAILED);
  1513. return 0;
  1514. }
  1515. return 1;
  1516. }
  1517. #ifdef OPENSSL_NO_DYNAMIC_ENGINE
  1518. # error "Only allowed as dynamically shared object"
  1519. #endif
  1520. static int bind_helper(ENGINE *e, const char *id)
  1521. {
  1522. if (id && (strcmp(id, loader_attic_id) != 0))
  1523. return 0;
  1524. if (!bind_loader_attic(e))
  1525. return 0;
  1526. return 1;
  1527. }
  1528. IMPLEMENT_DYNAMIC_CHECK_FN()
  1529. IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)