openssl.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238
  1. /*********************************************************************
  2. *
  3. * File : $Source: /cvsroot/ijbswa/current/openssl.c,v $
  4. *
  5. * Purpose : File with TLS/SSL extension. Contains methods for
  6. * creating, using and closing TLS/SSL connections.
  7. *
  8. * Copyright : Written by and Copyright (c) 2020 Maxim Antonov <mantonov@gmail.com>
  9. * Copyright (C) 2017 Vaclav Svec. FIT CVUT.
  10. * Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
  11. *
  12. * This program is free software; you can redistribute it
  13. * and/or modify it under the terms of the GNU General
  14. * Public License as published by the Free Software
  15. * Foundation; either version 2 of the License, or (at
  16. * your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will
  19. * be useful, but WITHOUT ANY WARRANTY; without even the
  20. * implied warranty of MERCHANTABILITY or FITNESS FOR A
  21. * PARTICULAR PURPOSE. See the GNU General Public
  22. * License for more details.
  23. *
  24. * The GNU General Public License should be included with
  25. * this file. If not, you can view it at
  26. * http://www.gnu.org/copyleft/gpl.html
  27. * or write to the Free Software Foundation, Inc., 59
  28. * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  29. *
  30. *********************************************************************/
  31. #include <string.h>
  32. #include <unistd.h>
  33. #include <openssl/bn.h>
  34. #include <openssl/opensslv.h>
  35. #include <openssl/pem.h>
  36. #include <openssl/md5.h>
  37. #include <openssl/x509v3.h>
  38. #include "config.h"
  39. #include "project.h"
  40. #include "miscutil.h"
  41. #include "errlog.h"
  42. #include "encode.h"
  43. #include "jcc.h"
  44. #include "ssl.h"
  45. #include "ssl_common.h"
  46. /*
  47. * Macros for openssl.c
  48. */
  49. #define CERTIFICATE_BASIC_CONSTRAINTS "CA:FALSE"
  50. #define CERTIFICATE_SUBJECT_KEY "hash"
  51. #define CERTIFICATE_AUTHORITY_KEY "keyid:always"
  52. #define CERTIFICATE_ALT_NAME_PREFIX "DNS:"
  53. #define CERTIFICATE_VERSION 2
  54. #define VALID_DATETIME_FMT "%y%m%d%H%M%SZ"
  55. #define VALID_DATETIME_BUFLEN 16
  56. static int generate_webpage_certificate(struct client_state *csp);
  57. static void free_client_ssl_structures(struct client_state *csp);
  58. static void free_server_ssl_structures(struct client_state *csp);
  59. static int ssl_store_cert(struct client_state *csp, X509* crt);
  60. static void log_ssl_errors(int debuglevel, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
  61. static int ssl_inited = 0;
  62. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  63. #define X509_set1_notBefore X509_set_notBefore
  64. #define X509_set1_notAfter X509_set_notAfter
  65. #define X509_get0_serialNumber X509_get_serialNumber
  66. #define X509_get0_notBefore X509_get_notBefore
  67. #define X509_get0_notAfter X509_get_notAfter
  68. #endif
  69. /*********************************************************************
  70. *
  71. * Function : openssl_init
  72. *
  73. * Description : Initializes OpenSSL library once
  74. *
  75. * Parameters : N/A
  76. *
  77. * Returns : N/A
  78. *
  79. *********************************************************************/
  80. static void openssl_init(void)
  81. {
  82. if (ssl_inited == 0)
  83. {
  84. privoxy_mutex_lock(&ssl_init_mutex);
  85. if (ssl_inited == 0)
  86. {
  87. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  88. SSL_library_init();
  89. #else
  90. OPENSSL_init_ssl(0, NULL);
  91. #endif
  92. SSL_load_error_strings();
  93. OpenSSL_add_ssl_algorithms();
  94. ssl_inited = 1;
  95. }
  96. privoxy_mutex_unlock(&ssl_init_mutex);
  97. }
  98. }
  99. /*********************************************************************
  100. *
  101. * Function : is_ssl_pending
  102. *
  103. * Description : Tests if there are some waiting data on ssl connection.
  104. * Only considers data that has actually been received
  105. * locally and ignores data that is still on the fly
  106. * or has not yet been sent by the remote end.
  107. *
  108. * Parameters :
  109. * 1 : ssl_attr = SSL context to test
  110. *
  111. * Returns : 0 => No data are pending
  112. * >0 => Pending data length
  113. *
  114. *********************************************************************/
  115. extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
  116. {
  117. BIO *bio = ssl_attr->openssl_attr.bio;
  118. if (bio == NULL)
  119. {
  120. return 0;
  121. }
  122. return (size_t)BIO_pending(bio);
  123. }
  124. /*********************************************************************
  125. *
  126. * Function : ssl_send_data
  127. *
  128. * Description : Sends the content of buf (for n bytes) to given SSL
  129. * connection context.
  130. *
  131. * Parameters :
  132. * 1 : ssl_attr = SSL context to send data to
  133. * 2 : buf = Pointer to data to be sent
  134. * 3 : len = Length of data to be sent to the SSL context
  135. *
  136. * Returns : Length of sent data or negative value on error.
  137. *
  138. *********************************************************************/
  139. extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
  140. {
  141. BIO *bio = ssl_attr->openssl_attr.bio;
  142. SSL *ssl;
  143. int ret = 0;
  144. int pos = 0; /* Position of unsent part in buffer */
  145. int fd = -1;
  146. if (len == 0)
  147. {
  148. return 0;
  149. }
  150. if (BIO_get_ssl(bio, &ssl) == 1)
  151. {
  152. fd = SSL_get_fd(ssl);
  153. }
  154. while (pos < len)
  155. {
  156. int send_len = (int)len - pos;
  157. log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
  158. fd, send_len, buf+pos);
  159. /*
  160. * Sending one part of the buffer
  161. */
  162. while ((ret = BIO_write(bio,
  163. (const unsigned char *)(buf + pos),
  164. send_len)) <= 0)
  165. {
  166. if (!BIO_should_retry(bio))
  167. {
  168. log_ssl_errors(LOG_LEVEL_ERROR,
  169. "Sending data on socket %d over TLS/SSL failed", fd);
  170. return -1;
  171. }
  172. }
  173. /* Adding count of sent bytes to position in buffer */
  174. pos = pos + ret;
  175. }
  176. return (int)len;
  177. }
  178. /*********************************************************************
  179. *
  180. * Function : ssl_recv_data
  181. *
  182. * Description : Receives data from given SSL context and puts
  183. * it into buffer.
  184. *
  185. * Parameters :
  186. * 1 : ssl_attr = SSL context to receive data from
  187. * 2 : buf = Pointer to buffer where data will be written
  188. * 3 : max_length = Maximum number of bytes to read
  189. *
  190. * Returns : Number of bytes read, 0 for EOF, or -1
  191. * on error.
  192. *
  193. *********************************************************************/
  194. extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
  195. {
  196. BIO *bio = ssl_attr->openssl_attr.bio;
  197. SSL *ssl;
  198. int ret = 0;
  199. int fd = -1;
  200. memset(buf, 0, max_length);
  201. /*
  202. * Receiving data from SSL context into buffer
  203. */
  204. do
  205. {
  206. ret = BIO_read(bio, buf, (int)max_length);
  207. } while (ret <= 0 && BIO_should_retry(bio));
  208. if (ret < 0)
  209. {
  210. log_ssl_errors(LOG_LEVEL_ERROR,
  211. "Receiving data on socket %d over TLS/SSL failed", fd);
  212. return -1;
  213. }
  214. if (BIO_get_ssl(bio, &ssl) == 1)
  215. {
  216. fd = SSL_get_fd(ssl);
  217. }
  218. log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
  219. fd, ret, buf);
  220. return ret;
  221. }
  222. /*********************************************************************
  223. *
  224. * Function : ssl_store_cert
  225. *
  226. * Description : This function is called once for each certificate in the
  227. * server's certificate trusted chain and prepares
  228. * information about the certificate. The information can
  229. * be used to inform the user about invalid certificates.
  230. *
  231. * Parameters :
  232. * 1 : csp = Current client state (buffers, headers, etc...)
  233. * 2 : crt = certificate from trusted chain
  234. *
  235. * Returns : 0 on success and negative value on error
  236. *
  237. *********************************************************************/
  238. static int ssl_store_cert(struct client_state *csp, X509* crt)
  239. {
  240. long len = 0;
  241. struct certs_chain *last = &(csp->server_certs_chain);
  242. int ret = 0;
  243. BIO *bio = BIO_new(BIO_s_mem());
  244. EVP_PKEY *pkey = NULL;
  245. char *bio_mem_data = 0;
  246. char *encoded_text;
  247. long l;
  248. const ASN1_INTEGER *bs;
  249. #if OPENSSL_VERSION_NUMBER > 0x10100000L
  250. const X509_ALGOR *tsig_alg;
  251. #endif
  252. int loc;
  253. if (!bio)
  254. {
  255. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
  256. return -1;
  257. }
  258. /*
  259. * Searching for last item in certificates linked list
  260. */
  261. while (last->next != NULL)
  262. {
  263. last = last->next;
  264. }
  265. /*
  266. * Preparing next item in linked list for next certificate
  267. */
  268. last->next = malloc_or_die(sizeof(struct certs_chain));
  269. last->next->next = NULL;
  270. memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
  271. memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
  272. /*
  273. * Saving certificate file into buffer
  274. */
  275. if (!PEM_write_bio_X509(bio, crt))
  276. {
  277. log_ssl_errors(LOG_LEVEL_ERROR, "PEM_write_X509() failed");
  278. ret = -1;
  279. goto exit;
  280. }
  281. len = BIO_get_mem_data(bio, &bio_mem_data);
  282. if (len > (sizeof(last->file_buf) - 1))
  283. {
  284. log_error(LOG_LEVEL_ERROR,
  285. "X509 PEM cert len %ld is larger than buffer len %lu",
  286. len, sizeof(last->file_buf) - 1);
  287. len = sizeof(last->file_buf) - 1;
  288. }
  289. strncpy(last->file_buf, bio_mem_data, (size_t)len);
  290. BIO_free(bio);
  291. bio = BIO_new(BIO_s_mem());
  292. if (!bio)
  293. {
  294. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
  295. ret = -1;
  296. goto exit;
  297. }
  298. /*
  299. * Saving certificate information into buffer
  300. */
  301. l = X509_get_version(crt);
  302. if (l >= 0 && l <= 2)
  303. {
  304. if (BIO_printf(bio, "cert. version : %ld\n", l + 1) <= 0)
  305. {
  306. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
  307. ret = -1;
  308. goto exit;
  309. }
  310. }
  311. else
  312. {
  313. if (BIO_printf(bio, "cert. version : Unknown (%ld)\n", l) <= 0)
  314. {
  315. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
  316. ret = -1;
  317. goto exit;
  318. }
  319. }
  320. if (BIO_puts(bio, "serial number : ") <= 0)
  321. {
  322. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
  323. ret = -1;
  324. goto exit;
  325. }
  326. bs = X509_get0_serialNumber(crt);
  327. if (bs->length <= (int)sizeof(long))
  328. {
  329. ERR_set_mark();
  330. l = ASN1_INTEGER_get(bs);
  331. ERR_pop_to_mark();
  332. }
  333. else
  334. {
  335. l = -1;
  336. }
  337. if (l != -1)
  338. {
  339. unsigned long ul;
  340. const char *neg;
  341. if (bs->type == V_ASN1_NEG_INTEGER)
  342. {
  343. ul = 0 - (unsigned long)l;
  344. neg = "-";
  345. }
  346. else
  347. {
  348. ul = (unsigned long)l;
  349. neg = "";
  350. }
  351. if (BIO_printf(bio, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
  352. {
  353. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
  354. ret = -1;
  355. goto exit;
  356. }
  357. }
  358. else
  359. {
  360. if (bs->type == V_ASN1_NEG_INTEGER)
  361. {
  362. if (BIO_puts(bio, " (Negative)") < 0)
  363. {
  364. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
  365. ret = -1;
  366. goto exit;
  367. }
  368. }
  369. for (int i = 0; i < bs->length; i++)
  370. {
  371. if (BIO_printf(bio, "%02x%c", bs->data[i],
  372. ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
  373. {
  374. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
  375. ret = -1;
  376. goto exit;
  377. }
  378. }
  379. }
  380. if (BIO_puts(bio, "issuer name : ") <= 0)
  381. {
  382. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issuer failed");
  383. ret = -1;
  384. goto exit;
  385. }
  386. if (X509_NAME_print_ex(bio, X509_get_issuer_name(crt), 0, 0) < 0)
  387. {
  388. log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for issuer failed");
  389. ret = -1;
  390. goto exit;
  391. }
  392. if (BIO_puts(bio, "\nsubject name : ") <= 0)
  393. {
  394. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for subject failed");
  395. ret = -1;
  396. goto exit;
  397. }
  398. if (X509_NAME_print_ex(bio, X509_get_subject_name(crt), 0, 0) < 0) {
  399. log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for subject failed");
  400. ret = -1;
  401. goto exit;
  402. }
  403. if (BIO_puts(bio, "\nissued on : ") <= 0)
  404. {
  405. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issued on failed");
  406. ret = -1;
  407. goto exit;
  408. }
  409. if (!ASN1_TIME_print(bio, X509_get0_notBefore(crt)))
  410. {
  411. log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for issued on failed");
  412. ret = -1;
  413. goto exit;
  414. }
  415. if (BIO_puts(bio, "\nexpires on : ") <= 0)
  416. {
  417. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for expires on failed");
  418. ret = -1;
  419. goto exit;
  420. }
  421. if (!ASN1_TIME_print(bio, X509_get0_notAfter(crt)))
  422. {
  423. log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for expires on failed");
  424. ret = -1;
  425. goto exit;
  426. }
  427. #if OPENSSL_VERSION_NUMBER > 0x10100000L
  428. if (BIO_puts(bio, "\nsigned using : ") <= 0)
  429. {
  430. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for signed using failed");
  431. ret = -1;
  432. goto exit;
  433. }
  434. tsig_alg = X509_get0_tbs_sigalg(crt);
  435. if (!i2a_ASN1_OBJECT(bio, tsig_alg->algorithm))
  436. {
  437. log_ssl_errors(LOG_LEVEL_ERROR, "i2a_ASN1_OBJECT() for signed using failed");
  438. ret = -1;
  439. goto exit;
  440. }
  441. #endif
  442. pkey = X509_get_pubkey(crt);
  443. if (!pkey)
  444. {
  445. log_ssl_errors(LOG_LEVEL_ERROR, "X509_get_pubkey() failed");
  446. ret = -1;
  447. goto exit;
  448. }
  449. #define BC "18"
  450. switch (EVP_PKEY_base_id(pkey))
  451. {
  452. case EVP_PKEY_RSA:
  453. ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "RSA key size", EVP_PKEY_bits(pkey));
  454. break;
  455. case EVP_PKEY_DSA:
  456. ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
  457. break;
  458. default:
  459. ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA key size", EVP_PKEY_bits(pkey));
  460. break;
  461. }
  462. if (ret <= 0)
  463. {
  464. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key size failed");
  465. ret = -1;
  466. goto exit;
  467. }
  468. loc = X509_get_ext_by_NID(crt, NID_basic_constraints, -1);
  469. if (loc != -1)
  470. {
  471. X509_EXTENSION *ex = X509_get_ext(crt, loc);
  472. if (BIO_puts(bio, "\nbasic constraints : ") <= 0)
  473. {
  474. log_ssl_errors(LOG_LEVEL_ERROR,
  475. "BIO_printf() for basic constraints failed");
  476. ret = -1;
  477. goto exit;
  478. }
  479. if (!X509V3_EXT_print(bio, ex, 0, 0))
  480. {
  481. if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253))
  482. {
  483. log_ssl_errors(LOG_LEVEL_ERROR,
  484. "ASN1_STRING_print_ex() for basic constraints failed");
  485. ret = -1;
  486. goto exit;
  487. }
  488. }
  489. }
  490. loc = X509_get_ext_by_NID(crt, NID_subject_alt_name, -1);
  491. if (loc != -1)
  492. {
  493. X509_EXTENSION *ex = X509_get_ext(crt, loc);
  494. if (BIO_puts(bio, "\nsubject alt name : ") <= 0)
  495. {
  496. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for alt name failed");
  497. ret = -1;
  498. goto exit;
  499. }
  500. if (!X509V3_EXT_print(bio, ex, 0, 0))
  501. {
  502. if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
  503. ASN1_STRFLGS_RFC2253))
  504. {
  505. log_ssl_errors(LOG_LEVEL_ERROR,
  506. "ASN1_STRING_print_ex() for alt name failed");
  507. ret = -1;
  508. goto exit;
  509. }
  510. }
  511. }
  512. loc = X509_get_ext_by_NID(crt, NID_netscape_cert_type, -1);
  513. if (loc != -1)
  514. {
  515. X509_EXTENSION *ex = X509_get_ext(crt, loc);
  516. if (BIO_puts(bio, "\ncert. type : ") <= 0)
  517. {
  518. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for cert type failed");
  519. ret = -1;
  520. goto exit;
  521. }
  522. if (!X509V3_EXT_print(bio, ex, 0, 0))
  523. {
  524. if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
  525. ASN1_STRFLGS_RFC2253))
  526. {
  527. log_ssl_errors(LOG_LEVEL_ERROR,
  528. "ASN1_STRING_print_ex() for cert type failed");
  529. ret = -1;
  530. goto exit;
  531. }
  532. }
  533. }
  534. loc = X509_get_ext_by_NID(crt, NID_key_usage, -1);
  535. if (loc != -1)
  536. {
  537. X509_EXTENSION *ex = X509_get_ext(crt, loc);
  538. if (BIO_puts(bio, "\nkey usage : ") <= 0)
  539. {
  540. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key usage failed");
  541. ret = -1;
  542. goto exit;
  543. }
  544. if (!X509V3_EXT_print(bio, ex, 0, 0))
  545. {
  546. if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
  547. ASN1_STRFLGS_RFC2253))
  548. {
  549. log_ssl_errors(LOG_LEVEL_ERROR,
  550. "ASN1_STRING_print_ex() for key usage failed");
  551. ret = -1;
  552. goto exit;
  553. }
  554. }
  555. }
  556. loc = X509_get_ext_by_NID(crt, NID_ext_key_usage, -1);
  557. if (loc != -1) {
  558. X509_EXTENSION *ex = X509_get_ext(crt, loc);
  559. if (BIO_puts(bio, "\next key usage : ") <= 0)
  560. {
  561. log_ssl_errors(LOG_LEVEL_ERROR,
  562. "BIO_printf() for ext key usage failed");
  563. ret = -1;
  564. goto exit;
  565. }
  566. if (!X509V3_EXT_print(bio, ex, 0, 0))
  567. {
  568. if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
  569. ASN1_STRFLGS_RFC2253))
  570. {
  571. log_ssl_errors(LOG_LEVEL_ERROR,
  572. "ASN1_STRING_print_ex() for ext key usage failed");
  573. ret = -1;
  574. goto exit;
  575. }
  576. }
  577. }
  578. loc = X509_get_ext_by_NID(crt, NID_certificate_policies, -1);
  579. if (loc != -1)
  580. {
  581. X509_EXTENSION *ex = X509_get_ext(crt, loc);
  582. if (BIO_puts(bio, "\ncertificate policies : ") <= 0)
  583. {
  584. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for certificate policies failed");
  585. ret = -1;
  586. goto exit;
  587. }
  588. if (!X509V3_EXT_print(bio, ex, 0, 0))
  589. {
  590. if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
  591. ASN1_STRFLGS_RFC2253))
  592. {
  593. log_ssl_errors(LOG_LEVEL_ERROR,
  594. "ASN1_STRING_print_ex() for certificate policies failed");
  595. ret = -1;
  596. goto exit;
  597. }
  598. }
  599. }
  600. /* make valgrind happy */
  601. static const char zero = 0;
  602. BIO_write(bio, &zero, 1);
  603. len = BIO_get_mem_data(bio, &bio_mem_data);
  604. encoded_text = html_encode(bio_mem_data);
  605. if (encoded_text == NULL)
  606. {
  607. log_error(LOG_LEVEL_ERROR,
  608. "Failed to HTML-encode the certificate information");
  609. ret = -1;
  610. goto exit;
  611. }
  612. strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
  613. freez(encoded_text);
  614. ret = 0;
  615. exit:
  616. if (bio)
  617. {
  618. BIO_free(bio);
  619. }
  620. if (pkey)
  621. {
  622. EVP_PKEY_free(pkey);
  623. }
  624. return ret;
  625. }
  626. /*********************************************************************
  627. *
  628. * Function : host_to_hash
  629. *
  630. * Description : Creates MD5 hash from host name. Host name is loaded
  631. * from structure csp and saved again into it.
  632. *
  633. * Parameters :
  634. * 1 : csp = Current client state (buffers, headers, etc...)
  635. *
  636. * Returns : 1 => Error while creating hash
  637. * 0 => Hash created successfully
  638. *
  639. *********************************************************************/
  640. static int host_to_hash(struct client_state *csp)
  641. {
  642. int ret = 0;
  643. memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
  644. MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
  645. csp->http->hash_of_host);
  646. /* Converting hash into string with hex */
  647. size_t i = 0;
  648. for (; i < 16; i++)
  649. {
  650. if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
  651. csp->http->hash_of_host[i])) < 0)
  652. {
  653. log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
  654. return -1;
  655. }
  656. }
  657. return 0;
  658. }
  659. /*********************************************************************
  660. *
  661. * Function : create_client_ssl_connection
  662. *
  663. * Description : Creates TLS/SSL secured connection with client
  664. *
  665. * Parameters :
  666. * 1 : csp = Current client state (buffers, headers, etc...)
  667. *
  668. * Returns : 0 on success, negative value if connection wasn't created
  669. * successfully.
  670. *
  671. *********************************************************************/
  672. extern int create_client_ssl_connection(struct client_state *csp)
  673. {
  674. struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
  675. /* Paths to certificates file and key file */
  676. char *key_file = NULL;
  677. char *ca_file = NULL;
  678. char *cert_file = NULL;
  679. int ret = 0;
  680. SSL *ssl;
  681. /*
  682. * Initializing OpenSSL structures for TLS/SSL connection
  683. */
  684. openssl_init();
  685. /*
  686. * Preparing hash of host for creating certificates
  687. */
  688. ret = host_to_hash(csp);
  689. if (ret != 0)
  690. {
  691. log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
  692. ret = -1;
  693. goto exit;
  694. }
  695. /*
  696. * Preparing paths to certificates files and key file
  697. */
  698. ca_file = csp->config->ca_cert_file;
  699. cert_file = make_certs_path(csp->config->certificate_directory,
  700. (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
  701. key_file = make_certs_path(csp->config->certificate_directory,
  702. (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
  703. if (cert_file == NULL || key_file == NULL)
  704. {
  705. ret = -1;
  706. goto exit;
  707. }
  708. /*
  709. * Generating certificate for requested host. Mutex to prevent
  710. * certificate and key inconsistence must be locked.
  711. */
  712. privoxy_mutex_lock(&certificate_mutex);
  713. ret = generate_webpage_certificate(csp);
  714. if (ret < 0)
  715. {
  716. log_error(LOG_LEVEL_ERROR,
  717. "Generate_webpage_certificate failed: %d", ret);
  718. privoxy_mutex_unlock(&certificate_mutex);
  719. ret = -1;
  720. goto exit;
  721. }
  722. privoxy_mutex_unlock(&certificate_mutex);
  723. if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
  724. {
  725. log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
  726. ret = -1;
  727. goto exit;
  728. }
  729. /* Set the key and cert */
  730. if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
  731. cert_file, SSL_FILETYPE_PEM) != 1)
  732. {
  733. log_ssl_errors(LOG_LEVEL_ERROR,
  734. "Loading webpage certificate %s failed", cert_file);
  735. ret = -1;
  736. goto exit;
  737. }
  738. if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx,
  739. key_file, SSL_FILETYPE_PEM) != 1)
  740. {
  741. log_ssl_errors(LOG_LEVEL_ERROR,
  742. "Loading webpage certificate private key %s failed", key_file);
  743. ret = -1;
  744. goto exit;
  745. }
  746. SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
  747. if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0)))
  748. {
  749. log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
  750. ret = -1;
  751. goto exit;
  752. }
  753. if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
  754. {
  755. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
  756. ret = -1;
  757. goto exit;
  758. }
  759. if (!SSL_set_fd(ssl, csp->cfd))
  760. {
  761. log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
  762. ret = -1;
  763. goto exit;
  764. }
  765. if (csp->config->cipher_list != NULL)
  766. {
  767. if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
  768. {
  769. log_ssl_errors(LOG_LEVEL_ERROR,
  770. "Setting the cipher list '%s' for the client connection failed",
  771. csp->config->cipher_list);
  772. ret = -1;
  773. goto exit;
  774. }
  775. }
  776. /*
  777. * Handshake with client
  778. */
  779. log_error(LOG_LEVEL_CONNECT,
  780. "Performing the TLS/SSL handshake with client. Hash of host: %s",
  781. csp->http->hash_of_host_hex);
  782. if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1)
  783. {
  784. log_ssl_errors(LOG_LEVEL_ERROR,
  785. "The TLS/SSL handshake with the client failed");
  786. ret = -1;
  787. goto exit;
  788. }
  789. log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
  790. csp->ssl_with_client_is_opened = 1;
  791. ret = 0;
  792. exit:
  793. /*
  794. * Freeing allocated paths to files
  795. */
  796. freez(cert_file);
  797. freez(key_file);
  798. /* Freeing structures if connection wasn't created successfully */
  799. if (ret < 0)
  800. {
  801. free_client_ssl_structures(csp);
  802. }
  803. return ret;
  804. }
  805. /*********************************************************************
  806. *
  807. * Function : close_client_ssl_connection
  808. *
  809. * Description : Closes TLS/SSL connection with client. This function
  810. * checks if this connection is already created.
  811. *
  812. * Parameters :
  813. * 1 : csp = Current client state (buffers, headers, etc...)
  814. *
  815. * Returns : N/A
  816. *
  817. *********************************************************************/
  818. extern void close_client_ssl_connection(struct client_state *csp)
  819. {
  820. struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
  821. SSL *ssl;
  822. if (csp->ssl_with_client_is_opened == 0)
  823. {
  824. return;
  825. }
  826. /*
  827. * Notifying the peer that the connection is being closed.
  828. */
  829. BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
  830. if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
  831. {
  832. log_ssl_errors(LOG_LEVEL_ERROR,
  833. "BIO_get_ssl() failed in close_client_ssl_connection()");
  834. }
  835. else
  836. {
  837. /*
  838. * Pretend we received a shutdown alert so
  839. * the BIO_free_all() call later on returns
  840. * quickly.
  841. */
  842. SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
  843. }
  844. free_client_ssl_structures(csp);
  845. csp->ssl_with_client_is_opened = 0;
  846. }
  847. /*********************************************************************
  848. *
  849. * Function : free_client_ssl_structures
  850. *
  851. * Description : Frees structures used for SSL communication with
  852. * client.
  853. *
  854. * Parameters :
  855. * 1 : csp = Current client state (buffers, headers, etc...)
  856. *
  857. * Returns : N/A
  858. *
  859. *********************************************************************/
  860. static void free_client_ssl_structures(struct client_state *csp)
  861. {
  862. struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
  863. if (ssl_attr->openssl_attr.bio)
  864. {
  865. BIO_free_all(ssl_attr->openssl_attr.bio);
  866. }
  867. if (ssl_attr->openssl_attr.ctx)
  868. {
  869. SSL_CTX_free(ssl_attr->openssl_attr.ctx);
  870. }
  871. }
  872. /*********************************************************************
  873. *
  874. * Function : close_server_ssl_connection
  875. *
  876. * Description : Closes TLS/SSL connection with server. This function
  877. * checks if this connection is already opened.
  878. *
  879. * Parameters :
  880. * 1 : csp = Current client state (buffers, headers, etc...)
  881. *
  882. * Returns : N/A
  883. *
  884. *********************************************************************/
  885. extern void close_server_ssl_connection(struct client_state *csp)
  886. {
  887. struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
  888. SSL *ssl;
  889. if (csp->ssl_with_server_is_opened == 0)
  890. {
  891. return;
  892. }
  893. /*
  894. * Notifying the peer that the connection is being closed.
  895. */
  896. BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
  897. if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
  898. {
  899. log_ssl_errors(LOG_LEVEL_ERROR,
  900. "BIO_get_ssl() failed in close_server_ssl_connection()");
  901. }
  902. else
  903. {
  904. /*
  905. * Pretend we received a shutdown alert so
  906. * the BIO_free_all() call later on returns
  907. * quickly.
  908. */
  909. SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
  910. }
  911. free_server_ssl_structures(csp);
  912. csp->ssl_with_server_is_opened = 0;
  913. }
  914. /*********************************************************************
  915. *
  916. * Function : create_server_ssl_connection
  917. *
  918. * Description : Creates TLS/SSL secured connection with server.
  919. *
  920. * Parameters :
  921. * 1 : csp = Current client state (buffers, headers, etc...)
  922. *
  923. * Returns : 0 on success, negative value if connection wasn't created
  924. * successfully.
  925. *
  926. *********************************************************************/
  927. extern int create_server_ssl_connection(struct client_state *csp)
  928. {
  929. openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
  930. int ret = 0;
  931. char *trusted_cas_file = NULL;
  932. STACK_OF(X509) *chain;
  933. SSL *ssl;
  934. csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
  935. csp->server_certs_chain.next = NULL;
  936. /* Setting path to file with trusted CAs */
  937. trusted_cas_file = csp->config->trusted_cas_file;
  938. ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
  939. if (!ssl_attrs->ctx)
  940. {
  941. log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
  942. ret = -1;
  943. goto exit;
  944. }
  945. /*
  946. * Loading file with trusted CAs
  947. */
  948. if (!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
  949. {
  950. log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
  951. trusted_cas_file);
  952. ret = -1;
  953. goto exit;
  954. }
  955. SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
  956. SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
  957. if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1)))
  958. {
  959. log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
  960. ret = -1;
  961. goto exit;
  962. }
  963. if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
  964. {
  965. log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
  966. ret = -1;
  967. goto exit;
  968. }
  969. if (!SSL_set_fd(ssl, csp->server_connection.sfd))
  970. {
  971. log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
  972. ret = -1;
  973. goto exit;
  974. }
  975. if (csp->config->cipher_list != NULL)
  976. {
  977. if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
  978. {
  979. log_ssl_errors(LOG_LEVEL_ERROR,
  980. "Setting the cipher list '%s' for the server connection failed",
  981. csp->config->cipher_list);
  982. ret = -1;
  983. goto exit;
  984. }
  985. }
  986. /*
  987. * Set the hostname to check against the received server certificate
  988. */
  989. #if OPENSSL_VERSION_NUMBER > 0x10100000L
  990. if (!SSL_set1_host(ssl, csp->http->host))
  991. {
  992. log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
  993. ret = -1;
  994. goto exit;
  995. }
  996. #else
  997. if (host_is_ip_address(csp->http->host))
  998. {
  999. if (X509_VERIFY_PARAM_set1_ip_asc(ssl->param, csp->http->host) != 1)
  1000. {
  1001. log_ssl_errors(LOG_LEVEL_ERROR,
  1002. "X509_VERIFY_PARAM_set1_ip_asc() failed");
  1003. ret = -1;
  1004. goto exit;
  1005. }
  1006. }
  1007. else
  1008. {
  1009. if (X509_VERIFY_PARAM_set1_host(ssl->param, csp->http->host, 0) != 1)
  1010. {
  1011. log_ssl_errors(LOG_LEVEL_ERROR,
  1012. "X509_VERIFY_PARAM_set1_host() failed");
  1013. ret = -1;
  1014. goto exit;
  1015. }
  1016. }
  1017. #endif
  1018. /* SNI extension */
  1019. if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
  1020. {
  1021. log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
  1022. ret = -1;
  1023. goto exit;
  1024. }
  1025. /*
  1026. * Handshake with server
  1027. */
  1028. log_error(LOG_LEVEL_CONNECT,
  1029. "Performing the TLS/SSL handshake with the server");
  1030. if (BIO_do_handshake(ssl_attrs->bio) != 1)
  1031. {
  1032. log_ssl_errors(LOG_LEVEL_ERROR,
  1033. "The TLS/SSL handshake with the server failed");
  1034. ret = -1;
  1035. goto exit;
  1036. }
  1037. chain = SSL_get_peer_cert_chain(ssl);
  1038. if (chain)
  1039. {
  1040. for (int i = 0; i < sk_X509_num(chain); i++)
  1041. {
  1042. if (ssl_store_cert(csp, sk_X509_value(chain, i)) != 0)
  1043. {
  1044. log_error(LOG_LEVEL_ERROR, "ssl_store_cert failed");
  1045. ret = -1;
  1046. goto exit;
  1047. }
  1048. }
  1049. }
  1050. if (!csp->dont_verify_certificate)
  1051. {
  1052. long verify_result = SSL_get_verify_result(ssl);
  1053. if (verify_result == X509_V_OK)
  1054. {
  1055. ret = 0;
  1056. csp->server_cert_verification_result = SSL_CERT_VALID;
  1057. }
  1058. else
  1059. {
  1060. csp->server_cert_verification_result = verify_result;
  1061. log_error(LOG_LEVEL_ERROR,
  1062. "X509 certificate verification for %s failed: %s",
  1063. csp->http->hostport, X509_verify_cert_error_string(verify_result));
  1064. ret = -1;
  1065. goto exit;
  1066. }
  1067. }
  1068. log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
  1069. /*
  1070. * Server certificate chain is valid, so we can clean
  1071. * chain, because we will not send it to client.
  1072. */
  1073. free_certificate_chain(csp);
  1074. csp->ssl_with_server_is_opened = 1;
  1075. exit:
  1076. /* Freeing structures if connection wasn't created successfully */
  1077. if (ret < 0)
  1078. {
  1079. free_server_ssl_structures(csp);
  1080. }
  1081. return ret;
  1082. }
  1083. /*********************************************************************
  1084. *
  1085. * Function : free_server_ssl_structures
  1086. *
  1087. * Description : Frees structures used for SSL communication with server
  1088. *
  1089. * Parameters :
  1090. * 1 : csp = Current client state (buffers, headers, etc...)
  1091. *
  1092. * Returns : N/A
  1093. *
  1094. *********************************************************************/
  1095. static void free_server_ssl_structures(struct client_state *csp)
  1096. {
  1097. struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
  1098. if (ssl_attr->openssl_attr.bio)
  1099. {
  1100. BIO_free_all(ssl_attr->openssl_attr.bio);
  1101. }
  1102. if (ssl_attr->openssl_attr.ctx)
  1103. {
  1104. SSL_CTX_free(ssl_attr->openssl_attr.ctx);
  1105. }
  1106. }
  1107. /*********************************************************************
  1108. *
  1109. * Function : log_ssl_errors
  1110. *
  1111. * Description : Log SSL errors
  1112. *
  1113. * Parameters :
  1114. * 1 : debuglevel = Debug level
  1115. * 2 : desc = Error description
  1116. *
  1117. * Returns : N/A
  1118. *
  1119. *********************************************************************/
  1120. static void log_ssl_errors(int debuglevel, const char* fmt, ...)
  1121. {
  1122. unsigned long err_code;
  1123. char prefix[ERROR_BUF_SIZE];
  1124. va_list args;
  1125. va_start(args, fmt);
  1126. vsnprintf(prefix, sizeof(prefix), fmt, args);
  1127. int reported = 0;
  1128. while ((err_code = ERR_get_error()))
  1129. {
  1130. char err_buf[ERROR_BUF_SIZE];
  1131. reported = 1;
  1132. ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
  1133. log_error(debuglevel, "%s: %s", prefix, err_buf);
  1134. }
  1135. va_end(args);
  1136. /*
  1137. * In case if called by mistake and there were
  1138. * no TLS/SSL errors let's report it to the log.
  1139. */
  1140. if (!reported)
  1141. {
  1142. log_error(debuglevel, "%s: no TLS/SSL errors detected", prefix);
  1143. }
  1144. }
  1145. /*********************************************************************
  1146. *
  1147. * Function : ssl_base64_encode
  1148. *
  1149. * Description : Encode a buffer into base64 format.
  1150. *
  1151. * Parameters :
  1152. * 1 : dst = Destination buffer
  1153. * 2 : dlen = Destination buffer length
  1154. * 3 : olen = Number of bytes written
  1155. * 4 : src = Source buffer
  1156. * 5 : slen = Amount of data to be encoded
  1157. *
  1158. * Returns : 0 on success, error code othervise
  1159. *
  1160. *********************************************************************/
  1161. extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
  1162. const unsigned char *src, size_t slen)
  1163. {
  1164. *olen = 4 * ((slen/3) + ((slen%3) ? 1 : 0)) + 1;
  1165. if (*olen < dlen)
  1166. {
  1167. return ENOBUFS;
  1168. }
  1169. *olen = (size_t)EVP_EncodeBlock(dst, src, (int)slen) + 1;
  1170. return 0;
  1171. }
  1172. /*********************************************************************
  1173. *
  1174. * Function : close_file_stream
  1175. *
  1176. * Description : Close file stream, report error on close error
  1177. *
  1178. * Parameters :
  1179. * 1 : f = file stream to close
  1180. * 2 : path = path for error report
  1181. *
  1182. * Returns : N/A
  1183. *
  1184. *********************************************************************/
  1185. static void close_file_stream(FILE *f, const char *path)
  1186. {
  1187. if (fclose(f) != 0)
  1188. {
  1189. log_error(LOG_LEVEL_ERROR,
  1190. "Error closing file %s: %s", path, strerror(errno));
  1191. }
  1192. }
  1193. /*********************************************************************
  1194. *
  1195. * Function : write_certificate
  1196. *
  1197. * Description : Writes certificate into file.
  1198. *
  1199. * Parameters :
  1200. * 1 : crt = certificate to write into file
  1201. * 2 : output_file = path to save certificate file
  1202. *
  1203. * on error
  1204. * Returns : 1 on success success or negative value
  1205. *
  1206. *********************************************************************/
  1207. static int write_certificate(X509 *crt, const char *output_file)
  1208. {
  1209. FILE *f = NULL;
  1210. int ret = -1;
  1211. /*
  1212. * Saving certificate into file
  1213. */
  1214. if ((f = fopen(output_file, "w")) == NULL)
  1215. {
  1216. log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
  1217. output_file);
  1218. return ret;
  1219. }
  1220. ret = PEM_write_X509(f, crt);
  1221. if (!ret)
  1222. {
  1223. log_ssl_errors(LOG_LEVEL_ERROR,
  1224. "Writing certificate into file %s failed", output_file);
  1225. ret = -1;
  1226. }
  1227. close_file_stream(f, output_file);
  1228. return ret;
  1229. }
  1230. /*********************************************************************
  1231. *
  1232. * Function : write_private_key
  1233. *
  1234. * Description : Writes private key into file and copies saved
  1235. * content into given pointer to string. If function
  1236. * returns 0 for success, this copy must be freed by
  1237. * caller.
  1238. *
  1239. * Parameters :
  1240. * 1 : key = key to write into file
  1241. * 2 : ret_buf = pointer to string with created key file content
  1242. * 3 : key_file_path = path where to save key file
  1243. *
  1244. * Returns : Length of written private key on success or negative value
  1245. * on error
  1246. *
  1247. *********************************************************************/
  1248. static int write_private_key(EVP_PKEY *key, char **ret_buf,
  1249. const char *key_file_path)
  1250. {
  1251. size_t len = 0; /* Length of created key */
  1252. FILE *f = NULL; /* File to save certificate */
  1253. int ret = 0;
  1254. BIO *bio_mem = BIO_new(BIO_s_mem());
  1255. char *bio_mem_data = 0;
  1256. if (bio_mem == NULL)
  1257. {
  1258. log_ssl_errors(LOG_LEVEL_ERROR, "write_private_key memory allocation failure");
  1259. return -1;
  1260. }
  1261. /*
  1262. * Writing private key into PEM string
  1263. */
  1264. if (!PEM_write_bio_PrivateKey(bio_mem, key, NULL, NULL, 0, NULL, NULL))
  1265. {
  1266. log_ssl_errors(LOG_LEVEL_ERROR,
  1267. "Writing private key into PEM string failed");
  1268. ret = -1;
  1269. goto exit;
  1270. }
  1271. len = (size_t)BIO_get_mem_data(bio_mem, &bio_mem_data);
  1272. /* Initializing buffer for key file content */
  1273. *ret_buf = zalloc_or_die(len + 1);
  1274. (*ret_buf)[len] = 0;
  1275. strncpy(*ret_buf, bio_mem_data, len);
  1276. /*
  1277. * Saving key into file
  1278. */
  1279. if ((f = fopen(key_file_path, "wb")) == NULL)
  1280. {
  1281. log_error(LOG_LEVEL_ERROR,
  1282. "Opening file %s to save private key failed: %E",
  1283. key_file_path);
  1284. ret = -1;
  1285. goto exit;
  1286. }
  1287. if (fwrite(*ret_buf, 1, len, f) != len)
  1288. {
  1289. log_error(LOG_LEVEL_ERROR,
  1290. "Writing private key into file %s failed",
  1291. key_file_path);
  1292. close_file_stream(f, key_file_path);
  1293. ret = -1;
  1294. goto exit;
  1295. }
  1296. close_file_stream(f, key_file_path);
  1297. exit:
  1298. BIO_free(bio_mem);
  1299. if (ret < 0)
  1300. {
  1301. freez(*ret_buf);
  1302. *ret_buf = NULL;
  1303. return ret;
  1304. }
  1305. return (int)len;
  1306. }
  1307. /*********************************************************************
  1308. *
  1309. * Function : generate_key
  1310. *
  1311. * Description : Tests if private key for host saved in csp already
  1312. * exists. If this file doesn't exists, a new key is
  1313. * generated and saved in a file. The generated key is also
  1314. * copied into given parameter key_buf, which must be then
  1315. * freed by caller. If file with key exists, key_buf
  1316. * contain NULL and no private key is generated.
  1317. *
  1318. * Parameters :
  1319. * 1 : csp = Current client state (buffers, headers, etc...)
  1320. * 2 : key_buf = buffer to save new generated key
  1321. *
  1322. * Returns : -1 => Error while generating private key
  1323. * 0 => Key already exists
  1324. * >0 => Length of generated private key
  1325. *
  1326. *********************************************************************/
  1327. static int generate_key(struct client_state *csp, char **key_buf)
  1328. {
  1329. int ret = 0;
  1330. char* key_file_path = NULL;
  1331. BIGNUM *exp = BN_new();
  1332. RSA *rsa = RSA_new();
  1333. EVP_PKEY *key = EVP_PKEY_new();
  1334. if (exp == NULL || rsa == NULL || key == NULL)
  1335. {
  1336. log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
  1337. ret = -1;
  1338. goto exit;
  1339. }
  1340. if (BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT) != 1)
  1341. {
  1342. log_ssl_errors(LOG_LEVEL_ERROR, "Setting RSA key exponent failed");
  1343. ret = -1;
  1344. goto exit;
  1345. }
  1346. key_file_path = make_certs_path(csp->config->certificate_directory,
  1347. (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
  1348. if (key_file_path == NULL)
  1349. {
  1350. ret = -1;
  1351. goto exit;
  1352. }
  1353. /*
  1354. * Test if key already exists. If so, we don't have to create it again.
  1355. */
  1356. if (file_exists(key_file_path) == 1)
  1357. {
  1358. ret = 0;
  1359. goto exit;
  1360. }
  1361. ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
  1362. if (ret == 0)
  1363. {
  1364. log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
  1365. ret = -1;
  1366. goto exit;
  1367. }
  1368. if (!EVP_PKEY_set1_RSA(key, rsa))
  1369. {
  1370. log_ssl_errors(LOG_LEVEL_ERROR,
  1371. "Error assigning RSA key pair to PKEY structure");
  1372. ret = -1;
  1373. goto exit;
  1374. }
  1375. /*
  1376. * Exporting private key into file
  1377. */
  1378. if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
  1379. {
  1380. log_error(LOG_LEVEL_ERROR,
  1381. "Writing private key into file %s failed", key_file_path);
  1382. ret = -1;
  1383. goto exit;
  1384. }
  1385. exit:
  1386. /*
  1387. * Freeing used variables
  1388. */
  1389. if (exp)
  1390. {
  1391. BN_free(exp);
  1392. }
  1393. if (rsa)
  1394. {
  1395. RSA_free(rsa);
  1396. }
  1397. if (key)
  1398. {
  1399. EVP_PKEY_free(key);
  1400. }
  1401. freez(key_file_path);
  1402. return ret;
  1403. }
  1404. /*********************************************************************
  1405. *
  1406. * Function : ssl_certificate_load
  1407. *
  1408. * Description : Loads certificate from file.
  1409. *
  1410. * Parameters :
  1411. * 1 : cert_path = The certificate path to load
  1412. *
  1413. * Returns : NULL => error loading certificate,
  1414. * pointer to certificate instance otherwise
  1415. *
  1416. *********************************************************************/
  1417. static X509* ssl_certificate_load(const char *cert_path)
  1418. {
  1419. X509 *cert = NULL;
  1420. FILE *cert_f = NULL;
  1421. if (!(cert_f = fopen(cert_path, "r")))
  1422. {
  1423. log_error(LOG_LEVEL_ERROR,
  1424. "Error opening certificate file %s: %s", cert_path, strerror(errno));
  1425. return NULL;
  1426. }
  1427. if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
  1428. {
  1429. log_ssl_errors(LOG_LEVEL_ERROR,
  1430. "Error reading certificate file %s", cert_path);
  1431. }
  1432. close_file_stream(cert_f, cert_path);
  1433. return cert;
  1434. }
  1435. /*********************************************************************
  1436. *
  1437. * Function : ssl_certificate_is_invalid
  1438. *
  1439. * Description : Checks whether or not a certificate is valid.
  1440. * Currently only checks that the certificate can be
  1441. * parsed and that the "valid to" date is in the future.
  1442. *
  1443. * Parameters :
  1444. * 1 : cert_file = The certificate to check
  1445. *
  1446. * Returns : 0 => The certificate is valid.
  1447. * 1 => The certificate is invalid
  1448. *
  1449. *********************************************************************/
  1450. static int ssl_certificate_is_invalid(const char *cert_file)
  1451. {
  1452. int ret;
  1453. X509 *cert = NULL;
  1454. if (!(cert = ssl_certificate_load(cert_file)))
  1455. {
  1456. log_ssl_errors(LOG_LEVEL_ERROR,
  1457. "Error reading certificate file %s", cert_file);
  1458. return 1;
  1459. }
  1460. ret = X509_cmp_current_time(X509_get_notAfter(cert));
  1461. if (ret == 0)
  1462. {
  1463. log_ssl_errors(LOG_LEVEL_ERROR,
  1464. "Error checking certificate %s validity", cert_file);
  1465. ret = -1;
  1466. }
  1467. X509_free(cert);
  1468. return ret == -1 ? 1 : 0;
  1469. }
  1470. /*********************************************************************
  1471. *
  1472. * Function : set_x509_ext
  1473. *
  1474. * Description : Sets the X509V3 extension data
  1475. *
  1476. * Parameters :
  1477. * 1 : cert = The certificate to modify
  1478. * 2 : issuer = Issuer certificate
  1479. * 3 : nid = OpenSSL NID
  1480. * 4 : value = extension value
  1481. *
  1482. * Returns : 0 => Error while setting extensuon data
  1483. * 1 => It worked
  1484. *
  1485. *********************************************************************/
  1486. static int set_x509_ext(X509 *cert, X509 *issuer, int nid, char *value)
  1487. {
  1488. X509_EXTENSION *ext = NULL;
  1489. X509V3_CTX ctx;
  1490. int ret = 0;
  1491. X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
  1492. ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
  1493. if (!ext)
  1494. {
  1495. log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
  1496. goto exit;
  1497. }
  1498. if (!X509_add_ext(cert, ext, -1))
  1499. {
  1500. log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
  1501. goto exit;
  1502. }
  1503. ret = 1;
  1504. exit:
  1505. if (ext)
  1506. {
  1507. X509_EXTENSION_free(ext);
  1508. }
  1509. return ret;
  1510. }
  1511. /*********************************************************************
  1512. *
  1513. * Function : set_subject_alternative_name
  1514. *
  1515. * Description : Sets the Subject Alternative Name extension to a cert
  1516. *
  1517. * Parameters :
  1518. * 1 : cert = The certificate to modify
  1519. * 2 : issuer = Issuer certificate
  1520. * 3 : hostname = The hostname to add
  1521. *
  1522. * Returns : 0 => Error while creating certificate.
  1523. * 1 => It worked
  1524. *
  1525. *********************************************************************/
  1526. static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
  1527. {
  1528. size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
  1529. char alt_name_buf[altname_len];
  1530. snprintf(alt_name_buf, sizeof(alt_name_buf),
  1531. CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
  1532. return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
  1533. }
  1534. /*********************************************************************
  1535. *
  1536. * Function : generate_webpage_certificate
  1537. *
  1538. * Description : Creates certificate file in presetted directory.
  1539. * If certificate already exists, no other certificate
  1540. * will be created. Subject of certificate is named
  1541. * by csp->http->host from parameter. This function also
  1542. * triggers generating of private key for new certificate.
  1543. *
  1544. * Parameters :
  1545. * 1 : csp = Current client state (buffers, headers, etc...)
  1546. *
  1547. * Returns : -1 => Error while creating certificate.
  1548. * 0 => Certificate already exists.
  1549. * 1 => Certificate created
  1550. *
  1551. *********************************************************************/
  1552. static int generate_webpage_certificate(struct client_state *csp)
  1553. {
  1554. char *key_buf = NULL; /* Buffer for created key */
  1555. X509 *issuer_cert = NULL;
  1556. X509 *cert = NULL;
  1557. BIO *pk_bio = NULL;
  1558. EVP_PKEY *loaded_subject_key = NULL;
  1559. EVP_PKEY *loaded_issuer_key = NULL;
  1560. X509_NAME *issuer_name;
  1561. X509_NAME *subject_name = NULL;
  1562. ASN1_TIME *asn_time = NULL;
  1563. ASN1_INTEGER *serial = NULL;
  1564. BIGNUM *serial_num = NULL;
  1565. int ret = 0;
  1566. cert_options cert_opt;
  1567. char cert_valid_from[VALID_DATETIME_BUFLEN];
  1568. char cert_valid_to[VALID_DATETIME_BUFLEN];
  1569. /* Paths to keys and certificates needed to create certificate */
  1570. cert_opt.issuer_key = NULL;
  1571. cert_opt.subject_key = NULL;
  1572. cert_opt.issuer_crt = NULL;
  1573. cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
  1574. (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
  1575. if (cert_opt.output_file == NULL)
  1576. {
  1577. return -1;
  1578. }
  1579. cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
  1580. (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
  1581. if (cert_opt.subject_key == NULL)
  1582. {
  1583. freez(cert_opt.output_file);
  1584. return -1;
  1585. }
  1586. if (file_exists(cert_opt.output_file) == 1)
  1587. {
  1588. /* The file exists, but is it valid? */
  1589. if (ssl_certificate_is_invalid(cert_opt.output_file))
  1590. {
  1591. log_error(LOG_LEVEL_CONNECT,
  1592. "Certificate %s is no longer valid. Removing it.",
  1593. cert_opt.output_file);
  1594. if (unlink(cert_opt.output_file))
  1595. {
  1596. log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
  1597. cert_opt.output_file);
  1598. freez(cert_opt.output_file);
  1599. freez(cert_opt.subject_key);
  1600. return -1;
  1601. }
  1602. if (unlink(cert_opt.subject_key))
  1603. {
  1604. log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
  1605. cert_opt.subject_key);
  1606. freez(cert_opt.output_file);
  1607. freez(cert_opt.subject_key);
  1608. return -1;
  1609. }
  1610. }
  1611. else
  1612. {
  1613. freez(cert_opt.output_file);
  1614. freez(cert_opt.subject_key);
  1615. return 0;
  1616. }
  1617. }
  1618. /*
  1619. * Create key for requested host
  1620. */
  1621. int subject_key_len = generate_key(csp, &key_buf);
  1622. if (subject_key_len < 0)
  1623. {
  1624. freez(cert_opt.output_file);
  1625. freez(cert_opt.subject_key);
  1626. log_error(LOG_LEVEL_ERROR, "Key generating failed");
  1627. return -1;
  1628. }
  1629. /*
  1630. * Converting unsigned long serial number to char * serial number.
  1631. * We must compute length of serial number in string + terminating null.
  1632. */
  1633. unsigned long certificate_serial = get_certificate_serial(csp);
  1634. unsigned long certificate_serial_time = (unsigned long)time(NULL);
  1635. int serial_num_size = snprintf(NULL, 0, "%lu%lu",
  1636. certificate_serial_time, certificate_serial) + 1;
  1637. if (serial_num_size <= 0)
  1638. {
  1639. serial_num_size = 1;
  1640. }
  1641. char serial_num_text[serial_num_size]; /* Buffer for serial number */
  1642. ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
  1643. certificate_serial_time, certificate_serial);
  1644. if (ret < 0 || ret >= serial_num_size)
  1645. {
  1646. log_error(LOG_LEVEL_ERROR,
  1647. "Converting certificate serial number into string failed");
  1648. ret = -1;
  1649. goto exit;
  1650. }
  1651. /*
  1652. * Preparing parameters for certificate
  1653. */
  1654. subject_name = X509_NAME_new();
  1655. if (!subject_name)
  1656. {
  1657. log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
  1658. ret = -1;
  1659. goto exit;
  1660. }
  1661. if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
  1662. MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
  1663. {
  1664. log_ssl_errors(LOG_LEVEL_ERROR,
  1665. "X509 subject name (code: %s, val: %s) error",
  1666. CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
  1667. ret = -1;
  1668. goto exit;
  1669. }
  1670. if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
  1671. MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
  1672. {
  1673. log_ssl_errors(LOG_LEVEL_ERROR,
  1674. "X509 subject name (code: %s, val: %s) error",
  1675. CERT_PARAM_ORGANIZATION_FCODE, csp->http->host);
  1676. ret = -1;
  1677. goto exit;
  1678. }
  1679. if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE,
  1680. MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
  1681. {
  1682. log_ssl_errors(LOG_LEVEL_ERROR,
  1683. "X509 subject name (code: %s, val: %s) error",
  1684. CERT_PARAM_ORG_UNIT_FCODE, csp->http->host);
  1685. ret = -1;
  1686. goto exit;
  1687. }
  1688. if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE,
  1689. MBSTRING_ASC, (void *)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
  1690. {
  1691. log_ssl_errors(LOG_LEVEL_ERROR,
  1692. "X509 subject name (code: %s, val: %s) error",
  1693. CERT_PARAM_COUNTRY_FCODE, csp->http->host);
  1694. ret = -1;
  1695. goto exit;
  1696. }
  1697. cert_opt.issuer_crt = csp->config->ca_cert_file;
  1698. cert_opt.issuer_key = csp->config->ca_key_file;
  1699. if (get_certificate_valid_from_date(cert_valid_from,
  1700. sizeof(cert_valid_from), VALID_DATETIME_FMT)
  1701. || get_certificate_valid_to_date(cert_valid_to,
  1702. sizeof(cert_valid_to), VALID_DATETIME_FMT))
  1703. {
  1704. log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
  1705. ret = -1;
  1706. goto exit;
  1707. }
  1708. cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
  1709. cert_opt.issuer_pwd = csp->config->ca_password;
  1710. cert_opt.not_before = cert_valid_from;
  1711. cert_opt.not_after = cert_valid_to;
  1712. cert_opt.serial = serial_num_text;
  1713. cert_opt.max_pathlen = -1;
  1714. /*
  1715. * Test if the private key was already created.
  1716. * XXX: Can this still happen?
  1717. */
  1718. if (subject_key_len == 0)
  1719. {
  1720. log_error(LOG_LEVEL_ERROR, "Subject key was already created");
  1721. ret = 0;
  1722. goto exit;
  1723. }
  1724. /*
  1725. * Parse serial to MPI
  1726. */
  1727. serial_num = BN_new();
  1728. if (!serial_num)
  1729. {
  1730. log_error(LOG_LEVEL_ERROR, "generate_webpage_certificate: memory error");
  1731. ret = -1;
  1732. goto exit;
  1733. }
  1734. if (!BN_dec2bn(&serial_num, cert_opt.serial))
  1735. {
  1736. log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
  1737. ret = -1;
  1738. goto exit;
  1739. }
  1740. if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
  1741. {
  1742. log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
  1743. ret = -1;
  1744. goto exit;
  1745. }
  1746. /*
  1747. * Loading certificates
  1748. */
  1749. if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
  1750. {
  1751. log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed",
  1752. cert_opt.issuer_crt);
  1753. ret = -1;
  1754. goto exit;
  1755. }
  1756. issuer_name = X509_get_issuer_name(issuer_cert);
  1757. /*
  1758. * Loading keys from file or from buffer
  1759. */
  1760. if (key_buf != NULL && subject_key_len > 0)
  1761. {
  1762. pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
  1763. }
  1764. else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
  1765. {
  1766. log_ssl_errors(LOG_LEVEL_ERROR,
  1767. "Failure opening subject key %s BIO", cert_opt.subject_key);
  1768. ret = -1;
  1769. goto exit;
  1770. }
  1771. loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
  1772. (void *)cert_opt.subject_pwd);
  1773. if (!loaded_subject_key)
  1774. {
  1775. log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed",
  1776. cert_opt.subject_key);
  1777. ret = -1;
  1778. goto exit;
  1779. }
  1780. if (!BIO_free(pk_bio))
  1781. {
  1782. log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
  1783. }
  1784. if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
  1785. {
  1786. log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO",
  1787. cert_opt.issuer_key);
  1788. ret = -1;
  1789. goto exit;
  1790. }
  1791. loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
  1792. (void *)cert_opt.issuer_pwd);
  1793. if (!loaded_issuer_key)
  1794. {
  1795. log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed",
  1796. cert_opt.subject_key);
  1797. ret = -1;
  1798. goto exit;
  1799. }
  1800. cert = X509_new();
  1801. if (!cert)
  1802. {
  1803. log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
  1804. ret = -1;
  1805. goto exit;
  1806. }
  1807. if (!X509_set_version(cert, CERTIFICATE_VERSION))
  1808. {
  1809. log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
  1810. ret = -1;
  1811. goto exit;
  1812. }
  1813. /*
  1814. * Setting parameters of signed certificate
  1815. */
  1816. if (!X509_set_pubkey(cert, loaded_subject_key))
  1817. {
  1818. log_ssl_errors(LOG_LEVEL_ERROR,
  1819. "Setting public key in signed certificate failed");
  1820. ret = -1;
  1821. goto exit;
  1822. }
  1823. if (!X509_set_subject_name(cert, subject_name))
  1824. {
  1825. log_ssl_errors(LOG_LEVEL_ERROR,
  1826. "Setting subject name in signed certificate failed");
  1827. ret = -1;
  1828. goto exit;
  1829. }
  1830. if (!X509_set_issuer_name(cert, issuer_name))
  1831. {
  1832. log_ssl_errors(LOG_LEVEL_ERROR,
  1833. "Setting issuer name in signed certificate failed");
  1834. ret = -1;
  1835. goto exit;
  1836. }
  1837. if (!X509_set_serialNumber(cert, serial))
  1838. {
  1839. log_ssl_errors(LOG_LEVEL_ERROR,
  1840. "Setting serial number in signed certificate failed");
  1841. ret = -1;
  1842. goto exit;
  1843. }
  1844. asn_time = ASN1_TIME_new();
  1845. if (!asn_time)
  1846. {
  1847. log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
  1848. ret = -1;
  1849. goto exit;
  1850. }
  1851. if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after))
  1852. {
  1853. log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
  1854. ret = -1;
  1855. goto exit;
  1856. }
  1857. if (!X509_set1_notAfter(cert, asn_time))
  1858. {
  1859. log_ssl_errors(LOG_LEVEL_ERROR,
  1860. "Setting valid not after in signed certificate failed");
  1861. ret = -1;
  1862. goto exit;
  1863. }
  1864. if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before))
  1865. {
  1866. log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
  1867. ret = -1;
  1868. goto exit;
  1869. }
  1870. if (!X509_set1_notBefore(cert, asn_time))
  1871. {
  1872. log_ssl_errors(LOG_LEVEL_ERROR,
  1873. "Setting valid not before in signed certificate failed");
  1874. ret = -1;
  1875. goto exit;
  1876. }
  1877. if (!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
  1878. {
  1879. log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
  1880. "in signed certificate failed");
  1881. ret = -1;
  1882. goto exit;
  1883. }
  1884. if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
  1885. {
  1886. log_ssl_errors(LOG_LEVEL_ERROR,
  1887. "Setting the Subject Key Identifier extension failed");
  1888. ret = -1;
  1889. goto exit;
  1890. }
  1891. if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
  1892. {
  1893. log_ssl_errors(LOG_LEVEL_ERROR,
  1894. "Setting the Authority Key Identifier extension failed");
  1895. ret = -1;
  1896. goto exit;
  1897. }
  1898. if (!host_is_ip_address(csp->http->host) &&
  1899. !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
  1900. {
  1901. log_ssl_errors(LOG_LEVEL_ERROR,
  1902. "Setting the Subject Alt Name extension failed");
  1903. ret = -1;
  1904. goto exit;
  1905. }
  1906. if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
  1907. {
  1908. log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
  1909. ret = -1;
  1910. goto exit;
  1911. }
  1912. /*
  1913. * Writing certificate into file
  1914. */
  1915. if (write_certificate(cert, cert_opt.output_file) < 0)
  1916. {
  1917. log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
  1918. ret = -1;
  1919. goto exit;
  1920. }
  1921. ret = 1;
  1922. exit:
  1923. /*
  1924. * Freeing used structures
  1925. */
  1926. if (issuer_cert)
  1927. {
  1928. X509_free(issuer_cert);
  1929. }
  1930. if (cert)
  1931. {
  1932. X509_free(cert);
  1933. }
  1934. if (pk_bio && !BIO_free(pk_bio))
  1935. {
  1936. log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
  1937. }
  1938. if (loaded_subject_key)
  1939. {
  1940. EVP_PKEY_free(loaded_subject_key);
  1941. }
  1942. if (loaded_issuer_key)
  1943. {
  1944. EVP_PKEY_free(loaded_issuer_key);
  1945. }
  1946. if (subject_name)
  1947. {
  1948. X509_NAME_free(subject_name);
  1949. }
  1950. if (asn_time)
  1951. {
  1952. ASN1_TIME_free(asn_time);
  1953. }
  1954. if (serial_num)
  1955. {
  1956. BN_free(serial_num);
  1957. }
  1958. if (serial)
  1959. {
  1960. ASN1_INTEGER_free(serial);
  1961. }
  1962. freez(cert_opt.subject_key);
  1963. freez(cert_opt.output_file);
  1964. freez(key_buf);
  1965. return ret;
  1966. }
  1967. /*********************************************************************
  1968. *
  1969. * Function : ssl_crt_verify_info
  1970. *
  1971. * Description : Returns an informational string about the verification
  1972. * status of a certificate.
  1973. *
  1974. * Parameters :
  1975. * 1 : buf = Buffer to write to
  1976. * 2 : size = Maximum size of buffer
  1977. * 3 : csp = client state
  1978. *
  1979. * Returns : N/A
  1980. *
  1981. *********************************************************************/
  1982. extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
  1983. {
  1984. strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
  1985. buf[size - 1] = 0;
  1986. }
  1987. /*********************************************************************
  1988. *
  1989. * Function : ssl_release
  1990. *
  1991. * Description : Release all SSL resources
  1992. *
  1993. * Parameters :
  1994. *
  1995. * Returns : N/A
  1996. *
  1997. *********************************************************************/
  1998. extern void ssl_release(void)
  1999. {
  2000. if (ssl_inited == 1)
  2001. {
  2002. #ifndef OPENSSL_NO_COMP
  2003. SSL_COMP_free_compression_methods();
  2004. #endif
  2005. CONF_modules_free();
  2006. CONF_modules_unload(1);
  2007. #ifndef OPENSSL_NO_COMP
  2008. COMP_zlib_cleanup();
  2009. #endif
  2010. ERR_free_strings();
  2011. EVP_cleanup();
  2012. CRYPTO_cleanup_all_ex_data();
  2013. }
  2014. }