tls_server.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. /*
  2. * $Id$
  3. *
  4. * TLS module - main server part
  5. *
  6. * Copyright (C) 2001-2003 FhG FOKUS
  7. * Copyright (C) 2005-2010 iptelorg GmbH
  8. *
  9. * This file is part of SIP-router, a free SIP server.
  10. *
  11. * Permission to use, copy, modify, and distribute this software for any
  12. * purpose with or without fee is hereby granted, provided that the above
  13. * copyright notice and this permission notice appear in all copies.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  16. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  17. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  18. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  21. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22. */
  23. /*
  24. * History:
  25. * --------
  26. * 2007-01-26 openssl kerberos malloc bug detection/workaround (andrei)
  27. * 2007-02-23 openssl low memory bugs workaround (andrei)
  28. * 2009-09-21 tls connection state is now kept in c->extra_data (no
  29. * longer shared with tcp state) (andrei)
  30. */
  31. /** main tls part (implements the tls hooks that are called from the tcp code).
  32. * @file tls_server.c
  33. * @ingroup tls
  34. * Module: @ref tls
  35. */
  36. #include <sys/poll.h>
  37. #include <openssl/err.h>
  38. #include <openssl/ssl.h>
  39. #include "../../dprint.h"
  40. #include "../../ip_addr.h"
  41. #include "../../mem/shm_mem.h"
  42. #include "../../pt.h"
  43. #include "../../timer.h"
  44. #include "../../globals.h"
  45. #include "../../pt.h"
  46. #include "../../tcp_int_send.h"
  47. #include "../../tcp_read.h"
  48. #include "../../cfg/cfg.h"
  49. #include "tls_init.h"
  50. #include "tls_domain.h"
  51. #include "tls_util.h"
  52. #include "tls_mod.h"
  53. #include "tls_server.h"
  54. #include "tls_bio.h"
  55. #include "tls_dump_vf.h"
  56. #include "tls_cfg.h"
  57. /* low memory treshold for openssl bug #1491 workaround */
  58. #define LOW_MEM_NEW_CONNECTION_TEST() \
  59. (cfg_get(tls, tls_cfg, low_mem_threshold1) && \
  60. (shm_available() < cfg_get(tls, tls_cfg, low_mem_threshold1)))
  61. #define LOW_MEM_CONNECTED_TEST() \
  62. (cfg_get(tls, tls_cfg, low_mem_threshold2) && \
  63. (shm_available() < cfg_get(tls, tls_cfg, low_mem_threshold2)))
  64. #define TLS_RD_MBUF_SZ 65536
  65. #define TLS_WR_MBUF_SZ 65536
  66. /* debugging */
  67. #ifdef NO_TLS_RD_DEBUG
  68. #undef TLS_RD_DEBUG
  69. #endif
  70. #ifdef NO_TLS_WR_DEBUG
  71. #undef TLS_WR_DEBUG
  72. #endif
  73. #if defined TLS_RD_DEBUG || defined TLS_WR_DEBUG
  74. #define TLS_F_DEBUG
  75. #endif
  76. /* if NO_TLS_F_DEBUG or NO_TLS_DEBUG => no debug code */
  77. #if defined NO_TLS_F_DEBUG || defined NO_TLS_DEBUG
  78. #undef TLS_F_DEBUG
  79. #endif
  80. #ifdef TLS_F_DEBUG
  81. #ifdef __SUNPRO_C
  82. #define TLS_F_TRACE(fmt, ...) \
  83. LOG_(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug),\
  84. "TLS_TRACE: " LOC_INFO, " %s" fmt,\
  85. _FUNC_NAME_, __VA_ARGS__)
  86. #else
  87. #define TLS_F_TRACE(fmt, args...) \
  88. LOG_(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug),\
  89. "TLS_TRACE: " LOC_INFO, " %s" fmt,\
  90. _FUNC_NAME_, ## args)
  91. #endif /* __SUNPRO_c */
  92. #else /* TLS_F_DEBUG */
  93. #ifdef __SUNPRO_C
  94. #define TLS_F_TRACE(...)
  95. #else
  96. #define TLS_F_TRACE(fmt, args...)
  97. #endif /* __SUNPRO_c */
  98. #endif /* TLS_F_DEBUG */
  99. /* tls_read debugging */
  100. #ifdef TLS_RD_DEBUG
  101. #define TLS_RD_TRACE TLS_F_TRACE
  102. #else /* TLS_RD_DEBUG */
  103. #ifdef __SUNPRO_C
  104. #define TLS_RD_TRACE(...)
  105. #else
  106. #define TLS_RD_TRACE(fmt, args...)
  107. #endif /* __SUNPRO_c */
  108. #endif /* TLS_RD_DEBUG */
  109. /* tls_write debugging */
  110. #ifdef TLS_WR_DEBUG
  111. #define TLS_WR_TRACE TLS_F_TRACE
  112. #else /* TLS_RD_DEBUG */
  113. #ifdef __SUNPRO_C
  114. #define TLS_WR_TRACE(...)
  115. #else
  116. #define TLS_WR_TRACE(fmt, args...)
  117. #endif /* __SUNPRO_c */
  118. #endif /* TLS_RD_DEBUG */
  119. /** finish the ssl init.
  120. * Creates the SSL context + internal tls_extra_data and sets
  121. * extra_data to it.
  122. * Separated from tls_tcpconn_init to allow delayed ssl context
  123. * init (from the "child" process and not from the main one).
  124. * WARNING: the connection should be already locked.
  125. * @return 0 on success, -1 on errror.
  126. */
  127. static int tls_complete_init(struct tcp_connection* c)
  128. {
  129. tls_domain_t* dom;
  130. struct tls_extra_data* data = 0;
  131. tls_domains_cfg_t* cfg;
  132. enum tls_conn_states state;
  133. if (LOW_MEM_NEW_CONNECTION_TEST()){
  134. ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
  135. " operation: %lu\n", shm_available());
  136. goto error2;
  137. }
  138. /* Get current TLS configuration and increase reference
  139. * count immediately. There is no need to lock the structure
  140. * here, because it does not get deleted immediately. When
  141. * SER reloads TLS configuration it will put the old configuration
  142. * on a garbage queue and delete it later, so we know here that
  143. * the pointer we get from *tls_domains_cfg will be valid for a while,
  144. * at least by the time this function finishes
  145. */
  146. cfg = *tls_domains_cfg;
  147. /* Increment the reference count in the configuration structure, this
  148. * is to ensure that, while on the garbage queue, the configuration does
  149. * not get deleted if there are still connection referencing its SSL_CTX
  150. */
  151. cfg->ref_count++;
  152. if (c->flags & F_CONN_PASSIVE) {
  153. state=S_TLS_ACCEPTING;
  154. dom = tls_lookup_cfg(cfg, TLS_DOMAIN_SRV,
  155. &c->rcv.dst_ip, c->rcv.dst_port);
  156. } else {
  157. state=S_TLS_CONNECTING;
  158. dom = tls_lookup_cfg(cfg, TLS_DOMAIN_CLI,
  159. &c->rcv.dst_ip, c->rcv.dst_port);
  160. }
  161. if (unlikely(c->state<0)) {
  162. BUG("Invalid connection (state %d)\n", c->state);
  163. goto error;
  164. }
  165. DBG("Using TLS domain %s\n", tls_domain_str(dom));
  166. data = (struct tls_extra_data*)shm_malloc(sizeof(struct tls_extra_data));
  167. if (!data) {
  168. ERR("Not enough shared memory left\n");
  169. goto error;
  170. }
  171. memset(data, '\0', sizeof(struct tls_extra_data));
  172. data->ssl = SSL_new(dom->ctx[process_no]);
  173. data->rwbio = tls_BIO_new_mbuf(0, 0);
  174. data->cfg = cfg;
  175. data->state = state;
  176. if (unlikely(data->ssl == 0 || data->rwbio == 0)) {
  177. TLS_ERR("Failed to create SSL or BIO structure:");
  178. if (data->ssl)
  179. SSL_free(data->ssl);
  180. if (data->rwbio)
  181. BIO_free(data->rwbio);
  182. goto error;
  183. }
  184. #ifdef TLS_KSSL_WORKARROUND
  185. /* if needed apply workaround for openssl bug #1467 */
  186. if (data->ssl->kssl_ctx && openssl_kssl_malloc_bug){
  187. kssl_ctx_free(data->ssl->kssl_ctx);
  188. data->ssl->kssl_ctx=0;
  189. }
  190. #endif
  191. SSL_set_bio(data->ssl, data->rwbio, data->rwbio);
  192. c->extra_data = data;
  193. /* link the extra data struct inside ssl connection*/
  194. SSL_set_app_data(data->ssl, data);
  195. return 0;
  196. error:
  197. cfg->ref_count--;
  198. if (data) shm_free(data);
  199. error2:
  200. return -1;
  201. }
  202. /** completes tls init if needed and checks if tls can be used (unsafe).
  203. * It will check for low memory.
  204. * If it returns success, c->extra_data is guaranteed to be !=0.
  205. * WARNING: must be called with c->write_lock held.
  206. * @return 0 on success, < 0 on error (complete init failed or out of memory).
  207. */
  208. static int tls_fix_connection_unsafe(struct tcp_connection* c)
  209. {
  210. if (unlikely(!c->extra_data)) {
  211. if (unlikely(tls_complete_init(c) < 0)) {
  212. return -1;
  213. }
  214. }else if (unlikely(LOW_MEM_CONNECTED_TEST())){
  215. ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
  216. " operation: %lu\n", shm_available());
  217. return -1;
  218. }
  219. return 0;
  220. }
  221. /** completes tls init if needed and checks if tls can be used, (safe).
  222. * It will check for low memory.
  223. * If it returns success, c->extra_data is guaranteed to be !=0.
  224. * WARNING: must _not_ be called with c->write_lock held (it will
  225. * lock/unlock internally), see also tls_fix_connection_unsafe().
  226. * @return 0 on success, < 0 on error (complete init failed or out of memory).
  227. */
  228. static int tls_fix_connection(struct tcp_connection* c)
  229. {
  230. int ret;
  231. if (unlikely(c->extra_data == 0)) {
  232. lock_get(&c->write_lock);
  233. if (unlikely(c->extra_data == 0)) {
  234. ret = tls_complete_init(c);
  235. lock_release(&c->write_lock);
  236. return ret;
  237. }
  238. lock_release(&c->write_lock);
  239. }
  240. if (unlikely(LOW_MEM_CONNECTED_TEST())){
  241. ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
  242. " operation: %lu\n", shm_available());
  243. return -1;
  244. }
  245. return 0;
  246. }
  247. /** sets an mbuf pair for the bio used by the tls connection.
  248. * WARNING: must be called with c->write_lock held.
  249. * @return 0 on success, -1 on error.
  250. */
  251. static int tls_set_mbufs(struct tcp_connection *c,
  252. struct tls_mbuf* rd,
  253. struct tls_mbuf* wr)
  254. {
  255. BIO *rwbio;
  256. rwbio = ((struct tls_extra_data*)c->extra_data)->rwbio;
  257. if (unlikely(tls_BIO_mbuf_set(rwbio, rd, wr)<=0)) {
  258. /* it should be always 1 */
  259. ERR("failed to set mbufs");
  260. return -1;
  261. }
  262. return 0;
  263. }
  264. static void tls_dump_cert_info(char* s, X509* cert)
  265. {
  266. char* subj;
  267. char* issuer;
  268. subj=issuer=0;
  269. subj = X509_NAME_oneline(X509_get_subject_name(cert), 0 , 0);
  270. issuer = X509_NAME_oneline(X509_get_issuer_name(cert), 0 , 0);
  271. if (subj){
  272. LOG(cfg_get(tls, tls_cfg, log), "%s subject:%s\n", s ? s : "", subj);
  273. OPENSSL_free(subj);
  274. }
  275. if (issuer){
  276. LOG(cfg_get(tls, tls_cfg, log), "%s issuer:%s\n", s ? s : "", issuer);
  277. OPENSSL_free(issuer);
  278. }
  279. }
  280. /** wrapper around SSL_accept, usin SSL return convention.
  281. * It will also log critical errors and certificate debugging info.
  282. * @param c - tcp connection with tls (extra_data must be a filled
  283. * tcp_extra_data structure). The state must be S_TLS_ACCEPTING.
  284. * @param error set to the error reason (SSL_ERROR_*).
  285. * Note that it can be SSL_ERROR_NONE while the return is < 0
  286. * ("internal" error, not at the SSL level, see below).
  287. * @return >=1 on success, 0 and <0 on error. 0 means the underlying SSL
  288. * connection was closed/shutdown. < 0 is returned for any
  289. * SSL_ERROR (including WANT_READ or WANT_WRITE), but also
  290. * for internal non SSL related errors (in this case -2 is
  291. * returned and error==SSL_ERROR_NONE).
  292. *
  293. */
  294. int tls_accept(struct tcp_connection *c, int* error)
  295. {
  296. int ret;
  297. SSL *ssl;
  298. X509* cert;
  299. struct tls_extra_data* tls_c;
  300. int tls_log;
  301. *error = SSL_ERROR_NONE;
  302. tls_c=(struct tls_extra_data*)c->extra_data;
  303. ssl=tls_c->ssl;
  304. if (unlikely(tls_c->state != S_TLS_ACCEPTING)) {
  305. BUG("Invalid connection state %d (bug in TLS code)\n", tls_c->state);
  306. goto err;
  307. }
  308. ret = SSL_accept(ssl);
  309. if (unlikely(ret == 1)) {
  310. DBG("TLS accept successful\n");
  311. tls_c->state = S_TLS_ESTABLISHED;
  312. tls_log = cfg_get(tls, tls_cfg, log);
  313. LOG(tls_log, "tls_accept: new connection from %s:%d using %s %s %d\n",
  314. ip_addr2a(&c->rcv.src_ip), c->rcv.src_port,
  315. SSL_get_cipher_version(ssl), SSL_get_cipher_name(ssl),
  316. SSL_get_cipher_bits(ssl, 0)
  317. );
  318. LOG(tls_log, "tls_accept: local socket: %s:%d\n",
  319. ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port
  320. );
  321. cert = SSL_get_peer_certificate(ssl);
  322. if (cert != 0) {
  323. tls_dump_cert_info("tls_accept: client certificate", cert);
  324. if (SSL_get_verify_result(ssl) != X509_V_OK) {
  325. LOG(tls_log, "WARNING: tls_accept: client certificate "
  326. "verification failed!!!\n");
  327. tls_dump_verification_failure(SSL_get_verify_result(ssl));
  328. }
  329. X509_free(cert);
  330. } else {
  331. LOG(tls_log, "tls_accept: client did not present a certificate\n");
  332. }
  333. } else { /* ret == 0 or < 0 */
  334. *error = SSL_get_error(ssl, ret);
  335. }
  336. return ret;
  337. err:
  338. /* internal non openssl related errors */
  339. return -2;
  340. }
  341. /** wrapper around SSL_connect, using SSL return convention.
  342. * It will also log critical errors and certificate debugging info.
  343. * @param c - tcp connection with tls (extra_data must be a filled
  344. * tcp_extra_data structure). The state must be S_TLS_CONNECTING.
  345. * @param error set to the error reason (SSL_ERROR_*).
  346. * Note that it can be SSL_ERROR_NONE while the return is < 0
  347. * ("internal" error, not at the SSL level, see below).
  348. * @return >=1 on success, 0 and <0 on error. 0 means the underlying SSL
  349. * connection was closed/shutdown. < 0 is returned for any
  350. * SSL_ERROR (including WANT_READ or WANT_WRITE), but also
  351. * for internal non SSL related errors (in this case -2 is
  352. * returned and error==SSL_ERROR_NONE).
  353. *
  354. */
  355. int tls_connect(struct tcp_connection *c, int* error)
  356. {
  357. SSL *ssl;
  358. int ret;
  359. X509* cert;
  360. struct tls_extra_data* tls_c;
  361. int tls_log;
  362. *error = SSL_ERROR_NONE;
  363. tls_c=(struct tls_extra_data*)c->extra_data;
  364. ssl=tls_c->ssl;
  365. if (unlikely(tls_c->state != S_TLS_CONNECTING)) {
  366. BUG("Invalid connection state %d (bug in TLS code)\n", tls_c->state);
  367. goto err;
  368. }
  369. ret = SSL_connect(ssl);
  370. if (unlikely(ret == 1)) {
  371. DBG("TLS connect successful\n");
  372. tls_c->state = S_TLS_ESTABLISHED;
  373. tls_log = cfg_get(tls, tls_cfg, log);
  374. LOG(tls_log, "tls_connect: new connection to %s:%d using %s %s %d\n",
  375. ip_addr2a(&c->rcv.src_ip), c->rcv.src_port,
  376. SSL_get_cipher_version(ssl), SSL_get_cipher_name(ssl),
  377. SSL_get_cipher_bits(ssl, 0)
  378. );
  379. LOG(tls_log, "tls_connect: sending socket: %s:%d \n",
  380. ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port
  381. );
  382. cert = SSL_get_peer_certificate(ssl);
  383. if (cert != 0) {
  384. tls_dump_cert_info("tls_connect: server certificate", cert);
  385. if (SSL_get_verify_result(ssl) != X509_V_OK) {
  386. LOG(tls_log, "WARNING: tls_connect: server certificate "
  387. "verification failed!!!\n");
  388. tls_dump_verification_failure(SSL_get_verify_result(ssl));
  389. }
  390. X509_free(cert);
  391. } else {
  392. /* this should not happen, servers always present a cert */
  393. LOG(tls_log, "tls_connect: server did not "
  394. "present a certificate\n");
  395. }
  396. } else { /* 0 or < 0 */
  397. *error = SSL_get_error(ssl, ret);
  398. }
  399. return ret;
  400. err:
  401. /* internal non openssl related errors */
  402. return -2;
  403. }
  404. /*
  405. * wrapper around SSL_shutdown, returns -1 on error, 0 on success.
  406. */
  407. static int tls_shutdown(struct tcp_connection *c)
  408. {
  409. int ret, err, ssl_err;
  410. struct tls_extra_data* tls_c;
  411. SSL *ssl;
  412. tls_c=(struct tls_extra_data*)c->extra_data;
  413. if (unlikely(tls_c == 0 || tls_c->ssl == 0)) {
  414. ERR("No SSL data to perform tls_shutdown\n");
  415. return -1;
  416. }
  417. ssl = tls_c->ssl;
  418. /* it doesn't make sense to try a TLS level shutdown
  419. if the connection is not fully initialized */
  420. if (unlikely(tls_c->state != S_TLS_ESTABLISHED))
  421. return 0;
  422. if (unlikely(LOW_MEM_CONNECTED_TEST())){
  423. ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
  424. " operation: %lu\n", shm_available());
  425. goto err;
  426. }
  427. ret = SSL_shutdown(ssl);
  428. if (ret == 1) {
  429. DBG("TLS shutdown successful\n");
  430. return 0;
  431. } else if (ret == 0) {
  432. DBG("First phase of 2-way handshake completed succesfuly\n");
  433. return 0;
  434. } else {
  435. err = SSL_get_error(ssl, ret);
  436. switch (err) {
  437. case SSL_ERROR_ZERO_RETURN:
  438. DBG("TLS shutdown failed cleanly\n");
  439. goto err;
  440. case SSL_ERROR_WANT_READ:
  441. DBG("Need to get more data to finish TLS shutdown\n");
  442. break;
  443. case SSL_ERROR_WANT_WRITE:
  444. DBG("Need to send more data to finish TLS shutdown\n");
  445. break;
  446. #if OPENSSL_VERSION_NUMBER >= 0x00907000L /*0.9.7*/
  447. case SSL_ERROR_WANT_CONNECT:
  448. DBG("Need to retry connect\n");
  449. break;
  450. case SSL_ERROR_WANT_ACCEPT:
  451. DBG("Need to retry accept\n");
  452. break;
  453. #endif
  454. case SSL_ERROR_WANT_X509_LOOKUP:
  455. DBG("Application callback asked to be called again\n");
  456. break;
  457. case SSL_ERROR_SYSCALL:
  458. TLS_ERR_RET(ssl_err, "TLS shutdown");
  459. if (!ssl_err) {
  460. if (ret == 0) {
  461. WARN("Unexpected EOF occurred while performing TLS shutdown\n");
  462. } else {
  463. ERR("IO error: (%d) %s\n", errno, strerror(errno));
  464. }
  465. }
  466. goto err;
  467. case SSL_ERROR_SSL:
  468. default:
  469. TLS_ERR("SSL error:");
  470. goto err;
  471. }
  472. }
  473. return 0;
  474. err:
  475. return -1;
  476. }
  477. /** init tls specific data in a tcp connection.
  478. * Called when a new tcp connection is accepted or connected.
  479. * It completes the tcp connection initialisation by setting the tls
  480. * specific parts.
  481. * Note that ssl context creation and other expensive operation are left
  482. * out (they are delayed until the first read/write).
  483. * No locking is needed (when the connection is created no other process
  484. * can access it).
  485. * @param c - tcp connection.
  486. * @param sock - socket (unused for now).
  487. * @return 0 on success, < 0 on error.
  488. */
  489. int tls_h_tcpconn_init(struct tcp_connection *c, int sock)
  490. {
  491. c->type = PROTO_TLS;
  492. c->rcv.proto = PROTO_TLS;
  493. c->timeout = get_ticks_raw() + cfg_get(tls, tls_cfg, con_lifetime);
  494. c->extra_data = 0;
  495. return 0;
  496. }
  497. /** clean the extra data upon connection shut down.
  498. */
  499. void tls_h_tcpconn_clean(struct tcp_connection *c)
  500. {
  501. struct tls_extra_data* extra;
  502. /*
  503. * runs within global tcp lock
  504. */
  505. if ((c->type != PROTO_TLS) && (c->type != PROTO_WSS)) {
  506. BUG("Bad connection structure\n");
  507. abort();
  508. }
  509. if (c->extra_data) {
  510. extra = (struct tls_extra_data*)c->extra_data;
  511. SSL_free(extra->ssl);
  512. extra->cfg->ref_count--;
  513. if (extra->ct_wq)
  514. tls_ct_wq_free(&extra->ct_wq);
  515. if (extra->enc_rd_buf) {
  516. shm_free(extra->enc_rd_buf);
  517. extra->enc_rd_buf = 0;
  518. }
  519. shm_free(c->extra_data);
  520. c->extra_data = 0;
  521. }
  522. }
  523. /** perform one-way shutdown, do not wait for notify from the remote peer.
  524. */
  525. void tls_h_close(struct tcp_connection *c, int fd)
  526. {
  527. unsigned char wr_buf[TLS_WR_MBUF_SZ];
  528. struct tls_mbuf rd, wr;
  529. /*
  530. * runs either within global tcp lock or after the connection has
  531. * been "detached" and is unreachable from any other process.
  532. * Unfortunately when called via
  533. * tcpconn_put_destroy()+tcpconn_close_main_fd() the connection might
  534. * still be in a writer, so in this case locking is needed.
  535. */
  536. DBG("Closing SSL connection %p\n", c->extra_data);
  537. if (unlikely(cfg_get(tls, tls_cfg, send_close_notify) && c->extra_data)) {
  538. lock_get(&c->write_lock);
  539. if (unlikely(c->extra_data == 0)) {
  540. /* changed in the meanwhile */
  541. lock_release(&c->write_lock);
  542. return;
  543. }
  544. tls_mbuf_init(&rd, 0, 0); /* no read */
  545. tls_mbuf_init(&wr, wr_buf, sizeof(wr_buf));
  546. if (tls_set_mbufs(c, &rd, &wr)==0) {
  547. tls_shutdown(c); /* shudown only on succesfull set fd */
  548. /* write as much as possible and update wr.
  549. * Since this is a close, we don't want to queue the write
  550. * (if it can't write immediately, just fail silently)
  551. */
  552. if (wr.used)
  553. _tcpconn_write_nb(fd, c, (char*)wr.buf, wr.used);
  554. /* we don't bother reading anything (we don't want to wait
  555. on close) */
  556. }
  557. lock_release(&c->write_lock);
  558. }
  559. }
  560. /* generic tcpconn_{do,1st}_send() function pointer type */
  561. typedef int (*tcp_low_level_send_t)(int fd, struct tcp_connection *c,
  562. char* buf, unsigned len,
  563. snd_flags_t send_flags,
  564. long* resp, int locked);
  565. /** tls encrypt before sending function.
  566. * It is a callback that will be called by the tcp code, before a send
  567. * on TLS would be attempted. It should replace the input buffer with a
  568. * new static buffer containing the TLS processed data.
  569. * If the input buffer could not be fully encoded (e.g. run out of space
  570. * in the internal static buffer), it should set rest_buf and rest_len to
  571. * the remaining part, so that it could be called again once the output has
  572. * been used (sent). The send_flags used are also passed and they can be
  573. * changed (e.g. to disallow a close() after a partial encode).
  574. * WARNING: it must always be called with c->write_lock held!
  575. * @param c - tcp connection
  576. * @param pbuf - pointer to buffer (value/result, on success it will be
  577. * replaced with a static buffer).
  578. * @param plen - pointer to buffer size (value/result, on success it will be
  579. * replaced with the size of the replacement buffer.
  580. * @param rest_buf - (result) should be filled with a pointer to the
  581. * remaining unencoded part of the original buffer if any,
  582. * 0 otherwise.
  583. * @param rest_len - (result) should be filled with the length of the
  584. * remaining unencoded part of the original buffer (0 if
  585. * the original buffer was fully encoded).
  586. * @param send_flags - pointer to the send_flags that will be used for sending
  587. * the message.
  588. * @return *plen on success (>=0), < 0 on error.
  589. */
  590. int tls_encode_f(struct tcp_connection *c,
  591. const char** pbuf, unsigned int* plen,
  592. const char** rest_buf, unsigned int* rest_len,
  593. snd_flags_t* send_flags)
  594. {
  595. int n, offs;
  596. SSL* ssl;
  597. struct tls_extra_data* tls_c;
  598. static unsigned char wr_buf[TLS_WR_MBUF_SZ];
  599. struct tls_mbuf rd, wr;
  600. int ssl_error;
  601. char* err_src;
  602. const char* buf;
  603. unsigned int len;
  604. int x;
  605. buf = *pbuf;
  606. len = *plen;
  607. *rest_buf = 0;
  608. *rest_len = 0;
  609. TLS_WR_TRACE("(%p, %p, %d, ... 0x%0x) start (%s:%d* -> %s)\n",
  610. c, buf, len, send_flags->f,
  611. ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port,
  612. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)));
  613. n = 0;
  614. offs = 0;
  615. ssl_error = SSL_ERROR_NONE;
  616. err_src = "TLS write:";
  617. if (unlikely(tls_fix_connection_unsafe(c) < 0)) {
  618. /* c->extra_data might be null => exit immediately */
  619. TLS_WR_TRACE("(%p) end: tls_fix_connection_unsafe failed =>"
  620. " immediate error exit\n", c);
  621. return -1;
  622. }
  623. tls_c = (struct tls_extra_data*)c->extra_data;
  624. ssl = tls_c->ssl;
  625. tls_mbuf_init(&rd, 0, 0); /* no read */
  626. tls_mbuf_init(&wr, wr_buf, sizeof(wr_buf));
  627. /* clear text already queued (WANTS_READ) queue directly*/
  628. if (unlikely(tls_write_wants_read(tls_c))) {
  629. TLS_WR_TRACE("(%p) WANTS_READ queue present => queueing"
  630. " (%d bytes, %p + %d)\n", c, len - offs, buf, offs);
  631. if (unlikely(tls_ct_wq_add(&tls_c->ct_wq, buf+offs, len -offs) < 0)) {
  632. ERR("ct write buffer full for %p (%d bytes)\n",
  633. c, tls_c->ct_wq?tls_c->ct_wq->queued:0);
  634. goto error_wq_full;
  635. }
  636. /* buffer queued for a future send attempt, after first reading
  637. some data (key exchange) => don't allow immediate closing of
  638. the connection */
  639. send_flags->f &= ~SND_F_CON_CLOSE;
  640. goto end;
  641. }
  642. if (unlikely(tls_set_mbufs(c, &rd, &wr) < 0)) {
  643. ERR("tls_set_mbufs failed\n");
  644. goto error;
  645. }
  646. redo_wr:
  647. if (unlikely(tls_c->state == S_TLS_CONNECTING)) {
  648. n = tls_connect(c, &ssl_error);
  649. TLS_WR_TRACE("(%p) tls_connect() => %d (err=%d)\n", c, n, ssl_error);
  650. if (unlikely(n>=1)) {
  651. n = SSL_write(ssl, buf + offs, len - offs);
  652. if (unlikely(n <= 0))
  653. ssl_error = SSL_get_error(ssl, n);
  654. } else {
  655. /* tls_connect failed/needs more IO */
  656. if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE))
  657. goto error;
  658. err_src = "TLS connect:";
  659. }
  660. } else if (unlikely(tls_c->state == S_TLS_ACCEPTING)) {
  661. n = tls_accept(c, &ssl_error);
  662. TLS_WR_TRACE("(%p) tls_accept() => %d (err=%d)\n", c, n, ssl_error);
  663. if (unlikely(n>=1)) {
  664. n = SSL_write(ssl, buf + offs, len - offs);
  665. if (unlikely(n <= 0))
  666. ssl_error = SSL_get_error(ssl, n);
  667. } else {
  668. /* tls_accept failed/needs more IO */
  669. if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE))
  670. goto error;
  671. err_src = "TLS accept:";
  672. }
  673. } else {
  674. n = SSL_write(ssl, buf + offs, len - offs);
  675. if (unlikely(n <= 0))
  676. ssl_error = SSL_get_error(ssl, n);
  677. }
  678. TLS_WR_TRACE("(%p) SSL_write(%p + %d, %d) => %d (err=%d)\n",
  679. c, buf, offs, len - offs, n, ssl_error);
  680. /* check for possible ssl errors */
  681. if (unlikely(n <= 0)){
  682. switch(ssl_error) {
  683. case SSL_ERROR_NONE:
  684. BUG("unexpected SSL_ERROR_NONE for n=%d\n", n);
  685. goto error;
  686. break;
  687. case SSL_ERROR_ZERO_RETURN:
  688. /* SSL EOF */
  689. ERR("ssl level EOF\n");
  690. goto ssl_eof;
  691. case SSL_ERROR_WANT_READ:
  692. /* queue write buffer */
  693. TLS_WR_TRACE("(%p) SSL_ERROR_WANT_READ => queueing for read"
  694. " (%p + %d, %d)\n", c, buf, offs, len -offs);
  695. if (unlikely(tls_ct_wq_add(&tls_c->ct_wq, buf+offs, len -offs)
  696. < 0)) {
  697. ERR("ct write buffer full (%d bytes)\n",
  698. tls_c->ct_wq?tls_c->ct_wq->queued:0);
  699. goto error_wq_full;
  700. }
  701. tls_c->flags |= F_TLS_CON_WR_WANTS_RD;
  702. /* buffer queued for a future send attempt, after first
  703. reading some data (key exchange) => don't allow immediate
  704. closing of the connection */
  705. send_flags->f &= ~SND_F_CON_CLOSE;
  706. break; /* or goto end */
  707. case SSL_ERROR_WANT_WRITE:
  708. if (unlikely(offs == 0)) {
  709. /* error, no record fits in the buffer or
  710. no partial write enabled and buffer to small to fit
  711. all the records */
  712. BUG("write buffer too small (%d/%d bytes)\n",
  713. wr.used, wr.size);
  714. goto bug;
  715. } else {
  716. /* offs != 0 => something was "written" */
  717. *rest_buf = buf + offs;
  718. *rest_len = len - offs;
  719. /* this function should be called again => disallow
  720. immediate closing of the connection */
  721. send_flags->f &= ~SND_F_CON_CLOSE;
  722. TLS_WR_TRACE("(%p) SSL_ERROR_WANT_WRITE partial write"
  723. " (written %p , %d, rest_buf=%p"
  724. " rest_len=%d))\n", c, buf, offs,
  725. *rest_buf, *rest_len);
  726. }
  727. break; /* or goto end */
  728. case SSL_ERROR_SSL:
  729. /* protocol level error */
  730. TLS_ERR(err_src);
  731. goto error;
  732. #if OPENSSL_VERSION_NUMBER >= 0x00907000L /*0.9.7*/
  733. case SSL_ERROR_WANT_CONNECT:
  734. /* only if the underlying BIO is not yet connected
  735. and the call would block in connect().
  736. (not possible in our case) */
  737. BUG("unexpected SSL_ERROR_WANT_CONNECT\n");
  738. break;
  739. case SSL_ERROR_WANT_ACCEPT:
  740. /* only if the underlying BIO is not yet connected
  741. and call would block in accept()
  742. (not possible in our case) */
  743. BUG("unexpected SSL_ERROR_WANT_ACCEPT\n");
  744. break;
  745. #endif
  746. case SSL_ERROR_WANT_X509_LOOKUP:
  747. /* can only appear on client application and it indicates that
  748. an installed client cert. callback should be called again
  749. (it returned < 0 indicated that it wants to be called
  750. later). Not possible in our case */
  751. BUG("unsupported SSL_ERROR_WANT_X509_LOOKUP");
  752. goto bug;
  753. case SSL_ERROR_SYSCALL:
  754. TLS_ERR_RET(x, err_src);
  755. if (!x) {
  756. if (n == 0) {
  757. WARN("Unexpected EOF\n");
  758. } else
  759. /* should never happen */
  760. BUG("IO error (%d) %s\n", errno, strerror(errno));
  761. }
  762. goto error;
  763. default:
  764. TLS_ERR(err_src);
  765. BUG("unexpected SSL error %d\n", ssl_error);
  766. goto bug;
  767. }
  768. } else if (unlikely(n < (len - offs))) {
  769. /* partial ssl write (possible if SSL_MODE_ENABLE_PARTIAL_WRITE) =>
  770. retry with the rest */
  771. TLS_WR_TRACE("(%p) partial write (%d < %d, offset %d), retry\n",
  772. c, n, len - offs, offs);
  773. offs += n;
  774. goto redo_wr;
  775. }
  776. tls_set_mbufs(c, 0, 0);
  777. end:
  778. *pbuf = (const char*)wr.buf;
  779. *plen = wr.used;
  780. TLS_WR_TRACE("(%p) end (offs %d, rest_buf=%p rest_len=%d 0x%0x) => %d \n",
  781. c, offs, *rest_buf, *rest_len, send_flags->f, *plen);
  782. return *plen;
  783. error:
  784. /*error_send:*/
  785. error_wq_full:
  786. bug:
  787. tls_set_mbufs(c, 0, 0);
  788. TLS_WR_TRACE("(%p) end error (offs %d, %d encoded) => -1\n",
  789. c, offs, wr.used);
  790. return -1;
  791. ssl_eof:
  792. c->state = S_CONN_EOF;
  793. c->flags |= F_CONN_FORCE_EOF;
  794. *pbuf = (const char*)wr.buf;
  795. *plen = wr.used;
  796. DBG("TLS connection has been closed\n");
  797. TLS_WR_TRACE("(%p) end EOF (offs %d) => (%d\n",
  798. c, offs, *plen);
  799. return *plen;
  800. }
  801. /** tls read.
  802. * Each modification of ssl data structures has to be protected, another process * might ask for the same connection and attempt write to it which would
  803. * result in updating the ssl structures.
  804. * WARNING: must be called whic c->write_lock _unlocked_.
  805. * @param c - tcp connection pointer. The following flags might be set:
  806. * @param flags - value/result:
  807. * input: RD_CONN_FORCE_EOF - force EOF after the first
  808. * successful read (bytes_read >=0 )
  809. * output: RD_CONN_SHORT_READ if the read exhausted
  810. * all the bytes in the socket read buffer.
  811. * RD_CONN_EOF if EOF detected (0 bytes read)
  812. * or forced via RD_CONN_FORCE_EOF.
  813. * RD_CONN_REPEAT_READ if this function should
  814. * be called again (e.g. has some data
  815. * buffered internally that didn't fit in
  816. * tcp_req).
  817. * Note: RD_CONN_SHORT_READ & RD_CONN_EOF should be cleared
  818. * before calling this function when there is new
  819. * data (e.g. POLLIN), but not if the called is
  820. * retried because of RD_CONN_REPEAT_READ and there
  821. * is no information about the socket having more
  822. * read data available.
  823. * @return bytes decrypted on success, -1 on error (it also sets some
  824. * tcp connection flags and might set c->state and r->error on
  825. * EOF or error).
  826. */
  827. int tls_read_f(struct tcp_connection* c, int* flags)
  828. {
  829. struct tcp_req* r;
  830. int bytes_free, bytes_read, read_size, ssl_error, ssl_read;
  831. SSL* ssl;
  832. unsigned char rd_buf[TLS_RD_MBUF_SZ];
  833. unsigned char wr_buf[TLS_WR_MBUF_SZ];
  834. struct tls_mbuf rd, wr;
  835. struct tls_extra_data* tls_c;
  836. struct tls_rd_buf* enc_rd_buf;
  837. int n, flush_flags;
  838. char* err_src;
  839. int x;
  840. int tls_dbg;
  841. TLS_RD_TRACE("(%p, %p (%d)) start (%s -> %s:%d*)\n",
  842. c, flags, *flags,
  843. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  844. ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port);
  845. ssl_read = 0;
  846. r = &c->req;
  847. enc_rd_buf = 0;
  848. *flags &= ~RD_CONN_REPEAT_READ;
  849. if (unlikely(tls_fix_connection(c) < 0)) {
  850. TLS_RD_TRACE("(%p, %p) end: tls_fix_connection failed =>"
  851. " immediate error exit\n", c, flags);
  852. return -1;
  853. }
  854. /* here it's safe to use c->extra_data in read-only mode.
  855. If it's != 0 is changed only on destroy. It's not possible to have
  856. parallel reads.*/
  857. tls_c = c->extra_data;
  858. bytes_free = c->req.b_size - (int)(r->pos - r->buf);
  859. if (unlikely(bytes_free == 0)) {
  860. ERR("Buffer overrun, dropping\n");
  861. r->error = TCP_REQ_OVERRUN;
  862. return -1;
  863. }
  864. redo_read:
  865. /* if data queued from a previous read(), use it (don't perform
  866. * a real read()).
  867. */
  868. if (unlikely(tls_c->enc_rd_buf)) {
  869. /* use queued data */
  870. /* safe to use without locks, because only read changes it and
  871. there can't be parallel reads on the same connection */
  872. enc_rd_buf = tls_c->enc_rd_buf;
  873. tls_c->enc_rd_buf = 0;
  874. TLS_RD_TRACE("(%p, %p) using queued data (%p: %p %d bytes)\n", c,
  875. flags, enc_rd_buf, enc_rd_buf->buf + enc_rd_buf->pos,
  876. enc_rd_buf->size - enc_rd_buf->pos);
  877. tls_mbuf_init(&rd, enc_rd_buf->buf + enc_rd_buf->pos,
  878. enc_rd_buf->size - enc_rd_buf->pos);
  879. rd.used = enc_rd_buf->size - enc_rd_buf->pos;
  880. } else {
  881. /* if we were using using queued data before, free & reset the
  882. the queued read data before performing the real read() */
  883. if (unlikely(enc_rd_buf)) {
  884. TLS_RD_TRACE("(%p, %p) reset prev. used enc_rd_buf (%p)\n", c,
  885. flags, enc_rd_buf);
  886. shm_free(enc_rd_buf);
  887. enc_rd_buf = 0;
  888. }
  889. /* real read() */
  890. tls_mbuf_init(&rd, rd_buf, sizeof(rd_buf));
  891. /* read() only if no previously detected EOF, or previous
  892. short read (which means the socket buffer was emptied) */
  893. if (likely(!(*flags & (RD_CONN_EOF|RD_CONN_SHORT_READ)))) {
  894. /* don't read more then the free bytes in the tcp req buffer */
  895. read_size = MIN_unsigned(rd.size, bytes_free);
  896. bytes_read = tcp_read_data(c->fd, c, (char*)rd.buf, read_size,
  897. flags);
  898. TLS_RD_TRACE("(%p, %p) tcp_read_data(..., %d, *%d) => %d bytes\n",
  899. c, flags, read_size, *flags, bytes_read);
  900. /* try SSL_read even on 0 bytes read, it might have
  901. internally buffered data */
  902. if (unlikely(bytes_read < 0)) {
  903. goto error;
  904. }
  905. rd.used = bytes_read;
  906. }
  907. }
  908. continue_ssl_read:
  909. tls_mbuf_init(&wr, wr_buf, sizeof(wr_buf));
  910. ssl_error = SSL_ERROR_NONE;
  911. err_src = "TLS read:";
  912. /* we have to avoid to run in the same time
  913. * with a tls_write because of the
  914. * update bio stuff (we don't want a write
  915. * stealing the wbio or rbio under us or vice versa)
  916. * => lock on con->write_lock (ugly hack) */
  917. lock_get(&c->write_lock);
  918. tls_set_mbufs(c, &rd, &wr);
  919. ssl = tls_c->ssl;
  920. n = 0;
  921. if (unlikely(tls_write_wants_read(tls_c) &&
  922. !(*flags & RD_CONN_EOF))) {
  923. n = tls_ct_wq_flush(c, &tls_c->ct_wq, &flush_flags,
  924. &ssl_error);
  925. TLS_RD_TRACE("(%p, %p) tls write on read (WRITE_WANTS_READ):"
  926. " ct_wq_flush()=> %d (ff=%d ssl_error=%d))\n",
  927. c, flags, n, flush_flags, ssl_error);
  928. if (unlikely(n < 0 )) {
  929. tls_set_mbufs(c, 0, 0);
  930. lock_release(&c->write_lock);
  931. ERR("write flush error (%d)\n", n);
  932. goto error;
  933. }
  934. if (likely(flush_flags & F_BUFQ_EMPTY))
  935. tls_c->flags &= ~F_TLS_CON_WR_WANTS_RD;
  936. if (unlikely(flush_flags & F_BUFQ_ERROR_FLUSH))
  937. err_src = "TLS write:";
  938. }
  939. if (likely(ssl_error == SSL_ERROR_NONE)) {
  940. if (unlikely(tls_c->state == S_TLS_CONNECTING)) {
  941. n = tls_connect(c, &ssl_error);
  942. TLS_RD_TRACE("(%p, %p) tls_connect() => %d (err=%d)\n",
  943. c, flags, n, ssl_error);
  944. if (unlikely(n>=1)) {
  945. n = SSL_read(ssl, r->pos, bytes_free);
  946. } else {
  947. /* tls_connect failed/needs more IO */
  948. if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE)) {
  949. lock_release(&c->write_lock);
  950. goto error;
  951. }
  952. err_src = "TLS connect:";
  953. goto ssl_read_skipped;
  954. }
  955. } else if (unlikely(tls_c->state == S_TLS_ACCEPTING)) {
  956. n = tls_accept(c, &ssl_error);
  957. TLS_RD_TRACE("(%p, %p) tls_accept() => %d (err=%d)\n",
  958. c, flags, n, ssl_error);
  959. if (unlikely(n>=1)) {
  960. n = SSL_read(ssl, r->pos, bytes_free);
  961. } else {
  962. /* tls_accept failed/needs more IO */
  963. if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE)) {
  964. lock_release(&c->write_lock);
  965. goto error;
  966. }
  967. err_src = "TLS accept:";
  968. goto ssl_read_skipped;
  969. }
  970. } else {
  971. /* if bytes in then decrypt read buffer into tcpconn req.
  972. buffer */
  973. n = SSL_read(ssl, r->pos, bytes_free);
  974. }
  975. /** handle SSL_read() return.
  976. * There are 3 main cases, each with several sub-cases, depending
  977. * on whether or not the output buffer was filled, if there
  978. * is still unconsumed input data in the input buffer (rd)
  979. * and if there is "cached" data in the internal openssl
  980. * buffers.
  981. * 0. error (n<=0):
  982. * SSL_ERROR_WANT_READ - input data fully
  983. * consumed, no more returnable cached data inside openssl
  984. * => exit.
  985. * SSL_ERROR_WANT_WRITE - should never happen (the write
  986. * buffer is big enough to handle any re-negociation).
  987. * SSL_ERROR_ZERO_RETURN - ssl level shutdown => exit.
  988. * other errors are unexpected.
  989. * 1. output buffer filled (n == bytes_free):
  990. * 1i. - still unconsumed input, nothing buffered by openssl
  991. * 1ip. - unconsumed input + buffered data by openssl (pending
  992. on the next SSL_read).
  993. * 1p. - completely consumed input, buffered data internally
  994. * by openssl (pending).
  995. * Likely to happen, about the only case when
  996. * SSL_pending() could be used (but only if readahead=0).
  997. * 1f. - consumed input, no buffered data.
  998. * 2. output buffer not fully filled (n < bytes_free):
  999. * 2i. - still unconsumed input, nothing buffered by openssl.
  1000. * This can appear if SSL readahead is 0 (SSL_read()
  1001. * tries to get only 1 record from the input).
  1002. * 2ip. - unconsumed input and buffered data by openssl.
  1003. * Unlikely to happen (e.g. readahead is 1, more
  1004. * records are buffered internally by openssl, but
  1005. * there was not enough space for buffering the whole
  1006. * input).
  1007. * 2p - consumed input, but buffered data by openssl.
  1008. * It happens especially when readahead is 1.
  1009. * 2f. - consumed input, no buffered data.
  1010. *
  1011. * One should repeat SSL_read() until and error is detected
  1012. * (0*) or the input and internal ssl buffers are fully consumed
  1013. * (1f or 2f). However in general is not possible to see if
  1014. * SSL_read() could return more data. SSL_pending() has very
  1015. * limited usability (basically it would return !=0 only if there
  1016. * was no enough space in the output buffer and only if this did
  1017. * not happen at a record boundary).
  1018. * The solution is to repeat SSL_read() until error or until
  1019. * the output buffer is filled (0* or 1*).
  1020. * In the later case, this whole function should be called again
  1021. * once there is more output space (set RD_CONN_REPEAT_READ).
  1022. */
  1023. if (unlikely(tls_c->flags & F_TLS_CON_RENEGOTIATION)) {
  1024. /* Fix CVE-2009-3555 - disable renegotiation if started by client
  1025. * - simulate SSL EOF to force close connection*/
  1026. tls_dbg = cfg_get(tls, tls_cfg, debug);
  1027. LOG(tls_dbg, "Reading on a renegotiation of connection (n:%d) (%d)\n",
  1028. n, SSL_get_error(ssl, n));
  1029. err_src = "TLS R-N read:";
  1030. ssl_error = SSL_ERROR_ZERO_RETURN;
  1031. } else {
  1032. if (unlikely(n <= 0)) {
  1033. ssl_error = SSL_get_error(ssl, n);
  1034. err_src = "TLS read:";
  1035. /* errors handled below, outside the lock */
  1036. } else {
  1037. ssl_error = SSL_ERROR_NONE;
  1038. r->pos += n;
  1039. ssl_read += n;
  1040. bytes_free -=n;
  1041. }
  1042. }
  1043. TLS_RD_TRACE("(%p, %p) SSL_read() => %d (err=%d) ssl_read=%d"
  1044. " *flags=%d tls_c->flags=%d\n",
  1045. c, flags, n, ssl_error, ssl_read, *flags,
  1046. tls_c->flags);
  1047. ssl_read_skipped:
  1048. ;
  1049. }
  1050. if (unlikely(wr.used != 0 && ssl_error != SSL_ERROR_ZERO_RETURN)) {
  1051. TLS_RD_TRACE("(%p, %p) tcpconn_send_unsafe %d bytes\n",
  1052. c, flags, wr.used);
  1053. /* something was written and it's not ssl EOF*/
  1054. if (unlikely(tcpconn_send_unsafe(c->fd, c, (char*)wr.buf,
  1055. wr.used, c->send_flags) < 0)) {
  1056. tls_set_mbufs(c, 0, 0);
  1057. lock_release(&c->write_lock);
  1058. TLS_RD_TRACE("(%p, %p) tcpconn_send_unsafe error\n", c, flags);
  1059. goto error_send;
  1060. }
  1061. }
  1062. /* quickly catch bugs: segfault if accessed and not set */
  1063. tls_set_mbufs(c, 0, 0);
  1064. lock_release(&c->write_lock);
  1065. switch(ssl_error) {
  1066. case SSL_ERROR_NONE:
  1067. if (unlikely(n < 0)) {
  1068. BUG("unexpected SSL_ERROR_NONE for n=%d\n", n);
  1069. goto error;
  1070. }
  1071. break;
  1072. case SSL_ERROR_ZERO_RETURN:
  1073. /* SSL EOF */
  1074. TLS_RD_TRACE("(%p, %p) SSL EOF (fd=%d)\n", c, flags, c->fd);
  1075. goto ssl_eof;
  1076. case SSL_ERROR_WANT_READ:
  1077. TLS_RD_TRACE("(%p, %p) SSL_ERROR_WANT_READ *flags=%d\n",
  1078. c, flags, *flags);
  1079. /* needs to read more data */
  1080. if (unlikely(rd.pos != rd.used)) {
  1081. /* data still in the read buffer */
  1082. BUG("SSL_ERROR_WANT_READ but data still in"
  1083. " the rbio (%p, %d bytes at %d)\n", rd.buf,
  1084. rd.used - rd.pos, rd.pos);
  1085. goto bug;
  1086. }
  1087. if (unlikely((*flags & (RD_CONN_EOF | RD_CONN_SHORT_READ)) == 0) &&
  1088. bytes_free){
  1089. /* there might still be data to read and there is space
  1090. to decrypt it in tcp_req (no byte has been written into
  1091. tcp_req in this case) */
  1092. TLS_RD_TRACE("(%p, %p) redo read *flags=%d bytes_free=%d\n",
  1093. c, flags, *flags, bytes_free);
  1094. goto redo_read;
  1095. }
  1096. goto end; /* no more data to read */
  1097. case SSL_ERROR_WANT_WRITE:
  1098. if (wr.used) {
  1099. /* something was written => buffer not big enough to hold
  1100. everything => reset buffer & retry (the tcp_write already
  1101. happened if we are here) */
  1102. TLS_RD_TRACE("(%p) SSL_ERROR_WANT_WRITE partial write"
  1103. " (written %d), retrying\n", c, wr.used);
  1104. goto continue_ssl_read;
  1105. }
  1106. /* else write buffer too small, nothing written */
  1107. BUG("write buffer too small (%d/%d bytes)\n",
  1108. wr.used, wr.size);
  1109. goto bug;
  1110. case SSL_ERROR_SSL:
  1111. /* protocol level error */
  1112. TLS_ERR(err_src);
  1113. goto error;
  1114. #if OPENSSL_VERSION_NUMBER >= 0x00907000L /*0.9.7*/
  1115. case SSL_ERROR_WANT_CONNECT:
  1116. /* only if the underlying BIO is not yet connected
  1117. and the call would block in connect().
  1118. (not possible in our case) */
  1119. BUG("unexpected SSL_ERROR_WANT_CONNECT\n");
  1120. goto bug;
  1121. case SSL_ERROR_WANT_ACCEPT:
  1122. /* only if the underlying BIO is not yet connected
  1123. and call would block in accept()
  1124. (not possible in our case) */
  1125. BUG("unexpected SSL_ERROR_WANT_ACCEPT\n");
  1126. goto bug;
  1127. #endif
  1128. case SSL_ERROR_WANT_X509_LOOKUP:
  1129. /* can only appear on client application and it indicates that
  1130. an installed client cert. callback should be called again
  1131. (it returned < 0 indicated that it wants to be called
  1132. later). Not possible in our case */
  1133. BUG("unsupported SSL_ERROR_WANT_X509_LOOKUP");
  1134. goto bug;
  1135. case SSL_ERROR_SYSCALL:
  1136. TLS_ERR_RET(x, err_src);
  1137. if (!x) {
  1138. if (n == 0) {
  1139. WARN("Unexpected EOF\n");
  1140. } else
  1141. /* should never happen */
  1142. BUG("IO error (%d) %s\n", errno, strerror(errno));
  1143. }
  1144. goto error;
  1145. default:
  1146. TLS_ERR(err_src);
  1147. BUG("unexpected SSL error %d\n", ssl_error);
  1148. goto bug;
  1149. }
  1150. if (unlikely(n < 0)) {
  1151. /* here n should always be >= 0 */
  1152. BUG("unexpected value (n = %d)\n", n);
  1153. goto bug;
  1154. }
  1155. if (unlikely(rd.pos != rd.used)) {
  1156. /* encrypted data still in the read buffer (SSL_read() did not
  1157. consume all of it) */
  1158. if (unlikely(n < 0))
  1159. /* here n should always be >= 0 */
  1160. BUG("unexpected value (n = %d)\n", n);
  1161. else {
  1162. if (unlikely(bytes_free != 0)) {
  1163. /* 2i or 2ip: unconsumed input and output buffer not filled =>
  1164. retry ssl read (SSL_read() will read will stop at
  1165. record boundaries, unless readahead==1).
  1166. No tcp_read() is attempted, since that would reset the
  1167. current no-yet-consumed input data.
  1168. */
  1169. TLS_RD_TRACE("(%p, %p) input not fully consumed =>"
  1170. " retry SSL_read"
  1171. " (pos: %d, remaining %d, output free %d)\n",
  1172. c, flags, rd.pos, rd.used-rd.pos, bytes_free);
  1173. goto continue_ssl_read;
  1174. }
  1175. /* 1i or 1ip: bytes_free == 0
  1176. (unconsumed input, but filled output buffer) =>
  1177. queue read data, and exit asking for repeating the call
  1178. once there is some space in the output buffer.
  1179. */
  1180. if (likely(!enc_rd_buf)) {
  1181. TLS_RD_TRACE("(%p, %p) creating enc_rd_buf (for %d bytes)\n",
  1182. c, flags, rd.used - rd.pos);
  1183. enc_rd_buf = shm_malloc(sizeof(*enc_rd_buf) -
  1184. sizeof(enc_rd_buf->buf) +
  1185. rd.used - rd.pos);
  1186. if (unlikely(enc_rd_buf == 0)) {
  1187. ERR("memory allocation error (%d bytes requested)\n",
  1188. (int)(sizeof(*enc_rd_buf) + sizeof(enc_rd_buf->buf) +
  1189. rd.used - rd.pos));
  1190. goto error;
  1191. }
  1192. enc_rd_buf->pos = 0;
  1193. enc_rd_buf->size = rd.used - rd.pos;
  1194. memcpy(enc_rd_buf->buf, rd.buf + rd.pos,
  1195. enc_rd_buf->size);
  1196. } else if ((enc_rd_buf->buf + enc_rd_buf->pos) == rd.buf) {
  1197. TLS_RD_TRACE("(%p, %p) enc_rd_buf already in use,"
  1198. " updating pos %d\n",
  1199. c, flags, enc_rd_buf->pos);
  1200. enc_rd_buf->pos += rd.pos;
  1201. } else {
  1202. BUG("enc_rd_buf->buf = %p, pos = %d, rd_buf.buf = %p\n",
  1203. enc_rd_buf->buf, enc_rd_buf->pos, rd.buf);
  1204. goto bug;
  1205. }
  1206. if (unlikely(tls_c->enc_rd_buf))
  1207. BUG("tls_c->enc_rd_buf!=0 (%p)\n", tls_c->enc_rd_buf);
  1208. /* there can't be 2 reads in parallel, so no locking is needed
  1209. here */
  1210. tls_c->enc_rd_buf = enc_rd_buf;
  1211. enc_rd_buf = 0;
  1212. *flags |= RD_CONN_REPEAT_READ;
  1213. }
  1214. } else if (bytes_free != 0) {
  1215. /* 2f or 2p: input fully consumed (rd.pos == rd.used),
  1216. output buffer not filled, still possible to have pending
  1217. data buffered by openssl */
  1218. if (unlikely((*flags & (RD_CONN_EOF|RD_CONN_SHORT_READ)) == 0)) {
  1219. /* still space in the tcp unenc. req. buffer, no SSL_read error,
  1220. not a short read and not an EOF (possible more data in
  1221. the socket buffer) => try a new tcp read too */
  1222. TLS_RD_TRACE("(%p, %p) retry read (still space and no short"
  1223. " tcp read: %d)\n", c, flags, *flags);
  1224. goto redo_read;
  1225. } else {
  1226. /* don't tcp_read() anymore, but there might still be data
  1227. buffered internally by openssl (e.g. if readahead==1) =>
  1228. retry SSL_read() with the current full input buffer
  1229. (if no more internally SSL buffered data => WANT_READ => exit).
  1230. */
  1231. TLS_RD_TRACE("(%p, %p) retry SSL_read only (*flags =%d)\n",
  1232. c, flags, *flags);
  1233. goto continue_ssl_read;
  1234. }
  1235. } else {
  1236. /* 1p or 1f: rd.pos == rd.used && bytes_free == 0
  1237. (input fully consumed && output buffer filled) */
  1238. /* ask for a repeat when there is more buffer space
  1239. (there is no definitive way to know if ssl doesn't still have
  1240. some internal buffered data until we get WANT_READ, see
  1241. SSL_read() comment above) */
  1242. *flags |= RD_CONN_REPEAT_READ;
  1243. TLS_RD_TRACE("(%p, %p) output filled, exit asking to be called again"
  1244. " (*flags =%d)\n", c, flags, *flags);
  1245. }
  1246. end:
  1247. if (enc_rd_buf)
  1248. shm_free(enc_rd_buf);
  1249. TLS_RD_TRACE("(%p, %p) end => %d (*flags=%d)\n",
  1250. c, flags, ssl_read, *flags);
  1251. return ssl_read;
  1252. ssl_eof:
  1253. /* behave as an EOF would have been received at the tcp level */
  1254. if (enc_rd_buf)
  1255. shm_free(enc_rd_buf);
  1256. c->state = S_CONN_EOF;
  1257. *flags |= RD_CONN_EOF;
  1258. TLS_RD_TRACE("(%p, %p) end EOF => %d (*flags=%d)\n",
  1259. c, flags, ssl_read, *flags);
  1260. return ssl_read;
  1261. error_send:
  1262. error:
  1263. bug:
  1264. if (enc_rd_buf)
  1265. shm_free(enc_rd_buf);
  1266. r->error=TCP_READ_ERROR;
  1267. TLS_RD_TRACE("(%p, %p) end error => %d (*flags=%d)\n",
  1268. c, flags, ssl_read, *flags);
  1269. return -1;
  1270. }