2
0

ocsp.c 50 KB

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