tcptls.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. ao2_cleanup(i->private_data);
  500. }
  501. /*! \brief
  502. * creates a FILE * from the fd passed by the accept thread.
  503. * This operation is potentially expensive (certificate verification),
  504. * so we do it in the child thread context.
  505. *
  506. * \note must decrement ref count before returning NULL on error
  507. */
  508. static void *handle_tcptls_connection(void *data)
  509. {
  510. struct ast_tcptls_session_instance *tcptls_session = data;
  511. #ifdef DO_SSL
  512. int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
  513. int ret;
  514. char err[256];
  515. #endif
  516. /* TCP/TLS connections are associated with external protocols, and
  517. * should not be allowed to execute 'dangerous' functions. This may
  518. * need to be pushed down into the individual protocol handlers, but
  519. * this seems like a good general policy.
  520. */
  521. if (ast_thread_inhibit_escalations()) {
  522. ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
  523. ast_tcptls_close_session_file(tcptls_session);
  524. ao2_ref(tcptls_session, -1);
  525. return NULL;
  526. }
  527. tcptls_session->stream_cookie = tcptls_stream_alloc();
  528. if (!tcptls_session->stream_cookie) {
  529. ast_tcptls_close_session_file(tcptls_session);
  530. ao2_ref(tcptls_session, -1);
  531. return NULL;
  532. }
  533. /*
  534. * open a FILE * as appropriate.
  535. */
  536. if (!tcptls_session->parent->tls_cfg) {
  537. tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie, NULL,
  538. tcptls_session->fd, -1);
  539. if (tcptls_session->f) {
  540. if (setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
  541. ast_tcptls_close_session_file(tcptls_session);
  542. }
  543. }
  544. }
  545. #ifdef DO_SSL
  546. else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
  547. SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
  548. if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
  549. ast_log(LOG_ERROR, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
  550. } else if ((tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie,
  551. tcptls_session->ssl, tcptls_session->fd, -1))) {
  552. if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
  553. || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
  554. X509 *peer;
  555. long res;
  556. peer = SSL_get_peer_certificate(tcptls_session->ssl);
  557. if (!peer) {
  558. ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
  559. ast_tcptls_close_session_file(tcptls_session);
  560. ao2_ref(tcptls_session, -1);
  561. return NULL;
  562. }
  563. res = SSL_get_verify_result(tcptls_session->ssl);
  564. if (res != X509_V_OK) {
  565. ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
  566. X509_free(peer);
  567. ast_tcptls_close_session_file(tcptls_session);
  568. ao2_ref(tcptls_session, -1);
  569. return NULL;
  570. }
  571. if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
  572. ASN1_STRING *str;
  573. unsigned char *str2;
  574. X509_NAME *name = X509_get_subject_name(peer);
  575. int pos = -1;
  576. int found = 0;
  577. for (;;) {
  578. /* Walk the certificate to check all available "Common Name" */
  579. /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
  580. pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
  581. if (pos < 0) {
  582. break;
  583. }
  584. str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
  585. ret = ASN1_STRING_to_UTF8(&str2, str);
  586. if (ret < 0) {
  587. continue;
  588. }
  589. if (str2) {
  590. if (strlen((char *) str2) != ret) {
  591. ast_log(LOG_WARNING, "Invalid certificate common name length (contains NULL bytes?)\n");
  592. } else if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2)) {
  593. found = 1;
  594. }
  595. ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
  596. OPENSSL_free(str2);
  597. }
  598. if (found) {
  599. break;
  600. }
  601. }
  602. if (!found) {
  603. ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
  604. X509_free(peer);
  605. ast_tcptls_close_session_file(tcptls_session);
  606. ao2_ref(tcptls_session, -1);
  607. return NULL;
  608. }
  609. }
  610. X509_free(peer);
  611. }
  612. }
  613. if (!tcptls_session->f) { /* no success opening descriptor stacking */
  614. SSL_free(tcptls_session->ssl);
  615. }
  616. }
  617. #endif /* DO_SSL */
  618. if (!tcptls_session->f) {
  619. ast_tcptls_close_session_file(tcptls_session);
  620. ast_log(LOG_WARNING, "FILE * open failed!\n");
  621. #ifndef DO_SSL
  622. if (tcptls_session->parent->tls_cfg) {
  623. ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
  624. }
  625. #endif
  626. ao2_ref(tcptls_session, -1);
  627. return NULL;
  628. }
  629. if (tcptls_session->parent->worker_fn) {
  630. return tcptls_session->parent->worker_fn(tcptls_session);
  631. } else {
  632. return tcptls_session;
  633. }
  634. }
  635. void *ast_tcptls_server_root(void *data)
  636. {
  637. struct ast_tcptls_session_args *desc = data;
  638. int fd;
  639. struct ast_sockaddr addr;
  640. struct ast_tcptls_session_instance *tcptls_session;
  641. pthread_t launched;
  642. for (;;) {
  643. int i, flags;
  644. if (desc->periodic_fn) {
  645. desc->periodic_fn(desc);
  646. }
  647. i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
  648. if (i <= 0) {
  649. continue;
  650. }
  651. fd = ast_accept(desc->accept_fd, &addr);
  652. if (fd < 0) {
  653. if ((errno != EAGAIN) && (errno != EWOULDBLOCK) && (errno != EINTR) && (errno != ECONNABORTED)) {
  654. ast_log(LOG_ERROR, "Accept failed: %s\n", strerror(errno));
  655. break;
  656. }
  657. continue;
  658. }
  659. tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
  660. if (!tcptls_session) {
  661. ast_log(LOG_WARNING, "No memory for new session: %s\n", strerror(errno));
  662. if (close(fd)) {
  663. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  664. }
  665. continue;
  666. }
  667. tcptls_session->overflow_buf = ast_str_create(128);
  668. flags = fcntl(fd, F_GETFL);
  669. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  670. tcptls_session->fd = fd;
  671. tcptls_session->parent = desc;
  672. ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
  673. tcptls_session->client = 0;
  674. /* This thread is now the only place that controls the single ref to tcptls_session */
  675. if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
  676. ast_log(LOG_ERROR, "Unable to launch helper thread: %s\n", strerror(errno));
  677. ast_tcptls_close_session_file(tcptls_session);
  678. ao2_ref(tcptls_session, -1);
  679. }
  680. }
  681. return NULL;
  682. }
  683. static int __ssl_setup(struct ast_tls_config *cfg, int client)
  684. {
  685. #ifndef DO_SSL
  686. cfg->enabled = 0;
  687. return 0;
  688. #else
  689. int disable_ssl = 0;
  690. if (!cfg->enabled) {
  691. return 0;
  692. }
  693. /* Get rid of an old SSL_CTX since we're about to
  694. * allocate a new one
  695. */
  696. if (cfg->ssl_ctx) {
  697. SSL_CTX_free(cfg->ssl_ctx);
  698. cfg->ssl_ctx = NULL;
  699. }
  700. if (client) {
  701. #ifndef OPENSSL_NO_SSL2
  702. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
  703. ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  704. cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
  705. } else
  706. #endif
  707. #ifndef OPENSSL_NO_SSL3_METHOD
  708. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
  709. ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  710. cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
  711. } else
  712. #endif
  713. if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
  714. cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
  715. } else {
  716. disable_ssl = 1;
  717. cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  718. }
  719. } else {
  720. disable_ssl = 1;
  721. cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  722. }
  723. if (!cfg->ssl_ctx) {
  724. ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
  725. cfg->enabled = 0;
  726. return 0;
  727. }
  728. /* Due to the POODLE vulnerability, completely disable
  729. * SSLv2 and SSLv3 if we are not explicitly told to use
  730. * them. SSLv23_*_method supports TLSv1+.
  731. */
  732. if (disable_ssl) {
  733. long ssl_opts;
  734. ssl_opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
  735. SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
  736. }
  737. SSL_CTX_set_verify(cfg->ssl_ctx,
  738. ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
  739. NULL);
  740. if (!ast_strlen_zero(cfg->certfile)) {
  741. char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
  742. if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
  743. if (!client) {
  744. /* Clients don't need a certificate, but if its setup we can use it */
  745. ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
  746. cfg->enabled = 0;
  747. SSL_CTX_free(cfg->ssl_ctx);
  748. cfg->ssl_ctx = NULL;
  749. return 0;
  750. }
  751. }
  752. if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
  753. if (!client) {
  754. /* Clients don't need a private key, but if its setup we can use it */
  755. ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
  756. cfg->enabled = 0;
  757. SSL_CTX_free(cfg->ssl_ctx);
  758. cfg->ssl_ctx = NULL;
  759. return 0;
  760. }
  761. }
  762. }
  763. if (!ast_strlen_zero(cfg->cipher)) {
  764. if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
  765. if (!client) {
  766. ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
  767. cfg->enabled = 0;
  768. SSL_CTX_free(cfg->ssl_ctx);
  769. cfg->ssl_ctx = NULL;
  770. return 0;
  771. }
  772. }
  773. }
  774. if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
  775. if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
  776. ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
  777. }
  778. }
  779. #ifdef HAVE_OPENSSL_EC
  780. if (!ast_strlen_zero(cfg->pvtfile)) {
  781. BIO *bio = BIO_new_file(cfg->pvtfile, "r");
  782. if (bio != NULL) {
  783. DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  784. if (dh != NULL) {
  785. if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
  786. long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
  787. options = SSL_CTX_set_options(cfg->ssl_ctx, options);
  788. ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
  789. }
  790. DH_free(dh);
  791. }
  792. BIO_free(bio);
  793. }
  794. }
  795. #ifndef SSL_CTRL_SET_ECDH_AUTO
  796. #define SSL_CTRL_SET_ECDH_AUTO 94
  797. #endif
  798. /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
  799. if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
  800. ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
  801. } else {
  802. /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
  803. EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  804. if (ecdh != NULL) {
  805. if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
  806. ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
  807. }
  808. EC_KEY_free(ecdh);
  809. }
  810. }
  811. #endif /* #ifdef HAVE_OPENSSL_EC */
  812. ast_verb(2, "TLS/SSL certificate ok\n"); /* We should log which one that is ok. This message doesn't really make sense in production use */
  813. return 1;
  814. #endif
  815. }
  816. int ast_ssl_setup(struct ast_tls_config *cfg)
  817. {
  818. return __ssl_setup(cfg, 0);
  819. }
  820. void ast_ssl_teardown(struct ast_tls_config *cfg)
  821. {
  822. #ifdef DO_SSL
  823. if (cfg->ssl_ctx) {
  824. SSL_CTX_free(cfg->ssl_ctx);
  825. cfg->ssl_ctx = NULL;
  826. }
  827. #endif
  828. }
  829. struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
  830. {
  831. struct ast_tcptls_session_args *desc;
  832. int flags;
  833. if (!(desc = tcptls_session->parent)) {
  834. goto client_start_error;
  835. }
  836. if (ast_connect(desc->accept_fd, &desc->remote_address)) {
  837. ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
  838. desc->name,
  839. ast_sockaddr_stringify(&desc->remote_address),
  840. strerror(errno));
  841. goto client_start_error;
  842. }
  843. flags = fcntl(desc->accept_fd, F_GETFL);
  844. fcntl(desc->accept_fd, F_SETFL, flags & ~O_NONBLOCK);
  845. if (desc->tls_cfg) {
  846. desc->tls_cfg->enabled = 1;
  847. __ssl_setup(desc->tls_cfg, 1);
  848. }
  849. return handle_tcptls_connection(tcptls_session);
  850. client_start_error:
  851. if (desc) {
  852. close(desc->accept_fd);
  853. desc->accept_fd = -1;
  854. }
  855. ao2_ref(tcptls_session, -1);
  856. return NULL;
  857. }
  858. struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
  859. {
  860. int x = 1;
  861. struct ast_tcptls_session_instance *tcptls_session = NULL;
  862. /* Do nothing if nothing has changed */
  863. if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
  864. ast_debug(1, "Nothing changed in %s\n", desc->name);
  865. return NULL;
  866. }
  867. /* If we return early, there is no connection */
  868. ast_sockaddr_setnull(&desc->old_address);
  869. if (desc->accept_fd != -1) {
  870. close(desc->accept_fd);
  871. }
  872. desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
  873. AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
  874. if (desc->accept_fd < 0) {
  875. ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
  876. desc->name, strerror(errno));
  877. return NULL;
  878. }
  879. /* if a local address was specified, bind to it so the connection will
  880. originate from the desired address */
  881. if (!ast_sockaddr_isnull(&desc->local_address)) {
  882. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  883. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  884. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  885. desc->name,
  886. ast_sockaddr_stringify(&desc->local_address),
  887. strerror(errno));
  888. goto error;
  889. }
  890. }
  891. if (!(tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor))) {
  892. goto error;
  893. }
  894. tcptls_session->overflow_buf = ast_str_create(128);
  895. tcptls_session->client = 1;
  896. tcptls_session->fd = desc->accept_fd;
  897. tcptls_session->parent = desc;
  898. tcptls_session->parent->worker_fn = NULL;
  899. ast_sockaddr_copy(&tcptls_session->remote_address,
  900. &desc->remote_address);
  901. /* Set current info */
  902. ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
  903. return tcptls_session;
  904. error:
  905. close(desc->accept_fd);
  906. desc->accept_fd = -1;
  907. if (tcptls_session) {
  908. ao2_ref(tcptls_session, -1);
  909. }
  910. return NULL;
  911. }
  912. void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
  913. {
  914. int flags;
  915. int x = 1;
  916. /* Do nothing if nothing has changed */
  917. if (!ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
  918. ast_debug(1, "Nothing changed in %s\n", desc->name);
  919. return;
  920. }
  921. /* If we return early, there is no one listening */
  922. ast_sockaddr_setnull(&desc->old_address);
  923. /* Shutdown a running server if there is one */
  924. if (desc->master != AST_PTHREADT_NULL) {
  925. pthread_cancel(desc->master);
  926. pthread_kill(desc->master, SIGURG);
  927. pthread_join(desc->master, NULL);
  928. }
  929. if (desc->accept_fd != -1) {
  930. close(desc->accept_fd);
  931. }
  932. /* If there's no new server, stop here */
  933. if (ast_sockaddr_isnull(&desc->local_address)) {
  934. ast_debug(2, "Server disabled: %s\n", desc->name);
  935. return;
  936. }
  937. desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->local_address) ?
  938. AF_INET6 : AF_INET, SOCK_STREAM, 0);
  939. if (desc->accept_fd < 0) {
  940. ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
  941. return;
  942. }
  943. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  944. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  945. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  946. desc->name,
  947. ast_sockaddr_stringify(&desc->local_address),
  948. strerror(errno));
  949. goto error;
  950. }
  951. if (listen(desc->accept_fd, 10)) {
  952. ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
  953. goto error;
  954. }
  955. flags = fcntl(desc->accept_fd, F_GETFL);
  956. fcntl(desc->accept_fd, F_SETFL, flags | O_NONBLOCK);
  957. if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
  958. ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
  959. desc->name,
  960. ast_sockaddr_stringify(&desc->local_address),
  961. strerror(errno));
  962. goto error;
  963. }
  964. /* Set current info */
  965. ast_sockaddr_copy(&desc->old_address, &desc->local_address);
  966. return;
  967. error:
  968. close(desc->accept_fd);
  969. desc->accept_fd = -1;
  970. }
  971. void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
  972. {
  973. if (tcptls_session->f) {
  974. fflush(tcptls_session->f);
  975. if (fclose(tcptls_session->f)) {
  976. ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
  977. }
  978. tcptls_session->f = NULL;
  979. tcptls_session->fd = -1;
  980. } else if (tcptls_session->fd != -1) {
  981. /*
  982. * Issuing shutdown() is necessary here to avoid a race
  983. * condition where the last data written may not appear
  984. * in the TCP stream. See ASTERISK-23548
  985. */
  986. shutdown(tcptls_session->fd, SHUT_RDWR);
  987. if (close(tcptls_session->fd)) {
  988. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  989. }
  990. tcptls_session->fd = -1;
  991. } else {
  992. ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
  993. }
  994. }
  995. void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
  996. {
  997. if (desc->master != AST_PTHREADT_NULL) {
  998. pthread_cancel(desc->master);
  999. pthread_kill(desc->master, SIGURG);
  1000. pthread_join(desc->master, NULL);
  1001. desc->master = AST_PTHREADT_NULL;
  1002. }
  1003. if (desc->accept_fd != -1) {
  1004. close(desc->accept_fd);
  1005. }
  1006. desc->accept_fd = -1;
  1007. ast_debug(2, "Stopped server :: %s\n", desc->name);
  1008. }
  1009. int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
  1010. {
  1011. if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
  1012. tls_cfg->enabled = ast_true(value) ? 1 : 0;
  1013. } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
  1014. ast_free(tls_cfg->certfile);
  1015. tls_cfg->certfile = ast_strdup(value);
  1016. } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
  1017. ast_free(tls_cfg->pvtfile);
  1018. tls_cfg->pvtfile = ast_strdup(value);
  1019. } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
  1020. ast_free(tls_cfg->cipher);
  1021. tls_cfg->cipher = ast_strdup(value);
  1022. } else if (!strcasecmp(varname, "tlscafile")) {
  1023. ast_free(tls_cfg->cafile);
  1024. tls_cfg->cafile = ast_strdup(value);
  1025. } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
  1026. ast_free(tls_cfg->capath);
  1027. tls_cfg->capath = ast_strdup(value);
  1028. } else if (!strcasecmp(varname, "tlsverifyclient")) {
  1029. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
  1030. } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
  1031. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
  1032. } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
  1033. if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
  1034. ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
  1035. } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
  1036. if (!strcasecmp(value, "tlsv1")) {
  1037. ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1038. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1039. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1040. } else if (!strcasecmp(value, "sslv3")) {
  1041. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1042. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1043. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1044. } else if (!strcasecmp(value, "sslv2")) {
  1045. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1046. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1047. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1048. }
  1049. } else {
  1050. return -1;
  1051. }
  1052. return 0;
  1053. }