tcptls.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  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. #include "asterisk.h"
  27. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  28. #include "asterisk/tcptls.h" /* for ast_tls_config, ast_tcptls_se... */
  29. #ifdef HAVE_FCNTL_H
  30. #include <fcntl.h> /* for O_NONBLOCK */
  31. #endif /* HAVE_FCNTL_H */
  32. #include <netinet/in.h> /* for IPPROTO_TCP */
  33. #ifdef DO_SSL
  34. #include <openssl/asn1.h> /* for ASN1_STRING_to_UTF8 */
  35. #include <openssl/crypto.h> /* for OPENSSL_free */
  36. #include <openssl/err.h> /* for ERR_error_string */
  37. #include <openssl/opensslconf.h> /* for OPENSSL_NO_SSL3_METHOD, OPENS... */
  38. #include <openssl/opensslv.h> /* for OPENSSL_VERSION_NUMBER */
  39. #include <openssl/safestack.h> /* for STACK_OF */
  40. #include <openssl/ssl.h> /* for SSL_CTX_free, SSL_get_error, ... */
  41. #include <openssl/x509.h> /* for X509_free, X509_NAME_ENTRY_ge... */
  42. #include <openssl/x509v3.h> /* for GENERAL_NAME, sk_GENERAL_NAME... */
  43. #ifndef OPENSSL_NO_DH
  44. #include <openssl/bio.h> /* for BIO_free, BIO_new_file */
  45. #include <openssl/dh.h> /* for DH_free */
  46. #include <openssl/pem.h> /* for PEM_read_bio_DHparams */
  47. #endif /* OPENSSL_NO_DH */
  48. #ifndef OPENSSL_NO_EC
  49. #include <openssl/ec.h> /* for EC_KEY_free, EC_KEY_new_by_cu... */
  50. #endif /* OPENSSL_NO_EC */
  51. #endif /* DO_SSL */
  52. #include <pthread.h> /* for pthread_cancel, pthread_join */
  53. #include <signal.h> /* for pthread_kill, SIGURG */
  54. #include <sys/socket.h> /* for setsockopt, shutdown, socket */
  55. #include <sys/stat.h> /* for stat */
  56. #include <sys/time.h> /* for timeval */
  57. #include "asterisk/app.h" /* for ast_read_textfile */
  58. #include "asterisk/astobj2.h" /* for ao2_ref, ao2_t_ref, ao2_alloc */
  59. #include "asterisk/compat.h" /* for strcasecmp */
  60. #include "asterisk/config.h" /* for ast_parse_arg, ast_parse_flag... */
  61. #include "asterisk/lock.h" /* for AST_PTHREADT_NULL */
  62. #include "asterisk/logger.h" /* for ast_log, LOG_ERROR, ast_debug */
  63. #include "asterisk/netsock2.h" /* for ast_sockaddr_copy, ast_sockad... */
  64. #include "asterisk/pbx.h" /* for ast_thread_inhibit_escalations */
  65. #include "asterisk/threadstorage.h" /* for ast_threadstorage_get, AST_TH... */
  66. #include "asterisk/time.h" /* for ast_remaining_ms, ast_tvnow */
  67. #include "asterisk/utils.h" /* for ast_true, ast_free, ast_wait_... */
  68. /*! ao2 object used for the FILE stream fopencookie()/funopen() cookie. */
  69. struct ast_tcptls_stream {
  70. /*! SSL state if not NULL */
  71. SSL *ssl;
  72. /*!
  73. * \brief Start time from when an I/O sequence must complete
  74. * by struct ast_tcptls_stream.timeout.
  75. *
  76. * \note If struct ast_tcptls_stream.start.tv_sec is zero then
  77. * start time is the current I/O request.
  78. */
  79. struct timeval start;
  80. /*!
  81. * \brief The socket returned by accept().
  82. *
  83. * \note Set to -1 if the stream is closed.
  84. */
  85. int fd;
  86. /*!
  87. * \brief Timeout in ms relative to struct ast_tcptls_stream.start
  88. * to wait for an event on struct ast_tcptls_stream.fd.
  89. *
  90. * \note Set to -1 to disable timeout.
  91. * \note The socket needs to be set to non-blocking for the timeout
  92. * feature to work correctly.
  93. */
  94. int timeout;
  95. /*! TRUE if stream can exclusively wait for fd input. */
  96. int exclusive_input;
  97. };
  98. #if defined(DO_SSL)
  99. AST_THREADSTORAGE(err2str_threadbuf);
  100. #define ERR2STR_BUFSIZE 128
  101. static const char *ssl_error_to_string(int sslerr, int ret)
  102. {
  103. switch (sslerr) {
  104. case SSL_ERROR_SSL:
  105. return "Internal SSL error";
  106. case SSL_ERROR_SYSCALL:
  107. if (!ret) {
  108. return "System call EOF";
  109. } else if (ret == -1) {
  110. char *buf;
  111. buf = ast_threadstorage_get(&err2str_threadbuf, ERR2STR_BUFSIZE);
  112. if (!buf) {
  113. return "Unknown";
  114. }
  115. snprintf(buf, ERR2STR_BUFSIZE, "Underlying BIO error: %s", strerror(errno));
  116. return buf;
  117. } else {
  118. return "System call other";
  119. }
  120. default:
  121. break;
  122. }
  123. return "Unknown";
  124. }
  125. #endif
  126. void ast_tcptls_stream_set_timeout_disable(struct ast_tcptls_stream *stream)
  127. {
  128. ast_assert(stream != NULL);
  129. stream->timeout = -1;
  130. }
  131. void ast_tcptls_stream_set_timeout_inactivity(struct ast_tcptls_stream *stream, int timeout)
  132. {
  133. ast_assert(stream != NULL);
  134. stream->start.tv_sec = 0;
  135. stream->timeout = timeout;
  136. }
  137. void ast_tcptls_stream_set_timeout_sequence(struct ast_tcptls_stream *stream, struct timeval start, int timeout)
  138. {
  139. ast_assert(stream != NULL);
  140. stream->start = start;
  141. stream->timeout = timeout;
  142. }
  143. void ast_tcptls_stream_set_exclusive_input(struct ast_tcptls_stream *stream, int exclusive_input)
  144. {
  145. ast_assert(stream != NULL);
  146. stream->exclusive_input = exclusive_input;
  147. }
  148. /*!
  149. * \internal
  150. * \brief fopencookie()/funopen() stream read function.
  151. *
  152. * \param cookie Stream control data.
  153. * \param buf Where to put read data.
  154. * \param size Size of the buffer.
  155. *
  156. * \retval number of bytes put into buf.
  157. * \retval 0 on end of file.
  158. * \retval -1 on error.
  159. */
  160. static HOOK_T tcptls_stream_read(void *cookie, char *buf, LEN_T size)
  161. {
  162. struct ast_tcptls_stream *stream = cookie;
  163. struct timeval start;
  164. int ms;
  165. int res;
  166. if (!size) {
  167. /* You asked for no data you got no data. */
  168. return 0;
  169. }
  170. if (!stream || stream->fd == -1) {
  171. errno = EBADF;
  172. return -1;
  173. }
  174. if (stream->start.tv_sec) {
  175. start = stream->start;
  176. } else {
  177. start = ast_tvnow();
  178. }
  179. #if defined(DO_SSL)
  180. if (stream->ssl) {
  181. for (;;) {
  182. int sslerr;
  183. char err[256];
  184. res = SSL_read(stream->ssl, buf, size);
  185. if (0 < res) {
  186. /* We read some payload data. */
  187. return res;
  188. }
  189. sslerr = SSL_get_error(stream->ssl, res);
  190. switch (sslerr) {
  191. case SSL_ERROR_ZERO_RETURN:
  192. /* Report EOF for a shutdown */
  193. ast_debug(1, "TLS clean shutdown alert reading data\n");
  194. return 0;
  195. case SSL_ERROR_WANT_READ:
  196. if (!stream->exclusive_input) {
  197. /* We cannot wait for data now. */
  198. errno = EAGAIN;
  199. return -1;
  200. }
  201. while ((ms = ast_remaining_ms(start, stream->timeout))) {
  202. res = ast_wait_for_input(stream->fd, ms);
  203. if (0 < res) {
  204. /* Socket is ready to be read. */
  205. break;
  206. }
  207. if (res < 0) {
  208. if (errno == EINTR || errno == EAGAIN) {
  209. /* Try again. */
  210. continue;
  211. }
  212. ast_debug(1, "TLS socket error waiting for read data: %s\n",
  213. strerror(errno));
  214. return -1;
  215. }
  216. }
  217. break;
  218. case SSL_ERROR_WANT_WRITE:
  219. while ((ms = ast_remaining_ms(start, stream->timeout))) {
  220. res = ast_wait_for_output(stream->fd, ms);
  221. if (0 < res) {
  222. /* Socket is ready to be written. */
  223. break;
  224. }
  225. if (res < 0) {
  226. if (errno == EINTR || errno == EAGAIN) {
  227. /* Try again. */
  228. continue;
  229. }
  230. ast_debug(1, "TLS socket error waiting for write space: %s\n",
  231. strerror(errno));
  232. return -1;
  233. }
  234. }
  235. break;
  236. default:
  237. /* Report EOF for an undecoded SSL or transport error. */
  238. ast_debug(1, "TLS transport or SSL error reading data: %s, %s\n", ERR_error_string(sslerr, err),
  239. ssl_error_to_string(sslerr, res));
  240. return 0;
  241. }
  242. if (!ms) {
  243. /* Report EOF for a timeout */
  244. ast_debug(1, "TLS timeout reading data\n");
  245. return 0;
  246. }
  247. }
  248. }
  249. #endif /* defined(DO_SSL) */
  250. for (;;) {
  251. res = read(stream->fd, buf, size);
  252. if (0 <= res || !stream->exclusive_input) {
  253. /* Got data or we cannot wait for it. */
  254. return res;
  255. }
  256. if (errno != EINTR && errno != EAGAIN) {
  257. /* Not a retryable error. */
  258. ast_debug(1, "TCP socket error reading data: %s\n",
  259. strerror(errno));
  260. return -1;
  261. }
  262. ms = ast_remaining_ms(start, stream->timeout);
  263. if (!ms) {
  264. /* Report EOF for a timeout */
  265. ast_debug(1, "TCP timeout reading data\n");
  266. return 0;
  267. }
  268. ast_wait_for_input(stream->fd, ms);
  269. }
  270. }
  271. /*!
  272. * \internal
  273. * \brief fopencookie()/funopen() stream write function.
  274. *
  275. * \param cookie Stream control data.
  276. * \param buf Where to get data to write.
  277. * \param size Size of the buffer.
  278. *
  279. * \retval number of bytes written from buf.
  280. * \retval -1 on error.
  281. */
  282. static HOOK_T tcptls_stream_write(void *cookie, const char *buf, LEN_T size)
  283. {
  284. struct ast_tcptls_stream *stream = cookie;
  285. struct timeval start;
  286. int ms;
  287. int res;
  288. int written;
  289. int remaining;
  290. if (!size) {
  291. /* You asked to write no data you wrote no data. */
  292. return 0;
  293. }
  294. if (!stream || stream->fd == -1) {
  295. errno = EBADF;
  296. return -1;
  297. }
  298. if (stream->start.tv_sec) {
  299. start = stream->start;
  300. } else {
  301. start = ast_tvnow();
  302. }
  303. #if defined(DO_SSL)
  304. if (stream->ssl) {
  305. written = 0;
  306. remaining = size;
  307. for (;;) {
  308. int sslerr;
  309. char err[256];
  310. res = SSL_write(stream->ssl, buf + written, remaining);
  311. if (res == remaining) {
  312. /* Everything was written. */
  313. return size;
  314. }
  315. if (0 < res) {
  316. /* Successfully wrote part of the buffer. Try to write the rest. */
  317. written += res;
  318. remaining -= res;
  319. continue;
  320. }
  321. sslerr = SSL_get_error(stream->ssl, res);
  322. switch (sslerr) {
  323. case SSL_ERROR_ZERO_RETURN:
  324. ast_debug(1, "TLS clean shutdown alert writing data\n");
  325. if (written) {
  326. /* Report partial write. */
  327. return written;
  328. }
  329. errno = EBADF;
  330. return -1;
  331. case SSL_ERROR_WANT_READ:
  332. ms = ast_remaining_ms(start, stream->timeout);
  333. if (!ms) {
  334. /* Report partial write. */
  335. ast_debug(1, "TLS timeout writing data (want read)\n");
  336. return written;
  337. }
  338. ast_wait_for_input(stream->fd, ms);
  339. break;
  340. case SSL_ERROR_WANT_WRITE:
  341. ms = ast_remaining_ms(start, stream->timeout);
  342. if (!ms) {
  343. /* Report partial write. */
  344. ast_debug(1, "TLS timeout writing data (want write)\n");
  345. return written;
  346. }
  347. ast_wait_for_output(stream->fd, ms);
  348. break;
  349. default:
  350. /* Undecoded SSL or transport error. */
  351. ast_debug(1, "TLS transport or SSL error writing data: %s, %s\n", ERR_error_string(sslerr, err),
  352. ssl_error_to_string(sslerr, res));
  353. if (written) {
  354. /* Report partial write. */
  355. return written;
  356. }
  357. errno = EBADF;
  358. return -1;
  359. }
  360. }
  361. }
  362. #endif /* defined(DO_SSL) */
  363. written = 0;
  364. remaining = size;
  365. for (;;) {
  366. res = write(stream->fd, buf + written, remaining);
  367. if (res == remaining) {
  368. /* Yay everything was written. */
  369. return size;
  370. }
  371. if (0 < res) {
  372. /* Successfully wrote part of the buffer. Try to write the rest. */
  373. written += res;
  374. remaining -= res;
  375. continue;
  376. }
  377. if (errno != EINTR && errno != EAGAIN) {
  378. /* Not a retryable error. */
  379. ast_debug(1, "TCP socket error writing: %s\n", strerror(errno));
  380. if (written) {
  381. return written;
  382. }
  383. return -1;
  384. }
  385. ms = ast_remaining_ms(start, stream->timeout);
  386. if (!ms) {
  387. /* Report partial write. */
  388. ast_debug(1, "TCP timeout writing data\n");
  389. return written;
  390. }
  391. ast_wait_for_output(stream->fd, ms);
  392. }
  393. }
  394. /*!
  395. * \internal
  396. * \brief fopencookie()/funopen() stream close function.
  397. *
  398. * \param cookie Stream control data.
  399. *
  400. * \retval 0 on success.
  401. * \retval -1 on error.
  402. */
  403. static int tcptls_stream_close(void *cookie)
  404. {
  405. struct ast_tcptls_stream *stream = cookie;
  406. if (!stream) {
  407. errno = EBADF;
  408. return -1;
  409. }
  410. if (stream->fd != -1) {
  411. #if defined(DO_SSL)
  412. if (stream->ssl) {
  413. int res;
  414. /*
  415. * According to the TLS standard, it is acceptable for an
  416. * application to only send its shutdown alert and then
  417. * close the underlying connection without waiting for
  418. * the peer's response (this way resources can be saved,
  419. * as the process can already terminate or serve another
  420. * connection).
  421. */
  422. res = SSL_shutdown(stream->ssl);
  423. if (res < 0) {
  424. int sslerr = SSL_get_error(stream->ssl, res);
  425. char err[256];
  426. ast_log(LOG_ERROR, "SSL_shutdown() failed: %s, %s\n",
  427. ERR_error_string(sslerr, err), ssl_error_to_string(sslerr, res));
  428. }
  429. #if !defined(LIBRESSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  430. if (!SSL_is_server(stream->ssl)) {
  431. #else
  432. if (!stream->ssl->server) {
  433. #endif
  434. /* For client threads, ensure that the error stack is cleared */
  435. #if defined(LIBRESSL_VERSION_NUMBER) || (OPENSSL_VERSION_NUMBER < 0x10100000L)
  436. #if OPENSSL_VERSION_NUMBER >= 0x10000000L
  437. ERR_remove_thread_state(NULL);
  438. #else
  439. ERR_remove_state(0);
  440. #endif /* openssl == 1.0 */
  441. #endif /* openssl < 1.1 */
  442. }
  443. SSL_free(stream->ssl);
  444. stream->ssl = NULL;
  445. }
  446. #endif /* defined(DO_SSL) */
  447. /*
  448. * Issuing shutdown() is necessary here to avoid a race
  449. * condition where the last data written may not appear
  450. * in the TCP stream. See ASTERISK-23548
  451. */
  452. shutdown(stream->fd, SHUT_RDWR);
  453. if (close(stream->fd)) {
  454. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  455. }
  456. stream->fd = -1;
  457. }
  458. ao2_t_ref(stream, -1, "Closed tcptls stream cookie");
  459. return 0;
  460. }
  461. /*!
  462. * \internal
  463. * \brief fopencookie()/funopen() stream destructor function.
  464. *
  465. * \param cookie Stream control data.
  466. *
  467. * \return Nothing
  468. */
  469. static void tcptls_stream_dtor(void *cookie)
  470. {
  471. #ifdef AST_DEVMODE
  472. /* Since the ast_assert below is the only one using stream,
  473. * and ast_assert is only available with AST_DEVMODE, we
  474. * put this in a conditional to avoid compiler warnings. */
  475. struct ast_tcptls_stream *stream = cookie;
  476. #endif
  477. ast_assert(stream->fd == -1);
  478. }
  479. /*!
  480. * \internal
  481. * \brief fopencookie()/funopen() stream allocation function.
  482. *
  483. * \retval stream_cookie on success.
  484. * \retval NULL on error.
  485. */
  486. static struct ast_tcptls_stream *tcptls_stream_alloc(void)
  487. {
  488. struct ast_tcptls_stream *stream;
  489. stream = ao2_alloc_options(sizeof(*stream), tcptls_stream_dtor,
  490. AO2_ALLOC_OPT_LOCK_NOLOCK);
  491. if (stream) {
  492. stream->fd = -1;
  493. stream->timeout = -1;
  494. }
  495. return stream;
  496. }
  497. /*!
  498. * \internal
  499. * \brief Open a custom FILE stream for tcptls.
  500. *
  501. * \param stream Stream cookie control data.
  502. * \param ssl SSL state if not NULL.
  503. * \param fd Socket file descriptor.
  504. * \param timeout ms to wait for an event on fd. -1 if timeout disabled.
  505. *
  506. * \retval fp on success.
  507. * \retval NULL on error.
  508. */
  509. static FILE *tcptls_stream_fopen(struct ast_tcptls_stream *stream, SSL *ssl, int fd, int timeout)
  510. {
  511. FILE *fp;
  512. #if defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
  513. static const cookie_io_functions_t cookie_funcs = {
  514. tcptls_stream_read,
  515. tcptls_stream_write,
  516. NULL,
  517. tcptls_stream_close
  518. };
  519. #endif /* defined(HAVE_FOPENCOOKIE) */
  520. if (fd == -1) {
  521. /* Socket not open. */
  522. return NULL;
  523. }
  524. stream->ssl = ssl;
  525. stream->fd = fd;
  526. stream->timeout = timeout;
  527. ao2_t_ref(stream, +1, "Opening tcptls stream cookie");
  528. #if defined(HAVE_FUNOPEN) /* the BSD interface */
  529. fp = funopen(stream, tcptls_stream_read, tcptls_stream_write, NULL,
  530. tcptls_stream_close);
  531. #elif defined(HAVE_FOPENCOOKIE) /* the glibc/linux interface */
  532. fp = fopencookie(stream, "w+", cookie_funcs);
  533. #else
  534. /* could add other methods here */
  535. ast_debug(2, "No stream FILE methods attempted!\n");
  536. fp = NULL;
  537. #endif
  538. if (!fp) {
  539. stream->fd = -1;
  540. ao2_t_ref(stream, -1, "Failed to open tcptls stream cookie");
  541. }
  542. return fp;
  543. }
  544. HOOK_T ast_tcptls_server_read(struct ast_tcptls_session_instance *tcptls_session, void *buf, size_t count)
  545. {
  546. if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
  547. ast_log(LOG_ERROR, "TCP/TLS read called on invalid stream.\n");
  548. errno = EIO;
  549. return -1;
  550. }
  551. return tcptls_stream_read(tcptls_session->stream_cookie, buf, count);
  552. }
  553. HOOK_T ast_tcptls_server_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t count)
  554. {
  555. if (!tcptls_session->stream_cookie || tcptls_session->stream_cookie->fd == -1) {
  556. ast_log(LOG_ERROR, "TCP/TLS write called on invalid stream.\n");
  557. errno = EIO;
  558. return -1;
  559. }
  560. return tcptls_stream_write(tcptls_session->stream_cookie, buf, count);
  561. }
  562. static void session_instance_destructor(void *obj)
  563. {
  564. struct ast_tcptls_session_instance *i = obj;
  565. if (i->stream_cookie) {
  566. ao2_t_ref(i->stream_cookie, -1, "Destroying tcptls session instance");
  567. i->stream_cookie = NULL;
  568. }
  569. ast_free(i->overflow_buf);
  570. ao2_cleanup(i->private_data);
  571. }
  572. #ifdef DO_SSL
  573. static int check_tcptls_cert_name(ASN1_STRING *cert_str, const char *hostname, const char *desc)
  574. {
  575. unsigned char *str;
  576. int ret;
  577. ret = ASN1_STRING_to_UTF8(&str, cert_str);
  578. if (ret < 0 || !str) {
  579. return -1;
  580. }
  581. if (strlen((char *) str) != ret) {
  582. ast_log(LOG_WARNING, "Invalid certificate %s length (contains NULL bytes?)\n", desc);
  583. ret = -1;
  584. } else if (!strcasecmp(hostname, (char *) str)) {
  585. ret = 0;
  586. } else {
  587. ret = -1;
  588. }
  589. ast_debug(3, "SSL %s compare s1='%s' s2='%s'\n", desc, hostname, str);
  590. OPENSSL_free(str);
  591. return ret;
  592. }
  593. #endif
  594. /*! \brief
  595. * creates a FILE * from the fd passed by the accept thread.
  596. * This operation is potentially expensive (certificate verification),
  597. * so we do it in the child thread context.
  598. *
  599. * \note must decrement ref count before returning NULL on error
  600. */
  601. static void *handle_tcptls_connection(void *data)
  602. {
  603. struct ast_tcptls_session_instance *tcptls_session = data;
  604. #ifdef DO_SSL
  605. int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
  606. int ret;
  607. #endif
  608. /* TCP/TLS connections are associated with external protocols, and
  609. * should not be allowed to execute 'dangerous' functions. This may
  610. * need to be pushed down into the individual protocol handlers, but
  611. * this seems like a good general policy.
  612. */
  613. if (ast_thread_inhibit_escalations()) {
  614. ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
  615. ast_tcptls_close_session_file(tcptls_session);
  616. ao2_ref(tcptls_session, -1);
  617. return NULL;
  618. }
  619. /*
  620. * TCP/TLS connections are associated with external protocols which can
  621. * be considered to be user interfaces (even for SIP messages), and
  622. * will not handle channel media. This may need to be pushed down into
  623. * the individual protocol handlers, but this seems like a good start.
  624. */
  625. if (ast_thread_user_interface_set(1)) {
  626. ast_log(LOG_ERROR, "Failed to set user interface status; killing connection\n");
  627. ast_tcptls_close_session_file(tcptls_session);
  628. ao2_ref(tcptls_session, -1);
  629. return NULL;
  630. }
  631. tcptls_session->stream_cookie = tcptls_stream_alloc();
  632. if (!tcptls_session->stream_cookie) {
  633. ast_tcptls_close_session_file(tcptls_session);
  634. ao2_ref(tcptls_session, -1);
  635. return NULL;
  636. }
  637. /*
  638. * open a FILE * as appropriate.
  639. */
  640. if (!tcptls_session->parent->tls_cfg) {
  641. tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie, NULL,
  642. tcptls_session->fd, -1);
  643. if (tcptls_session->f) {
  644. if (setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
  645. ast_tcptls_close_session_file(tcptls_session);
  646. }
  647. }
  648. }
  649. #ifdef DO_SSL
  650. else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
  651. SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
  652. if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
  653. char err[256];
  654. int sslerr = SSL_get_error(tcptls_session->ssl, ret);
  655. ast_log(LOG_ERROR, "Problem setting up ssl connection: %s, %s\n", ERR_error_string(sslerr, err),
  656. ssl_error_to_string(sslerr, ret));
  657. } else if ((tcptls_session->f = tcptls_stream_fopen(tcptls_session->stream_cookie,
  658. tcptls_session->ssl, tcptls_session->fd, -1))) {
  659. if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
  660. || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
  661. X509 *peer;
  662. long res;
  663. peer = SSL_get_peer_certificate(tcptls_session->ssl);
  664. if (!peer) {
  665. ast_log(LOG_ERROR, "No peer SSL certificate to verify\n");
  666. ast_tcptls_close_session_file(tcptls_session);
  667. ao2_ref(tcptls_session, -1);
  668. return NULL;
  669. }
  670. res = SSL_get_verify_result(tcptls_session->ssl);
  671. if (res != X509_V_OK) {
  672. ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
  673. X509_free(peer);
  674. ast_tcptls_close_session_file(tcptls_session);
  675. ao2_ref(tcptls_session, -1);
  676. return NULL;
  677. }
  678. if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
  679. ASN1_STRING *str;
  680. X509_NAME *name = X509_get_subject_name(peer);
  681. STACK_OF(GENERAL_NAME) *alt_names;
  682. int pos = -1;
  683. int found = 0;
  684. for (;;) {
  685. /* Walk the certificate to check all available "Common Name" */
  686. /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
  687. pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
  688. if (pos < 0) {
  689. break;
  690. }
  691. str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
  692. if (!check_tcptls_cert_name(str, tcptls_session->parent->hostname, "common name")) {
  693. found = 1;
  694. break;
  695. }
  696. }
  697. if (!found) {
  698. alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, NULL, NULL);
  699. if (alt_names != NULL) {
  700. int alt_names_count = sk_GENERAL_NAME_num(alt_names);
  701. for (pos = 0; pos < alt_names_count; pos++) {
  702. const GENERAL_NAME *alt_name = sk_GENERAL_NAME_value(alt_names, pos);
  703. if (alt_name->type != GEN_DNS) {
  704. continue;
  705. }
  706. if (!check_tcptls_cert_name(alt_name->d.dNSName, tcptls_session->parent->hostname, "alt name")) {
  707. found = 1;
  708. break;
  709. }
  710. }
  711. sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
  712. }
  713. }
  714. if (!found) {
  715. ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
  716. X509_free(peer);
  717. ast_tcptls_close_session_file(tcptls_session);
  718. ao2_ref(tcptls_session, -1);
  719. return NULL;
  720. }
  721. }
  722. X509_free(peer);
  723. }
  724. }
  725. if (!tcptls_session->f) { /* no success opening descriptor stacking */
  726. SSL_free(tcptls_session->ssl);
  727. }
  728. }
  729. #endif /* DO_SSL */
  730. if (!tcptls_session->f) {
  731. ast_tcptls_close_session_file(tcptls_session);
  732. ast_log(LOG_WARNING, "FILE * open failed!\n");
  733. #ifndef DO_SSL
  734. if (tcptls_session->parent->tls_cfg) {
  735. ast_log(LOG_ERROR, "Attempted a TLS connection without OpenSSL support. This will not work!\n");
  736. }
  737. #endif
  738. ao2_ref(tcptls_session, -1);
  739. return NULL;
  740. }
  741. if (tcptls_session->parent->worker_fn) {
  742. return tcptls_session->parent->worker_fn(tcptls_session);
  743. } else {
  744. return tcptls_session;
  745. }
  746. }
  747. void *ast_tcptls_server_root(void *data)
  748. {
  749. struct ast_tcptls_session_args *desc = data;
  750. int fd;
  751. struct ast_sockaddr addr;
  752. struct ast_tcptls_session_instance *tcptls_session;
  753. pthread_t launched;
  754. for (;;) {
  755. int i;
  756. if (desc->periodic_fn) {
  757. desc->periodic_fn(desc);
  758. }
  759. i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
  760. if (i <= 0) {
  761. /* Prevent tight loop from hogging CPU */
  762. usleep(1);
  763. continue;
  764. }
  765. fd = ast_accept(desc->accept_fd, &addr);
  766. if (fd < 0) {
  767. if (errno != EAGAIN
  768. && errno != EWOULDBLOCK
  769. && errno != EINTR
  770. && errno != ECONNABORTED) {
  771. ast_log(LOG_ERROR, "TCP/TLS accept failed: %s\n", strerror(errno));
  772. if (errno != EMFILE) {
  773. break;
  774. }
  775. }
  776. /* Prevent tight loop from hogging CPU */
  777. usleep(1);
  778. continue;
  779. }
  780. tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
  781. if (!tcptls_session) {
  782. close(fd);
  783. continue;
  784. }
  785. tcptls_session->overflow_buf = ast_str_create(128);
  786. if (!tcptls_session->overflow_buf) {
  787. ao2_ref(tcptls_session, -1);
  788. close(fd);
  789. continue;
  790. }
  791. ast_fd_clear_flags(fd, O_NONBLOCK);
  792. tcptls_session->fd = fd;
  793. tcptls_session->parent = desc;
  794. ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
  795. tcptls_session->client = 0;
  796. /* This thread is now the only place that controls the single ref to tcptls_session */
  797. if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
  798. ast_log(LOG_ERROR, "TCP/TLS unable to launch helper thread: %s\n",
  799. strerror(errno));
  800. ast_tcptls_close_session_file(tcptls_session);
  801. ao2_ref(tcptls_session, -1);
  802. }
  803. }
  804. ast_log(LOG_ERROR, "TCP/TLS listener thread ended abnormally\n");
  805. /* Close the listener socket so Asterisk doesn't appear dead. */
  806. fd = desc->accept_fd;
  807. desc->accept_fd = -1;
  808. if (0 <= fd) {
  809. close(fd);
  810. }
  811. return NULL;
  812. }
  813. static int __ssl_setup(struct ast_tls_config *cfg, int client)
  814. {
  815. #ifndef DO_SSL
  816. if (cfg->enabled) {
  817. ast_log(LOG_NOTICE, "Configured without OpenSSL Development Headers");
  818. cfg->enabled = 0;
  819. }
  820. return 0;
  821. #else
  822. int disable_ssl = 0;
  823. long ssl_opts = 0;
  824. if (!cfg->enabled) {
  825. return 0;
  826. }
  827. /* Get rid of an old SSL_CTX since we're about to
  828. * allocate a new one
  829. */
  830. if (cfg->ssl_ctx) {
  831. SSL_CTX_free(cfg->ssl_ctx);
  832. cfg->ssl_ctx = NULL;
  833. }
  834. if (client) {
  835. #if !defined(OPENSSL_NO_SSL2) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
  836. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
  837. ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  838. cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
  839. } else
  840. #endif
  841. #if !defined(OPENSSL_NO_SSL3_METHOD) && !(defined(OPENSSL_API_COMPAT) && (OPENSSL_API_COMPAT >= 0x10100000L))
  842. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
  843. ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  844. cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
  845. } else
  846. #endif
  847. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  848. cfg->ssl_ctx = SSL_CTX_new(TLS_client_method());
  849. #else
  850. if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
  851. cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
  852. } else {
  853. disable_ssl = 1;
  854. cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  855. }
  856. #endif
  857. } else {
  858. disable_ssl = 1;
  859. cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  860. }
  861. if (!cfg->ssl_ctx) {
  862. ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
  863. cfg->enabled = 0;
  864. return 0;
  865. }
  866. /* Due to the POODLE vulnerability, completely disable
  867. * SSLv2 and SSLv3 if we are not explicitly told to use
  868. * them. SSLv23_*_method supports TLSv1+.
  869. */
  870. if (disable_ssl) {
  871. ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
  872. }
  873. if (ast_test_flag(&cfg->flags, AST_SSL_SERVER_CIPHER_ORDER)) {
  874. ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
  875. }
  876. if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV1)) {
  877. ssl_opts |= SSL_OP_NO_TLSv1;
  878. }
  879. #if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2)
  880. if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV11)) {
  881. ssl_opts |= SSL_OP_NO_TLSv1_1;
  882. }
  883. if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV12)) {
  884. ssl_opts |= SSL_OP_NO_TLSv1_2;
  885. }
  886. #else
  887. ast_log(LOG_WARNING, "Your version of OpenSSL leaves you potentially vulnerable "
  888. "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
  889. #endif
  890. SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
  891. SSL_CTX_set_verify(cfg->ssl_ctx,
  892. ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
  893. NULL);
  894. if (!ast_strlen_zero(cfg->certfile)) {
  895. char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
  896. if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
  897. if (!client) {
  898. /* Clients don't need a certificate, but if its setup we can use it */
  899. ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
  900. cfg->enabled = 0;
  901. SSL_CTX_free(cfg->ssl_ctx);
  902. cfg->ssl_ctx = NULL;
  903. return 0;
  904. }
  905. }
  906. if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
  907. if (!client) {
  908. /* Clients don't need a private key, but if its setup we can use it */
  909. ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
  910. cfg->enabled = 0;
  911. SSL_CTX_free(cfg->ssl_ctx);
  912. cfg->ssl_ctx = NULL;
  913. return 0;
  914. }
  915. }
  916. }
  917. if (!ast_strlen_zero(cfg->cipher)) {
  918. if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
  919. if (!client) {
  920. ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
  921. cfg->enabled = 0;
  922. SSL_CTX_free(cfg->ssl_ctx);
  923. cfg->ssl_ctx = NULL;
  924. return 0;
  925. }
  926. }
  927. }
  928. if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
  929. if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
  930. ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
  931. }
  932. }
  933. #ifndef OPENSSL_NO_DH
  934. if (!ast_strlen_zero(cfg->pvtfile)) {
  935. BIO *bio = BIO_new_file(cfg->pvtfile, "r");
  936. if (bio != NULL) {
  937. DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  938. if (dh != NULL) {
  939. if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
  940. long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
  941. options = SSL_CTX_set_options(cfg->ssl_ctx, options);
  942. ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
  943. }
  944. DH_free(dh);
  945. }
  946. BIO_free(bio);
  947. }
  948. }
  949. #endif
  950. #ifndef SSL_CTRL_SET_ECDH_AUTO
  951. #define SSL_CTRL_SET_ECDH_AUTO 94
  952. #endif
  953. /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
  954. if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
  955. ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
  956. #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
  957. } else {
  958. /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
  959. EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  960. if (ecdh != NULL) {
  961. if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
  962. ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
  963. }
  964. EC_KEY_free(ecdh);
  965. }
  966. #endif
  967. }
  968. 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 */
  969. return 1;
  970. #endif
  971. }
  972. int ast_ssl_setup(struct ast_tls_config *cfg)
  973. {
  974. return __ssl_setup(cfg, 0);
  975. }
  976. void ast_ssl_teardown(struct ast_tls_config *cfg)
  977. {
  978. #ifdef DO_SSL
  979. if (cfg && cfg->ssl_ctx) {
  980. SSL_CTX_free(cfg->ssl_ctx);
  981. cfg->ssl_ctx = NULL;
  982. }
  983. #endif
  984. }
  985. struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
  986. {
  987. struct ast_tcptls_session_args *desc;
  988. if (!(desc = tcptls_session->parent)) {
  989. goto client_start_error;
  990. }
  991. if (ast_connect(desc->accept_fd, &desc->remote_address)) {
  992. ast_log(LOG_ERROR, "Unable to connect %s to %s: %s\n",
  993. desc->name,
  994. ast_sockaddr_stringify(&desc->remote_address),
  995. strerror(errno));
  996. goto client_start_error;
  997. }
  998. ast_fd_clear_flags(desc->accept_fd, O_NONBLOCK);
  999. if (desc->tls_cfg) {
  1000. desc->tls_cfg->enabled = 1;
  1001. __ssl_setup(desc->tls_cfg, 1);
  1002. }
  1003. return handle_tcptls_connection(tcptls_session);
  1004. client_start_error:
  1005. if (desc) {
  1006. close(desc->accept_fd);
  1007. desc->accept_fd = -1;
  1008. }
  1009. ao2_ref(tcptls_session, -1);
  1010. return NULL;
  1011. }
  1012. struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
  1013. {
  1014. int x = 1;
  1015. struct ast_tcptls_session_instance *tcptls_session = NULL;
  1016. /* Do nothing if nothing has changed */
  1017. if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
  1018. ast_debug(1, "Nothing changed in %s\n", desc->name);
  1019. return NULL;
  1020. }
  1021. /* If we return early, there is no connection */
  1022. ast_sockaddr_setnull(&desc->old_address);
  1023. if (desc->accept_fd != -1) {
  1024. close(desc->accept_fd);
  1025. }
  1026. desc->accept_fd = socket(ast_sockaddr_is_ipv6(&desc->remote_address) ?
  1027. AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1028. if (desc->accept_fd < 0) {
  1029. ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
  1030. desc->name, strerror(errno));
  1031. return NULL;
  1032. }
  1033. /* if a local address was specified, bind to it so the connection will
  1034. originate from the desired address */
  1035. if (!ast_sockaddr_isnull(&desc->local_address) &&
  1036. !ast_sockaddr_is_any(&desc->local_address)) {
  1037. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  1038. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  1039. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  1040. desc->name,
  1041. ast_sockaddr_stringify(&desc->local_address),
  1042. strerror(errno));
  1043. goto error;
  1044. }
  1045. }
  1046. tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
  1047. if (!tcptls_session) {
  1048. goto error;
  1049. }
  1050. tcptls_session->overflow_buf = ast_str_create(128);
  1051. if (!tcptls_session->overflow_buf) {
  1052. goto error;
  1053. }
  1054. tcptls_session->client = 1;
  1055. tcptls_session->fd = desc->accept_fd;
  1056. tcptls_session->parent = desc;
  1057. tcptls_session->parent->worker_fn = NULL;
  1058. ast_sockaddr_copy(&tcptls_session->remote_address,
  1059. &desc->remote_address);
  1060. /* Set current info */
  1061. ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
  1062. return tcptls_session;
  1063. error:
  1064. close(desc->accept_fd);
  1065. desc->accept_fd = -1;
  1066. ao2_cleanup(tcptls_session);
  1067. return NULL;
  1068. }
  1069. void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
  1070. {
  1071. int x = 1;
  1072. int tls_changed = 0;
  1073. if (desc->tls_cfg) {
  1074. char hash[41];
  1075. char *str = NULL;
  1076. struct stat st;
  1077. /* Store the hashes of the TLS certificate etc. */
  1078. if (stat(desc->tls_cfg->certfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->certfile))) {
  1079. memset(hash, 0, 41);
  1080. } else {
  1081. ast_sha1_hash(hash, str);
  1082. }
  1083. ast_free(str);
  1084. str = NULL;
  1085. memcpy(desc->tls_cfg->certhash, hash, 41);
  1086. if (stat(desc->tls_cfg->pvtfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->pvtfile))) {
  1087. memset(hash, 0, 41);
  1088. } else {
  1089. ast_sha1_hash(hash, str);
  1090. }
  1091. ast_free(str);
  1092. str = NULL;
  1093. memcpy(desc->tls_cfg->pvthash, hash, 41);
  1094. if (stat(desc->tls_cfg->cafile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->cafile))) {
  1095. memset(hash, 0, 41);
  1096. } else {
  1097. ast_sha1_hash(hash, str);
  1098. }
  1099. ast_free(str);
  1100. str = NULL;
  1101. memcpy(desc->tls_cfg->cahash, hash, 41);
  1102. /* Check whether TLS configuration has changed */
  1103. if (!desc->old_tls_cfg) { /* No previous configuration */
  1104. tls_changed = 1;
  1105. desc->old_tls_cfg = ast_calloc(1, sizeof(*desc->old_tls_cfg));
  1106. } else if (memcmp(desc->tls_cfg->certhash, desc->old_tls_cfg->certhash, 41)) {
  1107. tls_changed = 1;
  1108. } else if (memcmp(desc->tls_cfg->pvthash, desc->old_tls_cfg->pvthash, 41)) {
  1109. tls_changed = 1;
  1110. } else if (strcmp(desc->tls_cfg->cipher, desc->old_tls_cfg->cipher)) {
  1111. tls_changed = 1;
  1112. } else if (memcmp(desc->tls_cfg->cahash, desc->old_tls_cfg->cahash, 41)) {
  1113. tls_changed = 1;
  1114. } else if (strcmp(desc->tls_cfg->capath, desc->old_tls_cfg->capath)) {
  1115. tls_changed = 1;
  1116. } else if (memcmp(&desc->tls_cfg->flags, &desc->old_tls_cfg->flags, sizeof(desc->tls_cfg->flags))) {
  1117. tls_changed = 1;
  1118. }
  1119. if (tls_changed) {
  1120. ast_debug(1, "Changed parameters for %s found\n", desc->name);
  1121. }
  1122. }
  1123. /* Do nothing if nothing has changed */
  1124. if (!tls_changed && !ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
  1125. ast_debug(1, "Nothing changed in %s\n", desc->name);
  1126. return;
  1127. }
  1128. /* If we return early, there is no one listening */
  1129. ast_sockaddr_setnull(&desc->old_address);
  1130. /* Shutdown a running server if there is one */
  1131. if (desc->master != AST_PTHREADT_NULL) {
  1132. pthread_cancel(desc->master);
  1133. pthread_kill(desc->master, SIGURG);
  1134. pthread_join(desc->master, NULL);
  1135. }
  1136. if (desc->accept_fd != -1) {
  1137. close(desc->accept_fd);
  1138. }
  1139. /* If there's no new server, stop here */
  1140. if (ast_sockaddr_isnull(&desc->local_address)) {
  1141. ast_debug(2, "Server disabled: %s\n", desc->name);
  1142. return;
  1143. }
  1144. desc->accept_fd = ast_socket_nonblock(ast_sockaddr_is_ipv6(&desc->local_address) ?
  1145. AF_INET6 : AF_INET, SOCK_STREAM, 0);
  1146. if (desc->accept_fd < 0) {
  1147. ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
  1148. return;
  1149. }
  1150. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  1151. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  1152. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  1153. desc->name,
  1154. ast_sockaddr_stringify(&desc->local_address),
  1155. strerror(errno));
  1156. goto error;
  1157. }
  1158. if (listen(desc->accept_fd, 10)) {
  1159. ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
  1160. goto error;
  1161. }
  1162. if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
  1163. ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
  1164. desc->name,
  1165. ast_sockaddr_stringify(&desc->local_address),
  1166. strerror(errno));
  1167. goto error;
  1168. }
  1169. /* Set current info */
  1170. ast_sockaddr_copy(&desc->old_address, &desc->local_address);
  1171. if (desc->old_tls_cfg) {
  1172. ast_free(desc->old_tls_cfg->certfile);
  1173. ast_free(desc->old_tls_cfg->pvtfile);
  1174. ast_free(desc->old_tls_cfg->cipher);
  1175. ast_free(desc->old_tls_cfg->cafile);
  1176. ast_free(desc->old_tls_cfg->capath);
  1177. desc->old_tls_cfg->certfile = ast_strdup(desc->tls_cfg->certfile);
  1178. desc->old_tls_cfg->pvtfile = ast_strdup(desc->tls_cfg->pvtfile);
  1179. desc->old_tls_cfg->cipher = ast_strdup(desc->tls_cfg->cipher);
  1180. desc->old_tls_cfg->cafile = ast_strdup(desc->tls_cfg->cafile);
  1181. desc->old_tls_cfg->capath = ast_strdup(desc->tls_cfg->capath);
  1182. memcpy(desc->old_tls_cfg->certhash, desc->tls_cfg->certhash, 41);
  1183. memcpy(desc->old_tls_cfg->pvthash, desc->tls_cfg->pvthash, 41);
  1184. memcpy(desc->old_tls_cfg->cahash, desc->tls_cfg->cahash, 41);
  1185. memcpy(&desc->old_tls_cfg->flags, &desc->tls_cfg->flags, sizeof(desc->old_tls_cfg->flags));
  1186. }
  1187. return;
  1188. error:
  1189. close(desc->accept_fd);
  1190. desc->accept_fd = -1;
  1191. }
  1192. void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
  1193. {
  1194. if (tcptls_session->f) {
  1195. fflush(tcptls_session->f);
  1196. if (fclose(tcptls_session->f)) {
  1197. ast_log(LOG_ERROR, "fclose() failed: %s\n", strerror(errno));
  1198. }
  1199. tcptls_session->f = NULL;
  1200. tcptls_session->fd = -1;
  1201. } else if (tcptls_session->fd != -1) {
  1202. /*
  1203. * Issuing shutdown() is necessary here to avoid a race
  1204. * condition where the last data written may not appear
  1205. * in the TCP stream. See ASTERISK-23548
  1206. */
  1207. shutdown(tcptls_session->fd, SHUT_RDWR);
  1208. if (close(tcptls_session->fd)) {
  1209. ast_log(LOG_ERROR, "close() failed: %s\n", strerror(errno));
  1210. }
  1211. tcptls_session->fd = -1;
  1212. } else {
  1213. ast_log(LOG_ERROR, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
  1214. }
  1215. }
  1216. void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
  1217. {
  1218. if (desc->master != AST_PTHREADT_NULL) {
  1219. pthread_cancel(desc->master);
  1220. pthread_kill(desc->master, SIGURG);
  1221. pthread_join(desc->master, NULL);
  1222. desc->master = AST_PTHREADT_NULL;
  1223. }
  1224. if (desc->accept_fd != -1) {
  1225. close(desc->accept_fd);
  1226. }
  1227. desc->accept_fd = -1;
  1228. if (desc->old_tls_cfg) {
  1229. ast_free(desc->old_tls_cfg->certfile);
  1230. ast_free(desc->old_tls_cfg->pvtfile);
  1231. ast_free(desc->old_tls_cfg->cipher);
  1232. ast_free(desc->old_tls_cfg->cafile);
  1233. ast_free(desc->old_tls_cfg->capath);
  1234. ast_free(desc->old_tls_cfg);
  1235. desc->old_tls_cfg = NULL;
  1236. }
  1237. ast_debug(2, "Stopped server :: %s\n", desc->name);
  1238. }
  1239. int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
  1240. {
  1241. if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
  1242. tls_cfg->enabled = ast_true(value) ? 1 : 0;
  1243. } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
  1244. ast_free(tls_cfg->certfile);
  1245. tls_cfg->certfile = ast_strdup(value);
  1246. } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
  1247. ast_free(tls_cfg->pvtfile);
  1248. tls_cfg->pvtfile = ast_strdup(value);
  1249. } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
  1250. ast_free(tls_cfg->cipher);
  1251. tls_cfg->cipher = ast_strdup(value);
  1252. } else if (!strcasecmp(varname, "tlscafile")) {
  1253. ast_free(tls_cfg->cafile);
  1254. tls_cfg->cafile = ast_strdup(value);
  1255. } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
  1256. ast_free(tls_cfg->capath);
  1257. tls_cfg->capath = ast_strdup(value);
  1258. } else if (!strcasecmp(varname, "tlsverifyclient")) {
  1259. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
  1260. } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
  1261. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
  1262. } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
  1263. if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
  1264. ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
  1265. } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
  1266. if (!strcasecmp(value, "tlsv1")) {
  1267. ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1268. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1269. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1270. } else if (!strcasecmp(value, "sslv3")) {
  1271. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1272. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1273. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1274. } else if (!strcasecmp(value, "sslv2")) {
  1275. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  1276. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  1277. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  1278. }
  1279. } else if (!strcasecmp(varname, "tlsservercipherorder")) {
  1280. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_SERVER_CIPHER_ORDER);
  1281. } else if (!strcasecmp(varname, "tlsdisablev1")) {
  1282. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV1);
  1283. } else if (!strcasecmp(varname, "tlsdisablev11")) {
  1284. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV11);
  1285. } else if (!strcasecmp(varname, "tlsdisablev12")) {
  1286. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV12);
  1287. } else {
  1288. return -1;
  1289. }
  1290. return 0;
  1291. }