1 /* * eap-tls.c - EAP-TLS implementation for PPP
3 * Copyright (c) Beniamino Galvani 2005 All rights reserved.
4 * Jan Just Keijser 2006-2019 All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
18 * 3. The name(s) of the authors of this software must not be used to
19 * endorse or promote products derived from this software without
20 * prior written permission.
22 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
23 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
24 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
25 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
27 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
28 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
39 #include <openssl/conf.h>
40 #include <openssl/engine.h>
41 #include <openssl/hmac.h>
42 #include <openssl/err.h>
43 #include <openssl/ui.h>
44 #include <openssl/x509v3.h>
45 #include <openssl/pkcs12.h>
54 #include "pathnames.h"
56 typedef struct pw_cb_data
59 const char *prompt_info;
62 #ifndef OPENSSL_NO_ENGINE
63 /* The openssl configuration file and engines can be loaded only once */
64 static CONF *ssl_config = NULL;
65 static ENGINE *cert_engine = NULL;
66 static ENGINE *pkey_engine = NULL;
69 /* TLSv1.3 do we have a session ticket ? */
70 static int have_session_ticket = 0;
72 int ssl_verify_callback(int, X509_STORE_CTX *);
73 void ssl_msg_callback(int write_p, int version, int ct, const void *buf,
74 size_t len, SSL * ssl, void *arg);
75 int ssl_new_session_cb(SSL *s, SSL_SESSION *sess);
77 X509 *get_X509_from_file(char *filename);
78 int ssl_cmp_certs(char *filename, X509 * a);
81 * OpenSSL 1.1+ introduced a generic TLS_method()
82 * For older releases we substitute the appropriate method
85 #if OPENSSL_VERSION_NUMBER < 0x10100000L
87 #define TLS_method SSLv23_method
89 #define SSL3_RT_HEADER 0x100
91 #ifndef SSL_CTX_set_max_proto_version
92 /** Mimics SSL_CTX_set_max_proto_version for OpenSSL < 1.1 */
93 static inline int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, long tls_ver_max)
97 if (tls_ver_max < TLS1_VERSION)
99 sslopt |= SSL_OP_NO_TLSv1;
101 #ifdef SSL_OP_NO_TLSv1_1
102 if (tls_ver_max < TLS1_1_VERSION)
104 sslopt |= SSL_OP_NO_TLSv1_1;
107 #ifdef SSL_OP_NO_TLSv1_2
108 if (tls_ver_max < TLS1_2_VERSION)
110 sslopt |= SSL_OP_NO_TLSv1_2;
113 SSL_CTX_set_options(ctx, sslopt);
117 #endif /* SSL_CTX_set_max_proto_version */
119 #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
122 #define EAPTLS_MPPE_KEY_LEN 32
125 * Generate keys according to RFC 2716 and add to reply
127 void eaptls_gen_mppe_keys(struct eaptls_session *ets, int client)
129 unsigned char out[4*EAPTLS_MPPE_KEY_LEN];
130 const char *prf_label;
132 unsigned char eap_tls13_context[] = { EAPT_TLS };
133 unsigned char *context = NULL;
134 size_t context_len = 0;
137 dbglog("EAP-TLS generating MPPE keys");
140 prf_label = "EXPORTER_EAP_TLS_Key_Material";
141 context = eap_tls13_context;
146 prf_label = "client EAP encryption";
149 dbglog("EAP-TLS PRF label = %s", prf_label);
150 prf_size = strlen(prf_label);
151 if (SSL_export_keying_material(ets->ssl, out, sizeof(out), prf_label, prf_size,
152 context, context_len, 0) != 1)
154 warn( "EAP-TLS: Failed generating keying material" );
159 * We now have the master send and receive keys.
160 * From these, generate the session send and receive keys.
161 * (see RFC3079 / draft-ietf-pppext-mppe-keys-03.txt for details)
165 mppe_set_keys(out, out + EAPTLS_MPPE_KEY_LEN, EAPTLS_MPPE_KEY_LEN);
169 mppe_set_keys(out + EAPTLS_MPPE_KEY_LEN, out, EAPTLS_MPPE_KEY_LEN);
176 void log_ssl_errors( void )
178 unsigned long ssl_err = ERR_get_error();
181 dbglog("EAP-TLS SSL error stack:");
182 while (ssl_err != 0) {
183 dbglog( ERR_error_string( ssl_err, NULL ) );
184 ssl_err = ERR_get_error();
189 int password_callback (char *buf, int size, int rwflag, void *u)
193 strlcpy (buf, passwd, size);
200 CONF *eaptls_ssl_load_config( void )
204 long error_line = 33;
206 config = NCONF_new( NULL );
207 dbglog( "Loading OpenSSL config file" );
208 ret_code = NCONF_load( config, _PATH_OPENSSLCONFFILE, &error_line );
211 warn( "EAP-TLS: Error in OpenSSL config file %s at line %d", _PATH_OPENSSLCONFFILE, error_line );
212 NCONF_free( config );
217 dbglog( "Loading OpenSSL built-ins" );
218 #ifndef OPENSSL_NO_ENGINE
219 ENGINE_load_builtin_engines();
221 OPENSSL_load_builtin_modules();
223 dbglog( "Loading OpenSSL configured modules" );
224 if (CONF_modules_load( config, NULL, 0 ) <= 0 )
226 warn( "EAP-TLS: Error loading OpenSSL modules" );
234 #ifndef OPENSSL_NO_ENGINE
235 ENGINE *eaptls_ssl_load_engine( char *engine_name )
239 dbglog( "Enabling OpenSSL auto engines" );
240 ENGINE_register_all_complete();
242 dbglog( "Loading OpenSSL '%s' engine support", engine_name );
243 e = ENGINE_by_id( engine_name );
246 dbglog( "EAP-TLS: Cannot load '%s' engine support, trying 'dynamic'", engine_name );
247 e = ENGINE_by_id( "dynamic" );
250 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine_name, 0)
251 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
253 warn( "EAP-TLS: Error loading dynamic engine '%s'", engine_name );
261 warn( "EAP-TLS: Cannot load dynamic engine support" );
267 dbglog( "Initialising engine" );
268 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
270 warn( "EAP-TLS: Cannot use that engine" );
283 * Initialize the SSL stacks and tests if certificates, key and crl
284 * for client or server use can be loaded.
286 SSL_CTX *eaptls_init_ssl(int init_server, char *cacertfile, char *capath,
287 char *certfile, char *peer_certfile, char *privkeyfile, char *pkcs12)
289 #ifndef OPENSSL_NO_ENGINE
290 char *cert_engine_name = NULL;
291 char *pkey_engine_name = NULL;
296 X509_STORE *certstore;
301 EVP_PKEY *pkey = NULL;
302 STACK_OF(X509) *chain = NULL;
306 #if defined(TLS1_2_VERSION)
307 long tls_version = TLS1_2_VERSION;
308 #elif defined(TLS1_1_VERSION)
309 long tls_version = TLS1_1_VERSION;
311 long tls_version = TLS1_VERSION;
315 * Without these can't continue
319 if (!(cacertfile[0] || capath[0]))
321 error("EAP-TLS: CA certificate file or path missing");
327 error("EAP-TLS: Certificate missing");
333 error("EAP-TLS: Private key missing");
339 SSL_load_error_strings();
341 #ifndef OPENSSL_NO_ENGINE
342 /* load the openssl config file only once and load it before triggering
343 the loading of a global openssl config file via SSL_CTX_new()
346 ssl_config = eaptls_ssl_load_config();
349 ctx = SSL_CTX_new(TLS_method());
352 error("EAP-TLS: Cannot initialize SSL CTX context");
356 #ifndef OPENSSL_NO_ENGINE
357 /* if the certificate filename is of the form engine:id. e.g.
359 then we try to load and use this engine.
360 If the certificate filename starts with a / or . then we
361 ALWAYS assume it is a file and not an engine/pkcs11 identifier
363 if ( (idx = index( certfile, ':' )) != NULL )
365 cert_engine_name = strdup( certfile );
366 cert_engine_name[idx - certfile] = 0;
368 dbglog( "Using engine '%s' for certificate, URI: '%s'",
369 cert_engine_name, certfile );
372 /* if the privatekey filename is of the form engine:id. e.g.
374 then we try to load and use this engine.
375 If the privatekey filename starts with a / or . then we
376 ALWAYS assume it is a file and not an engine/pkcs11 identifier
378 if ( (idx = index( privkeyfile, ':' )) != NULL )
380 pkey_engine_name = strdup( privkeyfile );
381 pkey_engine_name[idx - privkeyfile] = 0;
383 dbglog( "Using engine '%s' for private key, URI: '%s'",
384 pkey_engine_name, privkeyfile );
387 if (cert_engine_name && pkey_engine_name)
389 if (strlen( certfile ) - strlen( cert_engine_name ) == 1)
391 if (strlen( privkeyfile ) - strlen( pkey_engine_name ) == 1)
392 error( "EAP-TLS: both the certificate and privatekey identifiers are missing!" );
395 dbglog( "Substituting privatekey identifier for certificate identifier" );
396 certfile = privkeyfile;
401 if (strlen( privkeyfile ) - strlen( pkey_engine_name ) == 1)
403 dbglog( "Substituting certificate identifier for privatekey identifier" );
404 privkeyfile = certfile;
409 if (ssl_config && cert_engine_name)
410 cert_engine = eaptls_ssl_load_engine( cert_engine_name );
412 if (ssl_config && pkey_engine_name)
414 /* don't load the same engine twice */
415 if ( cert_engine && strcmp( cert_engine_name, pkey_engine_name) == 0 )
416 pkey_engine = cert_engine;
418 pkey_engine = eaptls_ssl_load_engine( pkey_engine_name );
421 if (cert_engine_name)
422 free(cert_engine_name);
424 if (pkey_engine_name)
425 free(pkey_engine_name);
429 SSL_CTX_set_default_passwd_cb (ctx, password_callback);
431 if (strlen(cacertfile) == 0) cacertfile = NULL;
432 if (strlen(capath) == 0) capath = NULL;
434 if (!SSL_CTX_load_verify_locations(ctx, cacertfile, capath))
436 error("EAP-TLS: Cannot load verify locations");
437 if (cacertfile) dbglog("CA certificate file = [%s]", cacertfile);
438 if (capath) dbglog("CA certificate path = [%s]", capath);
443 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(cacertfile));
445 #ifndef OPENSSL_NO_ENGINE
450 const char *s_slot_cert_id;
454 cert_info.s_slot_cert_id = certfile;
455 cert_info.cert = NULL;
457 if (!ENGINE_ctrl_cmd( cert_engine, "LOAD_CERT_CTRL", 0, &cert_info, NULL, 0 ) )
459 error( "EAP-TLS: Error loading certificate with URI '%s' from engine", certfile );
465 dbglog( "Got the certificate" );
466 dbglog( "subject = %s", X509_NAME_oneline( X509_get_subject_name( cert_info.cert ), NULL, 0 ) );
467 cert = cert_info.cert;
471 warn("EAP-TLS: Cannot load key with URI: '%s'", certfile );
480 input = BIO_new_file(pkcs12, "r");
483 error("EAP-TLS: Cannot open `%s' PKCS12 for input", pkcs12);
487 p12 = d2i_PKCS12_bio(input, NULL);
491 error("EAP-TLS: Cannot load PKCS12 certificate");
495 if (PKCS12_parse(p12, passwd, &pkey, &cert, &chain) != 1)
497 error("EAP-TLS: Cannot parse PKCS12 certificate, invalid password");
506 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile))
508 error( "EAP-TLS: Cannot load certificate %s", certfile );
516 if (!SSL_CTX_use_certificate(ctx, cert))
518 error("EAP-TLS: Cannot use load certificate");
525 for (i = 0; i < sk_X509_num(chain); i++)
527 if (!SSL_CTX_add_extra_chain_cert(ctx, sk_X509_value(chain, i)))
529 error("EAP-TLS: Cannot add extra chain certificate");
537 * Check the Before and After dates of the certificate
540 tmp = SSL_get_certificate(ssl);
542 ret = X509_cmp_time(X509_get_notBefore(tmp), NULL);
545 warn( "EAP-TLS: Failed to read certificate notBefore field.");
549 warn( "EAP-TLS: Your certificate is not yet valid!");
552 ret = X509_cmp_time(X509_get_notAfter(tmp), NULL);
555 warn( "EAP-TLS: Failed to read certificate notAfter field.");
559 warn( "EAP-TLS: Your certificate has expired!");
563 #ifndef OPENSSL_NO_ENGINE
568 cb_data.password = passwd;
569 cb_data.prompt_info = privkeyfile;
573 UI_METHOD* transfer_pin = UI_create_method("transfer_pin");
575 int writer (UI *ui, UI_STRING *uis)
577 PW_CB_DATA* cb_data = (PW_CB_DATA*)UI_get0_user_data(ui);
578 UI_set_result(ui, uis, cb_data->password);
581 int stub (UI* ui) {return 1;};
582 int stub_reader (UI *ui, UI_STRING *uis) {return 1;};
584 UI_method_set_writer(transfer_pin, writer);
585 UI_method_set_opener(transfer_pin, stub);
586 UI_method_set_closer(transfer_pin, stub);
587 UI_method_set_flusher(transfer_pin, stub);
588 UI_method_set_reader(transfer_pin, stub_reader);
590 dbglog( "Using our private key URI: '%s' in engine", privkeyfile );
591 pkey = ENGINE_load_private_key(pkey_engine, privkeyfile, transfer_pin, &cb_data);
593 if (transfer_pin) UI_destroy_method(transfer_pin);
596 dbglog( "Loading private key URI: '%s' from engine", privkeyfile );
597 pkey = ENGINE_load_private_key(pkey_engine, privkeyfile, NULL, NULL);
605 input = BIO_new_file(privkeyfile, "r");
608 error("EAP-TLS: Could not open private key, %s", privkeyfile);
612 pkey = PEM_read_bio_PrivateKey(input, NULL, password_callback, NULL);
616 error("EAP-TLS: Cannot load private key, %s", privkeyfile);
622 if (SSL_CTX_use_PrivateKey(ctx, pkey) != 1)
624 error("EAP-TLS: Cannot use private key");
628 if (SSL_CTX_check_private_key(ctx) != 1)
630 error("EAP-TLS: Private key fails security check");
634 /* Explicitly set the NO_TICKETS flag to support Win7/Win8 clients */
635 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3
636 #ifdef SSL_OP_NO_TICKET
641 /* OpenSSL 1.1.1+ does not include RC4 ciphers by default.
642 * This causes totally obsolete WinXP clients to fail. If you really
643 * need ppp+EAP-TLS+openssl 1.1.1+WinXP then enable RC4 cipers and
644 * make sure that you use an OpenSSL that supports them
646 SSL_CTX_set_cipher_list(ctx, "RC4");
650 /* Set up a SSL Session cache with a callback. This is needed for TLSv1.3+.
651 * During the initial handshake the server signals to the client early on
652 * that the handshake is finished, even before the client has sent its
653 * credentials to the server. The actual connection (and moment that the
654 * client sends its credentials) only starts after the arrival of the first
655 * session ticket. The 'ssl_new_session_cb' catches this ticket.
657 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
658 SSL_CTX_sess_set_new_cb(ctx, ssl_new_session_cb);
660 /* As EAP-TLS+TLSv1.3 is highly experimental we offer the user a chance to override */
663 if (strncmp(max_tls_version, "1.0", 3) == 0)
664 tls_version = TLS1_VERSION;
665 else if (strncmp(max_tls_version, "1.1", 3) == 0)
666 tls_version = TLS1_1_VERSION;
667 else if (strncmp(max_tls_version, "1.2", 3) == 0)
668 #ifdef TLS1_2_VERSION
669 tls_version = TLS1_2_VERSION;
672 warn("TLSv1.2 not available. Defaulting to TLSv1.1");
673 tls_version = TLS_1_1_VERSION;
676 else if (strncmp(max_tls_version, "1.3", 3) == 0)
677 #ifdef TLS1_3_VERSION
678 tls_version = TLS1_3_VERSION;
680 warn("TLSv1.3 not available.");
684 dbglog("EAP-TLS: Setting max protocol version to 0x%X", tls_version);
685 SSL_CTX_set_max_proto_version(ctx, tls_version);
687 SSL_CTX_set_verify_depth(ctx, 5);
688 SSL_CTX_set_verify(ctx,
690 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
691 &ssl_verify_callback);
694 if (!(certstore = SSL_CTX_get_cert_store(ctx))) {
695 error("EAP-TLS: Failed to get certificate store");
700 X509_STORE_add_lookup(certstore, X509_LOOKUP_hash_dir()))) {
701 error("EAP-TLS: Store lookup for CRL failed");
706 X509_LOOKUP_add_dir(lookup, crl_dir, X509_FILETYPE_PEM);
707 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
712 X509_CRL *crl = NULL;
714 fp = fopen(crl_file, "r");
716 error("EAP-TLS: Cannot open CRL file '%s'", crl_file);
720 crl = PEM_read_X509_CRL(fp, NULL, NULL, NULL);
722 error("EAP-TLS: Cannot read CRL file '%s'", crl_file);
726 if (!(certstore = SSL_CTX_get_cert_store(ctx))) {
727 error("EAP-TLS: Failed to get certificate store");
730 if (!X509_STORE_add_crl(certstore, crl)) {
731 error("EAP-TLS: Cannot add CRL to certificate store");
734 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
739 * If a peer certificate file was specified, it must be valid, else fail
741 if (peer_certfile[0]) {
742 if (!(tmp = get_X509_from_file(peer_certfile))) {
743 error("EAP-TLS: Error loading client certificate from file %s",
761 sk_X509_pop_free(chain, X509_free);
769 * Determine the maximum packet size by looking at the LCP handshake
772 int eaptls_get_mtu(int unit)
776 lcp_options *wo = &lcp_wantoptions[unit];
777 lcp_options *go = &lcp_gotoptions[unit];
778 lcp_options *ho = &lcp_hisoptions[unit];
779 lcp_options *ao = &lcp_allowoptions[unit];
781 mtu = ho->neg_mru? ho->mru: PPP_MRU;
782 mru = go->neg_mru? MAX(wo->mru, go->mru): PPP_MRU;
783 mtu = MIN(MIN(mtu, mru), ao->mru)- PPP_HDRLEN - 10;
785 dbglog("MTU = %d", mtu);
791 * Init the ssl handshake (server mode)
793 int eaptls_init_ssl_server(eap_state * esp)
795 struct eaptls_session *ets;
796 char servcertfile[MAXWORDLEN];
797 char clicertfile[MAXWORDLEN];
798 char cacertfile[MAXWORDLEN];
799 char capath[MAXWORDLEN];
800 char pkfile[MAXWORDLEN];
801 char pkcs12[MAXWORDLEN];
804 * Allocate new eaptls session
806 esp->es_server.ea_session = malloc(sizeof(struct eaptls_session));
807 if (!esp->es_server.ea_session)
808 fatal("Allocation error");
809 ets = esp->es_server.ea_session;
812 if (!esp->es_server.ea_peer) {
813 error("EAP-TLS: Error: client name not set (BUG)");
817 strlcpy(ets->peer, esp->es_server.ea_peer, MAXWORDLEN-1);
819 dbglog( "getting eaptls secret" );
820 if (!get_eaptls_secret(esp->es_unit, esp->es_server.ea_peer,
821 esp->es_server.ea_name, clicertfile,
822 servcertfile, cacertfile, capath, pkfile, pkcs12, 1)) {
823 error( "EAP-TLS: Cannot get secret/password for client \"%s\", server \"%s\"",
824 esp->es_server.ea_peer, esp->es_server.ea_name );
828 ets->mtu = eaptls_get_mtu(esp->es_unit);
830 ets->ctx = eaptls_init_ssl(1, cacertfile, capath, servcertfile, clicertfile, pkfile, pkcs12);
834 if (!(ets->ssl = SSL_new(ets->ctx)))
838 * Set auto-retry to avoid timeouts on BIO_read
840 SSL_set_mode(ets->ssl, SSL_MODE_AUTO_RETRY);
843 * Initialize the BIOs we use to read/write to ssl engine
845 ets->into_ssl = BIO_new(BIO_s_mem());
846 ets->from_ssl = BIO_new(BIO_s_mem());
847 SSL_set_bio(ets->ssl, ets->into_ssl, ets->from_ssl);
849 SSL_set_msg_callback(ets->ssl, ssl_msg_callback);
850 SSL_set_msg_callback_arg(ets->ssl, ets);
853 * Attach the session struct to the connection, so we can later
854 * retrieve it when doing certificate verification
856 SSL_set_ex_data(ets->ssl, 0, ets);
858 SSL_set_accept_state(ets->ssl);
868 * If we specified the client certificate file, store it in ets->peercertfile,
869 * so we can check it later in ssl_verify_callback()
872 strlcpy(&ets->peercertfile[0], clicertfile, MAXWORDLEN);
874 ets->peercertfile[0] = 0;
879 SSL_CTX_free(ets->ctx);
884 * Init the ssl handshake (client mode)
886 int eaptls_init_ssl_client(eap_state * esp)
888 struct eaptls_session *ets;
889 char servcertfile[MAXWORDLEN];
890 char clicertfile[MAXWORDLEN];
891 char cacertfile[MAXWORDLEN];
892 char capath[MAXWORDLEN];
893 char pkfile[MAXWORDLEN];
894 char pkcs12[MAXWORDLEN];
897 * Allocate new eaptls session
899 esp->es_client.ea_session = malloc(sizeof(struct eaptls_session));
900 if (!esp->es_client.ea_session)
901 fatal("Allocation error");
902 ets = esp->es_client.ea_session;
906 * If available, copy server name in ets; it will be used in cert
909 if (esp->es_client.ea_peer)
910 strlcpy(ets->peer, esp->es_client.ea_peer, MAXWORDLEN-1);
914 ets->mtu = eaptls_get_mtu(esp->es_unit);
916 dbglog( "calling get_eaptls_secret" );
917 if (!get_eaptls_secret(esp->es_unit, esp->es_client.ea_name,
918 ets->peer, clicertfile,
919 servcertfile, cacertfile, capath, pkfile, pkcs12, 0)) {
920 error( "EAP-TLS: Cannot get secret/password for client \"%s\", server \"%s\"",
921 esp->es_client.ea_name, ets->peer );
925 dbglog( "calling eaptls_init_ssl" );
926 ets->ctx = eaptls_init_ssl(0, cacertfile, capath, clicertfile, servcertfile, pkfile, pkcs12);
930 ets->ssl = SSL_new(ets->ctx);
936 * Initialize the BIOs we use to read/write to ssl engine
938 dbglog( "Initializing SSL BIOs" );
939 ets->into_ssl = BIO_new(BIO_s_mem());
940 ets->from_ssl = BIO_new(BIO_s_mem());
941 SSL_set_bio(ets->ssl, ets->into_ssl, ets->from_ssl);
943 SSL_set_msg_callback(ets->ssl, ssl_msg_callback);
944 SSL_set_msg_callback_arg(ets->ssl, ets);
947 * Attach the session struct to the connection, so we can later
948 * retrieve it when doing certificate verification
950 SSL_set_ex_data(ets->ssl, 0, ets);
952 SSL_set_connect_state(ets->ssl);
962 * If we specified the server certificate file, store it in
963 * ets->peercertfile, so we can check it later in
964 * ssl_verify_callback()
967 strlcpy(ets->peercertfile, servcertfile, MAXWORDLEN);
969 ets->peercertfile[0] = 0;
974 dbglog( "eaptls_init_ssl_client: fail" );
975 SSL_CTX_free(ets->ctx);
980 void eaptls_free_session(struct eaptls_session *ets)
986 SSL_CTX_free(ets->ctx);
992 int eaptls_is_init_finished(struct eaptls_session *ets)
994 if (ets->ssl && SSL_is_init_finished(ets->ssl))
997 return have_session_ticket;
1006 * Handle a received packet, reassembling fragmented messages and
1007 * passing them to the ssl engine
1009 int eaptls_receive(struct eaptls_session *ets, u_char * inp, int len)
1013 u_char dummy[65536];
1016 warn("EAP-TLS: received no or invalid data");
1020 GETCHAR(flags, inp);
1023 if (flags & EAP_TLS_FLAGS_LI && len > 4) {
1025 * LenghtIncluded flag set -> this is the first packet of a message
1029 * the first 4 octets are the length of the EAP-TLS message
1031 GETLONG(tlslen, inp);
1036 if (tlslen > EAP_TLS_MAX_LEN) {
1037 error("EAP-TLS: TLS message length > %d, truncated", EAP_TLS_MAX_LEN);
1038 tlslen = EAP_TLS_MAX_LEN;
1042 * Allocate memory for the whole message
1044 ets->data = malloc(tlslen);
1046 fatal("EAP-TLS: allocation error\n");
1049 ets->tlslen = tlslen;
1052 warn("EAP-TLS: non-first LI packet? that's odd...");
1054 else if (!ets->data) {
1056 * A non fragmented message without LI flag
1059 ets->data = malloc(len);
1061 fatal("EAP-TLS: memory allocation error in eaptls_receive\n");
1067 if (flags & EAP_TLS_FLAGS_MF)
1073 warn("EAP-TLS: received malformed data");
1077 if (len + ets->datalen > ets->tlslen) {
1078 warn("EAP-TLS: received data > TLS message length");
1082 BCOPY(inp, ets->data + ets->datalen, len);
1083 ets->datalen += len;
1088 * If we have the whole message, pass it to ssl
1091 if (ets->datalen != ets->tlslen) {
1092 warn("EAP-TLS: received data != TLS message length");
1096 if (BIO_write(ets->into_ssl, ets->data, ets->datalen) == -1)
1099 SSL_read(ets->ssl, dummy, 65536);
1110 * Return an eap-tls packet in outp.
1111 * A TLS message read from the ssl engine is buffered in ets->data.
1112 * At each call we control if there is buffered data and send a
1113 * packet of mtu bytes.
1115 int eaptls_send(struct eaptls_session *ets, u_char ** outp)
1119 u_char fromtls[65536];
1127 if(!ets->alert_sent)
1129 res = SSL_read(ets->ssl, fromtls, 65536);
1135 if ((res = BIO_read(ets->from_ssl, fromtls, 65536)) == -1)
1137 warn("EAP-TLS send: No data from BIO_read");
1143 ets->data = malloc(ets->datalen);
1145 fatal("EAP-TLS: memory allocation error in eaptls_send\n");
1147 BCOPY(fromtls, ets->data, ets->datalen);
1153 size = ets->datalen - ets->offset;
1155 if (size > ets->mtu) {
1161 PUTCHAR(EAPT_TLS, *outp);
1164 * Set right flags and length if necessary
1166 if (ets->frag && first) {
1167 PUTCHAR(EAP_TLS_FLAGS_LI | EAP_TLS_FLAGS_MF, *outp);
1168 PUTLONG(ets->datalen, *outp);
1169 } else if (ets->frag) {
1170 PUTCHAR(EAP_TLS_FLAGS_MF, *outp);
1175 * Copy the data in outp
1177 BCOPY(ets->data + ets->offset, *outp, size);
1178 INCPTR(size, *outp);
1181 * Copy the packet in retransmission buffer
1183 BCOPY(start, &ets->rtx[0], *outp - start);
1184 ets->rtx_len = *outp - start;
1186 ets->offset += size;
1188 if (ets->offset >= ets->datalen) {
1191 * The whole message has been sent
1204 * Get the sent packet from the retransmission buffer
1206 void eaptls_retransmit(struct eaptls_session *ets, u_char ** outp)
1208 BCOPY(ets->rtx, *outp, ets->rtx_len);
1209 INCPTR(ets->rtx_len, *outp);
1213 * Verify a certificate.
1214 * Most of the work (signatures and issuer attributes checking)
1215 * is done by ssl; we check the CN in the peer certificate
1216 * against the peer name.
1218 int ssl_verify_callback(int ok, X509_STORE_CTX * ctx)
1225 struct eaptls_session *ets;
1226 char *ptr1 = NULL, *ptr2 = NULL;
1228 peer_cert = X509_STORE_CTX_get_current_cert(ctx);
1229 err = X509_STORE_CTX_get_error(ctx);
1230 depth = X509_STORE_CTX_get_error_depth(ctx);
1232 dbglog("certificate verify depth: %d", depth);
1234 if (auth_required && !ok) {
1235 X509_NAME_oneline(X509_get_subject_name(peer_cert),
1238 X509_NAME_get_text_by_NID(X509_get_subject_name(peer_cert),
1239 NID_commonName, cn_str, 256);
1241 dbglog("Certificate verification error:\n depth: %d CN: %s"
1242 "\n err: %d (%s)\n", depth, cn_str, err,
1243 X509_verify_cert_error_string(err));
1248 ssl = X509_STORE_CTX_get_ex_data(ctx,
1249 SSL_get_ex_data_X509_STORE_CTX_idx());
1251 ets = (struct eaptls_session *)SSL_get_ex_data(ssl, 0);
1254 error("Error: SSL_get_ex_data returned NULL");
1262 /* Verify certificate based on certificate type and extended key usage */
1263 if (tls_verify_key_usage) {
1264 int purpose = ets->client ? X509_PURPOSE_SSL_SERVER : X509_PURPOSE_SSL_CLIENT ;
1265 if (X509_check_purpose(peer_cert, purpose, 0) == 0) {
1266 error("Certificate verification error: nsCertType mismatch");
1270 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1271 int flags = ets->client ? XKU_SSL_SERVER : XKU_SSL_CLIENT;
1272 if (!(X509_get_extended_key_usage(peer_cert) & flags)) {
1273 error("Certificate verification error: invalid extended key usage");
1277 info("Certificate key usage: OK");
1281 * If acting as client and the name of the server wasn't specified
1282 * explicitely, we can't verify the server authenticity
1284 if (!tls_verify_method)
1285 tls_verify_method = TLS_VERIFY_NONE;
1287 if (!ets->peer[0] || !strcmp(TLS_VERIFY_NONE, tls_verify_method)) {
1288 warn("Certificate verication disabled or no peer name was specified");
1292 /* This is the peer certificate */
1293 X509_NAME_oneline(X509_get_subject_name(peer_cert),
1296 X509_NAME_get_text_by_NID(X509_get_subject_name(peer_cert),
1297 NID_commonName, cn_str, 256);
1299 /* Verify based on subject name */
1301 if (!strcmp(TLS_VERIFY_SUBJECT, tls_verify_method)) {
1305 /* Verify based on common name (default) */
1306 if (strlen(tls_verify_method) == 0 ||
1307 !strcmp(TLS_VERIFY_NAME, tls_verify_method)) {
1311 /* Match the suffix of common name */
1312 if (!strcmp(TLS_VERIFY_SUFFIX, tls_verify_method)) {
1313 int len = strlen(ptr1);
1314 int off = strlen(cn_str) - len;
1317 ptr2 = cn_str + off;
1321 if (strcmp(ptr1, ptr2)) {
1322 error("Certificate verification error: CN (%s) != %s", ptr1, ptr2);
1326 info("Certificate CN: %s, peer name %s", cn_str, ets->peer);
1329 * If a peer certificate file was specified, here we check it
1331 if (ets->peercertfile[0]) {
1332 if (ssl_cmp_certs(&ets->peercertfile[0], peer_cert)
1335 ("Peer certificate doesn't match stored certificate");
1345 * Compare a certificate with the one stored in a file
1347 int ssl_cmp_certs(char *filename, X509 * a)
1352 if (!(b = get_X509_from_file(filename)))
1355 ret = X509_cmp(a, b);
1362 X509 *get_X509_from_file(char *filename)
1367 if (!(fp = fopen(filename, "r")))
1370 ret = PEM_read_X509(fp, NULL, NULL, NULL);
1378 * Every sent & received message this callback function is invoked,
1379 * so we know when alert messages have arrived or are sent and
1380 * we can print debug information about TLS handshake.
1383 ssl_msg_callback(int write_p, int version, int content_type,
1384 const void *buf, size_t len, SSL * ssl, void *arg)
1387 struct eaptls_session *ets = (struct eaptls_session *)arg;
1389 const unsigned char*msg = buf;
1390 int hvers = msg[1] << 8 | msg[2];
1393 strcpy(string, " -> ");
1395 strcpy(string, " <- ");
1397 switch(content_type) {
1399 case SSL3_RT_HEADER:
1400 strcat(string, "SSL/TLS Header: ");
1403 strcat(string, "SSL 3.0");
1406 strcat(string, "TLS 1.0");
1408 case TLS1_1_VERSION:
1409 strcat(string, "TLS 1.1");
1411 case TLS1_2_VERSION:
1412 strcat(string, "TLS 1.2");
1415 sprintf(string, "SSL/TLS Header: Unknown version (%d)", hvers);
1420 strcat(string, "Alert: ");
1424 ets->alert_sent = 1;
1425 ets->alert_sent_desc = code;
1427 ets->alert_recv = 1;
1428 ets->alert_recv_desc = code;
1431 strcat(string, SSL_alert_desc_string_long(code));
1434 case SSL3_RT_CHANGE_CIPHER_SPEC:
1435 strcat(string, "ChangeCipherSpec");
1438 #ifdef SSL3_RT_INNER_CONTENT_TYPE
1439 case SSL3_RT_INNER_CONTENT_TYPE:
1440 strcat(string, "InnerContentType (TLS1.3)");
1444 case SSL3_RT_HANDSHAKE:
1446 strcat(string, "Handshake: ");
1450 case SSL3_MT_HELLO_REQUEST:
1451 strcat(string,"Hello Request");
1453 case SSL3_MT_CLIENT_HELLO:
1454 strcat(string,"Client Hello");
1456 case SSL3_MT_SERVER_HELLO:
1457 strcat(string,"Server Hello");
1459 #ifdef SSL3_MT_NEWSESSION_TICKET
1460 case SSL3_MT_NEWSESSION_TICKET:
1461 strcat(string,"New Session Ticket");
1464 #ifdef SSL3_MT_END_OF_EARLY_DATA
1465 case SSL3_MT_END_OF_EARLY_DATA:
1466 strcat(string,"End of Early Data");
1469 #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
1470 case SSL3_MT_ENCRYPTED_EXTENSIONS:
1471 strcat(string,"Encryped Extensions");
1474 case SSL3_MT_CERTIFICATE:
1475 strcat(string,"Certificate");
1477 case SSL3_MT_SERVER_KEY_EXCHANGE:
1478 strcat(string,"Server Key Exchange");
1480 case SSL3_MT_CERTIFICATE_REQUEST:
1481 strcat(string,"Certificate Request");
1483 case SSL3_MT_SERVER_DONE:
1484 strcat(string,"Server Hello Done");
1486 case SSL3_MT_CERTIFICATE_VERIFY:
1487 strcat(string,"Certificate Verify");
1489 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1490 strcat(string,"Client Key Exchange");
1492 case SSL3_MT_FINISHED:
1493 strcat(string,"Finished: ");
1494 hvers = SSL_version(ssl);
1497 strcat(string, "SSL 3.0");
1500 strcat(string, "TLS 1.0");
1502 case TLS1_1_VERSION:
1503 strcat(string, "TLS 1.1");
1505 case TLS1_2_VERSION:
1506 strcat(string, "TLS 1.2");
1508 #ifdef TLS1_3_VERSION
1509 case TLS1_3_VERSION:
1510 strcat(string, "TLS 1.3 (experimental)");
1515 strcat(string, "Unknown version");
1519 sprintf( string, "Handshake: Unknown SSL3 code received: %d", code );
1524 sprintf( string, "SSL message contains unknown content type: %d", content_type );
1527 /* Alert messages must always be displayed */
1528 if(content_type == SSL3_RT_ALERT)
1529 error("%s", string);
1531 dbglog("%s", string);
1535 ssl_new_session_cb(SSL *s, SSL_SESSION *sess)
1537 dbglog("EAP-TLS: Post-Handshake New Session Ticket arrived:");
1538 have_session_ticket = 1;
1540 /* always return success */