36#include <netinet/in.h>
38#include <openssl/asn1.h>
39#include <openssl/crypto.h>
40#include <openssl/err.h>
41#include <openssl/opensslconf.h>
42#include <openssl/opensslv.h>
43#include <openssl/safestack.h>
44#include <openssl/ssl.h>
45#include <openssl/x509.h>
46#include <openssl/x509v3.h>
48#include <openssl/bio.h>
49#include <openssl/dh.h>
50#include <openssl/pem.h>
53#include <openssl/ec.h>
58#include <sys/socket.h>
85static int check_tcptls_cert_name(ASN1_STRING *cert_str,
const char *
hostname,
const char *
desc)
90 ret = ASN1_STRING_to_UTF8(&
str, cert_str);
91 if (ret < 0 || !
str) {
95 if (strlen((
char *)
str) != ret) {
111static void write_openssl_error_to_log(
void)
117 fp = open_memstream(&buffer, &length);
122 ERR_print_errors_fp(fp);
153 ast_log(
LOG_ERROR,
"Failed to inhibit privilege escalations; killing connection from peer '%s'\n",
167 ast_log(
LOG_ERROR,
"Failed to set user interface status; killing connection from peer '%s'\n",
192 peer = SSL_get_peer_certificate(ssl);
201 res = SSL_get_verify_result(ssl);
202 if (res != X509_V_OK) {
205 X509_verify_cert_error_string(res));
213 X509_NAME *
name = X509_get_subject_name(peer);
214 STACK_OF(GENERAL_NAME) *alt_names;
221 pos = X509_NAME_get_index_by_NID(
name, NID_commonName, pos);
225 str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(
name, pos));
226 if (!check_tcptls_cert_name(
str, tcptls_session->
parent->
hostname,
"common name")) {
233 alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name,
NULL,
NULL);
234 if (alt_names !=
NULL) {
235 int alt_names_count = sk_GENERAL_NAME_num(alt_names);
237 for (pos = 0; pos < alt_names_count; pos++) {
238 const GENERAL_NAME *alt_name = sk_GENERAL_NAME_value(alt_names, pos);
240 if (alt_name->type != GEN_DNS) {
244 if (!check_tcptls_cert_name(alt_name->d.dNSName, tcptls_session->
parent->
hostname,
"alt name")) {
250 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
255 ast_log(
LOG_ERROR,
"Certificate common name from peer '%s' did not match (%s)\n",
266 ast_log(
LOG_ERROR,
"TLS client failed: Asterisk is compiled without OpenSSL support. Install OpenSSL development headers and rebuild Asterisk after running ./configure\n");
276 return tcptls_session;
291 if (
desc->periodic_fn) {
303 &&
errno != EWOULDBLOCK
305 &&
errno != ECONNABORTED) {
307 if (
errno != EMFILE) {
316 if (!tcptls_session) {
330 if (!tcptls_session->
stream) {
339 tcptls_session->
client = 0;
343 ast_log(
LOG_ERROR,
"TCP/TLS unable to launch helper thread for peer '%s': %s\n",
353 fd =
desc->accept_fd;
354 desc->accept_fd = -1;
362static void __ssl_setup_certs(
struct ast_tls_config *cfg,
const size_t cert_file_len,
const char *key_type_extension,
const char *key_type)
366 memcpy(cert_file + cert_file_len - 8, key_type_extension, 5);
367 if (access(cert_file, F_OK) == 0) {
368 if (SSL_CTX_use_certificate_chain_file(cfg->
ssl_ctx, cert_file) == 0) {
369 ast_log(
LOG_WARNING,
"TLS/SSL error loading public %s key (certificate) from <%s>.\n", key_type, cert_file);
370 write_openssl_error_to_log();
371 }
else if (SSL_CTX_use_PrivateKey_file(cfg->
ssl_ctx, cert_file, SSL_FILETYPE_PEM) == 0) {
372 ast_log(
LOG_WARNING,
"TLS/SSL error loading private %s key from <%s>.\n", key_type, cert_file);
373 write_openssl_error_to_log();
374 }
else if (SSL_CTX_check_private_key(cfg->
ssl_ctx) == 0) {
375 ast_log(
LOG_WARNING,
"TLS/SSL error matching private %s key and certificate in <%s>.\n", key_type, cert_file);
376 write_openssl_error_to_log();
386 ast_log(
LOG_ERROR,
"TLS server failed: Asterisk is compiled without OpenSSL support. Install OpenSSL development headers and rebuild Asterisk after running ./configure\n");
407#if !defined(OPENSSL_NO_SSL2) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
409 ast_log(
LOG_WARNING,
"Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
410 cfg->
ssl_ctx = SSL_CTX_new(SSLv2_client_method());
413#if !defined(OPENSSL_NO_SSL3_METHOD) && !(defined(OPENSSL_API_COMPAT) && (OPENSSL_API_COMPAT >= 0x10100000L))
415 ast_log(
LOG_WARNING,
"Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
416 cfg->
ssl_ctx = SSL_CTX_new(SSLv3_client_method());
419#if OPENSSL_VERSION_NUMBER >= 0x10100000L
420 cfg->
ssl_ctx = SSL_CTX_new(TLS_client_method());
423 cfg->
ssl_ctx = SSL_CTX_new(TLSv1_client_method());
426 cfg->
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
431 cfg->
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
435 ast_debug(1,
"Sorry, SSL_CTX_new call returned null...\n");
445 ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
449 ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
453 ssl_opts |= SSL_OP_NO_TLSv1;
455#if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2)
457 ssl_opts |= SSL_OP_NO_TLSv1_1;
460 ssl_opts |= SSL_OP_NO_TLSv1_2;
464 "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
467 SSL_CTX_set_options(cfg->
ssl_ctx, ssl_opts);
469 SSL_CTX_set_verify(cfg->
ssl_ctx,
475 if (SSL_CTX_use_certificate_chain_file(cfg->
ssl_ctx, cfg->
certfile) == 0) {
479 write_openssl_error_to_log();
486 if ((SSL_CTX_use_PrivateKey_file(cfg->
ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->
ssl_ctx) == 0 )) {
489 ast_log(
LOG_ERROR,
"TLS/SSL error loading private key file. <%s>\n", tmpprivate);
490 write_openssl_error_to_log();
498 size_t certfile_len = strlen(cfg->
certfile);
503 if (certfile_len >= 8 && !strncmp(cfg->
certfile + certfile_len - 8,
"_rsa.", 5)) {
504 __ssl_setup_certs(cfg, certfile_len,
"_ecc.",
"ECC");
505 __ssl_setup_certs(cfg, certfile_len,
"_dsa.",
"DSA");
510 if (SSL_CTX_set_cipher_list(cfg->
ssl_ctx, cfg->
cipher) == 0 ) {
513 write_openssl_error_to_log();
524 write_openssl_error_to_log();
530 BIO *bio = BIO_new_file(cfg->
pvtfile,
"r");
534 if (SSL_CTX_set_tmp_dh(cfg->
ssl_ctx, dh)) {
535 long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
537 ast_verb(2,
"TLS/SSL DH initialized, PFS cipher-suites enabled\n");
546 #ifndef SSL_CTRL_SET_ECDH_AUTO
547 #define SSL_CTRL_SET_ECDH_AUTO 94
550 if (SSL_CTX_ctrl(cfg->
ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1,
NULL)) {
551 ast_verb(2,
"TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
552#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
555 EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
557 if (SSL_CTX_set_tmp_ecdh(cfg->
ssl_ctx, ecdh)) {
558 ast_verb(2,
"TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
565 ast_verb(2,
"TLS/SSL certificate ok\n");
604 socklen_t optlen =
sizeof(int);
616 if (
errno != EINPROGRESS) {
626 if (
errno != EINTR) {
633 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) < 0) {
666 desc->tls_cfg->enabled = 1;
697 AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
698 if (
desc->accept_fd < 0) {
708 setsockopt(
desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x,
sizeof(x));
719 if (!tcptls_session) {
727 tcptls_session->
client = 1;
729 if (!tcptls_session->
stream) {
739 &
desc->remote_address);
751 return tcptls_session;
754 close(
desc->accept_fd);
755 desc->accept_fd = -1;
779 memcpy(
desc->tls_cfg->certhash, hash, 41);
787 memcpy(
desc->tls_cfg->pvthash, hash, 41);
795 memcpy(
desc->tls_cfg->cahash, hash, 41);
798 if (!
desc->old_tls_cfg) {
801 }
else if (memcmp(
desc->tls_cfg->certhash,
desc->old_tls_cfg->certhash, 41)) {
803 }
else if (memcmp(
desc->tls_cfg->pvthash,
desc->old_tls_cfg->pvthash, 41)) {
805 }
else if (strcmp(
desc->tls_cfg->cipher,
desc->old_tls_cfg->cipher)) {
807 }
else if (memcmp(
desc->tls_cfg->cahash,
desc->old_tls_cfg->cahash, 41)) {
809 }
else if (strcmp(
desc->tls_cfg->capath,
desc->old_tls_cfg->capath)) {
811 }
else if (memcmp(&
desc->tls_cfg->flags, &
desc->old_tls_cfg->flags,
sizeof(
desc->tls_cfg->flags))) {
816 ast_debug(1,
"Changed parameters for %s found\n",
desc->name);
831 pthread_cancel(
desc->master);
832 pthread_kill(
desc->master, SIGURG);
838 if (sd_socket != -1) {
839 if (
desc->accept_fd != sd_socket) {
840 if (
desc->accept_fd != -1) {
841 close(
desc->accept_fd);
843 desc->accept_fd = sd_socket;
846 goto systemd_socket_activation;
849 if (
desc->accept_fd != -1) {
850 close(
desc->accept_fd);
851 desc->accept_fd = -1;
861 AF_INET6 : AF_INET, SOCK_STREAM, 0);
862 if (
desc->accept_fd < 0) {
867 setsockopt(
desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x,
sizeof(x));
875 if (listen(
desc->accept_fd, 10)) {
880systemd_socket_activation:
891 if (
desc->old_tls_cfg) {
902 memcpy(
desc->old_tls_cfg->certhash,
desc->tls_cfg->certhash, 41);
903 memcpy(
desc->old_tls_cfg->pvthash,
desc->tls_cfg->pvthash, 41);
904 memcpy(
desc->old_tls_cfg->cahash,
desc->tls_cfg->cahash, 41);
905 memcpy(&
desc->old_tls_cfg->flags, &
desc->tls_cfg->flags,
sizeof(
desc->old_tls_cfg->flags));
911 close(
desc->accept_fd);
912 desc->accept_fd = -1;
917 if (tcptls_session->
stream) {
921 ast_debug(1,
"ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
928 pthread_cancel(
desc->master);
929 pthread_kill(
desc->master, SIGURG);
933 if (
desc->accept_fd != -1) {
934 close(
desc->accept_fd);
936 desc->accept_fd = -1;
938 if (
desc->old_tls_cfg) {
953 if (!strcasecmp(varname,
"tlsenable") || !strcasecmp(varname,
"sslenable")) {
955 }
else if (!strcasecmp(varname,
"tlscertfile") || !strcasecmp(varname,
"sslcert") || !strcasecmp(varname,
"tlscert")) {
958 }
else if (!strcasecmp(varname,
"tlsprivatekey") || !strcasecmp(varname,
"sslprivatekey")) {
961 }
else if (!strcasecmp(varname,
"tlscipher") || !strcasecmp(varname,
"sslcipher")) {
964 }
else if (!strcasecmp(varname,
"tlscafile")) {
967 }
else if (!strcasecmp(varname,
"tlscapath") || !strcasecmp(varname,
"tlscadir")) {
970 }
else if (!strcasecmp(varname,
"tlsverifyclient")) {
972 }
else if (!strcasecmp(varname,
"tlsdontverifyserver")) {
974 }
else if (!strcasecmp(varname,
"tlsbindaddr") || !strcasecmp(varname,
"sslbindaddr")) {
977 }
else if (!strcasecmp(varname,
"tlsclientmethod") || !strcasecmp(varname,
"sslclientmethod")) {
978 if (!strcasecmp(
value,
"tlsv1")) {
982 }
else if (!strcasecmp(
value,
"sslv3")) {
986 }
else if (!strcasecmp(
value,
"sslv2")) {
991 }
else if (!strcasecmp(varname,
"tlsservercipherorder")) {
993 }
else if (!strcasecmp(varname,
"tlsdisablev1")) {
995 }
else if (!strcasecmp(varname,
"tlsdisablev11")) {
997 }
else if (!strcasecmp(varname,
"tlsdisablev12")) {
Asterisk main include file. File version handling, generic pbx functions.
void ast_std_free(void *ptr)
#define ast_strdup(str)
A wrapper for strdup()
#define ast_strdupa(s)
duplicate a string in memory from the stack
#define ast_calloc(num, len)
A wrapper for calloc()
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
#define ao2_alloc(data_size, destructor_fn)
Application convenience functions, designed to give consistent look and feel to Asterisk apps.
char * ast_read_textfile(const char *file)
Read a file into asterisk.
General Definitions for Asterisk top level program Included by asterisk.h to handle platform-specific...
Configuration File Parser.
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *p_result,...)
The argument parsing routine.
Support for logging to various files, console and syslog Configuration in file logger....
#define ast_debug(level,...)
Log a DEBUG message.
#define ast_verb(level,...)
I/O Management (derived from Cheops-NG)
int ast_sd_get_fd(int type, const struct ast_sockaddr *addr)
Find a listening file descriptor provided by socket activation.
Generic abstraction for input/output streams.
struct ast_iostream * ast_iostream_from_fd(int *fd)
Create an iostream from a file descriptor.
SSL * ast_iostream_get_ssl(struct ast_iostream *stream)
Get a pointer to an iostream's OpenSSL SSL structure.
int ast_iostream_start_tls(struct ast_iostream **stream, SSL_CTX *ctx, int client)
Begin TLS on an iostream.
int ast_iostream_set_sni_hostname(struct ast_iostream *stream, const char *sni_hostname)
Set the iostream's SNI hostname for TLS client connections.
int ast_iostream_close(struct ast_iostream *stream)
Close an iostream.
Asterisk locking-related definitions:
#define AST_PTHREADT_NULL
static char hostname[MAXHOSTNAMELEN]
int ast_connect(int sockfd, const struct ast_sockaddr *addr)
Wrapper around connect(2) that uses struct ast_sockaddr.
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
int ast_sockaddr_is_ipv6(const struct ast_sockaddr *addr)
Determine if this is an IPv6 address.
int ast_bind(int sockfd, const struct ast_sockaddr *addr)
Wrapper around bind(2) that uses struct ast_sockaddr.
int ast_sockaddr_is_any(const struct ast_sockaddr *addr)
Determine if the address type is unspecified, or "any" address.
int ast_accept(int sockfd, struct ast_sockaddr *addr)
Wrapper around accept(2) that uses struct ast_sockaddr.
static int ast_sockaddr_isnull(const struct ast_sockaddr *addr)
Checks if the ast_sockaddr is null. "null" in this sense essentially means uninitialized,...
int ast_sockaddr_cmp(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares two ast_sockaddr structures.
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
Core PBX routines and definitions.
int ast_thread_inhibit_escalations(void)
Inhibit (in the current thread) the execution of dialplan functions which cause privilege escalations...
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one.
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true"....
static force_inline int attribute_pure ast_strlen_zero(const char *s)
#define ast_str_create(init_len)
Create a malloc'ed dynamic length string.
Socket address structure.
arguments for the accepting thread
struct ast_sockaddr local_address
void *(* worker_fn)(void *)
struct ast_tls_config * tls_cfg
char hostname[MAXHOSTNAMELEN]
describes a server instance
struct ast_iostream * stream
struct ast_sockaddr remote_address
struct ast_tcptls_session_args * parent
struct ast_str * overflow_buf
static int __ssl_setup(struct ast_tls_config *cfg, int client)
static int socket_connect(int sockfd, const struct ast_sockaddr *addr, int timeout)
void ast_tcptls_server_stop(struct ast_tcptls_session_args *desc)
Shutdown a running server if there is one.
int ast_ssl_setup(struct ast_tls_config *cfg)
Set up an SSL server.
void ast_tcptls_server_start(struct ast_tcptls_session_args *desc)
This is a generic (re)start routine for a TCP server, which does the socket/bind/listen and starts a ...
void * ast_tcptls_server_root(void *data)
static void * handle_tcptls_connection(void *data)
creates a FILE * from the fd passed by the accept thread. This operation is potentially expensive (ce...
static void session_instance_destructor(void *obj)
void ast_ssl_teardown(struct ast_tls_config *cfg)
free resources used by an SSL server
struct ast_tcptls_session_instance * ast_tcptls_client_create(struct ast_tcptls_session_args *desc)
Creates a client connection's ast_tcptls_session_instance.
struct ast_tcptls_session_instance * ast_tcptls_client_start_timeout(struct ast_tcptls_session_instance *tcptls_session, int timeout)
Attempt to connect and start a tcptls session within the given timeout.
struct ast_tcptls_session_instance * ast_tcptls_client_start(struct ast_tcptls_session_instance *tcptls_session)
Attempt to connect and start a tcptls session.
int ast_tls_read_conf(struct ast_tls_config *tls_cfg, struct ast_tcptls_session_args *tls_desc, const char *varname, const char *value)
Used to parse conf files containing tls/ssl options.
void ast_tcptls_close_session_file(struct ast_tcptls_session_instance *tcptls_session)
Closes a tcptls session instance's file and/or file descriptor. The tcptls_session will be set to NUL...
Generic support for tcp/tls servers in Asterisk.
@ AST_SSL_DONT_VERIFY_SERVER
@ AST_SSL_IGNORE_COMMON_NAME
@ AST_SSL_SERVER_CIPHER_ORDER
int error(const char *format,...)
#define ast_test_flag(p, flag)
#define ast_socket_nonblock(domain, type, protocol)
Create a non-blocking socket.
int ast_thread_user_interface_set(int is_user_interface)
Set the current thread's user interface status.
#define ast_pthread_create_background(a, b, c, d)
int ast_wait_for_input(int fd, int ms)
#define ast_set2_flag(p, value, flag)
#define ast_clear_flag(p, flag)
int ast_wait_for_output(int fd, int ms)
#define ast_pthread_create_detached_background(a, b, c, d)
#define ast_set_flag(p, flag)
#define ast_fd_clear_flags(fd, flags)
Clear flags on the given file descriptor.
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.