tls_server.c 45 KB

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