tcptls.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2007 - 2008, Digium, Inc.
  5. *
  6. * Luigi Rizzo (TCP and TLS server code)
  7. * Brett Bryant <brettbryant@gmail.com> (updated for client support)
  8. *
  9. * See http://www.asterisk.org for more information about
  10. * the Asterisk project. Please do not directly contact
  11. * any of the maintainers of this project for assistance;
  12. * the project provides a web site, mailing lists and IRC
  13. * channels for your use.
  14. *
  15. * This program is free software, distributed under the terms of
  16. * the GNU General Public License Version 2. See the LICENSE file
  17. * at the top of the source tree.
  18. */
  19. /*!
  20. * \file
  21. * \brief Code to support TCP and TLS server/client
  22. *
  23. * \author Luigi Rizzo
  24. * \author Brett Bryant <brettbryant@gmail.com>
  25. */
  26. /*** MODULEINFO
  27. <support_level>core</support_level>
  28. ***/
  29. #include "asterisk.h"
  30. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  31. #ifdef HAVE_FCNTL_H
  32. #include <fcntl.h>
  33. #endif
  34. #include <signal.h>
  35. #include <sys/signal.h>
  36. #include "asterisk/compat.h"
  37. #include "asterisk/tcptls.h"
  38. #include "asterisk/http.h"
  39. #include "asterisk/utils.h"
  40. #include "asterisk/strings.h"
  41. #include "asterisk/options.h"
  42. #include "asterisk/manager.h"
  43. #include "asterisk/astobj2.h"
  44. #include "asterisk/pbx.h"
  45. /*! ao2 object used for the FILE stream fopencookie()/funopen() cookie. */
  46. struct ast_tcptls_stream {
  47. /*! SSL state if not NULL */
  48. SSL *ssl;
  49. /*!
  50. * \brief Start time from when an I/O sequence must complete
  51. * by struct ast_tcptls_stream.timeout.
  52. *
  53. * \note If struct ast_tcptls_stream.start.tv_sec is zero then
  54. * start time is the current I/O request.
  55. */
  56. struct timeval start;
  57. /*!
  58. * \brief The socket returned by accept().
  59. *
  60. * \note Set to -1 if the stream is closed.
  61. */
  62. int fd;
  63. /*!
  64. * \brief Timeout in ms relative to struct ast_tcptls_stream.start
  65. * to wait for an event on struct ast_tcptls_stream.fd.
  66. *
  67. * \note Set to -1 to disable timeout.
  68. * \note The socket needs to be set to non-blocking for the timeout
  69. * feature to work correctly.
  70. */
  71. int timeout;
  72. /*! TRUE if stream can exclusively wait for fd input. */
  73. int exclusive_input;
  74. };
  75. void ast_tcptls_stream_set_timeout_disable(struct ast_tcptls_stream *stream)
  76. {
  77. ast_assert(stream != NULL);
  78. stream->timeout = -1;
  79. }
  80. void ast_tcptls_stream_set_timeout_inactivity(struct ast_tcptls_stream *stream, int timeout)
  81. {
  82. ast_assert(stream != NULL);
  83. stream->start.tv_sec = 0;
  84. stream->timeout = timeout;
  85. }
  86. void ast_tcptls_stream_set_timeout_sequence(struct ast_tcptls_stream *stream, struct timeval start, int timeout)
  87. {
  88. ast_assert(stream != NULL);
  89. stream->start = start;
  90. stream->timeout = timeout;
  91. }
  92. void ast_tcptls_stream_set_exclusive_input(struct ast_tcptls_stream *stream, int exclusive_input)
  93. {
  94. ast_assert(stream != NULL);
  95. stream->exclusive_input = exclusive_input;
  96. }
  97. /*!
  98. * \internal
  99. * \brief fopencookie()/funopen() stream read function.
  100. *
  101. * \param cookie Stream control data.
  102. * \param buf Where to put read data.
  103. * \param size Size of the buffer.
  104. *
  105. * \retval number of bytes put into buf.
  106. * \retval 0 on end of file.
  107. * \retval -1 on error.
  108. */
  109. static HOOK_T tcptls_stream_read(void *cookie, char *buf, LEN_T size)
  110. {
  111. struct ast_tcptls_stream *stream = cookie;
  112. struct timeval start;
  113. int ms;
  114. int res;
  115. if (!size) {
  116. /* You asked for no data you got no data. */
  117. return 0;
  118. }
  119. if (!stream || stream->fd == -1) {
  120. errno = EBADF;
  121. return -1;
  122. }
  123. if (stream->start.tv_sec) {
  124. start = stream->start;
  125. } else {
  126. start = ast_tvnow();
  127. }
  128. #if defined(DO_SSL)
  129. if (stream->ssl) {
  130. for (;;) {
  131. res = SSL_read(stream->ssl, buf, size);
  132. if (0 < res) {
  133. /* We read some payload data. */
  134. return res;
  135. }
  136. switch (SSL_get_error(stream->ssl, res)) {
  137. case SSL_ERROR_ZERO_RETURN:
  138. /* Report EOF for a shutdown */
  139. ast_debug(1, "TLS clean shutdown alert reading data\n");
  140. return 0;
  141. case SSL_ERROR_WANT_READ:
  142. if (!stream->exclusive_input) {
  143. /* We cannot wait for data now. */
  144. errno = EAGAIN;
  145. return -1;
  146. }
  147. while ((ms = ast_remaining_ms(start, stream->timeout))) {
  148. res = ast_wait_for_input(stream->fd, ms);
  149. if (0 < res) {
  150. /* Socket is ready to be read. */
  151. break;
  152. }
  153. if (res < 0) {
  154. if (errno == EINTR || errno == EAGAIN) {
  155. /* Try again. */
  156. continue;
  157. }
  158. ast_debug(1, "TLS socket error waiting for read data: %s\n",
  159. strerror(errno));
  160. return -1;
  161. }
  162. }
  163. break;
  164. case SSL_ERROR_WANT_WRITE:
  165. while ((ms = ast_remaining_ms(start, stream->timeout))) {
  166. res = ast_wait_for_output(stream->fd, ms);
  167. if (0 < res) {
  168. /* Socket is ready to be written. */
  169. break;
  170. }
  171. if (res < 0) {
  172. if (errno == EINTR || errno == EAGAIN) {
  173. /* Try again. */
  174. continue;
  175. }
  176. ast_debug(1, "TLS socket error waiting for write space: %s\n",
  177. strerror(errno));
  178. return -1;
  179. }
  180. }
  181. break;
  182. default:
  183. /* Report EOF for an undecoded SSL or transport error. */
  184. ast_debug(1, "TLS transport or SSL error reading data\n");
  185. return 0;
  186. }
  187. if (!ms) {
  188. /* Report EOF for a timeout */
  189. ast_debug(1, "TLS timeout reading data\n");
  190. return 0;
  191. }
  192. }
  193. }
  194. #endif /* defined(DO_SSL) */
  195. for (;;) {
  196. res = read(stream->fd, buf, size);
  197. if (0 <= res || !stream->exclusive_input) {
  198. /* Got data or we cannot wait for it. */
  199. return res;
  200. }
  201. if (errno != EINTR && errno != EAGAIN) {
  202. /* Not a retryable error. */
  203. ast_debug(1, "TCP socket error reading data: %s\n",
  204. strerror(errno));
  205. return -1;
  206. }
  207. ms = ast_remaining_ms(start, stream->timeout);
  208. if (!ms) {
  209. /* Report EOF for a timeout */
  210. ast_debug(1, "TCP timeout reading data\n");
  211. return 0;
  212. }
  213. ast_wait_for_input(stream->fd, ms);
  214. }
  215. }
  216. /*!
  217. * \internal
  218. * \brief fopencookie()/funopen() stream write function.
  219. *
  220. * \param cookie Stream control data.
  221. * \param buf Where to get data to write.
  222. * \param size Size of the buffer.
  223. *
  224. * \retval number of bytes written from buf.
  225. * \retval -1 on error.
  226. */
  227. static HOOK_T tcptls_stream_write(void *cookie, const char *buf, LEN_T size)
  228. {
  229. struct ast_tcptls_stream *stream = cookie;
  230. struct timeval start;
  231. int ms;
  232. int res;
  233. int written;
  234. int remaining;
  235. if (!size) {
  236. /* You asked to write no data you wrote no data. */
  237. return 0;
  238. }
  239. if (!stream || stream->fd == -1) {
  240. errno = EBADF;
  241. return -1;
  242. }
  243. if (stream->start.tv_sec) {
  244. start = stream->start;
  245. } else {
  246. start = ast_tvnow();
  247. }
  248. #if defined(DO_SSL)
  249. if (stream->ssl) {
  250. written = 0;
  251. remaining = size;
  252. for (;;) {
  253. res = SSL_write(stream->ssl, buf + written, remaining);
  254. if (res == remaining) {
  255. /* Everything was written. */
  256. return size;
  257. }
  258. if (0 < res) {
  259. /* Successfully wrote part of the buffer. Try to write the rest. */
  260. written += res;
  261. remaining -= res;
  262. continue;
  263. }
  264. switch (SSL_get_error(stream->ssl, res)) {
  265. case SSL_ERROR_ZERO_RETURN:
  266. ast_debug(1, "TLS clean shutdown alert writing data\n");
  267. if (written) {
  268. /* Report partial write. */
  269. return written;
  270. }
  271. errno = EBADF;
  272. return -1;
  273. case SSL_ERROR_WANT_READ:
  274. ms = ast_remaining_ms(start, stream->timeout);
  275. if (!ms) {
  276. /* Report partial write. */
  277. ast_debug(1, "TLS timeout writing data (want read)\n");
  278. return written;
  279. }
  280. ast_wait_for_input(stream->fd, ms);
  281. break;
  282. case SSL_ERROR_WANT_WRITE:
  283. ms = ast_remaining_ms(start, stream->timeout);
  284. if (!ms) {
  285. /* Report partial write. */
  286. ast_debug(1, "TLS timeout writing data (want write)\n");
  287. return written;
  288. }
  289. ast_wait_for_output(stream->fd, ms);
  290. break;
  291. default:
  292. /* Undecoded SSL or transport error. */
  293. ast_debug(1, "TLS transport or SSL error writing data\n");
  294. if (written) {
  295. /* Report partial write. */
  296. return written;
  297. }
  298. errno = EBADF;
  299. return -1;
  300. }
  301. }
  302. }
  303. #endif /* defined(DO_SSL) */
  304. written = 0;
  305. remaining = size;
  306. for (;;) {
  307. res = write(stream->fd, buf + written, remaining);
  308. if (res == remaining) {
  309. /* Yay everything was written. */
  310. return size;
  311. }
  312. if (0 < res) {
  313. /* Successfully wrote part of the buffer. Try to write the rest. */
  314. written += res;
  315. remaining -= res;
  316. continue;
  317. }
  318. if (errno != EINTR && errno != EAGAIN) {
  319. /* Not a retryable error. */
  320. ast_debug(1, "TCP socket error writing: %s\n", strerror(errno));
  321. if (written) {
  322. return written;
  323. }
  324. return -1;
  325. }
  326. ms = ast_remaining_ms(start, stream->timeout);
  327. if (!ms) {
  328. /* Report partial write. */
  329. ast_debug(1, "TCP timeout writing data\n");
  330. return written;
  331. }
  332. ast_wait_for_output(stream->fd, ms);
  333. }
  334. }
  335. /*!
  336. * \internal
  337. * \brief fopencookie()/funopen() stream close function.
  338. *
  339. * \param cookie Stream control data.
  340. *
  341. * \retval 0 on success.
  342. * \retval -1 on error.
  343. */
  344. static int tcptls_stream_close(void *cookie)
  345. {
  346. struct ast_tcptls_stream *stream = cookie;
  347. if (!stream) {
  348. errno = EBADF;
  349. return -1;
  350. }
  351. if (stream->fd != -1) {
  352. #if defined(DO_SSL)
  353. if (stream->ssl) {
  354. int res;
  355. /*
  356. * According to the TLS standard, it is acceptable for an
  357. * application to only send its shutdown alert and then
  358. * close the underlying connection without waiting for
  359. * the peer's response (this way resources can be saved,
  360. * as the process can already terminate or serve another
  361. * connection).
  362. */
  363. res = SSL_shutdown(stream->ssl);
  364. if (res < 0) {
  365. ast_log(LOG_ERROR, "SSL_shutdown() failed: %d\n",
  366. SSL_get_error(stream->ssl, res));
  367. }
  368. if (!stream->ssl->server) {
  369. /* For client threads, ensure that the error stack is cleared */
  370. ERR_remove_state(0);
  371. }
  372. SSL_free(stream->ssl);
  373. stream->ssl = NULL;
  374. }
  375. #endif /* defined(DO_SSL) */
  376. /*
  377. * Issuing shutdown() is necessary here to avoid a race
  378. * condition where the last data written may not appear
  379. * in the TCP stream. See ASTERISK-23548
  380. */
  381. shutdown(stream->fd, SHUT_RDWR);
  382. if (close(stream->fd)) {
  383. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  384. }
  385. stream->fd = -1;
  386. }
  387. ao2_t_ref(stream, -1, "Closed tcptls stream cookie");
  388. return 0;
  389. }
  390. /*!
  391. * \internal
  392. * \brief fopencookie()/funopen() stream destructor function.
  393. *
  394. * \param cookie Stream control data.
  395. *
  396. * \return Nothing
  397. */
  398. static void tcptls_stream_dtor(void *cookie)
  399. {
  400. #ifdef AST_DEVMODE
  401. /* Since the ast_assert below is the only one using stream,
  402. * and ast_assert is only available with AST_DEVMODE, we
  403. * put this in a conditional to avoid compiler warnings. */
  404. struct ast_tcptls_stream *stream = cookie;
  405. #endif
  406. ast_assert(stream->fd == -1);
  407. }
  408. /*!
  409. * \internal
  410. * \brief fopencookie()/funopen() stream allocation function.
  411. *
  412. * \retval stream_cookie on success.
  413. * \retval NULL on error.
  414. */
  415. static struct ast_tcptls_stream *tcptls_stream_alloc(void)
  416. {
  417. struct ast_tcptls_stream *stream;
  418. stream = ao2_alloc_options(sizeof(*stream), tcptls_stream_dtor,
  419. AO2_ALLOC_OPT_LOCK_NOLOCK);
  420. if (stream) {
  421. stream->fd = -1;
  422. stream->timeout = -1;
  423. }
  424. return stream;
  425. }
  426. /*!
  427. * \internal
  428. * \brief Open a custom FILE stream for tcptls.
  429. *
  430. * \param stream Stream cookie control data.
  431. * \param ssl SSL state if not NULL.
  432. * \param fd Socket file descriptor.
  433. * \param timeout ms to wait for an event on fd. -1 if timeout disabled.
  434. *
  435. * \retval fp on success.
  436. * \retval NULL on error.
  437. */
  438. static FILE *tcptls_stream_fopen(struct ast_tcptls_stream *stream, SSL *ssl, int fd, int timeout)
  439. {
  440. FILE *fp;
  441. #if defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
  442. static const cookie_io_functions_t cookie_funcs = {
  443. tcptls_stream_read,
  444. tcptls_stream_write,
  445. NULL,
  446. tcptls_stream_close
  447. };
  448. #endif /* defined(HAVE_FOPENCOOKIE) */
  449. if (fd == -1) {
  450. /* Socket not open. */
  451. return NULL;
  452. }
  453. stream->ssl = ssl;
  454. stream->fd = fd;
  455. stream->timeout = timeout;
  456. ao2_t_ref(stream, +1, "Opening tcptls stream cookie");
  457. #if defined(HAVE_FUNOPEN) /* the BSD interface */
  458. fp = funopen(stream, tcptls_stream_read, tcptls_stream_write, NULL,
  459. tcptls_stream_close);
  460. #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
  461. fp = fopencookie(stream, "w+", cookie_funcs);
  462. #else
  463. /* could add other methods here */
  464. ast_debug(2, "No stream FILE methods attempted!\n");
  465. fp = NULL;
  466. #endif
  467. if (!fp) {
  468. stream->fd = -1;
  469. ao2_t_ref(stream, -1, "Failed to open tcptls stream cookie");
  470. }
  471. return fp;
  472. }
  473. HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
  474. {
  475. if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
  476. ast_log(LOG_ERROR, "TCP/TLS read called on invalid stream.\n");
  477. errno = EIO;
  478. return -1;
  479. }
  480. return tcptls_stream_read(tcptls_session->stream_cookie, buf, count);
  481. }
  482. HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
  483. {
  484. if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
  485. ast_log(LOG_ERROR, "TCP/TLS write called on invalid stream.\n");
  486. errno = EIO;
  487. return -1;
  488. }
  489. return tcptls_stream_write(tcptls_session->stream_cookie, buf, count);
  490. }
  491. static void session_instance_destructor(void *obj)
  492. {
  493. struct ast_tcptls_session_instance *i = obj;
  494. if (i->stream_cookie) {
  495. ao2_t_ref(i->stream_cookie, -1, "Destroying tcptls session instance");
  496. i->stream_cookie = NULL;
  497. }
  498. ast_free(i->overflow_buf);
  499. }
  500. /*! \brief
  501. * creates a FILE * from the fd passed by the accept thread.
  502. * This operation is potentially expensive (certificate verification),
  503. * so we do it in the child thread context.
  504. *
  505. * \note must decrement ref count before returning NULL on error
  506. */
  507. static void *handle_tcptls_connection(void *data)
  508. {
  509. struct ast_tcptls_session_instance *tcptls_session = data;
  510. #ifdef DO_SSL
  511. int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
  512. int ret;
  513. char err[256];
  514. #endif
  515. /* TCP/TLS connections are associated with external protocols, and
  516. * should not be allowed to execute 'dangerous' functions. This may
  517. * need to be pushed down into the individual protocol handlers, but
  518. * this seems like a good general policy.
  519. */
  520. if (ast_thread_inhibit_escalations()) {
  521. ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
  522. ast_tcptls_close_session_file(tcptls_session);
  523. ao2_ref(tcptls_session, -1);
  524. return NULL;
  525. }
  526. tcptls_session->stream_cookie = tcptls_stream_alloc();
  527. if (!tcptls_session->stream_cookie) {
  528. ast_tcptls_close_session_file(tcptls_session);
  529. ao2_ref(tcptls_session, -1);
  530. return NULL;
  531. }
  532. /*
  533. * open a FILE * as appropriate.
  534. */
  535. if (!tcptls_session->parent->tls_cfg) {
  536. tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie, NULL,
  537. tcptls_session->fd, -1);
  538. if (tcptls_session->f) {
  539. if (setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
  540. ast_tcptls_close_session_file(tcptls_session);
  541. }
  542. }
  543. }
  544. #ifdef DO_SSL
  545. else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
  546. SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
  547. if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
  548. ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
  549. } else if ((tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie,
  550. tcptls_session->ssl, tcptls_session->fd, -1))) {
  551. if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
  552. || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
  553. X509 *peer;
  554. long res;
  555. peer = SSL_get_peer_certificate(tcptls_session->ssl);
  556. if (!peer) {
  557. ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
  558. ast_tcptls_close_session_file(tcptls_session);
  559. ao2_ref(tcptls_session, -1);
  560. return NULL;
  561. }
  562. res = SSL_get_verify_result(tcptls_session->ssl);
  563. if (res != X509_V_OK) {
  564. ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
  565. X509_free(peer);
  566. ast_tcptls_close_session_file(tcptls_session);
  567. ao2_ref(tcptls_session, -1);
  568. return NULL;
  569. }
  570. if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
  571. ASN1_STRING *str;
  572. unsigned char *str2;
  573. X509_NAME *name = X509_get_subject_name(peer);
  574. int pos = -1;
  575. int found = 0;
  576. for (;;) {
  577. /* Walk the certificate to check all available "Common Name" */
  578. /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
  579. pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
  580. if (pos < 0) {
  581. break;
  582. }
  583. str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
  584. ret = ASN1_STRING_to_UTF8(&str2, str);
  585. if (ret < 0) {
  586. continue;
  587. }
  588. if (str2) {
  589. if (strlen((char *) str2) != ret) {
  590. ast_log(LOG_WARNING, "Invalid certificate common name length (contains NULL bytes?)\n");
  591. } else if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2)) {
  592. found = 1;
  593. }
  594. ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
  595. OPENSSL_free(str2);
  596. }
  597. if (found) {
  598. break;
  599. }
  600. }
  601. if (!found) {
  602. ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
  603. X509_free(peer);
  604. ast_tcptls_close_session_file(tcptls_session);
  605. ao2_ref(tcptls_session, -1);
  606. return NULL;
  607. }
  608. }
  609. X509_free(peer);
  610. }
  611. }
  612. if (!tcptls_session->f) { /* no success opening descriptor stacking */
  613. SSL_free(tcptls_session->ssl);
  614. }
  615. }
  616. #endif /* DO_SSL */
  617. if (!tcptls_session->f) {
  618. ast_tcptls_close_session_file(tcptls_session);
  619. ast_log(LOG_WARNING, "FILE * open failed!\n");
  620. #ifndef DO_SSL
  621. if (tcptls_session->parent->tls_cfg) {
  622. ast_log(LOG_WARNING, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
  623. }
  624. #endif
  625. ao2_ref(tcptls_session, -1);
  626. return NULL;
  627. }
  628. if (tcptls_session->parent->worker_fn) {
  629. return tcptls_session->parent->worker_fn(tcptls_session);
  630. } else {
  631. return tcptls_session;
  632. }
  633. }
  634. void *ast_tcptls_server_root(void *data)
  635. {
  636. struct ast_tcptls_session_args *desc = data;
  637. int fd;
  638. struct ast_sockaddr addr;
  639. struct ast_tcptls_session_instance *tcptls_session;
  640. pthread_t launched;
  641. for (;;) {
  642. int i, flags;
  643. if (desc->periodic_fn) {
  644. desc->periodic_fn(desc);
  645. }
  646. i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
  647. if (i <= 0) {
  648. continue;
  649. }
  650. fd = ast_accept(desc->accept_fd, &addr);
  651. if (fd < 0) {
  652. if ((errno != EAGAIN) && (errno != EWOULDBLOCK) && (errno != EINTR) && (errno != ECONNABORTED)) {
  653. ast_log(LOG_WARNING, "Accept failed: %s\n", strerror(errno));
  654. break;
  655. }
  656. continue;
  657. }
  658. tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
  659. if (!tcptls_session) {
  660. ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
  661. if (close(fd)) {
  662. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  663. }
  664. continue;
  665. }
  666. tcptls_session->overflow_buf = ast_str_create(128);
  667. flags = fcntl(fd, F_GETFL);
  668. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  669. tcptls_session->fd = fd;
  670. tcptls_session->parent = desc;
  671. ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
  672. tcptls_session->client = 0;
  673. /* This thread is now the only place that controls the single ref to tcptls_session */
  674. if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
  675. ast_log(LOG_WARNING, "Unable to launch helper thread: %s\n", strerror(errno));
  676. ast_tcptls_close_session_file(tcptls_session);
  677. ao2_ref(tcptls_session, -1);
  678. }
  679. }
  680. return NULL;
  681. }
  682. static int __ssl_setup(struct ast_tls_config *cfg, int client)
  683. {
  684. #ifndef DO_SSL
  685. cfg->enabled = 0;
  686. return 0;
  687. #else
  688. int disable_ssl = 0;
  689. if (!cfg->enabled) {
  690. return 0;
  691. }
  692. /* Get rid of an old SSL_CTX since we're about to
  693. * allocate a new one
  694. */
  695. if (cfg->ssl_ctx) {
  696. SSL_CTX_free(cfg->ssl_ctx);
  697. cfg->ssl_ctx = NULL;
  698. }
  699. if (client) {
  700. #ifndef OPENSSL_NO_SSL2
  701. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
  702. ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  703. cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
  704. } else
  705. #endif
  706. #ifndef OPENSSL_NO_SSL3_METHOD
  707. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
  708. ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  709. cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
  710. } else
  711. #endif
  712. if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
  713. cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
  714. } else {
  715. disable_ssl = 1;
  716. cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  717. }
  718. } else {
  719. disable_ssl = 1;
  720. cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  721. }
  722. if (!cfg->ssl_ctx) {
  723. ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
  724. cfg->enabled = 0;
  725. return 0;
  726. }
  727. /* Due to the POODLE vulnerability, completely disable
  728. * SSLv2 and SSLv3 if we are not explicitly told to use
  729. * them. SSLv23_*_method supports TLSv1+.
  730. */
  731. if (disable_ssl) {
  732. long ssl_opts;
  733. ssl_opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
  734. SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
  735. }
  736. SSL_CTX_set_verify(cfg->ssl_ctx,
  737. ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
  738. NULL);
  739. if (!ast_strlen_zero(cfg->certfile)) {
  740. char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
  741. if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
  742. if (!client) {
  743. /* Clients don't need a certificate, but if its setup we can use it */
  744. ast_verb(0, "SSL error loading cert file. <%s>\n", cfg->certfile);
  745. cfg->enabled = 0;
  746. SSL_CTX_free(cfg->ssl_ctx);
  747. cfg->ssl_ctx = NULL;
  748. return 0;
  749. }
  750. }
  751. if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
  752. if (!client) {
  753. /* Clients don't need a private key, but if its setup we can use it */
  754. ast_verb(0, "SSL error loading private key file. <%s>\n", tmpprivate);
  755. cfg->enabled = 0;
  756. SSL_CTX_free(cfg->ssl_ctx);
  757. cfg->ssl_ctx = NULL;
  758. return 0;
  759. }
  760. }
  761. }
  762. if (!ast_strlen_zero(cfg->cipher)) {
  763. if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
  764. if (!client) {
  765. ast_verb(0, "SSL cipher error <%s>\n", cfg->cipher);
  766. cfg->enabled = 0;
  767. SSL_CTX_free(cfg->ssl_ctx);
  768. cfg->ssl_ctx = NULL;
  769. return 0;
  770. }
  771. }
  772. }
  773. if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
  774. if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
  775. ast_verb(0, "SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
  776. }
  777. }
  778. ast_verb(0, "SSL certificate ok\n");
  779. return 1;
  780. #endif
  781. }
  782. int ast_ssl_setup(struct ast_tls_config *cfg)
  783. {
  784. return __ssl_setup(cfg, 0);
  785. }
  786. void ast_ssl_teardown(struct ast_tls_config *cfg)
  787. {
  788. #ifdef DO_SSL
  789. if (cfg->ssl_ctx) {
  790. SSL_CTX_free(cfg->ssl_ctx);
  791. cfg->ssl_ctx = NULL;
  792. }
  793. #endif
  794. }
  795. struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
  796. {
  797. struct ast_tcptls_session_args *desc;
  798. int flags;
  799. if (!(desc = tcptls_session->parent)) {
  800. goto client_start_error;
  801. }
  802. if (ast_connect(desc->accept_fd, &desc->remote_address)) {
  803. ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
  804. desc->name,
  805. ast_sockaddr_stringify(&desc->remote_address),
  806. strerror(errno));
  807. goto client_start_error;
  808. }
  809. flags = fcntl(desc->accept_fd, F_GETFL);
  810. fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
  811. if (desc->tls_cfg) {
  812. desc->tls_cfg->enabled = 1;
  813. __ssl_setup(desc->tls_cfg, 1);
  814. }
  815. return handle_tcptls_connection(tcptls_session);
  816. client_start_error:
  817. if (desc) {
  818. close(desc->accept_fd);
  819. desc->accept_fd = -1;
  820. }
  821. ao2_ref(tcptls_session, -1);
  822. return NULL;
  823. }
  824. struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
  825. {
  826. int x = 1;
  827. struct ast_tcptls_session_instance *tcptls_session = NULL;
  828. /* Do nothing if nothing has changed */
  829. if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
  830. ast_debug(1, "Nothing changed in %s\n", desc->name);
  831. return NULL;
  832. }
  833. /* If we return early, there is no connection */
  834. ast_sockaddr_setnull(&desc->old_address);
  835. if (desc->accept_fd != -1) {
  836. close(desc->accept_fd);
  837. }
  838. desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
  839. AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
  840. if (desc->accept_fd < 0) {
  841. ast_log(LOG_WARNING, "Unable to allocate socket for %s: %s\n",
  842. desc->name, strerror(errno));
  843. return NULL;
  844. }
  845. /* if a local address was specified, bind to it so the connection will
  846. originate from the desired address */
  847. if (!ast_sockaddr_isnull(&desc->local_address)) {
  848. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  849. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  850. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  851. desc->name,
  852. ast_sockaddr_stringify(&desc->local_address),
  853. strerror(errno));
  854. goto error;
  855. }
  856. }
  857. if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor))) {
  858. goto error;
  859. }
  860. tcptls_session->overflow_buf = ast_str_create(128);
  861. tcptls_session->client = 1;
  862. tcptls_session->fd = desc->accept_fd;
  863. tcptls_session->parent = desc;
  864. tcptls_session->parent->worker_fn = NULL;
  865. ast_sockaddr_copy(&tcptls_session->remote_address,
  866. &desc->remote_address);
  867. /* Set current info */
  868. ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
  869. return tcptls_session;
  870. error:
  871. close(desc->accept_fd);
  872. desc->accept_fd = -1;
  873. if (tcptls_session) {
  874. ao2_ref(tcptls_session, -1);
  875. }
  876. return NULL;
  877. }
  878. void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
  879. {
  880. int flags;
  881. int x = 1;
  882. /* Do nothing if nothing has changed */
  883. if (!ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
  884. ast_debug(1, "Nothing changed in %s\n", desc->name);
  885. return;
  886. }
  887. /* If we return early, there is no one listening */
  888. ast_sockaddr_setnull(&desc->old_address);
  889. /* Shutdown a running server if there is one */
  890. if (desc->master != AST_PTHREADT_NULL) {
  891. pthread_cancel(desc->master);
  892. pthread_kill(desc->master, SIGURG);
  893. pthread_join(desc->master, NULL);
  894. }
  895. if (desc->accept_fd != -1) {
  896. close(desc->accept_fd);
  897. }
  898. /* If there's no new server, stop here */
  899. if (ast_sockaddr_isnull(&desc->local_address)) {
  900. ast_debug(2, "Server disabled: %s\n", desc->name);
  901. return;
  902. }
  903. desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
  904. AF_INET6 : AF_INET, SOCK_STREAM, 0);
  905. if (desc->accept_fd < 0) {
  906. ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
  907. return;
  908. }
  909. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  910. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  911. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  912. desc->name,
  913. ast_sockaddr_stringify(&desc->local_address),
  914. strerror(errno));
  915. goto error;
  916. }
  917. if (listen(desc->accept_fd, 10)) {
  918. ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
  919. goto error;
  920. }
  921. flags = fcntl(desc->accept_fd, F_GETFL);
  922. fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
  923. if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
  924. ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
  925. desc->name,
  926. ast_sockaddr_stringify(&desc->local_address),
  927. strerror(errno));
  928. goto error;
  929. }
  930. /* Set current info */
  931. ast_sockaddr_copy(&desc->old_address, &desc->local_address);
  932. return;
  933. error:
  934. close(desc->accept_fd);
  935. desc->accept_fd = -1;
  936. }
  937. void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
  938. {
  939. if (tcptls_session->f) {
  940. fflush(tcptls_session->f);
  941. if (fclose(tcptls_session->f)) {
  942. ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
  943. }
  944. tcptls_session->f = NULL;
  945. tcptls_session->fd = -1;
  946. } else if (tcptls_session->fd != -1) {
  947. /*
  948. * Issuing shutdown() is necessary here to avoid a race
  949. * condition where the last data written may not appear
  950. * in the TCP stream. See ASTERISK-23548
  951. */
  952. shutdown(tcptls_session->fd, SHUT_RDWR);
  953. if (close(tcptls_session->fd)) {
  954. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  955. }
  956. tcptls_session->fd = -1;
  957. } else {
  958. ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
  959. }
  960. }
  961. void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
  962. {
  963. if (desc->master != AST_PTHREADT_NULL) {
  964. pthread_cancel(desc->master);
  965. pthread_kill(desc->master, SIGURG);
  966. pthread_join(desc->master, NULL);
  967. desc->master = AST_PTHREADT_NULL;
  968. }
  969. if (desc->accept_fd != -1) {
  970. close(desc->accept_fd);
  971. }
  972. desc->accept_fd = -1;
  973. ast_debug(2, "Stopped server :: %s\n", desc->name);
  974. }
  975. int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
  976. {
  977. if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
  978. tls_cfg->enabled = ast_true(value) ? 1 : 0;
  979. } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
  980. ast_free(tls_cfg->certfile);
  981. tls_cfg->certfile = ast_strdup(value);
  982. } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
  983. ast_free(tls_cfg->pvtfile);
  984. tls_cfg->pvtfile = ast_strdup(value);
  985. } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
  986. ast_free(tls_cfg->cipher);
  987. tls_cfg->cipher = ast_strdup(value);
  988. } else if (!strcasecmp(varname, "tlscafile")) {
  989. ast_free(tls_cfg->cafile);
  990. tls_cfg->cafile = ast_strdup(value);
  991. } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
  992. ast_free(tls_cfg->capath);
  993. tls_cfg->capath = ast_strdup(value);
  994. } else if (!strcasecmp(varname, "tlsverifyclient")) {
  995. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
  996. } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
  997. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
  998. } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
  999. if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
  1000. ast_log(LOG_WARNING, "Invalid %s '%s'\n", varname, value);
  1001. } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
  1002. if (!strcasecmp(value, "tlsv1")) {
  1003. ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1004. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1005. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1006. } else if (!strcasecmp(value, "sslv3")) {
  1007. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1008. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1009. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1010. } else if (!strcasecmp(value, "sslv2")) {
  1011. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1012. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1013. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1014. }
  1015. } else {
  1016. return -1;
  1017. }
  1018. return 0;
  1019. }