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();
 
  383    int suppress_progress_msgs)
 
  387        ast_log(
LOG_ERROR, 
"TLS server failed: Asterisk is compiled without OpenSSL support. Install OpenSSL development headers and rebuild Asterisk after running ./configure\n");
 
  408#if !defined(OPENSSL_NO_SSL2) && (OPENSSL_VERSION_NUMBER < 0x10100000L) 
  410            ast_log(
LOG_WARNING, 
"Usage of SSLv2 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
 
  411            cfg->
ssl_ctx = SSL_CTX_new(SSLv2_client_method());
 
  414#if !defined(OPENSSL_NO_SSL3_METHOD) && !(defined(OPENSSL_API_COMPAT) && (OPENSSL_API_COMPAT >= 0x10100000L)) 
  416            ast_log(
LOG_WARNING, 
"Usage of SSLv3 is discouraged due to known vulnerabilities. Please use 'tlsv1' or leave the TLS method unspecified!\n");
 
  417            cfg->
ssl_ctx = SSL_CTX_new(SSLv3_client_method());
 
  420#if OPENSSL_VERSION_NUMBER >= 0x10100000L 
  421        cfg->
ssl_ctx = SSL_CTX_new(TLS_client_method());
 
  424            cfg->
ssl_ctx = SSL_CTX_new(TLSv1_client_method());
 
  427            cfg->
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
 
  432        cfg->
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
 
  436        ast_debug(1, 
"Sorry, SSL_CTX_new call returned null...\n");
 
  446        ssl_opts |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
 
  450        ssl_opts |= SSL_OP_CIPHER_SERVER_PREFERENCE;
 
  454        ssl_opts |= SSL_OP_NO_TLSv1;
 
  456#if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2) 
  458        ssl_opts |= SSL_OP_NO_TLSv1_1;
 
  461        ssl_opts |= SSL_OP_NO_TLSv1_2;
 
  465            "to the SSL BEAST attack. Please upgrade to OpenSSL 1.0.1 or later\n");
 
  468    SSL_CTX_set_options(cfg->
ssl_ctx, ssl_opts);
 
  470    SSL_CTX_set_verify(cfg->
ssl_ctx,
 
  476        if (SSL_CTX_use_certificate_chain_file(cfg->
ssl_ctx, cfg->
certfile) == 0) {
 
  480                write_openssl_error_to_log();
 
  487        if ((SSL_CTX_use_PrivateKey_file(cfg->
ssl_ctx, tmpprivate, SSL_FILETYPE_PEM) == 0) || (SSL_CTX_check_private_key(cfg->
ssl_ctx) == 0 )) {
 
  490                ast_log(
LOG_ERROR, 
"TLS/SSL error loading private key file. <%s>\n", tmpprivate);
 
  491                write_openssl_error_to_log();
 
  499            size_t certfile_len = strlen(cfg->
certfile);
 
  504            if (certfile_len >= 8 && !strncmp(cfg->
certfile + certfile_len - 8, 
"_rsa.", 5)) {
 
  505                __ssl_setup_certs(cfg, certfile_len, 
"_ecc.", 
"ECC");
 
  506                __ssl_setup_certs(cfg, certfile_len, 
"_dsa.", 
"DSA");
 
  511        if (SSL_CTX_set_cipher_list(cfg->
ssl_ctx, cfg->
cipher) == 0 ) {
 
  514                write_openssl_error_to_log();
 
  525            write_openssl_error_to_log();
 
  531        BIO *bio = BIO_new_file(cfg->
pvtfile, 
"r");
 
  535                if (SSL_CTX_set_tmp_dh(cfg->
ssl_ctx, dh)) {
 
  536                    long options = SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
 
  538                    if (!suppress_progress_msgs) {
 
  539                        ast_verb(2, 
"TLS/SSL DH initialized, PFS cipher-suites enabled\n");
 
  549    #ifndef SSL_CTRL_SET_ECDH_AUTO 
  550        #define SSL_CTRL_SET_ECDH_AUTO 94 
  553    if (SSL_CTX_ctrl(cfg->
ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, 
NULL)) {
 
  554        if (!suppress_progress_msgs) {
 
  555            ast_verb(2, 
"TLS/SSL ECDH initialized (automatic), faster PFS ciphers enabled\n");
 
  557#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L) 
  560        EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
 
  562            if (SSL_CTX_set_tmp_ecdh(cfg->
ssl_ctx, ecdh)) {
 
  563                ast_verb(2, 
"TLS/SSL ECDH initialized (secp256r1), faster PFS cipher-suites enabled\n");
 
  570    if (!suppress_progress_msgs) {
 
  571        ast_verb(2, 
"TLS/SSL certificate ok\n");    
 
 
  611    socklen_t optlen = 
sizeof(int);
 
  623        if (
errno != EINPROGRESS) {
 
  633            if (
errno != EINTR) {
 
  640    if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) < 0) {
 
 
  663        if (!
desc->suppress_connection_msgs) {
 
 
  705                      AF_INET6 : AF_INET, SOCK_STREAM, IPPROTO_TCP);
 
  706    if (
desc->accept_fd < 0) {
 
  716        setsockopt(
desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, 
sizeof(x));
 
  727    if (!tcptls_session) {
 
  735    tcptls_session->
client = 1;
 
  737    if (!tcptls_session->
stream) {
 
  747              &
desc->remote_address);
 
  759    return tcptls_session;
 
  762    close(
desc->accept_fd);
 
  763    desc->accept_fd = -1;
 
 
  787        memcpy(
desc->tls_cfg->certhash, hash, 41);
 
  795        memcpy(
desc->tls_cfg->pvthash, hash, 41);
 
  803        memcpy(
desc->tls_cfg->cahash, hash, 41);
 
  806        if (!
desc->old_tls_cfg) { 
 
  809        } 
else if (memcmp(
desc->tls_cfg->certhash, 
desc->old_tls_cfg->certhash, 41)) {
 
  811        } 
else if (memcmp(
desc->tls_cfg->pvthash, 
desc->old_tls_cfg->pvthash, 41)) {
 
  813        } 
else if (strcmp(
desc->tls_cfg->cipher, 
desc->old_tls_cfg->cipher)) {
 
  815        } 
else if (memcmp(
desc->tls_cfg->cahash, 
desc->old_tls_cfg->cahash, 41)) {
 
  817        } 
else if (strcmp(
desc->tls_cfg->capath, 
desc->old_tls_cfg->capath)) {
 
  819        } 
else if (memcmp(&
desc->tls_cfg->flags, &
desc->old_tls_cfg->flags, 
sizeof(
desc->tls_cfg->flags))) {
 
  824            ast_debug(1, 
"Changed parameters for %s found\n", 
desc->name);
 
  839        pthread_cancel(
desc->master);
 
  840        pthread_kill(
desc->master, SIGURG);
 
  846    if (sd_socket != -1) {
 
  847        if (
desc->accept_fd != sd_socket) {
 
  848            if (
desc->accept_fd != -1) {
 
  849                close(
desc->accept_fd);
 
  851            desc->accept_fd = sd_socket;
 
  854        goto systemd_socket_activation;
 
  857    if (
desc->accept_fd != -1) {
 
  858        close(
desc->accept_fd);
 
  859        desc->accept_fd = -1;
 
  869                 AF_INET6 : AF_INET, SOCK_STREAM, 0);
 
  870    if (
desc->accept_fd < 0) {
 
  875    setsockopt(
desc->accept_fd, SOL_SOCKET, SO_REUSEADDR, &x, 
sizeof(x));
 
  883    if (listen(
desc->accept_fd, 10)) {
 
  888systemd_socket_activation:
 
  899    if (
desc->old_tls_cfg) {
 
  910        memcpy(
desc->old_tls_cfg->certhash, 
desc->tls_cfg->certhash, 41);
 
  911        memcpy(
desc->old_tls_cfg->pvthash, 
desc->tls_cfg->pvthash, 41);
 
  912        memcpy(
desc->old_tls_cfg->cahash, 
desc->tls_cfg->cahash, 41);
 
  913        memcpy(&
desc->old_tls_cfg->flags, &
desc->tls_cfg->flags, 
sizeof(
desc->old_tls_cfg->flags));
 
  919    close(
desc->accept_fd);
 
  920    desc->accept_fd = -1;
 
 
  925    if (tcptls_session->
stream) {
 
  929        ast_debug(1, 
"ast_tcptls_close_session_file invoked on session instance without file or file descriptor\n");
 
 
  936        pthread_cancel(
desc->master);
 
  937        pthread_kill(
desc->master, SIGURG);
 
  941    if (
desc->accept_fd != -1) {
 
  942        close(
desc->accept_fd);
 
  944    desc->accept_fd = -1;
 
  946    if (
desc->old_tls_cfg) {
 
 
  961    if (!strcasecmp(varname, 
"tlsenable") || !strcasecmp(varname, 
"sslenable")) {
 
  963    } 
else if (!strcasecmp(varname, 
"tlscertfile") || !strcasecmp(varname, 
"sslcert") || !strcasecmp(varname, 
"tlscert")) {
 
  966    } 
else if (!strcasecmp(varname, 
"tlsprivatekey") || !strcasecmp(varname, 
"sslprivatekey")) {
 
  969    } 
else if (!strcasecmp(varname, 
"tlscipher") || !strcasecmp(varname, 
"sslcipher")) {
 
  972    } 
else if (!strcasecmp(varname, 
"tlscafile")) {
 
  975    } 
else if (!strcasecmp(varname, 
"tlscapath") || !strcasecmp(varname, 
"tlscadir")) {
 
  978    } 
else if (!strcasecmp(varname, 
"tlsverifyclient")) {
 
  980    } 
else if (!strcasecmp(varname, 
"tlsdontverifyserver")) {
 
  982    } 
else if (!strcasecmp(varname, 
"tlsbindaddr") || !strcasecmp(varname, 
"sslbindaddr")) {
 
  985    } 
else if (!strcasecmp(varname, 
"tlsclientmethod") || !strcasecmp(varname, 
"sslclientmethod")) {
 
  986        if (!strcasecmp(
value, 
"tlsv1")) {
 
  990        } 
else if (!strcasecmp(
value, 
"sslv3")) {
 
  994        } 
else if (!strcasecmp(
value, 
"sslv2")) {
 
  999    } 
else if (!strcasecmp(varname, 
"tlsservercipherorder")) {
 
 1001    } 
else if (!strcasecmp(varname, 
"tlsdisablev1")) {
 
 1003    } 
else if (!strcasecmp(varname, 
"tlsdisablev11")) {
 
 1005    } 
else if (!strcasecmp(varname, 
"tlsdisablev12")) {
 
 
General Definitions for Asterisk top level program Included by asterisk.h to handle platform-specific...
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.
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 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...
static int __ssl_setup(struct ast_tls_config *cfg, int client, int suppress_progress_msgs)
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.