TLS support

Peter Griffiths

unknown

Edited by

Bogdan-Andrei Iancu

Edited by

Cesc Santasusana

Edited by

Klaus Darilion

Revision History
Revision $Revision: 4680 $$Date: 2008-08-12 09:26:43 +0200 (Tue, 12 Aug 2008) $

Table of Contents

1. User's Guide
1.1. Overview
1.2. History
1.3. Scenario
1.4. Compiling TLS support
1.4.1. Dependencies of external libraries
1.5. TLS configuration
1.5.1. Creating CA root certificate
1.5.2. Creating a server or client certificate
1.5.3. Configuring Kamailio to use the certificate
1.5.4. Kamailio TLS authentication behavior
1.6. Kamailio TLS configuration parameters
1.6.1. disable_tls=integer
1.6.2. listen=interface
1.6.3. tls_port_no=number
1.6.4. tls_method=value
1.6.5. tls_certificate=file
1.6.6. tls_private_key=file
1.6.7. tls_ca_list=file
1.6.8. tls_ciphers_list=string
1.6.9. tls_verify_client=number and tls_require_client_certificate=number
1.6.10. tls_verify_server=number
1.6.11. tls_handshake_timeout=number and tls_send_timeout=number
1.6.12. tls_client_domain_avp=number
1.6.13. tls_server_name_avp=number
1.6.14. tls_server_domain, tls_client_domain section
1.7. Kamailio with TLS - script example
2. TLS Developer's Guide
2.1. TLS_CONFIG
2.2. TLS_INIT
2.2.1. ssl context
2.2.2. pre_init_tls
2.2.3. init_tls
2.2.4. destroy_tls
2.2.5. tls_init
2.2.6. ser_malloc, ser_realloc, ser_free
2.3. TLS_SERVER
2.3.1. SSL data per connection
2.3.2. tls_print_errstack
2.3.3. tls_tcpconn_init
2.3.4. tls_tcpconn_clean
2.3.5. tls_blocking_write
2.3.6. tls_read
2.3.7. tls_fix_read_conn
2.4. TLS_DOMAIN
2.4.1. tls_domains
2.4.2. tls_find_server_domain
2.4.3. tls_find_server_domain_server_name
2.4.4. tls_find_client_domain
2.4.5. tls_find_client_domain_name
2.4.6. tls_new__domain
2.4.7. tls_new_server_domain
2.4.8. tls_new_client_domain
2.4.9. tls_new_client_domain_name
2.4.10. tls_free_domains
3. Frequently Asked Questions

Chapter 1. User's Guide

Revision History
Revision $Revision: 5591 $$Date: 2009-02-11 16:07:42 +0100 (Wed, 11 Feb 2009) $

1.1. Overview

TLS is an optional part of the Kamailio's core, not a module. TLS, as defined in the SIP RFC3261, is a mandatory feature for proxys and is used to secure the SIP signalling on a hop-by-hop basis (not end-to-end). TLS works on top of TCP. DTLS, or TLS over UDP is also defined by IETF and may become available in a future release of Kamailio.

1.2. History

The TLS support was originally developed by Peter Griffiths and posted as a patch on SER development mailing list. Thanks to Cesc Santasusana, several problems were fixed and some improvements were added. Later, TLS pseudo variables, name based TLS client domains and TLS server_name extension was added by Klaus Darilion.

The TLS support was simultaneously added in both projects. In SER, the support was committed in a separate “experimental” CVS tree, as patch to the main CVS tree. In Kamailio, the support was integrated directly into the CVS tree, as a built-in component, and is part of stable Kamailio since release >=1.0.0.

Update: Since version 2.0 SER has a new TLS implementation, thus the TLS code and features in SER and Kamailio are different now.

1.3. Scenario

By the increased number of VoIP providers and enterprise SIP installations, the SIP world is continuously growing. More users means more calls and more calls means a high probability for a user to receive calls from totally unknown people or, in the worst case, to receive unwanted calls. SIP is also used for presence and instant messaging, sessions that may contain sensitive data for an individual or a company.

To prevent this, a defense mechanism must be adopted. Since only the called user is fully able to classify a call as being unwanted, the SIP server, based on all information regarding the call should notify the user about the desirability of the call. Information like the caller domain, the received source or the incoming protocol can be very useful for a SIP server to establish the nature of the call.

As this information is quite limited, it is very improbable for a server to be able detect the unwanted calls - there are many calls that it cannot predict anything about its status (neutral calls). So, instead on alerting the called user about unwanted calls, the server can notify the user about calls that are considered trusted - calls for which the server is 100% sure that they are not unwanted.

So, a trust concept must be defined for SIP servers. Which calls are trusted and which are not? A call is trusted if the caller can be identified as a trustable user - a user that we have reliable information about.

Since all the users from a domain that the server hosts are authenticated (or should be), a SIP server can consider all the calls generated by a local user as trusted. Now we have to extend the trust concept to the multi-domain level. A mutual agreement, between several domains, can establish a trusting relationship. So, a domain (called A) will consider also as trusted calls all the calls generated by user from a different domain (called B) and vice-versa. But just an agreement is not enough; since the authentication information is strictly limited to a domain (a domain can authenticate only its own user, not the user from other domains), there is still the problem of checking the authenticity of the caller - he can impersonate (by a false FROM header) a user from a domain that is trusted.

The answer to this problem is TLS (Transport Layer Security). All calls via domain A and domain B will be done via TLS. Authentication in origin domain plus TLS transport between domains will make the call trusted in the target domain. This concept doesn't scale to a larger network, which is why the IETF works on standardizing security for SIP identities.

In order to set up trust between domains, the following requirements must be met:

  • All UAs within both domains must be configured to use a local server as an outbound proxy.

  • all SIP servers must authenticate all the calls generated by their own users.

  • all SIP servers must relay the calls generated be their user to a trusted domain via TLS

Based on this, a server can classify a call as trusted for one of its users only if the call is also generated by one of its users or the call is received from a trusted domain (which is equivalent with a call received via TLS). Untrusted calls will be calls received from users belonging to untrusted domains or from users from trusted domains, but whose calls are not routed via their home server (so, they are not authenticated by their home servers).

Once the server is able to tell if the call is trusted or not, the still open issue is about the mechanism used by server to notify the called user about the nature of the incoming call.

One way to do it is by remotely changing the ringing type of the called user's phone. This can be done by inserting special header into the INVITE request. Such feature is supported by now by several hardphones like CISCO ATA, CISCO 7960 and SNOM. This phones can change their ringing tone based on the present or content of the "Alert-Info" SIP header as follows:

  • CISCO ATA - it has 4 pre-defined ringing types. The Alert-Info header must look like “Alert-info: Bellcore-drX EOH"” where X can be between 1 and 4. Note that 1 is the phone default ringing tone.

  • CISCO 7960 - it has 2 pre-defined ringing types and the possibility of uploading new ones. The “Alert-Info” header must look like “Alert-info: X EOH” where X can be whatever number. When this header is present, the phones will not change the ringing tone, but the ringing pattern. Normally, the phone rings like [ring.........ring..........ring] where [ring] is the ringing tone; if the header is present, the ringing pattern will be [ring.ring.........ring.ring........]. So, to be able to hear some difference between the two patterns (and not only as length), its strongly recommended to have a highly asymmetric ringing type (as the pre-defined are not!!).

  • SNOM - The “Alert-Info” header must look like “Alert-info: URL EOH"” where URL can be a HTTP URL (for example) from where the phone can retrieve a ringing tone.

A script example which implements this scenario can be found in Section 1.7, “Kamailio with TLS - script example”.

1.4. Compiling TLS support

To compile Kamailio with the TLS support, the environment variable TLS must be set. Note that this is required for all make commands (and not only for compiling). There are several ways to set the variable:

  • run all make commands like “TLS=1 make all|clean|install|etc

  • before starting, export the TLS variable like “export TLS=1” (in bash) and use the make commands as usual. NOTE: the exported variable will be available only in current shell!

  • comment (to disable) or uncomment (to enable) the “TLS=1” line in the Makefile file; use the make commands as usual without any limitations.

To enable the server_name (aka SNI) TLS extension an openssl version with TLS extension support must be installed, e.g. openssl 0.9.9 or openssl 0.9.8h. When compiling OpenSSL, run "./configure --enable-tlsext".

1.4.1. Dependencies of external libraries

Kamailio TLS support requires OpenSSL from http://www.openssl.org. For FreeBSD, you can either use the system OpenSSL or OpenSSL from the ports system. In Linux, it's distributed in the following packages:

  • openssl or libssl >= 0.9.6

  • openssl-dev or libssl-dev

1.5. TLS configuration

TLS provides for strong authentication, as well as encryption following authentication. Of course, null encryption can be used, as well as weak authentication mechanisms (for example, anonymous, that is, no authentication).

How does verification work? Verification is the process by which the authentication data provided by the peers is checked. This data consists usually of a signed user or server certificate, plus a chain of trusted certification authorities. If for whatever reason, either of the peers thinks that the handshake is not valid, the TLS connection is not established. The reasons could be many: untrusted server certificate, too weak algorithm, invalid client certificate, no client authentication or expired certificate.

This paragraph describes how to generate all the needed keys and certificates for establishing TLS connections with Kamailio. The described TLS setup is based on the assumption that we run our own certificate authority (CA) and we want to securely connect several Kamailio servers (SIP domain).

Warning

In this setup the private key has no passphrase The client and server keys must not be encrypted (or else Kamailio will ask you for a password on startup or will fail to load the certificates), but you should use a password at least for your CA private key.

1.5.1. Creating CA root certificate

This part must be done only once, disregarding the number of how many interconnected Kamailio servers and users we want to certificate.

Using “kamctl tls rootCA”, you can create a local root CA.

The script will produce the private key (which will be used to sign client and server certificates) and the self-signed certificate for your certificate authority. This certificate will later be installed in all clients and servers as a trusted CA certificate.

1.5.2. Creating a server or client certificate

This part must be done for each Kamailio server interconnected into your TLS enabled network: build a certificate request and sign it with a root CA, your own CA (see above) or a public CA like CAcert.org.

For this purpose you may use the “kamailioctl tls userCERT

The output of the script will be a directory containing all needed TLS files for configuring the Kamailio proxy (private key, signed certificate and CA list)

1.5.3. Configuring Kamailio to use the certificate

Append all the trusted CA root certificates to the CA list file (this list must contain all CA root certificates to be accepted by your server):

If you use the “kamailioctl tls userCERT” command, it will create an one element CA list with the CA used to sign the certificate.

To add more CAs to your list, just do:

  • cat add_cacert.pem >> calist.pem

Now copy intended Kamailio certificate, private key and CA list file (basically the whole content of the kamailioX directory) to your intended machine in some directory (which will be further refer by path “path”). Make sure that the private key is well protected during the process.

There are some Kamailio TLS specific parameters that must be configured in Kamailio configuration file to use the certificate:

  • set up kamailio.cfg to use the certificate:

    tls_certificate=/path/cert.pem

  • set up Kamailio to use the private key :

    tls_private_key=/path/privkey.pem

  • set up Kamailio to use the CA list (optional - makes sense only if tls_verify is turned on)

    tls_ca_list=/path/calist.pem

1.5.4. Kamailio TLS authentication behavior

The "tls_verify_server", "tls_verify_client" and "tls_require_client_certificate" are Kamailio-names for the OpenSSL defined flags:

  • SSL_VERIFY_PEER is tls_verify_client/tls_verify_server

  • SSL_VERIFY_FAIL_IF_NO_PEER_CERT is tls_require_client_certificate (tls_require_client_certificate is only used if tls_verify_client=1)

If your Kamailio is acting as a server (incoming TLS connections), it will always send its server-side certificate to the client. If tls_verify_client is disabled (set to 0), your Kamailio will not request a client-certificate. This means that the client is not authenticated. If tls_verify_client=1, your Kamailio (the server) sends a client-certificate request to the client. But the client is free to not provide any. In this case, tls_require_client_certificate comes into play:

  • tls_require_client_certificate=0 - the verification process will succeed if the client does not provide a certificate, or if it provides one, it verifies correctly against the server's list of trusted certification authorities.

  • tls_require_client_certificate=1 - the verification process will only succeed if the client provides a certificate and this verifies correctly against the server's list of trusted CAs.

If your Kamailio server is acting as a client (outgoing TLS connections), it will always receive a certificate from the peer. If tls_verify_server is disabled (set to 0), Kamailio will not verifiy the certificate and allows TLS connections to servers which do not present a valid certificate. If tls_verify_server=1, Kamailio (as a client) verifies the server certificate and will close the TLS connection if the server certificate is not valid.

For more details see the OpenSSL page “man verify”(1).

1.6. Kamailio TLS configuration parameters

All these parameters can be configured in the kamailio.cfg file, to configure the behavior of Kamailio-TLS.

1.6.1. disable_tls=integer

Disables TLS (no server is created on the listen addresses, no outgoing connections can be set up). A non 0 value means disable.

It's usable only if TLS support was compiled.

Default value is 1 (TLS disabled).

Example 1.1. Set disable_tls variable

...
disable_tls = 1
...
				

1.6.2. listen=interface

Not specific to TLS. Allows to specify the protocol (udp, tcp, tls), the IP address and the port where the listening server will be.

Example 1.2. Set listen variable

...
listen = tls:1.2.3.4:5061
...
				

1.6.3. tls_port_no=number

Sets the default TLS listening port.

It's usable only if TLS support was compiled.

Default value is 5061.

Example 1.3. Set tls_port_no variable

...
tls_port_no = 5062
...
				

1.6.4. tls_method=value

Sets the TLS protocol method which can be:

  • TLSv1 - means Kamailio will accept only TLSv1 connections (RFC3261 conformant).

  • SSLv3 - means Kamailio will accept only SSLv3 connections

  • SSLv2 - means Kamailio will accept only SSLv2 connections (almost all old clients support this).

  • SSLv23 - means Kamailio will accept any of the above methods, but the initial SSL hello must be v2 (in the initial hello all the supported protocols are advertised enabling switching to a higher and more secure version). The initial v2 hello means it will not accept connections from SSLv3 or TLSv1 only clients.

It's usable only if TLS support was compiled.

Default value is SSLv23.

Warning

Best is to use SSLv23, for extended compatibility. Using any of the other will restrict the version to just that one version. In fact, SSLv2 is disabled in the source code; to use it, you need to edit the file tls/tls_init.c

If you want RFC3261 conformance and all your clients support TLSv1 (or you are planning to use encrypted "tunnels" only between different Kamailio proxies) use TLSv1. If you want to support older clients use SSLv23 (in fact most of the applications with SSL support use the SSLv23 method).

Example 1.4. Set tls_method variable

...
tls_method = TLSv1
...
				

1.6.5. tls_certificate=file

Public certificate file for Kamailio in PEM format. It will be used as server-side certificate for incoming TLS connections, and as a client-side certificate for outgoing TLS connections.

See previous chapter Section 1.5.3, “Configuring Kamailio to use the certificate” for more information.

It's usable only if TLS support was compiled.

Default value is "CFG_DIR/cert.pem".

Example 1.5. Set tls_certificate variable

...
tls_certificate="/mycerts/certs/kamailio_server_cert.pem"
...
				

1.6.6. tls_private_key=file

Private key of the above certificate in PEM format. I must be kept in a safe place with tight permissions!

See previous chapter Section 1.5.3, “Configuring Kamailio to use the certificate” for more information.

It's usable only if TLS support was compiled.

Default value is "CFG_DIR/cert.pem".

Example 1.6. Set tls_private_key variable

...
tls_private_key="/mycerts/private/prik.pem"
...
				

1.6.7. tls_ca_list=file

List of trusted CAs. The file contains the certificates accepted, one after the other in PEM format. It MUST be a file, not a folder.

See previous chapter Section 1.5.3, “Configuring Kamailio to use the certificate” for more information.

It's usable only if TLS support was compiled.

Default value is "".

Example 1.7. Set tls_ca_list variable

...
tls_ca_list="/mycerts/certs/ca_list.pem"
...
				

1.6.8. tls_ciphers_list=string

You can specify the list of algorithms for authentication and encryption that you allow. To obtain a list of ciphers and then choose, use the openssl application:

  • openssl ciphers 'ALL:eNULL:!LOW:!EXPORT'

Warning

Do not use the NULL algorithms (no encryption) in production. Use it only for testing!

It's usable only if TLS support was compiled.

It defaults to the OpenSSL default ciphers.

Example 1.8. Set tls_ciphers_list variable

...
tls_ciphers_list="NULL"
...
				

1.6.9. tls_verify_client=number and tls_require_client_certificate=number

Technically, tls_verify_client activates SSL_VERIFY_PEER in the ssl_context. tls_require_client_certificate does the same with SSL_VERIFY_FAIL_IF_NO_PEER_CERT, which is only possible if SSL_VERIFY_PEER is also turned on.

These two parameters are used for incoming TLS connections, where Kamailio acts as server.

See previous chapter Section 1.5.4, “Kamailio TLS authentication behavior” for more information.

It's usable only if TLS support was compiled.

Default value for both is 1.

Example 1.9. Set tls_verify_client and tls_require_client_certificate variable

...
# turn on the strictest and strongest authentication possible
tls_verify_client = 1
tls_require_client_certificate = 1
...
				

1.6.10. tls_verify_server=number

Technically, tls_verify_server activates SSL_VERIFY_PEER in the ssl_context.

This parameter is used for outgoing TLS connections, where Kamailio acts as client.

See previous chapter Section 1.5.4, “Kamailio TLS authentication behavior” for more information.

It's usable only if TLS support was compiled.

Default value is 1.

Example 1.10. Set tls_verify_server variable

...
# turn on the strictest and strongest authentication possible
tls_verify_server = 1
...
				

1.6.11. tls_handshake_timeout=number and tls_send_timeout=number

Timeouts (advanced setting)

It's usable only if TLS support was compiled.

Default value for both is 30.

Example 1.11. Set tls_handshake_timeout and tls_send_timeout variable

...
tls_handshake_timeout=119    # number of seconds
tls_send_timeout=121         # number of seconds
...
				

1.6.12. tls_client_domain_avp=number

This sets the interger AVP used for name based TLS server domains (please see tls_client_domain for more details). Setting the value to 0 disables name based TLS client domains.

It's usable only if TLS support was compiled and if your OpenSSL was compiled with support for name based TLS sessions.

Default value is 0.

Example 1.12. Set tls_client_domain_avp variable

...
tls_client_domain_avp=400    # only integer named AVPs are supported
...
				

1.6.13. tls_server_name_avp=number

This sets the integer AVP used for the server_name TLS extension. If tls_server_name_avp is set, and the AVP is set in the routing script, then the value of the AVP will be set as server_name in the TLS extension during establishment of outgoing TLS connection (TLS ClientHello message, thus Kamailio is acting as TLS client). This enables (if the receiving proxy supports this extension too) virtual TLS domains hosting using a single socket (socket = IP:port). Setting the value to 0 disables server_name extension in the TLS client.

It's usable only if TLS support was compiled, and openssl version was build with support for TLS extensions.

Default value is 0.

Example 1.13. Set tls_server_name_avp variable

...
tls_client_domain_avp=401    # only integer named AVPs are supported
...
route {
   ...
   $avp(i:401) = "biloxy.com";
   ...
   t_relay();
}
				

1.6.14. tls_server_domain, tls_client_domain section

If you only run one domain, the main TLS settings are enough. If you are running several TLS servers (that is, you have more than one listen=tls:ip:port entry in the config file), you can specify some parameters for each of them separately (not all the above).

The wording 'TLS domain' means that this TLS connection will have different TLS parameters than another TLS connection (from another TLS domain). Thus, TLS domains are not directly related to different SIP domains, although they are often used in common. Depending on the direction of the TLS handshake, a TLS domain is called 'client domain' (=outgouing TLS connection) or 'server domain' (= incoming TLS connection).

For example, TLS domains can be used in virtual hosting scenarios with TLS. Kamailio offers SIP service for multiple domains, e.g. atlanta.com and biloxi.com. Altough both domains will be hosted in a common SIP proxy, the SIP proxy needs 2 certificates: One for atlanta.com and one for biloxi.com. For incoming TLS connections, the SIP proxy has to present the respective certificate during the TLS handshake. As the SIP proxy hasn't received a SIP message yet (this is done after the TLS handshake), the SIP proxy can not retrieve the target domain (which will be usually retrieved from the domain in the request URI). Thus, distinction for these domains must be done by using multiple sockets. The socket on which the TLS connection is received, identifies the respective domain. Thus the SIP proxy is able to present the proper certificate. This is called a "socket based TLS server domain". If Kamailio was compiled using an OpenSSL version with TLS extensions support, then Kamailio can use the "server_name" (SNI) extension to find out which certifiate to present to the TLS client. This allows to use a single socket for multiple TLS domains. This is called "server_name based TLS server domain".

Note: If you use server_name based TLS server domains you MUST configure a socket based TLS server domain for the respective socket too. Otherwise the server_name based domains will note work!

For outgoing TLS connections, the SIP proxy usually has to provide a client certificate. In this scenario, Kamailio again supports two different methods to specify the TLS client domains which should be used for connection setup. TLS client domains can be associated with a name (e.g. the domain can be used as name). If the SIP proxy establishes a new outgoing TLS connection, it checks for the TLS client domain AVP (parameter tls_client_domain_avp). If this AVP is set (e.g. in Kamailio.cfg), Kamailio searches for a TLS client domain with the same name and uses the TLS parameters defined in the respective tls_client_domain section. This is called "name based TLS client domain". If the AVP is not set, or a responding name based TLS client domain is not found, Kamailio will try to find a TLS client domain where the remote socket equals the request's destination IP:port. This is called "socket based TLS client domain". If no matching TLS client domain is found, Kamailio will use the default TLS settings for this outgoing TLS request. If Kamailio was compiled using an OpenSSL version with TLS extensions support, then Kamailio can set the "server_name" (SNI) extension to signal the requested domain to the TLS server. To enable this feature, the AVP tls_server_name_avp must be defined and set in the routing script.

Note: If there is already an existing TLS connection to the remote target (socket), it will be reused wether the TLS client domain AVP matches or not. This can be seen as a security issue!

NOTE: Make sure to also configure Kamailio to listen on the specified IP:port.

NOTE: Except tls_handshake_timeout and tls_send_timeout all TLS parameters can be set per TLS domain. If a parameter is not explicit set, the default value will be used.

NOTE: The tls_verify_client and tls_require_client_certificate options can only be configured in TLS server domains, whereas the tls_verify_server option is only valid for configuring TLS client domains.

It's usable only if TLS support was compiled.

Example 1.14. Usage of tls_client_domain and tls_server_domain block

# TLS configuration example
# The SIP proxy will listen on 3 sockets for incoming TLS connections
#   IP_1:port1: we do not specify a server domain for this socket, 
#               thus the default TLS settings (=default TLS server 
#               domain) will be used for TLS requests received on 
#               this socket.
#   IP_2:port2: we specify a socket based TLS server domain for this
#               socket. Thus, incoming requests on this socket will 
#               use this TLS settings.
#   IP_3:port3: This socket will be used as server_name based TLS 
#               server domain. Thus, we specify a "default" TLS 
#               domain for this socket which will be used if the 
#               incoming TLS request does not signal the server_name
#               extension or if the specified server_name is not 
#               configured. Further, some server_name based domains 
#               are configured on this socket.

listen=tls:IP_1:port1
listen=tls:IP_2:port2
listen=tls:IP_3:port3

# specify the default TLS settings (will be used 
# for client and server mode)
disable_tls = 0
tls_verify_server = 0
tls_verify_client = 0
tls_method = TLSv1
tls_require_client_certificate = 0
tls_certificate = "/certs/default/cert.pem"
tls_private_key = "/certs/default/privkey.pem"
tls_ca_list     = "/certs/default/CAs.pem"

# set the TLS client domain AVP
tls_client_domain_avp = 400
tls_server_name_avp   = 401


# socket 1: socket based TLS server domain
#   as we do not define TLS settings for socket 1
#   the default TLS settings will be used.


# socket 2: socket based TLS server domain
tls_server_domain[IP_2:port2] {
    #specify parameters for a domain in particular, otherwise, 
    #it will use the default values. 
    tls_certificate   = "/certs/atlanta.com/cert.pem"
    tls_private_key   = "/certs/atlanta.com/privkey.pem"
    tls_ca_list       = "/certs/atlanta.com/wellknownCAs"
    tls_method        = tlsv1
}


# socket 3: server_name based TLS server domain
#   default domain
tls_server_domain[IP_3:port3] {
    tls_certificate   = "/certs/biloxy.com/cert.pem"
    tls_private_key   = "/certs/biloxy.com/privkey.pem"
    tls_ca_list       = "/certs/wellknownCAs"
    tls_method        = tlsv1
    tls_verify_client = 1
    tls_require_client_certificate = 1
}
#   server_name domain: aaa.example.com
tls_server_domain[IP_3:port3] {
    tls_certificate   = "/certs/aaa.example.com/cert.pem"
    tls_private_key   = "/certs/aaa.example.com/privkey.pem"
    tls_ca_list       = "/certs/aaa.example.com/ca.pem"
    tls_method        = tlsv1
    tls_verify_client = 1
    tls_require_client_certificate = 1
	server_name       = "aaa.example.com"
}
#   server_name domain: bbb.example.com
tls_server_domain[IP_3:port3] {
    tls_certificate   = "/certs/bbb.example.com/cert.pem"
    tls_private_key   = "/certs/bbb.example.com/privkey.pem"
    tls_ca_list       = "/certs/bbb.example.com/ca.pem"
    tls_method        = tlsv1
    tls_verify_client = 1
    tls_require_client_certificate = 1
	server_name       = "bbb.example.com"
}
#   server_name domain: ccc.example.com
tls_server_domain[IP_3:port3] {
    tls_certificate   = "/certs/ccc.example.com/cert.pem"
    tls_private_key   = "/certs/ccc.example.com/privkey.pem"
    tls_ca_list       = "/certs/ccc.example.com/ca.pem"
    tls_method        = tlsv1
    tls_verify_client = 1
    tls_require_client_certificate = 1
	server_name       = "ccc.example.com"
}


# TLS client domains: if non of the below TLS client 
# domains match, the default TLS domains (see above) 
# will be used

# a name based TLS client domain
tls_client_domain["atlanta.com"] {
    tls_certificate = "/certs/atlanta.com/cert.pem"
    tls_private_key = "/certs/atlanta.com/privkey.pem"
    tls_ca_list     = "/certs/wellknownCAs"
    tls_method=tlsv1
    tls_verify_server = 1
}

# another name based TLS client domain
tls_client_domain["biloxi.com"] {
    tls_certificate = "/certs/biloxy.com/cert.pem"
    tls_private_key = "/certs/biloxy.com/privkey.pem"
    tls_ca_list     = "/certs/wellknownCAs"
    tls_method=tlsv1
    tls_verify_server = 0
}

# a socket based TLS client domains (e.g. for 
# TLS based upstream to a SIP-PSTN gateway provider)
# GW IP: 1.2.3.4, GW port: 6677
tls_client_domain[1.2.3.4:6677] {
    tls_certificate = "/certs/local/cert.pem"
    tls_private_key = "/certs/local/privkey.pem"
    tls_ca_list     = "/certs/GWproviderSelfSignedCA"
    tls_method=tlsv1
    tls_verify_server = 1
}

# another socket based TLS client domain
# used for peering in our VoIP Provider Federation XYZ.
# Peer A: IP: 5.5.5.5, port: 5061
tls_client_domain[5.5.5.5:5061] {
    tls_certificate = "/certs/XYZ/mycert.pem"
    tls_private_key = "/certs/XYZ/myprivkey.pem"
    tls_ca_list     = "/certs/XYZ/cacert.pem"
    tls_method=tlsv1
    tls_verify_server = 1
}
# Peer B: IP: 6.6.6.6, port: 5061
tls_client_domain[6.6.6.6:5061] {
    tls_certificate = "/certs/XYZ/mycert.pem"
    tls_private_key = "/certs/XYZ/myprivkey.pem"
    tls_ca_list     = "/certs/XYZ/cacert.pem"
    tls_method=tlsv1
    tls_verify_server = 1
}
# Peer B: IP: 7.7.7.7, port: 5061
tls_client_domain[7.7.7.7:5061] {
    tls_certificate = "/certs/XYZ/mycert.pem"
    tls_private_key = "/certs/XYZ/myprivkey.pem"
    tls_ca_list     = "/certs/XYZ/cacert.pem"
    tls_method=tlsv1
    tls_verify_server = 1
}
...
route{
...
    # calls to other SIP domains (openser is in 
	# "TLS client" mode)

    # - set the proper SSL context (certificate) for local 
	#   hosted domains
    $avp(i:400) = $fd;

	# - set the TLS server_name. usually this will be set
	#   to the callee's domain
    $avp(i:401) = $rd;
    t_relay(); # uses NAPTR and SRV lookups
    exit;
...
    # send calls to the PSTN gateway using TLS
    t_relay("tls:1.2.3.4:6677");
    exit;
...
				

1.7. Kamailio with TLS - script example

IMPORTANT: The TLS support is based on TCP, and for allowing Kamailio to use TCP, it must be started in multi-process mode. So, there is a must to have the "fork" parameter set to "yes":

NOTE: Since the TLS engine is quite memory consuming, increase the used memory by the run time parameter "-m" (see kamailio -h for more details).

  • fork = yes

Example 1.15. Script with TLS support

  # ----------- global configuration parameters ------------------------
  debug=3
  fork=yes
  log_stderror=no

  check_via=no
  dns=no
  rev_dns=no
  listen=_your_serv_IP_
  port=5060
  children=4
  fifo="/tmp/kamailio_fifo"

  #TLS specific settings
  tls_certificate="/path/kamailioX_cert.pem"
  tls_private_key="/path/privkey.pem"
  tls_ca_list="/path/calist.pem"
  tls_verify=on
  tls_require_client_certificate=on

  alias=_DNS_ALIAS_

  # ------------------ module loading ----------------------------------

  loadmodule "modules/sl/sl.so"
  loadmodule "modules/rr/rr.so"
  loadmodule "modules/maxfwd/maxfwd.so"
  loadmodule "modules/mysql/mysql.so"
  loadmodule "modules/usrloc/usrloc.so"
  loadmodule "modules/registrar/registrar.so"
  loadmodule "modules/tm/tm.so"
  loadmodule "modules/auth/auth.so"
  loadmodule "modules/auth_db/auth_db.so"
  loadmodule "modules/textops/textops.so"
  loadmodule "modules/uri_db/uri_db.so"

  # ----------------- setting module-specific parameters ---------------

  # -- auth_db params --
  modparam("auth_db", "db_url", "sql_url")
  modparam("auth_db", "password_column", "password")
  modparam("auth_db", "calculate_ha1", 1)

  # -- registrar params --
  # no multiple registrations
  modparam("registrar", "append_branches", 0)

  # -- rr params --
  # add value to ;lr param to make some broken UAs happy
  modparam("rr", "enable_full_lr", 1)

  # -------------------------  request routing logic -------------------

  # main routing logic

  route{

  # initial sanity checks
  if (!mf_process_maxfwd_header("10")) {
      sl_send_reply("483","Too Many Hops");
      break;
  };

  # if somene claims to belong to our domain in From,
  # challenge him (skip REGISTERs -- we will chalenge them later)
  if (from_uri==myself) {
      setflag(1);
      if ( (method=="INVITE" || method=="SUBSCRIBE" || method=="MESSAGE")
      &&  !(src_ip==myself) ) {
          if  (!(proxy_authorize( "domA.net", "subscriber" ))) {
              proxy_challenge("domA.net","0"/*no-qop*/);
              break;
          };
          if (!check_from()) {
              log("LOG: From Cheating attempt in INVITE\n");
              sl_send_reply("403",
                  "That is ugly -- use From=id next time (OB)");
              break;
          };
      }; # non-REGISTER from other domain
  } else if ( method=="INVITE" && uri!=myself ) {
      sl_send_reply("403", "No relaying");
      break;
  };

  /* ********   do record-route and loose-route ******* */
  if (!(method=="REGISTER"))
      record_route();

  if (loose_route()) {
      append_hf("P-hint: rr-enforced\r\n");
      route(1);
      break;
  };

  /* ******* check for requests targeted out of our domain ******* */
  if ( uri!=myself ) {
      append_hf("P-hint: OUTBOUND\r\n");
      if (uri=~".*@domB.net") {
          t_relay_to_tls("domB.net","5061");
      } else if (uri=~".*@domC.net") {
          t_relay_to_tls("domC.net","5061");
      } else {
          route(1);
      };
      break;
  };

  /* ******* divert to other domain according to prefixes ******* */
  if (method!="REGISTER") {
      if ( uri=~"sip:201") {
          strip(3);
          sethost("domB.net");
          t_relay_to_tls("domB.net","5061");
          break;
      } else if ( uri=~"sip:202" ) {
          strip(3);
          sethost("domC.net");
          t_relay_to_tls("domC.net","5061");
          break;
      };
  };

  /* ************ requests for our domain ********** */
  if (method=="REGISTER") {
      if (!www_authorize( "domA.net", "subscriber" )) {
          # challenge if none or invalid credentials
          www_challenge( "domA.net" /* realm */, 
              "0" /* no qop -- some phones can't deal with it */);
          break;
      };
      if (!check_to()) {
          log("LOG: To Cheating attempt\n");
          sl_send_reply("403", "That is ugly -- use To=id in REGISTERs");
          break;
      };
      # it is an authenticated request, update Contact database now
      if (!save("location")) {
          sl_reply_error();
      };
      break;
  };

  # native SIP destinations are handled using USRLOC DB
  if (!lookup("location")) {
      # handle user which was not found
      sl_send_reply("404", "Not Found");
      break;
  };

  # remove all present Alert-info headers
  remove_hf("Alert-Info");

  if (method=="INVITE" && (proto==tls || isflagset(1))) {
      append_hf("Alert-info: 1\r\n");                     # cisco 7960
      append_hf("Alert-info: Bellcore-dr4\r\n");          # cisco ATA
      append_hf("Alert-info: http://foo.bar/x.wav\r\n");  # snom
  };

  # do forwarding
  if (!t_relay()) {
      sl_reply_error();
  };

  #end of script
  }
		

Chapter 2. TLS Developer's Guide

Revision History
Revision $Revision: 5591 $$Date: 2009-02-11 16:07:42 +0100 (Wed, 11 Feb 2009) $

2.1. TLS_CONFIG

It contains configuration variables for Kamailio's TLS (timeouts, file paths, etc).

2.2. TLS_INIT

Initialization related functions and parameters.

2.2.1. ssl context

extern SSL_CTX *default_client_ctx;

The ssl context is a member of the TLS domain strcuture. Thus, every TLS domain, default and virtual - servers and clients, have its own SSL context.

2.2.2. pre_init_tls

int init_tls(void);

Called once to pre_initialize the tls subsystem, from the main(). Called before parsing the configuration file.

2.2.3. init_tls

int init_tls(void);

Called once to initialize the tls subsystem, from the main(). Called after parsing the configuration file.

2.2.4. destroy_tls

void destroy_tls(void);

Called once, just before cleanup.

2.2.5. tls_init

int tls_init(struct socket_info *c);

Called once for each tls socket created, from main.c

2.2.6. ser_malloc, ser_realloc, ser_free

Wrapper functions around the shm_* functions. OpenSSL uses non-shared memory to create its objects, thus it would not work in Kamailio. By creating these wrappers and configuring OpenSSL to use them instead of its default memory functions, we have all OpenSSL objects in shared memory, ready to use.

2.3. TLS_SERVER

2.3.1. SSL data per connection

Each TLS connection, incoming or outgoing, creates an SSL * object, where configuration inherited from the SSL_CTX * and particular info on that socket are stored. This SSL * structure is kept in Kamailio as long as the connection is alive, as part of the “struct tcp_connection *” object:

...
struct tcp_connection *c;
SSL *ssl;

/*create somehow SSL object*/
c->extra_data = (void *) ssl; 
ssl = (SSL *) c->extra_data;
...

2.3.2. tls_print_errstack

void tls_print_errstack(void);

Dumps ssl error stack.

2.3.3. tls_tcpconn_init

int tls_tcpconn_init( struct tcp_connection *c, int fd);

Called when new tcp connection is accepted

2.3.4. tls_tcpconn_clean

void tls_tcpconn_clean( struct tcp_connection *c);

Shuts down the TLS connection.

2.3.5. tls_blocking_write

size_t tls_blocking_write( struct tcp_connection *c, int fd, const char *buf, size_t len);

Writes a memory chunk in blocking mode (syncron).

2.3.6. tls_read

size_t tls_read( struct tcp_connection *c);

Reads from a TLS connection. Return the number of bytes read.

2.3.7. tls_fix_read_conn

void tls_tcpconn_clean( struct tcp_connection *c);

Shuts down the TLS connection.

2.4. TLS_DOMAIN

2.4.1. tls_domains

extern struct tls_domain *tls_default_server_domain;

The default TLS server domain.

extern struct tls_domain *tls_default_client_domain;

The default TLS client domain.

extern struct tls_domain *tls_server_domains;

List with the configured TLS server domains. Contains (local) socket based and server_name based TLS server domains.

extern struct tls_domain *tls_client_domains;

List with the configured TLS client domains. Contains (remote) socket based and name based TLS client domains.

2.4.2. tls_find_server_domain

struct tls_domain *tls_find_server_domain(struct ip_addr *ip, unsigned short port);

Find a server domain with given ip and port. It will only return server domains which do not have a server_name defined (as to those will be searched for only in the server_name callback function). If a TLS with matching IP:port and empty server_name is not found in the list, it will return the default server domain.

2.4.3. tls_find_server_domain_server_name

struct tls_domain *tls_find_server_domain_server_name(struct ip_addr *ip, unsigned short port, const char *server_name);

Find a server domain with given ip and port and matching server_name. If none is found, it will return 0.

2.4.4. tls_find_client_domain

struct tls_domain *tls_find_client_domain(struct ip_addr *ip, unsigned short port);

Find TLS client domain with given ip and port (socket of the remote destination).

2.4.5. tls_find_client_domain_name

struct tls_domain *tls_find_client_name(str name);

Find TLS client domain with given name.

2.4.6. tls_new__domain

struct tls_domain *tls_new_domain(int type);

Creates new TLS: allocate memory, set the type and initialize members

2.4.7. tls_new_server_domain

int tls_new_server_domain(struct ip_addr *ip, unsigned short port);

Creates and adds to the list of TLS server domains a new domain.

2.4.8. tls_new_client_domain

int tls_new_client_domain(struct ip_addr *ip, unsigned short port);

Creates and adds to the list of TLS client domains a new socket based domain.

2.4.9. tls_new_client_domain_name

int tls_new_client_domain_name(char *s, int len);

Creates and adds to the list of TLS client domains a new name based domain.

2.4.10. tls_free_domains

void tls_free_domains(void);

Cleans up the entire domain lists.

Chapter 3. Frequently Asked Questions

Revision History
Revision $Revision: 5591 $$Date: 2009-02-11 16:07:42 +0100 (Wed, 11 Feb 2009) $
3.1.

Where can I post a question about TLS?

Use one (the most appropriate) of the Kamailio mailing lists:

3.2.

How can I report a bug?

Accumulate as much as possible information (Kamailio version, kamailio -V output, your OS (uname -a), Kamailio logs, network dumps, core dump files, configuration file) and send a mail to http://lists.kamailio.org/cgi-bin/mailman/listinfo/devel

3.3.

How can I debug ssl/tls problems?

You can try to:

  • Increase the log level in openser.cfg (debug=4) and watch the log statements in syslog.

  • Install the ssldump utility and start it. This will give you a trace of the ssl/tls connections, e.g: "ssldump -i any port 5061"

  • You can use the openssl s_client and s_server tool to test the server_name TLS extension.