1 /* Copyright (c) 2007-2009, UNINETT AS
2  * Copyright (c) 2010-2011,2015-2016, NORDUnet A/S */
3 /* See LICENSE for licensing information. */
4 
5 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
6 #define _GNU_SOURCE
7 #include <stdio.h>
8 #include <signal.h>
9 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <netdb.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <limits.h>
15 #include <fcntl.h>
16 #include <poll.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <ctype.h>
20 #include <sys/wait.h>
21 #include <arpa/inet.h>
22 #include <regex.h>
23 #include <libgen.h>
24 #include <pthread.h>
25 #include <openssl/ssl.h>
26 #include <openssl/rand.h>
27 #include <openssl/err.h>
28 #include <openssl/md5.h>
29 #include <openssl/x509v3.h>
30 #include "debug.h"
31 #include "hash.h"
32 #include "util.h"
33 #include "hostport.h"
34 #include "radsecproxy.h"
35 
36 static struct hash *tlsconfs = NULL;
37 
38 #define COOKIE_SECRET_LENGTH 16
39 static unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
40 static uint8_t cookie_secret_initialized = 0;
41 
42 
43 /* callbacks for making OpenSSL < 1.1 thread safe */
44 #if OPENSSL_VERSION_NUMBER < 0x10100000
45 static pthread_mutex_t *ssl_locks = NULL;
46 
47 #if OPENSSL_VERSION_NUMBER < 0x10000000
ssl_thread_id()48 unsigned long ssl_thread_id() {
49     return (unsigned long)pthread_self();
50 }
51 #else
ssl_thread_id(CRYPTO_THREADID * id)52 void ssl_thread_id(CRYPTO_THREADID *id) {
53     CRYPTO_THREADID_set_numeric(id, (unsigned long)pthread_self());
54 }
55 #endif
56 
57 
ssl_locking_callback(int mode,int type,const char * file,int line)58 void ssl_locking_callback(int mode, int type, const char *file, int line) {
59     if (mode & CRYPTO_LOCK)
60        pthread_mutex_lock(&ssl_locks[type]);
61     else
62        pthread_mutex_unlock(&ssl_locks[type]);
63 }
64 #endif
65 
sslinit()66 void sslinit() {
67 #if OPENSSL_VERSION_NUMBER < 0x10100000
68     int i;
69 
70     SSL_library_init();
71 
72     ssl_locks = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
73     if (!ssl_locks)
74         debugx(1, DBG_ERR, "malloc failed");
75 
76     for (i = 0; i < CRYPTO_num_locks(); i++) {
77         pthread_mutex_init(&ssl_locks[i], NULL);
78     }
79 #if OPENSSL_VERSION_NUMBER < 0x10000000
80     CRYPTO_set_id_callback(ssl_thread_id);
81 #else
82     CRYPTO_THREADID_set_callback(ssl_thread_id);
83 #endif
84     CRYPTO_set_locking_callback(ssl_locking_callback);
85     SSL_load_error_strings();
86 #else
87     OPENSSL_init_ssl(0, NULL);
88 #endif
89 }
90 
pem_passwd_cb(char * buf,int size,int rwflag,void * userdata)91 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
92     int pwdlen = strlen(userdata);
93     if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
94 	return 0;
95     memcpy(buf, userdata, pwdlen);
96     return pwdlen;
97 }
98 
verify_cb(int ok,X509_STORE_CTX * ctx)99 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
100     char *buf = NULL;
101     X509 *err_cert;
102     int err, depth;
103 
104     err_cert = X509_STORE_CTX_get_current_cert(ctx);
105     err = X509_STORE_CTX_get_error(ctx);
106     depth = X509_STORE_CTX_get_error_depth(ctx);
107 
108     if (depth > MAX_CERT_DEPTH) {
109 	ok = 0;
110 	err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
111 	X509_STORE_CTX_set_error(ctx, err);
112     }
113 
114     if (!ok) {
115 	if (err_cert)
116 	    buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
117 	debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
118 	free(buf);
119 	buf = NULL;
120 
121 	switch (err) {
122 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
123 	    if (err_cert) {
124 		buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
125 		if (buf) {
126 		    debug(DBG_WARN, "\tIssuer=%s", buf);
127 		    free(buf);
128 		    buf = NULL;
129 		}
130 	    }
131 	    break;
132 	case X509_V_ERR_CERT_NOT_YET_VALID:
133 	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
134 	    debug(DBG_WARN, "\tCertificate not yet valid");
135 	    break;
136 	case X509_V_ERR_CERT_HAS_EXPIRED:
137 	    debug(DBG_WARN, "Certificate has expired");
138 	    break;
139 	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
140 	    debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
141 	    break;
142 	case X509_V_ERR_NO_EXPLICIT_POLICY:
143 	    debug(DBG_WARN, "No Explicit Certificate Policy");
144 	    break;
145 	}
146     }
147 #ifdef DEBUG
148     printf("certificate verify returns %d\n", ok);
149 #endif
150     return ok;
151 }
152 
cookie_calculate_hash(struct sockaddr * peer,time_t time,uint8_t * result,unsigned int * resultlength)153 static int cookie_calculate_hash(struct sockaddr *peer, time_t time, uint8_t *result, unsigned int *resultlength) {
154     uint8_t *buf;
155     int length;
156 
157     length = SOCKADDRP_SIZE(peer) + sizeof(time_t);
158     buf = OPENSSL_malloc(length);
159     if (!buf) {
160         debug(DBG_ERR, "cookie_calculate_hash: malloc failed");
161         return 0;
162     }
163 
164     memcpy(buf, &time, sizeof(time_t));
165     memcpy(buf+sizeof(time_t), peer, SOCKADDRP_SIZE(peer));
166 
167     HMAC(EVP_sha256(), (const void*) cookie_secret, COOKIE_SECRET_LENGTH,
168          buf, length, result, resultlength);
169     OPENSSL_free(buf);
170     return 1;
171 }
172 
cookie_generate_cb(SSL * ssl,unsigned char * cookie,unsigned int * cookie_len)173 static int cookie_generate_cb(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) {
174     struct sockaddr_storage peer;
175     struct timeval now;
176     uint8_t result[EVP_MAX_MD_SIZE];
177     unsigned int resultlength;
178 
179     if (!cookie_secret_initialized) {
180         if (!RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH))
181             debugx(1,DBG_ERR, "cookie_generate_cg: error generating random secret");
182         cookie_secret_initialized = 1;
183     }
184 
185     if (BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer) <= 0)
186         return 0;
187     gettimeofday(&now, NULL);
188     if (!cookie_calculate_hash((struct sockaddr *)&peer, now.tv_sec, result, &resultlength))
189         return 0;
190 
191     memcpy(cookie, &now.tv_sec, sizeof(time_t));
192     memcpy(cookie + sizeof(time_t), result, resultlength);
193     *cookie_len = resultlength + sizeof(time_t);
194 
195     return 1;
196 }
197 
198 #if OPENSSL_VERSION_NUMBER < 0x10100000
cookie_verify_cb(SSL * ssl,unsigned char * cookie,unsigned int cookie_len)199 static int cookie_verify_cb(SSL *ssl, unsigned char *cookie, unsigned int cookie_len) {
200 #else
201 static int cookie_verify_cb(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len) {
202 #endif
203     struct sockaddr_storage peer;
204     struct timeval now;
205     time_t cookie_time;
206     uint8_t result[EVP_MAX_MD_SIZE];
207     unsigned int resultlength;
208 
209     if (!cookie_secret_initialized)
210         return 0;
211 
212     if (cookie_len < sizeof(time_t)) {
213         debug(DBG_DBG, "cookie_verify_cb: cookie too short. ignoring.");
214         return 0;
215     }
216 
217     gettimeofday(&now, NULL);
218     cookie_time = *(time_t *)cookie;
219     if (now.tv_sec - cookie_time > 5) {
220         debug(DBG_DBG, "cookie_verify_cb: cookie invalid or older than 5s. ignoring.");
221         return 0;
222     }
223 
224     if (BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer) <= 0)
225         return 0;
226     if (!cookie_calculate_hash((struct sockaddr *)&peer, cookie_time, result, &resultlength))
227         return 0;
228 
229     if (resultlength + sizeof(time_t) != cookie_len) {
230         debug(DBG_DBG, "cookie_verify_cb: invalid cookie length. ignoring.");
231         return 0;
232     }
233 
234     if (memcmp(cookie + sizeof(time_t), result, resultlength)) {
235         debug(DBG_DBG, "cookie_verify_cb: cookie not valid. ignoring.");
236         return 0;
237     }
238     return 1;
239 }
240 
241 #ifdef DEBUG
242 static void ssl_info_callback(const SSL *ssl, int where, int ret) {
243     const char *s;
244     int w;
245 
246     w = where & ~SSL_ST_MASK;
247 
248     if (w & SSL_ST_CONNECT)
249 	s = "SSL_connect";
250     else if (w & SSL_ST_ACCEPT)
251 	s = "SSL_accept";
252     else
253 	s = "undefined";
254 
255     if (where & SSL_CB_LOOP)
256 	debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
257     else if (where & SSL_CB_ALERT) {
258 	s = (where & SSL_CB_READ) ? "read" : "write";
259 	debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
260     }
261     else if (where & SSL_CB_EXIT) {
262 	if (ret == 0)
263 	    debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
264 	else if (ret < 0)
265 	    debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
266     }
267 }
268 #endif
269 
270 static X509_VERIFY_PARAM *createverifyparams(char **poids) {
271     X509_VERIFY_PARAM *pm;
272     ASN1_OBJECT *pobject;
273     int i;
274 
275     pm = X509_VERIFY_PARAM_new();
276     if (!pm)
277 	return NULL;
278 
279     for (i = 0; poids[i]; i++) {
280 	pobject = OBJ_txt2obj(poids[i], 0);
281 	if (!pobject) {
282 	    X509_VERIFY_PARAM_free(pm);
283 	    return NULL;
284 	}
285 	X509_VERIFY_PARAM_add0_policy(pm, pobject);
286     }
287 
288     X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
289     return pm;
290 }
291 
292 static int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
293     STACK_OF(X509_NAME) *calist;
294     X509_STORE *x509_s;
295     unsigned long error;
296 
297     SSL_CTX_set_cert_store(ctx, X509_STORE_new());
298     if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
299 	while ((error = ERR_get_error()))
300 	    debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
301 	debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
302 	return 0;
303     }
304 
305     calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
306     if (!conf->cacertfile || calist) {
307 	if (conf->cacertpath) {
308 	    if (!calist)
309 		calist = sk_X509_NAME_new_null();
310 	    if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
311 		sk_X509_NAME_free(calist);
312 		calist = NULL;
313 	    }
314 	}
315     }
316     if (!calist) {
317 	while ((error = ERR_get_error()))
318 	    debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
319 	debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
320 	return 0;
321     }
322     ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
323     SSL_CTX_set_client_CA_list(ctx, calist);
324 
325     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
326     SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
327     SSL_CTX_set_cookie_generate_cb(ctx, cookie_generate_cb);
328     SSL_CTX_set_cookie_verify_cb(ctx, cookie_verify_cb);
329 
330     if (conf->crlcheck || conf->vpm) {
331 	x509_s = SSL_CTX_get_cert_store(ctx);
332 	if (conf->crlcheck)
333 	    X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
334 	if (conf->vpm)
335 	    X509_STORE_set1_param(x509_s, conf->vpm);
336     }
337 
338     debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
339     return 1;
340 }
341 
342 static SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
343     SSL_CTX *ctx = NULL;
344     unsigned long error;
345 
346     switch (type) {
347 #ifdef RADPROT_TLS
348     case RAD_TLS:
349 #if OPENSSL_VERSION_NUMBER >= 0x10100000
350         /* TLS_method() was introduced in OpenSSL 1.1.0. */
351 	ctx = SSL_CTX_new(TLS_method());
352 #else
353         /* No TLS_method(), use SSLv23_method() and disable SSLv2 and SSLv3. */
354         ctx = SSL_CTX_new(SSLv23_method());
355         SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
356 #endif
357 #ifdef DEBUG
358 	SSL_CTX_set_info_callback(ctx, ssl_info_callback);
359 #endif
360 	break;
361 #endif
362 #ifdef RADPROT_DTLS
363     case RAD_DTLS:
364 #if OPENSSL_VERSION_NUMBER >= 0x10002000
365         /* DTLS_method() seems to have been introduced in OpenSSL 1.0.2. */
366 	ctx = SSL_CTX_new(DTLS_method());
367 #else
368 	ctx = SSL_CTX_new(DTLSv1_method());
369 #endif
370 #ifdef DEBUG
371 	SSL_CTX_set_info_callback(ctx, ssl_info_callback);
372 #endif
373 	SSL_CTX_set_read_ahead(ctx, 1);
374 	break;
375 #endif
376     }
377     if (!ctx) {
378 	debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
379 	return NULL;
380     }
381 
382 #if OPENSSL_VERSION_NUMBER < 0x10100000L
383     {
384     long sslversion = SSLeay();
385     if (sslversion < 0x00908100L ||
386         (sslversion >= 0x10000000L && sslversion < 0x10000020L)) {
387         debug(DBG_WARN, "%s: %s seems to be of a version with a "
388 	      "certain security critical bug (fixed in OpenSSL 0.9.8p and "
389 	      "1.0.0b).  Disabling OpenSSL session caching for context %p.",
390 	      __func__, SSLeay_version(SSLEAY_VERSION), ctx);
391         SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
392     }
393     }
394 #endif
395 
396     if (conf->certkeypwd) {
397 	SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
398 	SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
399     }
400     if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
401 	!SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
402 	!SSL_CTX_check_private_key(ctx)) {
403 	while ((error = ERR_get_error()))
404 	    debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
405 	debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
406 	SSL_CTX_free(ctx);
407 	return NULL;
408     }
409 
410     if (conf->policyoids) {
411 	if (!conf->vpm) {
412 	    conf->vpm = createverifyparams(conf->policyoids);
413 	    if (!conf->vpm) {
414 		debug(DBG_ERR, "tlscreatectx: Failed to add policyOIDs in TLS context %s", conf->name);
415 		SSL_CTX_free(ctx);
416 		return NULL;
417 	    }
418 	}
419     }
420 
421     if (!tlsaddcacrl(ctx, conf)) {
422 	if (conf->vpm) {
423 	    X509_VERIFY_PARAM_free(conf->vpm);
424 	    conf->vpm = NULL;
425 	}
426 	SSL_CTX_free(ctx);
427 	return NULL;
428     }
429 
430     debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
431     return ctx;
432 }
433 
434 struct tls *tlsgettls(char *alt1, char *alt2) {
435     struct tls *t;
436 
437     t = hash_read(tlsconfs, alt1, strlen(alt1));
438     if (!t)
439 	t = hash_read(tlsconfs, alt2, strlen(alt2));
440     return t;
441 }
442 
443 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
444     struct timeval now;
445 
446     if (!t)
447 	return NULL;
448     gettimeofday(&now, NULL);
449 
450     switch (type) {
451 #ifdef RADPROT_TLS
452     case RAD_TLS:
453 	if (t->tlsexpiry && t->tlsctx) {
454 	    if (t->tlsexpiry < now.tv_sec) {
455 		t->tlsexpiry = now.tv_sec + t->cacheexpiry;
456 		tlsaddcacrl(t->tlsctx, t);
457 	    }
458 	}
459 	if (!t->tlsctx) {
460 	    t->tlsctx = tlscreatectx(RAD_TLS, t);
461 	    if (t->cacheexpiry)
462 		t->tlsexpiry = now.tv_sec + t->cacheexpiry;
463 	}
464 	return t->tlsctx;
465 #endif
466 #ifdef RADPROT_DTLS
467     case RAD_DTLS:
468 	if (t->dtlsexpiry && t->dtlsctx) {
469 	    if (t->dtlsexpiry < now.tv_sec) {
470 		t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
471 		tlsaddcacrl(t->dtlsctx, t);
472 	    }
473 	}
474 	if (!t->dtlsctx) {
475 	    t->dtlsctx = tlscreatectx(RAD_DTLS, t);
476 	    if (t->cacheexpiry)
477 		t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
478 	}
479 	return t->dtlsctx;
480 #endif
481     }
482     return NULL;
483 }
484 
485 void tlsreloadcrls() {
486     struct tls *conf;
487     struct hash_entry *entry;
488     struct timeval now;
489 
490     debug (DBG_NOTICE, "reloading CRLs");
491 
492     gettimeofday(&now, NULL);
493 
494     for (entry = hash_first(tlsconfs); entry; entry = hash_next(entry)) {
495 	conf = (struct tls *)entry->data;
496 #ifdef RADPROT_TLS
497 	if (conf->tlsctx) {
498 	    if (conf->tlsexpiry)
499 		conf->tlsexpiry = now.tv_sec + conf->cacheexpiry;
500 	    tlsaddcacrl(conf->tlsctx, conf);
501 	}
502 #endif
503 #ifdef RADPROT_DTLS
504 	if (conf->dtlsctx) {
505 	    if (conf->dtlsexpiry)
506 		conf->dtlsexpiry = now.tv_sec + conf->cacheexpiry;
507 	    tlsaddcacrl(conf->dtlsctx, conf);
508 	}
509 #endif
510     }
511 }
512 
513 X509 *verifytlscert(SSL *ssl) {
514     X509 *cert;
515     unsigned long error;
516 
517     if (SSL_get_verify_result(ssl) != X509_V_OK) {
518 	debug(DBG_ERR, "verifytlscert: basic validation failed");
519 	while ((error = ERR_get_error()))
520 	    debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
521 	return NULL;
522     }
523 
524     cert = SSL_get_peer_certificate(ssl);
525     if (!cert)
526 	debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
527     return cert;
528 }
529 
530 static int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
531     int loc, i, l, n, r = 0;
532     char *v;
533     X509_EXTENSION *ex;
534     STACK_OF(GENERAL_NAME) *alt;
535     GENERAL_NAME *gn;
536 
537     debug(DBG_DBG, "subjectaltnameaddr");
538 
539     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
540     if (loc < 0)
541 	return r;
542 
543     ex = X509_get_ext(cert, loc);
544     alt = X509V3_EXT_d2i(ex);
545     if (!alt)
546 	return r;
547 
548     n = sk_GENERAL_NAME_num(alt);
549     for (i = 0; i < n; i++) {
550 	gn = sk_GENERAL_NAME_value(alt, i);
551 	if (gn->type != GEN_IPADD)
552 	    continue;
553 	r = -1;
554 	v = (char *)ASN1_STRING_get0_data(gn->d.ia5);
555 	l = ASN1_STRING_length(gn->d.ia5);
556 	if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
557 	    && !memcmp(v, addr, l)) {
558 	    r = 1;
559 	    break;
560 	}
561     }
562     GENERAL_NAMES_free(alt);
563     return r;
564 }
565 
566 static int subjectaltnameregexp(X509 *cert, int type, char *exact,  regex_t *regex) {
567     int loc, i, l, n, r = 0;
568     char *s, *v, *fail = NULL, *tmp;
569     X509_EXTENSION *ex;
570     STACK_OF(GENERAL_NAME) *alt;
571     GENERAL_NAME *gn;
572 
573     debug(DBG_DBG, "subjectaltnameregexp");
574 
575     loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
576     if (loc < 0)
577 	return r;
578 
579     ex = X509_get_ext(cert, loc);
580     alt = X509V3_EXT_d2i(ex);
581     if (!alt)
582 	return r;
583 
584     n = sk_GENERAL_NAME_num(alt);
585     for (i = 0; i < n; i++) {
586 	gn = sk_GENERAL_NAME_value(alt, i);
587 	if (gn->type != type)
588 	    continue;
589 	r = -1;
590 	v = (char *)ASN1_STRING_get0_data(gn->d.ia5);
591 	l = ASN1_STRING_length(gn->d.ia5);
592 	if (l <= 0)
593 	    continue;
594 #ifdef DEBUG
595 	printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, (uint8_t *) v, l);
596 #endif
597 	if (exact) {
598 	    if (memcmp(v, exact, l))
599 		continue;
600 	} else {
601 	    s = stringcopy((char *)v, l);
602 	    if (!s) {
603 		debug(DBG_ERR, "malloc failed");
604 		continue;
605 	    }
606         debug(DBG_DBG, "subjectaltnameregex: matching %s", s);
607         if (regexec(regex, s, 0, NULL, 0)) {
608             tmp = fail;
609             if (asprintf(&fail, "%s%s%s", tmp ? tmp : "", tmp ? ", " : "", s) >= 0)
610                 free(tmp);
611             else
612                 fail = tmp;
613             free(s);
614             continue;
615 	    }
616 	    free(s);
617 	}
618 	r = 1;
619 	break;
620     }
621     if (r!=1)
622         debug(DBG_WARN, "subjectaltnameregex: no matching Subject Alt Name %s found! (%s)",
623             type == GEN_DNS ? "DNS" : "URI", fail);
624     GENERAL_NAMES_free(alt);
625     free(fail);
626     return r;
627 }
628 
629 static int cnregexp(X509 *cert, char *exact, regex_t *regex) {
630     int loc, l;
631     char *v, *s;
632     X509_NAME *nm;
633     X509_NAME_ENTRY *e;
634     ASN1_STRING *t;
635 
636     nm = X509_get_subject_name(cert);
637     loc = -1;
638     for (;;) {
639 	loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
640 	if (loc == -1)
641 	    break;
642 	e = X509_NAME_get_entry(nm, loc);
643 	t = X509_NAME_ENTRY_get_data(e);
644 	v = (char *) ASN1_STRING_get0_data(t);
645 	l = ASN1_STRING_length(t);
646 	if (l < 0)
647 	    continue;
648 	if (exact) {
649 	    if (l == strlen(exact) && !strncasecmp(exact, v, l))
650 		return 1;
651 	} else {
652 	    s = stringcopy((char *)v, l);
653 	    if (!s) {
654 		debug(DBG_ERR, "malloc failed");
655 		continue;
656 	    }
657 	    if (regexec(regex, s, 0, NULL, 0)) {
658 		free(s);
659 		continue;
660 	    }
661 	    free(s);
662 	    return 1;
663 	}
664     }
665     return 0;
666 }
667 
668 /* this is a bit sloppy, should not always accept match to any */
669 int certnamecheck(X509 *cert, struct list *hostports) {
670     struct list_node *entry;
671     struct hostportres *hp;
672     int r = 0;
673     uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
674     struct in6_addr addr;
675 
676     for (entry = list_first(hostports); entry; entry = list_next(entry)) {
677         hp = (struct hostportres *)entry->data;
678         if (hp->prefixlen != 255) {
679             /* we disable the check for prefixes */
680             return 1;
681         }
682         if (inet_pton(AF_INET, hp->host, &addr))
683             type = AF_INET;
684         else if (inet_pton(AF_INET6, hp->host, &addr))
685             type = AF_INET6;
686         else
687             type = 0;
688 
689         if (type)
690             r = subjectaltnameaddr(cert, type, &addr);
691         if (!r)
692             r = subjectaltnameregexp(cert, GEN_DNS, hp->host, NULL);
693         if (r) {
694             if (r > 0) {
695                 debug(DBG_DBG, "certnamecheck: Found subjectaltname matching %s %s", type ? "address" : "host", hp->host);
696                 return 1;
697             }
698             debug(DBG_WARN, "certnamecheck: No subjectaltname matching %s %s", type ? "address" : "host", hp->host);
699         } else {
700             if (cnregexp(cert, hp->host, NULL)) {
701                 debug(DBG_DBG, "certnamecheck: Found cn matching host %s", hp->host);
702                 return 1;
703             }
704             debug(DBG_WARN, "certnamecheck: cn not matching host %s", hp->host);
705         }
706     }
707     return 0;
708 }
709 
710 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
711     char *subject;
712     char addrbuf[INET6_ADDRSTRLEN];
713     int ok = 1;
714 
715     subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
716     debug(DBG_DBG, "verifyconfcert: verify certificate for host %s, subject %s", conf->name, subject);
717     if (conf->certnamecheck) {
718         debug(DBG_DBG, "verifyconfcert: verify hostname");
719         if (!certnamecheck(cert, conf->hostports)) {
720             debug(DBG_DBG, "verifyconfcert: certificate name check failed for host %s", conf->name);
721             ok = 0;
722         }
723     }
724     if (conf->certcnregex) {
725         debug(DBG_DBG, "verifyconfcert: matching CN regex %s", conf->matchcertattr);
726         if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
727             debug(DBG_WARN, "verifyconfcert: CN not matching regex for host %s (%s)", conf->name, subject);
728             ok = 0;
729         }
730     }
731     if (conf->certuriregex) {
732         debug(DBG_DBG, "verifyconfcert: matching subjectaltname URI regex %s", conf->matchcertattr);
733         if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
734             debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex for host %s (%s)", conf->name, subject);
735             ok = 0;
736         }
737     }
738     if (conf->certdnsregex) {
739         debug(DBG_DBG, "verifyconfcert: matching subjectaltname DNS regex %s", conf->matchcertattr);
740         if (subjectaltnameregexp(cert, GEN_DNS, NULL, conf->certdnsregex) < 1) {
741             debug(DBG_WARN, "verifyconfcert: subjectaltname DNS not matching regex for host %s (%s)", conf->name, subject);
742             ok = 0;
743         }
744     }
745     if (conf->certipmatchaf) {
746         debug(DBG_DBG, "verifyconfcert: matching subjectaltname IP %s", inet_ntop(conf->certipmatchaf, &conf->certipmatch, addrbuf, INET6_ADDRSTRLEN));
747         if (subjectaltnameaddr(cert, conf->certipmatchaf, &conf->certipmatch) < 1) {
748             debug(DBG_WARN, "verifyconfcert: subjectaltname IP not matching regex for host %s (%s)", conf->name, subject);
749             ok = 0;
750         }
751     }
752     free(subject);
753     return ok;
754 }
755 
756 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
757     struct tls *conf;
758     long int expiry = LONG_MIN;
759 
760     debug(DBG_DBG, "conftls_cb called for %s", block);
761 
762     conf = malloc(sizeof(struct tls));
763     if (!conf) {
764 	debug(DBG_ERR, "conftls_cb: malloc failed");
765 	return 0;
766     }
767     memset(conf, 0, sizeof(struct tls));
768 
769     if (!getgenericconfig(cf, block,
770 			  "CACertificateFile", CONF_STR, &conf->cacertfile,
771 			  "CACertificatePath", CONF_STR, &conf->cacertpath,
772 			  "CertificateFile", CONF_STR, &conf->certfile,
773 			  "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
774 			  "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
775 			  "CacheExpiry", CONF_LINT, &expiry,
776 			  "CRLCheck", CONF_BLN, &conf->crlcheck,
777 			  "PolicyOID", CONF_MSTR, &conf->policyoids,
778 			  NULL
779 	    )) {
780 	debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
781 	goto errexit;
782     }
783     if (!conf->certfile || !conf->certkeyfile) {
784 	debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
785 	goto errexit;
786     }
787     if (!conf->cacertfile && !conf->cacertpath) {
788 	debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
789 	goto errexit;
790     }
791     if (expiry != LONG_MIN) {
792 	if (expiry < 0) {
793 	    debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
794 	    goto errexit;
795 	}
796 	conf->cacheexpiry = expiry;
797     }
798 
799     conf->name = stringcopy(val, 0);
800     if (!conf->name) {
801 	debug(DBG_ERR, "conftls_cb: malloc failed");
802 	goto errexit;
803     }
804     pthread_mutex_init(&conf->lock, NULL);
805 
806     if (!tlsconfs)
807 	tlsconfs = hash_create();
808     if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
809 	debug(DBG_ERR, "conftls_cb: malloc failed");
810 	goto errexit;
811     }
812     if (!tlsgetctx(RAD_TLS, conf))
813 	debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
814     debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
815     return 1;
816 
817 errexit:
818     free(conf->cacertfile);
819     free(conf->cacertpath);
820     free(conf->certfile);
821     free(conf->certkeyfile);
822     free(conf->certkeypwd);
823     freegconfmstr(conf->policyoids);
824     free(conf);
825     return 0;
826 }
827 
828 int addmatchcertattr(struct clsrvconf *conf) {
829     char *v;
830     regex_t **r;
831 
832     if (!strncasecmp(conf->matchcertattr, "SubjectAltName:IP:", 18)) {
833         if (inet_pton(AF_INET, conf->matchcertattr+18, &conf->certipmatch))
834             conf->certipmatchaf = AF_INET;
835         else if (inet_pton(AF_INET6, conf->matchcertattr+18, &conf->certipmatch))
836             conf->certipmatchaf = AF_INET6;
837         else
838             return 0;
839         return 1;
840     }
841 
842     /* the other cases below use a common regex match */
843     if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
844         r = &conf->certcnregex;
845         v = conf->matchcertattr + 4;
846     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
847         r = &conf->certuriregex;
848         v = conf->matchcertattr + 20;
849     } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:DNS:/", 20)) {
850         r = &conf->certdnsregex;
851         v = conf->matchcertattr + 20;
852     }
853     else
854         return 0;
855 
856     if (!*v)
857         return 0;
858     /* regexp, remove optional trailing / if present */
859     if (v[strlen(v) - 1] == '/')
860         v[strlen(v) - 1] = '\0';
861     if (!*v)
862         return 0;
863 
864     *r = malloc(sizeof(regex_t));
865     if (!*r) {
866         debug(DBG_ERR, "malloc failed");
867         return 0;
868     }
869     if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
870         free(*r);
871         *r = NULL;
872         debug(DBG_ERR, "failed to compile regular expression %s", v);
873         return 0;
874     }
875     return 1;
876 }
877 
878 int sslaccepttimeout (SSL *ssl, int timeout) {
879     int socket, origflags, ndesc, r = -1, sockerr = 0;
880     socklen_t errlen = sizeof(sockerr);
881     struct pollfd fds[1];
882     uint8_t want_write = 1;
883 
884     socket = SSL_get_fd(ssl);
885     origflags = fcntl(socket, F_GETFL, 0);
886     if (origflags == -1) {
887         debugerrno(errno, DBG_WARN, "Failed to get flags");
888         return -1;
889     }
890     if (fcntl(socket, F_SETFL, origflags | O_NONBLOCK) == -1) {
891         debugerrno(errno, DBG_WARN, "Failed to set O_NONBLOCK");
892         return -1;
893     }
894 
895     while (r < 1) {
896         fds[0].fd = socket;
897         fds[0].events = POLLIN;
898         if (want_write) {
899             fds[0].events |= POLLOUT;
900             want_write = 0;
901         }
902         if ((ndesc = poll(fds, 1, timeout * 1000)) < 1) {
903             if (ndesc == 0)
904                 debug(DBG_DBG, "sslaccepttimeout: timeout during SSL_accept");
905             else
906                 debugerrno(errno, DBG_DBG, "sslaccepttimeout: poll error");
907             break;
908         }
909 
910         if (fds[0].revents & POLLERR) {
911             if(!getsockopt(socket, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &errlen))
912                 debug(DBG_WARN, "SSL Accept failed: %s", strerror(sockerr));
913             else
914                 debug(DBG_WARN, "SSL Accept failed: unknown error");
915         } else if (fds[0].revents & POLLHUP) {
916                 debug(DBG_WARN, "SSL Accept error: hang up");
917         } else if (fds[0].revents & POLLNVAL) {
918                 debug(DBG_WARN, "SSL Accept error: fd not open");
919         } else {
920             r = SSL_accept(ssl);
921             if (r <= 0) {
922                 switch (SSL_get_error(ssl, r)) {
923                     case SSL_ERROR_WANT_WRITE:
924                         want_write = 1;
925                     case SSL_ERROR_WANT_READ:
926                         continue;
927                 }
928             }
929         }
930         break;
931     }
932 
933     if (fcntl(socket, F_SETFL, origflags) == -1)
934         debugerrno(errno, DBG_WARN, "Failed to set original flags back");
935     return r;
936 }
937 
938 int sslconnecttimeout(SSL *ssl, int timeout) {
939     int socket, origflags, ndesc, r = -1, sockerr = 0;
940     socklen_t errlen = sizeof(sockerr);
941     struct pollfd fds[1];
942     uint8_t want_write = 1;
943 
944     socket = SSL_get_fd(ssl);
945     origflags = fcntl(socket, F_GETFL, 0);
946     if (origflags == -1) {
947         debugerrno(errno, DBG_WARN, "Failed to get flags");
948         return -1;
949     }
950     if (fcntl(socket, F_SETFL, origflags | O_NONBLOCK) == -1) {
951         debugerrno(errno, DBG_WARN, "Failed to set O_NONBLOCK");
952         return -1;
953     }
954 
955     while (r < 1) {
956         fds[0].fd = socket;
957         fds[0].events = POLLIN;
958         if (want_write) {
959             fds[0].events |= POLLOUT;
960             want_write = 0;
961         }
962         if ((ndesc = poll(fds, 1, timeout * 1000)) < 1) {
963             if (ndesc == 0)
964                 debug(DBG_DBG, "sslconnecttimeout: timeout during SSL_connect");
965             else
966                 debugerrno(errno, DBG_DBG, "sslconnecttimeout: poll error");
967             break;
968         }
969 
970         if (fds[0].revents & POLLERR) {
971             if(!getsockopt(socket, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &errlen))
972                 debug(DBG_WARN, "SSL Connection failed: %s", strerror(sockerr));
973             else
974                 debug(DBG_WARN, "SSL Connection failed: unknown error");
975         } else if (fds[0].revents & POLLHUP) {
976                 debug(DBG_WARN, "SSL Connect error: hang up");
977         } else if (fds[0].revents & POLLNVAL) {
978                 debug(DBG_WARN, "SSL Connect error: fd not open");
979         } else {
980             r = SSL_connect(ssl);
981             if (r <= 0) {
982                 switch (SSL_get_error(ssl, r)) {
983                     case SSL_ERROR_WANT_WRITE:
984                         want_write = 1;
985                     case SSL_ERROR_WANT_READ:
986                         continue;
987                 }
988             }
989         }
990         break;
991     }
992 
993     if (fcntl(socket, F_SETFL, origflags) == -1)
994         debugerrno(errno, DBG_WARN, "Failed to set original flags back");
995     return r;
996 }
997 
998 #else
999 /* Just to makes file non-empty, should rather avoid compiling this file when not needed */
1000 static void tlsdummy() {
1001 }
1002 #endif
1003 
1004 /* Local Variables: */
1005 /* c-file-style: "stroustrup" */
1006 /* End: */
1007