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