Added missing check for lookup
[freeradius.git] / src / modules / rlm_eap / types / rlm_eap_tls / rlm_eap_tls.c
index 7bf69fd..e041c4c 100644 (file)
@@ -32,7 +32,12 @@ RCSID("$Id$")
 #include <openssl/rand.h>
 #endif
 
+#ifdef HAVE_OPENSSL_EVP_H
+#include <openssl/evp.h>
+#endif
+
 #include "rlm_eap_tls.h"
+#include "config.h"
 
 #ifdef HAVE_SYS_STAT_H
 #include <sys/stat.h>
@@ -50,6 +55,14 @@ static CONF_PARSER cache_config[] = {
        { NULL, -1, 0, NULL, NULL }           /* end the list */
 };
 
+static CONF_PARSER verify_config[] = {
+       { "tmpdir", PW_TYPE_STRING_PTR,
+         offsetof(EAP_TLS_CONF, verify_tmp_dir), NULL, NULL},
+       { "client", PW_TYPE_STRING_PTR,
+         offsetof(EAP_TLS_CONF, verify_client_cert_cmd), NULL, NULL},
+       { NULL, -1, 0, NULL, NULL }           /* end the list */
+};
+
 static CONF_PARSER module_config[] = {
        { "rsa_key_exchange", PW_TYPE_BOOLEAN,
          offsetof(EAP_TLS_CONF, rsa_key), NULL, "no" },
@@ -94,6 +107,8 @@ static CONF_PARSER module_config[] = {
 
        { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
 
+       { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
+
        { NULL, -1, 0, NULL, NULL }           /* end the list */
 };
 
@@ -159,7 +174,7 @@ static int generate_eph_rsa_key(SSL_CTX *ctx)
  */
 #define MAX_SESSION_SIZE (256)
 
-static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
+static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
 {
        size_t size;
        char buffer[2 * MAX_SESSION_SIZE + 1];
@@ -175,7 +190,7 @@ static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
         return;
 }
 
-static int cbtls_new_session(SSL *s, SSL_SESSION *sess)
+static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
 {
        size_t size;
        char buffer[2 * MAX_SESSION_SIZE + 1];
@@ -190,8 +205,9 @@ static int cbtls_new_session(SSL *s, SSL_SESSION *sess)
        return 1;
 }
 
-static SSL_SESSION *cbtls_get_session(SSL *s, unsigned char *data, int len,
-                                     int *copy)
+static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
+                                     unsigned char *data, int len,
+                                     UNUSED int *copy)
 {
        size_t size;
        char buffer[2 * MAX_SESSION_SIZE + 1];
@@ -208,6 +224,23 @@ static SSL_SESSION *cbtls_get_session(SSL *s, unsigned char *data, int len,
 }
 
 /*
+ *     For creating certificate attributes.
+ */
+static const char *cert_attr_names[5][2] = {
+  { "TLS-Client-Cert-Serial",          "TLS-Cert-Serial" },
+  { "TLS-Client-Cert-Expiration",      "TLS-Cert-Expiration" },
+  { "TLS-Client-Cert-Subject",         "TLS-Cert-Subject" },
+  { "TLS-Client-Cert-Issuer",          "TLS-Cert-Issuer" },
+  { "TLS-Client-Cert-Common-Name",     "TLS-Cert-Common-Name" }
+};
+
+#define EAPTLS_SERIAL          (0)
+#define EAPTLS_EXPIRATION      (1)
+#define EAPTLS_SUBJECT         (2)
+#define EAPTLS_ISSUER          (3)
+#define EAPTLS_CN              (4)
+
+/*
  *     Before trusting a certificate, you must make sure that the
  *     certificate is 'valid'. There are several steps that your
  *     application can take in determining if a certificate is
@@ -238,23 +271,28 @@ static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
        char issuer[1024]; /* Used for the issuer name */
        char common_name[1024];
        char cn_str[1024];
+       char buf[64];
        EAP_HANDLER *handler = NULL;
        X509 *client_cert;
        SSL *ssl;
-       int err, depth;
+       int err, depth, lookup;
        EAP_TLS_CONF *conf;
        int my_ok = ok;
        REQUEST *request;
+       ASN1_INTEGER *sn = NULL;
+       ASN1_TIME *asn_time = NULL;
 
        client_cert = X509_STORE_CTX_get_current_cert(ctx);
        err = X509_STORE_CTX_get_error(ctx);
        depth = X509_STORE_CTX_get_error_depth(ctx);
 
-       if (!my_ok) {
-               radlog(L_ERR,"--> verify error:num=%d:%s\n",err,
-                       X509_verify_cert_error_string(err));
-               return my_ok;
-       }
+       lookup = depth;
+
+       /*
+        *      Log client/issuing cert.  If there's an error, log
+        *      issuing cert.
+        */
+       if ((lookup > 1) && !my_ok) lookup = 1;
 
        /*
         * Retrieve the pointer to the SSL of the connection currently treated
@@ -266,16 +304,59 @@ static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
        conf = (EAP_TLS_CONF *)SSL_get_ex_data(ssl, 1);
 
        /*
+        *      Get the Serial Number
+        */
+       buf[0] = '\0';
+       sn = X509_get_serialNumber(client_cert);
+
+       /*
+        *      For this next bit, we create the attributes *only* if
+        *      we're at the client or issuing certificate.
+        */
+       if ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {
+               char *p = buf;
+               int i;
+
+               for (i = 0; i < sn->length; i++) {
+                       sprintf(p, "%02x", (unsigned int)sn->data[i]);
+                       p += 2;
+               }
+               pairadd(&handler->certs,
+                       pairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));
+       }
+
+
+       /*
+        *      Get the Expiration Date
+        */
+       buf[0] = '\0';
+       asn_time = X509_get_notAfter(client_cert);
+       if ((lookup <= 1) && asn_time && (asn_time->length < MAX_STRING_LEN)) {
+               memcpy(buf, (char*) asn_time->data, asn_time->length);
+               buf[asn_time->length] = '\0';
+               pairadd(&handler->certs,
+                       pairmake(cert_attr_names[EAPTLS_EXPIRATION][lookup], buf, T_OP_SET));
+       }
+
+       /*
         *      Get the Subject & Issuer
         */
        subject[0] = issuer[0] = '\0';
        X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
                          sizeof(subject));
+       subject[sizeof(subject) - 1] = '\0';
+       if ((lookup <= 1) && subject[0] && (strlen(subject) < MAX_STRING_LEN)) {
+               pairadd(&handler->certs,
+                       pairmake(cert_attr_names[EAPTLS_SUBJECT][lookup], subject, T_OP_SET));
+       }
+
        X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
                          sizeof(issuer));
-
-       subject[sizeof(subject) - 1] = '\0';
        issuer[sizeof(issuer) - 1] = '\0';
+       if ((lookup <= 1) && issuer[0] && (strlen(issuer) < MAX_STRING_LEN)) {
+               pairadd(&handler->certs,
+                       pairmake(cert_attr_names[EAPTLS_ISSUER][lookup], issuer, T_OP_SET));
+       }
 
        /*
         *      Get the Common Name
@@ -283,6 +364,18 @@ static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
        X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
                                  NID_commonName, common_name, sizeof(common_name));
        common_name[sizeof(common_name) - 1] = '\0';
+       if ((lookup <= 1) && common_name[0] && (strlen(common_name) < MAX_STRING_LEN)) {
+               pairadd(&handler->certs,
+                       pairmake(cert_attr_names[EAPTLS_CN][lookup], common_name, T_OP_SET));
+       }
+
+       if (!my_ok) {
+               const char *p = X509_verify_cert_error_string(err);
+               radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
+               radius_pairmake(request, &request->packet->vps,
+                               "Module-Failure-Message", p, T_OP_SET);
+               return my_ok;
+       }
 
        switch (ctx->error) {
 
@@ -340,6 +433,59 @@ static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
                                }
                        }
                } /* check_cert_cn */
+
+               while (conf->verify_client_cert_cmd) {
+                       char filename[256];
+                       FILE *fp;
+
+                       snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
+                                conf->verify_tmp_dir, progname);
+                       if (mkstemp(filename) < 0) {
+                               RDEBUG("Failed creating file in %s: %s",
+                                      conf->verify_tmp_dir, strerror(errno));
+                               break;                                 
+                       }
+
+                       fp = fopen(filename, "w");
+                       if (!fp) {
+                               RDEBUG("Failed opening file %s: %s",
+                                      filename, strerror(errno));
+                               break;
+                       }
+
+                       if (!PEM_write_X509(fp, client_cert)) {
+                               fclose(fp);
+                               RDEBUG("Failed writing certificate to file");
+                               goto do_unlink;
+                       }
+                       fclose(fp);
+
+                       if (!radius_pairmake(request, &request->packet->vps,
+                                            "TLS-Client-Cert-Filename",
+                                            filename, T_OP_SET)) {
+                               RDEBUG("Failed creating TLS-Client-Cert-Filename");
+                               
+                               goto do_unlink;
+                       }
+
+                       RDEBUG("Verifying client certificate: %s",
+                              conf->verify_client_cert_cmd);
+                       if (radius_exec_program(conf->verify_client_cert_cmd,
+                                               request, 1, NULL, 0, 
+                                               request->packet->vps,
+                                               NULL, 1) != 0) {
+                               radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
+                               my_ok = 0;
+                       } else {
+                               RDEBUG("Client certificate CN %s passed external validation", common_name);
+                       }
+
+               do_unlink:
+                       unlink(filename);
+                       break;
+               }
+
+
        } /* depth == 0 */
 
        if (debug_flag > 0) {
@@ -357,6 +503,20 @@ static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
 
 
 /*
+ *     Free cached session data, which is always a list of VALUE_PAIRs
+ */
+static void eaptls_session_free(UNUSED void *parent, void *data_ptr,
+                               UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
+                               UNUSED long argl, UNUSED void *argp)
+{
+       VALUE_PAIR *vp = data_ptr;
+       if (!data_ptr) return;
+
+       pairfree(&vp);
+}
+
+
+/*
  *     Create Global context SSL and use it in every new session
  *
  *     - Load the trusted CAs
@@ -379,6 +539,15 @@ static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
        SSL_library_init();
        SSL_load_error_strings();
 
+       /*
+        *      SHA256 is in all versions of OpenSSL, but isn't
+        *      initialized by default.  It's needed for WiMAX
+        *      certificates.
+        */
+#ifdef HAVE_OPENSSL_EVP_SHA256
+       EVP_add_digest(EVP_sha256());
+#endif
+
        meth = TLSv1_method();
        ctx = SSL_CTX_new(meth);
 
@@ -395,6 +564,49 @@ static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
         * Set the password to load private key
         */
        if (conf->private_key_password) {
+#ifdef __APPLE__
+               /*
+                * We don't want to put the private key password in eap.conf, so  check
+                * for our special string which indicates we should get the password
+                * programmatically. 
+                */
+               const char* special_string = "Apple:UseCertAdmin";
+               if (strncmp(conf->private_key_password,
+                                       special_string,
+                                       strlen(special_string)) == 0)
+               {
+                       char cmd[256];
+                       const long max_password_len = 128;
+                       snprintf(cmd, sizeof(cmd) - 1,
+                                        "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
+                                        conf->private_key_file);
+
+                       DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
+
+                       FILE* cmd_pipe = popen(cmd, "r");
+                       if (!cmd_pipe) {
+                               radlog(L_ERR, "rlm_eap: %s command failed.      Unable to get private_key_password", cmd);
+                               radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
+                               return NULL;
+                       }
+
+                       free(conf->private_key_password);
+                       conf->private_key_password = malloc(max_password_len * sizeof(char));
+                       if (!conf->private_key_password) {
+                               radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
+                               radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
+                               pclose(cmd_pipe);
+                               return NULL;
+                       }
+
+                       fgets(conf->private_key_password, max_password_len, cmd_pipe);
+                       pclose(cmd_pipe);
+
+                       /* Get rid of newline at end of password. */
+                       conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
+                       DEBUG2("rlm_eap:  Password from command = \"%s\"", conf->private_key_password);
+               }
+#endif
                SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
                SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
        }
@@ -422,10 +634,12 @@ static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
        }
 
        /* Load the CAs we trust */
-       if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
-               radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
-               radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
-               return NULL;
+       if (conf->ca_file || conf->ca_path) {
+               if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
+                       radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
+                       radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
+                       return NULL;
+               }
        }
        if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
        if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
@@ -447,6 +661,9 @@ static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
         */
        ctx_options |= SSL_OP_NO_SSLv2;
        ctx_options |= SSL_OP_NO_SSLv3;
+#ifdef SSL_OP_NO_TICKET
+       ctx_options |= SSL_OP_NO_TICKET ;
+#endif
 
        /*
         *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
@@ -584,6 +801,28 @@ static SSL_CTX *init_tls_ctx(EAP_TLS_CONF *conf)
                SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
        }
 
+       /*
+        *      Register the application indices.  We can't use
+        *      hard-coded "0" and "1" as before, because we need to
+        *      set up a "free" handler for the cached session
+        *      information.
+        */
+       if (eaptls_handle_idx < 0) {
+               eaptls_handle_idx = SSL_get_ex_new_index(0, "eaptls_handle_idx",
+                                                         NULL, NULL, NULL);
+       }
+       
+       if (eaptls_conf_idx < 0) {
+               eaptls_conf_idx = SSL_get_ex_new_index(0, "eaptls_conf_idx",
+                                                         NULL, NULL, NULL);
+       }
+
+       if (eaptls_session_idx < 0) {
+               eaptls_session_idx = SSL_get_ex_new_index(0, "eaptls_session_idx",
+                                                         NULL, NULL,
+                                                         eaptls_session_free);
+       }
+
        return ctx;
 }
 
@@ -712,9 +951,26 @@ static int eaptls_attach(CONF_SECTION *cs, void **instance)
        }
 
         if (generate_eph_rsa_key(inst->ctx) < 0) {
+               eaptls_detach(inst);
                 return -1;
         }
 
+       if (conf->verify_tmp_dir) {
+               char filename[256];
+
+               if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
+                       radlog(L_ERR, "rlm_eap_tls: Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
+                       eaptls_detach(inst);
+                       return -1;
+               }
+       }
+
+       if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
+               radlog(L_ERR, "rlm_eap_tls: You MUST set the verify directory in order to use verify_client_cmd");
+               eaptls_detach(inst);
+               return -1;
+       }
+
        *instance = inst;
 
        return 0;
@@ -752,6 +1008,9 @@ static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
 
        inst = (eap_tls_t *)type_arg;
 
+       handler->tls = TRUE;
+       handler->finished = FALSE;
+
        /*
         *      Manually flush the sessions every so often.  If HALF
         *      of the session lifetime has passed since we last
@@ -776,7 +1035,7 @@ static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
         */
        if (handler->eap_type != PW_EAP_TLS) {
                vp = pairfind(handler->request->config_items,
-                             PW_EAP_TLS_REQUIRE_CLIENT_CERT);
+                             PW_EAP_TLS_REQUIRE_CLIENT_CERT, 0);
                if (!vp) {
                        client_cert = FALSE;
                } else {
@@ -833,7 +1092,7 @@ static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
         *      just too much.
         */
        ssn->offset = inst->conf->fragment_size;
-       vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU);
+       vp = pairfind(handler->request->packet->vps, PW_FRAMED_MTU, 0);
        if (vp && ((vp->vp_integer - 14) < ssn->offset)) {
                /*
                 *      Discount the Framed-MTU by:
@@ -894,6 +1153,10 @@ static int eaptls_initiate(void *type_arg, EAP_HANDLER *handler)
                break;
        }
 
+       if (inst->conf->session_cache_enable) {
+               ssn->allow_session_resumption = 1; /* otherwise it's zero */
+       }
+
        /*
         *      TLS session initialization is over.  Now handle TLS
         *      related handshaking or application data.
@@ -1021,8 +1284,7 @@ static int eaptls_authenticate(void *arg, EAP_HANDLER *handler)
        /*
         *      Success: Automatically return MPPE keys.
         */
-       eaptls_success(handler, 0);
-       return 1;
+       return eaptls_success(handler, 0);
 }
 
 /*