2
0

ocsp.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. /*
  2. * Copyright 2001-2018 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_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. signal(SIGINT, SIG_DFL);
  885. signal(SIGTERM, SIG_DFL);
  886. if (termsig)
  887. _exit(0);
  888. if (RAND_poll() <= 0) {
  889. syslog(LOG_ERR, "fatal: RAND_poll() failed");
  890. _exit(1);
  891. }
  892. return;
  893. default: /* parent */
  894. for (i = 0; i < multi; ++i) {
  895. if (kidpids[i] == 0) {
  896. kidpids[i] = fpid;
  897. procs++;
  898. break;
  899. }
  900. }
  901. if (i >= multi) {
  902. syslog(LOG_ERR, "fatal: internal error: no free child slots");
  903. killall(1, kidpids);
  904. }
  905. break;
  906. }
  907. }
  908. /* The loop above can only break on termsig */
  909. syslog(LOG_INFO, "terminating on signal: %d", termsig);
  910. killall(0, kidpids);
  911. }
  912. # endif
  913. static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
  914. const EVP_MD *cert_id_md, X509 *issuer,
  915. STACK_OF(OCSP_CERTID) *ids)
  916. {
  917. OCSP_CERTID *id;
  918. if (issuer == NULL) {
  919. BIO_printf(bio_err, "No issuer certificate specified\n");
  920. return 0;
  921. }
  922. if (*req == NULL)
  923. *req = OCSP_REQUEST_new();
  924. if (*req == NULL)
  925. goto err;
  926. id = OCSP_cert_to_id(cert_id_md, cert, issuer);
  927. if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
  928. goto err;
  929. if (!OCSP_request_add0_id(*req, id))
  930. goto err;
  931. return 1;
  932. err:
  933. BIO_printf(bio_err, "Error Creating OCSP request\n");
  934. return 0;
  935. }
  936. static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
  937. const EVP_MD *cert_id_md, X509 *issuer,
  938. STACK_OF(OCSP_CERTID) *ids)
  939. {
  940. OCSP_CERTID *id;
  941. X509_NAME *iname;
  942. ASN1_BIT_STRING *ikey;
  943. ASN1_INTEGER *sno;
  944. if (issuer == NULL) {
  945. BIO_printf(bio_err, "No issuer certificate specified\n");
  946. return 0;
  947. }
  948. if (*req == NULL)
  949. *req = OCSP_REQUEST_new();
  950. if (*req == NULL)
  951. goto err;
  952. iname = X509_get_subject_name(issuer);
  953. ikey = X509_get0_pubkey_bitstr(issuer);
  954. sno = s2i_ASN1_INTEGER(NULL, serial);
  955. if (sno == NULL) {
  956. BIO_printf(bio_err, "Error converting serial number %s\n", serial);
  957. return 0;
  958. }
  959. id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
  960. ASN1_INTEGER_free(sno);
  961. if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
  962. goto err;
  963. if (!OCSP_request_add0_id(*req, id))
  964. goto err;
  965. return 1;
  966. err:
  967. BIO_printf(bio_err, "Error Creating OCSP request\n");
  968. return 0;
  969. }
  970. static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
  971. STACK_OF(OPENSSL_STRING) *names,
  972. STACK_OF(OCSP_CERTID) *ids, long nsec,
  973. long maxage)
  974. {
  975. OCSP_CERTID *id;
  976. const char *name;
  977. int i, status, reason;
  978. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  979. if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
  980. || !sk_OCSP_CERTID_num(ids))
  981. return;
  982. for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
  983. id = sk_OCSP_CERTID_value(ids, i);
  984. name = sk_OPENSSL_STRING_value(names, i);
  985. BIO_printf(out, "%s: ", name);
  986. if (!OCSP_resp_find_status(bs, id, &status, &reason,
  987. &rev, &thisupd, &nextupd)) {
  988. BIO_puts(out, "ERROR: No Status found.\n");
  989. continue;
  990. }
  991. /*
  992. * Check validity: if invalid write to output BIO so we know which
  993. * response this refers to.
  994. */
  995. if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
  996. BIO_puts(out, "WARNING: Status times invalid.\n");
  997. ERR_print_errors(out);
  998. }
  999. BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
  1000. BIO_puts(out, "\tThis Update: ");
  1001. ASN1_GENERALIZEDTIME_print(out, thisupd);
  1002. BIO_puts(out, "\n");
  1003. if (nextupd) {
  1004. BIO_puts(out, "\tNext Update: ");
  1005. ASN1_GENERALIZEDTIME_print(out, nextupd);
  1006. BIO_puts(out, "\n");
  1007. }
  1008. if (status != V_OCSP_CERTSTATUS_REVOKED)
  1009. continue;
  1010. if (reason != -1)
  1011. BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
  1012. BIO_puts(out, "\tRevocation Time: ");
  1013. ASN1_GENERALIZEDTIME_print(out, rev);
  1014. BIO_puts(out, "\n");
  1015. }
  1016. }
  1017. static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
  1018. CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
  1019. EVP_PKEY *rkey, const EVP_MD *rmd,
  1020. STACK_OF(OPENSSL_STRING) *sigopts,
  1021. STACK_OF(X509) *rother, unsigned long flags,
  1022. int nmin, int ndays, int badsig)
  1023. {
  1024. ASN1_TIME *thisupd = NULL, *nextupd = NULL;
  1025. OCSP_CERTID *cid;
  1026. OCSP_BASICRESP *bs = NULL;
  1027. int i, id_count;
  1028. EVP_MD_CTX *mctx = NULL;
  1029. EVP_PKEY_CTX *pkctx = NULL;
  1030. id_count = OCSP_request_onereq_count(req);
  1031. if (id_count <= 0) {
  1032. *resp =
  1033. OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
  1034. goto end;
  1035. }
  1036. bs = OCSP_BASICRESP_new();
  1037. thisupd = X509_gmtime_adj(NULL, 0);
  1038. if (ndays != -1)
  1039. nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
  1040. /* Examine each certificate id in the request */
  1041. for (i = 0; i < id_count; i++) {
  1042. OCSP_ONEREQ *one;
  1043. ASN1_INTEGER *serial;
  1044. char **inf;
  1045. int jj;
  1046. int found = 0;
  1047. ASN1_OBJECT *cert_id_md_oid;
  1048. const EVP_MD *cert_id_md;
  1049. one = OCSP_request_onereq_get0(req, i);
  1050. cid = OCSP_onereq_get0_id(one);
  1051. OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
  1052. cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
  1053. if (cert_id_md == NULL) {
  1054. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
  1055. NULL);
  1056. goto end;
  1057. }
  1058. for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
  1059. X509 *ca_cert = sk_X509_value(ca, jj);
  1060. OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
  1061. if (OCSP_id_issuer_cmp(ca_id, cid) == 0)
  1062. found = 1;
  1063. OCSP_CERTID_free(ca_id);
  1064. }
  1065. if (!found) {
  1066. OCSP_basic_add1_status(bs, cid,
  1067. V_OCSP_CERTSTATUS_UNKNOWN,
  1068. 0, NULL, thisupd, nextupd);
  1069. continue;
  1070. }
  1071. OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
  1072. inf = lookup_serial(db, serial);
  1073. if (inf == NULL) {
  1074. OCSP_basic_add1_status(bs, cid,
  1075. V_OCSP_CERTSTATUS_UNKNOWN,
  1076. 0, NULL, thisupd, nextupd);
  1077. } else if (inf[DB_type][0] == DB_TYPE_VAL) {
  1078. OCSP_basic_add1_status(bs, cid,
  1079. V_OCSP_CERTSTATUS_GOOD,
  1080. 0, NULL, thisupd, nextupd);
  1081. } else if (inf[DB_type][0] == DB_TYPE_REV) {
  1082. ASN1_OBJECT *inst = NULL;
  1083. ASN1_TIME *revtm = NULL;
  1084. ASN1_GENERALIZEDTIME *invtm = NULL;
  1085. OCSP_SINGLERESP *single;
  1086. int reason = -1;
  1087. unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
  1088. single = OCSP_basic_add1_status(bs, cid,
  1089. V_OCSP_CERTSTATUS_REVOKED,
  1090. reason, revtm, thisupd, nextupd);
  1091. if (invtm != NULL)
  1092. OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
  1093. invtm, 0, 0);
  1094. else if (inst != NULL)
  1095. OCSP_SINGLERESP_add1_ext_i2d(single,
  1096. NID_hold_instruction_code, inst,
  1097. 0, 0);
  1098. ASN1_OBJECT_free(inst);
  1099. ASN1_TIME_free(revtm);
  1100. ASN1_GENERALIZEDTIME_free(invtm);
  1101. }
  1102. }
  1103. OCSP_copy_nonce(bs, req);
  1104. mctx = EVP_MD_CTX_new();
  1105. if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
  1106. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
  1107. goto end;
  1108. }
  1109. for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
  1110. char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
  1111. if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
  1112. BIO_printf(err, "parameter error \"%s\"\n", sigopt);
  1113. ERR_print_errors(bio_err);
  1114. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
  1115. NULL);
  1116. goto end;
  1117. }
  1118. }
  1119. OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags);
  1120. if (badsig) {
  1121. const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
  1122. corrupt_signature(sig);
  1123. }
  1124. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
  1125. end:
  1126. EVP_MD_CTX_free(mctx);
  1127. ASN1_TIME_free(thisupd);
  1128. ASN1_TIME_free(nextupd);
  1129. OCSP_BASICRESP_free(bs);
  1130. }
  1131. static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
  1132. {
  1133. int i;
  1134. BIGNUM *bn = NULL;
  1135. char *itmp, *row[DB_NUMBER], **rrow;
  1136. for (i = 0; i < DB_NUMBER; i++)
  1137. row[i] = NULL;
  1138. bn = ASN1_INTEGER_to_BN(ser, NULL);
  1139. OPENSSL_assert(bn); /* FIXME: should report an error at this
  1140. * point and abort */
  1141. if (BN_is_zero(bn))
  1142. itmp = OPENSSL_strdup("00");
  1143. else
  1144. itmp = BN_bn2hex(bn);
  1145. row[DB_serial] = itmp;
  1146. BN_free(bn);
  1147. rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
  1148. OPENSSL_free(itmp);
  1149. return rrow;
  1150. }
  1151. /* Quick and dirty OCSP server: read in and parse input request */
  1152. static BIO *init_responder(const char *port)
  1153. {
  1154. # ifdef OPENSSL_NO_SOCK
  1155. BIO_printf(bio_err,
  1156. "Error setting up accept BIO - sockets not supported.\n");
  1157. return NULL;
  1158. # else
  1159. BIO *acbio = NULL, *bufbio = NULL;
  1160. bufbio = BIO_new(BIO_f_buffer());
  1161. if (bufbio == NULL)
  1162. goto err;
  1163. acbio = BIO_new(BIO_s_accept());
  1164. if (acbio == NULL
  1165. || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
  1166. || BIO_set_accept_port(acbio, port) < 0) {
  1167. log_message(LOG_ERR, "Error setting up accept BIO");
  1168. goto err;
  1169. }
  1170. BIO_set_accept_bios(acbio, bufbio);
  1171. bufbio = NULL;
  1172. if (BIO_do_accept(acbio) <= 0) {
  1173. log_message(LOG_ERR, "Error starting accept");
  1174. goto err;
  1175. }
  1176. return acbio;
  1177. err:
  1178. BIO_free_all(acbio);
  1179. BIO_free(bufbio);
  1180. return NULL;
  1181. # endif
  1182. }
  1183. # ifndef OPENSSL_NO_SOCK
  1184. /*
  1185. * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
  1186. */
  1187. static int urldecode(char *p)
  1188. {
  1189. unsigned char *out = (unsigned char *)p;
  1190. unsigned char *save = out;
  1191. for (; *p; p++) {
  1192. if (*p != '%')
  1193. *out++ = *p;
  1194. else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
  1195. /* Don't check, can't fail because of ixdigit() call. */
  1196. *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
  1197. | OPENSSL_hexchar2int(p[2]);
  1198. p += 2;
  1199. }
  1200. else
  1201. return -1;
  1202. }
  1203. *out = '\0';
  1204. return (int)(out - save);
  1205. }
  1206. # endif
  1207. # ifdef OCSP_DAEMON
  1208. static void sock_timeout(int signum)
  1209. {
  1210. if (acfd != (int)INVALID_SOCKET)
  1211. (void)shutdown(acfd, SHUT_RD);
  1212. }
  1213. # endif
  1214. static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
  1215. int timeout)
  1216. {
  1217. # ifdef OPENSSL_NO_SOCK
  1218. return 0;
  1219. # else
  1220. int len;
  1221. OCSP_REQUEST *req = NULL;
  1222. char inbuf[2048], reqbuf[2048];
  1223. char *p, *q;
  1224. BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
  1225. const char *client;
  1226. *preq = NULL;
  1227. /* Connection loss before accept() is routine, ignore silently */
  1228. if (BIO_do_accept(acbio) <= 0)
  1229. return 0;
  1230. cbio = BIO_pop(acbio);
  1231. *pcbio = cbio;
  1232. client = BIO_get_peer_name(cbio);
  1233. # ifdef OCSP_DAEMON
  1234. if (timeout > 0) {
  1235. (void) BIO_get_fd(cbio, &acfd);
  1236. alarm(timeout);
  1237. }
  1238. # endif
  1239. /* Read the request line. */
  1240. len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
  1241. if (len <= 0)
  1242. goto out;
  1243. if (strncmp(reqbuf, "GET ", 4) == 0) {
  1244. /* Expecting GET {sp} /URL {sp} HTTP/1.x */
  1245. for (p = reqbuf + 4; *p == ' '; ++p)
  1246. continue;
  1247. if (*p != '/') {
  1248. log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
  1249. goto out;
  1250. }
  1251. p++;
  1252. /* Splice off the HTTP version identifier. */
  1253. for (q = p; *q; q++)
  1254. if (*q == ' ')
  1255. break;
  1256. if (strncmp(q, " HTTP/1.", 8) != 0) {
  1257. log_message(LOG_INFO,
  1258. "Invalid request -- bad HTTP version: %s", client);
  1259. goto out;
  1260. }
  1261. *q = '\0';
  1262. /*
  1263. * Skip "GET / HTTP..." requests often used by load-balancers
  1264. */
  1265. if (p[1] == '\0')
  1266. goto out;
  1267. len = urldecode(p);
  1268. if (len <= 0) {
  1269. log_message(LOG_INFO,
  1270. "Invalid request -- bad URL encoding: %s", client);
  1271. goto out;
  1272. }
  1273. if ((getbio = BIO_new_mem_buf(p, len)) == NULL
  1274. || (b64 = BIO_new(BIO_f_base64())) == NULL) {
  1275. log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
  1276. goto out;
  1277. }
  1278. BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
  1279. getbio = BIO_push(b64, getbio);
  1280. } else if (strncmp(reqbuf, "POST ", 5) != 0) {
  1281. log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
  1282. goto out;
  1283. }
  1284. /* Read and skip past the headers. */
  1285. for (;;) {
  1286. len = BIO_gets(cbio, inbuf, sizeof(inbuf));
  1287. if (len <= 0)
  1288. goto out;
  1289. if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
  1290. break;
  1291. }
  1292. # ifdef OCSP_DAEMON
  1293. /* Clear alarm before we close the client socket */
  1294. alarm(0);
  1295. timeout = 0;
  1296. # endif
  1297. /* Try to read OCSP request */
  1298. if (getbio != NULL) {
  1299. req = d2i_OCSP_REQUEST_bio(getbio, NULL);
  1300. BIO_free_all(getbio);
  1301. } else {
  1302. req = d2i_OCSP_REQUEST_bio(cbio, NULL);
  1303. }
  1304. if (req == NULL)
  1305. log_message(LOG_ERR, "Error parsing OCSP request");
  1306. *preq = req;
  1307. out:
  1308. # ifdef OCSP_DAEMON
  1309. if (timeout > 0)
  1310. alarm(0);
  1311. acfd = (int)INVALID_SOCKET;
  1312. # endif
  1313. return 1;
  1314. # endif
  1315. }
  1316. static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
  1317. {
  1318. char http_resp[] =
  1319. "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
  1320. "Content-Length: %d\r\n\r\n";
  1321. if (cbio == NULL)
  1322. return 0;
  1323. BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
  1324. i2d_OCSP_RESPONSE_bio(cbio, resp);
  1325. (void)BIO_flush(cbio);
  1326. return 1;
  1327. }
  1328. # ifndef OPENSSL_NO_SOCK
  1329. static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
  1330. const char *path,
  1331. const STACK_OF(CONF_VALUE) *headers,
  1332. OCSP_REQUEST *req, int req_timeout)
  1333. {
  1334. int fd;
  1335. int rv;
  1336. int i;
  1337. int add_host = 1;
  1338. OCSP_REQ_CTX *ctx = NULL;
  1339. OCSP_RESPONSE *rsp = NULL;
  1340. fd_set confds;
  1341. struct timeval tv;
  1342. if (req_timeout != -1)
  1343. BIO_set_nbio(cbio, 1);
  1344. rv = BIO_do_connect(cbio);
  1345. if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
  1346. BIO_puts(bio_err, "Error connecting BIO\n");
  1347. return NULL;
  1348. }
  1349. if (BIO_get_fd(cbio, &fd) < 0) {
  1350. BIO_puts(bio_err, "Can't get connection fd\n");
  1351. goto err;
  1352. }
  1353. if (req_timeout != -1 && rv <= 0) {
  1354. FD_ZERO(&confds);
  1355. openssl_fdset(fd, &confds);
  1356. tv.tv_usec = 0;
  1357. tv.tv_sec = req_timeout;
  1358. rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
  1359. if (rv == 0) {
  1360. BIO_puts(bio_err, "Timeout on connect\n");
  1361. return NULL;
  1362. }
  1363. }
  1364. ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
  1365. if (ctx == NULL)
  1366. return NULL;
  1367. for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
  1368. CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
  1369. if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
  1370. add_host = 0;
  1371. if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
  1372. goto err;
  1373. }
  1374. if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
  1375. goto err;
  1376. if (!OCSP_REQ_CTX_set1_req(ctx, req))
  1377. goto err;
  1378. for (;;) {
  1379. rv = OCSP_sendreq_nbio(&rsp, ctx);
  1380. if (rv != -1)
  1381. break;
  1382. if (req_timeout == -1)
  1383. continue;
  1384. FD_ZERO(&confds);
  1385. openssl_fdset(fd, &confds);
  1386. tv.tv_usec = 0;
  1387. tv.tv_sec = req_timeout;
  1388. if (BIO_should_read(cbio)) {
  1389. rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
  1390. } else if (BIO_should_write(cbio)) {
  1391. rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
  1392. } else {
  1393. BIO_puts(bio_err, "Unexpected retry condition\n");
  1394. goto err;
  1395. }
  1396. if (rv == 0) {
  1397. BIO_puts(bio_err, "Timeout on request\n");
  1398. break;
  1399. }
  1400. if (rv == -1) {
  1401. BIO_puts(bio_err, "Select error\n");
  1402. break;
  1403. }
  1404. }
  1405. err:
  1406. OCSP_REQ_CTX_free(ctx);
  1407. return rsp;
  1408. }
  1409. OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
  1410. const char *host, const char *path,
  1411. const char *port, int use_ssl,
  1412. STACK_OF(CONF_VALUE) *headers,
  1413. int req_timeout)
  1414. {
  1415. BIO *cbio = NULL;
  1416. SSL_CTX *ctx = NULL;
  1417. OCSP_RESPONSE *resp = NULL;
  1418. cbio = BIO_new_connect(host);
  1419. if (cbio == NULL) {
  1420. BIO_printf(bio_err, "Error creating connect BIO\n");
  1421. goto end;
  1422. }
  1423. if (port != NULL)
  1424. BIO_set_conn_port(cbio, port);
  1425. if (use_ssl == 1) {
  1426. BIO *sbio;
  1427. ctx = SSL_CTX_new(TLS_client_method());
  1428. if (ctx == NULL) {
  1429. BIO_printf(bio_err, "Error creating SSL context.\n");
  1430. goto end;
  1431. }
  1432. SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
  1433. sbio = BIO_new_ssl(ctx, 1);
  1434. cbio = BIO_push(sbio, cbio);
  1435. }
  1436. resp = query_responder(cbio, host, path, headers, req, req_timeout);
  1437. if (resp == NULL)
  1438. BIO_printf(bio_err, "Error querying OCSP responder\n");
  1439. end:
  1440. BIO_free_all(cbio);
  1441. SSL_CTX_free(ctx);
  1442. return resp;
  1443. }
  1444. # endif
  1445. #endif