ssl.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  1. /*********************************************************************
  2. *
  3. * File : $Source: /cvsroot/ijbswa/current/ssl.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) 2017-2020 Vaclav Svec. FIT CVUT.
  9. * Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
  10. *
  11. * This program is free software; you can redistribute it
  12. * and/or modify it under the terms of the GNU General
  13. * Public License as published by the Free Software
  14. * Foundation; either version 2 of the License, or (at
  15. * your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will
  18. * be useful, but WITHOUT ANY WARRANTY; without even the
  19. * implied warranty of MERCHANTABILITY or FITNESS FOR A
  20. * PARTICULAR PURPOSE. See the GNU General Public
  21. * License for more details.
  22. *
  23. * The GNU General Public License should be included with
  24. * this file. If not, you can view it at
  25. * http://www.gnu.org/copyleft/gpl.html
  26. * or write to the Free Software Foundation, Inc., 59
  27. * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  28. *
  29. *********************************************************************/
  30. #include <string.h>
  31. #include <unistd.h>
  32. #if !defined(MBEDTLS_CONFIG_FILE)
  33. # include "mbedtls/config.h"
  34. #else
  35. # include MBEDTLS_CONFIG_FILE
  36. #endif
  37. #include "mbedtls/md5.h"
  38. #include "mbedtls/pem.h"
  39. #include "mbedtls/base64.h"
  40. #include "mbedtls/error.h"
  41. #include "mbedtls/oid.h"
  42. #include "mbedtls/asn1write.h"
  43. #include "config.h"
  44. #include "project.h"
  45. #include "miscutil.h"
  46. #include "errlog.h"
  47. #include "jcc.h"
  48. #include "ssl.h"
  49. #include "ssl_common.h"
  50. #include "encode.h"
  51. /*
  52. * Macros for searching begin and end of certificates.
  53. * Necessary to convert structure mbedtls_x509_crt to crt file.
  54. */
  55. #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
  56. #define PEM_END_CRT "-----END CERTIFICATE-----\n"
  57. #define VALID_DATETIME_FMT "%Y%m%d%H%M%S"
  58. #define VALID_DATETIME_BUFLEN 15
  59. /*
  60. * Macros for ssl.c
  61. */
  62. #define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
  63. #define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
  64. #define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
  65. #define CERT_PARAM_COMMON_NAME CERT_PARAM_COMMON_NAME_FCODE"="
  66. #define CERT_PARAM_ORGANIZATION ","CERT_PARAM_ORGANIZATION_FCODE"="
  67. #define CERT_PARAM_ORG_UNIT ","CERT_PARAM_ORG_UNIT_FCODE"="
  68. #define CERT_PARAM_COUNTRY ","CERT_PARAM_COUNTRY_FCODE"="CERT_PARAM_COUNTRY_CODE
  69. /*
  70. * Properties of key for generating
  71. */
  72. typedef struct {
  73. mbedtls_pk_type_t type; /* type of key to generate */
  74. int rsa_keysize; /* length of key in bits */
  75. char *key_file_path; /* filename of the key file */
  76. } key_options;
  77. /* Variables for one common RNG for all SSL use */
  78. static mbedtls_ctr_drbg_context ctr_drbg;
  79. static mbedtls_entropy_context entropy;
  80. static int rng_seeded;
  81. static int generate_webpage_certificate(struct client_state *csp);
  82. static int host_to_hash(struct client_state *csp);
  83. static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
  84. static void free_client_ssl_structures(struct client_state *csp);
  85. static void free_server_ssl_structures(struct client_state *csp);
  86. static int seed_rng(struct client_state *csp);
  87. static int *get_ciphersuites_from_string(const char *ciphersuites_string);
  88. /*********************************************************************
  89. *
  90. * Function : is_ssl_pending
  91. *
  92. * Description : Tests if there are some waiting data on ssl connection.
  93. * Only considers data that has actually been received
  94. * locally and ignores data that is still on the fly
  95. * or has not yet been sent by the remote end.
  96. *
  97. * Parameters :
  98. * 1 : ssl_attr = SSL context to test
  99. *
  100. * Returns : 0 => No data are pending
  101. * >0 => Pending data length
  102. *
  103. *********************************************************************/
  104. extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
  105. {
  106. mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
  107. if (ssl == NULL)
  108. {
  109. return 0;
  110. }
  111. return mbedtls_ssl_get_bytes_avail(ssl);
  112. }
  113. /*********************************************************************
  114. *
  115. * Function : ssl_send_data
  116. *
  117. * Description : Sends the content of buf (for n bytes) to given SSL
  118. * connection context.
  119. *
  120. * Parameters :
  121. * 1 : ssl_attr = SSL context to send data to
  122. * 2 : buf = Pointer to data to be sent
  123. * 3 : len = Length of data to be sent to the SSL context
  124. *
  125. * Returns : Length of sent data or negative value on error.
  126. *
  127. *********************************************************************/
  128. extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
  129. {
  130. mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
  131. int ret = 0;
  132. size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
  133. int send_len = 0; /* length of one data part to send */
  134. int pos = 0; /* Position of unsent part in buffer */
  135. if (len == 0)
  136. {
  137. return 0;
  138. }
  139. /* Getting maximal length of data sent in one fragment */
  140. max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
  141. /*
  142. * Whole buffer must be sent in many fragments, because each fragment
  143. * has its maximal length.
  144. */
  145. while (pos < len)
  146. {
  147. /* Compute length of data, that can be send in next fragment */
  148. if ((pos + (int)max_fragment_size) > len)
  149. {
  150. send_len = (int)len - pos;
  151. }
  152. else
  153. {
  154. send_len = (int)max_fragment_size;
  155. }
  156. log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
  157. ssl_attr->mbedtls_attr.socket_fd.fd, send_len, buf+pos);
  158. /*
  159. * Sending one part of the buffer
  160. */
  161. while ((ret = mbedtls_ssl_write(ssl,
  162. (const unsigned char *)(buf + pos),
  163. (size_t)send_len)) < 0)
  164. {
  165. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  166. ret != MBEDTLS_ERR_SSL_WANT_WRITE)
  167. {
  168. char err_buf[ERROR_BUF_SIZE];
  169. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  170. log_error(LOG_LEVEL_ERROR,
  171. "Sending data on socket %d over TLS/SSL failed: %s",
  172. ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
  173. return -1;
  174. }
  175. }
  176. /* Adding count of sent bytes to position in buffer */
  177. pos = pos + send_len;
  178. }
  179. return (int)len;
  180. }
  181. /*********************************************************************
  182. *
  183. * Function : ssl_recv_data
  184. *
  185. * Description : Receives data from given SSL context and puts
  186. * it into buffer.
  187. *
  188. * Parameters :
  189. * 1 : ssl_attr = SSL context to receive data from
  190. * 2 : buf = Pointer to buffer where data will be written
  191. * 3 : max_length = Maximum number of bytes to read
  192. *
  193. * Returns : Number of bytes read, 0 for EOF, or -1
  194. * on error.
  195. *
  196. *********************************************************************/
  197. extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
  198. {
  199. mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
  200. int ret = 0;
  201. memset(buf, 0, max_length);
  202. /*
  203. * Receiving data from SSL context into buffer
  204. */
  205. do
  206. {
  207. ret = mbedtls_ssl_read(ssl, buf, max_length);
  208. } while (ret == MBEDTLS_ERR_SSL_WANT_READ
  209. || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
  210. if (ret < 0)
  211. {
  212. char err_buf[ERROR_BUF_SIZE];
  213. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
  214. {
  215. log_error(LOG_LEVEL_CONNECT, "The peer notified us that "
  216. "the connection on socket %d is going to be closed",
  217. ssl_attr->mbedtls_attr.socket_fd.fd);
  218. return 0;
  219. }
  220. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  221. log_error(LOG_LEVEL_ERROR,
  222. "Receiving data on socket %d over TLS/SSL failed: %s",
  223. ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
  224. return -1;
  225. }
  226. log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
  227. ssl_attr->mbedtls_attr.socket_fd.fd, ret, buf);
  228. return ret;
  229. }
  230. /*********************************************************************
  231. *
  232. * Function : create_client_ssl_connection
  233. *
  234. * Description : Creates TLS/SSL secured connection with client
  235. *
  236. * Parameters :
  237. * 1 : csp = Current client state (buffers, headers, etc...)
  238. *
  239. * Returns : 0 on success, negative value if connection wasn't created
  240. * successfully.
  241. *
  242. *********************************************************************/
  243. extern int create_client_ssl_connection(struct client_state *csp)
  244. {
  245. struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
  246. /* Paths to certificates file and key file */
  247. char *key_file = NULL;
  248. char *ca_file = NULL;
  249. char *cert_file = NULL;
  250. int ret = 0;
  251. char err_buf[ERROR_BUF_SIZE];
  252. /*
  253. * Initializing mbedtls structures for TLS/SSL connection
  254. */
  255. mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
  256. mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
  257. mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
  258. mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
  259. mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
  260. #if defined(MBEDTLS_SSL_CACHE_C)
  261. mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
  262. #endif
  263. /*
  264. * Preparing hash of host for creating certificates
  265. */
  266. ret = host_to_hash(csp);
  267. if (ret != 0)
  268. {
  269. log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
  270. ret = -1;
  271. goto exit;
  272. }
  273. /*
  274. * Preparing paths to certificates files and key file
  275. */
  276. ca_file = csp->config->ca_cert_file;
  277. cert_file = make_certs_path(csp->config->certificate_directory,
  278. (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
  279. key_file = make_certs_path(csp->config->certificate_directory,
  280. (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
  281. if (cert_file == NULL || key_file == NULL)
  282. {
  283. ret = -1;
  284. goto exit;
  285. }
  286. /*
  287. * Generating certificate for requested host. Mutex to prevent
  288. * certificate and key inconsistence must be locked.
  289. */
  290. privoxy_mutex_lock(&certificate_mutex);
  291. ret = generate_webpage_certificate(csp);
  292. if (ret < 0)
  293. {
  294. log_error(LOG_LEVEL_ERROR,
  295. "Generate_webpage_certificate failed: %d", ret);
  296. privoxy_mutex_unlock(&certificate_mutex);
  297. ret = -1;
  298. goto exit;
  299. }
  300. privoxy_mutex_unlock(&certificate_mutex);
  301. /*
  302. * Seed the RNG
  303. */
  304. ret = seed_rng(csp);
  305. if (ret != 0)
  306. {
  307. ret = -1;
  308. goto exit;
  309. }
  310. /*
  311. * Loading CA file, webpage certificate and key files
  312. */
  313. ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
  314. cert_file);
  315. if (ret != 0)
  316. {
  317. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  318. log_error(LOG_LEVEL_ERROR,
  319. "Loading webpage certificate %s failed: %s", cert_file, err_buf);
  320. ret = -1;
  321. goto exit;
  322. }
  323. ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
  324. ca_file);
  325. if (ret != 0)
  326. {
  327. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  328. log_error(LOG_LEVEL_ERROR,
  329. "Loading CA certificate %s failed: %s", ca_file, err_buf);
  330. ret = -1;
  331. goto exit;
  332. }
  333. ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
  334. key_file, NULL);
  335. if (ret != 0)
  336. {
  337. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  338. log_error(LOG_LEVEL_ERROR,
  339. "Loading and parsing webpage certificate private key %s failed: %s",
  340. key_file, err_buf);
  341. ret = -1;
  342. goto exit;
  343. }
  344. /*
  345. * Setting SSL parameters
  346. */
  347. ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
  348. MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
  349. MBEDTLS_SSL_PRESET_DEFAULT);
  350. if (ret != 0)
  351. {
  352. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  353. log_error(LOG_LEVEL_ERROR,
  354. "mbedtls_ssl_config_defaults failed: %s", err_buf);
  355. ret = -1;
  356. goto exit;
  357. }
  358. mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
  359. mbedtls_ctr_drbg_random, &ctr_drbg);
  360. #if defined(MBEDTLS_SSL_CACHE_C)
  361. mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
  362. &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
  363. mbedtls_ssl_cache_set);
  364. #endif
  365. /*
  366. * Setting certificates
  367. */
  368. ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
  369. &(ssl_attr->mbedtls_attr.server_cert),
  370. &(ssl_attr->mbedtls_attr.prim_key));
  371. if (ret != 0)
  372. {
  373. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  374. log_error(LOG_LEVEL_ERROR,
  375. "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
  376. ret = -1;
  377. goto exit;
  378. }
  379. if (csp->config->cipher_list != NULL)
  380. {
  381. ssl_attr->mbedtls_attr.ciphersuites_list =
  382. get_ciphersuites_from_string(csp->config->cipher_list);
  383. if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
  384. {
  385. log_error(LOG_LEVEL_ERROR,
  386. "Setting the cipher list '%s' for the client connection failed",
  387. csp->config->cipher_list);
  388. ret = -1;
  389. goto exit;
  390. }
  391. mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
  392. ssl_attr->mbedtls_attr.ciphersuites_list);
  393. }
  394. ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
  395. &(ssl_attr->mbedtls_attr.conf));
  396. if (ret != 0)
  397. {
  398. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  399. log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
  400. ret = -1;
  401. goto exit;
  402. }
  403. mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
  404. &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
  405. mbedtls_net_recv, NULL);
  406. mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
  407. /*
  408. * Setting socket fd in mbedtls_net_context structure. This structure
  409. * can't be set by mbedtls functions, because we already have created
  410. * a TCP connection when this function is called.
  411. */
  412. ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
  413. /*
  414. * Handshake with client
  415. */
  416. log_error(LOG_LEVEL_CONNECT,
  417. "Performing the TLS/SSL handshake with client. Hash of host: %s",
  418. csp->http->hash_of_host_hex);
  419. while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
  420. {
  421. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  422. ret != MBEDTLS_ERR_SSL_WANT_WRITE)
  423. {
  424. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  425. log_error(LOG_LEVEL_ERROR,
  426. "medtls_ssl_handshake with client failed: %s", err_buf);
  427. ret = -1;
  428. goto exit;
  429. }
  430. }
  431. log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
  432. csp->ssl_with_client_is_opened = 1;
  433. exit:
  434. /*
  435. * Freeing allocated paths to files
  436. */
  437. freez(cert_file);
  438. freez(key_file);
  439. /* Freeing structures if connection wasn't created successfully */
  440. if (ret < 0)
  441. {
  442. free_client_ssl_structures(csp);
  443. }
  444. return ret;
  445. }
  446. /*********************************************************************
  447. *
  448. * Function : close_client_ssl_connection
  449. *
  450. * Description : Closes TLS/SSL connection with client. This function
  451. * checks if this connection is already created.
  452. *
  453. * Parameters :
  454. * 1 : csp = Current client state (buffers, headers, etc...)
  455. *
  456. * Returns : N/A
  457. *
  458. *********************************************************************/
  459. extern void close_client_ssl_connection(struct client_state *csp)
  460. {
  461. struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
  462. int ret = 0;
  463. if (csp->ssl_with_client_is_opened == 0)
  464. {
  465. return;
  466. }
  467. /*
  468. * Notifying the peer that the connection is being closed.
  469. */
  470. do {
  471. ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
  472. } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
  473. free_client_ssl_structures(csp);
  474. csp->ssl_with_client_is_opened = 0;
  475. }
  476. /*********************************************************************
  477. *
  478. * Function : free_client_ssl_structures
  479. *
  480. * Description : Frees structures used for SSL communication with
  481. * client.
  482. *
  483. * Parameters :
  484. * 1 : csp = Current client state (buffers, headers, etc...)
  485. *
  486. * Returns : N/A
  487. *
  488. *********************************************************************/
  489. static void free_client_ssl_structures(struct client_state *csp)
  490. {
  491. struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
  492. /*
  493. * We can't use function mbedtls_net_free, because this function
  494. * inter alia close TCP connection on set fd. Instead of this
  495. * function, we change fd to -1, which is the same what does
  496. * rest of mbedtls_net_free function.
  497. */
  498. ssl_attr->mbedtls_attr.socket_fd.fd = -1;
  499. /* Freeing mbedtls structures */
  500. mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
  501. mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
  502. mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
  503. freez(ssl_attr->mbedtls_attr.ciphersuites_list);
  504. mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
  505. #if defined(MBEDTLS_SSL_CACHE_C)
  506. mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
  507. #endif
  508. }
  509. /*********************************************************************
  510. *
  511. * Function : create_server_ssl_connection
  512. *
  513. * Description : Creates TLS/SSL secured connection with server.
  514. *
  515. * Parameters :
  516. * 1 : csp = Current client state (buffers, headers, etc...)
  517. *
  518. * Returns : 0 on success, negative value if connection wasn't created
  519. * successfully.
  520. *
  521. *********************************************************************/
  522. extern int create_server_ssl_connection(struct client_state *csp)
  523. {
  524. struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
  525. int ret = 0;
  526. char err_buf[ERROR_BUF_SIZE];
  527. char *trusted_cas_file = NULL;
  528. int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
  529. csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
  530. csp->server_certs_chain.next = NULL;
  531. /* Setting path to file with trusted CAs */
  532. trusted_cas_file = csp->config->trusted_cas_file;
  533. /*
  534. * Initializing mbedtls structures for TLS/SSL connection
  535. */
  536. mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
  537. mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
  538. mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
  539. mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
  540. /*
  541. * Setting socket fd in mbedtls_net_context structure. This structure
  542. * can't be set by mbedtls functions, because we already have created
  543. * TCP connection when calling this function.
  544. */
  545. ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
  546. /*
  547. * Seed the RNG
  548. */
  549. ret = seed_rng(csp);
  550. if (ret != 0)
  551. {
  552. ret = -1;
  553. goto exit;
  554. }
  555. /*
  556. * Loading file with trusted CAs
  557. */
  558. ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
  559. trusted_cas_file);
  560. if (ret < 0)
  561. {
  562. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  563. log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
  564. trusted_cas_file, err_buf);
  565. ret = -1;
  566. goto exit;
  567. }
  568. /*
  569. * Set TLS/SSL options
  570. */
  571. ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
  572. MBEDTLS_SSL_IS_CLIENT,
  573. MBEDTLS_SSL_TRANSPORT_STREAM,
  574. MBEDTLS_SSL_PRESET_DEFAULT);
  575. if (ret != 0)
  576. {
  577. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  578. log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
  579. err_buf);
  580. ret = -1;
  581. goto exit;
  582. }
  583. /*
  584. * Setting how strict should certificate verification be and other
  585. * parameters for certificate verification
  586. */
  587. if (csp->dont_verify_certificate)
  588. {
  589. auth_mode = MBEDTLS_SSL_VERIFY_NONE;
  590. }
  591. mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
  592. mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
  593. &(ssl_attr->mbedtls_attr.ca_cert), NULL);
  594. /* Setting callback function for certificates verification */
  595. mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
  596. ssl_verify_callback, (void *)csp);
  597. mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
  598. mbedtls_ctr_drbg_random, &ctr_drbg);
  599. if (csp->config->cipher_list != NULL)
  600. {
  601. ssl_attr->mbedtls_attr.ciphersuites_list =
  602. get_ciphersuites_from_string(csp->config->cipher_list);
  603. if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
  604. {
  605. log_error(LOG_LEVEL_ERROR,
  606. "Setting the cipher list '%s' for the server connection failed",
  607. csp->config->cipher_list);
  608. ret = -1;
  609. goto exit;
  610. }
  611. mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
  612. ssl_attr->mbedtls_attr.ciphersuites_list);
  613. }
  614. ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
  615. &(ssl_attr->mbedtls_attr.conf));
  616. if (ret != 0)
  617. {
  618. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  619. log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
  620. ret = -1;
  621. goto exit;
  622. }
  623. /*
  624. * Set the hostname to check against the received server certificate
  625. */
  626. ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
  627. csp->http->host);
  628. if (ret != 0)
  629. {
  630. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  631. log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
  632. err_buf);
  633. ret = -1;
  634. goto exit;
  635. }
  636. mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
  637. &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
  638. mbedtls_net_recv, NULL);
  639. /*
  640. * Handshake with server
  641. */
  642. log_error(LOG_LEVEL_CONNECT,
  643. "Performing the TLS/SSL handshake with the server");
  644. while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
  645. {
  646. if (ret != MBEDTLS_ERR_SSL_WANT_READ
  647. && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
  648. {
  649. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  650. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
  651. {
  652. char reason[INVALID_CERT_INFO_BUF_SIZE];
  653. csp->server_cert_verification_result =
  654. mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
  655. mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
  656. csp->server_cert_verification_result);
  657. /* Log the reason without the trailing new line */
  658. log_error(LOG_LEVEL_ERROR,
  659. "X509 certificate verification for %s failed: %N",
  660. csp->http->hostport, strlen(reason)-1, reason);
  661. ret = -1;
  662. }
  663. else
  664. {
  665. log_error(LOG_LEVEL_ERROR,
  666. "mbedtls_ssl_handshake with server failed: %s", err_buf);
  667. free_certificate_chain(csp);
  668. ret = -1;
  669. }
  670. goto exit;
  671. }
  672. }
  673. log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
  674. /*
  675. * Server certificate chain is valid, so we can clean
  676. * chain, because we will not send it to client.
  677. */
  678. free_certificate_chain(csp);
  679. csp->ssl_with_server_is_opened = 1;
  680. csp->server_cert_verification_result =
  681. mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
  682. exit:
  683. /* Freeing structures if connection wasn't created successfully */
  684. if (ret < 0)
  685. {
  686. free_server_ssl_structures(csp);
  687. }
  688. return ret;
  689. }
  690. /*********************************************************************
  691. *
  692. * Function : close_server_ssl_connection
  693. *
  694. * Description : Closes TLS/SSL connection with server. This function
  695. * checks if this connection is already opened.
  696. *
  697. * Parameters :
  698. * 1 : csp = Current client state (buffers, headers, etc...)
  699. *
  700. * Returns : N/A
  701. *
  702. *********************************************************************/
  703. extern void close_server_ssl_connection(struct client_state *csp)
  704. {
  705. struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
  706. int ret = 0;
  707. if (csp->ssl_with_server_is_opened == 0)
  708. {
  709. return;
  710. }
  711. /*
  712. * Notifying the peer that the connection is being closed.
  713. */
  714. do {
  715. ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
  716. } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
  717. free_server_ssl_structures(csp);
  718. csp->ssl_with_server_is_opened = 0;
  719. }
  720. /*********************************************************************
  721. *
  722. * Function : free_server_ssl_structures
  723. *
  724. * Description : Frees structures used for SSL communication with server
  725. *
  726. * Parameters :
  727. * 1 : csp = Current client state (buffers, headers, etc...)
  728. *
  729. * Returns : N/A
  730. *
  731. *********************************************************************/
  732. static void free_server_ssl_structures(struct client_state *csp)
  733. {
  734. struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
  735. /*
  736. * We can't use function mbedtls_net_free, because this function
  737. * inter alia close TCP connection on set fd. Instead of this
  738. * function, we change fd to -1, which is the same what does
  739. * rest of mbedtls_net_free function.
  740. */
  741. ssl_attr->mbedtls_attr.socket_fd.fd = -1;
  742. mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
  743. mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
  744. freez(ssl_attr->mbedtls_attr.ciphersuites_list);
  745. mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
  746. }
  747. /*====================== Certificates ======================*/
  748. /*********************************************************************
  749. *
  750. * Function : write_certificate
  751. *
  752. * Description : Writes certificate into file.
  753. *
  754. * Parameters :
  755. * 1 : crt = certificate to write into file
  756. * 2 : output_file = path to save certificate file
  757. * 3 : f_rng = mbedtls_ctr_drbg_random
  758. * 4 : p_rng = mbedtls_ctr_drbg_context
  759. *
  760. * Returns : Length of written certificate on success or negative value
  761. * on error
  762. *
  763. *********************************************************************/
  764. static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
  765. int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  766. {
  767. FILE *f = NULL;
  768. size_t len = 0;
  769. unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
  770. int ret = 0;
  771. char err_buf[ERROR_BUF_SIZE];
  772. memset(cert_buf, 0, sizeof(cert_buf));
  773. /*
  774. * Writing certificate into PEM string. If buffer is too small, function
  775. * returns specific error and no buffer overflow can happen.
  776. */
  777. if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
  778. sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
  779. {
  780. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  781. log_error(LOG_LEVEL_ERROR,
  782. "Writing certificate into buffer failed: %s", err_buf);
  783. return -1;
  784. }
  785. len = strlen((char *)cert_buf);
  786. /*
  787. * Saving certificate into file
  788. */
  789. if ((f = fopen(output_file, "w")) == NULL)
  790. {
  791. log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
  792. output_file);
  793. return -1;
  794. }
  795. if (fwrite(cert_buf, 1, len, f) != len)
  796. {
  797. log_error(LOG_LEVEL_ERROR,
  798. "Writing certificate into file %s failed", output_file);
  799. fclose(f);
  800. return -1;
  801. }
  802. fclose(f);
  803. return (int)len;
  804. }
  805. /*********************************************************************
  806. *
  807. * Function : write_private_key
  808. *
  809. * Description : Writes private key into file and copies saved
  810. * content into given pointer to string. If function
  811. * returns 0 for success, this copy must be freed by
  812. * caller.
  813. *
  814. * Parameters :
  815. * 1 : key = key to write into file
  816. * 2 : ret_buf = pointer to string with created key file content
  817. * 3 : key_file_path = path where to save key file
  818. *
  819. * Returns : Length of written private key on success or negative value
  820. * on error
  821. *
  822. *********************************************************************/
  823. static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
  824. const char *key_file_path)
  825. {
  826. size_t len = 0; /* Length of created key */
  827. FILE *f = NULL; /* File to save certificate */
  828. int ret = 0;
  829. char err_buf[ERROR_BUF_SIZE];
  830. /* Initializing buffer for key file content */
  831. *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
  832. /*
  833. * Writing private key into PEM string
  834. */
  835. if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
  836. {
  837. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  838. log_error(LOG_LEVEL_ERROR,
  839. "Writing private key into PEM string failed: %s", err_buf);
  840. ret = -1;
  841. goto exit;
  842. }
  843. len = strlen((char *)*ret_buf);
  844. /*
  845. * Saving key into file
  846. */
  847. if ((f = fopen(key_file_path, "wb")) == NULL)
  848. {
  849. log_error(LOG_LEVEL_ERROR,
  850. "Opening file %s to save private key failed: %E",
  851. key_file_path);
  852. ret = -1;
  853. goto exit;
  854. }
  855. if (fwrite(*ret_buf, 1, len, f) != len)
  856. {
  857. fclose(f);
  858. log_error(LOG_LEVEL_ERROR,
  859. "Writing private key into file %s failed",
  860. key_file_path);
  861. ret = -1;
  862. goto exit;
  863. }
  864. fclose(f);
  865. exit:
  866. if (ret < 0)
  867. {
  868. freez(*ret_buf);
  869. *ret_buf = NULL;
  870. return ret;
  871. }
  872. return (int)len;
  873. }
  874. /*********************************************************************
  875. *
  876. * Function : generate_key
  877. *
  878. * Description : Tests if private key for host saved in csp already
  879. * exists. If this file doesn't exists, a new key is
  880. * generated and saved in a file. The generated key is also
  881. * copied into given parameter key_buf, which must be then
  882. * freed by caller. If file with key exists, key_buf
  883. * contain NULL and no private key is generated.
  884. *
  885. * Parameters :
  886. * 1 : csp = Current client state (buffers, headers, etc...)
  887. * 2 : key_buf = buffer to save new generated key
  888. *
  889. * Returns : -1 => Error while generating private key
  890. * 0 => Key already exists
  891. * >0 => Length of generated private key
  892. *
  893. *********************************************************************/
  894. static int generate_key(struct client_state *csp, unsigned char **key_buf)
  895. {
  896. mbedtls_pk_context key;
  897. key_options key_opt;
  898. int ret = 0;
  899. char err_buf[ERROR_BUF_SIZE];
  900. key_opt.key_file_path = NULL;
  901. /*
  902. * Initializing structures for key generating
  903. */
  904. mbedtls_pk_init(&key);
  905. /*
  906. * Preparing path for key file and other properties for generating key
  907. */
  908. key_opt.type = MBEDTLS_PK_RSA;
  909. key_opt.rsa_keysize = RSA_KEYSIZE;
  910. key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
  911. (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
  912. if (key_opt.key_file_path == NULL)
  913. {
  914. ret = -1;
  915. goto exit;
  916. }
  917. /*
  918. * Test if key already exists. If so, we don't have to create it again.
  919. */
  920. if (file_exists(key_opt.key_file_path) == 1)
  921. {
  922. ret = 0;
  923. goto exit;
  924. }
  925. /*
  926. * Seed the RNG
  927. */
  928. ret = seed_rng(csp);
  929. if (ret != 0)
  930. {
  931. ret = -1;
  932. goto exit;
  933. }
  934. /*
  935. * Setting attributes of private key and generating it
  936. */
  937. if ((ret = mbedtls_pk_setup(&key,
  938. mbedtls_pk_info_from_type(key_opt.type))) != 0)
  939. {
  940. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  941. log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
  942. ret = -1;
  943. goto exit;
  944. }
  945. ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
  946. &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
  947. if (ret != 0)
  948. {
  949. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  950. log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
  951. ret = -1;
  952. goto exit;
  953. }
  954. /*
  955. * Exporting private key into file
  956. */
  957. if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
  958. {
  959. log_error(LOG_LEVEL_ERROR,
  960. "Writing private key into file %s failed", key_opt.key_file_path);
  961. ret = -1;
  962. goto exit;
  963. }
  964. exit:
  965. /*
  966. * Freeing used variables
  967. */
  968. freez(key_opt.key_file_path);
  969. mbedtls_pk_free(&key);
  970. return ret;
  971. }
  972. /*********************************************************************
  973. *
  974. * Function : ssl_certificate_is_invalid
  975. *
  976. * Description : Checks whether or not a certificate is valid.
  977. * Currently only checks that the certificate can be
  978. * parsed and that the "valid to" date is in the future.
  979. *
  980. * Parameters :
  981. * 1 : cert_file = The certificate to check
  982. *
  983. * Returns : 0 => The certificate is valid.
  984. * 1 => The certificate is invalid
  985. *
  986. *********************************************************************/
  987. static int ssl_certificate_is_invalid(const char *cert_file)
  988. {
  989. mbedtls_x509_crt cert;
  990. int ret;
  991. mbedtls_x509_crt_init(&cert);
  992. ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
  993. if (ret != 0)
  994. {
  995. char err_buf[ERROR_BUF_SIZE];
  996. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  997. log_error(LOG_LEVEL_ERROR,
  998. "Loading certificate %s to check validity failed: %s",
  999. cert_file, err_buf);
  1000. mbedtls_x509_crt_free(&cert);
  1001. return 1;
  1002. }
  1003. if (mbedtls_x509_time_is_past(&cert.valid_to))
  1004. {
  1005. mbedtls_x509_crt_free(&cert);
  1006. return 1;
  1007. }
  1008. mbedtls_x509_crt_free(&cert);
  1009. return 0;
  1010. }
  1011. /*********************************************************************
  1012. *
  1013. * Function : set_subject_alternative_name
  1014. *
  1015. * Description : Sets the Subject Alternative Name extension to a cert
  1016. *
  1017. * Parameters :
  1018. * 1 : cert = The certificate to modify
  1019. * 2 : hostname = The hostname to add
  1020. *
  1021. * Returns : <0 => Error while creating certificate.
  1022. * 0 => It worked
  1023. *
  1024. *********************************************************************/
  1025. static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
  1026. {
  1027. char err_buf[ERROR_BUF_SIZE];
  1028. int ret;
  1029. char *subject_alternative_name;
  1030. size_t subject_alternative_name_len;
  1031. #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
  1032. unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
  1033. unsigned char *c;
  1034. int len;
  1035. subject_alternative_name_len = strlen(hostname) + 1;
  1036. subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
  1037. strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
  1038. memset(san_buf, 0, sizeof(san_buf));
  1039. c = san_buf + sizeof(san_buf);
  1040. len = 0;
  1041. ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
  1042. (const unsigned char *)subject_alternative_name,
  1043. strlen(subject_alternative_name));
  1044. if (ret < 0)
  1045. {
  1046. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1047. log_error(LOG_LEVEL_ERROR,
  1048. "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
  1049. goto exit;
  1050. }
  1051. len += ret;
  1052. ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
  1053. if (ret < 0)
  1054. {
  1055. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1056. log_error(LOG_LEVEL_ERROR,
  1057. "mbedtls_asn1_write_len() failed: %s", err_buf);
  1058. goto exit;
  1059. }
  1060. len += ret;
  1061. ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
  1062. if (ret < 0)
  1063. {
  1064. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1065. log_error(LOG_LEVEL_ERROR,
  1066. "mbedtls_asn1_write_tag() failed: %s", err_buf);
  1067. goto exit;
  1068. }
  1069. len += ret;
  1070. ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
  1071. if (ret < 0)
  1072. {
  1073. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1074. log_error(LOG_LEVEL_ERROR,
  1075. "mbedtls_asn1_write_len() failed: %s", err_buf);
  1076. goto exit;
  1077. }
  1078. len += ret;
  1079. ret = mbedtls_asn1_write_tag(&c, san_buf,
  1080. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
  1081. if (ret < 0)
  1082. {
  1083. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1084. log_error(LOG_LEVEL_ERROR,
  1085. "mbedtls_asn1_write_tag() failed: %s", err_buf);
  1086. goto exit;
  1087. }
  1088. len += ret;
  1089. ret = mbedtls_x509write_crt_set_extension(cert,
  1090. MBEDTLS_OID_SUBJECT_ALT_NAME,
  1091. MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
  1092. 0, san_buf + sizeof(san_buf) - len, (size_t)len);
  1093. if (ret < 0)
  1094. {
  1095. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1096. log_error(LOG_LEVEL_ERROR,
  1097. "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
  1098. }
  1099. exit:
  1100. freez(subject_alternative_name);
  1101. return ret;
  1102. }
  1103. /*********************************************************************
  1104. *
  1105. * Function : generate_webpage_certificate
  1106. *
  1107. * Description : Creates certificate file in presetted directory.
  1108. * If certificate already exists, no other certificate
  1109. * will be created. Subject of certificate is named
  1110. * by csp->http->host from parameter. This function also
  1111. * triggers generating of private key for new certificate.
  1112. *
  1113. * Parameters :
  1114. * 1 : csp = Current client state (buffers, headers, etc...)
  1115. *
  1116. * Returns : -1 => Error while creating certificate.
  1117. * 0 => Certificate already exists.
  1118. * >0 => Length of created certificate.
  1119. *
  1120. *********************************************************************/
  1121. static int generate_webpage_certificate(struct client_state *csp)
  1122. {
  1123. mbedtls_x509_crt issuer_cert;
  1124. mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
  1125. mbedtls_pk_context *issuer_key = &loaded_issuer_key;
  1126. mbedtls_pk_context *subject_key = &loaded_subject_key;
  1127. mbedtls_x509write_cert cert;
  1128. mbedtls_mpi serial;
  1129. unsigned char *key_buf = NULL; /* Buffer for created key */
  1130. int ret = 0;
  1131. char err_buf[ERROR_BUF_SIZE];
  1132. cert_options cert_opt;
  1133. char cert_valid_from[VALID_DATETIME_BUFLEN];
  1134. char cert_valid_to[VALID_DATETIME_BUFLEN];
  1135. /* Paths to keys and certificates needed to create certificate */
  1136. cert_opt.issuer_key = NULL;
  1137. cert_opt.subject_key = NULL;
  1138. cert_opt.issuer_crt = NULL;
  1139. cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
  1140. (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
  1141. if (cert_opt.output_file == NULL)
  1142. {
  1143. return -1;
  1144. }
  1145. cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
  1146. (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
  1147. if (cert_opt.subject_key == NULL)
  1148. {
  1149. freez(cert_opt.output_file);
  1150. return -1;
  1151. }
  1152. if (file_exists(cert_opt.output_file) == 1)
  1153. {
  1154. /* The file exists, but is it valid? */
  1155. if (ssl_certificate_is_invalid(cert_opt.output_file))
  1156. {
  1157. log_error(LOG_LEVEL_CONNECT,
  1158. "Certificate %s is no longer valid. Removing it.",
  1159. cert_opt.output_file);
  1160. if (unlink(cert_opt.output_file))
  1161. {
  1162. log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
  1163. cert_opt.output_file);
  1164. freez(cert_opt.output_file);
  1165. freez(cert_opt.subject_key);
  1166. return -1;
  1167. }
  1168. if (unlink(cert_opt.subject_key))
  1169. {
  1170. log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
  1171. cert_opt.subject_key);
  1172. freez(cert_opt.output_file);
  1173. freez(cert_opt.subject_key);
  1174. return -1;
  1175. }
  1176. }
  1177. else
  1178. {
  1179. freez(cert_opt.output_file);
  1180. freez(cert_opt.subject_key);
  1181. return 0;
  1182. }
  1183. }
  1184. /*
  1185. * Create key for requested host
  1186. */
  1187. int subject_key_len = generate_key(csp, &key_buf);
  1188. if (subject_key_len < 0)
  1189. {
  1190. freez(cert_opt.output_file);
  1191. freez(cert_opt.subject_key);
  1192. log_error(LOG_LEVEL_ERROR, "Key generating failed");
  1193. return -1;
  1194. }
  1195. /*
  1196. * Initializing structures for certificate generating
  1197. */
  1198. mbedtls_x509write_crt_init(&cert);
  1199. mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
  1200. mbedtls_pk_init(&loaded_issuer_key);
  1201. mbedtls_pk_init(&loaded_subject_key);
  1202. mbedtls_mpi_init(&serial);
  1203. mbedtls_x509_crt_init(&issuer_cert);
  1204. /*
  1205. * Presetting parameters for certificate. We must compute total length
  1206. * of parameters.
  1207. */
  1208. size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
  1209. strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
  1210. strlen(CERT_PARAM_ORG_UNIT) +
  1211. 3 * strlen(csp->http->host) + 1;
  1212. char cert_params[cert_params_len];
  1213. memset(cert_params, 0, cert_params_len);
  1214. /*
  1215. * Converting unsigned long serial number to char * serial number.
  1216. * We must compute length of serial number in string + terminating null.
  1217. */
  1218. unsigned long certificate_serial = get_certificate_serial(csp);
  1219. unsigned long certificate_serial_time = (unsigned long)time(NULL);
  1220. int serial_num_size = snprintf(NULL, 0, "%lu%lu",
  1221. certificate_serial_time, certificate_serial) + 1;
  1222. if (serial_num_size <= 0)
  1223. {
  1224. serial_num_size = 1;
  1225. }
  1226. char serial_num_text[serial_num_size]; /* Buffer for serial number */
  1227. ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
  1228. certificate_serial_time, certificate_serial);
  1229. if (ret < 0 || ret >= serial_num_size)
  1230. {
  1231. log_error(LOG_LEVEL_ERROR,
  1232. "Converting certificate serial number into string failed");
  1233. ret = -1;
  1234. goto exit;
  1235. }
  1236. /*
  1237. * Preparing parameters for certificate
  1238. */
  1239. strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
  1240. strlcat(cert_params, csp->http->host, cert_params_len);
  1241. strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
  1242. strlcat(cert_params, csp->http->host, cert_params_len);
  1243. strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
  1244. strlcat(cert_params, csp->http->host, cert_params_len);
  1245. strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
  1246. cert_opt.issuer_crt = csp->config->ca_cert_file;
  1247. cert_opt.issuer_key = csp->config->ca_key_file;
  1248. if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
  1249. || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
  1250. {
  1251. log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
  1252. ret = -1;
  1253. goto exit;
  1254. }
  1255. cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
  1256. cert_opt.issuer_pwd = csp->config->ca_password;
  1257. cert_opt.subject_name = cert_params;
  1258. cert_opt.not_before = cert_valid_from;
  1259. cert_opt.not_after = cert_valid_to;
  1260. cert_opt.serial = serial_num_text;
  1261. cert_opt.is_ca = 0;
  1262. cert_opt.max_pathlen = -1;
  1263. /*
  1264. * Test if the private key was already created.
  1265. * XXX: Can this still happen?
  1266. */
  1267. if (subject_key_len == 0)
  1268. {
  1269. log_error(LOG_LEVEL_ERROR, "Subject key was already created");
  1270. ret = 0;
  1271. goto exit;
  1272. }
  1273. /*
  1274. * Seed the PRNG
  1275. */
  1276. ret = seed_rng(csp);
  1277. if (ret != 0)
  1278. {
  1279. ret = -1;
  1280. goto exit;
  1281. }
  1282. /*
  1283. * Parse serial to MPI
  1284. */
  1285. ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
  1286. if (ret != 0)
  1287. {
  1288. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1289. log_error(LOG_LEVEL_ERROR,
  1290. "mbedtls_mpi_read_string failed: %s", err_buf);
  1291. ret = -1;
  1292. goto exit;
  1293. }
  1294. /*
  1295. * Loading certificates
  1296. */
  1297. ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
  1298. if (ret != 0)
  1299. {
  1300. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1301. log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
  1302. cert_opt.issuer_crt, err_buf);
  1303. ret = -1;
  1304. goto exit;
  1305. }
  1306. ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
  1307. sizeof(cert_opt.issuer_name), &issuer_cert.subject);
  1308. if (ret < 0)
  1309. {
  1310. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1311. log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
  1312. ret = -1;
  1313. goto exit;
  1314. }
  1315. /*
  1316. * Loading keys from file or from buffer
  1317. */
  1318. if (key_buf != NULL && subject_key_len > 0)
  1319. {
  1320. /* Key was created in this function and is stored in buffer */
  1321. ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
  1322. (size_t)(subject_key_len + 1), (unsigned const char *)
  1323. cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
  1324. }
  1325. else
  1326. {
  1327. /* Key wasn't created in this function, because it already existed */
  1328. ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
  1329. cert_opt.subject_key, cert_opt.subject_pwd);
  1330. }
  1331. if (ret != 0)
  1332. {
  1333. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1334. log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
  1335. cert_opt.subject_key, err_buf);
  1336. ret = -1;
  1337. goto exit;
  1338. }
  1339. ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
  1340. cert_opt.issuer_pwd);
  1341. if (ret != 0)
  1342. {
  1343. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1344. log_error(LOG_LEVEL_ERROR,
  1345. "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
  1346. ret = -1;
  1347. goto exit;
  1348. }
  1349. /*
  1350. * Check if key and issuer certificate match
  1351. */
  1352. if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
  1353. mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
  1354. &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
  1355. mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
  1356. &mbedtls_pk_rsa(*issuer_key)->E) != 0)
  1357. {
  1358. log_error(LOG_LEVEL_ERROR,
  1359. "Issuer key doesn't match issuer certificate");
  1360. ret = -1;
  1361. goto exit;
  1362. }
  1363. mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
  1364. mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
  1365. /*
  1366. * Setting parameters of signed certificate
  1367. */
  1368. ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
  1369. if (ret != 0)
  1370. {
  1371. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1372. log_error(LOG_LEVEL_ERROR,
  1373. "Setting subject name in signed certificate failed: %s", err_buf);
  1374. ret = -1;
  1375. goto exit;
  1376. }
  1377. ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
  1378. if (ret != 0)
  1379. {
  1380. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1381. log_error(LOG_LEVEL_ERROR,
  1382. "Setting issuer name in signed certificate failed: %s", err_buf);
  1383. ret = -1;
  1384. goto exit;
  1385. }
  1386. ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
  1387. if (ret != 0)
  1388. {
  1389. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1390. log_error(LOG_LEVEL_ERROR,
  1391. "Setting serial number in signed certificate failed: %s", err_buf);
  1392. ret = -1;
  1393. goto exit;
  1394. }
  1395. ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
  1396. cert_opt.not_after);
  1397. if (ret != 0)
  1398. {
  1399. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1400. log_error(LOG_LEVEL_ERROR,
  1401. "Setting validity in signed certificate failed: %s", err_buf);
  1402. ret = -1;
  1403. goto exit;
  1404. }
  1405. /*
  1406. * Setting the basicConstraints extension for certificate
  1407. */
  1408. ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
  1409. cert_opt.max_pathlen);
  1410. if (ret != 0)
  1411. {
  1412. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1413. log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
  1414. "in signed certificate failed: %s", err_buf);
  1415. ret = -1;
  1416. goto exit;
  1417. }
  1418. #if defined(MBEDTLS_SHA1_C)
  1419. /* Setting the subjectKeyIdentifier extension for certificate */
  1420. ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
  1421. if (ret != 0)
  1422. {
  1423. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1424. log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
  1425. "identifier failed: %s", err_buf);
  1426. ret = -1;
  1427. goto exit;
  1428. }
  1429. /* Setting the authorityKeyIdentifier extension for certificate */
  1430. ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
  1431. if (ret != 0)
  1432. {
  1433. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1434. log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
  1435. "identifier failed: %s", err_buf);
  1436. ret = -1;
  1437. goto exit;
  1438. }
  1439. #endif /* MBEDTLS_SHA1_C */
  1440. if (!host_is_ip_address(csp->http->host) &&
  1441. set_subject_alternative_name(&cert, csp->http->host))
  1442. {
  1443. /* Errors are already logged by set_subject_alternative_name() */
  1444. ret = -1;
  1445. goto exit;
  1446. }
  1447. /*
  1448. * Writing certificate into file
  1449. */
  1450. ret = write_certificate(&cert, cert_opt.output_file,
  1451. mbedtls_ctr_drbg_random, &ctr_drbg);
  1452. if (ret < 0)
  1453. {
  1454. log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
  1455. goto exit;
  1456. }
  1457. exit:
  1458. /*
  1459. * Freeing used structures
  1460. */
  1461. mbedtls_x509write_crt_free(&cert);
  1462. mbedtls_pk_free(&loaded_subject_key);
  1463. mbedtls_pk_free(&loaded_issuer_key);
  1464. mbedtls_mpi_free(&serial);
  1465. mbedtls_x509_crt_free(&issuer_cert);
  1466. freez(cert_opt.subject_key);
  1467. freez(cert_opt.output_file);
  1468. freez(key_buf);
  1469. return ret;
  1470. }
  1471. /*********************************************************************
  1472. *
  1473. * Function : ssl_verify_callback
  1474. *
  1475. * Description : This is a callback function for certificate verification.
  1476. * It's called once for each certificate in the server's
  1477. * certificate trusted chain and prepares information about
  1478. * the certificate. The information can be used to inform
  1479. * the user about invalid certificates.
  1480. *
  1481. * Parameters :
  1482. * 1 : csp_void = Current client state (buffers, headers, etc...)
  1483. * 2 : crt = certificate from trusted chain
  1484. * 3 : depth = depth in trusted chain
  1485. * 4 : flags = certificate flags
  1486. *
  1487. * Returns : 0 on success and negative value on error
  1488. *
  1489. *********************************************************************/
  1490. static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
  1491. int depth, uint32_t *flags)
  1492. {
  1493. struct client_state *csp = (struct client_state *)csp_void;
  1494. struct certs_chain *last = &(csp->server_certs_chain);
  1495. size_t olen = 0;
  1496. int ret = 0;
  1497. /*
  1498. * Searching for last item in certificates linked list
  1499. */
  1500. while (last->next != NULL)
  1501. {
  1502. last = last->next;
  1503. }
  1504. /*
  1505. * Preparing next item in linked list for next certificate
  1506. */
  1507. last->next = malloc_or_die(sizeof(struct certs_chain));
  1508. last->next->next = NULL;
  1509. memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
  1510. memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
  1511. /*
  1512. * Saving certificate file into buffer
  1513. */
  1514. if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
  1515. crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
  1516. sizeof(last->file_buf)-1, &olen)) != 0)
  1517. {
  1518. char err_buf[ERROR_BUF_SIZE];
  1519. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1520. log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
  1521. err_buf);
  1522. return(ret);
  1523. }
  1524. /*
  1525. * Saving certificate information into buffer
  1526. */
  1527. {
  1528. char buf[CERT_INFO_BUF_SIZE];
  1529. char *encoded_text;
  1530. mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
  1531. encoded_text = html_encode(buf);
  1532. if (encoded_text == NULL)
  1533. {
  1534. log_error(LOG_LEVEL_ERROR,
  1535. "Failed to HTML-encode the certificate information");
  1536. return -1;
  1537. }
  1538. strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
  1539. freez(encoded_text);
  1540. }
  1541. return 0;
  1542. }
  1543. /*********************************************************************
  1544. *
  1545. * Function : host_to_hash
  1546. *
  1547. * Description : Creates MD5 hash from host name. Host name is loaded
  1548. * from structure csp and saved again into it.
  1549. *
  1550. * Parameters :
  1551. * 1 : csp = Current client state (buffers, headers, etc...)
  1552. *
  1553. * Returns : 1 => Error while creating hash
  1554. * 0 => Hash created successfully
  1555. *
  1556. *********************************************************************/
  1557. static int host_to_hash(struct client_state *csp)
  1558. {
  1559. int ret = 0;
  1560. #if !defined(MBEDTLS_MD5_C)
  1561. #error mbedTLS needs to be compiled with md5 support
  1562. #else
  1563. memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
  1564. mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
  1565. csp->http->hash_of_host);
  1566. /* Converting hash into string with hex */
  1567. size_t i = 0;
  1568. for (; i < 16; i++)
  1569. {
  1570. if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
  1571. csp->http->hash_of_host[i])) < 0)
  1572. {
  1573. log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
  1574. return -1;
  1575. }
  1576. }
  1577. return 0;
  1578. #endif /* MBEDTLS_MD5_C */
  1579. }
  1580. /*********************************************************************
  1581. *
  1582. * Function : seed_rng
  1583. *
  1584. * Description : Seeding the RNG for all SSL uses
  1585. *
  1586. * Parameters :
  1587. * 1 : csp = Current client state (buffers, headers, etc...)
  1588. *
  1589. * Returns : -1 => RNG wasn't seed successfully
  1590. * 0 => RNG is seeded successfully
  1591. *
  1592. *********************************************************************/
  1593. static int seed_rng(struct client_state *csp)
  1594. {
  1595. int ret = 0;
  1596. char err_buf[ERROR_BUF_SIZE];
  1597. if (rng_seeded == 0)
  1598. {
  1599. privoxy_mutex_lock(&ssl_init_mutex);
  1600. if (rng_seeded == 0)
  1601. {
  1602. mbedtls_ctr_drbg_init(&ctr_drbg);
  1603. mbedtls_entropy_init(&entropy);
  1604. ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
  1605. &entropy, NULL, 0);
  1606. if (ret != 0)
  1607. {
  1608. mbedtls_strerror(ret, err_buf, sizeof(err_buf));
  1609. log_error(LOG_LEVEL_ERROR,
  1610. "mbedtls_ctr_drbg_seed failed: %s", err_buf);
  1611. privoxy_mutex_unlock(&ssl_init_mutex);
  1612. return -1;
  1613. }
  1614. rng_seeded = 1;
  1615. }
  1616. privoxy_mutex_unlock(&ssl_init_mutex);
  1617. }
  1618. return 0;
  1619. }
  1620. /*********************************************************************
  1621. *
  1622. * Function : ssl_base64_encode
  1623. *
  1624. * Description : Encode a buffer into base64 format.
  1625. *
  1626. * Parameters :
  1627. * 1 : dst = Destination buffer
  1628. * 2 : dlen = Destination buffer length
  1629. * 3 : olen = Number of bytes written
  1630. * 4 : src = Source buffer
  1631. * 5 : slen = Amount of data to be encoded
  1632. *
  1633. * Returns : 0 on success, error code othervise
  1634. *
  1635. *********************************************************************/
  1636. extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
  1637. const unsigned char *src, size_t slen)
  1638. {
  1639. return mbedtls_base64_encode(dst, dlen, olen, src, slen);
  1640. }
  1641. /*********************************************************************
  1642. *
  1643. * Function : ssl_crt_verify_info
  1644. *
  1645. * Description : Returns an informational string about the verification
  1646. * status of a certificate.
  1647. *
  1648. * Parameters :
  1649. * 1 : buf = Buffer to write to
  1650. * 2 : size = Maximum size of buffer
  1651. * 3 : csp = client state
  1652. *
  1653. * Returns : N/A
  1654. *
  1655. *********************************************************************/
  1656. extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
  1657. {
  1658. mbedtls_x509_crt_verify_info(buf, size, " ", csp->server_cert_verification_result);
  1659. }
  1660. /*********************************************************************
  1661. *
  1662. * Function : ssl_release
  1663. *
  1664. * Description : Release all SSL resources
  1665. *
  1666. * Parameters :
  1667. *
  1668. * Returns : N/A
  1669. *
  1670. *********************************************************************/
  1671. extern void ssl_release(void)
  1672. {
  1673. if (rng_seeded == 1)
  1674. {
  1675. mbedtls_ctr_drbg_free(&ctr_drbg);
  1676. mbedtls_entropy_free(&entropy);
  1677. }
  1678. }
  1679. /*********************************************************************
  1680. *
  1681. * Function : get_ciphersuites_from_string
  1682. *
  1683. * Description : Converts a string of ciphersuite names to
  1684. * an array of ciphersuite ids.
  1685. *
  1686. * Parameters :
  1687. * 1 : ciphersuites_string = String containing allowed
  1688. * ciphersuites.
  1689. *
  1690. * Returns : Array of ciphersuite ids
  1691. *
  1692. *********************************************************************/
  1693. static int *get_ciphersuites_from_string(const char *parameter_string)
  1694. {
  1695. char *ciphersuites_index;
  1696. char *item_end;
  1697. char *ciphersuites_string;
  1698. int *ciphersuite_ids;
  1699. size_t count = 2;
  1700. int index = 0;
  1701. const char separator = ':';
  1702. size_t parameter_len = strlen(parameter_string);
  1703. ciphersuites_string = zalloc_or_die(parameter_len + 1);
  1704. strncpy(ciphersuites_string, parameter_string, parameter_len);
  1705. ciphersuites_index = ciphersuites_string;
  1706. while (*ciphersuites_index)
  1707. {
  1708. if (*ciphersuites_index++ == separator)
  1709. {
  1710. ++count;
  1711. }
  1712. }
  1713. ciphersuite_ids = zalloc_or_die(count * sizeof(int));
  1714. ciphersuites_index = ciphersuites_string;
  1715. do
  1716. {
  1717. item_end = strchr(ciphersuites_index, separator);
  1718. if (item_end != NULL)
  1719. {
  1720. *item_end = '\0';
  1721. }
  1722. ciphersuite_ids[index] =
  1723. mbedtls_ssl_get_ciphersuite_id(ciphersuites_index);
  1724. if (ciphersuite_ids[index] == 0)
  1725. {
  1726. log_error(LOG_LEVEL_ERROR,
  1727. "Failed to get ciphersuite id for %s", ciphersuites_index);
  1728. freez(ciphersuite_ids);
  1729. freez(ciphersuites_string);
  1730. return NULL;
  1731. }
  1732. ciphersuites_index = item_end + 1;
  1733. index++;
  1734. } while (item_end != NULL);
  1735. ciphersuite_ids[index] = 0;
  1736. freez(ciphersuites_string);
  1737. return ciphersuite_ids;
  1738. }