tcptls.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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. #include "asterisk/tcptls.h" /* for ast_tls_config, ast_tcptls_se... */
  28. #include "asterisk/iostream.h" /* for DO_SSL, ast_iostream_close, a... */
  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_print_errors_fp */
  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 "asterisk/app.h" /* for ast_read_textfile */
  57. #include "asterisk/astobj2.h" /* for ao2_ref, ao2_t_ref, ao2_alloc */
  58. #include "asterisk/compat.h" /* for strcasecmp */
  59. #include "asterisk/config.h" /* for ast_parse_arg, ast_parse_flag... */
  60. #include "asterisk/io.h" /* for ast_sd_get_fd */
  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/utils.h" /* for ast_true, ast_free, ast_wait_... */
  66. static void session_instance_destructor(void *obj)
  67. {
  68. struct ast_tcptls_session_instance *i = obj;
  69. if (i->stream) {
  70. ast_iostream_close(i->stream);
  71. i->stream = NULL;
  72. }
  73. ast_free(i->overflow_buf);
  74. ao2_cleanup(i->private_data);
  75. }
  76. #ifdef DO_SSL
  77. static int check_tcptls_cert_name(ASN1_STRING *cert_str, const char *hostname, const char *desc)
  78. {
  79. unsigned char *str;
  80. int ret;
  81. ret = ASN1_STRING_to_UTF8(&str, cert_str);
  82. if (ret < 0 || !str) {
  83. return -1;
  84. }
  85. if (strlen((char *) str) != ret) {
  86. ast_log(LOG_WARNING, "Invalid certificate %s length (contains NULL bytes?)\n", desc);
  87. ret = -1;
  88. } else if (!strcasecmp(hostname, (char *) str)) {
  89. ret = 0;
  90. } else {
  91. ret = -1;
  92. }
  93. ast_debug(3, "SSL %s compare s1='%s' s2='%s'\n", desc, hostname, str);
  94. OPENSSL_free(str);
  95. return ret;
  96. }
  97. static void write_openssl_error_to_log(void)
  98. {
  99. FILE *fp;
  100. char *buffer;
  101. size_t length;
  102. fp = open_memstream(&buffer, &length);
  103. if (!fp) {
  104. return;
  105. }
  106. ERR_print_errors_fp(fp);
  107. fclose(fp);
  108. if (length) {
  109. ast_log(LOG_ERROR, "%.*s\n", (int) length, buffer);
  110. }
  111. ast_std_free(buffer);
  112. }
  113. #endif
  114. /*! \brief
  115. * creates a FILE * from the fd passed by the accept thread.
  116. * This operation is potentially expensive (certificate verification),
  117. * so we do it in the child thread context.
  118. *
  119. * \note must decrement ref count before returning NULL on error
  120. */
  121. static void *handle_tcptls_connection(void *data)
  122. {
  123. struct ast_tcptls_session_instance *tcptls_session = data;
  124. #ifdef DO_SSL
  125. SSL *ssl;
  126. #endif
  127. /* TCP/TLS connections are associated with external protocols, and
  128. * should not be allowed to execute 'dangerous' functions. This may
  129. * need to be pushed down into the individual protocol handlers, but
  130. * this seems like a good general policy.
  131. */
  132. if (ast_thread_inhibit_escalations()) {
  133. ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection from peer '%s'\n",
  134. ast_sockaddr_stringify(&tcptls_session->remote_address));
  135. ast_tcptls_close_session_file(tcptls_session);
  136. ao2_ref(tcptls_session, -1);
  137. return NULL;
  138. }
  139. /*
  140. * TCP/TLS connections are associated with external protocols which can
  141. * be considered to be user interfaces (even for SIP messages), and
  142. * will not handle channel media. This may need to be pushed down into
  143. * the individual protocol handlers, but this seems like a good start.
  144. */
  145. if (ast_thread_user_interface_set(1)) {
  146. ast_log(LOG_ERROR, "Failed to set user interface status; killing connection from peer '%s'\n",
  147. ast_sockaddr_stringify(&tcptls_session->remote_address));
  148. ast_tcptls_close_session_file(tcptls_session);
  149. ao2_ref(tcptls_session, -1);
  150. return NULL;
  151. }
  152. if (tcptls_session->parent->tls_cfg) {
  153. #ifdef DO_SSL
  154. if (ast_iostream_start_tls(&tcptls_session->stream, tcptls_session->parent->tls_cfg->ssl_ctx, tcptls_session->client) < 0) {
  155. SSL *ssl = ast_iostream_get_ssl(tcptls_session->stream);
  156. if (ssl) {
  157. ast_log(LOG_ERROR, "Unable to set up ssl connection with peer '%s'\n",
  158. ast_sockaddr_stringify(&tcptls_session->remote_address));
  159. }
  160. ast_tcptls_close_session_file(tcptls_session);
  161. ao2_ref(tcptls_session, -1);
  162. return NULL;
  163. }
  164. ssl = ast_iostream_get_ssl(tcptls_session->stream);
  165. if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
  166. || (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
  167. X509 *peer;
  168. long res;
  169. peer = SSL_get_peer_certificate(ssl);
  170. if (!peer) {
  171. ast_log(LOG_ERROR, "No SSL certificate to verify from peer '%s'\n",
  172. ast_sockaddr_stringify(&tcptls_session->remote_address));
  173. ast_tcptls_close_session_file(tcptls_session);
  174. ao2_ref(tcptls_session, -1);
  175. return NULL;
  176. }
  177. res = SSL_get_verify_result(ssl);
  178. if (res != X509_V_OK) {
  179. ast_log(LOG_ERROR, "Certificate from peer '%s' did not verify: %s\n",
  180. ast_sockaddr_stringify(&tcptls_session->remote_address),
  181. X509_verify_cert_error_string(res));
  182. X509_free(peer);
  183. ast_tcptls_close_session_file(tcptls_session);
  184. ao2_ref(tcptls_session, -1);
  185. return NULL;
  186. }
  187. if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
  188. ASN1_STRING *str;
  189. X509_NAME *name = X509_get_subject_name(peer);
  190. STACK_OF(GENERAL_NAME) *alt_names;
  191. int pos = -1;
  192. int found = 0;
  193. for (;;) {
  194. /* Walk the certificate to check all available "Common Name" */
  195. /* XXX Probably should do a gethostbyname on the hostname and compare that as well */
  196. pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
  197. if (pos < 0) {
  198. break;
  199. }
  200. str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
  201. if (!check_tcptls_cert_name(str, tcptls_session->parent->hostname, "common name")) {
  202. found = 1;
  203. break;
  204. }
  205. }
  206. if (!found) {
  207. alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, NULL, NULL);
  208. if (alt_names != NULL) {
  209. int alt_names_count = sk_GENERAL_NAME_num(alt_names);
  210. for (pos = 0; pos < alt_names_count; pos++) {
  211. const GENERAL_NAME *alt_name = sk_GENERAL_NAME_value(alt_names, pos);
  212. if (alt_name->type != GEN_DNS) {
  213. continue;
  214. }
  215. if (!check_tcptls_cert_name(alt_name->d.dNSName, tcptls_session->parent->hostname, "alt name")) {
  216. found = 1;
  217. break;
  218. }
  219. }
  220. sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
  221. }
  222. }
  223. if (!found) {
  224. ast_log(LOG_ERROR, "Certificate common name from peer '%s' did not match (%s)\n",
  225. ast_sockaddr_stringify(&tcptls_session->remote_address), tcptls_session->parent->hostname);
  226. X509_free(peer);
  227. ast_tcptls_close_session_file(tcptls_session);
  228. ao2_ref(tcptls_session, -1);
  229. return NULL;
  230. }
  231. }
  232. X509_free(peer);
  233. }
  234. #else
  235. ast_log(LOG_ERROR, "TLS client failed: Asterisk is compiled without OpenSSL support. Install OpenSSL development headers and rebuild Asterisk after running ./configure\n");
  236. ast_tcptls_close_session_file(tcptls_session);
  237. ao2_ref(tcptls_session, -1);
  238. return NULL;
  239. #endif /* DO_SSL */
  240. }
  241. if (tcptls_session->parent->worker_fn) {
  242. return tcptls_session->parent->worker_fn(tcptls_session);
  243. } else {
  244. return tcptls_session;
  245. }
  246. }
  247. void *ast_tcptls_server_root(void *data)
  248. {
  249. struct ast_tcptls_session_args *desc = data;
  250. int fd;
  251. struct ast_sockaddr addr;
  252. struct ast_tcptls_session_instance *tcptls_session;
  253. pthread_t launched;
  254. for (;;) {
  255. int i;
  256. if (desc->periodic_fn) {
  257. desc->periodic_fn(desc);
  258. }
  259. i = ast_wait_for_input(desc->accept_fd, desc->poll_timeout);
  260. if (i <= 0) {
  261. /* Prevent tight loop from hogging CPU */
  262. usleep(1);
  263. continue;
  264. }
  265. fd = ast_accept(desc->accept_fd, &addr);
  266. if (fd < 0) {
  267. if (errno != EAGAIN
  268. && errno != EWOULDBLOCK
  269. && errno != EINTR
  270. && errno != ECONNABORTED) {
  271. ast_log(LOG_ERROR, "TCP/TLS accept failed: %s\n", strerror(errno));
  272. if (errno != EMFILE) {
  273. break;
  274. }
  275. }
  276. /* Prevent tight loop from hogging CPU */
  277. usleep(1);
  278. continue;
  279. }
  280. tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
  281. if (!tcptls_session) {
  282. close(fd);
  283. continue;
  284. }
  285. tcptls_session->overflow_buf = ast_str_create(128);
  286. if (!tcptls_session->overflow_buf) {
  287. ao2_ref(tcptls_session, -1);
  288. close(fd);
  289. continue;
  290. }
  291. ast_fd_clear_flags(fd, O_NONBLOCK);
  292. tcptls_session->stream = ast_iostream_from_fd(&fd);
  293. if (!tcptls_session->stream) {
  294. ao2_ref(tcptls_session, -1);
  295. close(fd);
  296. continue;
  297. }
  298. tcptls_session->parent = desc;
  299. ast_sockaddr_copy(&tcptls_session->remote_address, &addr);
  300. tcptls_session->client = 0;
  301. /* This thread is now the only place that controls the single ref to tcptls_session */
  302. if (ast_pthread_create_detached_background(&launched, NULL, handle_tcptls_connection, tcptls_session)) {
  303. ast_log(LOG_ERROR, "TCP/TLS unable to launch helper thread for peer '%s': %s\n",
  304. ast_sockaddr_stringify(&tcptls_session->remote_address),
  305. strerror(errno));
  306. ao2_ref(tcptls_session, -1);
  307. }
  308. }
  309. ast_log(LOG_ERROR, "TCP/TLS listener thread ended abnormally\n");
  310. /* Close the listener socket so Asterisk doesn't appear dead. */
  311. fd = desc->accept_fd;
  312. desc->accept_fd = -1;
  313. if (0 <= fd) {
  314. close(fd);
  315. }
  316. return NULL;
  317. }
  318. #ifdef DO_SSL
  319. static void __ssl_setup_certs(struct ast_tls_config *cfg, const size_t cert_file_len, const char *key_type_extension, const char *key_type)
  320. {
  321. char *cert_file = ast_strdupa(cfg->certfile);
  322. memcpy(cert_file + cert_file_len - 8, key_type_extension, 5);
  323. if (access(cert_file, F_OK) == 0) {
  324. if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cert_file) == 0) {
  325. ast_log(LOG_WARNING, "TLS/SSL error loading public %s key (certificate) from <%s>.\n", key_type, cert_file);
  326. write_openssl_error_to_log();
  327. } else if (SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, cert_file, SSL_FILETYPE_PEM) == 0) {
  328. ast_log(LOG_WARNING, "TLS/SSL error loading private %s key from <%s>.\n", key_type, cert_file);
  329. write_openssl_error_to_log();
  330. } else if (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0) {
  331. ast_log(LOG_WARNING, "TLS/SSL error matching private %s key and certificate in <%s>.\n", key_type, cert_file);
  332. write_openssl_error_to_log();
  333. }
  334. }
  335. }
  336. #endif
  337. static int __ssl_setup(struct ast_tls_config *cfg, int client)
  338. {
  339. #ifndef DO_SSL
  340. if (cfg->enabled) {
  341. ast_log(LOG_ERROR, "TLS server failed: Asterisk is compiled without OpenSSL support. Install OpenSSL development headers and rebuild Asterisk after running ./configure\n");
  342. cfg->enabled = 0;
  343. }
  344. return 0;
  345. #else
  346. int disable_ssl = 0;
  347. long ssl_opts = 0;
  348. if (!cfg->enabled) {
  349. return 0;
  350. }
  351. /* Get rid of an old SSL_CTX since we're about to
  352. * allocate a new one
  353. */
  354. if (cfg->ssl_ctx) {
  355. SSL_CTX_free(cfg->ssl_ctx);
  356. cfg->ssl_ctx = NULL;
  357. }
  358. if (client) {
  359. #if !defined(OPENSSL_NO_SSL2) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
  360. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV2_CLIENT)) {
  361. ast_log(LOG_WARNING, "Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  362. cfg->ssl_ctx = SSL_CTX_new(SSLv2_client_method());
  363. } else
  364. #endif
  365. #if !defined(OPENSSL_NO_SSL3_METHOD) && !(defined(OPENSSL_API_COMPAT) && (OPENSSL_API_COMPAT >= 0x10100000L))
  366. if (ast_test_flag(&cfg->flags, AST_SSL_SSLV3_CLIENT)) {
  367. ast_log(LOG_WARNING, "Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
  368. cfg->ssl_ctx = SSL_CTX_new(SSLv3_client_method());
  369. } else
  370. #endif
  371. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  372. cfg->ssl_ctx = SSL_CTX_new(TLS_client_method());
  373. #else
  374. if (ast_test_flag(&cfg->flags, AST_SSL_TLSV1_CLIENT)) {
  375. cfg->ssl_ctx = SSL_CTX_new(TLSv1_client_method());
  376. } else {
  377. disable_ssl = 1;
  378. cfg->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  379. }
  380. #endif
  381. } else {
  382. disable_ssl = 1;
  383. cfg->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  384. }
  385. if (!cfg->ssl_ctx) {
  386. ast_debug(1, "Sorry, SSL_CTX_new call returned null...\n");
  387. cfg->enabled = 0;
  388. return 0;
  389. }
  390. /* Due to the POODLE vulnerability, completely disable
  391. * SSLv2 and SSLv3 if we are not explicitly told to use
  392. * them. SSLv23_*_method supports TLSv1+.
  393. */
  394. if (disable_ssl) {
  395. ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
  396. }
  397. if (ast_test_flag(&cfg->flags, AST_SSL_SERVER_CIPHER_ORDER)) {
  398. ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
  399. }
  400. if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV1)) {
  401. ssl_opts |= SSL_OP_NO_TLSv1;
  402. }
  403. #if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2)
  404. if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV11)) {
  405. ssl_opts |= SSL_OP_NO_TLSv1_1;
  406. }
  407. if (ast_test_flag(&cfg->flags, AST_SSL_DISABLE_TLSV12)) {
  408. ssl_opts |= SSL_OP_NO_TLSv1_2;
  409. }
  410. #else
  411. ast_log(LOG_WARNING, "Your version of OpenSSL leaves you potentially vulnerable "
  412. "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
  413. #endif
  414. SSL_CTX_set_options(cfg->ssl_ctx, ssl_opts);
  415. SSL_CTX_set_verify(cfg->ssl_ctx,
  416. ast_test_flag(&cfg->flags, AST_SSL_VERIFY_CLIENT) ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE,
  417. NULL);
  418. if (!ast_strlen_zero(cfg->certfile)) {
  419. char *tmpprivate = ast_strlen_zero(cfg->pvtfile) ? cfg->certfile : cfg->pvtfile;
  420. if (SSL_CTX_use_certificate_chain_file(cfg->ssl_ctx, cfg->certfile) == 0) {
  421. if (!client) {
  422. /* Clients don't need a certificate, but if its setup we can use it */
  423. ast_log(LOG_ERROR, "TLS/SSL error loading cert file. <%s>\n", cfg->certfile);
  424. write_openssl_error_to_log();
  425. cfg->enabled = 0;
  426. SSL_CTX_free(cfg->ssl_ctx);
  427. cfg->ssl_ctx = NULL;
  428. return 0;
  429. }
  430. }
  431. if ((SSL_CTX_use_PrivateKey_file(cfg->ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->ssl_ctx) == 0 )) {
  432. if (!client) {
  433. /* Clients don't need a private key, but if its setup we can use it */
  434. ast_log(LOG_ERROR, "TLS/SSL error loading private key file. <%s>\n", tmpprivate);
  435. write_openssl_error_to_log();
  436. cfg->enabled = 0;
  437. SSL_CTX_free(cfg->ssl_ctx);
  438. cfg->ssl_ctx = NULL;
  439. return 0;
  440. }
  441. }
  442. if (!client) {
  443. size_t certfile_len = strlen(cfg->certfile);
  444. /* expects a file name which contains _rsa. like asterisk_rsa.pem
  445. * ignores any 3-character file-extension like .pem, .cer, .crt
  446. */
  447. if (certfile_len >= 8 && !strncmp(cfg->certfile + certfile_len - 8, "_rsa.", 5)) {
  448. __ssl_setup_certs(cfg, certfile_len, "_ecc.", "ECC");
  449. __ssl_setup_certs(cfg, certfile_len, "_dsa.", "DSA");
  450. }
  451. }
  452. }
  453. if (!ast_strlen_zero(cfg->cipher)) {
  454. if (SSL_CTX_set_cipher_list(cfg->ssl_ctx, cfg->cipher) == 0 ) {
  455. if (!client) {
  456. ast_log(LOG_ERROR, "TLS/SSL cipher error <%s>\n", cfg->cipher);
  457. write_openssl_error_to_log();
  458. cfg->enabled = 0;
  459. SSL_CTX_free(cfg->ssl_ctx);
  460. cfg->ssl_ctx = NULL;
  461. return 0;
  462. }
  463. }
  464. }
  465. if (!ast_strlen_zero(cfg->cafile) || !ast_strlen_zero(cfg->capath)) {
  466. if (SSL_CTX_load_verify_locations(cfg->ssl_ctx, S_OR(cfg->cafile, NULL), S_OR(cfg->capath,NULL)) == 0) {
  467. ast_log(LOG_ERROR, "TLS/SSL CA file(%s)/path(%s) error\n", cfg->cafile, cfg->capath);
  468. write_openssl_error_to_log();
  469. }
  470. }
  471. #ifndef OPENSSL_NO_DH
  472. if (!ast_strlen_zero(cfg->pvtfile)) {
  473. BIO *bio = BIO_new_file(cfg->pvtfile, "r");
  474. if (bio != NULL) {
  475. DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  476. if (dh != NULL) {
  477. if (SSL_CTX_set_tmp_dh(cfg->ssl_ctx, dh)) {
  478. long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
  479. options = SSL_CTX_set_options(cfg->ssl_ctx, options);
  480. ast_verb(2, "TLS/SSL DH initialized, PFS cipher-suites enabled\n");
  481. }
  482. DH_free(dh);
  483. }
  484. BIO_free(bio);
  485. }
  486. }
  487. #endif
  488. #ifndef SSL_CTRL_SET_ECDH_AUTO
  489. #define SSL_CTRL_SET_ECDH_AUTO 94
  490. #endif
  491. /* SSL_CTX_set_ecdh_auto(cfg->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
  492. if (SSL_CTX_ctrl(cfg->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
  493. ast_verb(2, "TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
  494. #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
  495. } else {
  496. /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
  497. EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  498. if (ecdh != NULL) {
  499. if (SSL_CTX_set_tmp_ecdh(cfg->ssl_ctx, ecdh)) {
  500. ast_verb(2, "TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
  501. }
  502. EC_KEY_free(ecdh);
  503. }
  504. #endif
  505. }
  506. 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 */
  507. return 1;
  508. #endif
  509. }
  510. int ast_ssl_setup(struct ast_tls_config *cfg)
  511. {
  512. return __ssl_setup(cfg, 0);
  513. }
  514. void ast_ssl_teardown(struct ast_tls_config *cfg)
  515. {
  516. #ifdef DO_SSL
  517. if (cfg && cfg->ssl_ctx) {
  518. SSL_CTX_free(cfg->ssl_ctx);
  519. cfg->ssl_ctx = NULL;
  520. }
  521. #endif
  522. }
  523. /*!
  524. * \internal
  525. * \brief Connect a socket
  526. *
  527. * Attempt to connect to a given address for up to 'timeout' milliseconds. A negative
  528. * timeout value equates to an infinite wait time.
  529. *
  530. * A -1 is returned on error, and an appropriate errno value is set based on the
  531. * type of error.
  532. *
  533. * \param sockfd The socket file descriptor
  534. * \param addr The address to connect to
  535. * \param timeout How long, in milliseconds, to attempt to connect
  536. *
  537. * \return 0 if successfully connected, -1 otherwise
  538. */
  539. static int socket_connect(int sockfd, const struct ast_sockaddr *addr, int timeout)
  540. {
  541. int optval = 0;
  542. socklen_t optlen = sizeof(int);
  543. errno = 0;
  544. if (ast_connect(sockfd, addr)) {
  545. int res;
  546. /*
  547. * A connect failure could mean things are still in progress.
  548. * If so wait for it to complete.
  549. */
  550. if (errno != EINPROGRESS) {
  551. return -1;
  552. }
  553. while ((res = ast_wait_for_output(sockfd, timeout)) != 1) {
  554. if (res == 0) {
  555. errno = ETIMEDOUT;
  556. return -1;
  557. }
  558. if (errno != EINTR) {
  559. return -1;
  560. }
  561. }
  562. }
  563. /* Check the status to ensure it actually connected successfully */
  564. if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) < 0) {
  565. return -1;
  566. }
  567. if (optval) {
  568. errno = optval;
  569. return -1;
  570. }
  571. return 0;
  572. }
  573. struct ast_tcptls_session_instance *ast_tcptls_client_start_timeout(
  574. struct ast_tcptls_session_instance *tcptls_session, int timeout)
  575. {
  576. struct ast_tcptls_session_args *desc;
  577. if (!(desc = tcptls_session->parent)) {
  578. ao2_ref(tcptls_session, -1);
  579. return NULL;
  580. }
  581. if (socket_connect(desc->accept_fd, &desc->remote_address, timeout)) {
  582. ast_log(LOG_WARNING, "Unable to connect %s to %s: %s\n", desc->name,
  583. ast_sockaddr_stringify(&desc->remote_address), strerror(errno));
  584. ao2_ref(tcptls_session, -1);
  585. return NULL;
  586. }
  587. ast_fd_clear_flags(desc->accept_fd, O_NONBLOCK);
  588. if (desc->tls_cfg) {
  589. desc->tls_cfg->enabled = 1;
  590. __ssl_setup(desc->tls_cfg, 1);
  591. }
  592. return handle_tcptls_connection(tcptls_session);
  593. }
  594. struct ast_tcptls_session_instance *ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
  595. {
  596. return ast_tcptls_client_start_timeout(tcptls_session, -1);
  597. }
  598. struct ast_tcptls_session_instance *ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
  599. {
  600. int fd, x = 1;
  601. struct ast_tcptls_session_instance *tcptls_session = NULL;
  602. ast_assert(!desc->tls_cfg
  603. || ast_test_flag(&desc->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER)
  604. || !ast_strlen_zero(desc->hostname));
  605. /* Do nothing if nothing has changed */
  606. if (!ast_sockaddr_cmp(&desc->old_address, &desc->remote_address)) {
  607. ast_debug(1, "Nothing changed in %s\n", desc->name);
  608. return NULL;
  609. }
  610. /* If we return early, there is no connection */
  611. ast_sockaddr_setnull(&desc->old_address);
  612. fd = desc->accept_fd = ast_socket_nonblock(ast_sockaddr_is_ipv6(&desc->remote_address) ?
  613. AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
  614. if (desc->accept_fd < 0) {
  615. ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n",
  616. desc->name, strerror(errno));
  617. return NULL;
  618. }
  619. /* if a local address was specified, bind to it so the connection will
  620. originate from the desired address */
  621. if (!ast_sockaddr_isnull(&desc->local_address) &&
  622. !ast_sockaddr_is_any(&desc->local_address)) {
  623. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  624. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  625. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  626. desc->name,
  627. ast_sockaddr_stringify(&desc->local_address),
  628. strerror(errno));
  629. goto error;
  630. }
  631. }
  632. tcptls_session = ao2_alloc(sizeof(*tcptls_session), session_instance_destructor);
  633. if (!tcptls_session) {
  634. goto error;
  635. }
  636. tcptls_session->overflow_buf = ast_str_create(128);
  637. if (!tcptls_session->overflow_buf) {
  638. goto error;
  639. }
  640. tcptls_session->client = 1;
  641. tcptls_session->stream = ast_iostream_from_fd(&fd);
  642. if (!tcptls_session->stream) {
  643. goto error;
  644. }
  645. /* From here on out, the iostream owns the accept_fd and it will take
  646. * care of closing it when the iostream is closed */
  647. tcptls_session->parent = desc;
  648. tcptls_session->parent->worker_fn = NULL;
  649. ast_sockaddr_copy(&tcptls_session->remote_address,
  650. &desc->remote_address);
  651. /* Set current info */
  652. ast_sockaddr_copy(&desc->old_address, &desc->remote_address);
  653. if (!ast_strlen_zero(desc->hostname)) {
  654. if (ast_iostream_set_sni_hostname(tcptls_session->stream, desc->hostname) != 0) {
  655. ast_log(LOG_WARNING, "Unable to set SNI hostname '%s' on connection '%s'\n",
  656. desc->hostname, desc->name);
  657. }
  658. }
  659. return tcptls_session;
  660. error:
  661. close(desc->accept_fd);
  662. desc->accept_fd = -1;
  663. ao2_cleanup(tcptls_session);
  664. return NULL;
  665. }
  666. void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
  667. {
  668. int x = 1;
  669. int tls_changed = 0;
  670. int sd_socket;
  671. if (desc->tls_cfg) {
  672. char hash[41];
  673. char *str = NULL;
  674. struct stat st;
  675. /* Store the hashes of the TLS certificate etc. */
  676. if (stat(desc->tls_cfg->certfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->certfile))) {
  677. memset(hash, 0, 41);
  678. } else {
  679. ast_sha1_hash(hash, str);
  680. }
  681. ast_free(str);
  682. str = NULL;
  683. memcpy(desc->tls_cfg->certhash, hash, 41);
  684. if (stat(desc->tls_cfg->pvtfile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->pvtfile))) {
  685. memset(hash, 0, 41);
  686. } else {
  687. ast_sha1_hash(hash, str);
  688. }
  689. ast_free(str);
  690. str = NULL;
  691. memcpy(desc->tls_cfg->pvthash, hash, 41);
  692. if (stat(desc->tls_cfg->cafile, &st) || NULL == (str = ast_read_textfile(desc->tls_cfg->cafile))) {
  693. memset(hash, 0, 41);
  694. } else {
  695. ast_sha1_hash(hash, str);
  696. }
  697. ast_free(str);
  698. str = NULL;
  699. memcpy(desc->tls_cfg->cahash, hash, 41);
  700. /* Check whether TLS configuration has changed */
  701. if (!desc->old_tls_cfg) { /* No previous configuration */
  702. tls_changed = 1;
  703. desc->old_tls_cfg = ast_calloc(1, sizeof(*desc->old_tls_cfg));
  704. } else if (memcmp(desc->tls_cfg->certhash, desc->old_tls_cfg->certhash, 41)) {
  705. tls_changed = 1;
  706. } else if (memcmp(desc->tls_cfg->pvthash, desc->old_tls_cfg->pvthash, 41)) {
  707. tls_changed = 1;
  708. } else if (strcmp(desc->tls_cfg->cipher, desc->old_tls_cfg->cipher)) {
  709. tls_changed = 1;
  710. } else if (memcmp(desc->tls_cfg->cahash, desc->old_tls_cfg->cahash, 41)) {
  711. tls_changed = 1;
  712. } else if (strcmp(desc->tls_cfg->capath, desc->old_tls_cfg->capath)) {
  713. tls_changed = 1;
  714. } else if (memcmp(&desc->tls_cfg->flags, &desc->old_tls_cfg->flags, sizeof(desc->tls_cfg->flags))) {
  715. tls_changed = 1;
  716. }
  717. if (tls_changed) {
  718. ast_debug(1, "Changed parameters for %s found\n", desc->name);
  719. }
  720. }
  721. /* Do nothing if nothing has changed */
  722. if (!tls_changed && !ast_sockaddr_cmp(&desc->old_address, &desc->local_address)) {
  723. ast_debug(1, "Nothing changed in %s\n", desc->name);
  724. return;
  725. }
  726. /* If we return early, there is no one listening */
  727. ast_sockaddr_setnull(&desc->old_address);
  728. /* Shutdown a running server if there is one */
  729. if (desc->master != AST_PTHREADT_NULL) {
  730. pthread_cancel(desc->master);
  731. pthread_kill(desc->master, SIGURG);
  732. pthread_join(desc->master, NULL);
  733. }
  734. sd_socket = ast_sd_get_fd(SOCK_STREAM, &desc->local_address);
  735. if (sd_socket != -1) {
  736. if (desc->accept_fd != sd_socket) {
  737. if (desc->accept_fd != -1) {
  738. close(desc->accept_fd);
  739. }
  740. desc->accept_fd = sd_socket;
  741. }
  742. goto systemd_socket_activation;
  743. }
  744. if (desc->accept_fd != -1) {
  745. close(desc->accept_fd);
  746. desc->accept_fd = -1;
  747. }
  748. /* If there's no new server, stop here */
  749. if (ast_sockaddr_isnull(&desc->local_address)) {
  750. ast_debug(2, "Server disabled: %s\n", desc->name);
  751. return;
  752. }
  753. desc->accept_fd = ast_socket_nonblock(ast_sockaddr_is_ipv6(&desc->local_address) ?
  754. AF_INET6 : AF_INET, SOCK_STREAM, 0);
  755. if (desc->accept_fd < 0) {
  756. ast_log(LOG_ERROR, "Unable to allocate socket for %s: %s\n", desc->name, strerror(errno));
  757. return;
  758. }
  759. setsockopt(desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
  760. if (ast_bind(desc->accept_fd, &desc->local_address)) {
  761. ast_log(LOG_ERROR, "Unable to bind %s to %s: %s\n",
  762. desc->name,
  763. ast_sockaddr_stringify(&desc->local_address),
  764. strerror(errno));
  765. goto error;
  766. }
  767. if (listen(desc->accept_fd, 10)) {
  768. ast_log(LOG_ERROR, "Unable to listen for %s!\n", desc->name);
  769. goto error;
  770. }
  771. systemd_socket_activation:
  772. if (ast_pthread_create_background(&desc->master, NULL, desc->accept_fn, desc)) {
  773. ast_log(LOG_ERROR, "Unable to launch thread for %s on %s: %s\n",
  774. desc->name,
  775. ast_sockaddr_stringify(&desc->local_address),
  776. strerror(errno));
  777. goto error;
  778. }
  779. /* Set current info */
  780. ast_sockaddr_copy(&desc->old_address, &desc->local_address);
  781. if (desc->old_tls_cfg) {
  782. ast_free(desc->old_tls_cfg->certfile);
  783. ast_free(desc->old_tls_cfg->pvtfile);
  784. ast_free(desc->old_tls_cfg->cipher);
  785. ast_free(desc->old_tls_cfg->cafile);
  786. ast_free(desc->old_tls_cfg->capath);
  787. desc->old_tls_cfg->certfile = ast_strdup(desc->tls_cfg->certfile);
  788. desc->old_tls_cfg->pvtfile = ast_strdup(desc->tls_cfg->pvtfile);
  789. desc->old_tls_cfg->cipher = ast_strdup(desc->tls_cfg->cipher);
  790. desc->old_tls_cfg->cafile = ast_strdup(desc->tls_cfg->cafile);
  791. desc->old_tls_cfg->capath = ast_strdup(desc->tls_cfg->capath);
  792. memcpy(desc->old_tls_cfg->certhash, desc->tls_cfg->certhash, 41);
  793. memcpy(desc->old_tls_cfg->pvthash, desc->tls_cfg->pvthash, 41);
  794. memcpy(desc->old_tls_cfg->cahash, desc->tls_cfg->cahash, 41);
  795. memcpy(&desc->old_tls_cfg->flags, &desc->tls_cfg->flags, sizeof(desc->old_tls_cfg->flags));
  796. }
  797. return;
  798. error:
  799. close(desc->accept_fd);
  800. desc->accept_fd = -1;
  801. }
  802. void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
  803. {
  804. if (tcptls_session->stream) {
  805. ast_iostream_close(tcptls_session->stream);
  806. tcptls_session->stream = NULL;
  807. } else {
  808. ast_debug(1, "ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
  809. }
  810. }
  811. void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
  812. {
  813. if (desc->master != AST_PTHREADT_NULL) {
  814. pthread_cancel(desc->master);
  815. pthread_kill(desc->master, SIGURG);
  816. pthread_join(desc->master, NULL);
  817. desc->master = AST_PTHREADT_NULL;
  818. }
  819. if (desc->accept_fd != -1) {
  820. close(desc->accept_fd);
  821. }
  822. desc->accept_fd = -1;
  823. if (desc->old_tls_cfg) {
  824. ast_free(desc->old_tls_cfg->certfile);
  825. ast_free(desc->old_tls_cfg->pvtfile);
  826. ast_free(desc->old_tls_cfg->cipher);
  827. ast_free(desc->old_tls_cfg->cafile);
  828. ast_free(desc->old_tls_cfg->capath);
  829. ast_free(desc->old_tls_cfg);
  830. desc->old_tls_cfg = NULL;
  831. }
  832. ast_debug(2, "Stopped server :: %s\n", desc->name);
  833. }
  834. int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
  835. {
  836. if (!strcasecmp(varname, "tlsenable") || !strcasecmp(varname, "sslenable")) {
  837. tls_cfg->enabled = ast_true(value) ? 1 : 0;
  838. } else if (!strcasecmp(varname, "tlscertfile") || !strcasecmp(varname, "sslcert") || !strcasecmp(varname, "tlscert")) {
  839. ast_free(tls_cfg->certfile);
  840. tls_cfg->certfile = ast_strdup(value);
  841. } else if (!strcasecmp(varname, "tlsprivatekey") || !strcasecmp(varname, "sslprivatekey")) {
  842. ast_free(tls_cfg->pvtfile);
  843. tls_cfg->pvtfile = ast_strdup(value);
  844. } else if (!strcasecmp(varname, "tlscipher") || !strcasecmp(varname, "sslcipher")) {
  845. ast_free(tls_cfg->cipher);
  846. tls_cfg->cipher = ast_strdup(value);
  847. } else if (!strcasecmp(varname, "tlscafile")) {
  848. ast_free(tls_cfg->cafile);
  849. tls_cfg->cafile = ast_strdup(value);
  850. } else if (!strcasecmp(varname, "tlscapath") || !strcasecmp(varname, "tlscadir")) {
  851. ast_free(tls_cfg->capath);
  852. tls_cfg->capath = ast_strdup(value);
  853. } else if (!strcasecmp(varname, "tlsverifyclient")) {
  854. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_VERIFY_CLIENT);
  855. } else if (!strcasecmp(varname, "tlsdontverifyserver")) {
  856. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DONT_VERIFY_SERVER);
  857. } else if (!strcasecmp(varname, "tlsbindaddr") || !strcasecmp(varname, "sslbindaddr")) {
  858. if (ast_parse_arg(value, PARSE_ADDR, &tls_desc->local_address))
  859. ast_log(LOG_ERROR, "Invalid %s '%s'\n", varname, value);
  860. } else if (!strcasecmp(varname, "tlsclientmethod") || !strcasecmp(varname, "sslclientmethod")) {
  861. if (!strcasecmp(value, "tlsv1")) {
  862. ast_set_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  863. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  864. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  865. } else if (!strcasecmp(value, "sslv3")) {
  866. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  867. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  868. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  869. } else if (!strcasecmp(value, "sslv2")) {
  870. ast_set_flag(&tls_cfg->flags, AST_SSL_SSLV2_CLIENT);
  871. ast_clear_flag(&tls_cfg->flags, AST_SSL_TLSV1_CLIENT);
  872. ast_clear_flag(&tls_cfg->flags, AST_SSL_SSLV3_CLIENT);
  873. }
  874. } else if (!strcasecmp(varname, "tlsservercipherorder")) {
  875. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_SERVER_CIPHER_ORDER);
  876. } else if (!strcasecmp(varname, "tlsdisablev1")) {
  877. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV1);
  878. } else if (!strcasecmp(varname, "tlsdisablev11")) {
  879. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV11);
  880. } else if (!strcasecmp(varname, "tlsdisablev12")) {
  881. ast_set2_flag(&tls_cfg->flags, ast_true(value), AST_SSL_DISABLE_TLSV12);
  882. } else {
  883. return -1;
  884. }
  885. return 0;
  886. }