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>
51 #include "pathnames.h"
53 typedef struct pw_cb_data
56 const char *prompt_info;
59 #ifndef OPENSSL_NO_ENGINE
60 /* The openssl configuration file and engines can be loaded only once */
61 static CONF *ssl_config = NULL;
62 static ENGINE *cert_engine = NULL;
63 static ENGINE *pkey_engine = NULL;
66 /* TLSv1.3 do we have a session ticket ? */
67 static int have_session_ticket = 0;
69 int ssl_verify_callback(int, X509_STORE_CTX *);
70 void ssl_msg_callback(int write_p, int version, int ct, const void *buf,
71 size_t len, SSL * ssl, void *arg);
72 int ssl_new_session_cb(SSL *s, SSL_SESSION *sess);
74 X509 *get_X509_from_file(char *filename);
75 int ssl_cmp_certs(char *filename, X509 * a);
79 #define EAPTLS_MPPE_KEY_LEN 32
82 * OpenSSL 1.1+ introduced a generic TLS_method()
83 * For older releases we substitute the appropriate method
86 #if OPENSSL_VERSION_NUMBER < 0x10100000L
88 #define TLS_method SSLv23_method
90 #define SSL3_RT_HEADER 0x100
92 #ifndef SSL_CTX_set_max_proto_version
93 /** Mimics SSL_CTX_set_max_proto_version for OpenSSL < 1.1 */
94 static inline int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, long tls_ver_max)
98 if (tls_ver_max < TLS1_VERSION)
100 sslopt |= SSL_OP_NO_TLSv1;
102 #ifdef SSL_OP_NO_TLSv1_1
103 if (tls_ver_max < TLS1_1_VERSION)
105 sslopt |= SSL_OP_NO_TLSv1_1;
108 #ifdef SSL_OP_NO_TLSv1_2
109 if (tls_ver_max < TLS1_2_VERSION)
111 sslopt |= SSL_OP_NO_TLSv1_2;
114 SSL_CTX_set_options(ctx, sslopt);
118 #endif /* SSL_CTX_set_max_proto_version */
120 #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
124 * Generate keys according to RFC 2716 and add to reply
126 void eaptls_gen_mppe_keys(struct eaptls_session *ets, int client)
128 unsigned char out[4*EAPTLS_MPPE_KEY_LEN];
129 const char *prf_label;
131 unsigned char eap_tls13_context[] = { EAPT_TLS };
132 unsigned char *context = NULL;
133 size_t context_len = 0;
136 dbglog("EAP-TLS generating MPPE keys");
139 prf_label = "EXPORTER_EAP_TLS_Key_Material";
140 context = eap_tls13_context;
145 prf_label = "client EAP encryption";
148 dbglog("EAP-TLS PRF label = %s", prf_label);
149 prf_size = strlen(prf_label);
150 if (SSL_export_keying_material(ets->ssl, out, sizeof(out), prf_label, prf_size,
151 context, context_len, 0) != 1)
153 warn( "EAP-TLS: Failed generating keying material" );
158 * We now have the master send and receive keys.
159 * From these, generate the session send and receive keys.
160 * (see RFC3079 / draft-ietf-pppext-mppe-keys-03.txt for details)
165 BCOPY( p, mppe_send_key, sizeof(mppe_send_key) );
166 p += EAPTLS_MPPE_KEY_LEN;
167 BCOPY( p, mppe_recv_key, sizeof(mppe_recv_key) );
172 BCOPY( p, mppe_recv_key, sizeof(mppe_recv_key) );
173 p += EAPTLS_MPPE_KEY_LEN;
174 BCOPY( p, mppe_send_key, sizeof(mppe_send_key) );
182 void log_ssl_errors( void )
184 unsigned long ssl_err = ERR_get_error();
187 dbglog("EAP-TLS SSL error stack:");
188 while (ssl_err != 0) {
189 dbglog( ERR_error_string( ssl_err, NULL ) );
190 ssl_err = ERR_get_error();
195 int password_callback (char *buf, int size, int rwflag, void *u)
199 strlcpy (buf, passwd, size);
206 CONF *eaptls_ssl_load_config( void )
210 long error_line = 33;
212 config = NCONF_new( NULL );
213 dbglog( "Loading OpenSSL config file" );
214 ret_code = NCONF_load( config, _PATH_OPENSSLCONFFILE, &error_line );
217 warn( "EAP-TLS: Error in OpenSSL config file %s at line %d", _PATH_OPENSSLCONFFILE, error_line );
218 NCONF_free( config );
223 dbglog( "Loading OpenSSL built-ins" );
224 #ifndef OPENSSL_NO_ENGINE
225 ENGINE_load_builtin_engines();
227 OPENSSL_load_builtin_modules();
229 dbglog( "Loading OpenSSL configured modules" );
230 if (CONF_modules_load( config, NULL, 0 ) <= 0 )
232 warn( "EAP-TLS: Error loading OpenSSL modules" );
240 #ifndef OPENSSL_NO_ENGINE
241 ENGINE *eaptls_ssl_load_engine( char *engine_name )
245 dbglog( "Enabling OpenSSL auto engines" );
246 ENGINE_register_all_complete();
248 dbglog( "Loading OpenSSL '%s' engine support", engine_name );
249 e = ENGINE_by_id( engine_name );
252 dbglog( "EAP-TLS: Cannot load '%s' engine support, trying 'dynamic'", engine_name );
253 e = ENGINE_by_id( "dynamic" );
256 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine_name, 0)
257 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
259 warn( "EAP-TLS: Error loading dynamic engine '%s'", engine_name );
267 warn( "EAP-TLS: Cannot load dynamic engine support" );
273 dbglog( "Initialising engine" );
274 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
276 warn( "EAP-TLS: Cannot use that engine" );
289 * Initialize the SSL stacks and tests if certificates, key and crl
290 * for client or server use can be loaded.
292 SSL_CTX *eaptls_init_ssl(int init_server, char *cacertfile, char *capath,
293 char *certfile, char *peer_certfile, char *privkeyfile)
295 #ifndef OPENSSL_NO_ENGINE
296 char *cert_engine_name = NULL;
297 char *cert_identifier = NULL;
298 char *pkey_engine_name = NULL;
299 char *pkey_identifier = NULL;
303 X509_STORE *certstore;
307 #if defined(TLS1_2_VERSION)
308 long tls_version = TLS1_2_VERSION;
309 #elif defined(TLS1_1_VERSION)
310 long tls_version = TLS1_1_VERSION;
312 long tls_version = TLS1_VERSION;
316 * Without these can't continue
318 if (!(cacertfile[0] || capath[0]))
320 error("EAP-TLS: CA certificate file or path missing");
326 error("EAP-TLS: Certificate missing");
332 error("EAP-TLS: Private key missing");
337 SSL_load_error_strings();
339 #ifndef OPENSSL_NO_ENGINE
340 /* load the openssl config file only once and load it before triggering
341 the loading of a global openssl config file via SSL_CTX_new()
344 ssl_config = eaptls_ssl_load_config();
347 ctx = SSL_CTX_new(TLS_method());
350 error("EAP-TLS: Cannot initialize SSL CTX context");
354 #ifndef OPENSSL_NO_ENGINE
355 /* if the certificate filename is of the form engine:id. e.g.
357 then we try to load and use this engine.
358 If the certificate filename starts with a / or . then we
359 ALWAYS assume it is a file and not an engine/pkcs11 identifier
361 if ( index( certfile, '/' ) == NULL && index( certfile, '.') == NULL )
363 cert_identifier = index( certfile, ':' );
367 cert_engine_name = certfile;
368 *cert_identifier = '\0';
371 dbglog( "Found certificate engine '%s'", cert_engine_name );
372 dbglog( "Found certificate identifier '%s'", cert_identifier );
376 /* if the privatekey filename is of the form engine:id. e.g.
378 then we try to load and use this engine.
379 If the privatekey filename starts with a / or . then we
380 ALWAYS assume it is a file and not an engine/pkcs11 identifier
382 if ( index( privkeyfile, '/' ) == NULL && index( privkeyfile, '.') == NULL )
384 pkey_identifier = index( privkeyfile, ':' );
388 pkey_engine_name = privkeyfile;
389 *pkey_identifier = '\0';
392 dbglog( "Found privatekey engine '%s'", pkey_engine_name );
393 dbglog( "Found privatekey identifier '%s'", pkey_identifier );
397 if (cert_identifier && pkey_identifier)
399 if (strlen( cert_identifier ) == 0)
401 if (strlen( pkey_identifier ) == 0)
402 error( "EAP-TLS: both the certificate and privatekey identifiers are missing!" );
405 dbglog( "Substituting privatekey identifier for certificate identifier" );
406 cert_identifier = pkey_identifier;
411 if (strlen( pkey_identifier ) == 0)
413 dbglog( "Substituting certificate identifier for privatekey identifier" );
414 pkey_identifier = cert_identifier;
419 if (ssl_config && cert_engine_name)
420 cert_engine = eaptls_ssl_load_engine( cert_engine_name );
422 if (ssl_config && pkey_engine_name)
424 /* don't load the same engine twice */
425 if ( cert_engine && strcmp( cert_engine_name, pkey_engine_name) == 0 )
426 pkey_engine = cert_engine;
428 pkey_engine = eaptls_ssl_load_engine( pkey_engine_name );
432 SSL_CTX_set_default_passwd_cb (ctx, password_callback);
434 if (strlen(cacertfile) == 0) cacertfile = NULL;
435 if (strlen(capath) == 0) capath = NULL;
437 if (!SSL_CTX_load_verify_locations(ctx, cacertfile, capath))
439 error("EAP-TLS: Cannot load verify locations");
440 if (cacertfile) dbglog("CA certificate file = [%s]", cacertfile);
441 if (capath) dbglog("CA certificate path = [%s]", capath);
446 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(cacertfile));
448 #ifndef OPENSSL_NO_ENGINE
453 const char *s_slot_cert_id;
457 cert_info.s_slot_cert_id = cert_identifier;
458 cert_info.cert = NULL;
460 if (!ENGINE_ctrl_cmd( cert_engine, "LOAD_CERT_CTRL", 0, &cert_info, NULL, 0 ) )
462 error( "EAP-TLS: Error loading certificate with id '%s' from engine", cert_identifier );
468 dbglog( "Got the certificate, adding it to SSL context" );
469 dbglog( "subject = %s", X509_NAME_oneline( X509_get_subject_name( cert_info.cert ), NULL, 0 ) );
470 if (SSL_CTX_use_certificate(ctx, cert_info.cert) <= 0)
472 error("EAP-TLS: Cannot use PKCS11 certificate %s", cert_identifier);
478 warn("EAP-TLS: Cannot load PKCS11 key %s", cert_identifier);
485 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile))
487 error( "EAP-TLS: Cannot use public certificate %s", certfile );
494 * Check the Before and After dates of the certificate
497 tmp = SSL_get_certificate(ssl);
499 ret = X509_cmp_time(X509_get_notBefore(tmp), NULL);
502 warn( "EAP-TLS: Failed to read certificate notBefore field.");
506 warn( "EAP-TLS: Your certificate is not yet valid!");
509 ret = X509_cmp_time(X509_get_notAfter(tmp), NULL);
512 warn( "EAP-TLS: Failed to read certificate notAfter field.");
516 warn( "EAP-TLS: Your certificate has expired!");
520 #ifndef OPENSSL_NO_ENGINE
523 EVP_PKEY *pkey = NULL;
526 cb_data.password = passwd;
527 cb_data.prompt_info = pkey_identifier;
531 UI_METHOD* transfer_pin = UI_create_method("transfer_pin");
533 int writer (UI *ui, UI_STRING *uis)
535 PW_CB_DATA* cb_data = (PW_CB_DATA*)UI_get0_user_data(ui);
536 UI_set_result(ui, uis, cb_data->password);
539 int stub (UI* ui) {return 1;};
540 int stub_reader (UI *ui, UI_STRING *uis) {return 1;};
542 UI_method_set_writer(transfer_pin, writer);
543 UI_method_set_opener(transfer_pin, stub);
544 UI_method_set_closer(transfer_pin, stub);
545 UI_method_set_flusher(transfer_pin, stub);
546 UI_method_set_reader(transfer_pin, stub_reader);
548 dbglog( "Using our private key '%s' in engine", pkey_identifier );
549 pkey = ENGINE_load_private_key(pkey_engine, pkey_identifier, transfer_pin, &cb_data);
551 if (transfer_pin) UI_destroy_method(transfer_pin);
554 dbglog( "Loading private key '%s' from engine", pkey_identifier );
555 pkey = ENGINE_load_private_key(pkey_engine, pkey_identifier, NULL, NULL);
559 dbglog( "Got the private key, adding it to SSL context" );
560 if (SSL_CTX_use_PrivateKey(ctx, pkey) <= 0)
562 error("EAP-TLS: Cannot use PKCS11 key %s", pkey_identifier);
568 warn("EAP-TLS: Cannot load PKCS11 key %s", pkey_identifier);
575 if (!SSL_CTX_use_PrivateKey_file(ctx, privkeyfile, SSL_FILETYPE_PEM))
577 error("EAP-TLS: Cannot use private key %s", privkeyfile);
582 if (SSL_CTX_check_private_key(ctx) != 1) {
583 error("EAP-TLS: Private key %s fails security check", privkeyfile);
587 /* Explicitly set the NO_TICKETS flag to support Win7/Win8 clients */
588 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3
589 #ifdef SSL_OP_NO_TICKET
594 /* OpenSSL 1.1.1+ does not include RC4 ciphers by default.
595 * This causes totally obsolete WinXP clients to fail. If you really
596 * need ppp+EAP-TLS+openssl 1.1.1+WinXP then enable RC4 cipers and
597 * make sure that you use an OpenSSL that supports them
599 SSL_CTX_set_cipher_list(ctx, "RC4");
603 /* Set up a SSL Session cache with a callback. This is needed for TLSv1.3+.
604 * During the initial handshake the server signals to the client early on
605 * that the handshake is finished, even before the client has sent its
606 * credentials to the server. The actual connection (and moment that the
607 * client sends its credentials) only starts after the arrival of the first
608 * session ticket. The 'ssl_new_session_cb' catches this ticket.
610 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
611 SSL_CTX_sess_set_new_cb(ctx, ssl_new_session_cb);
613 /* As EAP-TLS+TLSv1.3 is highly experimental we offer the user a chance to override */
616 if (strncmp(max_tls_version, "1.0", 3) == 0)
617 tls_version = TLS1_VERSION;
618 else if (strncmp(max_tls_version, "1.1", 3) == 0)
619 tls_version = TLS1_1_VERSION;
620 else if (strncmp(max_tls_version, "1.2", 3) == 0)
621 #ifdef TLS1_2_VERSION
622 tls_version = TLS1_2_VERSION;
625 warn("TLSv1.2 not available. Defaulting to TLSv1.1");
626 tls_version = TLS_1_1_VERSION;
629 else if (strncmp(max_tls_version, "1.3", 3) == 0)
630 #ifdef TLS1_3_VERSION
631 tls_version = TLS1_3_VERSION;
633 warn("TLSv1.3 not available.");
637 dbglog("EAP-TLS: Setting max protocol version to 0x%X", tls_version);
638 SSL_CTX_set_max_proto_version(ctx, tls_version);
640 SSL_CTX_set_verify_depth(ctx, 5);
641 SSL_CTX_set_verify(ctx,
643 SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
644 &ssl_verify_callback);
647 if (!(certstore = SSL_CTX_get_cert_store(ctx))) {
648 error("EAP-TLS: Failed to get certificate store");
653 X509_STORE_add_lookup(certstore, X509_LOOKUP_hash_dir()))) {
654 error("EAP-TLS: Store lookup for CRL failed");
659 X509_LOOKUP_add_dir(lookup, crl_dir, X509_FILETYPE_PEM);
660 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
665 X509_CRL *crl = NULL;
667 fp = fopen(crl_file, "r");
669 error("EAP-TLS: Cannot open CRL file '%s'", crl_file);
673 crl = PEM_read_X509_CRL(fp, NULL, NULL, NULL);
675 error("EAP-TLS: Cannot read CRL file '%s'", crl_file);
679 if (!(certstore = SSL_CTX_get_cert_store(ctx))) {
680 error("EAP-TLS: Failed to get certificate store");
683 if (!X509_STORE_add_crl(certstore, crl)) {
684 error("EAP-TLS: Cannot add CRL to certificate store");
687 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
692 * If a peer certificate file was specified, it must be valid, else fail
694 if (peer_certfile[0]) {
695 if (!(tmp = get_X509_from_file(peer_certfile))) {
696 error("EAP-TLS: Error loading client certificate from file %s",
712 * Determine the maximum packet size by looking at the LCP handshake
715 int eaptls_get_mtu(int unit)
719 lcp_options *wo = &lcp_wantoptions[unit];
720 lcp_options *go = &lcp_gotoptions[unit];
721 lcp_options *ho = &lcp_hisoptions[unit];
722 lcp_options *ao = &lcp_allowoptions[unit];
724 mtu = ho->neg_mru? ho->mru: PPP_MRU;
725 mru = go->neg_mru? MAX(wo->mru, go->mru): PPP_MRU;
726 mtu = MIN(MIN(mtu, mru), ao->mru)- PPP_HDRLEN - 10;
728 dbglog("MTU = %d", mtu);
734 * Init the ssl handshake (server mode)
736 int eaptls_init_ssl_server(eap_state * esp)
738 struct eaptls_session *ets;
739 char servcertfile[MAXWORDLEN];
740 char clicertfile[MAXWORDLEN];
741 char cacertfile[MAXWORDLEN];
742 char capath[MAXWORDLEN];
743 char pkfile[MAXWORDLEN];
745 * Allocate new eaptls session
747 esp->es_server.ea_session = malloc(sizeof(struct eaptls_session));
748 if (!esp->es_server.ea_session)
749 fatal("Allocation error");
750 ets = esp->es_server.ea_session;
753 if (!esp->es_server.ea_peer) {
754 error("EAP-TLS: Error: client name not set (BUG)");
758 strlcpy(ets->peer, esp->es_server.ea_peer, MAXWORDLEN-1);
760 dbglog( "getting eaptls secret" );
761 if (!get_eaptls_secret(esp->es_unit, esp->es_server.ea_peer,
762 esp->es_server.ea_name, clicertfile,
763 servcertfile, cacertfile, capath, pkfile, 1)) {
764 error( "EAP-TLS: Cannot get secret/password for client \"%s\", server \"%s\"",
765 esp->es_server.ea_peer, esp->es_server.ea_name );
769 ets->mtu = eaptls_get_mtu(esp->es_unit);
771 ets->ctx = eaptls_init_ssl(1, cacertfile, capath, servcertfile, clicertfile, pkfile);
775 if (!(ets->ssl = SSL_new(ets->ctx)))
779 * Set auto-retry to avoid timeouts on BIO_read
781 SSL_set_mode(ets->ssl, SSL_MODE_AUTO_RETRY);
784 * Initialize the BIOs we use to read/write to ssl engine
786 ets->into_ssl = BIO_new(BIO_s_mem());
787 ets->from_ssl = BIO_new(BIO_s_mem());
788 SSL_set_bio(ets->ssl, ets->into_ssl, ets->from_ssl);
790 SSL_set_msg_callback(ets->ssl, ssl_msg_callback);
791 SSL_set_msg_callback_arg(ets->ssl, ets);
794 * Attach the session struct to the connection, so we can later
795 * retrieve it when doing certificate verification
797 SSL_set_ex_data(ets->ssl, 0, ets);
799 SSL_set_accept_state(ets->ssl);
809 * If we specified the client certificate file, store it in ets->peercertfile,
810 * so we can check it later in ssl_verify_callback()
813 strlcpy(&ets->peercertfile[0], clicertfile, MAXWORDLEN);
815 ets->peercertfile[0] = 0;
820 SSL_CTX_free(ets->ctx);
825 * Init the ssl handshake (client mode)
827 int eaptls_init_ssl_client(eap_state * esp)
829 struct eaptls_session *ets;
830 char servcertfile[MAXWORDLEN];
831 char clicertfile[MAXWORDLEN];
832 char cacertfile[MAXWORDLEN];
833 char capath[MAXWORDLEN];
834 char pkfile[MAXWORDLEN];
837 * Allocate new eaptls session
839 esp->es_client.ea_session = malloc(sizeof(struct eaptls_session));
840 if (!esp->es_client.ea_session)
841 fatal("Allocation error");
842 ets = esp->es_client.ea_session;
846 * If available, copy server name in ets; it will be used in cert
849 if (esp->es_client.ea_peer)
850 strlcpy(ets->peer, esp->es_client.ea_peer, MAXWORDLEN-1);
854 ets->mtu = eaptls_get_mtu(esp->es_unit);
856 dbglog( "calling get_eaptls_secret" );
857 if (!get_eaptls_secret(esp->es_unit, esp->es_client.ea_name,
858 ets->peer, clicertfile,
859 servcertfile, cacertfile, capath, pkfile, 0)) {
860 error( "EAP-TLS: Cannot get secret/password for client \"%s\", server \"%s\"",
861 esp->es_client.ea_name, ets->peer );
865 dbglog( "calling eaptls_init_ssl" );
866 ets->ctx = eaptls_init_ssl(0, cacertfile, capath, clicertfile, servcertfile, pkfile);
870 ets->ssl = SSL_new(ets->ctx);
876 * Initialize the BIOs we use to read/write to ssl engine
878 dbglog( "Initializing SSL BIOs" );
879 ets->into_ssl = BIO_new(BIO_s_mem());
880 ets->from_ssl = BIO_new(BIO_s_mem());
881 SSL_set_bio(ets->ssl, ets->into_ssl, ets->from_ssl);
883 SSL_set_msg_callback(ets->ssl, ssl_msg_callback);
884 SSL_set_msg_callback_arg(ets->ssl, ets);
887 * Attach the session struct to the connection, so we can later
888 * retrieve it when doing certificate verification
890 SSL_set_ex_data(ets->ssl, 0, ets);
892 SSL_set_connect_state(ets->ssl);
902 * If we specified the server certificate file, store it in
903 * ets->peercertfile, so we can check it later in
904 * ssl_verify_callback()
907 strlcpy(ets->peercertfile, servcertfile, MAXWORDLEN);
909 ets->peercertfile[0] = 0;
914 dbglog( "eaptls_init_ssl_client: fail" );
915 SSL_CTX_free(ets->ctx);
920 void eaptls_free_session(struct eaptls_session *ets)
926 SSL_CTX_free(ets->ctx);
932 int eaptls_is_init_finished(struct eaptls_session *ets)
934 if (ets->ssl && SSL_is_init_finished(ets->ssl))
937 return have_session_ticket;
946 * Handle a received packet, reassembling fragmented messages and
947 * passing them to the ssl engine
949 int eaptls_receive(struct eaptls_session *ets, u_char * inp, int len)
956 warn("EAP-TLS: received no or invalid data");
963 if (flags & EAP_TLS_FLAGS_LI && len > 4) {
965 * LenghtIncluded flag set -> this is the first packet of a message
969 * the first 4 octets are the length of the EAP-TLS message
971 GETLONG(tlslen, inp);
976 if (tlslen > EAP_TLS_MAX_LEN) {
977 error("EAP-TLS: TLS message length > %d, truncated", EAP_TLS_MAX_LEN);
978 tlslen = EAP_TLS_MAX_LEN;
982 * Allocate memory for the whole message
984 ets->data = malloc(tlslen);
986 fatal("EAP-TLS: allocation error\n");
989 ets->tlslen = tlslen;
992 warn("EAP-TLS: non-first LI packet? that's odd...");
994 else if (!ets->data) {
996 * A non fragmented message without LI flag
999 ets->data = malloc(len);
1001 fatal("EAP-TLS: memory allocation error in eaptls_receive\n");
1007 if (flags & EAP_TLS_FLAGS_MF)
1013 warn("EAP-TLS: received malformed data");
1017 if (len + ets->datalen > ets->tlslen) {
1018 warn("EAP-TLS: received data > TLS message length");
1022 BCOPY(inp, ets->data + ets->datalen, len);
1023 ets->datalen += len;
1028 * If we have the whole message, pass it to ssl
1031 if (ets->datalen != ets->tlslen) {
1032 warn("EAP-TLS: received data != TLS message length");
1036 if (BIO_write(ets->into_ssl, ets->data, ets->datalen) == -1)
1039 SSL_read(ets->ssl, dummy, 65536);
1050 * Return an eap-tls packet in outp.
1051 * A TLS message read from the ssl engine is buffered in ets->data.
1052 * At each call we control if there is buffered data and send a
1053 * packet of mtu bytes.
1055 int eaptls_send(struct eaptls_session *ets, u_char ** outp)
1059 u_char fromtls[65536];
1067 if(!ets->alert_sent)
1069 res = SSL_read(ets->ssl, fromtls, 65536);
1075 if ((res = BIO_read(ets->from_ssl, fromtls, 65536)) == -1)
1077 warn("EAP-TLS send: No data from BIO_read");
1083 ets->data = malloc(ets->datalen);
1085 fatal("EAP-TLS: memory allocation error in eaptls_send\n");
1087 BCOPY(fromtls, ets->data, ets->datalen);
1093 size = ets->datalen - ets->offset;
1095 if (size > ets->mtu) {
1101 PUTCHAR(EAPT_TLS, *outp);
1104 * Set right flags and length if necessary
1106 if (ets->frag && first) {
1107 PUTCHAR(EAP_TLS_FLAGS_LI | EAP_TLS_FLAGS_MF, *outp);
1108 PUTLONG(ets->datalen, *outp);
1109 } else if (ets->frag) {
1110 PUTCHAR(EAP_TLS_FLAGS_MF, *outp);
1115 * Copy the data in outp
1117 BCOPY(ets->data + ets->offset, *outp, size);
1118 INCPTR(size, *outp);
1121 * Copy the packet in retransmission buffer
1123 BCOPY(start, &ets->rtx[0], *outp - start);
1124 ets->rtx_len = *outp - start;
1126 ets->offset += size;
1128 if (ets->offset >= ets->datalen) {
1131 * The whole message has been sent
1144 * Get the sent packet from the retransmission buffer
1146 void eaptls_retransmit(struct eaptls_session *ets, u_char ** outp)
1148 BCOPY(ets->rtx, *outp, ets->rtx_len);
1149 INCPTR(ets->rtx_len, *outp);
1153 * Verify a certificate.
1154 * Most of the work (signatures and issuer attributes checking)
1155 * is done by ssl; we check the CN in the peer certificate
1156 * against the peer name.
1158 int ssl_verify_callback(int ok, X509_STORE_CTX * ctx)
1165 struct eaptls_session *ets;
1166 char *ptr1 = NULL, *ptr2 = NULL;
1168 peer_cert = X509_STORE_CTX_get_current_cert(ctx);
1169 err = X509_STORE_CTX_get_error(ctx);
1170 depth = X509_STORE_CTX_get_error_depth(ctx);
1172 dbglog("certificate verify depth: %d", depth);
1174 if (auth_required && !ok) {
1175 X509_NAME_oneline(X509_get_subject_name(peer_cert),
1178 X509_NAME_get_text_by_NID(X509_get_subject_name(peer_cert),
1179 NID_commonName, cn_str, 256);
1181 dbglog("Certificate verification error:\n depth: %d CN: %s"
1182 "\n err: %d (%s)\n", depth, cn_str, err,
1183 X509_verify_cert_error_string(err));
1188 ssl = X509_STORE_CTX_get_ex_data(ctx,
1189 SSL_get_ex_data_X509_STORE_CTX_idx());
1191 ets = (struct eaptls_session *)SSL_get_ex_data(ssl, 0);
1194 error("Error: SSL_get_ex_data returned NULL");
1202 /* Verify certificate based on certificate type and extended key usage */
1203 if (tls_verify_key_usage) {
1204 int purpose = ets->client ? X509_PURPOSE_SSL_SERVER : X509_PURPOSE_SSL_CLIENT ;
1205 if (X509_check_purpose(peer_cert, purpose, 0) == 0) {
1206 error("Certificate verification error: nsCertType mismatch");
1210 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1211 int flags = ets->client ? XKU_SSL_SERVER : XKU_SSL_CLIENT;
1212 if (!(X509_get_extended_key_usage(peer_cert) & flags)) {
1213 error("Certificate verification error: invalid extended key usage");
1217 info("Certificate key usage: OK");
1221 * If acting as client and the name of the server wasn't specified
1222 * explicitely, we can't verify the server authenticity
1224 if (!tls_verify_method)
1225 tls_verify_method = TLS_VERIFY_NONE;
1227 if (!ets->peer[0] || !strcmp(TLS_VERIFY_NONE, tls_verify_method)) {
1228 warn("Certificate verication disabled or no peer name was specified");
1232 /* This is the peer certificate */
1233 X509_NAME_oneline(X509_get_subject_name(peer_cert),
1236 X509_NAME_get_text_by_NID(X509_get_subject_name(peer_cert),
1237 NID_commonName, cn_str, 256);
1239 /* Verify based on subject name */
1241 if (!strcmp(TLS_VERIFY_SUBJECT, tls_verify_method)) {
1245 /* Verify based on common name (default) */
1246 if (strlen(tls_verify_method) == 0 ||
1247 !strcmp(TLS_VERIFY_NAME, tls_verify_method)) {
1251 /* Match the suffix of common name */
1252 if (!strcmp(TLS_VERIFY_SUFFIX, tls_verify_method)) {
1253 int len = strlen(ptr1);
1254 int off = strlen(cn_str) - len;
1257 ptr2 = cn_str + off;
1261 if (strcmp(ptr1, ptr2)) {
1262 error("Certificate verification error: CN (%s) != %s", ptr1, ptr2);
1266 info("Certificate CN: %s, peer name %s", cn_str, ets->peer);
1269 * If a peer certificate file was specified, here we check it
1271 if (ets->peercertfile[0]) {
1272 if (ssl_cmp_certs(&ets->peercertfile[0], peer_cert)
1275 ("Peer certificate doesn't match stored certificate");
1285 * Compare a certificate with the one stored in a file
1287 int ssl_cmp_certs(char *filename, X509 * a)
1292 if (!(b = get_X509_from_file(filename)))
1295 ret = X509_cmp(a, b);
1302 X509 *get_X509_from_file(char *filename)
1307 if (!(fp = fopen(filename, "r")))
1310 ret = PEM_read_X509(fp, NULL, NULL, NULL);
1318 * Every sent & received message this callback function is invoked,
1319 * so we know when alert messages have arrived or are sent and
1320 * we can print debug information about TLS handshake.
1323 ssl_msg_callback(int write_p, int version, int content_type,
1324 const void *buf, size_t len, SSL * ssl, void *arg)
1327 struct eaptls_session *ets = (struct eaptls_session *)arg;
1329 const unsigned char*msg = buf;
1330 int hvers = msg[1] << 8 | msg[2];
1333 strcpy(string, " -> ");
1335 strcpy(string, " <- ");
1337 switch(content_type) {
1339 case SSL3_RT_HEADER:
1340 strcat(string, "SSL/TLS Header: ");
1343 strcat(string, "SSL 3.0");
1346 strcat(string, "TLS 1.0");
1348 case TLS1_1_VERSION:
1349 strcat(string, "TLS 1.1");
1351 case TLS1_2_VERSION:
1352 strcat(string, "TLS 1.2");
1355 sprintf(string, "SSL/TLS Header: Unknown version (%d)", hvers);
1360 strcat(string, "Alert: ");
1364 ets->alert_sent = 1;
1365 ets->alert_sent_desc = code;
1367 ets->alert_recv = 1;
1368 ets->alert_recv_desc = code;
1371 strcat(string, SSL_alert_desc_string_long(code));
1374 case SSL3_RT_CHANGE_CIPHER_SPEC:
1375 strcat(string, "ChangeCipherSpec");
1378 #ifdef SSL3_RT_INNER_CONTENT_TYPE
1379 case SSL3_RT_INNER_CONTENT_TYPE:
1380 strcat(string, "InnerContentType (TLS1.3)");
1384 case SSL3_RT_HANDSHAKE:
1386 strcat(string, "Handshake: ");
1390 case SSL3_MT_HELLO_REQUEST:
1391 strcat(string,"Hello Request");
1393 case SSL3_MT_CLIENT_HELLO:
1394 strcat(string,"Client Hello");
1396 case SSL3_MT_SERVER_HELLO:
1397 strcat(string,"Server Hello");
1399 #ifdef SSL3_MT_NEWSESSION_TICKET
1400 case SSL3_MT_NEWSESSION_TICKET:
1401 strcat(string,"New Session Ticket");
1404 #ifdef SSL3_MT_END_OF_EARLY_DATA
1405 case SSL3_MT_END_OF_EARLY_DATA:
1406 strcat(string,"End of Early Data");
1409 #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
1410 case SSL3_MT_ENCRYPTED_EXTENSIONS:
1411 strcat(string,"Encryped Extensions");
1414 case SSL3_MT_CERTIFICATE:
1415 strcat(string,"Certificate");
1417 case SSL3_MT_SERVER_KEY_EXCHANGE:
1418 strcat(string,"Server Key Exchange");
1420 case SSL3_MT_CERTIFICATE_REQUEST:
1421 strcat(string,"Certificate Request");
1423 case SSL3_MT_SERVER_DONE:
1424 strcat(string,"Server Hello Done");
1426 case SSL3_MT_CERTIFICATE_VERIFY:
1427 strcat(string,"Certificate Verify");
1429 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1430 strcat(string,"Client Key Exchange");
1432 case SSL3_MT_FINISHED:
1433 strcat(string,"Finished: ");
1434 hvers = SSL_version(ssl);
1437 strcat(string, "SSL 3.0");
1440 strcat(string, "TLS 1.0");
1442 case TLS1_1_VERSION:
1443 strcat(string, "TLS 1.1");
1445 case TLS1_2_VERSION:
1446 strcat(string, "TLS 1.2");
1448 #ifdef TLS1_3_VERSION
1449 case TLS1_3_VERSION:
1450 strcat(string, "TLS 1.3 (experimental)");
1455 strcat(string, "Unknown version");
1459 sprintf( string, "Handshake: Unknown SSL3 code received: %d", code );
1464 sprintf( string, "SSL message contains unknown content type: %d", content_type );
1467 /* Alert messages must always be displayed */
1468 if(content_type == SSL3_RT_ALERT)
1469 error("%s", string);
1471 dbglog("%s", string);
1475 ssl_new_session_cb(SSL *s, SSL_SESSION *sess)
1477 dbglog("EAP-TLS: Post-Handshake New Session Ticket arrived:");
1478 have_session_ticket = 1;
1480 /* always return success */