ocsp.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. /*
  2. * Copyright 2001-2018 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. #include <openssl/opensslconf.h>
  10. #ifdef OPENSSL_NO_OCSP
  11. NON_EMPTY_TRANSLATION_UNIT
  12. #else
  13. # ifdef OPENSSL_SYS_VMS
  14. # define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
  15. * on OpenVMS */
  16. # endif
  17. # include <stdio.h>
  18. # include <stdlib.h>
  19. # include <string.h>
  20. # include <time.h>
  21. # include <ctype.h>
  22. /* Needs to be included before the openssl headers */
  23. # include "apps.h"
  24. # include "progs.h"
  25. # include "internal/sockets.h"
  26. # include <openssl/e_os2.h>
  27. # include <openssl/crypto.h>
  28. # include <openssl/err.h>
  29. # include <openssl/ssl.h>
  30. # include <openssl/evp.h>
  31. # include <openssl/bn.h>
  32. # include <openssl/x509v3.h>
  33. # include <openssl/rand.h>
  34. # if defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_NO_SOCK) \
  35. && !defined(OPENSSL_NO_POSIX_IO)
  36. # define OCSP_DAEMON
  37. # include <sys/types.h>
  38. # include <sys/wait.h>
  39. # include <syslog.h>
  40. # include <signal.h>
  41. # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
  42. # else
  43. # undef LOG_INFO
  44. # undef LOG_WARNING
  45. # undef LOG_ERR
  46. # define LOG_INFO 0
  47. # define LOG_WARNING 1
  48. # define LOG_ERR 2
  49. # endif
  50. /* Maximum leeway in validity period: default 5 minutes */
  51. # define MAX_VALIDITY_PERIOD (5 * 60)
  52. static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
  53. const EVP_MD *cert_id_md, X509 *issuer,
  54. STACK_OF(OCSP_CERTID) *ids);
  55. static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
  56. const EVP_MD *cert_id_md, X509 *issuer,
  57. STACK_OF(OCSP_CERTID) *ids);
  58. static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
  59. STACK_OF(OPENSSL_STRING) *names,
  60. STACK_OF(OCSP_CERTID) *ids, long nsec,
  61. long maxage);
  62. static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
  63. CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
  64. EVP_PKEY *rkey, const EVP_MD *md,
  65. STACK_OF(OPENSSL_STRING) *sigopts,
  66. STACK_OF(X509) *rother, unsigned long flags,
  67. int nmin, int ndays, int badsig);
  68. static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
  69. static BIO *init_responder(const char *port);
  70. static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
  71. static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
  72. static void log_message(int level, const char *fmt, ...);
  73. static char *prog;
  74. static int multi = 0;
  75. # ifdef OCSP_DAEMON
  76. static int acfd = (int) INVALID_SOCKET;
  77. static int index_changed(CA_DB *);
  78. static void spawn_loop(void);
  79. static int print_syslog(const char *str, size_t len, void *levPtr);
  80. static void sock_timeout(int signum);
  81. # endif
  82. # ifndef OPENSSL_NO_SOCK
  83. static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
  84. const char *path,
  85. const STACK_OF(CONF_VALUE) *headers,
  86. OCSP_REQUEST *req, int req_timeout);
  87. # endif
  88. typedef enum OPTION_choice {
  89. OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
  90. OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
  91. OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
  92. OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
  93. OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
  94. OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
  95. OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
  96. OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
  97. OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH,
  98. OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
  99. OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
  100. OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
  101. OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
  102. OPT_V_ENUM,
  103. OPT_MD,
  104. OPT_MULTI
  105. } OPTION_CHOICE;
  106. const OPTIONS ocsp_options[] = {
  107. {"help", OPT_HELP, '-', "Display this summary"},
  108. {"out", OPT_OUTFILE, '>', "Output filename"},
  109. {"timeout", OPT_TIMEOUT, 'p',
  110. "Connection timeout (in seconds) to the OCSP responder"},
  111. {"url", OPT_URL, 's', "Responder URL"},
  112. {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
  113. {"port", OPT_PORT, 'p', "Port to run responder on"},
  114. {"ignore_err", OPT_IGNORE_ERR, '-',
  115. "Ignore error on OCSP request or response and continue running"},
  116. {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
  117. {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
  118. {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
  119. {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
  120. "Don't include any certificates in response"},
  121. {"resp_key_id", OPT_RESP_KEY_ID, '-',
  122. "Identify response by signing certificate key ID"},
  123. # ifdef OCSP_DAEMON
  124. {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
  125. # endif
  126. {"no_certs", OPT_NO_CERTS, '-',
  127. "Don't include any certificates in signed request"},
  128. {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
  129. "Don't check signature on response"},
  130. {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
  131. "Don't check signing certificate"},
  132. {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
  133. {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
  134. "Don't do additional checks on signing certificate"},
  135. {"no_explicit", OPT_NO_EXPLICIT, '-',
  136. "Do not explicitly check the chain, just verify the root"},
  137. {"trust_other", OPT_TRUST_OTHER, '-',
  138. "Don't verify additional certificates"},
  139. {"no_intern", OPT_NO_INTERN, '-',
  140. "Don't search certificates contained in response for signer"},
  141. {"badsig", OPT_BADSIG, '-',
  142. "Corrupt last byte of loaded OSCP response signature (for test)"},
  143. {"text", OPT_TEXT, '-', "Print text form of request and response"},
  144. {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
  145. {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
  146. {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
  147. {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
  148. {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
  149. {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
  150. {"sign_other", OPT_SIGN_OTHER, '<',
  151. "Additional certificates to include in signed request"},
  152. {"verify_other", OPT_VERIFY_OTHER, '<',
  153. "Additional certificates to search for signer"},
  154. {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
  155. {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
  156. {"no-CAfile", OPT_NOCAFILE, '-',
  157. "Do not load the default certificates file"},
  158. {"no-CApath", OPT_NOCAPATH, '-',
  159. "Do not load certificates from the default certificates directory"},
  160. {"validity_period", OPT_VALIDITY_PERIOD, 'u',
  161. "Maximum validity discrepancy in seconds"},
  162. {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
  163. {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
  164. {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
  165. {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
  166. {"path", OPT_PATH, 's', "Path to use in OCSP request"},
  167. {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
  168. {"cert", OPT_CERT, '<', "Certificate to check"},
  169. {"serial", OPT_SERIAL, 's', "Serial number to check"},
  170. {"index", OPT_INDEX, '<', "Certificate status index file"},
  171. {"CA", OPT_CA, '<', "CA certificate"},
  172. {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
  173. {"nrequest", OPT_REQUEST, 'p',
  174. "Number of requests to accept (default unlimited)"},
  175. {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
  176. {"rsigner", OPT_RSIGNER, '<',
  177. "Responder certificate to sign responses with"},
  178. {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
  179. {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
  180. {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
  181. {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
  182. {"header", OPT_HEADER, 's', "key=value header to add"},
  183. {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
  184. OPT_V_OPTIONS,
  185. {NULL}
  186. };
  187. int ocsp_main(int argc, char **argv)
  188. {
  189. BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
  190. const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
  191. STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
  192. int trailing_md = 0;
  193. CA_DB *rdb = NULL;
  194. EVP_PKEY *key = NULL, *rkey = NULL;
  195. OCSP_BASICRESP *bs = NULL;
  196. OCSP_REQUEST *req = NULL;
  197. OCSP_RESPONSE *resp = NULL;
  198. STACK_OF(CONF_VALUE) *headers = NULL;
  199. STACK_OF(OCSP_CERTID) *ids = NULL;
  200. STACK_OF(OPENSSL_STRING) *reqnames = NULL;
  201. STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
  202. STACK_OF(X509) *issuers = NULL;
  203. X509 *issuer = NULL, *cert = NULL;
  204. STACK_OF(X509) *rca_cert = NULL;
  205. X509 *signer = NULL, *rsigner = NULL;
  206. X509_STORE *store = NULL;
  207. X509_VERIFY_PARAM *vpm = NULL;
  208. const char *CAfile = NULL, *CApath = NULL;
  209. char *header, *value;
  210. char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
  211. char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
  212. char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
  213. char *rsignfile = NULL, *rkeyfile = NULL;
  214. char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
  215. char *signfile = NULL, *keyfile = NULL;
  216. char *thost = NULL, *tport = NULL, *tpath = NULL;
  217. int noCAfile = 0, noCApath = 0;
  218. int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
  219. int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
  220. int req_text = 0, resp_text = 0, ret = 1;
  221. int req_timeout = -1;
  222. long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
  223. unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
  224. OPTION_CHOICE o;
  225. reqnames = sk_OPENSSL_STRING_new_null();
  226. if (reqnames == NULL)
  227. goto end;
  228. ids = sk_OCSP_CERTID_new_null();
  229. if (ids == NULL)
  230. goto end;
  231. if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
  232. return 1;
  233. prog = opt_init(argc, argv, ocsp_options);
  234. while ((o = opt_next()) != OPT_EOF) {
  235. switch (o) {
  236. case OPT_EOF:
  237. case OPT_ERR:
  238. opthelp:
  239. BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
  240. goto end;
  241. case OPT_HELP:
  242. ret = 0;
  243. opt_help(ocsp_options);
  244. goto end;
  245. case OPT_OUTFILE:
  246. outfile = opt_arg();
  247. break;
  248. case OPT_TIMEOUT:
  249. #ifndef OPENSSL_NO_SOCK
  250. req_timeout = atoi(opt_arg());
  251. #endif
  252. break;
  253. case OPT_URL:
  254. OPENSSL_free(thost);
  255. OPENSSL_free(tport);
  256. OPENSSL_free(tpath);
  257. thost = tport = tpath = NULL;
  258. if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
  259. BIO_printf(bio_err, "%s Error parsing URL\n", prog);
  260. goto end;
  261. }
  262. thost = host;
  263. tport = port;
  264. tpath = path;
  265. break;
  266. case OPT_HOST:
  267. host = opt_arg();
  268. break;
  269. case OPT_PORT:
  270. port = opt_arg();
  271. break;
  272. case OPT_IGNORE_ERR:
  273. ignore_err = 1;
  274. break;
  275. case OPT_NOVERIFY:
  276. noverify = 1;
  277. break;
  278. case OPT_NONCE:
  279. add_nonce = 2;
  280. break;
  281. case OPT_NO_NONCE:
  282. add_nonce = 0;
  283. break;
  284. case OPT_RESP_NO_CERTS:
  285. rflags |= OCSP_NOCERTS;
  286. break;
  287. case OPT_RESP_KEY_ID:
  288. rflags |= OCSP_RESPID_KEY;
  289. break;
  290. case OPT_NO_CERTS:
  291. sign_flags |= OCSP_NOCERTS;
  292. break;
  293. case OPT_NO_SIGNATURE_VERIFY:
  294. verify_flags |= OCSP_NOSIGS;
  295. break;
  296. case OPT_NO_CERT_VERIFY:
  297. verify_flags |= OCSP_NOVERIFY;
  298. break;
  299. case OPT_NO_CHAIN:
  300. verify_flags |= OCSP_NOCHAIN;
  301. break;
  302. case OPT_NO_CERT_CHECKS:
  303. verify_flags |= OCSP_NOCHECKS;
  304. break;
  305. case OPT_NO_EXPLICIT:
  306. verify_flags |= OCSP_NOEXPLICIT;
  307. break;
  308. case OPT_TRUST_OTHER:
  309. verify_flags |= OCSP_TRUSTOTHER;
  310. break;
  311. case OPT_NO_INTERN:
  312. verify_flags |= OCSP_NOINTERN;
  313. break;
  314. case OPT_BADSIG:
  315. badsig = 1;
  316. break;
  317. case OPT_TEXT:
  318. req_text = resp_text = 1;
  319. break;
  320. case OPT_REQ_TEXT:
  321. req_text = 1;
  322. break;
  323. case OPT_RESP_TEXT:
  324. resp_text = 1;
  325. break;
  326. case OPT_REQIN:
  327. reqin = opt_arg();
  328. break;
  329. case OPT_RESPIN:
  330. respin = opt_arg();
  331. break;
  332. case OPT_SIGNER:
  333. signfile = opt_arg();
  334. break;
  335. case OPT_VAFILE:
  336. verify_certfile = opt_arg();
  337. verify_flags |= OCSP_TRUSTOTHER;
  338. break;
  339. case OPT_SIGN_OTHER:
  340. sign_certfile = opt_arg();
  341. break;
  342. case OPT_VERIFY_OTHER:
  343. verify_certfile = opt_arg();
  344. break;
  345. case OPT_CAFILE:
  346. CAfile = opt_arg();
  347. break;
  348. case OPT_CAPATH:
  349. CApath = opt_arg();
  350. break;
  351. case OPT_NOCAFILE:
  352. noCAfile = 1;
  353. break;
  354. case OPT_NOCAPATH:
  355. noCApath = 1;
  356. break;
  357. case OPT_V_CASES:
  358. if (!opt_verify(o, vpm))
  359. goto end;
  360. vpmtouched++;
  361. break;
  362. case OPT_VALIDITY_PERIOD:
  363. opt_long(opt_arg(), &nsec);
  364. break;
  365. case OPT_STATUS_AGE:
  366. opt_long(opt_arg(), &maxage);
  367. break;
  368. case OPT_SIGNKEY:
  369. keyfile = opt_arg();
  370. break;
  371. case OPT_REQOUT:
  372. reqout = opt_arg();
  373. break;
  374. case OPT_RESPOUT:
  375. respout = opt_arg();
  376. break;
  377. case OPT_PATH:
  378. path = opt_arg();
  379. break;
  380. case OPT_ISSUER:
  381. issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
  382. if (issuer == NULL)
  383. goto end;
  384. if (issuers == NULL) {
  385. if ((issuers = sk_X509_new_null()) == NULL)
  386. goto end;
  387. }
  388. sk_X509_push(issuers, issuer);
  389. break;
  390. case OPT_CERT:
  391. X509_free(cert);
  392. cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
  393. if (cert == NULL)
  394. goto end;
  395. if (cert_id_md == NULL)
  396. cert_id_md = EVP_sha1();
  397. if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
  398. goto end;
  399. if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
  400. goto end;
  401. trailing_md = 0;
  402. break;
  403. case OPT_SERIAL:
  404. if (cert_id_md == NULL)
  405. cert_id_md = EVP_sha1();
  406. if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
  407. goto end;
  408. if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
  409. goto end;
  410. trailing_md = 0;
  411. break;
  412. case OPT_INDEX:
  413. ridx_filename = opt_arg();
  414. break;
  415. case OPT_CA:
  416. rca_filename = opt_arg();
  417. break;
  418. case OPT_NMIN:
  419. opt_int(opt_arg(), &nmin);
  420. if (ndays == -1)
  421. ndays = 0;
  422. break;
  423. case OPT_REQUEST:
  424. opt_int(opt_arg(), &accept_count);
  425. break;
  426. case OPT_NDAYS:
  427. ndays = atoi(opt_arg());
  428. break;
  429. case OPT_RSIGNER:
  430. rsignfile = opt_arg();
  431. break;
  432. case OPT_RKEY:
  433. rkeyfile = opt_arg();
  434. break;
  435. case OPT_ROTHER:
  436. rcertfile = opt_arg();
  437. break;
  438. case OPT_RMD: /* Response MessageDigest */
  439. if (!opt_md(opt_arg(), &rsign_md))
  440. goto end;
  441. break;
  442. case OPT_RSIGOPT:
  443. if (rsign_sigopts == NULL)
  444. rsign_sigopts = sk_OPENSSL_STRING_new_null();
  445. if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
  446. goto end;
  447. break;
  448. case OPT_HEADER:
  449. header = opt_arg();
  450. value = strchr(header, '=');
  451. if (value == NULL) {
  452. BIO_printf(bio_err, "Missing = in header key=value\n");
  453. goto opthelp;
  454. }
  455. *value++ = '\0';
  456. if (!X509V3_add_value(header, value, &headers))
  457. goto end;
  458. break;
  459. case OPT_MD:
  460. if (trailing_md) {
  461. BIO_printf(bio_err,
  462. "%s: Digest must be before -cert or -serial\n",
  463. prog);
  464. goto opthelp;
  465. }
  466. if (!opt_md(opt_unknown(), &cert_id_md))
  467. goto opthelp;
  468. trailing_md = 1;
  469. break;
  470. case OPT_MULTI:
  471. # ifdef OCSP_DAEMON
  472. multi = atoi(opt_arg());
  473. # endif
  474. break;
  475. }
  476. }
  477. if (trailing_md) {
  478. BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
  479. prog);
  480. goto opthelp;
  481. }
  482. argc = opt_num_rest();
  483. if (argc != 0)
  484. goto opthelp;
  485. /* Have we anything to do? */
  486. if (req == NULL && reqin == NULL
  487. && respin == NULL && !(port != NULL && ridx_filename != NULL))
  488. goto opthelp;
  489. out = bio_open_default(outfile, 'w', FORMAT_TEXT);
  490. if (out == NULL)
  491. goto end;
  492. if (req == NULL && (add_nonce != 2))
  493. add_nonce = 0;
  494. if (req == NULL && reqin != NULL) {
  495. derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
  496. if (derbio == NULL)
  497. goto end;
  498. req = d2i_OCSP_REQUEST_bio(derbio, NULL);
  499. BIO_free(derbio);
  500. if (req == NULL) {
  501. BIO_printf(bio_err, "Error reading OCSP request\n");
  502. goto end;
  503. }
  504. }
  505. if (req == NULL && port != NULL) {
  506. acbio = init_responder(port);
  507. if (acbio == NULL)
  508. goto end;
  509. }
  510. if (rsignfile != NULL) {
  511. if (rkeyfile == NULL)
  512. rkeyfile = rsignfile;
  513. rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
  514. if (rsigner == NULL) {
  515. BIO_printf(bio_err, "Error loading responder certificate\n");
  516. goto end;
  517. }
  518. if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
  519. NULL, "CA certificate"))
  520. goto end;
  521. if (rcertfile != NULL) {
  522. if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
  523. "responder other certificates"))
  524. goto end;
  525. }
  526. rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
  527. "responder private key");
  528. if (rkey == NULL)
  529. goto end;
  530. }
  531. if (ridx_filename != NULL
  532. && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
  533. BIO_printf(bio_err,
  534. "Responder mode requires certificate, key, and CA.\n");
  535. goto end;
  536. }
  537. if (ridx_filename != NULL) {
  538. rdb = load_index(ridx_filename, NULL);
  539. if (rdb == NULL || index_index(rdb) <= 0) {
  540. ret = 1;
  541. goto end;
  542. }
  543. }
  544. # ifdef OCSP_DAEMON
  545. if (multi && acbio != NULL)
  546. spawn_loop();
  547. if (acbio != NULL && req_timeout > 0)
  548. signal(SIGALRM, sock_timeout);
  549. #endif
  550. if (acbio != NULL)
  551. log_message(LOG_INFO, "waiting for OCSP client connections...");
  552. redo_accept:
  553. if (acbio != NULL) {
  554. # ifdef OCSP_DAEMON
  555. if (index_changed(rdb)) {
  556. CA_DB *newrdb = load_index(ridx_filename, NULL);
  557. if (newrdb != NULL && index_index(newrdb) > 0) {
  558. free_index(rdb);
  559. rdb = newrdb;
  560. } else {
  561. free_index(newrdb);
  562. log_message(LOG_ERR, "error reloading updated index: %s",
  563. ridx_filename);
  564. }
  565. }
  566. # endif
  567. req = NULL;
  568. if (!do_responder(&req, &cbio, acbio, req_timeout))
  569. goto redo_accept;
  570. if (req == NULL) {
  571. resp =
  572. OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
  573. NULL);
  574. send_ocsp_response(cbio, resp);
  575. goto done_resp;
  576. }
  577. }
  578. if (req == NULL
  579. && (signfile != NULL || reqout != NULL
  580. || host != NULL || add_nonce || ridx_filename != NULL)) {
  581. BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
  582. goto end;
  583. }
  584. if (req != NULL && add_nonce)
  585. OCSP_request_add1_nonce(req, NULL, -1);
  586. if (signfile != NULL) {
  587. if (keyfile == NULL)
  588. keyfile = signfile;
  589. signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
  590. if (signer == NULL) {
  591. BIO_printf(bio_err, "Error loading signer certificate\n");
  592. goto end;
  593. }
  594. if (sign_certfile != NULL) {
  595. if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
  596. "signer certificates"))
  597. goto end;
  598. }
  599. key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
  600. "signer private key");
  601. if (key == NULL)
  602. goto end;
  603. if (!OCSP_request_sign
  604. (req, signer, key, NULL, sign_other, sign_flags)) {
  605. BIO_printf(bio_err, "Error signing OCSP request\n");
  606. goto end;
  607. }
  608. }
  609. if (req_text && req != NULL)
  610. OCSP_REQUEST_print(out, req, 0);
  611. if (reqout != NULL) {
  612. derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
  613. if (derbio == NULL)
  614. goto end;
  615. i2d_OCSP_REQUEST_bio(derbio, req);
  616. BIO_free(derbio);
  617. }
  618. if (rdb != NULL) {
  619. make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
  620. rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig);
  621. if (cbio != NULL)
  622. send_ocsp_response(cbio, resp);
  623. } else if (host != NULL) {
  624. # ifndef OPENSSL_NO_SOCK
  625. resp = process_responder(req, host, path,
  626. port, use_ssl, headers, req_timeout);
  627. if (resp == NULL)
  628. goto end;
  629. # else
  630. BIO_printf(bio_err,
  631. "Error creating connect BIO - sockets not supported.\n");
  632. goto end;
  633. # endif
  634. } else if (respin != NULL) {
  635. derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
  636. if (derbio == NULL)
  637. goto end;
  638. resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
  639. BIO_free(derbio);
  640. if (resp == NULL) {
  641. BIO_printf(bio_err, "Error reading OCSP response\n");
  642. goto end;
  643. }
  644. } else {
  645. ret = 0;
  646. goto end;
  647. }
  648. done_resp:
  649. if (respout != NULL) {
  650. derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
  651. if (derbio == NULL)
  652. goto end;
  653. i2d_OCSP_RESPONSE_bio(derbio, resp);
  654. BIO_free(derbio);
  655. }
  656. i = OCSP_response_status(resp);
  657. if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  658. BIO_printf(out, "Responder Error: %s (%d)\n",
  659. OCSP_response_status_str(i), i);
  660. if (!ignore_err)
  661. goto end;
  662. }
  663. if (resp_text)
  664. OCSP_RESPONSE_print(out, resp, 0);
  665. /* If running as responder don't verify our own response */
  666. if (cbio != NULL) {
  667. /* If not unlimited, see if we took all we should. */
  668. if (accept_count != -1 && --accept_count <= 0) {
  669. ret = 0;
  670. goto end;
  671. }
  672. BIO_free_all(cbio);
  673. cbio = NULL;
  674. OCSP_REQUEST_free(req);
  675. req = NULL;
  676. OCSP_RESPONSE_free(resp);
  677. resp = NULL;
  678. goto redo_accept;
  679. }
  680. if (ridx_filename != NULL) {
  681. ret = 0;
  682. goto end;
  683. }
  684. if (store == NULL) {
  685. store = setup_verify(CAfile, CApath, noCAfile, noCApath);
  686. if (!store)
  687. goto end;
  688. }
  689. if (vpmtouched)
  690. X509_STORE_set1_param(store, vpm);
  691. if (verify_certfile != NULL) {
  692. if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
  693. "validator certificate"))
  694. goto end;
  695. }
  696. bs = OCSP_response_get1_basic(resp);
  697. if (bs == NULL) {
  698. BIO_printf(bio_err, "Error parsing response\n");
  699. goto end;
  700. }
  701. ret = 0;
  702. if (!noverify) {
  703. if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
  704. if (i == -1)
  705. BIO_printf(bio_err, "WARNING: no nonce in response\n");
  706. else {
  707. BIO_printf(bio_err, "Nonce Verify error\n");
  708. ret = 1;
  709. goto end;
  710. }
  711. }
  712. i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
  713. if (i <= 0 && issuers) {
  714. i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
  715. if (i > 0)
  716. ERR_clear_error();
  717. }
  718. if (i <= 0) {
  719. BIO_printf(bio_err, "Response Verify Failure\n");
  720. ERR_print_errors(bio_err);
  721. ret = 1;
  722. } else {
  723. BIO_printf(bio_err, "Response verify OK\n");
  724. }
  725. }
  726. print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
  727. end:
  728. ERR_print_errors(bio_err);
  729. X509_free(signer);
  730. X509_STORE_free(store);
  731. X509_VERIFY_PARAM_free(vpm);
  732. sk_OPENSSL_STRING_free(rsign_sigopts);
  733. EVP_PKEY_free(key);
  734. EVP_PKEY_free(rkey);
  735. X509_free(cert);
  736. sk_X509_pop_free(issuers, X509_free);
  737. X509_free(rsigner);
  738. sk_X509_pop_free(rca_cert, X509_free);
  739. free_index(rdb);
  740. BIO_free_all(cbio);
  741. BIO_free_all(acbio);
  742. BIO_free_all(out);
  743. OCSP_REQUEST_free(req);
  744. OCSP_RESPONSE_free(resp);
  745. OCSP_BASICRESP_free(bs);
  746. sk_OPENSSL_STRING_free(reqnames);
  747. sk_OCSP_CERTID_free(ids);
  748. sk_X509_pop_free(sign_other, X509_free);
  749. sk_X509_pop_free(verify_other, X509_free);
  750. sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
  751. OPENSSL_free(thost);
  752. OPENSSL_free(tport);
  753. OPENSSL_free(tpath);
  754. return ret;
  755. }
  756. static void
  757. log_message(int level, const char *fmt, ...)
  758. {
  759. va_list ap;
  760. va_start(ap, fmt);
  761. # ifdef OCSP_DAEMON
  762. if (multi) {
  763. char buf[1024];
  764. if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
  765. syslog(level, "%s", buf);
  766. }
  767. if (level >= LOG_ERR)
  768. ERR_print_errors_cb(print_syslog, &level);
  769. }
  770. # endif
  771. if (!multi) {
  772. BIO_printf(bio_err, "%s: ", prog);
  773. BIO_vprintf(bio_err, fmt, ap);
  774. BIO_printf(bio_err, "\n");
  775. }
  776. va_end(ap);
  777. }
  778. # ifdef OCSP_DAEMON
  779. static int print_syslog(const char *str, size_t len, void *levPtr)
  780. {
  781. int level = *(int *)levPtr;
  782. int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
  783. syslog(level, "%.*s", ilen, str);
  784. return ilen;
  785. }
  786. static int index_changed(CA_DB *rdb)
  787. {
  788. struct stat sb;
  789. if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
  790. if (rdb->dbst.st_mtime != sb.st_mtime
  791. || rdb->dbst.st_ctime != sb.st_ctime
  792. || rdb->dbst.st_ino != sb.st_ino
  793. || rdb->dbst.st_dev != sb.st_dev) {
  794. syslog(LOG_INFO, "index file changed, reloading");
  795. return 1;
  796. }
  797. }
  798. return 0;
  799. }
  800. static void killall(int ret, pid_t *kidpids)
  801. {
  802. int i;
  803. for (i = 0; i < multi; ++i)
  804. if (kidpids[i] != 0)
  805. (void)kill(kidpids[i], SIGTERM);
  806. sleep(1);
  807. exit(ret);
  808. }
  809. static int termsig = 0;
  810. static void noteterm (int sig)
  811. {
  812. termsig = sig;
  813. }
  814. /*
  815. * Loop spawning up to `multi` child processes, only child processes return
  816. * from this function. The parent process loops until receiving a termination
  817. * signal, kills extant children and exits without returning.
  818. */
  819. static void spawn_loop(void)
  820. {
  821. pid_t *kidpids = NULL;
  822. int status;
  823. int procs = 0;
  824. int i;
  825. openlog(prog, LOG_PID, LOG_DAEMON);
  826. if (setpgid(0, 0)) {
  827. syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
  828. strerror(errno));
  829. exit(1);
  830. }
  831. kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
  832. for (i = 0; i < multi; ++i)
  833. kidpids[i] = 0;
  834. signal(SIGINT, noteterm);
  835. signal(SIGTERM, noteterm);
  836. while (termsig == 0) {
  837. pid_t fpid;
  838. /*
  839. * Wait for a child to replace when we're at the limit.
  840. * Slow down if a child exited abnormally or waitpid() < 0
  841. */
  842. while (termsig == 0 && procs >= multi) {
  843. if ((fpid = waitpid(-1, &status, 0)) > 0) {
  844. for (i = 0; i < procs; ++i) {
  845. if (kidpids[i] == fpid) {
  846. kidpids[i] = 0;
  847. --procs;
  848. break;
  849. }
  850. }
  851. if (i >= multi) {
  852. syslog(LOG_ERR, "fatal: internal error: "
  853. "no matching child slot for pid: %ld",
  854. (long) fpid);
  855. killall(1, kidpids);
  856. }
  857. if (status != 0) {
  858. if (WIFEXITED(status))
  859. syslog(LOG_WARNING, "child process: %ld, exit status: %d",
  860. (long)fpid, WEXITSTATUS(status));
  861. else if (WIFSIGNALED(status))
  862. syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
  863. (long)fpid, WTERMSIG(status),
  864. #ifdef WCOREDUMP
  865. WCOREDUMP(status) ? " (core dumped)" :
  866. #endif
  867. "");
  868. sleep(1);
  869. }
  870. break;
  871. } else if (errno != EINTR) {
  872. syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
  873. killall(1, kidpids);
  874. }
  875. }
  876. if (termsig)
  877. break;
  878. switch(fpid = fork()) {
  879. case -1: /* error */
  880. /* System critically low on memory, pause and try again later */
  881. sleep(30);
  882. break;
  883. case 0: /* child */
  884. OPENSSL_free(kidpids);
  885. signal(SIGINT, SIG_DFL);
  886. signal(SIGTERM, SIG_DFL);
  887. if (termsig)
  888. _exit(0);
  889. if (RAND_poll() <= 0) {
  890. syslog(LOG_ERR, "fatal: RAND_poll() failed");
  891. _exit(1);
  892. }
  893. return;
  894. default: /* parent */
  895. for (i = 0; i < multi; ++i) {
  896. if (kidpids[i] == 0) {
  897. kidpids[i] = fpid;
  898. procs++;
  899. break;
  900. }
  901. }
  902. if (i >= multi) {
  903. syslog(LOG_ERR, "fatal: internal error: no free child slots");
  904. killall(1, kidpids);
  905. }
  906. break;
  907. }
  908. }
  909. /* The loop above can only break on termsig */
  910. OPENSSL_free(kidpids);
  911. syslog(LOG_INFO, "terminating on signal: %d", termsig);
  912. killall(0, kidpids);
  913. }
  914. # endif
  915. static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
  916. const EVP_MD *cert_id_md, X509 *issuer,
  917. STACK_OF(OCSP_CERTID) *ids)
  918. {
  919. OCSP_CERTID *id;
  920. if (issuer == NULL) {
  921. BIO_printf(bio_err, "No issuer certificate specified\n");
  922. return 0;
  923. }
  924. if (*req == NULL)
  925. *req = OCSP_REQUEST_new();
  926. if (*req == NULL)
  927. goto err;
  928. id = OCSP_cert_to_id(cert_id_md, cert, issuer);
  929. if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
  930. goto err;
  931. if (!OCSP_request_add0_id(*req, id))
  932. goto err;
  933. return 1;
  934. err:
  935. BIO_printf(bio_err, "Error Creating OCSP request\n");
  936. return 0;
  937. }
  938. static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
  939. const EVP_MD *cert_id_md, X509 *issuer,
  940. STACK_OF(OCSP_CERTID) *ids)
  941. {
  942. OCSP_CERTID *id;
  943. X509_NAME *iname;
  944. ASN1_BIT_STRING *ikey;
  945. ASN1_INTEGER *sno;
  946. if (issuer == NULL) {
  947. BIO_printf(bio_err, "No issuer certificate specified\n");
  948. return 0;
  949. }
  950. if (*req == NULL)
  951. *req = OCSP_REQUEST_new();
  952. if (*req == NULL)
  953. goto err;
  954. iname = X509_get_subject_name(issuer);
  955. ikey = X509_get0_pubkey_bitstr(issuer);
  956. sno = s2i_ASN1_INTEGER(NULL, serial);
  957. if (sno == NULL) {
  958. BIO_printf(bio_err, "Error converting serial number %s\n", serial);
  959. return 0;
  960. }
  961. id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
  962. ASN1_INTEGER_free(sno);
  963. if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
  964. goto err;
  965. if (!OCSP_request_add0_id(*req, id))
  966. goto err;
  967. return 1;
  968. err:
  969. BIO_printf(bio_err, "Error Creating OCSP request\n");
  970. return 0;
  971. }
  972. static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
  973. STACK_OF(OPENSSL_STRING) *names,
  974. STACK_OF(OCSP_CERTID) *ids, long nsec,
  975. long maxage)
  976. {
  977. OCSP_CERTID *id;
  978. const char *name;
  979. int i, status, reason;
  980. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  981. if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
  982. || !sk_OCSP_CERTID_num(ids))
  983. return;
  984. for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
  985. id = sk_OCSP_CERTID_value(ids, i);
  986. name = sk_OPENSSL_STRING_value(names, i);
  987. BIO_printf(out, "%s: ", name);
  988. if (!OCSP_resp_find_status(bs, id, &status, &reason,
  989. &rev, &thisupd, &nextupd)) {
  990. BIO_puts(out, "ERROR: No Status found.\n");
  991. continue;
  992. }
  993. /*
  994. * Check validity: if invalid write to output BIO so we know which
  995. * response this refers to.
  996. */
  997. if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
  998. BIO_puts(out, "WARNING: Status times invalid.\n");
  999. ERR_print_errors(out);
  1000. }
  1001. BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
  1002. BIO_puts(out, "\tThis Update: ");
  1003. ASN1_GENERALIZEDTIME_print(out, thisupd);
  1004. BIO_puts(out, "\n");
  1005. if (nextupd) {
  1006. BIO_puts(out, "\tNext Update: ");
  1007. ASN1_GENERALIZEDTIME_print(out, nextupd);
  1008. BIO_puts(out, "\n");
  1009. }
  1010. if (status != V_OCSP_CERTSTATUS_REVOKED)
  1011. continue;
  1012. if (reason != -1)
  1013. BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
  1014. BIO_puts(out, "\tRevocation Time: ");
  1015. ASN1_GENERALIZEDTIME_print(out, rev);
  1016. BIO_puts(out, "\n");
  1017. }
  1018. }
  1019. static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
  1020. CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
  1021. EVP_PKEY *rkey, const EVP_MD *rmd,
  1022. STACK_OF(OPENSSL_STRING) *sigopts,
  1023. STACK_OF(X509) *rother, unsigned long flags,
  1024. int nmin, int ndays, int badsig)
  1025. {
  1026. ASN1_TIME *thisupd = NULL, *nextupd = NULL;
  1027. OCSP_CERTID *cid;
  1028. OCSP_BASICRESP *bs = NULL;
  1029. int i, id_count;
  1030. EVP_MD_CTX *mctx = NULL;
  1031. EVP_PKEY_CTX *pkctx = NULL;
  1032. id_count = OCSP_request_onereq_count(req);
  1033. if (id_count <= 0) {
  1034. *resp =
  1035. OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
  1036. goto end;
  1037. }
  1038. bs = OCSP_BASICRESP_new();
  1039. thisupd = X509_gmtime_adj(NULL, 0);
  1040. if (ndays != -1)
  1041. nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
  1042. /* Examine each certificate id in the request */
  1043. for (i = 0; i < id_count; i++) {
  1044. OCSP_ONEREQ *one;
  1045. ASN1_INTEGER *serial;
  1046. char **inf;
  1047. int jj;
  1048. int found = 0;
  1049. ASN1_OBJECT *cert_id_md_oid;
  1050. const EVP_MD *cert_id_md;
  1051. one = OCSP_request_onereq_get0(req, i);
  1052. cid = OCSP_onereq_get0_id(one);
  1053. OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
  1054. cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
  1055. if (cert_id_md == NULL) {
  1056. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
  1057. NULL);
  1058. goto end;
  1059. }
  1060. for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
  1061. X509 *ca_cert = sk_X509_value(ca, jj);
  1062. OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
  1063. if (OCSP_id_issuer_cmp(ca_id, cid) == 0)
  1064. found = 1;
  1065. OCSP_CERTID_free(ca_id);
  1066. }
  1067. if (!found) {
  1068. OCSP_basic_add1_status(bs, cid,
  1069. V_OCSP_CERTSTATUS_UNKNOWN,
  1070. 0, NULL, thisupd, nextupd);
  1071. continue;
  1072. }
  1073. OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
  1074. inf = lookup_serial(db, serial);
  1075. if (inf == NULL) {
  1076. OCSP_basic_add1_status(bs, cid,
  1077. V_OCSP_CERTSTATUS_UNKNOWN,
  1078. 0, NULL, thisupd, nextupd);
  1079. } else if (inf[DB_type][0] == DB_TYPE_VAL) {
  1080. OCSP_basic_add1_status(bs, cid,
  1081. V_OCSP_CERTSTATUS_GOOD,
  1082. 0, NULL, thisupd, nextupd);
  1083. } else if (inf[DB_type][0] == DB_TYPE_REV) {
  1084. ASN1_OBJECT *inst = NULL;
  1085. ASN1_TIME *revtm = NULL;
  1086. ASN1_GENERALIZEDTIME *invtm = NULL;
  1087. OCSP_SINGLERESP *single;
  1088. int reason = -1;
  1089. unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
  1090. single = OCSP_basic_add1_status(bs, cid,
  1091. V_OCSP_CERTSTATUS_REVOKED,
  1092. reason, revtm, thisupd, nextupd);
  1093. if (invtm != NULL)
  1094. OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
  1095. invtm, 0, 0);
  1096. else if (inst != NULL)
  1097. OCSP_SINGLERESP_add1_ext_i2d(single,
  1098. NID_hold_instruction_code, inst,
  1099. 0, 0);
  1100. ASN1_OBJECT_free(inst);
  1101. ASN1_TIME_free(revtm);
  1102. ASN1_GENERALIZEDTIME_free(invtm);
  1103. }
  1104. }
  1105. OCSP_copy_nonce(bs, req);
  1106. mctx = EVP_MD_CTX_new();
  1107. if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
  1108. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
  1109. goto end;
  1110. }
  1111. for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
  1112. char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
  1113. if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
  1114. BIO_printf(err, "parameter error \"%s\"\n", sigopt);
  1115. ERR_print_errors(bio_err);
  1116. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
  1117. NULL);
  1118. goto end;
  1119. }
  1120. }
  1121. OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags);
  1122. if (badsig) {
  1123. const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
  1124. corrupt_signature(sig);
  1125. }
  1126. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
  1127. end:
  1128. EVP_MD_CTX_free(mctx);
  1129. ASN1_TIME_free(thisupd);
  1130. ASN1_TIME_free(nextupd);
  1131. OCSP_BASICRESP_free(bs);
  1132. }
  1133. static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
  1134. {
  1135. int i;
  1136. BIGNUM *bn = NULL;
  1137. char *itmp, *row[DB_NUMBER], **rrow;
  1138. for (i = 0; i < DB_NUMBER; i++)
  1139. row[i] = NULL;
  1140. bn = ASN1_INTEGER_to_BN(ser, NULL);
  1141. OPENSSL_assert(bn); /* FIXME: should report an error at this
  1142. * point and abort */
  1143. if (BN_is_zero(bn))
  1144. itmp = OPENSSL_strdup("00");
  1145. else
  1146. itmp = BN_bn2hex(bn);
  1147. row[DB_serial] = itmp;
  1148. BN_free(bn);
  1149. rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
  1150. OPENSSL_free(itmp);
  1151. return rrow;
  1152. }
  1153. /* Quick and dirty OCSP server: read in and parse input request */
  1154. static BIO *init_responder(const char *port)
  1155. {
  1156. # ifdef OPENSSL_NO_SOCK
  1157. BIO_printf(bio_err,
  1158. "Error setting up accept BIO - sockets not supported.\n");
  1159. return NULL;
  1160. # else
  1161. BIO *acbio = NULL, *bufbio = NULL;
  1162. bufbio = BIO_new(BIO_f_buffer());
  1163. if (bufbio == NULL)
  1164. goto err;
  1165. acbio = BIO_new(BIO_s_accept());
  1166. if (acbio == NULL
  1167. || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
  1168. || BIO_set_accept_port(acbio, port) < 0) {
  1169. log_message(LOG_ERR, "Error setting up accept BIO");
  1170. goto err;
  1171. }
  1172. BIO_set_accept_bios(acbio, bufbio);
  1173. bufbio = NULL;
  1174. if (BIO_do_accept(acbio) <= 0) {
  1175. log_message(LOG_ERR, "Error starting accept");
  1176. goto err;
  1177. }
  1178. return acbio;
  1179. err:
  1180. BIO_free_all(acbio);
  1181. BIO_free(bufbio);
  1182. return NULL;
  1183. # endif
  1184. }
  1185. # ifndef OPENSSL_NO_SOCK
  1186. /*
  1187. * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
  1188. */
  1189. static int urldecode(char *p)
  1190. {
  1191. unsigned char *out = (unsigned char *)p;
  1192. unsigned char *save = out;
  1193. for (; *p; p++) {
  1194. if (*p != '%')
  1195. *out++ = *p;
  1196. else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
  1197. /* Don't check, can't fail because of ixdigit() call. */
  1198. *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
  1199. | OPENSSL_hexchar2int(p[2]);
  1200. p += 2;
  1201. }
  1202. else
  1203. return -1;
  1204. }
  1205. *out = '\0';
  1206. return (int)(out - save);
  1207. }
  1208. # endif
  1209. # ifdef OCSP_DAEMON
  1210. static void sock_timeout(int signum)
  1211. {
  1212. if (acfd != (int)INVALID_SOCKET)
  1213. (void)shutdown(acfd, SHUT_RD);
  1214. }
  1215. # endif
  1216. static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
  1217. int timeout)
  1218. {
  1219. # ifdef OPENSSL_NO_SOCK
  1220. return 0;
  1221. # else
  1222. int len;
  1223. OCSP_REQUEST *req = NULL;
  1224. char inbuf[2048], reqbuf[2048];
  1225. char *p, *q;
  1226. BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
  1227. const char *client;
  1228. *preq = NULL;
  1229. /* Connection loss before accept() is routine, ignore silently */
  1230. if (BIO_do_accept(acbio) <= 0)
  1231. return 0;
  1232. cbio = BIO_pop(acbio);
  1233. *pcbio = cbio;
  1234. client = BIO_get_peer_name(cbio);
  1235. # ifdef OCSP_DAEMON
  1236. if (timeout > 0) {
  1237. (void) BIO_get_fd(cbio, &acfd);
  1238. alarm(timeout);
  1239. }
  1240. # endif
  1241. /* Read the request line. */
  1242. len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
  1243. if (len <= 0)
  1244. goto out;
  1245. if (strncmp(reqbuf, "GET ", 4) == 0) {
  1246. /* Expecting GET {sp} /URL {sp} HTTP/1.x */
  1247. for (p = reqbuf + 4; *p == ' '; ++p)
  1248. continue;
  1249. if (*p != '/') {
  1250. log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
  1251. goto out;
  1252. }
  1253. p++;
  1254. /* Splice off the HTTP version identifier. */
  1255. for (q = p; *q; q++)
  1256. if (*q == ' ')
  1257. break;
  1258. if (strncmp(q, " HTTP/1.", 8) != 0) {
  1259. log_message(LOG_INFO,
  1260. "Invalid request -- bad HTTP version: %s", client);
  1261. goto out;
  1262. }
  1263. *q = '\0';
  1264. /*
  1265. * Skip "GET / HTTP..." requests often used by load-balancers
  1266. */
  1267. if (p[1] == '\0')
  1268. goto out;
  1269. len = urldecode(p);
  1270. if (len <= 0) {
  1271. log_message(LOG_INFO,
  1272. "Invalid request -- bad URL encoding: %s", client);
  1273. goto out;
  1274. }
  1275. if ((getbio = BIO_new_mem_buf(p, len)) == NULL
  1276. || (b64 = BIO_new(BIO_f_base64())) == NULL) {
  1277. log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
  1278. goto out;
  1279. }
  1280. BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
  1281. getbio = BIO_push(b64, getbio);
  1282. } else if (strncmp(reqbuf, "POST ", 5) != 0) {
  1283. log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
  1284. goto out;
  1285. }
  1286. /* Read and skip past the headers. */
  1287. for (;;) {
  1288. len = BIO_gets(cbio, inbuf, sizeof(inbuf));
  1289. if (len <= 0)
  1290. goto out;
  1291. if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
  1292. break;
  1293. }
  1294. # ifdef OCSP_DAEMON
  1295. /* Clear alarm before we close the client socket */
  1296. alarm(0);
  1297. timeout = 0;
  1298. # endif
  1299. /* Try to read OCSP request */
  1300. if (getbio != NULL) {
  1301. req = d2i_OCSP_REQUEST_bio(getbio, NULL);
  1302. BIO_free_all(getbio);
  1303. } else {
  1304. req = d2i_OCSP_REQUEST_bio(cbio, NULL);
  1305. }
  1306. if (req == NULL)
  1307. log_message(LOG_ERR, "Error parsing OCSP request");
  1308. *preq = req;
  1309. out:
  1310. # ifdef OCSP_DAEMON
  1311. if (timeout > 0)
  1312. alarm(0);
  1313. acfd = (int)INVALID_SOCKET;
  1314. # endif
  1315. return 1;
  1316. # endif
  1317. }
  1318. static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
  1319. {
  1320. char http_resp[] =
  1321. "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
  1322. "Content-Length: %d\r\n\r\n";
  1323. if (cbio == NULL)
  1324. return 0;
  1325. BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
  1326. i2d_OCSP_RESPONSE_bio(cbio, resp);
  1327. (void)BIO_flush(cbio);
  1328. return 1;
  1329. }
  1330. # ifndef OPENSSL_NO_SOCK
  1331. static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
  1332. const char *path,
  1333. const STACK_OF(CONF_VALUE) *headers,
  1334. OCSP_REQUEST *req, int req_timeout)
  1335. {
  1336. int fd;
  1337. int rv;
  1338. int i;
  1339. int add_host = 1;
  1340. OCSP_REQ_CTX *ctx = NULL;
  1341. OCSP_RESPONSE *rsp = NULL;
  1342. fd_set confds;
  1343. struct timeval tv;
  1344. if (req_timeout != -1)
  1345. BIO_set_nbio(cbio, 1);
  1346. rv = BIO_do_connect(cbio);
  1347. if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
  1348. BIO_puts(bio_err, "Error connecting BIO\n");
  1349. return NULL;
  1350. }
  1351. if (BIO_get_fd(cbio, &fd) < 0) {
  1352. BIO_puts(bio_err, "Can't get connection fd\n");
  1353. goto err;
  1354. }
  1355. if (req_timeout != -1 && rv <= 0) {
  1356. FD_ZERO(&confds);
  1357. openssl_fdset(fd, &confds);
  1358. tv.tv_usec = 0;
  1359. tv.tv_sec = req_timeout;
  1360. rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
  1361. if (rv == 0) {
  1362. BIO_puts(bio_err, "Timeout on connect\n");
  1363. return NULL;
  1364. }
  1365. }
  1366. ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
  1367. if (ctx == NULL)
  1368. return NULL;
  1369. for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
  1370. CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
  1371. if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
  1372. add_host = 0;
  1373. if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
  1374. goto err;
  1375. }
  1376. if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
  1377. goto err;
  1378. if (!OCSP_REQ_CTX_set1_req(ctx, req))
  1379. goto err;
  1380. for (;;) {
  1381. rv = OCSP_sendreq_nbio(&rsp, ctx);
  1382. if (rv != -1)
  1383. break;
  1384. if (req_timeout == -1)
  1385. continue;
  1386. FD_ZERO(&confds);
  1387. openssl_fdset(fd, &confds);
  1388. tv.tv_usec = 0;
  1389. tv.tv_sec = req_timeout;
  1390. if (BIO_should_read(cbio)) {
  1391. rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
  1392. } else if (BIO_should_write(cbio)) {
  1393. rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
  1394. } else {
  1395. BIO_puts(bio_err, "Unexpected retry condition\n");
  1396. goto err;
  1397. }
  1398. if (rv == 0) {
  1399. BIO_puts(bio_err, "Timeout on request\n");
  1400. break;
  1401. }
  1402. if (rv == -1) {
  1403. BIO_puts(bio_err, "Select error\n");
  1404. break;
  1405. }
  1406. }
  1407. err:
  1408. OCSP_REQ_CTX_free(ctx);
  1409. return rsp;
  1410. }
  1411. OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
  1412. const char *host, const char *path,
  1413. const char *port, int use_ssl,
  1414. STACK_OF(CONF_VALUE) *headers,
  1415. int req_timeout)
  1416. {
  1417. BIO *cbio = NULL;
  1418. SSL_CTX *ctx = NULL;
  1419. OCSP_RESPONSE *resp = NULL;
  1420. cbio = BIO_new_connect(host);
  1421. if (cbio == NULL) {
  1422. BIO_printf(bio_err, "Error creating connect BIO\n");
  1423. goto end;
  1424. }
  1425. if (port != NULL)
  1426. BIO_set_conn_port(cbio, port);
  1427. if (use_ssl == 1) {
  1428. BIO *sbio;
  1429. ctx = SSL_CTX_new(TLS_client_method());
  1430. if (ctx == NULL) {
  1431. BIO_printf(bio_err, "Error creating SSL context.\n");
  1432. goto end;
  1433. }
  1434. SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
  1435. sbio = BIO_new_ssl(ctx, 1);
  1436. cbio = BIO_push(sbio, cbio);
  1437. }
  1438. resp = query_responder(cbio, host, path, headers, req, req_timeout);
  1439. if (resp == NULL)
  1440. BIO_printf(bio_err, "Error querying OCSP responder\n");
  1441. end:
  1442. BIO_free_all(cbio);
  1443. SSL_CTX_free(ctx);
  1444. return resp;
  1445. }
  1446. # endif
  1447. #endif