Revert "lrkproxy: Add new features : TURN support, behind_nat support, subset of...
[sip-router] / 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_f(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         sr_tls_methods[TLS_USE_TLSv1_3_cli - 1].TLSMethod = TLS_client_method();
467         sr_tls_methods[TLS_USE_TLSv1_3_cli - 1].TLSMethodMin = TLS1_3_VERSION;
468         sr_tls_methods[TLS_USE_TLSv1_3_cli - 1].TLSMethodMax = TLS1_3_VERSION;
469         sr_tls_methods[TLS_USE_TLSv1_3_srv - 1].TLSMethod = TLS_server_method();
470         sr_tls_methods[TLS_USE_TLSv1_3_srv - 1].TLSMethodMin = TLS1_3_VERSION;
471         sr_tls_methods[TLS_USE_TLSv1_3_srv - 1].TLSMethodMax = TLS1_3_VERSION;
472         sr_tls_methods[TLS_USE_TLSv1_3 - 1].TLSMethod = TLS_method();
473         sr_tls_methods[TLS_USE_TLSv1_3 - 1].TLSMethodMin = TLS1_3_VERSION;
474         sr_tls_methods[TLS_USE_TLSv1_3 - 1].TLSMethodMax = TLS1_3_VERSION;
475
476         /* ranges of TLS versions (require a minimum TLS version) */
477         sr_tls_methods[TLS_USE_TLSv1_PLUS - 1].TLSMethod = TLS_method();
478         sr_tls_methods[TLS_USE_TLSv1_PLUS - 1].TLSMethodMin = TLS1_VERSION;
479
480         sr_tls_methods[TLS_USE_TLSv1_1_PLUS - 1].TLSMethod = TLS_method();
481         sr_tls_methods[TLS_USE_TLSv1_1_PLUS - 1].TLSMethodMin = TLS1_1_VERSION;
482
483         sr_tls_methods[TLS_USE_TLSv1_2_PLUS - 1].TLSMethod = TLS_method();
484         sr_tls_methods[TLS_USE_TLSv1_2_PLUS - 1].TLSMethodMin = TLS1_2_VERSION;
485
486         sr_tls_methods[TLS_USE_TLSv1_3_PLUS - 1].TLSMethod = TLS_method();
487         sr_tls_methods[TLS_USE_TLSv1_3_PLUS - 1].TLSMethodMin = TLS1_3_VERSION;
488
489 #endif
490 }
491
492
493 /*
494  * Fix openssl compression bugs if necessary
495  */
496 static int init_tls_compression(void)
497 {
498 #ifndef LIBRESSL_VERSION_NUMBER
499 #if OPENSSL_VERSION_NUMBER < 0x010100000L
500 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
501         int n, r;
502         STACK_OF(SSL_COMP)* comp_methods;
503         SSL_COMP* zlib_comp;
504         long ssl_version;
505
506         /* disabling compression */
507 #       ifndef SSL_COMP_ZLIB_IDX
508 #               define SSL_COMP_ZLIB_IDX 1 /* openssl/ssl/ssl_ciph.c:84 */
509 #       endif
510         comp_methods = SSL_COMP_get_compression_methods();
511         if (comp_methods == 0) {
512                 LM_INFO("compression support disabled in the"
513                                 " openssl lib\n");
514                 goto end; /* nothing to do, exit */
515         } else if (cfg_get(tls, tls_cfg, disable_compression)){
516                 LM_INFO("disabling compression...\n");
517                 sk_SSL_COMP_zero(comp_methods);
518         }else{
519                 ssl_version=SSLeay();
520                 /* replace openssl zlib compression with our version if necessary
521                  * (the openssl zlib compression uses the wrong malloc, see
522                  *  openssl #1468): 0.9.8-dev < version  <0.9.8e-beta1 */
523                 if ((ssl_version >= 0x00908000L) && (ssl_version < 0x00908051L)){
524                         /* the above SSL_COMP_get_compression_methods() call has the side
525                          * effect of initializing the compression stack (if not already
526                          * initialized) => after it zlib is initialized and in the stack */
527                         /* find zlib_comp (cannot use ssl3_comp_find, not exported) */
528                         n = sk_SSL_COMP_num(comp_methods);
529                         zlib_comp = 0;
530                         for (r = 0; r < n; r++) {
531                                 zlib_comp = sk_SSL_COMP_value(comp_methods, r);
532                                 LM_DBG("found compression method %p id %d\n",
533                                                 zlib_comp, zlib_comp->id);
534                                 if (zlib_comp->id == SSL_COMP_ZLIB_IDX) {
535                                         LM_DBG("found zlib compression (%d)\n",
536                                                         SSL_COMP_ZLIB_IDX);
537                                         break /* found */;
538                                 } else {
539                                         zlib_comp = 0;
540                                 }
541                         }
542                         if (zlib_comp == 0) {
543                                 LM_INFO("no openssl zlib compression found\n");
544                         }else{
545                                 LM_WARN("detected openssl lib with "
546                                                 "known zlib compression bug: \"%s\" (0x%08lx)\n",
547                                                 SSLeay_version(SSLEAY_VERSION), ssl_version);
548 #       ifdef TLS_FIX_ZLIB_COMPRESSION
549                                 LM_WARN("enabling openssl zlib compression "
550                                                 "bug workaround (replacing zlib COMP method with "
551                                                 "our own version)\n");
552                                 /* hack: make sure that the CRYPTO_EX_INDEX_COMP class is empty
553                                  * and it does not contain any free_ex_data from the
554                                  * built-in zlib. This can happen if the current openssl
555                                  * zlib malloc fix patch is used (CRYPTO_get_ex_new_index() in
556                                  * COMP_zlib()). Unfortunately the only way
557                                  * to do this it to cleanup all the ex_data stuff.
558                                  * It should be safe if this is executed before SSL_init()
559                                  * (only the COMP class is initialized before).
560                                  */
561                                 CRYPTO_cleanup_all_ex_data();
562
563                                 if (fixed_c_zlib_init() != 0) {
564                                         LM_CRIT("BUG: failed to initialize zlib"
565                                                         " compression fix, disabling compression...\n");
566                                         sk_SSL_COMP_zero(comp_methods); /* delete compression */
567                                         goto end;
568                                 }
569                                 /* "fix" it */
570                                 zlib_comp->method = &zlib_method;
571 #       else
572                                 LM_WARN("disabling openssl zlib compression \n");
573                                 zlib_comp=sk_SSL_COMP_delete(comp_methods, r);
574                                 if (zlib_comp)
575                                         OPENSSL_free(zlib_comp);
576 #       endif
577                         }
578                 }
579         }
580 end:
581 #endif /* OPENSSL_VERSION_NUMBER >= 0.9.8 */
582 #endif /* OPENSSL_VERSION_NUMBER < 1.1.0 */
583 #endif /* LIBRESSL_VERSION_NUMBER */
584         return 0;
585 }
586
587
588 /**
589  * tls pre-init function
590  * - executed when module is loaded
591  */
592 int tls_pre_init(void)
593 {
594 #ifndef LIBRESSL_VERSION_NUMBER
595 #if OPENSSL_VERSION_NUMBER < 0x010100000L
596         void *(*mf)(size_t) = NULL;
597         void *(*rf)(void *, size_t) = NULL;
598         void (*ff)(void *) = NULL;
599 #else
600         void *(*mf)(size_t, const char *, int) = NULL;
601         void *(*rf)(void *, size_t, const char *, int) = NULL;
602         void (*ff)(void *, const char *, int) = NULL;
603 #endif
604
605 #ifdef KSR_LIBSSL_STATIC
606         LM_INFO("libssl linked mode: static\n");
607 #endif
608
609         /*
610          * this has to be called before any function calling CRYPTO_malloc,
611          * CRYPTO_malloc will set allow_customize in openssl to 0
612          */
613         CRYPTO_get_mem_functions(&mf, &rf, &ff);
614         LM_DBG("initial memory functions - malloc: %p realloc: %p free: %p\n",
615                         mf, rf, ff);
616         mf = NULL;
617         rf = NULL;
618         ff = NULL;
619 #ifdef TLS_MALLOC_DBG
620         if (!CRYPTO_set_mem_ex_functions(ser_malloc, ser_realloc, ser_free)) {
621 #else
622         if (!CRYPTO_set_mem_functions(ser_malloc, ser_realloc, ser_free)) {
623 #endif
624                 LM_ERR("Unable to set the memory allocation functions\n");
625                 CRYPTO_get_mem_functions(&mf, &rf, &ff);
626                 LM_ERR("libssl current mem functions - m: %p r: %p f: %p\n",
627                                         mf, rf, ff);
628                 LM_ERR("module mem functions - m: %p r: %p f: %p\n",
629                                         ser_malloc, ser_realloc, ser_free);
630                 LM_ERR("Be sure tls module is loaded before any other module using"
631                                 " libssl (can be loaded first to be safe)\n");
632                 return -1;
633         }
634         LM_DBG("updated memory functions - malloc: %p realloc: %p free: %p\n",
635                         ser_malloc, ser_realloc, ser_free);
636 #endif /* LIBRESSL_VERSION_NUMBER */
637
638         if (tls_init_locks()<0)
639                 return -1;
640
641         init_tls_compression();
642
643         return 0;
644 }
645
646 /**
647  * tls mod pre-init function
648  * - executed before any mod_init()
649  */
650 int tls_h_mod_pre_init_f(void)
651 {
652         if(tls_mod_preinitialized==1) {
653                 LM_DBG("already mod pre-initialized\n");
654                 return 0;
655         }
656         LM_DBG("preparing tls env for modules initialization\n");
657 #if OPENSSL_VERSION_NUMBER >= 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
658         LM_DBG("preparing tls env for modules initialization (libssl >=1.1)\n");
659         OPENSSL_init_ssl(0, NULL);
660 #else
661         LM_DBG("preparing tls env for modules initialization (libssl <=1.0)\n");
662         SSL_library_init();
663 #endif
664         SSL_load_error_strings();
665         tls_mod_preinitialized=1;
666         return 0;
667 }
668
669 /*
670  * First step of TLS initialization
671  */
672 int tls_h_mod_init_f(void)
673 {
674         /*struct socket_info* si;*/
675         long ssl_version;
676         const char *ssl_version_txt;
677 #if OPENSSL_VERSION_NUMBER < 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
678         int lib_kerberos;
679         int lib_zlib;
680         int kerberos_support;
681         int comp_support;
682         const char* lib_cflags;
683 #endif
684         int low_mem_threshold1;
685         int low_mem_threshold2;
686         str tls_grp;
687         str s;
688         cfg_ctx_t* cfg_ctx;
689
690         if(tls_mod_initialized == 1) {
691                 LM_DBG("already initialized\n");
692                 return 0;
693         }
694         LM_DBG("initializing tls system\n");
695
696 #if OPENSSL_VERSION_NUMBER < 0x00907000L
697         LM_WARN("You are using an old version of OpenSSL (< 0.9.7). Upgrade!\n");
698 #endif
699
700 #if OPENSSL_VERSION_NUMBER < 0x010100000L
701         ssl_version=SSLeay();
702         ssl_version_txt=SSLeay_version(SSLEAY_VERSION);
703 #else
704         ssl_version=OpenSSL_version_num();
705         ssl_version_txt=OpenSSL_version(OPENSSL_VERSION);
706 #endif
707
708         /* check if version have the same major minor and fix level
709          * (e.g. 0.9.8a & 0.9.8c are ok, but 0.9.8 and 0.9.9x are not)
710          * - values is represented as 0xMMNNFFPPS: major minor fix patch status
711          *   0x00090705f == 0.9.7e release */
712         if ((ssl_version>>12)!=(OPENSSL_VERSION_NUMBER>>12)){
713                 LM_CRIT("installed openssl library"
714                                 " version is too different from the library the " NAME " tls"
715                                 " module was compiled with: installed \"%s\" (0x%08lx),"
716                                 " compiled \"%s\" (0x%08lx).\n"
717                                 " Please make sure a compatible version is used"
718                                 " (tls_force_run in kamailio.cfg will override this check)\n",
719                                 ssl_version_txt, ssl_version,
720                                 OPENSSL_VERSION_TEXT, (long)OPENSSL_VERSION_NUMBER);
721                 if (cfg_get(tls, tls_cfg, force_run))
722                         LM_WARN("tls_force_run turned on, ignoring "
723                                         " openssl version mismatch\n");
724                 else
725                         return -1; /* safer to exit */
726         }
727
728         /* check kerberos support using compile flags only for version < 1.1.0 */
729 #if OPENSSL_VERSION_NUMBER < 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
730
731 #ifdef TLS_KERBEROS_SUPPORT
732         kerberos_support=1;
733 #else
734         kerberos_support=0;
735 #endif
736 #ifdef TLS_COMP_SUPPORT
737         comp_support=1;
738 #else
739         comp_support=0;
740 #endif
741         /* attempt to guess if the library was compiled with kerberos or
742          * compression support from the cflags */
743         lib_cflags=SSLeay_version(SSLEAY_CFLAGS);
744         lib_kerberos=0;
745         lib_zlib=0;
746         if ((lib_cflags==0) || strstr(lib_cflags, "not available")){
747                 lib_kerberos=-1;
748                 lib_zlib=-1;
749         }else{
750                 if (strstr(lib_cflags, "-DZLIB"))
751                         lib_zlib=1;
752                 if (strstr(lib_cflags, "-DKRB5_"))
753                         lib_kerberos=1;
754         }
755         LM_INFO("compiled  with  openssl  version "
756                         "\"%s\" (0x%08lx), kerberos support: %s, compression: %s\n",
757                         OPENSSL_VERSION_TEXT, (long)OPENSSL_VERSION_NUMBER,
758                         kerberos_support?"on":"off", comp_support?"on":"off");
759         LM_INFO("installed openssl library version "
760                         "\"%s\" (0x%08lx), kerberos support: %s, "
761                         " zlib compression: %s"
762                         "\n %s\n",
763                         SSLeay_version(SSLEAY_VERSION), ssl_version,
764                         (lib_kerberos==1)?"on":(lib_kerberos==0)?"off":"unknown",
765                         (lib_zlib==1)?"on":(lib_zlib==0)?"off":"unknown",
766                         SSLeay_version(SSLEAY_CFLAGS));
767         if (lib_kerberos!=kerberos_support){
768                 if (lib_kerberos!=-1){
769                         LM_CRIT("openssl compile options"
770                                         " mismatch: library has kerberos support"
771                                         " %s and Kamailio tls %s (unstable configuration)\n"
772                                         " (tls_force_run in " NAME ".cfg will override this"
773                                         " check)\n",
774                                         lib_kerberos?"enabled":"disabled",
775                                         kerberos_support?"enabled":"disabled"
776                            );
777                         if (cfg_get(tls, tls_cfg, force_run))
778                                 LM_WARN("tls_force_run turned on, "
779                                                 "ignoring kerberos support mismatch\n");
780                         else
781                                 return -1; /* exit, is safer */
782                 }else{
783                         LM_WARN("openssl  compile options"
784                                         " missing -- cannot detect if kerberos support is"
785                                         " enabled. Possible unstable configuration\n");
786                 }
787         }
788
789 #ifdef TLS_KSSL_WORKARROUND
790         /* if openssl compiled with kerberos support, and openssl < 0.9.8e-dev
791          * or openssl between 0.9.9-dev and 0.9.9-beta1 apply workaround for
792          * openssl bug #1467 */
793         if (ssl_version < 0x00908050L ||
794                         (ssl_version >= 0x00909000L && ssl_version < 0x00909001L)){
795                 openssl_kssl_malloc_bug=1;
796                 LM_WARN("openssl kerberos malloc bug detected, "
797                                 " kerberos support will be disabled...\n");
798         }
799 #endif
800
801 #endif /* libssl version < 1.1.0 (OPENSSL_VERSION_NUMBER < 0x010100000L) */
802
803         /* set free memory threshold for openssl bug #1491 workaround */
804         low_mem_threshold1 = cfg_get(tls, tls_cfg, low_mem_threshold1);
805         low_mem_threshold2 = cfg_get(tls, tls_cfg, low_mem_threshold2);
806         if (low_mem_threshold1<0){
807                 /* default */
808                 low_mem_threshold1=512*1024*get_max_procs();
809         }else
810                 low_mem_threshold1*=1024; /* KB */
811         if (low_mem_threshold2<0){
812                 /* default */
813                 low_mem_threshold2=256*1024*get_max_procs();
814         }else
815                 low_mem_threshold2*=1024; /* KB */
816         if ((low_mem_threshold1==0) || (low_mem_threshold2==0))
817          LM_WARN("tls: openssl bug #1491 (crash/mem leaks on low memory)"
818                                 " workaround disabled\n");
819         else
820                 LM_WARN("openssl bug #1491 (crash/mem leaks on low memory)"
821                                 " workaround enabled (on low memory tls operations will fail"
822                                 " preemptively) with free memory thresholds %d and %d bytes\n",
823                                 low_mem_threshold1, low_mem_threshold2);
824
825         if (shm_available()==(unsigned long)(-1)){
826                 LM_WARN(NAME " is compiled without MALLOC_STATS support:"
827                                 " the workaround for low mem. openssl bugs will _not_ "
828                                 "work\n");
829                 low_mem_threshold1=0;
830                 low_mem_threshold2=0;
831         }
832         if ((low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1))
833                         || (low_mem_threshold2
834                                 != cfg_get(tls, tls_cfg, low_mem_threshold2))) {
835                 /* ugly hack to set the initial values for the mem tresholds */
836                 if (cfg_register_ctx(&cfg_ctx, 0)) {
837                         LM_ERR("failed to register cfg context\n");
838                         return -1;
839                 }
840                 tls_grp.s = "tls";
841                 tls_grp.len = strlen(tls_grp.s);
842                 s.s = "low_mem_threshold1";
843                 s.len = strlen(s.s);
844                 if (low_mem_threshold1 != cfg_get(tls, tls_cfg, low_mem_threshold1) &&
845                                 cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
846                                         low_mem_threshold1)) {
847                         LM_ERR("failed to set tls.low_mem_threshold1 to %d\n",
848                                         low_mem_threshold1);
849                         return -1;
850                 }
851                 s.s = "low_mem_threshold2";
852                 s.len = strlen(s.s);
853                 if (low_mem_threshold2 != cfg_get(tls, tls_cfg, low_mem_threshold2) &&
854                                 cfg_set_now_int(cfg_ctx, &tls_grp, NULL /* group id */, &s,
855                                         low_mem_threshold2)) {
856                         LM_ERR("failed to set tls.low_mem_threshold1 to %d\n",
857                                         low_mem_threshold2);
858                         return -1;
859                 }
860         }
861
862         init_ssl_methods();
863         tls_mod_initialized = 1;
864         return 0;
865 }
866
867
868 /*
869  * Make sure that all server domains in the configuration have corresponding
870  * listening socket in SER
871  */
872 int tls_check_sockets(tls_domains_cfg_t* cfg)
873 {
874         tls_domain_t* d;
875
876         if (!cfg) return 0;
877
878         d = cfg->srv_list;
879         while(d) {
880                 if (d->ip.len && !find_si(&d->ip, d->port, PROTO_TLS)) {
881                         LM_ERR("%s: No listening socket found\n", tls_domain_str(d));
882                         return -1;
883                 }
884                 d = d->next;
885         }
886         return 0;
887 }
888
889
890 /*
891  * TLS cleanup when application exits
892  */
893 void tls_h_mod_destroy_f(void)
894 {
895         LM_DBG("tls module final tls destroy\n");
896         if(tls_mod_preinitialized > 0)
897                 ERR_free_strings();
898         /* TODO: free all the ctx'es */
899         tls_destroy_cfg();
900         tls_destroy_locks();
901         tls_ct_wq_destroy();
902 #if OPENSSL_VERSION_NUMBER >= 0x010100000L && !defined(LIBRESSL_VERSION_NUMBER)
903         /* explicit execution of libssl cleanup to avoid being executed again
904          * by atexit(), when shm is gone */
905         LM_DBG("executing openssl v1.1+ cleanup\n");
906         OPENSSL_cleanup();
907 #endif
908 }