ef27d08f7f2ad5420f66c4bf3fed0b499bb55470
[kamailio] / src / modules / tls / tls_init.c
1 /*
2  * TLS module
3  *
4  * Copyright (C) 2005,2006 iptelorg GmbH
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 /*! \defgroup tls Kamailio TLS support
20  *
21  * This modules implements SIP over TCP with TLS encryption.
22  * Make sure you read the README file that describes configuration
23  * of TLS for single servers and servers hosting multiple domains,
24  * and thus using multiple SSL/TLS certificates.
25  *
26  *
27  */
28 /*!
29  * \file
30  * \brief Kamailio TLS support :: Initialization
31  * \ingroup tls
32  * Module: \ref tls
33  */
34
35
36
37 #include <stdio.h>
38 #include <sys/types.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <netinet/ip.h>
43 #include <unistd.h>
44 #include <string.h>
45 #include <openssl/ssl.h>
46
47 #include "../../core/dprint.h"
48 #include "../../core/mem/shm_mem.h"
49 #include "../../core/tcp_init.h"
50 #include "../../core/socket_info.h"
51 #include "../../core/pt.h"
52 #include "../../core/cfg/cfg.h"
53 #include "../../core/cfg/cfg_ctx.h"
54 #include "tls_verify.h"
55 #include "tls_domain.h"
56 #include "tls_util.h"
57 #include "tls_mod.h"
58 #include "tls_init.h"
59 #include "tls_locking.h"
60 #include "tls_ct_wrq.h"
61 #include "tls_cfg.h"
62
63 /* will be set to 1 when the TLS env is initialized to make destroy safe */
64 static int tls_mod_preinitialized = 0;
65 static int tls_mod_initialized = 0;
66
67 #if OPENSSL_VERSION_NUMBER < 0x00907000L
68 #    warning ""
69 #    warning "==============================================================="
70 #    warning " Your version of OpenSSL is < 0.9.7."
71 #    warning " Upgrade for better compatibility, features and security fixes!"
72 #    warning "==============================================================="
73 #    warning ""
74 #endif
75
76 /* replace openssl zlib compression with our version if necessary
77  * (the openssl zlib compression uses the wrong malloc, see
78  *  openssl #1468): 0.9.8-dev < version  <0.9.8e-beta1 */
79 #if OPENSSL_VERSION_NUMBER >= 0x00908000L  /* 0.9.8-dev */ && \
80                                                           OPENSSL_VERSION_NUMBER <  0x00908051L  /* 0.9.8.e-beta1 */
81 #    ifndef OPENSSL_NO_COMP
82 #        warning "openssl zlib compression bug workaround enabled"
83 #    endif
84 #    define TLS_FIX_ZLIB_COMPRESSION
85 #    include "fixed_c_zlib.h"
86 #endif
87
88 #ifdef TLS_KSSL_WORKARROUND
89 #if OPENSSL_VERSION_NUMBER < 0x00908050L
90 #       warning "openssl lib compiled with kerberos support which introduces a bug\
91         (wrong malloc/free used in kssl.c) -- attempting workaround"
92 #       warning "NOTE: if you don't link libssl staticaly don't try running the \
93         compiled code on a system with a differently compiled openssl (it's safer \
94                         to compile on the  _target_ system)"
95 #endif /* OPENSSL_VERSION_NUMBER */
96 #endif /* TLS_KSSL_WORKARROUND */
97
98 /* openssl < 1. 0 */
99 #if OPENSSL_VERSION_NUMBER < 0x01000000L
100 #       warning "openssl < 1.0: no TLS extensions or server name support"
101 #endif /* OPENSSL_VERION < 1.0 */
102
103
104
105 #ifndef OPENSSL_NO_COMP
106 #define TLS_COMP_SUPPORT
107 #else
108 #undef TLS_COMP_SUPPORT
109 #endif
110
111 #ifndef OPENSSL_NO_KRB5
112 #define TLS_KERBEROS_SUPPORT
113 #else
114 #undef TLS_KERBEROS_SUPPORT
115 #endif
116
117
118 #ifdef TLS_KSSL_WORKARROUND
119 int openssl_kssl_malloc_bug=0; /* is openssl bug #1467 present ? */
120 #endif
121
122 #if OPENSSL_VERSION_NUMBER < 0x10100000L
123 const SSL_METHOD* ssl_methods[TLS_METHOD_MAX];
124 #else
125 sr_tls_methods_t sr_tls_methods[TLS_METHOD_MAX];
126 #endif
127
128 #ifdef NO_TLS_MALLOC_DBG
129 #undef TLS_MALLOC_DBG /* extra malloc debug info from openssl */
130 #endif /* NO_TLS_MALLOC_DBG */
131
132 /*
133  * Wrappers around SER shared memory functions
134  * (which can be macros)
135  */
136 #ifdef TLS_MALLOC_DBG
137 #warning "tls module compiled with malloc debugging info (extra overhead)"
138 #include <execinfo.h>
139
140 /*
141 #define RAND_NULL_MALLOC (1024)
142 #define NULL_GRACE_PERIOD 10U
143 */
144
145
146
147 #ifndef LIBRESSL_VERSION_NUMBER
148 inline static char* buf_append(char* buf, char* end, char* str, int str_len)
149 {
150         if ( (buf+str_len)<end){
151                 memcpy(buf, str, str_len);
152                 return buf+str_len;
153         }
154         return 0;
155 }
156
157
158 inline static int backtrace2str(char* buf, int size)
159 {
160         void* bt[32];
161         int bt_size, i;
162         char** bt_strs;
163         char* p;
164         char* end;
165         char* next;
166         char* s;
167         char* e;
168
169         p=buf; end=buf+size;
170         bt_size=backtrace(bt, sizeof(bt)/sizeof(bt[0]));
171         bt_strs=backtrace_symbols(bt, bt_size);
172         if (bt_strs){
173                 p=buf; end=buf+size;
174                 /*if (bt_size>16) bt_size=16;*/ /* go up only 12 entries */
175                 for (i=3; i< bt_size; i++){
176                         /* try to isolate only the function name*/
177                         s=strchr(bt_strs[i], '(');
178                         if (s && ((e=strchr(s, ')'))!=0)){
179                                 s++;
180                         }else if ((s=strchr(bt_strs[i], '['))!=0){
181                                 e=s+strlen(s);
182                         }else{
183                                 s=bt_strs[i]; e=s+strlen(s); /* add thw whole string */
184                         }
185                         next=buf_append(p, end, s, (int)(long)(e-s));
186                         if (next==0) break;
187                         else p=next;
188                         if (p<end){
189                                 *p=':'; /* separator */
190                                 p++;
191                         }else break;
192                 }
193                 if (p==buf){
194                         *p=0;
195                         p++;
196                 }else
197                         *(p-1)=0;
198                 free(bt_strs);
199         }
200         return (int)(long)(p-buf);
201 }
202
203 static void* ser_malloc(size_t size, const char* file, int line)
204 {
205         void  *p;
206         char bt_buf[1024];
207         int s;
208 #ifdef RAND_NULL_MALLOC
209         static ticks_t st=0;
210
211         /* start random null returns only after
212          * NULL_GRACE_PERIOD from first call */
213         if (st==0) st=get_ticks();
214         if (((get_ticks()-st)<NULL_GRACE_PERIOD) || (random()%RAND_NULL_MALLOC)){
215 #endif
216                 s=backtrace2str(bt_buf, sizeof(bt_buf));
217                 /* ugly hack: keep the bt inside the alloc'ed fragment */
218                 p=_shm_malloc(size+s, file, "via ser_malloc", line);
219                 if (p==0){
220                         LM_CRIT("tls - ser_malloc(%d)[%s:%d]==null, bt: %s\n",
221                                         size, file, line, bt_buf);
222                 }else{
223                         memcpy(p+size, bt_buf, s);
224                         ((struct qm_frag*)((char*)p-sizeof(struct qm_frag)))->func=
225                                 p+size;
226                 }
227 #ifdef RAND_NULL_MALLOC
228         }else{
229                 p=0;
230                 backtrace2str(bt_buf, sizeof(bt_buf));
231                 LM_CRIT("tls - random ser_malloc(%d)[%s:%d] returning null - bt: %s\n",
232                                 size, file, line, bt_buf);
233         }
234 #endif
235         return p;
236 }
237
238
239 static void* ser_realloc(void *ptr, size_t size, const char* file, int line)
240 {
241         void  *p;
242         char bt_buf[1024];
243         int s;
244 #ifdef RAND_NULL_MALLOC
245         static ticks_t st=0;
246
247         /* start random null returns only after
248          * NULL_GRACE_PERIOD from first call */
249         if (st==0) st=get_ticks();
250         if (((get_ticks()-st)<NULL_GRACE_PERIOD) || (random()%RAND_NULL_MALLOC)){
251 #endif
252                 s=backtrace2str(bt_buf, sizeof(bt_buf));
253                 p=_shm_realloc(ptr, size+s, file, "via ser_realloc", line);
254                 if (p==0){
255                         LM_CRIT("tls - ser_realloc(%p, %d)[%s:%d]==null, bt: %s\n",
256                                         ptr, size, file, line, bt_buf);
257                 }else{
258                         memcpy(p+size, bt_buf, s);
259                         ((struct qm_frag*)((char*)p-sizeof(struct qm_frag)))->func=
260                                 p+size;
261                 }
262 #ifdef RAND_NULL_MALLOC
263         }else{
264                 p=0;
265                 backtrace2str(bt_buf, sizeof(bt_buf));
266                 LM_CRIT("tls - random ser_realloc(%p, %d)[%s:%d]"
267                                 " returning null - bt: %s\n", ptr, size, file, line,
268                                 bt_buf);
269         }
270 #endif
271         return p;
272 }
273 #endif /* LIBRESSL_VERSION_NUMBER */
274
275 #else /*TLS_MALLOC_DBG */
276
277 #ifndef LIBRESSL_VERSION_NUMBER
278
279 #if OPENSSL_VERSION_NUMBER < 0x010100000L
280 static void* ser_malloc(size_t size)
281 {
282         return shm_malloc(size);
283 }
284
285
286 static void* ser_realloc(void *ptr, size_t size)
287 {
288         return shm_realloc(ptr, size);
289 }
290 #else
291 static void* ser_malloc(size_t size, const char *fname, int fline)
292 {
293         return shm_malloc(size);
294 }
295
296
297 static void* ser_realloc(void *ptr, size_t size, const char *fname, int fline)
298 {
299         return shm_realloc(ptr, size);
300 }
301 #endif
302
303 #endif
304
305 #if OPENSSL_VERSION_NUMBER < 0x010100000L
306 static void ser_free(void *ptr)
307 {
308         /* The memory functions provided to openssl needs to behave like standard
309          * memory functions, i.e. free(). Therefore, ser_free must accept NULL
310          * pointers, see:
311          * http://openssl.6102.n7.nabble.com/Custom-free-routine-is-invoked-with-NULL-argument-in-openssl-1-0-1-td25937.html
312          * As shm_free() aborts on null pointers, we have to check for null pointer
313          * here in the wrapper function.
314          */
315         if (ptr) {
316                 shm_free(ptr);
317         }
318 }
319 #else
320 static void ser_free(void *ptr, const char *fname, int fline)
321 {
322         if (ptr) {
323                 shm_free(ptr);
324         }
325 }
326 #endif
327
328 #endif /* LIBRESSL_VERSION_NUMBER */
329
330 /*
331  * Initialize TLS socket
332  */
333 int tls_h_init_si(struct socket_info *si)
334 {
335         int ret;
336         /*
337          * reuse tcp initialization
338          */
339         ret = tcp_init(si);
340         if (ret != 0) {
341                 LM_ERR("Error while initializing TCP part of TLS socket %.*s:%d\n",
342                                 si->address_str.len, si->address_str.s, si->port_no);
343                 goto error;
344         }
345
346         si->proto = PROTO_TLS;
347         return 0;
348
349 error:
350         if (si->socket != -1) {
351                 close(si->socket);
352                 si->socket = -1;
353         }
354         return ret;
355 }
356
357
358
359 /*
360  * initialize ssl methods
361  */
362 static void init_ssl_methods(void)
363 {
364 #if OPENSSL_VERSION_NUMBER < 0x10100000L
365         /* libssl < 1.1.0 */
366         memset(ssl_methods, 0, sizeof(ssl_methods));
367
368         /* any SSL/TLS version */
369         ssl_methods[TLS_USE_SSLv23_cli - 1] = SSLv23_client_method();
370         ssl_methods[TLS_USE_SSLv23_srv - 1] = SSLv23_server_method();
371         ssl_methods[TLS_USE_SSLv23 - 1] = SSLv23_method();
372
373         /* only specific SSL or TLS version */
374 #if OPENSSL_VERSION_NUMBER < 0x010100000L || defined(LIBRESSL_VERSION_NUMBER)
375 #ifndef OPENSSL_NO_SSL2
376         ssl_methods[TLS_USE_SSLv2_cli - 1] = SSLv2_client_method();
377         ssl_methods[TLS_USE_SSLv2_srv - 1] = SSLv2_server_method();
378         ssl_methods[TLS_USE_SSLv2 - 1] = SSLv2_method();
379 #endif
380 #endif
381
382 #ifndef OPENSSL_NO_SSL3_METHOD
383         ssl_methods[TLS_USE_SSLv3_cli - 1] = SSLv3_client_method();
384         ssl_methods[TLS_USE_SSLv3_srv - 1] = SSLv3_server_method();
385         ssl_methods[TLS_USE_SSLv3 - 1] = SSLv3_method();
386 #endif
387
388         ssl_methods[TLS_USE_TLSv1_cli - 1] = TLSv1_client_method();
389         ssl_methods[TLS_USE_TLSv1_srv - 1] = TLSv1_server_method();
390         ssl_methods[TLS_USE_TLSv1 - 1] = TLSv1_method();
391
392 #if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(LIBRESSL_VERSION_NUMBER)
393         ssl_methods[TLS_USE_TLSv1_1_cli - 1] = TLSv1_1_client_method();
394         ssl_methods[TLS_USE_TLSv1_1_srv - 1] = TLSv1_1_server_method();
395         ssl_methods[TLS_USE_TLSv1_1 - 1] = TLSv1_1_method();
396 #endif
397
398 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(LIBRESSL_VERSION_NUMBER)
399         ssl_methods[TLS_USE_TLSv1_2_cli - 1] = TLSv1_2_client_method();
400         ssl_methods[TLS_USE_TLSv1_2_srv - 1] = TLSv1_2_server_method();
401         ssl_methods[TLS_USE_TLSv1_2 - 1] = TLSv1_2_method();
402 #endif
403
404         /* ranges of TLS versions (require a minimum TLS version) */
405         ssl_methods[TLS_USE_TLSv1_PLUS - 1] = (void*)TLS_OP_TLSv1_PLUS;
406
407 #if OPENSSL_VERSION_NUMBER >= 0x1000100fL && !defined(LIBRESSL_VERSION_NUMBER)
408         ssl_methods[TLS_USE_TLSv1_1_PLUS - 1] = (void*)TLS_OP_TLSv1_1_PLUS;
409 #endif
410
411 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(LIBRESSL_VERSION_NUMBER)
412         ssl_methods[TLS_USE_TLSv1_2_PLUS - 1] = (void*)TLS_OP_TLSv1_2_PLUS;
413 #endif
414
415 #else
416         /* openssl 1.1.0+ */
417         memset(sr_tls_methods, 0, sizeof(sr_tls_methods));
418
419         /* any SSL/TLS version */
420         sr_tls_methods[TLS_USE_SSLv23_cli - 1].TLSMethod = TLS_client_method();
421         sr_tls_methods[TLS_USE_SSLv23_srv - 1].TLSMethod = TLS_server_method();
422         sr_tls_methods[TLS_USE_SSLv23 - 1].TLSMethod = TLS_method();
423
424 #ifndef OPENSSL_NO_SSL3_METHOD
425         sr_tls_methods[TLS_USE_SSLv3_cli - 1].TLSMethod = TLS_client_method();
426         sr_tls_methods[TLS_USE_SSLv3_cli - 1].TLSMethodMin = SSL3_VERSION;
427         sr_tls_methods[TLS_USE_SSLv3_cli - 1].TLSMethodMax = SSL3_VERSION;
428         sr_tls_methods[TLS_USE_SSLv3_srv - 1].TLSMethod = TLS_server_method();
429         sr_tls_methods[TLS_USE_SSLv3_srv - 1].TLSMethodMin = SSL3_VERSION;
430         sr_tls_methods[TLS_USE_SSLv3_srv - 1].TLSMethodMax = SSL3_VERSION;
431         sr_tls_methods[TLS_USE_SSLv3 - 1].TLSMethod = TLS_method();
432         sr_tls_methods[TLS_USE_SSLv3 - 1].TLSMethodMin = SSL3_VERSION;
433         sr_tls_methods[TLS_USE_SSLv3 - 1].TLSMethodMax = SSL3_VERSION;
434 #endif
435
436         sr_tls_methods[TLS_USE_TLSv1_cli - 1].TLSMethod = TLS_client_method();
437         sr_tls_methods[TLS_USE_TLSv1_cli - 1].TLSMethodMin = TLS1_VERSION;
438         sr_tls_methods[TLS_USE_TLSv1_cli - 1].TLSMethodMax = TLS1_VERSION;
439         sr_tls_methods[TLS_USE_TLSv1_srv - 1].TLSMethod = TLS_server_method();
440         sr_tls_methods[TLS_USE_TLSv1_srv - 1].TLSMethodMin = TLS1_VERSION;
441         sr_tls_methods[TLS_USE_TLSv1_srv - 1].TLSMethodMax = TLS1_VERSION;
442         sr_tls_methods[TLS_USE_TLSv1 - 1].TLSMethod = TLS_method();
443         sr_tls_methods[TLS_USE_TLSv1 - 1].TLSMethodMin = TLS1_VERSION;
444         sr_tls_methods[TLS_USE_TLSv1 - 1].TLSMethodMax = TLS1_VERSION;
445
446         sr_tls_methods[TLS_USE_TLSv1_1_cli - 1].TLSMethod = TLS_client_method();
447         sr_tls_methods[TLS_USE_TLSv1_1_cli - 1].TLSMethodMin = TLS1_1_VERSION;
448         sr_tls_methods[TLS_USE_TLSv1_1_cli - 1].TLSMethodMax = TLS1_1_VERSION;
449         sr_tls_methods[TLS_USE_TLSv1_1_srv - 1].TLSMethod = TLS_server_method();
450         sr_tls_methods[TLS_USE_TLSv1_1_srv - 1].TLSMethodMin = TLS1_1_VERSION;
451         sr_tls_methods[TLS_USE_TLSv1_1_srv - 1].TLSMethodMax = TLS1_1_VERSION;
452         sr_tls_methods[TLS_USE_TLSv1_1 - 1].TLSMethod = TLS_method();
453         sr_tls_methods[TLS_USE_TLSv1_1 - 1].TLSMethodMin = TLS1_1_VERSION;
454         sr_tls_methods[TLS_USE_TLSv1_1 - 1].TLSMethodMax = TLS1_1_VERSION;
455
456         sr_tls_methods[TLS_USE_TLSv1_2_cli - 1].TLSMethod = TLS_client_method();
457         sr_tls_methods[TLS_USE_TLSv1_2_cli - 1].TLSMethodMin = TLS1_2_VERSION;
458         sr_tls_methods[TLS_USE_TLSv1_2_cli - 1].TLSMethodMax = TLS1_2_VERSION;
459         sr_tls_methods[TLS_USE_TLSv1_2_srv - 1].TLSMethod = TLS_server_method();
460         sr_tls_methods[TLS_USE_TLSv1_2_srv - 1].TLSMethodMin = TLS1_2_VERSION;
461         sr_tls_methods[TLS_USE_TLSv1_2_srv - 1].TLSMethodMax = TLS1_2_VERSION;
462         sr_tls_methods[TLS_USE_TLSv1_2 - 1].TLSMethod = TLS_method();
463         sr_tls_methods[TLS_USE_TLSv1_2 - 1].TLSMethodMin = TLS1_2_VERSION;
464         sr_tls_methods[TLS_USE_TLSv1_2 - 1].TLSMethodMax = TLS1_2_VERSION;
465
466         /* ranges of TLS versions (require a minimum TLS version) */
467         sr_tls_methods[TLS_USE_TLSv1_PLUS - 1].TLSMethod = TLS_method();
468         sr_tls_methods[TLS_USE_TLSv1_PLUS - 1].TLSMethodMin = TLS1_VERSION;
469
470         sr_tls_methods[TLS_USE_TLSv1_1_PLUS - 1].TLSMethod = TLS_method();
471         sr_tls_methods[TLS_USE_TLSv1_1_PLUS - 1].TLSMethodMin = TLS1_1_VERSION;
472
473         sr_tls_methods[TLS_USE_TLSv1_2_PLUS - 1].TLSMethod = TLS_method();
474         sr_tls_methods[TLS_USE_TLSv1_2_PLUS - 1].TLSMethodMin = TLS1_2_VERSION;
475
476 #endif
477 }
478
479
480 /*
481  * Fix openssl compression bugs if necessary
482  */
483 static int init_tls_compression(void)
484 {
485 #ifndef LIBRESSL_VERSION_NUMBER
486 #if OPENSSL_VERSION_NUMBER < 0x010100000L
487 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
488         int n, r;
489         STACK_OF(SSL_COMP)* comp_methods;
490         SSL_COMP* zlib_comp;
491         long ssl_version;
492
493         /* disabling compression */
494 #       ifndef SSL_COMP_ZLIB_IDX
495 #               define SSL_COMP_ZLIB_IDX 1 /* openssl/ssl/ssl_ciph.c:84 */
496 #       endif
497         comp_methods = SSL_COMP_get_compression_methods();
498         if (comp_methods == 0) {
499                 LM_INFO("compression support disabled in the"
500                                 " openssl lib\n");
501                 goto end; /* nothing to do, exit */
502         } else if (cfg_get(tls, tls_cfg, disable_compression)){
503                 LM_INFO("disabling compression...\n");
504                 sk_SSL_COMP_zero(comp_methods);
505         }else{
506                 ssl_version=SSLeay();
507                 /* replace openssl zlib compression with our version if necessary
508                  * (the openssl zlib compression uses the wrong malloc, see
509                  *  openssl #1468): 0.9.8-dev < version  <0.9.8e-beta1 */
510                 if ((ssl_version >= 0x00908000L) && (ssl_version < 0x00908051L)){
511                         /* the above SSL_COMP_get_compression_methods() call has the side
512                          * effect of initializing the compression stack (if not already
513                          * initialized) => after it zlib is initialized and in the stack */
514                         /* find zlib_comp (cannot use ssl3_comp_find, not exported) */
515                         n = sk_SSL_COMP_num(comp_methods);
516                         zlib_comp = 0;
517                         for (r = 0; r < n; r++) {
518                                 zlib_comp = sk_SSL_COMP_value(comp_methods, r);
519                                 LM_DBG("found compression method %p id %d\n",
520                                                 zlib_comp, zlib_comp->id);
521                                 if (zlib_comp->id == SSL_COMP_ZLIB_IDX) {
522                                         LM_DBG("found zlib compression (%d)\n",
523                                                         SSL_COMP_ZLIB_IDX);
524                                         break /* found */;
525                                 } else {
526                                         zlib_comp = 0;
527                                 }
528                         }
529                         if (zlib_comp == 0) {
530                                 LM_INFO("no openssl zlib compression found\n");
531                         }else{
532                                 LM_WARN("detected openssl lib with "
533                                                 "known zlib compression bug: \"%s\" (0x%08lx)\n",
534                                                 SSLeay_version(SSLEAY_VERSION), ssl_version);
535 #       ifdef TLS_FIX_ZLIB_COMPRESSION
536                                 LM_WARN("enabling openssl zlib compression "
537                                                 "bug workaround (replacing zlib COMP method with "
538                                                 "our own version)\n");
539                                 /* hack: make sure that the CRYPTO_EX_INDEX_COMP class is empty
540                                  * and it does not contain any free_ex_data from the
541                                  * built-in zlib. This can happen if the current openssl
542                                  * zlib malloc fix patch is used (CRYPTO_get_ex_new_index() in
543                                  * COMP_zlib()). Unfortunately the only way
544                                  * to do this it to cleanup all the ex_data stuff.
545                                  * It should be safe if this is executed before SSL_init()
546                                  * (only the COMP class is initialized before).
547                                  */
548                                 CRYPTO_cleanup_all_ex_data();
549
550                                 if (fixed_c_zlib_init() != 0) {
551                                         LM_CRIT("BUG: failed to initialize zlib"
552                                                         " compression fix, disabling compression...\n");
553                                         sk_SSL_COMP_zero(comp_methods); /* delete compression */
554                                         goto end;
555                                 }
556                                 /* "fix" it */
557                                 zlib_comp->method = &zlib_method;
558 #       else
559                                 LM_WARN("disabling openssl zlib compression \n");
560                                 zlib_comp=sk_SSL_COMP_delete(comp_methods, r);
561                                 if (zlib_comp)
562                                         OPENSSL_free(zlib_comp);
563 #       endif
564                         }
565                 }
566         }
567 end:
568 #endif /* OPENSSL_VERSION_NUMBER >= 0.9.8 */
569 #endif /* OPENSSL_VERSION_NUMBER < 1.1.0 */
570 #endif /* LIBRESSL_VERSION_NUMBER */
571         return 0;
572 }
573
574
575 /**
576  * tls pre-init function
577  * - executed when module is loaded
578  */
579 int tls_pre_init(void)
580 {
581 #ifndef LIBRESSL_VERSION_NUMBER
582 #if OPENSSL_VERSION_NUMBER < 0x010100000L
583         void *(*mf)(size_t) = NULL;
584         void *(*rf)(void *, size_t) = NULL;
585         void (*ff)(void *) = NULL;
586 #else
587         void *(*mf)(size_t, const char *, int) = NULL;
588         void *(*rf)(void *, size_t, const char *, int) = NULL;
589         void (*ff)(void *, const char *, int) = NULL;
590 #endif
591
592         /*
593          * this has to be called before any function calling CRYPTO_malloc,
594          * CRYPTO_malloc will set allow_customize in openssl to 0
595          */
596 #ifdef TLS_MALLOC_DBG
597         if (!CRYPTO_set_mem_ex_functions(ser_malloc, ser_realloc, ser_free)) {
598 #else
599         if (!CRYPTO_set_mem_functions(ser_malloc, ser_realloc, ser_free)) {
600 #endif
601                 LM_ERR("Unable to set the memory allocation functions\n");
602                 CRYPTO_get_mem_functions(&mf, &rf, &ff);
603                 LM_ERR("libssl current mem functions - m: %p r: %p f: %p\n",
604                                         mf, rf, ff);
605                 LM_ERR("Be sure tls module is loaded before any other module using"
606                                 " libssl (can be loaded first to be safe)\n");
607                 return -1;
608         }
609 #endif /* LIBRESSL_VERSION_NUMBER */
610
611         if (tls_init_locks()<0)
612                 return -1;
613
614         init_tls_compression();
615
616         return 0;
617 }
618
619 /**
620  * tls mod pre-init function
621  * - executed before any mod_init()
622  */
623 int tls_mod_pre_init_h(void)
624 {
625         if(tls_mod_preinitialized==1) {
626                 LM_DBG("already mod pre-initialized\n");
627                 return 0;
628         }
629         LM_DBG("preparing tls env for modules initialization\n");
630         SSL_library_init();
631         SSL_load_error_strings();
632         tls_mod_preinitialized=1;
633         return 0;
634 }
635
636 /*
637  * First step of TLS initialization
638  */
639 int init_tls_h(void)
640 {
641         /*struct socket_info* si;*/
642         long ssl_version;
643 #if OPENSSL_VERSION_NUMBER < 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
644         int lib_kerberos;
645         int lib_zlib;
646         int kerberos_support;
647         int comp_support;
648         const char* lib_cflags;
649 #endif
650         int low_mem_threshold1;
651         int low_mem_threshold2;
652         str tls_grp;
653         str s;
654         cfg_ctx_t* cfg_ctx;
655
656         if(tls_mod_initialized == 1) {
657                 LM_DBG("already initialized\n");
658                 return 0;
659         }
660         LM_DBG("initializing tls system\n");
661
662 #if OPENSSL_VERSION_NUMBER < 0x00907000L
663         LM_WARN("You are using an old version of OpenSSL (< 0.9.7). Upgrade!\n");
664 #endif
665         ssl_version=SSLeay();
666         /* check if version have the same major minor and fix level
667          * (e.g. 0.9.8a & 0.9.8c are ok, but 0.9.8 and 0.9.9x are not)
668          * - values is represented as 0xMMNNFFPPS: major minor fix patch status
669          *   0x00090705f == 0.9.7e release */
670         if ((ssl_version>>12)!=(OPENSSL_VERSION_NUMBER>>12)){
671                 LM_CRIT("installed openssl library"
672                                 " version is too different from the library the " NAME " tls"
673                                 " module was compiled with: installed \"%s\" (0x%08lx),"
674                                 " compiled \"%s\" (0x%08lx).\n"
675                                 " Please make sure a compatible version is used"
676                                 " (tls_force_run in kamailio.cfg will override this check)\n",
677                                 SSLeay_version(SSLEAY_VERSION), ssl_version,
678                                 OPENSSL_VERSION_TEXT, (long)OPENSSL_VERSION_NUMBER);
679                 if (cfg_get(tls, tls_cfg, force_run))
680                         LM_WARN("tls_force_run turned on, ignoring "
681                                         " openssl version mismatch\n");
682                 else
683                         return -1; /* safer to exit */
684         }
685
686         /* check kerberos support using compile flags only for version < 1.1.0 */
687 #if OPENSSL_VERSION_NUMBER < 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
688
689 #ifdef TLS_KERBEROS_SUPPORT
690         kerberos_support=1;
691 #else
692         kerberos_support=0;
693 #endif
694 #ifdef TLS_COMP_SUPPORT
695         comp_support=1;
696 #else
697         comp_support=0;
698 #endif
699         /* attempt to guess if the library was compiled with kerberos or
700          * compression support from the cflags */
701         lib_cflags=SSLeay_version(SSLEAY_CFLAGS);
702         lib_kerberos=0;
703         lib_zlib=0;
704         if ((lib_cflags==0) || strstr(lib_cflags, "not available")){
705                 lib_kerberos=-1;
706                 lib_zlib=-1;
707         }else{
708                 if (strstr(lib_cflags, "-DZLIB"))
709                         lib_zlib=1;
710                 if (strstr(lib_cflags, "-DKRB5_"))
711                         lib_kerberos=1;
712         }
713         LM_INFO("compiled  with  openssl  version "
714                         "\"%s\" (0x%08lx), kerberos support: %s, compression: %s\n",
715                         OPENSSL_VERSION_TEXT, (long)OPENSSL_VERSION_NUMBER,
716                         kerberos_support?"on":"off", comp_support?"on":"off");
717         LM_INFO("installed openssl library version "
718                         "\"%s\" (0x%08lx), kerberos support: %s, "
719                         " zlib compression: %s"
720                         "\n %s\n",
721                         SSLeay_version(SSLEAY_VERSION), ssl_version,
722                         (lib_kerberos==1)?"on":(lib_kerberos==0)?"off":"unknown",
723                         (lib_zlib==1)?"on":(lib_zlib==0)?"off":"unknown",
724                         SSLeay_version(SSLEAY_CFLAGS));
725         if (lib_kerberos!=kerberos_support){
726                 if (lib_kerberos!=-1){
727                         LM_CRIT("openssl compile options"
728                                         " mismatch: library has kerberos support"
729                                         " %s and Kamailio tls %s (unstable configuration)\n"
730                                         " (tls_force_run in " NAME ".cfg will override this"
731                                         " check)\n",
732                                         lib_kerberos?"enabled":"disabled",
733                                         kerberos_support?"enabled":"disabled"
734                            );
735                         if (cfg_get(tls, tls_cfg, force_run))
736                                 LM_WARN("tls_force_run turned on, "
737                                                 "ignoring kerberos support mismatch\n");
738                         else
739                                 return -1; /* exit, is safer */
740                 }else{
741                         LM_WARN("openssl  compile options"
742                                         " missing -- cannot detect if kerberos support is"
743                                         " enabled. Possible unstable configuration\n");
744                 }
745         }
746
747 #ifdef TLS_KSSL_WORKARROUND
748         /* if openssl compiled with kerberos support, and openssl < 0.9.8e-dev
749          * or openssl between 0.9.9-dev and 0.9.9-beta1 apply workaround for
750          * openssl bug #1467 */
751         if (ssl_version < 0x00908050L ||
752                         (ssl_version >= 0x00909000L && ssl_version < 0x00909001L)){
753                 openssl_kssl_malloc_bug=1;
754                 LM_WARN("openssl kerberos malloc bug detected, "
755                                 " kerberos support will be disabled...\n");
756         }
757 #endif
758
759 #endif /* libssl version < 1.1.0 (OPENSSL_VERSION_NUMBER < 0x010100000L) */
760
761         /* set free memory threshold for openssl bug #1491 workaround */
762         low_mem_threshold1 = cfg_get(tls, tls_cfg, low_mem_threshold1);
763         low_mem_threshold2 = cfg_get(tls, tls_cfg, low_mem_threshold2);
764         if (low_mem_threshold1<0){
765                 /* default */
766                 low_mem_threshold1=512*1024*get_max_procs();
767         }else
768                 low_mem_threshold1*=1024; /* KB */
769         if (low_mem_threshold2<0){
770                 /* default */
771                 low_mem_threshold2=256*1024*get_max_procs();
772         }else
773                 low_mem_threshold2*=1024; /* KB */
774         if ((low_mem_threshold1==0) || (low_mem_threshold2==0))
775          LM_WARN("tls: openssl bug #1491 (crash/mem leaks on low memory)"
776                                 " workarround disabled\n");
777         else
778                 LM_WARN("openssl bug #1491 (crash/mem leaks on low memory)"
779                                 " workaround enabled (on low memory tls operations will fail"
780                                 " preemptively) with free memory thresholds %d and %d bytes\n",
781                                 low_mem_threshold1, low_mem_threshold2);
782
783         if (shm_available()==(unsigned long)(-1)){
784                 LM_WARN(NAME " is compiled without MALLOC_STATS support:"
785                                 " the workaround for low mem. openssl bugs will _not_ "
786                                 "work\n");
787                 low_mem_threshold1=0;
788                 low_mem_threshold2=0;
789         }
790         if ((low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1))
791                         || (low_mem_threshold2
792                                 != cfg_get(tls, tls_cfg, low_mem_threshold2))) {
793                 /* ugly hack to set the initial values for the mem tresholds */
794                 if (cfg_register_ctx(&cfg_ctx, 0)) {
795                         LM_ERR("failed to register cfg context\n");
796                         return -1;
797                 }
798                 tls_grp.s = "tls";
799                 tls_grp.len = strlen(tls_grp.s);
800                 s.s = "low_mem_threshold1";
801                 s.len = strlen(s.s);
802                 if (low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1) &&
803                                 cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
804                                         low_mem_threshold1)) {
805                         LM_ERR("failed to set tls.low_mem_threshold1 to %d\n",
806                                         low_mem_threshold1);
807                         return -1;
808                 }
809                 s.s = "low_mem_threshold2";
810                 s.len = strlen(s.s);
811                 if (low_mem_threshold2 != cfg_get(tls, tls_cfg, low_mem_threshold2) &&
812                                 cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
813                                         low_mem_threshold2)) {
814                         LM_ERR("failed to set tls.low_mem_threshold1 to %d\n",
815                                         low_mem_threshold2);
816                         return -1;
817                 }
818         }
819
820         init_ssl_methods();
821         tls_mod_initialized = 1;
822         return 0;
823 }
824
825
826 /*
827  * Make sure that all server domains in the configuration have corresponding
828  * listening socket in SER
829  */
830 int tls_check_sockets(tls_domains_cfg_t* cfg)
831 {
832         tls_domain_t* d;
833
834         if (!cfg) return 0;
835
836         d = cfg->srv_list;
837         while(d) {
838                 if (d->ip.len && !find_si(&d->ip, d->port, PROTO_TLS)) {
839                         LM_ERR("%s: No listening socket found\n", tls_domain_str(d));
840                         return -1;
841                 }
842                 d = d->next;
843         }
844         return 0;
845 }
846
847
848 /*
849  * TLS cleanup when SER exits
850  */
851 void destroy_tls_h(void)
852 {
853         LM_DBG("tls module final tls destroy\n");
854         if(tls_mod_preinitialized > 0)
855                 ERR_free_strings();
856         /* TODO: free all the ctx'es */
857         tls_destroy_cfg();
858         tls_destroy_locks();
859         tls_ct_wq_destroy();
860 #if OPENSSL_VERSION_NUMBER >= 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
861         /* explicit execution of libssl cleanup to avoid being executed again
862          * by atexit(), when shm is gone */
863         LM_DBG("executing openssl v1.1+ cleanup\n");
864         OPENSSL_cleanup();
865 #endif
866 }