1 /* Copyright (c) 2007-2009, UNINETT AS
2 * Copyright (c) 2010-2011, NORDUnet A/S */
3 /* See LICENSE for licensing information. */
5 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
7 #include <sys/socket.h>
8 #include <netinet/in.h>
17 #include <sys/types.h>
18 #include <sys/select.h>
21 #include <arpa/inet.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>
34 #include "radsecproxy.h"
36 static struct hash *tlsconfs = NULL;
38 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
39 int pwdlen = strlen(userdata);
40 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
42 memcpy(buf, userdata, pwdlen);
46 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
51 err_cert = X509_STORE_CTX_get_current_cert(ctx);
52 err = X509_STORE_CTX_get_error(ctx);
53 depth = X509_STORE_CTX_get_error_depth(ctx);
55 if (depth > MAX_CERT_DEPTH) {
57 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
58 X509_STORE_CTX_set_error(ctx, err);
63 buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
64 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
69 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
71 buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
73 debug(DBG_WARN, "\tIssuer=%s", buf);
79 case X509_V_ERR_CERT_NOT_YET_VALID:
80 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
81 debug(DBG_WARN, "\tCertificate not yet valid");
83 case X509_V_ERR_CERT_HAS_EXPIRED:
84 debug(DBG_WARN, "Certificate has expired");
86 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
87 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
89 case X509_V_ERR_NO_EXPLICIT_POLICY:
90 debug(DBG_WARN, "No Explicit Certificate Policy");
95 printf("certificate verify returns %d\n", ok);
101 static void ssl_info_callback(const SSL *ssl, int where, int ret) {
105 w = where & ~SSL_ST_MASK;
107 if (w & SSL_ST_CONNECT)
109 else if (w & SSL_ST_ACCEPT)
114 if (where & SSL_CB_LOOP)
115 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
116 else if (where & SSL_CB_ALERT) {
117 s = (where & SSL_CB_READ) ? "read" : "write";
118 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
120 else if (where & SSL_CB_EXIT) {
122 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
124 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
129 static X509_VERIFY_PARAM *createverifyparams(char **poids) {
130 X509_VERIFY_PARAM *pm;
131 ASN1_OBJECT *pobject;
134 pm = X509_VERIFY_PARAM_new();
138 for (i = 0; poids[i]; i++) {
139 pobject = OBJ_txt2obj(poids[i], 0);
141 X509_VERIFY_PARAM_free(pm);
144 X509_VERIFY_PARAM_add0_policy(pm, pobject);
147 X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
151 static int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
152 STACK_OF(X509_NAME) *calist;
156 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
157 while ((error = ERR_get_error()))
158 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
159 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
163 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
164 if (!conf->cacertfile || calist) {
165 if (conf->cacertpath) {
167 calist = sk_X509_NAME_new_null();
168 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
169 sk_X509_NAME_free(calist);
175 while ((error = ERR_get_error()))
176 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
177 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
180 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
181 SSL_CTX_set_client_CA_list(ctx, calist);
183 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
184 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
186 if (conf->crlcheck || conf->vpm) {
187 x509_s = SSL_CTX_get_cert_store(ctx);
189 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
191 X509_STORE_set1_param(x509_s, conf->vpm);
194 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
198 static SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
201 long sslversion = SSLeay();
206 ctx = SSL_CTX_new(TLSv1_method());
208 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
214 ctx = SSL_CTX_new(DTLSv1_method());
216 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
218 SSL_CTX_set_read_ahead(ctx, 1);
223 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
227 if (sslversion < 0x00908100L ||
228 (sslversion >= 0x10000000L && sslversion < 0x10000020L)) {
229 debug(DBG_WARN, "%s: %s seems to be of a version with a "
230 "certain security critical bug (fixed in OpenSSL 0.9.8p and "
231 "1.0.0b). Disabling OpenSSL session caching for context %p.",
232 __func__, SSLeay_version(SSLEAY_VERSION), ctx);
233 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
236 if (conf->certkeypwd) {
237 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
238 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
240 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
241 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
242 !SSL_CTX_check_private_key(ctx)) {
243 while ((error = ERR_get_error()))
244 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
245 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
250 if (conf->policyoids) {
252 conf->vpm = createverifyparams(conf->policyoids);
254 debug(DBG_ERR, "tlscreatectx: Failed to add policyOIDs in TLS context %s", conf->name);
261 if (!tlsaddcacrl(ctx, conf)) {
263 X509_VERIFY_PARAM_free(conf->vpm);
270 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
274 struct tls *tlsgettls(char *alt1, char *alt2) {
277 t = hash_read(tlsconfs, alt1, strlen(alt1));
279 t = hash_read(tlsconfs, alt2, strlen(alt2));
283 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
288 gettimeofday(&now, NULL);
293 if (t->tlsexpiry && t->tlsctx) {
294 if (t->tlsexpiry < now.tv_sec) {
295 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
296 tlsaddcacrl(t->tlsctx, t);
300 t->tlsctx = tlscreatectx(RAD_TLS, t);
302 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
308 if (t->dtlsexpiry && t->dtlsctx) {
309 if (t->dtlsexpiry < now.tv_sec) {
310 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
311 tlsaddcacrl(t->dtlsctx, t);
315 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
317 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
325 X509 *verifytlscert(SSL *ssl) {
329 if (SSL_get_verify_result(ssl) != X509_V_OK) {
330 debug(DBG_ERR, "verifytlscert: basic validation failed");
331 while ((error = ERR_get_error()))
332 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
336 cert = SSL_get_peer_certificate(ssl);
338 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
342 static int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
343 int loc, i, l, n, r = 0;
346 STACK_OF(GENERAL_NAME) *alt;
349 debug(DBG_DBG, "subjectaltnameaddr");
351 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
355 ex = X509_get_ext(cert, loc);
356 alt = X509V3_EXT_d2i(ex);
360 n = sk_GENERAL_NAME_num(alt);
361 for (i = 0; i < n; i++) {
362 gn = sk_GENERAL_NAME_value(alt, i);
363 if (gn->type != GEN_IPADD)
366 v = (char *)ASN1_STRING_data(gn->d.ia5);
367 l = ASN1_STRING_length(gn->d.ia5);
368 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
369 && !memcmp(v, &addr, l)) {
374 GENERAL_NAMES_free(alt);
378 static int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
379 int loc, i, l, n, r = 0;
382 STACK_OF(GENERAL_NAME) *alt;
385 debug(DBG_DBG, "subjectaltnameregexp");
387 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
391 ex = X509_get_ext(cert, loc);
392 alt = X509V3_EXT_d2i(ex);
396 n = sk_GENERAL_NAME_num(alt);
397 for (i = 0; i < n; i++) {
398 gn = sk_GENERAL_NAME_value(alt, i);
399 if (gn->type != type)
402 v = (char *)ASN1_STRING_data(gn->d.ia5);
403 l = ASN1_STRING_length(gn->d.ia5);
407 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
410 if (memcmp(v, exact, l))
413 s = stringcopy((char *)v, l);
415 debug(DBG_ERR, "malloc failed");
418 if (regexec(regex, s, 0, NULL, 0)) {
427 GENERAL_NAMES_free(alt);
431 static int cnregexp(X509 *cert, char *exact, regex_t *regex) {
438 nm = X509_get_subject_name(cert);
441 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
444 e = X509_NAME_get_entry(nm, loc);
445 t = X509_NAME_ENTRY_get_data(e);
446 v = (char *) ASN1_STRING_data(t);
447 l = ASN1_STRING_length(t);
451 if (l == strlen(exact) && !strncasecmp(exact, v, l))
454 s = stringcopy((char *)v, l);
456 debug(DBG_ERR, "malloc failed");
459 if (regexec(regex, s, 0, NULL, 0)) {
470 /* this is a bit sloppy, should not always accept match to any */
471 int certnamecheck(X509 *cert, struct list *hostports) {
472 struct list_node *entry;
473 struct hostportres *hp;
475 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
476 struct in6_addr addr;
478 for (entry = list_first(hostports); entry; entry = list_next(entry)) {
479 hp = (struct hostportres *)entry->data;
480 if (hp->prefixlen != 255) {
481 /* we disable the check for prefixes */
484 if (inet_pton(AF_INET, hp->host, &addr))
486 else if (inet_pton(AF_INET6, hp->host, &addr))
491 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, hp->host, NULL);
494 debug(DBG_DBG, "certnamecheck: Found subjectaltname matching %s %s", type ? "address" : "host", hp->host);
497 debug(DBG_WARN, "certnamecheck: No subjectaltname matching %s %s", type ? "address" : "host", hp->host);
499 if (cnregexp(cert, hp->host, NULL)) {
500 debug(DBG_DBG, "certnamecheck: Found cn matching host %s", hp->host);
503 debug(DBG_WARN, "certnamecheck: cn not matching host %s", hp->host);
509 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
510 if (conf->certnamecheck) {
511 if (!certnamecheck(cert, conf->hostports)) {
512 debug(DBG_WARN, "verifyconfcert: certificate name check failed");
515 debug(DBG_WARN, "verifyconfcert: certificate name check ok");
517 if (conf->certcnregex) {
518 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
519 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
522 debug(DBG_DBG, "verifyconfcert: CN matching regex");
524 if (conf->certuriregex) {
525 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
526 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
529 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
534 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
536 long int expiry = LONG_MIN;
538 debug(DBG_DBG, "conftls_cb called for %s", block);
540 conf = malloc(sizeof(struct tls));
542 debug(DBG_ERR, "conftls_cb: malloc failed");
545 memset(conf, 0, sizeof(struct tls));
547 if (!getgenericconfig(cf, block,
548 "CACertificateFile", CONF_STR, &conf->cacertfile,
549 "CACertificatePath", CONF_STR, &conf->cacertpath,
550 "CertificateFile", CONF_STR, &conf->certfile,
551 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
552 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
553 "CacheExpiry", CONF_LINT, &expiry,
554 "CRLCheck", CONF_BLN, &conf->crlcheck,
555 "PolicyOID", CONF_MSTR, &conf->policyoids,
558 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
561 if (!conf->certfile || !conf->certkeyfile) {
562 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
565 if (!conf->cacertfile && !conf->cacertpath) {
566 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
569 if (expiry != LONG_MIN) {
571 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
574 conf->cacheexpiry = expiry;
577 conf->name = stringcopy(val, 0);
579 debug(DBG_ERR, "conftls_cb: malloc failed");
584 tlsconfs = hash_create();
585 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
586 debug(DBG_ERR, "conftls_cb: malloc failed");
589 if (!tlsgetctx(RAD_TLS, conf))
590 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
591 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
595 free(conf->cacertfile);
596 free(conf->cacertpath);
597 free(conf->certfile);
598 free(conf->certkeyfile);
599 free(conf->certkeypwd);
600 freegconfmstr(conf->policyoids);
605 int addmatchcertattr(struct clsrvconf *conf) {
609 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
610 r = &conf->certcnregex;
611 v = conf->matchcertattr + 4;
612 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
613 r = &conf->certuriregex;
614 v = conf->matchcertattr + 20;
619 /* regexp, remove optional trailing / if present */
620 if (v[strlen(v) - 1] == '/')
621 v[strlen(v) - 1] = '\0';
625 *r = malloc(sizeof(regex_t));
627 debug(DBG_ERR, "malloc failed");
630 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
633 debug(DBG_ERR, "failed to compile regular expression %s", v);
639 /* Just to makes file non-empty, should rather avoid compiling this file when not needed */
640 static void tlsdummy() {
644 /* Local Variables: */
645 /* c-file-style: "stroustrup" */