1ca62ff2000ad8d27a3ecb1f91a7cf423035aa10
[sip-router] / src / modules / tls / tls_domain.c
1 /*
2  * TLS module
3  *
4  * Copyright (C) 2005,2006 iptelorg GmbH
5  * Copyright (C) 2013 Motorola Solutions, Inc.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19
20 /**
21  * Kamailio TLS support :: Virtual domain configuration support
22  * @file
23  * @ingroup tls
24  * Module: @ref tls
25  */
26
27 #include <stdlib.h>
28 #include <openssl/ssl.h>
29 #include <openssl/opensslv.h>
30
31 #ifndef OPENSSL_NO_ENGINE
32 #include <openssl/engine.h>
33 #include "tls_map.h"
34 extern EVP_PKEY * tls_engine_private_key(const char* key_id);
35 #endif
36
37 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
38 # include <openssl/ui.h>
39 #endif
40 #include "../../core/ut.h"
41 #include "../../core/mem/shm_mem.h"
42 #include "../../core/pt.h"
43 #include "../../core/cfg/cfg.h"
44 #include "../../core/dprint.h"
45 #include "tls_config.h"
46 #include "tls_server.h"
47 #include "tls_util.h"
48 #include "tls_mod.h"
49 #include "tls_init.h"
50 #include "tls_domain.h"
51 #include "tls_cfg.h"
52
53 /*
54  * ECDHE is enabled only on OpenSSL 1.0.0e and later.
55  * See http://www.openssl.org/news/secadv_20110906.txt
56  * for details.
57  */
58 #ifndef OPENSSL_NO_ECDH
59 static void setup_ecdh(SSL_CTX *ctx)
60 {
61    EC_KEY *ecdh;
62
63    if (SSLeay() < 0x1000005fL) {
64       return;
65    }
66
67    ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
68    SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
69    SSL_CTX_set_tmp_ecdh(ctx, ecdh);
70
71    EC_KEY_free(ecdh);
72 }
73 #endif
74
75 #ifndef OPENSSL_NO_DH
76
77 static unsigned char dh3072_p[] = {
78    0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xC9,0x0F,0xDA,0xA2,
79    0x21,0x68,0xC2,0x34,0xC4,0xC6,0x62,0x8B,0x80,0xDC,0x1C,0xD1,
80    0x29,0x02,0x4E,0x08,0x8A,0x67,0xCC,0x74,0x02,0x0B,0xBE,0xA6,
81    0x3B,0x13,0x9B,0x22,0x51,0x4A,0x08,0x79,0x8E,0x34,0x04,0xDD,
82    0xEF,0x95,0x19,0xB3,0xCD,0x3A,0x43,0x1B,0x30,0x2B,0x0A,0x6D,
83    0xF2,0x5F,0x14,0x37,0x4F,0xE1,0x35,0x6D,0x6D,0x51,0xC2,0x45,
84    0xE4,0x85,0xB5,0x76,0x62,0x5E,0x7E,0xC6,0xF4,0x4C,0x42,0xE9,
85    0xA6,0x37,0xED,0x6B,0x0B,0xFF,0x5C,0xB6,0xF4,0x06,0xB7,0xED,
86    0xEE,0x38,0x6B,0xFB,0x5A,0x89,0x9F,0xA5,0xAE,0x9F,0x24,0x11,
87    0x7C,0x4B,0x1F,0xE6,0x49,0x28,0x66,0x51,0xEC,0xE4,0x5B,0x3D,
88    0xC2,0x00,0x7C,0xB8,0xA1,0x63,0xBF,0x05,0x98,0xDA,0x48,0x36,
89    0x1C,0x55,0xD3,0x9A,0x69,0x16,0x3F,0xA8,0xFD,0x24,0xCF,0x5F,
90    0x83,0x65,0x5D,0x23,0xDC,0xA3,0xAD,0x96,0x1C,0x62,0xF3,0x56,
91    0x20,0x85,0x52,0xBB,0x9E,0xD5,0x29,0x07,0x70,0x96,0x96,0x6D,
92    0x67,0x0C,0x35,0x4E,0x4A,0xBC,0x98,0x04,0xF1,0x74,0x6C,0x08,
93    0xCA,0x18,0x21,0x7C,0x32,0x90,0x5E,0x46,0x2E,0x36,0xCE,0x3B,
94    0xE3,0x9E,0x77,0x2C,0x18,0x0E,0x86,0x03,0x9B,0x27,0x83,0xA2,
95    0xEC,0x07,0xA2,0x8F,0xB5,0xC5,0x5D,0xF0,0x6F,0x4C,0x52,0xC9,
96    0xDE,0x2B,0xCB,0xF6,0x95,0x58,0x17,0x18,0x39,0x95,0x49,0x7C,
97    0xEA,0x95,0x6A,0xE5,0x15,0xD2,0x26,0x18,0x98,0xFA,0x05,0x10,
98    0x15,0x72,0x8E,0x5A,0x8A,0xAA,0xC4,0x2D,0xAD,0x33,0x17,0x0D,
99    0x04,0x50,0x7A,0x33,0xA8,0x55,0x21,0xAB,0xDF,0x1C,0xBA,0x64,
100    0xEC,0xFB,0x85,0x04,0x58,0xDB,0xEF,0x0A,0x8A,0xEA,0x71,0x57,
101    0x5D,0x06,0x0C,0x7D,0xB3,0x97,0x0F,0x85,0xA6,0xE1,0xE4,0xC7,
102    0xAB,0xF5,0xAE,0x8C,0xDB,0x09,0x33,0xD7,0x1E,0x8C,0x94,0xE0,
103    0x4A,0x25,0x61,0x9D,0xCE,0xE3,0xD2,0x26,0x1A,0xD2,0xEE,0x6B,
104    0xF1,0x2F,0xFA,0x06,0xD9,0x8A,0x08,0x64,0xD8,0x76,0x02,0x73,
105    0x3E,0xC8,0x6A,0x64,0x52,0x1F,0x2B,0x18,0x17,0x7B,0x20,0x0C,
106    0xBB,0xE1,0x17,0x57,0x7A,0x61,0x5D,0x6C,0x77,0x09,0x88,0xC0,
107    0xBA,0xD9,0x46,0xE2,0x08,0xE2,0x4F,0xA0,0x74,0xE5,0xAB,0x31,
108    0x43,0xDB,0x5B,0xFC,0xE0,0xFD,0x10,0x8E,0x4B,0x82,0xD1,0x20,
109    0xA9,0x3A,0xD2,0xCA,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
110
111 };
112
113 static unsigned char dh3072_g[] = { 0x02 };
114
115 static void setup_dh(SSL_CTX *ctx)
116 {
117         DH *dh;
118         BIGNUM *p;
119         BIGNUM *g;
120
121         dh = DH_new();
122         if (dh == NULL) {
123                 return;
124         }
125
126         p = BN_bin2bn(dh3072_p, sizeof(dh3072_p), NULL);
127         g = BN_bin2bn(dh3072_g, sizeof(dh3072_g), NULL);
128
129         if (p == NULL || g == NULL) {
130                 DH_free(dh);
131                 return;
132         }
133
134 #if (OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(LIBRESSL_VERSION_NUMBER)
135         /* libssl >= v1.1.0 */
136         DH_set0_pqg(dh, p, NULL, g);
137 #else
138         dh->p = p;
139         dh->g = g;
140 #endif
141
142
143    SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
144    SSL_CTX_set_tmp_dh(ctx, dh);
145
146    DH_free(dh);
147 }
148 #endif
149
150
151 /**
152  * @brief Create a new TLS domain structure
153  * 
154  * Create a new domain structure in new allocated shared memory.
155  * @param type domain Type
156  * @param ip domain IP
157  * @param port domain port
158  * @return new domain
159  */
160 tls_domain_t* tls_new_domain(int type, struct ip_addr *ip, unsigned short port)
161 {
162         tls_domain_t* d;
163
164         d = shm_malloc(sizeof(tls_domain_t));
165         if (d == NULL) {
166                 ERR("Memory allocation failure\n");
167                 return 0;
168         }
169         memset(d, '\0', sizeof(tls_domain_t));
170
171         d->type = type;
172         if (ip) memcpy(&d->ip, ip, sizeof(struct ip_addr));
173         d->port = port;
174         d->verify_cert = -1;
175         d->verify_depth = -1;
176         d->require_cert = -1;
177         return d;
178 }
179
180
181 /**
182  * @brief Free all memory used by TLS configuration domain
183  * @param d freed domain
184  */
185 void tls_free_domain(tls_domain_t* d)
186 {
187         int i;
188         int procs_no;
189         
190         if (!d) return;
191         if (d->ctx) {
192                 procs_no=get_max_procs();
193                 for(i = 0; i < procs_no; i++) {
194                         if (d->ctx[i]) SSL_CTX_free(d->ctx[i]);
195                 }
196                 shm_free(d->ctx);
197         }
198
199         if (d->cipher_list.s) shm_free(d->cipher_list.s);
200         if (d->ca_file.s) shm_free(d->ca_file.s);
201         if (d->crl_file.s) shm_free(d->crl_file.s);
202         if (d->pkey_file.s) shm_free(d->pkey_file.s);
203         if (d->cert_file.s) shm_free(d->cert_file.s);
204         if (d->server_name.s) shm_free(d->server_name.s);
205         if (d->server_id.s) shm_free(d->server_id.s);
206         shm_free(d);
207 }
208
209
210 /**
211  * @brief Free TLS configuration structure
212  * @param cfg freed configuration
213  */
214 void tls_free_cfg(tls_domains_cfg_t* cfg)
215 {
216         tls_domain_t* p;
217         while(cfg->srv_list) {
218                 p = cfg->srv_list;
219                 cfg->srv_list = cfg->srv_list->next;
220                 tls_free_domain(p);
221         }
222         while(cfg->cli_list) {
223                 p = cfg->cli_list;
224                 cfg->cli_list = cfg->cli_list->next;
225                 tls_free_domain(p);
226         }
227         if (cfg->srv_default) tls_free_domain(cfg->srv_default);
228         if (cfg->cli_default) tls_free_domain(cfg->cli_default);
229         shm_free(cfg);
230 }
231
232
233 /**
234  * @brief Destroy all TLS configuration data
235  */
236 void tls_destroy_cfg(void)
237 {
238         tls_domains_cfg_t* ptr;
239
240         if (tls_domains_cfg_lock) {
241                 lock_destroy(tls_domains_cfg_lock);
242                 lock_dealloc(tls_domains_cfg_lock);
243                 tls_domains_cfg_lock = 0;
244         }
245
246         if (tls_domains_cfg) {
247                 while(*tls_domains_cfg) {
248                         ptr = *tls_domains_cfg;
249                         *tls_domains_cfg = (*tls_domains_cfg)->next;
250                         tls_free_cfg(ptr);
251                 }
252                 
253                 shm_free(tls_domains_cfg);
254                 tls_domains_cfg = 0;
255         }
256 }
257
258
259
260 /**
261  * @brief Generate TLS domain identifier
262  * @param d printed domain
263  * @return printed domain, with zero termination
264  */
265 char* tls_domain_str(tls_domain_t* d)
266 {
267         static char buf[1024];
268         char* p;
269
270         buf[0] = '\0';
271         p = buf;
272         p = strcat(p, d->type & TLS_DOMAIN_SRV ? "TLSs<" : "TLSc<");
273         if (d->type & TLS_DOMAIN_DEF) {
274                 p = strcat(p, "default>");
275         } else if (d->type & TLS_DOMAIN_ANY) {
276                 p = strcat(p, "any:");
277                 if(d->server_name.s && d->server_name.len>0) {
278                         p = strncat(p, d->server_name.s, d->server_name.len);
279                 }
280                 p = strcat(p, ">");
281         } else {
282                 p = strcat(p, ip_addr2a(&d->ip));
283                 p = strcat(p, ":");
284                 p = strcat(p, int2str(d->port, 0));
285                 p = strcat(p, ">");
286         }
287         return buf;
288 }
289
290
291 /**
292  * @brief Initialize TLS domain parameters that have not been configured yet
293  * 
294  * Initialize TLS domain parameters that have not been configured from
295  * parent domain (usually one of default domains)
296  * @param d initialized domain
297  * @param parent parent domain
298  * @return 0 on success, -1 on error
299  */
300 static int ksr_tls_fill_missing(tls_domain_t* d, tls_domain_t* parent)
301 {
302         if (d->method == TLS_METHOD_UNSPEC) d->method = parent->method;
303         LOG(L_INFO, "%s: tls_method=%d\n", tls_domain_str(d), d->method);
304         
305         if (d->method < 1 || d->method >= TLS_METHOD_MAX) {
306                 ERR("%s: Invalid TLS method value\n", tls_domain_str(d));
307                 return -1;
308         }
309         
310         if (!d->cert_file.s) {
311                 if (shm_asciiz_dup(&d->cert_file.s, parent->cert_file.s) < 0)
312                         return -1;
313                 d->cert_file.len = parent->cert_file.len;
314         }
315         LOG(L_INFO, "%s: certificate='%s'\n", tls_domain_str(d), d->cert_file.s);
316         
317         if (!d->ca_file.s){
318                 if (shm_asciiz_dup(&d->ca_file.s, parent->ca_file.s) < 0)
319                         return -1;
320                 d->ca_file.len = parent->ca_file.len;
321         }
322         LOG(L_INFO, "%s: ca_list='%s'\n", tls_domain_str(d), d->ca_file.s);
323
324         if (!d->crl_file.s) {
325                 if (shm_asciiz_dup(&d->crl_file.s, parent->crl_file.s) < 0)
326                         return -1;
327                 d->crl_file.len = parent->crl_file.len;
328         }
329         LOG(L_INFO, "%s: crl='%s'\n", tls_domain_str(d), d->crl_file.s);
330         
331         if (d->require_cert == -1) d->require_cert = parent->require_cert;
332         LOG(L_INFO, "%s: require_certificate=%d\n", tls_domain_str(d),
333                         d->require_cert);
334         
335         if (!d->cipher_list.s) {
336                 if ( shm_asciiz_dup(&d->cipher_list.s, parent->cipher_list.s) < 0)
337                         return -1;
338                 d->cipher_list.len = parent->cipher_list.len;
339         }
340         LOG(L_INFO, "%s: cipher_list='%s'\n", tls_domain_str(d), d->cipher_list.s);
341         
342         if (!d->pkey_file.s) {
343                 if (shm_asciiz_dup(&d->pkey_file.s, parent->pkey_file.s) < 0)
344                         return -1;
345                 d->pkey_file.len = parent->pkey_file.len;
346         }
347         LOG(L_INFO, "%s: private_key='%s'\n", tls_domain_str(d), d->pkey_file.s);
348         
349         if (d->verify_cert == -1) d->verify_cert = parent->verify_cert;
350         LOG(L_INFO, "%s: verify_certificate=%d\n", tls_domain_str(d),
351                         d->verify_cert);
352         
353         if (d->verify_depth == -1) d->verify_depth = parent->verify_depth;
354         LOG(L_INFO, "%s: verify_depth=%d\n", tls_domain_str(d), d->verify_depth);
355
356         return 0;
357 }
358
359
360 /** 
361  * @brief Called for ctx, with 2 args
362  * @param ctx SSL context
363  * @param larg ?
364  * @param parg ?
365  * @return return 0 on succes, <0 on critical error
366  */
367 typedef int (*per_ctx_cbk_f)(SSL_CTX* ctx, long larg, void* parg);
368
369
370 /**
371  * @brief Execute callback on all the CTX'es on a domain
372  * @param d domain
373  * @param ctx_cbk callback function
374  * @param l1 parameter passed to the callback
375  * @param p2 parameter passed to the callback
376  * @return 0 on success, <0 on error
377  */
378 static int tls_domain_foreach_CTX(tls_domain_t* d, per_ctx_cbk_f ctx_cbk,
379                                                                         long l1, void* p2)
380 {
381         int i,ret;
382         int procs_no;
383         
384         procs_no=get_max_procs();
385         for(i = 0; i < procs_no; i++) {
386                 if ((ret=ctx_cbk(d->ctx[i], l1, p2))<0)
387                         return ret;
388         }
389         return 0;
390 }
391
392
393 /**
394  * @brief Execute callback on all the CTX'es on in a domain list
395  * @param d domain
396  * @param ctx_cbk callback function
397  * @param l1 parameter passed to the callback
398  * @param p2 parameter passed to the callback
399  * @return 0 on success, <0 on error
400  */
401 static int tls_foreach_CTX_in_domain_lst(tls_domain_t* d,
402                                                                                 per_ctx_cbk_f ctx_cbk,
403                                                                                 long l1, void* p2)
404 {
405         int ret;
406         for (; d; d=d->next)
407                 if ((ret=tls_domain_foreach_CTX(d, ctx_cbk, l1, p2))<0)
408                         return ret;
409         return 0;
410 }
411
412
413 /**
414  * @brief Execute callback on all the CTX'es in all the srv domains in a tls cfg
415  * @param cfg tls cfg.
416  * @param ctx_cbk callback function
417  * @param l1 parameter passed to the callback
418  * @param p2 parameter passed to the callback
419  * @return 0 on success, <0 on error
420  */
421 static int tls_foreach_CTX_in_srv_domains(tls_domains_cfg_t* cfg,
422                                                                                         per_ctx_cbk_f ctx_cbk,
423                                                                                         long l1, void* p2)
424 {
425         int ret;
426         if ((ret = tls_domain_foreach_CTX(cfg->srv_default, ctx_cbk, l1, p2)) < 0)
427                 return ret;
428         if ((ret = tls_foreach_CTX_in_domain_lst(cfg->srv_list, ctx_cbk, l1, p2))
429                         < 0)
430                 return ret;
431         return 0;
432 }
433
434
435 /**
436  * @brief Execute callback on all the CTX'es in all the client domains in a tls cfg
437  * @param cfg tls cfg.
438  * @param ctx_cbk callback function
439  * @param l1 parameter passed to the callback
440  * @param p2 parameter passed to the callback
441  * @return 0 on success, <0 on error.
442  */
443 static int tls_foreach_CTX_in_cli_domains(tls_domains_cfg_t* cfg,
444                                                                                         per_ctx_cbk_f ctx_cbk,
445                                                                                         long l1, void* p2)
446 {
447         int ret;
448         if ((ret = tls_domain_foreach_CTX(cfg->cli_default, ctx_cbk, l1, p2)) < 0)
449                 return ret;
450         if ((ret = tls_foreach_CTX_in_domain_lst(cfg->cli_list, ctx_cbk, l1, p2))
451                         < 0)
452                 return ret;
453         return 0;
454 }
455
456
457 /**
458  * @brief Execute callback on all the CTX'es in all the domains in a tls cfg
459  * @param cfg tls cfg
460  * @param ctx_cbk callback function
461  * @param l1 parameter passed to the callback
462  * @param p2 parameter passed to the callback
463  * @return 0 on success, <0 on error
464  */
465 static int tls_foreach_CTX_in_cfg(tls_domains_cfg_t* cfg,
466                                                                                 per_ctx_cbk_f ctx_cbk,
467                                                                                 long l1, void* p2)
468 {
469         int ret;
470
471         if ((ret = tls_foreach_CTX_in_srv_domains(cfg, ctx_cbk, l1, p2)) < 0)
472                 return ret;
473         if ((ret = tls_foreach_CTX_in_cli_domains(cfg, ctx_cbk, l1, p2)) < 0)
474                 return ret;
475         return 0;
476 }
477
478
479
480
481 /**
482  * @brief Fix pathnames when loading domain keys or other list
483  * 
484  * Fix pathnames, to be used when loading the domain key, cert, ca list a.s.o.
485  * It will replace path with a fixed shm allocated version. Assumes path->s
486  * was shm allocated.
487  * @param path path to be fixed. If it starts with '.' or '/' is left alone
488  * (forced "relative" or "absolute" path). Otherwise the path is considered 
489  * to be relative to the main config file directory
490  * (e.g. for /etc/ser/ser.cfg => /etc/ser/\<path\>).
491  * @return  0 on success, -1 on error
492  */
493 int fix_shm_pathname(str* path)
494 {
495         str new_path;
496         char *abs_path;
497
498         if(path->s && path->len && *path->s != '.' && *path->s != '/') {
499                 abs_path = get_abs_pathname(0, path);
500                 if(abs_path == 0) {
501                         LM_ERR("get abs pathname failed\n");
502                         return -1;
503                 }
504                 new_path.len = strlen(abs_path);
505                 new_path.s = shm_malloc(new_path.len + 1);
506                 if(new_path.s == 0) {
507                         LM_ERR("no more shm memory\n");
508                         pkg_free(abs_path);
509                         return -1;
510                 }
511                 memcpy(new_path.s, abs_path, new_path.len);
512                 new_path.s[new_path.len] = 0;
513                 shm_free(path->s);
514                 pkg_free(abs_path);
515                 *path = new_path;
516         }
517         return 0;
518 }
519
520
521
522 /**
523  * @brief Load certificate from file
524  * @param d domain
525  * @return 0 if not configured or on success, -1 on error
526  */
527 static int load_cert(tls_domain_t* d)
528 {
529         int i;
530         int procs_no;
531
532         if (!d->cert_file.s || !d->cert_file.len) {
533                 DBG("%s: No certificate configured\n", tls_domain_str(d));
534                 return 0;
535         }
536         if (fix_shm_pathname(&d->cert_file) < 0)
537                 return -1;
538         procs_no=get_max_procs();
539         for(i = 0; i < procs_no; i++) {
540                 if (!SSL_CTX_use_certificate_chain_file(d->ctx[i], d->cert_file.s)) {
541                         ERR("%s: Unable to load certificate file '%s'\n",
542                             tls_domain_str(d), d->cert_file.s);
543                         TLS_ERR("load_cert:");
544                         return -1;
545                 }
546                 
547         }
548         return 0;
549 }
550
551
552 /**
553  * @brief Load CA list from file
554  * @param d domain
555  * @return 0 if not configured or on success, -1 on error
556  */
557 static int load_ca_list(tls_domain_t* d)
558 {
559         int i;
560         int procs_no;
561
562         if (!d->ca_file.s || !d->ca_file.len) {
563                 DBG("%s: No CA list configured\n", tls_domain_str(d));
564                 return 0;
565         }
566         if (fix_shm_pathname(&d->ca_file) < 0)
567                 return -1;
568         procs_no=get_max_procs();
569         for(i = 0; i < procs_no; i++) {
570                 if (SSL_CTX_load_verify_locations(d->ctx[i], d->ca_file.s, 0) != 1) {
571                         ERR("%s: Unable to load CA list '%s'\n", tls_domain_str(d),
572                                         d->ca_file.s);
573                         TLS_ERR("load_ca_list:");
574                         return -1;
575                 }
576                 SSL_CTX_set_client_CA_list(d->ctx[i],
577                                 SSL_load_client_CA_file(d->ca_file.s));
578                 if (SSL_CTX_get_client_CA_list(d->ctx[i]) == 0) {
579                         ERR("%s: Error while setting client CA list\n", tls_domain_str(d));
580                         TLS_ERR("load_ca_list:");
581                         return -1;
582                 }
583         }
584         return 0;
585 }
586
587
588 /**
589  * @brief Load CRL from file
590  * @param d domain
591  * @return 0 if not configured or on success, -1 on error
592  */
593 static int load_crl(tls_domain_t* d)
594 {
595         int i;
596         int procs_no;
597         X509_STORE* store;
598
599         if (!d->crl_file.s) {
600                 DBG("%s: No CRL configured\n", tls_domain_str(d));
601                 return 0;
602         }
603         if (fix_shm_pathname(&d->crl_file) < 0)
604                 return -1;
605         LOG(L_INFO, "%s: Certificate revocation lists will be checked (%.*s)\n",
606                                 tls_domain_str(d), d->crl_file.len, d->crl_file.s);
607         procs_no=get_max_procs();
608         for(i = 0; i < procs_no; i++) {
609                 if (SSL_CTX_load_verify_locations(d->ctx[i], d->crl_file.s, 0) != 1) {
610                         ERR("%s: Unable to load certificate revocation list '%s'\n",
611                                         tls_domain_str(d), d->crl_file.s);
612                         TLS_ERR("load_crl:");
613                         return -1;
614                 }
615                 store = SSL_CTX_get_cert_store(d->ctx[i]);
616                 X509_STORE_set_flags(store,
617                                                 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
618         }
619         return 0;
620 }
621
622
623 #define C_DEF_NO_KRB5 "DEFAULT:!KRB5"
624 #define C_DEF_NO_KRB5_LEN (sizeof(C_DEF_NO_KRB5)-1)
625 #define C_NO_KRB5_SUFFIX ":!KRB5"
626 #define C_NO_KRB5_SUFFIX_LEN (sizeof(C_NO_KRB5_SUFFIX)-1)
627
628 /**
629  * @brief Configure cipher list
630  * @param d domain
631  * @return 0 on success, -1 on error
632  */
633 static int set_cipher_list(tls_domain_t* d)
634 {
635         int i;
636         int procs_no;
637         char* cipher_list;
638
639         cipher_list=d->cipher_list.s;
640 #ifdef TLS_KSSL_WORKARROUND
641         if (openssl_kssl_malloc_bug) { /* is openssl bug #1467 present ? */
642                 if (d->cipher_list.s==0) {
643                         /* use "DEFAULT:!KRB5" */
644                         cipher_list="DEFAULT:!KRB5";
645                 } else {
646                         /* append ":!KRB5" */
647                         cipher_list=shm_malloc(d->cipher_list.len+C_NO_KRB5_SUFFIX_LEN+1);
648                         if (cipher_list) {
649                                 memcpy(cipher_list, d->cipher_list.s, d->cipher_list.len);
650                                 memcpy(cipher_list+d->cipher_list.len, C_NO_KRB5_SUFFIX,
651                                                 C_NO_KRB5_SUFFIX_LEN);
652                                 cipher_list[d->cipher_list.len+C_NO_KRB5_SUFFIX_LEN]=0;
653                                 shm_free(d->cipher_list.s);
654                                 d->cipher_list.s=cipher_list;
655                                 d->cipher_list.len+=C_NO_KRB5_SUFFIX_LEN;
656                         }
657                 }
658         }
659 #endif /* TLS_KSSL_WORKARROUND */
660         if (!cipher_list) return 0;
661         procs_no=get_max_procs();
662         for(i = 0; i < procs_no; i++) {
663                 if (SSL_CTX_set_cipher_list(d->ctx[i], cipher_list) == 0 ) {
664                         ERR("%s: Failure to set SSL context cipher list \"%s\"\n",
665                                         tls_domain_str(d), cipher_list);
666                         return -1;
667                 }
668 #ifndef OPENSSL_NO_ECDH
669                 setup_ecdh(d->ctx[i]);
670 #endif
671 #ifndef OPENSSL_NO_DH
672                 setup_dh(d->ctx[i]);
673 #endif
674         }
675         return 0;
676 }
677
678
679 /**
680  * @brief Enable/disable TLS certificate verification
681  * @param d domain
682  * @return 0
683  */
684 static int set_verification(tls_domain_t* d)
685 {
686         int verify_mode, i;
687         int procs_no;
688
689         if (d->require_cert) {
690                 verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
691                 LOG(L_INFO, "%s: %s MUST present valid certificate\n", 
692                         tls_domain_str(d), d->type & TLS_DOMAIN_SRV ? "Client" : "Server");
693         } else {
694                 if (d->verify_cert) {
695                         verify_mode = SSL_VERIFY_PEER;
696                         if (d->type & TLS_DOMAIN_SRV) {
697                                 LOG(L_INFO, "%s: IF client provides certificate then it"
698                                                 " MUST be valid\n", tls_domain_str(d));
699                         } else {
700                                 LOG(L_INFO, "%s: Server MUST present valid certificate\n",
701                                      tls_domain_str(d));
702                         }
703                 } else {
704                         verify_mode = SSL_VERIFY_NONE;
705                         if (d->type & TLS_DOMAIN_SRV) {
706                                 LOG(L_INFO, "%s: No client certificate required and no checks"
707                                                 " performed\n", tls_domain_str(d));
708                         } else {
709                                 LOG(L_INFO, "%s: Server MAY present invalid certificate\n",
710                                      tls_domain_str(d));
711                         }
712                 }
713         }
714         
715         procs_no=get_max_procs();
716         for(i = 0; i < procs_no; i++) {
717                 SSL_CTX_set_verify(d->ctx[i], verify_mode, 0);
718                 SSL_CTX_set_verify_depth(d->ctx[i], d->verify_depth);
719                 
720         }
721         return 0;
722 }
723
724
725 /* This callback function is executed when libssl processes the SSL
726  * handshake and does SSL record layer stuff. It's used to trap
727  * client-initiated renegotiations.
728  */
729
730 static void sr_ssl_ctx_info_callback(const SSL *ssl, int event, int ret)
731 {
732         struct tls_extra_data* data = 0;
733         int tls_dbg;
734
735         if (event & SSL_CB_HANDSHAKE_START) {
736                 tls_dbg = cfg_get(tls, tls_cfg, debug);
737                 LOG(tls_dbg, "SSL handshake started\n");
738                 if(data==0)
739                         data = (struct tls_extra_data*)SSL_get_app_data(ssl);
740                 if(data->flags & F_TLS_CON_HANDSHAKED) {
741                         LOG(tls_dbg, "SSL renegotiation initiated by client\n");
742                         data->flags |= F_TLS_CON_RENEGOTIATION;
743                 }
744         }
745         if (event & SSL_CB_HANDSHAKE_DONE) {
746                 tls_dbg = cfg_get(tls, tls_cfg, debug);
747                 if(data==0)
748                         data = (struct tls_extra_data*)SSL_get_app_data(ssl);
749                 LOG(tls_dbg, "SSL handshake done\n");
750 #if OPENSSL_VERSION_NUMBER < 0x010100000L
751                 /* CVE-2009-3555 - disable renegotiation */
752                 if (ssl->s3) {
753                         LOG(tls_dbg, "SSL disable renegotiation\n");
754                         ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
755                 }
756 #endif
757                 data->flags |= F_TLS_CON_HANDSHAKED;
758         }
759 }
760
761 /**
762  * @brief Configure generic SSL parameters 
763  * @param d domain
764  * @return 0
765  */
766 static int set_ssl_options(tls_domain_t* d)
767 {
768         int i;
769         int procs_no;
770         long options;
771 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
772         long ssl_version;
773         STACK_OF(SSL_COMP)* comp_methods;
774 #endif
775         
776         procs_no=get_max_procs();
777         options=SSL_OP_ALL; /* all the bug workarrounds by default */
778 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
779         options|=SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
780                                 SSL_OP_CIPHER_SERVER_PREFERENCE;
781 #if             OPENSSL_VERSION_NUMBER >= 0x00908000L
782         ssl_version=SSLeay();
783         if ((ssl_version >= 0x0090800L) && (ssl_version < 0x0090803fL)){
784                 /* if 0.9.8 <= openssl version < 0.9.8c and compression support is
785                  * enabled disable SSL_OP_TLS_BLOCK_PADDING_BUG (set by SSL_OP_ALL),
786                  * see openssl #1204 http://rt.openssl.org/Ticket/Display.html?id=1204
787                  */
788                 
789                 comp_methods=SSL_COMP_get_compression_methods();
790                 if (comp_methods && (sk_SSL_COMP_num(comp_methods) > 0)){
791                         options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
792                         LOG(L_WARN, "tls: set_ssl_options: openssl "
793                                         "SSL_OP_TLS_BLOCK_PADDING bug workaround enabled "
794                                         "(openssl version %lx)\n", ssl_version);
795                 }else{
796                         LOG(L_INFO, "tls: set_ssl_options: detected openssl version (%lx) "
797                                         " has the SSL_OP_TLS_BLOCK_PADDING bug, but compression "
798                                         " is disabled so no workaround is needed\n", ssl_version);
799                 }
800         }
801 #       endif
802 #endif
803         for(i = 0; i < procs_no; i++) {
804                 SSL_CTX_set_options(d->ctx[i], options);
805                 if(sr_tls_renegotiation==0)
806                         SSL_CTX_set_info_callback(d->ctx[i], sr_ssl_ctx_info_callback);
807         }
808         return 0;
809 }
810
811
812 /**
813  * @brief Configure TLS session cache parameters 
814  * @param d domain
815  * @return 0
816  */
817 static int set_session_cache(tls_domain_t* d)
818 {
819         int i;
820         int procs_no;
821         str tls_session_id;
822         
823         procs_no=get_max_procs();
824         tls_session_id=cfg_get(tls, tls_cfg, session_id);
825         for(i = 0; i < procs_no; i++) {
826                 /* janakj: I am not sure if session cache makes sense in ser, session
827                  * cache is stored in SSL_CTX and we have one SSL_CTX per process,
828                  * thus sessions among processes will not be reused
829                  */
830                 SSL_CTX_set_session_cache_mode(d->ctx[i],
831                                 cfg_get(tls, tls_cfg, session_cache) ? SSL_SESS_CACHE_SERVER :
832                                 SSL_SESS_CACHE_OFF);
833                 /* not really needed is SSL_SESS_CACHE_OFF */
834                 SSL_CTX_set_session_id_context(d->ctx[i],
835                                         (unsigned char*)tls_session_id.s, tls_session_id.len);
836         }
837         return 0;
838 }
839
840
841
842 /**
843  * @brief TLS SSL_CTX_set_mode and SSL_CTX_clear_mode wrapper
844  * @param ctx SSL context
845  * @param mode SSL_MODE_*
846  * @param clear if set to !=0 will do a clear, else (==0) a set
847  * @return 0 (always succeeds)
848  */
849 static int tls_ssl_ctx_mode(SSL_CTX* ctx, long mode, void* clear)
850 {
851         if (clear)
852 #if OPENSSL_VERSION_NUMBER >= 0x01000000L || \
853         defined SSL_CTX_clear_mode
854                 SSL_CTX_clear_mode(ctx, mode);
855 #else
856         return -1;
857 #endif
858         else
859                 SSL_CTX_set_mode(ctx, mode);
860         return 0;
861 }
862
863
864
865 /**
866  * @brief TLS set ctx->free_list_max_len
867  * @param ctx TLS context
868  * @param val value (<0 ignored)
869  * @param unused unused
870  * @return 0 (always succeeds)
871  */
872 static int tls_ssl_ctx_set_freelist(SSL_CTX* ctx, long val, void* unused)
873 {
874 #if OPENSSL_VERSION_NUMBER < 0x010100000L
875         if (val >= 0)
876 #if OPENSSL_VERSION_NUMBER >= 0x01000000L
877 #ifndef OPENSSL_NO_BUF_FREELISTS
878                 ctx->freelist_max_len = val;
879 #endif
880 #endif
881 #if defined (OPENSSL_NO_BUF_FREELISTS) || OPENSSL_VERSION_NUMBER < 0x01000000L
882                 return -1;
883 #endif
884 #endif
885         return 0;
886 }
887
888 /**
889  * @brief TLS SSL_CTX_set_max_send_fragment wrapper
890  * @param ctx TLS context
891  * @param val value (<0 ignored). Should be between 512 and 16k
892  * @param unused unused
893  * @return 0 on success, < 0 on failure (invalid value)
894  */
895 static int tls_ssl_ctx_set_max_send_fragment(SSL_CTX* ctx, long val, void* unused)
896 {
897         if (val >= 0)
898 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
899                 return SSL_CTX_set_max_send_fragment(ctx, val) -1;
900 #else
901                 return -1;
902 #endif
903         return 0;
904 }
905
906
907
908 /**
909  * @brief TLS SSL_CTX_set_read_ahead wrapper
910  * @param ctx TLS context
911  * @param val value (<0 ignored, 0 or >0)
912  * @param unused unused
913  * @return 0 (always success).
914  */
915 static int tls_ssl_ctx_set_read_ahead(SSL_CTX* ctx, long val, void* unused)
916 {
917         if (val >= 0)
918                 SSL_CTX_set_read_ahead(ctx, val);
919         return 0;
920 }
921
922
923 #ifndef OPENSSL_NO_TLSEXT
924
925 /**
926  * @brief SNI callback function
927  *
928  * callback on server_name -> trigger context switch if a TLS domain
929  * for the server_name is found (checks socket too) */
930 static int tls_server_name_cb(SSL *ssl, int *ad, void *private)
931 {
932     tls_domain_t *orig_domain, *new_domain;
933         str server_name;
934
935         orig_domain = (tls_domain_t*)private;
936         server_name.s = (char*)SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
937         if (server_name.s)  {
938                 LM_DBG("received server_name (TLS extension): '%s'\n", server_name.s);
939         } else {
940                 LM_DBG("SSL_get_servername returned NULL: return SSL_TLSEXT_ERR_NOACK\n");
941                 return SSL_TLSEXT_ERR_NOACK;
942         }
943
944         server_name.len = strlen(server_name.s);
945
946         new_domain = tls_lookup_cfg(*tls_domains_cfg, TLS_DOMAIN_SRV,
947                         &orig_domain->ip, orig_domain->port, &server_name, 0);
948         if (new_domain==NULL) {
949                 LM_DBG("TLS domain for socket [%s:%d] and server_name='%s' "
950                         "not found\n", ip_addr2a(&orig_domain->ip),
951                         orig_domain->port, server_name.s);
952                 /* we do not perform SSL_CTX switching, thus the default server domain
953                    for this socket (or the default server domain) will be used. */
954                 return SSL_TLSEXT_ERR_ALERT_WARNING;
955         }
956
957         LM_DBG("TLS cfg domain selected for received server name [%s]:"
958                 " socket [%s:%d] server name='%s' -"
959                 " switching SSL CTX to %p dom %p%s\n",
960                 server_name.s, ip_addr2a(&new_domain->ip),
961                 new_domain->port, ZSW(new_domain->server_name.s),
962                 new_domain->ctx[process_no], new_domain,
963                 (new_domain->type & TLS_DOMAIN_DEF)?" (default)":"");
964         SSL_set_SSL_CTX(ssl, new_domain->ctx[process_no]);
965         /* SSL_set_SSL_CTX only sets the correct certificate parameters, but does
966            set the proper verify options. Thus this will be done manually! */
967
968         SSL_set_options(ssl, SSL_CTX_get_options(SSL_get_SSL_CTX(ssl)));
969         if ((SSL_get_verify_mode(ssl) == SSL_VERIFY_NONE) ||
970                                 (SSL_num_renegotiations(ssl) == 0)) {
971                 /*
972                  * Only initialize the verification settings from the ctx
973                  * if they are not yet set, or if we're called when a new
974                  * SSL connection is set up (num_renegotiations == 0).
975                  * Otherwise, we would possibly reset a per-directory
976                  * configuration which was put into effect by ssl_hook_access.
977                  */
978                 SSL_set_verify(ssl, SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(ssl)),
979                         SSL_CTX_get_verify_callback(SSL_get_SSL_CTX(ssl)));
980         }
981
982         return SSL_TLSEXT_ERR_OK;
983 }
984 #endif
985
986
987 /**
988  * @brief Initialize all domain attributes from default domains if necessary
989  * @param d initialized TLS domain
990  * @param def default TLS domains
991  */
992 static int ksr_tls_fix_domain(tls_domain_t* d, tls_domain_t* def)
993 {
994         int i;
995         int procs_no;
996
997         if (ksr_tls_fill_missing(d, def) < 0) return -1;
998
999         if(d->type & TLS_DOMAIN_ANY) {
1000                 if(d->server_name.s==NULL || d->server_name.len<0) {
1001                         LM_ERR("%s: tls domain for any address but no server name\n",
1002                                         tls_domain_str(d));
1003                         return -1;
1004                 }
1005         }
1006
1007         procs_no=get_max_procs();
1008         d->ctx = (SSL_CTX**)shm_malloc(sizeof(SSL_CTX*) * procs_no);
1009         if (!d->ctx) {
1010                 ERR("%s: Cannot allocate shared memory\n", tls_domain_str(d));
1011                 return -1;
1012         }
1013         if(d->method>TLS_USE_TLSvRANGE) {
1014                 LM_DBG("using tls methods range: %d\n", d->method);
1015         } else {
1016                 LM_DBG("using one tls method version: %d\n", d->method);
1017         }
1018         memset(d->ctx, 0, sizeof(SSL_CTX*) * procs_no);
1019         for(i = 0; i < procs_no; i++) {
1020
1021 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1022                 /* libssl < 1.1.0 */
1023                 if(d->method>TLS_USE_TLSvRANGE) {
1024                         d->ctx[i] = SSL_CTX_new(SSLv23_method());
1025                 } else {
1026                         d->ctx[i] = SSL_CTX_new((SSL_METHOD*)ssl_methods[d->method - 1]);
1027                 }
1028                 if (d->ctx[i] == NULL) {
1029                         ERR("%s: Cannot create SSL context\n", tls_domain_str(d));
1030                         return -1;
1031                 }
1032                 if(d->method>TLS_USE_TLSvRANGE) {
1033                         SSL_CTX_set_options(d->ctx[i], (long)ssl_methods[d->method - 1]);
1034                 }
1035 #else
1036                 /* libssl >= 1.1.0 */
1037                 d->ctx[i] = SSL_CTX_new(sr_tls_methods[d->method - 1].TLSMethod);
1038                 if (d->ctx[i] == NULL) {
1039                         ERR("%s: Cannot create SSL context\n", tls_domain_str(d));
1040                         return -1;
1041                 }
1042                 if(d->method>TLS_USE_TLSvRANGE) {
1043                         if(sr_tls_methods[d->method - 1].TLSMethodMin) {
1044                                 SSL_CTX_set_min_proto_version(d->ctx[i],
1045                                                 sr_tls_methods[d->method - 1].TLSMethodMin);
1046                         }
1047                 } else {
1048                         if(sr_tls_methods[d->method - 1].TLSMethodMin) {
1049                                 SSL_CTX_set_min_proto_version(d->ctx[i],
1050                                                 sr_tls_methods[d->method - 1].TLSMethodMin);
1051                         }
1052                         if(sr_tls_methods[d->method - 1].TLSMethodMax) {
1053                                 SSL_CTX_set_max_proto_version(d->ctx[i],
1054                                                 sr_tls_methods[d->method - 1].TLSMethodMax);
1055                         }
1056                 }
1057 #endif
1058
1059 #ifndef OPENSSL_NO_TLSEXT
1060                 /*
1061                 * check server domains for server_name extension and register
1062                 * callback function
1063                 */
1064                 if ((d->type & TLS_DOMAIN_SRV)
1065                                 && (d->server_name.len>0 || (d->type & TLS_DOMAIN_DEF))) {
1066                         if (!SSL_CTX_set_tlsext_servername_callback(d->ctx[i], tls_server_name_cb)) {
1067                                 LM_ERR("register server_name callback handler for socket "
1068                                         "[%s:%d], server_name='%s' failed for proc %d\n",
1069                                         ip_addr2a(&d->ip), d->port,
1070                                         (d->server_name.s)?d->server_name.s:"<default>", i);
1071                                 return -1;
1072                         }
1073                         if (!SSL_CTX_set_tlsext_servername_arg(d->ctx[i], d)) {
1074                                 LM_ERR("register server_name callback handler data for socket "
1075                                         "[%s:%d], server_name='%s' failed for proc %d\n",
1076                                         ip_addr2a(&d->ip), d->port,
1077                                         (d->server_name.s)?d->server_name.s:"<default>", i);
1078                                 return -1;
1079                         }
1080                 }
1081 #endif
1082         }
1083
1084 #ifndef OPENSSL_NO_TLSEXT
1085         if ((d->type & TLS_DOMAIN_SRV)
1086                         && (d->server_name.len>0 || (d->type & TLS_DOMAIN_DEF))) {
1087                 LM_NOTICE("registered server_name callback handler for socket "
1088                         "[%s:%d], server_name='%s' ...\n", ip_addr2a(&d->ip), d->port,
1089                         (d->server_name.s)?d->server_name.s:"<default>");
1090         }
1091 #endif
1092
1093         if (load_cert(d) < 0) return -1;
1094         if (load_ca_list(d) < 0) return -1;
1095         if (load_crl(d) < 0) return -1;
1096         if (set_cipher_list(d) < 0) return -1;
1097         if (set_verification(d) < 0) return -1;
1098         if (set_ssl_options(d) < 0) return -1;
1099         if (set_session_cache(d) < 0) return -1;
1100         return 0;
1101 }
1102
1103
1104 /**
1105  * @brief Password callback, ask for private key password on CLI
1106  * @param buf buffer
1107  * @param size buffer size
1108  * @param rwflag not used
1109  * @param filename filename
1110  * @return length of password on success, 0 on error
1111  */
1112 static int passwd_cb(char *buf, int size, int rwflag, void *filename)
1113 {
1114 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
1115         UI *ui;
1116         const char *prompt;
1117
1118         ui = UI_new();
1119         if(ui == NULL)
1120                 goto err;
1121
1122         prompt = UI_construct_prompt(ui, "passphrase", filename);
1123         UI_add_input_string(ui, prompt, 0, buf, 0, size - 1);
1124         UI_process(ui);
1125         UI_free(ui);
1126         return strlen(buf);
1127
1128 err:
1129         ERR("passwd_cb: Error in passwd_cb\n");
1130         return 0;
1131
1132 #else
1133         if(des_read_pw_string(buf, size - 1, "Enter Private Key password:", 0)) {
1134                 ERR("Error in passwd_cb\n");
1135                 return 0;
1136         }
1137         return strlen(buf);
1138 #endif
1139 }
1140
1141 #ifndef OPENSSL_NO_ENGINE
1142 /*
1143  * Implement a hash map from SSL_CTX to private key
1144  * as HSM keys need to be process local
1145  */
1146 static map_void_t private_key_map;
1147
1148 /**
1149  * @brief Return a private key from the lookup table
1150  * @param p SSL_CTX*
1151  * @return EVP_PKEY on success, NULL on error
1152  */
1153 EVP_PKEY* tls_lookup_private_key(SSL_CTX* ctx)
1154 {
1155         void *pkey;
1156         char ctx_str[64];
1157         snprintf(ctx_str, 64, "SSL_CTX-%p", ctx);
1158         pkey =  map_get(&private_key_map, ctx_str);
1159         LM_DBG("Private key lookup for %s: %p\n", ctx_str, pkey);
1160         if (pkey)
1161                 return *(EVP_PKEY**)pkey;
1162         else
1163                 return NULL;
1164 }
1165
1166
1167
1168 /**
1169  * @brief Load a private key from an OpenSSL engine
1170  * @param d TLS domain
1171  * @return 0 on success, -1 on error
1172  *
1173  * Do this in mod_child() as PKCS#11 libraries are not guaranteed
1174  * to be fork() safe
1175  *
1176  * private_key setting which starts with /engine: is assumed to be
1177  * an HSM key and not a file-based key
1178  *
1179  * We store the private key in a local memory hash table as
1180  * HSM keys must be process-local. We use the SSL_CTX* address
1181  * as the key. We cannot put the key into d->ctx[i] as that is
1182  * in shared memory.
1183  */
1184 static int load_engine_private_key(tls_domain_t* d)
1185 {
1186         int idx, ret_pwd, i;
1187         EVP_PKEY *pkey;
1188         int procs_no;
1189         char ctx_str[64];
1190
1191         if (!d->pkey_file.s || !d->pkey_file.len) {
1192                 DBG("%s: No private key specified\n", tls_domain_str(d));
1193                 return 0;
1194         }
1195         if (strncmp(d->pkey_file.s, "/engine:", 8) != 0)
1196                 return 0;
1197         procs_no = get_max_procs();
1198         for (i = 0; i<procs_no; i++) {
1199                 snprintf(ctx_str, 64, "SSL_CTX-%p", d->ctx[i]);
1200                 for(idx = 0, ret_pwd = 0; idx < 3; idx++) {
1201                         if (i) {
1202                                 map_set(&private_key_map, ctx_str, pkey);
1203                                 ret_pwd = 1;
1204                         } else {
1205                                 pkey = tls_engine_private_key(d->pkey_file.s+8);
1206                                 if (pkey) {
1207                                         map_set(&private_key_map, ctx_str, pkey);
1208                                         // store the key for i = 0 to perform certificate sanity check
1209                                         ret_pwd = SSL_CTX_use_PrivateKey(d->ctx[i], pkey);
1210                                 } else {
1211                                         ret_pwd = 0;
1212                                 }
1213                         }
1214                         if (ret_pwd) {
1215                                 break;
1216                         } else {
1217                                 ERR("%s: Unable to load private key '%s'\n",
1218                                     tls_domain_str(d), d->pkey_file.s);
1219                                 TLS_ERR("load_private_key:");
1220                                 continue;
1221                         }
1222                 }
1223
1224                 if (!ret_pwd) {
1225                         ERR("%s: Unable to load engine key label '%s'\n",
1226                             tls_domain_str(d), d->pkey_file.s);
1227                         TLS_ERR("load_private_key:");
1228                         return -1;
1229                 }
1230                 if (i == 0 && !SSL_CTX_check_private_key(d->ctx[i])) {
1231                         ERR("%s: Key '%s' does not match the public key of the"
1232                             " certificate\n", tls_domain_str(d), d->pkey_file.s);
1233                         TLS_ERR("load_engine_private_key:");
1234                         return -1;
1235                 }
1236         }
1237
1238
1239         LM_INFO("%s: Key '%s' successfully loaded\n",
1240                 tls_domain_str(d), d->pkey_file.s);
1241         return 0;
1242 }
1243 #endif
1244 /**
1245  * @brief Load a private key from a file 
1246  * @param d TLS domain
1247  * @return 0 on success, -1 on error
1248  */
1249 static int load_private_key(tls_domain_t* d)
1250 {
1251         int idx, ret_pwd, i;
1252         int procs_no;
1253         
1254         if (!d->pkey_file.s || !d->pkey_file.len) {
1255                 DBG("%s: No private key specified\n", tls_domain_str(d));
1256                 return 0;
1257         }
1258         if (fix_shm_pathname(&d->pkey_file) < 0)
1259                 return -1;
1260
1261         procs_no=get_max_procs();
1262         for(i = 0; i < procs_no; i++) {
1263                 SSL_CTX_set_default_passwd_cb(d->ctx[i], passwd_cb);
1264                 SSL_CTX_set_default_passwd_cb_userdata(d->ctx[i], d->pkey_file.s);
1265                 
1266                 for(idx = 0, ret_pwd = 0; idx < 3; idx++) {
1267 #ifndef OPENSSL_NO_ENGINE
1268                         // in PROC_INIT skip loading HSM keys due to
1269                         // fork() issues with PKCS#11 libaries
1270                         if (strncmp(d->pkey_file.s, "/engine:", 8) != 0) {
1271                                 ret_pwd = SSL_CTX_use_PrivateKey_file(d->ctx[i], d->pkey_file.s,
1272                                         SSL_FILETYPE_PEM);
1273                         } else {
1274                                 ret_pwd = 1;
1275                         }
1276 #else
1277                         ret_pwd = SSL_CTX_use_PrivateKey_file(d->ctx[i], d->pkey_file.s,
1278                                         SSL_FILETYPE_PEM);
1279 #endif
1280                         if (ret_pwd) {
1281                                 break;
1282                         } else {
1283                                 ERR("%s: Unable to load private key '%s'\n",
1284                                     tls_domain_str(d), d->pkey_file.s);
1285                                 TLS_ERR("load_private_key:");
1286                                 continue;
1287                         }
1288                 }
1289                 
1290                 if (!ret_pwd) {
1291                         ERR("%s: Unable to load private key file '%s'\n",
1292                             tls_domain_str(d), d->pkey_file.s);
1293                         TLS_ERR("load_private_key:");
1294                         return -1;
1295                 }
1296 #ifndef OPENSSL_NO_ENGINE
1297                 if (strncmp(d->pkey_file.s, "/engine:", 8) == 0) {
1298                         // skip private key validity check for HSM keys
1299                         continue;
1300                 }
1301 #endif
1302                 if (!SSL_CTX_check_private_key(d->ctx[i])) {
1303                         ERR("%s: Key '%s' does not match the public key of the"
1304                                         " certificate\n", tls_domain_str(d), d->pkey_file.s);
1305                         TLS_ERR("load_private_key:");
1306                         return -1;
1307                 }
1308         }               
1309
1310         DBG("%s: Key '%s' successfully loaded\n",
1311             tls_domain_str(d), d->pkey_file.s);
1312         return 0;
1313 }
1314
1315
1316 #ifndef OPENSSL_NO_ENGINE
1317 /**
1318  * @brief Initialize engine private keys
1319  *
1320  * PKCS#11 libraries are not guaranteed to be fork() safe
1321  * so we fix private keys in the child
1322  */
1323 int tls_fix_engine_keys(tls_domains_cfg_t* cfg, tls_domain_t* srv_defaults,
1324                                 tls_domain_t* cli_defaults)
1325 {
1326         tls_domain_t* d;
1327         d = cfg->srv_list;
1328         while(d) {
1329                 if (load_engine_private_key(d) < 0) return -1;
1330                 d = d->next;
1331         }
1332
1333         d = cfg->cli_list;
1334         while(d) {
1335                 if (load_engine_private_key(d) < 0) return -1;
1336                 d = d->next;
1337         }
1338
1339         if (load_engine_private_key(cfg->srv_default) < 0) return -1;
1340         if (load_engine_private_key(cfg->cli_default) < 0) return -1;
1341
1342         return 0;
1343
1344 }
1345 #endif
1346 /**
1347  * @brief Initialize attributes of all domains from default domains if necessary
1348  *
1349  * Initialize attributes of all domains from default domains if necessary,
1350  * fill in missing parameters.
1351  * @param cfg initialized domain
1352  * @param srv_defaults server defaults
1353  * @param cli_defaults command line interface defaults
1354  * @return 0 on success, -1 on error
1355  */
1356 int tls_fix_domains_cfg(tls_domains_cfg_t* cfg, tls_domain_t* srv_defaults,
1357                                 tls_domain_t* cli_defaults)
1358 {
1359         tls_domain_t* d;
1360         int ssl_mode_release_buffers;
1361         int ssl_freelist_max_len;
1362         int ssl_max_send_fragment;
1363         int ssl_read_ahead;
1364
1365         if (!cfg->cli_default) {
1366                 cfg->cli_default = tls_new_domain(TLS_DOMAIN_DEF | TLS_DOMAIN_CLI,
1367                                                                                         0, 0);
1368         }
1369
1370         if (!cfg->srv_default) {
1371                 cfg->srv_default = tls_new_domain(TLS_DOMAIN_DEF | TLS_DOMAIN_SRV,
1372                                                                                         0, 0);
1373         }
1374
1375         if (ksr_tls_fix_domain(cfg->srv_default, srv_defaults) < 0) return -1;
1376         if (ksr_tls_fix_domain(cfg->cli_default, cli_defaults) < 0) return -1;
1377
1378         d = cfg->srv_list;
1379         while (d) {
1380                 if (ksr_tls_fix_domain(d, srv_defaults) < 0) return -1;
1381                 d = d->next;
1382         }
1383
1384         d = cfg->cli_list;
1385         while (d) {
1386                 if (ksr_tls_fix_domain(d, cli_defaults) < 0) return -1;
1387                 d = d->next;
1388         }
1389
1390              /* Ask for passwords as the last step */
1391         d = cfg->srv_list;
1392         while(d) {
1393                 if (load_private_key(d) < 0) return -1;
1394                 d = d->next;
1395         }
1396
1397         d = cfg->cli_list;
1398         while(d) {
1399                 if (load_private_key(d) < 0) return -1;
1400                 d = d->next;
1401         }
1402
1403         if (load_private_key(cfg->srv_default) < 0) return -1;
1404         if (load_private_key(cfg->cli_default) < 0) return -1;
1405
1406         /* set various global per CTX options
1407          * (done here to show possible missing features messages only once)
1408          */
1409         ssl_mode_release_buffers = cfg_get(tls, tls_cfg, ssl_release_buffers);
1410         ssl_freelist_max_len = cfg_get(tls, tls_cfg, ssl_freelist_max);
1411         ssl_max_send_fragment = cfg_get(tls, tls_cfg, ssl_max_send_fragment);
1412         ssl_read_ahead = cfg_get(tls, tls_cfg, ssl_read_ahead);
1413 #if OPENSSL_VERSION_NUMBER >= 0x01000000L
1414         /* set SSL_MODE_RELEASE_BUFFERS if ssl_mode_release_buffers !=0,
1415            reset if == 0 and ignore if < 0 */
1416         /* only in >= 1.0.0 */
1417         if (ssl_mode_release_buffers >= 0 &&
1418                 tls_foreach_CTX_in_cfg(cfg, tls_ssl_ctx_mode, SSL_MODE_RELEASE_BUFFERS,
1419                                                                 (void*)(long)(ssl_mode_release_buffers==0))
1420                 < 0) {
1421                 ERR("invalid ssl_release_buffers value (%d)\n",
1422                                 ssl_mode_release_buffers);
1423                 return -1;
1424         }
1425 #else
1426         if (ssl_mode_release_buffers > 0)
1427                 ERR("cannot change openssl mode_release_buffers, the openssl version"
1428                                 " is too old (need at least 1.0.0)\n");
1429 #endif
1430         /* only in >= 1.0.0 */
1431 #if OPENSSL_VERSION_NUMBER >= 0x01000000L
1432 #ifndef OPENSSL_NO_BUF_FREELISTS
1433         if (tls_foreach_CTX_in_cfg(cfg, tls_ssl_ctx_set_freelist,
1434                                                                 ssl_freelist_max_len, 0) < 0) {
1435                 ERR("invalid ssl_freelist_max_len value (%d)\n",
1436                                 ssl_freelist_max_len);
1437                 return -1;
1438         }
1439 #endif
1440 #endif
1441 #if defined (OPENSSL_NO_BUF_FREELISTS) || OPENSSL_VERSION_NUMBER < 0x01000000L
1442         if (ssl_freelist_max_len >= 0)
1443                 ERR("cannot change openssl freelist_max_len, openssl too old"
1444                                 "(needed at least 1.0.0) or compiled without freelist support"
1445                                 " (OPENSSL_NO_BUF_FREELIST)\n");
1446 #endif
1447 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
1448         /* only in >= 0.9.9 */
1449         if (tls_foreach_CTX_in_cfg(cfg, tls_ssl_ctx_set_max_send_fragment,
1450                                                                 ssl_max_send_fragment, 0) < 0) {
1451                 ERR("invalid ssl_max_send_fragment value (%d)\n",
1452                                 ssl_max_send_fragment);
1453                 return -1;
1454         }
1455 #else
1456         if (ssl_max_send_fragment > 0)
1457                 ERR("cannot change openssl max_send_fragment, the openssl version"
1458                                 " is too old (need at least 0.9.9)\n");
1459 #endif
1460         if (tls_foreach_CTX_in_cfg(cfg, tls_ssl_ctx_set_read_ahead,
1461                                                                 ssl_read_ahead, 0) < 0) {
1462                 ERR("invalid ssl_read_ahead value (%d)\n", ssl_read_ahead);
1463                 return -1;
1464         }
1465         /* set options for SSL_write:
1466                 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER - needed when queueing
1467                   clear text for a future write (WANTS_READ). In this case the
1468                   buffer address will change for the repeated SSL_write() and
1469                   without this option it will trigger the openssl sanity checks.
1470                 SSL_MODE_ENABLE_PARTIAL_WRITE - needed to deal with potentially
1471                   huge multi-record writes that don't fit in the default buffer
1472                   (the default buffer must have space for at least 1 record) */
1473         if (tls_foreach_CTX_in_cfg(cfg, tls_ssl_ctx_mode,
1474                                                                 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
1475                                                                 SSL_MODE_ENABLE_PARTIAL_WRITE,
1476                                                                 0) < 0) {
1477                 ERR("could not set SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER and"
1478                                 " SSL_MODE_ENABLE_PARTIAL_WRITE\n");
1479                 return -1;
1480         }
1481
1482         return 0;
1483 }
1484
1485
1486 /**
1487  * @brief Create new configuration structure
1488  * 
1489  * Create new configuration structure in new allocated shared memory
1490  * @return configuration structure or zero on error
1491  */
1492 tls_domains_cfg_t* tls_new_cfg(void)
1493 {
1494         tls_domains_cfg_t* r;
1495
1496         r = (tls_domains_cfg_t*)shm_malloc(sizeof(tls_domains_cfg_t));
1497         if (!r) {
1498                 ERR("No memory left\n");
1499                 return 0;
1500         }
1501         memset(r, 0, sizeof(tls_domains_cfg_t));
1502         atomic_set(&r->ref_count, 0);
1503         return r;
1504 }
1505
1506
1507 /**
1508  * @brief Lookup TLS configuration based on type, ip, and port
1509  * @param cfg configuration set
1510  * @param type type of configuration
1511  * @param ip IP for configuration
1512  * @param port port for configuration
1513  * @return found configuration or default, if not found
1514  */
1515 tls_domain_t* tls_lookup_cfg(tls_domains_cfg_t* cfg, int type,
1516                 struct ip_addr* ip, unsigned short port, str *sname, str *srvid)
1517 {
1518         tls_domain_t *p;
1519         int dotpos;
1520
1521         if (type & TLS_DOMAIN_DEF) {
1522                 if (type & TLS_DOMAIN_SRV) return cfg->srv_default;
1523                 else return cfg->cli_default;
1524         } else {
1525                 if (type & TLS_DOMAIN_SRV) p = cfg->srv_list;
1526                 else p = cfg->cli_list;
1527         }
1528
1529         while (p) {
1530                 if(srvid && srvid->len>0) {
1531                         LM_DBG("comparing addr: [%s:%d]  [%s:%d] -- id: [%.*s] [%.*s]\n",
1532                                 ip_addr2a(&p->ip), p->port, ip_addr2a(ip), port,
1533                                 p->server_id.len, ZSW(p->server_id.s),
1534                                 srvid->len, ZSW(srvid->s));
1535                         if(p->server_id.s && p->server_id.len==srvid->len
1536                                         && strncasecmp(p->server_name.s, srvid->s, srvid->len)==0) {
1537                                 LM_DBG("TLS config found by server id\n");
1538                                 return p;
1539                         }
1540
1541                 }
1542                 if(sname) {
1543                         LM_DBG("comparing addr: l[%s:%d]  r[%s:%d] -- sni: l[%.*s] r[%.*s] %d"
1544                                 " -- type: %d\n",
1545                                 ip_addr2a(&p->ip), p->port, ip_addr2a(ip), port,
1546                                 p->server_name.len, ZSW(p->server_name.s),
1547                                 sname->len, ZSW(sname->s), p->server_name_mode, p->type);
1548                 }
1549                 if ((p->type & TLS_DOMAIN_ANY)
1550                                 || ((p->port==0 || p->port == port)
1551                                                 && ip_addr_cmp(&p->ip, ip))) {
1552                         if(sname && sname->s && sname->len>0
1553                                                 && p->server_name.s && p->server_name.len>0) {
1554                                 if (p->server_name_mode!=KSR_TLS_SNM_SUBDOM) {
1555                                         /* match sni domain */
1556                                         if(p->server_name.len==sname->len
1557                                                                 && strncasecmp(p->server_name.s, sname->s,
1558                                                                         sname->len)==0) {
1559                                                 LM_DBG("socket+server_name based TLS server domain found\n");
1560                                                 return p;
1561                                         }
1562                                 }
1563                                 if ((p->server_name_mode==KSR_TLS_SNM_INCDOM
1564                                                         || p->server_name_mode==KSR_TLS_SNM_SUBDOM)
1565                                                 && (p->server_name.len<sname->len)) {
1566                                         dotpos = sname->len - p->server_name.len - 1;
1567                                         if(sname->s[dotpos] == '.'
1568                                                         && strncasecmp(p->server_name.s,
1569                                                                         sname->s + dotpos + 1,
1570                                                                         p->server_name.len)==0) {
1571                                                 LM_DBG("socket+server_name based TLS server sub-domain found\n");
1572                                                 return p;
1573                                         }
1574                                 }
1575                         } else {
1576                                 if (!(p->type & TLS_DOMAIN_ANY)) {
1577                                         LM_DBG("socket based TLS server domain found\n");
1578                                         return p;
1579                                 }
1580                         }
1581                 }
1582                 p = p->next;
1583         }
1584
1585         /* No matching domain found, return default */
1586         if (type & TLS_DOMAIN_SRV) return cfg->srv_default;
1587         else return cfg->cli_default;
1588 }
1589
1590
1591 /**
1592  * @brief Check whether configuration domain is duplicated
1593  * @param cfg configuration set
1594  * @param d checked domain
1595  * @return 1 if domain is duplicated, 0 if it's not
1596  */
1597 int ksr_tls_domain_duplicated(tls_domains_cfg_t* cfg, tls_domain_t* d)
1598 {
1599         tls_domain_t *p;
1600
1601         if (d->type & TLS_DOMAIN_DEF) {
1602                 if (d->type & TLS_DOMAIN_SRV) {
1603                         if(cfg->srv_default==d) {
1604                                 return 0;
1605                         }
1606                         return cfg->srv_default != NULL;
1607                 } else {
1608                         if(cfg->cli_default==d) {
1609                                 return 0;
1610                         }
1611                         return cfg->cli_default != NULL;
1612                 }
1613         } else {
1614                 if (d->type & TLS_DOMAIN_SRV) p = cfg->srv_list;
1615                 else p = cfg->cli_list;
1616         }
1617
1618         if(d->type & TLS_DOMAIN_ANY) {
1619                 /* any address, it must have server_name for SNI */
1620                 if(d->server_name.len==0) {
1621                         LM_WARN("duplicate definition for a tls profile (same address)"
1622                                         " and no server name provided\n");
1623                         return 1;
1624                 } else {
1625                         return 0;
1626                 }
1627         }
1628
1629         while (p) {
1630                 if(p!=d) {
1631                         if ((p->port == d->port) && ip_addr_cmp(&p->ip, &d->ip)) {
1632                                 if(d->server_name.len==0 || p->server_name.len==0) {
1633                                         LM_WARN("duplicate definition for a tls profile (same address)"
1634                                                         " and no server name provided\n");
1635                                         return 1;
1636                                 }
1637                         }
1638                 }
1639                 p = p->next;
1640         }
1641
1642         return 0;
1643 }
1644
1645
1646 /**
1647  * @brief Add a domain to the configuration set
1648  * @param cfg configuration set
1649  * @param d TLS domain
1650  * @return 1 if domain already exists, 0 after addition, -1 on error
1651  */
1652 int tls_add_domain(tls_domains_cfg_t* cfg, tls_domain_t* d)
1653 {
1654         if (!cfg) {
1655                 ERR("TLS configuration structure missing\n");
1656                 return -1;
1657         }
1658
1659         if (d->type & TLS_DOMAIN_DEF) {
1660                 if (d->type & TLS_DOMAIN_CLI) {
1661                         cfg->cli_default = d;
1662                 } else {
1663                         cfg->srv_default = d;
1664                 }
1665         } else {
1666                 if (d->type & TLS_DOMAIN_SRV) {
1667                         d->next = cfg->srv_list;
1668                         cfg->srv_list = d;
1669                 } else {
1670                         d->next = cfg->cli_list;
1671                         cfg->cli_list = d;
1672                 }
1673         }
1674         return 0;
1675 }