2 * Copyright (C) 2006-2009 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 #if defined HAVE_CONFIG_H
13 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
15 #include <sys/socket.h>
16 #include <netinet/in.h>
25 #include <sys/types.h>
26 #include <sys/select.h>
29 #include <arpa/inet.h>
33 #include <openssl/ssl.h>
34 #include <openssl/rand.h>
35 #include <openssl/err.h>
36 #include <openssl/md5.h>
37 #include <openssl/x509v3.h>
38 #include "rsp_debug.h"
42 #include "../hostport_types.h"
43 #include "../radsecproxy.h"
45 static struct hash *tlsconfs = NULL;
51 SSL_load_error_strings();
54 while (!RAND_status()) {
57 RAND_seed((unsigned char *)&t, sizeof(time_t));
58 RAND_seed((unsigned char *)&pid, sizeof(pid));
62 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
63 int pwdlen = strlen(userdata);
64 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
66 memcpy(buf, userdata, pwdlen);
70 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
75 err_cert = X509_STORE_CTX_get_current_cert(ctx);
76 err = X509_STORE_CTX_get_error(ctx);
77 depth = X509_STORE_CTX_get_error_depth(ctx);
79 if (depth > MAX_CERT_DEPTH) {
81 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
82 X509_STORE_CTX_set_error(ctx, err);
87 buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
88 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
93 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
95 buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
97 debug(DBG_WARN, "\tIssuer=%s", buf);
103 case X509_V_ERR_CERT_NOT_YET_VALID:
104 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
105 debug(DBG_WARN, "\tCertificate not yet valid");
107 case X509_V_ERR_CERT_HAS_EXPIRED:
108 debug(DBG_WARN, "Certificate has expired");
110 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
111 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
113 case X509_V_ERR_NO_EXPLICIT_POLICY:
114 debug(DBG_WARN, "No Explicit Certificate Policy");
119 printf("certificate verify returns %d\n", ok);
125 static void ssl_info_callback(const SSL *ssl, int where, int ret) {
129 w = where & ~SSL_ST_MASK;
131 if (w & SSL_ST_CONNECT)
133 else if (w & SSL_ST_ACCEPT)
138 if (where & SSL_CB_LOOP)
139 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
140 else if (where & SSL_CB_ALERT) {
141 s = (where & SSL_CB_READ) ? "read" : "write";
142 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
144 else if (where & SSL_CB_EXIT) {
146 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
148 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
153 static X509_VERIFY_PARAM *createverifyparams(char **poids) {
154 X509_VERIFY_PARAM *pm;
155 ASN1_OBJECT *pobject;
158 pm = X509_VERIFY_PARAM_new();
162 for (i = 0; poids[i]; i++) {
163 pobject = OBJ_txt2obj(poids[i], 0);
165 X509_VERIFY_PARAM_free(pm);
168 X509_VERIFY_PARAM_add0_policy(pm, pobject);
171 X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
175 static int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
176 STACK_OF(X509_NAME) *calist;
180 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
181 while ((error = ERR_get_error()))
182 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
183 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
187 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
189 if (!conf->cacertfile || calist) {
190 if (conf->cacertpath) {
192 calist = sk_X509_NAME_new_null();
193 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
194 sk_X509_NAME_free(calist);
200 while ((error = ERR_get_error()))
201 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
202 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
205 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
206 SSL_CTX_set_client_CA_list(ctx, calist);
208 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
209 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
211 if (conf->crlcheck || conf->vpm) {
212 x509_s = SSL_CTX_get_cert_store(ctx);
214 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
216 X509_STORE_set1_param(x509_s, conf->vpm);
219 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
223 static SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
230 ctx = SSL_CTX_new(TLSv1_method());
235 ctx = SSL_CTX_new(DTLSv1_method());
236 SSL_CTX_set_read_ahead(ctx, 1);
241 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
242 while ((error = ERR_get_error()))
243 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
247 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
250 if (conf->certkeypwd) {
251 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
252 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
254 if (conf->certfile || conf->certkeyfile) {
255 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
256 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
257 !SSL_CTX_check_private_key(ctx)) {
258 while ((error = ERR_get_error()))
259 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
260 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS (certfile issues) in TLS context %s", conf->name);
266 if (conf->policyoids) {
268 conf->vpm = createverifyparams(conf->policyoids);
270 debug(DBG_ERR, "tlscreatectx: Failed to add policyOIDs in TLS context %s", conf->name);
277 if (!tlsaddcacrl(ctx, conf)) {
279 X509_VERIFY_PARAM_free(conf->vpm);
286 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
290 struct tls *tlsgettls(char *alt1, char *alt2) {
293 t = hash_read(tlsconfs, alt1, strlen(alt1));
295 t = hash_read(tlsconfs, alt2, strlen(alt2));
299 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
304 gettimeofday(&now, NULL);
309 if (t->tlsexpiry && t->tlsctx) {
310 if (t->tlsexpiry < now.tv_sec) {
311 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
312 tlsaddcacrl(t->tlsctx, t);
316 t->tlsctx = tlscreatectx(RAD_TLS, t);
318 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
324 if (t->dtlsexpiry && t->dtlsctx) {
325 if (t->dtlsexpiry < now.tv_sec) {
326 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
327 tlsaddcacrl(t->dtlsctx, t);
331 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
333 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
341 X509 *verifytlscert(SSL *ssl) {
345 if (SSL_get_verify_result(ssl) != X509_V_OK) {
346 debug(DBG_ERR, "verifytlscert: basic validation failed");
347 while ((error = ERR_get_error()))
348 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
352 cert = SSL_get_peer_certificate(ssl);
354 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
358 static int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
359 int loc, i, l, n, r = 0;
362 STACK_OF(GENERAL_NAME) *alt;
365 debug(DBG_DBG, "subjectaltnameaddr");
367 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
371 ex = X509_get_ext(cert, loc);
372 alt = X509V3_EXT_d2i(ex);
376 n = sk_GENERAL_NAME_num(alt);
377 for (i = 0; i < n; i++) {
378 gn = sk_GENERAL_NAME_value(alt, i);
379 if (gn->type != GEN_IPADD)
382 v = (char *)ASN1_STRING_data(gn->d.ia5);
383 l = ASN1_STRING_length(gn->d.ia5);
384 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
385 && !memcmp(v, &addr, l)) {
390 GENERAL_NAMES_free(alt);
394 static int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
395 int loc, i, l, n, r = 0;
398 STACK_OF(GENERAL_NAME) *alt;
401 debug(DBG_DBG, "subjectaltnameregexp");
403 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
407 ex = X509_get_ext(cert, loc);
408 alt = X509V3_EXT_d2i(ex);
412 n = sk_GENERAL_NAME_num(alt);
413 for (i = 0; i < n; i++) {
414 gn = sk_GENERAL_NAME_value(alt, i);
415 if (gn->type != type)
418 v = (char *)ASN1_STRING_data(gn->d.ia5);
419 l = ASN1_STRING_length(gn->d.ia5);
423 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
426 if (memcmp(v, exact, l))
429 s = stringcopy((char *)v, l);
431 debug(DBG_ERR, "malloc failed");
434 if (regexec(regex, s, 0, NULL, 0)) {
443 GENERAL_NAMES_free(alt);
447 static int cnregexp(X509 *cert, char *exact, regex_t *regex) {
454 nm = X509_get_subject_name(cert);
457 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
460 e = X509_NAME_get_entry(nm, loc);
461 t = X509_NAME_ENTRY_get_data(e);
462 v = (char *) ASN1_STRING_data(t);
463 l = ASN1_STRING_length(t);
467 if (l == strlen(exact) && !strncasecmp(exact, v, l))
470 s = stringcopy((char *)v, l);
472 debug(DBG_ERR, "malloc failed");
475 if (regexec(regex, s, 0, NULL, 0)) {
486 /* this is a bit sloppy, should not always accept match to any */
487 int certnamecheck(X509 *cert, struct list *hostports) {
488 struct list_node *entry;
489 struct hostportres *hp;
491 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
492 struct in6_addr addr;
494 for (entry = list_first(hostports); entry; entry = list_next(entry)) {
495 hp = (struct hostportres *)entry->data;
496 if (hp->prefixlen != 255) {
497 /* we disable the check for prefixes */
500 if (inet_pton(AF_INET, hp->host, &addr))
502 else if (inet_pton(AF_INET6, hp->host, &addr))
507 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, hp->host, NULL);
510 debug(DBG_DBG, "certnamecheck: Found subjectaltname matching %s %s", type ? "address" : "host", hp->host);
513 debug(DBG_WARN, "certnamecheck: No subjectaltname matching %s %s", type ? "address" : "host", hp->host);
515 if (cnregexp(cert, hp->host, NULL)) {
516 debug(DBG_DBG, "certnamecheck: Found cn matching host %s", hp->host);
519 debug(DBG_WARN, "certnamecheck: cn not matching host %s", hp->host);
525 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
526 if (conf->certnamecheck) {
527 if (!certnamecheck(cert, conf->hostports)) {
528 debug(DBG_WARN, "verifyconfcert: certificate name check failed");
531 debug(DBG_WARN, "verifyconfcert: certificate name check ok");
533 if (conf->certcnregex) {
534 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
535 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
538 debug(DBG_DBG, "verifyconfcert: CN matching regex");
540 if (conf->certuriregex) {
541 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
542 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
545 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
551 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
553 long int expiry = LONG_MIN;
555 debug(DBG_DBG, "conftls_cb called for %s", block);
557 conf = malloc(sizeof(struct tls));
559 debug(DBG_ERR, "conftls_cb: malloc failed");
562 memset(conf, 0, sizeof(struct tls));
564 if (!getgenericconfig(cf, block,
565 "CACertificateFile", CONF_STR, &conf->cacertfile,
566 "CACertificatePath", CONF_STR, &conf->cacertpath,
567 "CertificateFile", CONF_STR, &conf->certfile,
568 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
569 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
570 "CacheExpiry", CONF_LINT, &expiry,
571 "CRLCheck", CONF_BLN, &conf->crlcheck,
572 "PolicyOID", CONF_MSTR, &conf->policyoids,
575 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
578 if (!conf->certfile || !conf->certkeyfile) {
579 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
582 if (!conf->cacertfile && !conf->cacertpath) {
583 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
586 if (expiry != LONG_MIN) {
588 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
591 conf->cacheexpiry = expiry;
594 conf->name = stringcopy(val, 0);
596 debug(DBG_ERR, "conftls_cb: malloc failed");
601 tlsconfs = hash_create();
602 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
603 debug(DBG_ERR, "conftls_cb: malloc failed");
606 if (!tlsgetctx(RAD_TLS, conf))
607 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
608 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
612 free(conf->cacertfile);
613 free(conf->cacertpath);
614 free(conf->certfile);
615 free(conf->certkeyfile);
616 free(conf->certkeypwd);
617 freegconfmstr(conf->policyoids);
623 int addmatchcertattr(struct clsrvconf *conf) {
627 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
628 r = &conf->certcnregex;
629 v = conf->matchcertattr + 4;
630 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
631 r = &conf->certuriregex;
632 v = conf->matchcertattr + 20;
637 /* regexp, remove optional trailing / if present */
638 if (v[strlen(v) - 1] == '/')
639 v[strlen(v) - 1] = '\0';
643 *r = malloc(sizeof(regex_t));
645 debug(DBG_ERR, "malloc failed");
648 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
651 debug(DBG_ERR, "failed to compile regular expression %s", v);
657 /* Just to makes file non-empty, should rather avoid compiling this file when not needed */
658 static void tlsdummy() {
662 /* Local Variables: */
663 /* c-file-style: "stroustrup" */