ocsp.c 48 KB

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