ocsp.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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)) {
  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) {
  558. free_index(rdb);
  559. rdb = newrdb;
  560. } else {
  561. log_message(LOG_ERR, "error reloading updated index: %s",
  562. ridx_filename);
  563. }
  564. }
  565. # endif
  566. req = NULL;
  567. if (!do_responder(&req, &cbio, acbio, req_timeout))
  568. goto redo_accept;
  569. if (req == NULL) {
  570. resp =
  571. OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
  572. NULL);
  573. send_ocsp_response(cbio, resp);
  574. goto done_resp;
  575. }
  576. }
  577. if (req == NULL
  578. && (signfile != NULL || reqout != NULL
  579. || host != NULL || add_nonce || ridx_filename != NULL)) {
  580. BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
  581. goto end;
  582. }
  583. if (req != NULL && add_nonce)
  584. OCSP_request_add1_nonce(req, NULL, -1);
  585. if (signfile != NULL) {
  586. if (keyfile == NULL)
  587. keyfile = signfile;
  588. signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
  589. if (signer == NULL) {
  590. BIO_printf(bio_err, "Error loading signer certificate\n");
  591. goto end;
  592. }
  593. if (sign_certfile != NULL) {
  594. if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
  595. "signer certificates"))
  596. goto end;
  597. }
  598. key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
  599. "signer private key");
  600. if (key == NULL)
  601. goto end;
  602. if (!OCSP_request_sign
  603. (req, signer, key, NULL, sign_other, sign_flags)) {
  604. BIO_printf(bio_err, "Error signing OCSP request\n");
  605. goto end;
  606. }
  607. }
  608. if (req_text && req != NULL)
  609. OCSP_REQUEST_print(out, req, 0);
  610. if (reqout != NULL) {
  611. derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
  612. if (derbio == NULL)
  613. goto end;
  614. i2d_OCSP_REQUEST_bio(derbio, req);
  615. BIO_free(derbio);
  616. }
  617. if (rdb != NULL) {
  618. make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
  619. rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig);
  620. if (cbio != NULL)
  621. send_ocsp_response(cbio, resp);
  622. } else if (host != NULL) {
  623. # ifndef OPENSSL_NO_SOCK
  624. resp = process_responder(req, host, path,
  625. port, use_ssl, headers, req_timeout);
  626. if (resp == NULL)
  627. goto end;
  628. # else
  629. BIO_printf(bio_err,
  630. "Error creating connect BIO - sockets not supported.\n");
  631. goto end;
  632. # endif
  633. } else if (respin != NULL) {
  634. derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
  635. if (derbio == NULL)
  636. goto end;
  637. resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
  638. BIO_free(derbio);
  639. if (resp == NULL) {
  640. BIO_printf(bio_err, "Error reading OCSP response\n");
  641. goto end;
  642. }
  643. } else {
  644. ret = 0;
  645. goto end;
  646. }
  647. done_resp:
  648. if (respout != NULL) {
  649. derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
  650. if (derbio == NULL)
  651. goto end;
  652. i2d_OCSP_RESPONSE_bio(derbio, resp);
  653. BIO_free(derbio);
  654. }
  655. i = OCSP_response_status(resp);
  656. if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  657. BIO_printf(out, "Responder Error: %s (%d)\n",
  658. OCSP_response_status_str(i), i);
  659. if (!ignore_err) {
  660. ret = 0;
  661. goto end;
  662. }
  663. }
  664. if (resp_text)
  665. OCSP_RESPONSE_print(out, resp, 0);
  666. /* If running as responder don't verify our own response */
  667. if (cbio != NULL) {
  668. /* If not unlimited, see if we took all we should. */
  669. if (accept_count != -1 && --accept_count <= 0) {
  670. ret = 0;
  671. goto end;
  672. }
  673. BIO_free_all(cbio);
  674. cbio = NULL;
  675. OCSP_REQUEST_free(req);
  676. req = NULL;
  677. OCSP_RESPONSE_free(resp);
  678. resp = NULL;
  679. goto redo_accept;
  680. }
  681. if (ridx_filename != NULL) {
  682. ret = 0;
  683. goto end;
  684. }
  685. if (store == NULL) {
  686. store = setup_verify(CAfile, CApath, noCAfile, noCApath);
  687. if (!store)
  688. goto end;
  689. }
  690. if (vpmtouched)
  691. X509_STORE_set1_param(store, vpm);
  692. if (verify_certfile != NULL) {
  693. if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
  694. "validator certificate"))
  695. goto end;
  696. }
  697. bs = OCSP_response_get1_basic(resp);
  698. if (bs == NULL) {
  699. BIO_printf(bio_err, "Error parsing response\n");
  700. goto end;
  701. }
  702. ret = 0;
  703. if (!noverify) {
  704. if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
  705. if (i == -1)
  706. BIO_printf(bio_err, "WARNING: no nonce in response\n");
  707. else {
  708. BIO_printf(bio_err, "Nonce Verify error\n");
  709. ret = 1;
  710. goto end;
  711. }
  712. }
  713. i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
  714. if (i <= 0 && issuers) {
  715. i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
  716. if (i > 0)
  717. ERR_clear_error();
  718. }
  719. if (i <= 0) {
  720. BIO_printf(bio_err, "Response Verify Failure\n");
  721. ERR_print_errors(bio_err);
  722. ret = 1;
  723. } else {
  724. BIO_printf(bio_err, "Response verify OK\n");
  725. }
  726. }
  727. print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
  728. end:
  729. ERR_print_errors(bio_err);
  730. X509_free(signer);
  731. X509_STORE_free(store);
  732. X509_VERIFY_PARAM_free(vpm);
  733. sk_OPENSSL_STRING_free(rsign_sigopts);
  734. EVP_PKEY_free(key);
  735. EVP_PKEY_free(rkey);
  736. X509_free(cert);
  737. sk_X509_pop_free(issuers, X509_free);
  738. X509_free(rsigner);
  739. sk_X509_pop_free(rca_cert, X509_free);
  740. free_index(rdb);
  741. BIO_free_all(cbio);
  742. BIO_free_all(acbio);
  743. BIO_free_all(out);
  744. OCSP_REQUEST_free(req);
  745. OCSP_RESPONSE_free(resp);
  746. OCSP_BASICRESP_free(bs);
  747. sk_OPENSSL_STRING_free(reqnames);
  748. sk_OCSP_CERTID_free(ids);
  749. sk_X509_pop_free(sign_other, X509_free);
  750. sk_X509_pop_free(verify_other, X509_free);
  751. sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
  752. OPENSSL_free(thost);
  753. OPENSSL_free(tport);
  754. OPENSSL_free(tpath);
  755. return ret;
  756. }
  757. static void
  758. log_message(int level, const char *fmt, ...)
  759. {
  760. va_list ap;
  761. va_start(ap, fmt);
  762. # ifdef OCSP_DAEMON
  763. if (multi) {
  764. char buf[1024];
  765. if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
  766. syslog(level, "%s", buf);
  767. }
  768. if (level >= LOG_ERR)
  769. ERR_print_errors_cb(print_syslog, &level);
  770. }
  771. # endif
  772. if (!multi) {
  773. BIO_printf(bio_err, "%s: ", prog);
  774. BIO_vprintf(bio_err, fmt, ap);
  775. BIO_printf(bio_err, "\n");
  776. }
  777. va_end(ap);
  778. }
  779. # ifdef OCSP_DAEMON
  780. static int print_syslog(const char *str, size_t len, void *levPtr)
  781. {
  782. int level = *(int *)levPtr;
  783. int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
  784. syslog(level, "%.*s", ilen, str);
  785. return ilen;
  786. }
  787. static int index_changed(CA_DB *rdb)
  788. {
  789. struct stat sb;
  790. if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
  791. if (rdb->dbst.st_mtime != sb.st_mtime
  792. || rdb->dbst.st_ctime != sb.st_ctime
  793. || rdb->dbst.st_ino != sb.st_ino
  794. || rdb->dbst.st_dev != sb.st_dev) {
  795. syslog(LOG_INFO, "index file changed, reloading");
  796. return 1;
  797. }
  798. }
  799. return 0;
  800. }
  801. static void killall(int ret, pid_t *kidpids)
  802. {
  803. int i;
  804. for (i = 0; i < multi; ++i)
  805. if (kidpids[i] != 0)
  806. (void)kill(kidpids[i], SIGTERM);
  807. sleep(1);
  808. exit(ret);
  809. }
  810. static int termsig = 0;
  811. static void noteterm (int sig)
  812. {
  813. termsig = sig;
  814. }
  815. /*
  816. * Loop spawning up to `multi` child processes, only child processes return
  817. * from this function. The parent process loops until receiving a termination
  818. * signal, kills extant children and exits without returning.
  819. */
  820. static void spawn_loop(void)
  821. {
  822. pid_t *kidpids = NULL;
  823. int status;
  824. int procs = 0;
  825. int i;
  826. openlog(prog, LOG_PID, LOG_DAEMON);
  827. if (setpgid(0, 0)) {
  828. syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
  829. strerror(errno));
  830. exit(1);
  831. }
  832. kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
  833. for (i = 0; i < multi; ++i)
  834. kidpids[i] = 0;
  835. signal(SIGINT, noteterm);
  836. signal(SIGTERM, noteterm);
  837. while (termsig == 0) {
  838. pid_t fpid;
  839. /*
  840. * Wait for a child to replace when we're at the limit.
  841. * Slow down if a child exited abnormally or waitpid() < 0
  842. */
  843. while (termsig == 0 && procs >= multi) {
  844. if ((fpid = waitpid(-1, &status, 0)) > 0) {
  845. for (i = 0; i < procs; ++i) {
  846. if (kidpids[i] == fpid) {
  847. kidpids[i] = 0;
  848. --procs;
  849. break;
  850. }
  851. }
  852. if (i >= multi) {
  853. syslog(LOG_ERR, "fatal: internal error: "
  854. "no matching child slot for pid: %ld",
  855. (long) fpid);
  856. killall(1, kidpids);
  857. }
  858. if (status != 0) {
  859. if (WIFEXITED(status))
  860. syslog(LOG_WARNING, "child process: %ld, exit status: %d",
  861. (long)fpid, WEXITSTATUS(status));
  862. else if (WIFSIGNALED(status))
  863. syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
  864. (long)fpid, WTERMSIG(status),
  865. #ifdef WCOREDUMP
  866. WCOREDUMP(status) ? " (core dumped)" :
  867. #endif
  868. "");
  869. sleep(1);
  870. }
  871. break;
  872. } else if (errno != EINTR) {
  873. syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
  874. killall(1, kidpids);
  875. }
  876. }
  877. if (termsig)
  878. break;
  879. switch(fpid = fork()) {
  880. case -1: /* error */
  881. /* System critically low on memory, pause and try again later */
  882. sleep(30);
  883. break;
  884. case 0: /* child */
  885. signal(SIGINT, SIG_DFL);
  886. signal(SIGTERM, SIG_DFL);
  887. if (termsig)
  888. _exit(0);
  889. if (RAND_poll() <= 0) {
  890. syslog(LOG_ERR, "fatal: RAND_poll() failed");
  891. _exit(1);
  892. }
  893. return;
  894. default: /* parent */
  895. for (i = 0; i < multi; ++i) {
  896. if (kidpids[i] == 0) {
  897. kidpids[i] = fpid;
  898. procs++;
  899. break;
  900. }
  901. }
  902. if (i >= multi) {
  903. syslog(LOG_ERR, "fatal: internal error: no free child slots");
  904. killall(1, kidpids);
  905. }
  906. break;
  907. }
  908. }
  909. /* The loop above can only break on termsig */
  910. syslog(LOG_INFO, "terminating on signal: %d", termsig);
  911. killall(0, kidpids);
  912. }
  913. # endif
  914. static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
  915. const EVP_MD *cert_id_md, X509 *issuer,
  916. STACK_OF(OCSP_CERTID) *ids)
  917. {
  918. OCSP_CERTID *id;
  919. if (issuer == NULL) {
  920. BIO_printf(bio_err, "No issuer certificate specified\n");
  921. return 0;
  922. }
  923. if (*req == NULL)
  924. *req = OCSP_REQUEST_new();
  925. if (*req == NULL)
  926. goto err;
  927. id = OCSP_cert_to_id(cert_id_md, cert, issuer);
  928. if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
  929. goto err;
  930. if (!OCSP_request_add0_id(*req, id))
  931. goto err;
  932. return 1;
  933. err:
  934. BIO_printf(bio_err, "Error Creating OCSP request\n");
  935. return 0;
  936. }
  937. static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
  938. const EVP_MD *cert_id_md, X509 *issuer,
  939. STACK_OF(OCSP_CERTID) *ids)
  940. {
  941. OCSP_CERTID *id;
  942. X509_NAME *iname;
  943. ASN1_BIT_STRING *ikey;
  944. ASN1_INTEGER *sno;
  945. if (issuer == NULL) {
  946. BIO_printf(bio_err, "No issuer certificate specified\n");
  947. return 0;
  948. }
  949. if (*req == NULL)
  950. *req = OCSP_REQUEST_new();
  951. if (*req == NULL)
  952. goto err;
  953. iname = X509_get_subject_name(issuer);
  954. ikey = X509_get0_pubkey_bitstr(issuer);
  955. sno = s2i_ASN1_INTEGER(NULL, serial);
  956. if (sno == NULL) {
  957. BIO_printf(bio_err, "Error converting serial number %s\n", serial);
  958. return 0;
  959. }
  960. id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
  961. ASN1_INTEGER_free(sno);
  962. if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
  963. goto err;
  964. if (!OCSP_request_add0_id(*req, id))
  965. goto err;
  966. return 1;
  967. err:
  968. BIO_printf(bio_err, "Error Creating OCSP request\n");
  969. return 0;
  970. }
  971. static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
  972. STACK_OF(OPENSSL_STRING) *names,
  973. STACK_OF(OCSP_CERTID) *ids, long nsec,
  974. long maxage)
  975. {
  976. OCSP_CERTID *id;
  977. const char *name;
  978. int i, status, reason;
  979. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  980. if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
  981. || !sk_OCSP_CERTID_num(ids))
  982. return;
  983. for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
  984. id = sk_OCSP_CERTID_value(ids, i);
  985. name = sk_OPENSSL_STRING_value(names, i);
  986. BIO_printf(out, "%s: ", name);
  987. if (!OCSP_resp_find_status(bs, id, &status, &reason,
  988. &rev, &thisupd, &nextupd)) {
  989. BIO_puts(out, "ERROR: No Status found.\n");
  990. continue;
  991. }
  992. /*
  993. * Check validity: if invalid write to output BIO so we know which
  994. * response this refers to.
  995. */
  996. if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
  997. BIO_puts(out, "WARNING: Status times invalid.\n");
  998. ERR_print_errors(out);
  999. }
  1000. BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
  1001. BIO_puts(out, "\tThis Update: ");
  1002. ASN1_GENERALIZEDTIME_print(out, thisupd);
  1003. BIO_puts(out, "\n");
  1004. if (nextupd) {
  1005. BIO_puts(out, "\tNext Update: ");
  1006. ASN1_GENERALIZEDTIME_print(out, nextupd);
  1007. BIO_puts(out, "\n");
  1008. }
  1009. if (status != V_OCSP_CERTSTATUS_REVOKED)
  1010. continue;
  1011. if (reason != -1)
  1012. BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
  1013. BIO_puts(out, "\tRevocation Time: ");
  1014. ASN1_GENERALIZEDTIME_print(out, rev);
  1015. BIO_puts(out, "\n");
  1016. }
  1017. }
  1018. static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
  1019. CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
  1020. EVP_PKEY *rkey, const EVP_MD *rmd,
  1021. STACK_OF(OPENSSL_STRING) *sigopts,
  1022. STACK_OF(X509) *rother, unsigned long flags,
  1023. int nmin, int ndays, int badsig)
  1024. {
  1025. ASN1_TIME *thisupd = NULL, *nextupd = NULL;
  1026. OCSP_CERTID *cid;
  1027. OCSP_BASICRESP *bs = NULL;
  1028. int i, id_count;
  1029. EVP_MD_CTX *mctx = NULL;
  1030. EVP_PKEY_CTX *pkctx = NULL;
  1031. id_count = OCSP_request_onereq_count(req);
  1032. if (id_count <= 0) {
  1033. *resp =
  1034. OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
  1035. goto end;
  1036. }
  1037. bs = OCSP_BASICRESP_new();
  1038. thisupd = X509_gmtime_adj(NULL, 0);
  1039. if (ndays != -1)
  1040. nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
  1041. /* Examine each certificate id in the request */
  1042. for (i = 0; i < id_count; i++) {
  1043. OCSP_ONEREQ *one;
  1044. ASN1_INTEGER *serial;
  1045. char **inf;
  1046. int jj;
  1047. int found = 0;
  1048. ASN1_OBJECT *cert_id_md_oid;
  1049. const EVP_MD *cert_id_md;
  1050. one = OCSP_request_onereq_get0(req, i);
  1051. cid = OCSP_onereq_get0_id(one);
  1052. OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
  1053. cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
  1054. if (cert_id_md == NULL) {
  1055. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
  1056. NULL);
  1057. goto end;
  1058. }
  1059. for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
  1060. X509 *ca_cert = sk_X509_value(ca, jj);
  1061. OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
  1062. if (OCSP_id_issuer_cmp(ca_id, cid) == 0)
  1063. found = 1;
  1064. OCSP_CERTID_free(ca_id);
  1065. }
  1066. if (!found) {
  1067. OCSP_basic_add1_status(bs, cid,
  1068. V_OCSP_CERTSTATUS_UNKNOWN,
  1069. 0, NULL, thisupd, nextupd);
  1070. continue;
  1071. }
  1072. OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
  1073. inf = lookup_serial(db, serial);
  1074. if (inf == NULL) {
  1075. OCSP_basic_add1_status(bs, cid,
  1076. V_OCSP_CERTSTATUS_UNKNOWN,
  1077. 0, NULL, thisupd, nextupd);
  1078. } else if (inf[DB_type][0] == DB_TYPE_VAL) {
  1079. OCSP_basic_add1_status(bs, cid,
  1080. V_OCSP_CERTSTATUS_GOOD,
  1081. 0, NULL, thisupd, nextupd);
  1082. } else if (inf[DB_type][0] == DB_TYPE_REV) {
  1083. ASN1_OBJECT *inst = NULL;
  1084. ASN1_TIME *revtm = NULL;
  1085. ASN1_GENERALIZEDTIME *invtm = NULL;
  1086. OCSP_SINGLERESP *single;
  1087. int reason = -1;
  1088. unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
  1089. single = OCSP_basic_add1_status(bs, cid,
  1090. V_OCSP_CERTSTATUS_REVOKED,
  1091. reason, revtm, thisupd, nextupd);
  1092. if (invtm != NULL)
  1093. OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
  1094. invtm, 0, 0);
  1095. else if (inst != NULL)
  1096. OCSP_SINGLERESP_add1_ext_i2d(single,
  1097. NID_hold_instruction_code, inst,
  1098. 0, 0);
  1099. ASN1_OBJECT_free(inst);
  1100. ASN1_TIME_free(revtm);
  1101. ASN1_GENERALIZEDTIME_free(invtm);
  1102. }
  1103. }
  1104. OCSP_copy_nonce(bs, req);
  1105. mctx = EVP_MD_CTX_new();
  1106. if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
  1107. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
  1108. goto end;
  1109. }
  1110. for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
  1111. char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
  1112. if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
  1113. BIO_printf(err, "parameter error \"%s\"\n", sigopt);
  1114. ERR_print_errors(bio_err);
  1115. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
  1116. NULL);
  1117. goto end;
  1118. }
  1119. }
  1120. OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags);
  1121. if (badsig) {
  1122. const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
  1123. corrupt_signature(sig);
  1124. }
  1125. *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
  1126. end:
  1127. EVP_MD_CTX_free(mctx);
  1128. ASN1_TIME_free(thisupd);
  1129. ASN1_TIME_free(nextupd);
  1130. OCSP_BASICRESP_free(bs);
  1131. }
  1132. static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
  1133. {
  1134. int i;
  1135. BIGNUM *bn = NULL;
  1136. char *itmp, *row[DB_NUMBER], **rrow;
  1137. for (i = 0; i < DB_NUMBER; i++)
  1138. row[i] = NULL;
  1139. bn = ASN1_INTEGER_to_BN(ser, NULL);
  1140. OPENSSL_assert(bn); /* FIXME: should report an error at this
  1141. * point and abort */
  1142. if (BN_is_zero(bn))
  1143. itmp = OPENSSL_strdup("00");
  1144. else
  1145. itmp = BN_bn2hex(bn);
  1146. row[DB_serial] = itmp;
  1147. BN_free(bn);
  1148. rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
  1149. OPENSSL_free(itmp);
  1150. return rrow;
  1151. }
  1152. /* Quick and dirty OCSP server: read in and parse input request */
  1153. static BIO *init_responder(const char *port)
  1154. {
  1155. # ifdef OPENSSL_NO_SOCK
  1156. BIO_printf(bio_err,
  1157. "Error setting up accept BIO - sockets not supported.\n");
  1158. return NULL;
  1159. # else
  1160. BIO *acbio = NULL, *bufbio = NULL;
  1161. bufbio = BIO_new(BIO_f_buffer());
  1162. if (bufbio == NULL)
  1163. goto err;
  1164. acbio = BIO_new(BIO_s_accept());
  1165. if (acbio == NULL
  1166. || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
  1167. || BIO_set_accept_port(acbio, port) < 0) {
  1168. log_message(LOG_ERR, "Error setting up accept BIO");
  1169. goto err;
  1170. }
  1171. BIO_set_accept_bios(acbio, bufbio);
  1172. bufbio = NULL;
  1173. if (BIO_do_accept(acbio) <= 0) {
  1174. log_message(LOG_ERR, "Error starting accept");
  1175. goto err;
  1176. }
  1177. return acbio;
  1178. err:
  1179. BIO_free_all(acbio);
  1180. BIO_free(bufbio);
  1181. return NULL;
  1182. # endif
  1183. }
  1184. # ifndef OPENSSL_NO_SOCK
  1185. /*
  1186. * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
  1187. */
  1188. static int urldecode(char *p)
  1189. {
  1190. unsigned char *out = (unsigned char *)p;
  1191. unsigned char *save = out;
  1192. for (; *p; p++) {
  1193. if (*p != '%')
  1194. *out++ = *p;
  1195. else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
  1196. /* Don't check, can't fail because of ixdigit() call. */
  1197. *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
  1198. | OPENSSL_hexchar2int(p[2]);
  1199. p += 2;
  1200. }
  1201. else
  1202. return -1;
  1203. }
  1204. *out = '\0';
  1205. return (int)(out - save);
  1206. }
  1207. # endif
  1208. # ifdef OCSP_DAEMON
  1209. static void sock_timeout(int signum)
  1210. {
  1211. if (acfd != (int)INVALID_SOCKET)
  1212. (void)shutdown(acfd, SHUT_RD);
  1213. }
  1214. # endif
  1215. static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
  1216. int timeout)
  1217. {
  1218. # ifdef OPENSSL_NO_SOCK
  1219. return 0;
  1220. # else
  1221. int len;
  1222. OCSP_REQUEST *req = NULL;
  1223. char inbuf[2048], reqbuf[2048];
  1224. char *p, *q;
  1225. BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
  1226. const char *client;
  1227. *preq = NULL;
  1228. /* Connection loss before accept() is routine, ignore silently */
  1229. if (BIO_do_accept(acbio) <= 0)
  1230. return 0;
  1231. cbio = BIO_pop(acbio);
  1232. *pcbio = cbio;
  1233. client = BIO_get_peer_name(cbio);
  1234. # ifdef OCSP_DAEMON
  1235. if (timeout > 0) {
  1236. (void) BIO_get_fd(cbio, &acfd);
  1237. alarm(timeout);
  1238. }
  1239. # endif
  1240. /* Read the request line. */
  1241. len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
  1242. if (len <= 0)
  1243. goto out;
  1244. if (strncmp(reqbuf, "GET ", 4) == 0) {
  1245. /* Expecting GET {sp} /URL {sp} HTTP/1.x */
  1246. for (p = reqbuf + 4; *p == ' '; ++p)
  1247. continue;
  1248. if (*p != '/') {
  1249. log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
  1250. goto out;
  1251. }
  1252. p++;
  1253. /* Splice off the HTTP version identifier. */
  1254. for (q = p; *q; q++)
  1255. if (*q == ' ')
  1256. break;
  1257. if (strncmp(q, " HTTP/1.", 8) != 0) {
  1258. log_message(LOG_INFO,
  1259. "Invalid request -- bad HTTP version: %s", client);
  1260. goto out;
  1261. }
  1262. *q = '\0';
  1263. /*
  1264. * Skip "GET / HTTP..." requests often used by load-balancers
  1265. */
  1266. if (p[1] == '\0')
  1267. goto out;
  1268. len = urldecode(p);
  1269. if (len <= 0) {
  1270. log_message(LOG_INFO,
  1271. "Invalid request -- bad URL encoding: %s", client);
  1272. goto out;
  1273. }
  1274. if ((getbio = BIO_new_mem_buf(p, len)) == NULL
  1275. || (b64 = BIO_new(BIO_f_base64())) == NULL) {
  1276. log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
  1277. goto out;
  1278. }
  1279. BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
  1280. getbio = BIO_push(b64, getbio);
  1281. } else if (strncmp(reqbuf, "POST ", 5) != 0) {
  1282. log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
  1283. goto out;
  1284. }
  1285. /* Read and skip past the headers. */
  1286. for (;;) {
  1287. len = BIO_gets(cbio, inbuf, sizeof(inbuf));
  1288. if (len <= 0)
  1289. goto out;
  1290. if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
  1291. break;
  1292. }
  1293. # ifdef OCSP_DAEMON
  1294. /* Clear alarm before we close the client socket */
  1295. alarm(0);
  1296. timeout = 0;
  1297. # endif
  1298. /* Try to read OCSP request */
  1299. if (getbio != NULL) {
  1300. req = d2i_OCSP_REQUEST_bio(getbio, NULL);
  1301. BIO_free_all(getbio);
  1302. } else {
  1303. req = d2i_OCSP_REQUEST_bio(cbio, NULL);
  1304. }
  1305. if (req == NULL)
  1306. log_message(LOG_ERR, "Error parsing OCSP request");
  1307. *preq = req;
  1308. out:
  1309. # ifdef OCSP_DAEMON
  1310. if (timeout > 0)
  1311. alarm(0);
  1312. acfd = (int)INVALID_SOCKET;
  1313. # endif
  1314. return 1;
  1315. # endif
  1316. }
  1317. static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
  1318. {
  1319. char http_resp[] =
  1320. "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
  1321. "Content-Length: %d\r\n\r\n";
  1322. if (cbio == NULL)
  1323. return 0;
  1324. BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
  1325. i2d_OCSP_RESPONSE_bio(cbio, resp);
  1326. (void)BIO_flush(cbio);
  1327. return 1;
  1328. }
  1329. # ifndef OPENSSL_NO_SOCK
  1330. static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
  1331. const char *path,
  1332. const STACK_OF(CONF_VALUE) *headers,
  1333. OCSP_REQUEST *req, int req_timeout)
  1334. {
  1335. int fd;
  1336. int rv;
  1337. int i;
  1338. int add_host = 1;
  1339. OCSP_REQ_CTX *ctx = NULL;
  1340. OCSP_RESPONSE *rsp = NULL;
  1341. fd_set confds;
  1342. struct timeval tv;
  1343. if (req_timeout != -1)
  1344. BIO_set_nbio(cbio, 1);
  1345. rv = BIO_do_connect(cbio);
  1346. if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
  1347. BIO_puts(bio_err, "Error connecting BIO\n");
  1348. return NULL;
  1349. }
  1350. if (BIO_get_fd(cbio, &fd) < 0) {
  1351. BIO_puts(bio_err, "Can't get connection fd\n");
  1352. goto err;
  1353. }
  1354. if (req_timeout != -1 && rv <= 0) {
  1355. FD_ZERO(&confds);
  1356. openssl_fdset(fd, &confds);
  1357. tv.tv_usec = 0;
  1358. tv.tv_sec = req_timeout;
  1359. rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
  1360. if (rv == 0) {
  1361. BIO_puts(bio_err, "Timeout on connect\n");
  1362. return NULL;
  1363. }
  1364. }
  1365. ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
  1366. if (ctx == NULL)
  1367. return NULL;
  1368. for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
  1369. CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
  1370. if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
  1371. add_host = 0;
  1372. if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
  1373. goto err;
  1374. }
  1375. if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
  1376. goto err;
  1377. if (!OCSP_REQ_CTX_set1_req(ctx, req))
  1378. goto err;
  1379. for (;;) {
  1380. rv = OCSP_sendreq_nbio(&rsp, ctx);
  1381. if (rv != -1)
  1382. break;
  1383. if (req_timeout == -1)
  1384. continue;
  1385. FD_ZERO(&confds);
  1386. openssl_fdset(fd, &confds);
  1387. tv.tv_usec = 0;
  1388. tv.tv_sec = req_timeout;
  1389. if (BIO_should_read(cbio)) {
  1390. rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
  1391. } else if (BIO_should_write(cbio)) {
  1392. rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
  1393. } else {
  1394. BIO_puts(bio_err, "Unexpected retry condition\n");
  1395. goto err;
  1396. }
  1397. if (rv == 0) {
  1398. BIO_puts(bio_err, "Timeout on request\n");
  1399. break;
  1400. }
  1401. if (rv == -1) {
  1402. BIO_puts(bio_err, "Select error\n");
  1403. break;
  1404. }
  1405. }
  1406. err:
  1407. OCSP_REQ_CTX_free(ctx);
  1408. return rsp;
  1409. }
  1410. OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
  1411. const char *host, const char *path,
  1412. const char *port, int use_ssl,
  1413. STACK_OF(CONF_VALUE) *headers,
  1414. int req_timeout)
  1415. {
  1416. BIO *cbio = NULL;
  1417. SSL_CTX *ctx = NULL;
  1418. OCSP_RESPONSE *resp = NULL;
  1419. cbio = BIO_new_connect(host);
  1420. if (cbio == NULL) {
  1421. BIO_printf(bio_err, "Error creating connect BIO\n");
  1422. goto end;
  1423. }
  1424. if (port != NULL)
  1425. BIO_set_conn_port(cbio, port);
  1426. if (use_ssl == 1) {
  1427. BIO *sbio;
  1428. ctx = SSL_CTX_new(TLS_client_method());
  1429. if (ctx == NULL) {
  1430. BIO_printf(bio_err, "Error creating SSL context.\n");
  1431. goto end;
  1432. }
  1433. SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
  1434. sbio = BIO_new_ssl(ctx, 1);
  1435. cbio = BIO_push(sbio, cbio);
  1436. }
  1437. resp = query_responder(cbio, host, path, headers, req, req_timeout);
  1438. if (resp == NULL)
  1439. BIO_printf(bio_err, "Error querying OCSP responder\n");
  1440. end:
  1441. BIO_free_all(cbio);
  1442. SSL_CTX_free(ctx);
  1443. return resp;
  1444. }
  1445. # endif
  1446. #endif