summaryrefslogtreecommitdiff
path: root/pppd/eap-tls.c
blob: d70557ee7b189d8921ba58af0888c3c662ba4765 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
/* * eap-tls.c - EAP-TLS implementation for PPP
 *
 * Copyright (c) Beniamino Galvani 2005 All rights reserved.
 *               Jan Just Keijser  2006-2019 All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The name(s) of the authors of this software must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission.
 *
 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <openssl/conf.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif
#include <openssl/ssl.h>
#include <openssl/hmac.h>
#include <openssl/err.h>
#include <openssl/ui.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>

#include "pppd-private.h"
#include "tls.h"
#include "eap.h"
#include "eap-tls.h"
#include "fsm.h"
#include "lcp.h"
#include "chap_ms.h"
#include "mppe.h"
#include "pathnames.h"

#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
#define SSL3_RT_HEADER  0x100
#endif

typedef struct pw_cb_data
{
    const void *password;
    const char *prompt_info;
} PW_CB_DATA;

#ifndef OPENSSL_NO_ENGINE
/* The openssl configuration file and engines can be loaded only once */
static CONF   *ssl_config  = NULL;
static ENGINE *cert_engine = NULL;
static ENGINE *pkey_engine = NULL;
#endif

/* TLSv1.3 do we have a session ticket ? */
static int have_session_ticket = 0;

void ssl_msg_callback(int write_p, int version, int ct, const void *buf,
              size_t len, SSL * ssl, void *arg);
int ssl_new_session_cb(SSL *s, SSL_SESSION *sess);

#ifdef PPP_WITH_MPPE
#define EAPTLS_MPPE_KEY_LEN     32

/*
 *  Generate keys according to RFC 2716 and add to reply
 */
void eaptls_gen_mppe_keys(struct eaptls_session *ets, int client)
{
    unsigned char  out[4*EAPTLS_MPPE_KEY_LEN];
    const char    *prf_label;
    size_t         prf_size;
    unsigned char  eap_tls13_context[] = { EAPT_TLS };
    unsigned char *context = NULL;
    size_t         context_len = 0;
    unsigned char *p;

    dbglog("EAP-TLS generating MPPE keys");
    if (ets->tls_v13)
    {
        prf_label = "EXPORTER_EAP_TLS_Key_Material";
        context   = eap_tls13_context;
        context_len = 1;
    }
    else
    {
        prf_label = "client EAP encryption";
    }

    dbglog("EAP-TLS PRF label = %s", prf_label);
    prf_size = strlen(prf_label);
    if (SSL_export_keying_material(ets->ssl, out, sizeof(out), prf_label, prf_size, 
                                   context, context_len, 0) != 1)
    {
        warn( "EAP-TLS: Failed generating keying material" );
        return;
    }   

    /* 
     * We now have the master send and receive keys.
     * From these, generate the session send and receive keys.
     * (see RFC3079 / draft-ietf-pppext-mppe-keys-03.txt for details)
     */
    if (client)
    {
        mppe_set_keys(out, out + EAPTLS_MPPE_KEY_LEN, EAPTLS_MPPE_KEY_LEN);
    }
    else
    {
        mppe_set_keys(out + EAPTLS_MPPE_KEY_LEN, out, EAPTLS_MPPE_KEY_LEN);
    }
}

#endif /* PPP_WITH_MPPE */

int password_callback (char *buf, int size, int rwflag, void *u)
{
    if (buf)
    {
        strlcpy (buf, passwd, size);
        return strlen (buf);
    }
    return 0;
}


CONF *eaptls_ssl_load_config( void )
{
    CONF        *config;
    int          ret_code;
    long         error_line = 33;

    config = NCONF_new( NULL );
    dbglog( "Loading OpenSSL config file" );
    ret_code = NCONF_load( config, PPP_PATH_OPENSSLCONFFILE, &error_line );
    if (ret_code == 0)
    {
        warn( "EAP-TLS: Error in OpenSSL config file %s at line %d", PPP_PATH_OPENSSLCONFFILE, error_line );
        NCONF_free( config );
        config = NULL;
        ERR_clear_error();
    }

    dbglog( "Loading OpenSSL built-ins" );
#ifndef OPENSSL_NO_ENGINE
    ENGINE_load_builtin_engines();
#endif
    OPENSSL_load_builtin_modules();
   
    dbglog( "Loading OpenSSL configured modules" );
    if (CONF_modules_load( config, NULL, 0 ) <= 0 )
    {
        warn( "EAP-TLS: Error loading OpenSSL modules" );
        tls_log_sslerr();
        config = NULL;
    }

    return config;
}

#ifndef OPENSSL_NO_ENGINE
ENGINE *eaptls_ssl_load_engine( char *engine_name )
{
    ENGINE      *e = NULL;

    dbglog( "Enabling OpenSSL auto engines" );
    ENGINE_register_all_complete();

    dbglog( "Loading OpenSSL '%s' engine support", engine_name );
    e = ENGINE_by_id( engine_name );
    if (!e) 
    {
        dbglog( "EAP-TLS: Cannot load '%s' engine support, trying 'dynamic'", engine_name );
        e = ENGINE_by_id( "dynamic" );
        if (e)
        {
            if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine_name, 0)
             || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
            {
                warn( "EAP-TLS: Error loading dynamic engine '%s'", engine_name );
                tls_log_sslerr();
                ENGINE_free(e);
                e = NULL;
            }
        }
        else
        {
            warn( "EAP-TLS: Cannot load dynamic engine support" );
        }
    }

    if (e)
    {
        dbglog( "Initialising engine" );
        if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
        {
            warn( "EAP-TLS: Cannot use that engine" );
            tls_log_sslerr();
            ENGINE_free(e);
            e = NULL;
        }
    }

    return e;
}
#endif


#ifndef OPENSSL_NO_ENGINE
static int eaptls_UI_writer(UI *ui, UI_STRING *uis)
{
    PW_CB_DATA* cb_data = (PW_CB_DATA*)UI_get0_user_data(ui);
    UI_set_result(ui, uis, cb_data->password);
    return 1;
}

static int eaptls_UI_stub(UI* ui) {
    return 1;
}

static int eaptls_UI_reader(UI *ui, UI_STRING *uis) {
    return 1;
}
#endif

/*
 * Initialize the SSL stacks and tests if certificates, key and crl
 * for client or server use can be loaded.
 */
SSL_CTX *eaptls_init_ssl(int init_server, char *cacertfile, char *capath,
            char *certfile, char *privkeyfile, char *pkcs12)
{
#ifndef OPENSSL_NO_ENGINE
    char        *cert_engine_name = NULL;
    char        *pkey_engine_name = NULL;
    char        *idx;
#endif
    SSL_CTX     *ctx;
    SSL         *ssl;
    X509        *tmp;
    X509        *cert = NULL;
    PKCS12      *p12 = NULL;
    EVP_PKEY    *pkey = NULL;
    STACK_OF(X509) *chain = NULL;
    BIO         *input;
    int          ret;
    int          reason;

    /*
     * Without these can't continue 
     */
    if (!pkcs12[0]) 
    {
        if (!(cacertfile[0] || capath[0]))
        {
            error("EAP-TLS: CA certificate file or path missing");
            return NULL;
        }

        if (!certfile[0])
        {
            error("EAP-TLS: Certificate missing");
            return NULL;
        }

        if (!privkeyfile[0])
        {
            error("EAP-TLS: Private key missing");
            return NULL;
        }
    }

    tls_init();

#ifndef OPENSSL_NO_ENGINE
    /* load the openssl config file only once and load it before triggering
       the loading of a global openssl config file via SSL_CTX_new()
     */
    if (!ssl_config)
        ssl_config = eaptls_ssl_load_config();
#endif

    ctx = SSL_CTX_new(tls_method());
    if (!ctx) {
        error("EAP-TLS: Cannot initialize SSL CTX context");
        goto fail;
    }

#ifndef OPENSSL_NO_ENGINE
    /* if the certificate filename is of the form engine:id. e.g.
        pkcs11:12345
       then we try to load and use this engine.
       If the certificate filename starts with a / or . then we
       ALWAYS assume it is a file and not an engine/pkcs11 identifier
     */
    if ( (idx = index( certfile, ':' )) != NULL )
    {
        cert_engine_name = strdup( certfile );
        cert_engine_name[idx - certfile] = 0;

        dbglog( "Using engine '%s' for certificate, URI: '%s'",
                cert_engine_name, certfile );
    }

    /* if the privatekey filename is of the form engine:id. e.g.
        pkcs11:12345
       then we try to load and use this engine.
       If the privatekey filename starts with a / or . then we
       ALWAYS assume it is a file and not an engine/pkcs11 identifier
     */
    if ( (idx = index( privkeyfile, ':' )) != NULL )
    {
        pkey_engine_name = strdup( privkeyfile );
        pkey_engine_name[idx - privkeyfile] = 0;

        dbglog( "Using engine '%s' for private key, URI: '%s'",
                pkey_engine_name, privkeyfile );
    }

    if (cert_engine_name && pkey_engine_name)
    {
        if (strlen( certfile ) - strlen( cert_engine_name ) == 1)
        {
            if (strlen( privkeyfile ) - strlen( pkey_engine_name ) == 1)
                error( "EAP-TLS: both the certificate and privatekey identifiers are missing!" );
            else
            {
                dbglog( "Substituting privatekey identifier for certificate identifier" );
                certfile = privkeyfile;
            }
        }
        else
        {
            if (strlen( privkeyfile ) - strlen( pkey_engine_name ) == 1)
            {
                dbglog( "Substituting certificate identifier for privatekey identifier" );
                privkeyfile = certfile;
            }
        }
    }

    if (ssl_config && cert_engine_name)
        cert_engine = eaptls_ssl_load_engine( cert_engine_name );

    if (ssl_config && pkey_engine_name)
    {
        /* don't load the same engine twice */
        if ( cert_engine && strcmp( cert_engine_name, pkey_engine_name) == 0 )
            pkey_engine = cert_engine;
        else
            pkey_engine = eaptls_ssl_load_engine( pkey_engine_name );
    }

    if (cert_engine_name)
        free(cert_engine_name);

    if (pkey_engine_name)
        free(pkey_engine_name);

#endif

    SSL_CTX_set_default_passwd_cb (ctx, password_callback);

    if (tls_set_ca(ctx, capath, cacertfile) != 0) {
        goto fail;
    }

    if (init_server)
        SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(cacertfile));

#ifndef OPENSSL_NO_ENGINE
    if (cert_engine)
    {
        struct
        {
            const char *s_slot_cert_id;
            X509 *cert;
        } cert_info;

        cert_info.s_slot_cert_id = certfile;
        cert_info.cert = NULL;
        
        if (!ENGINE_ctrl_cmd( cert_engine, "LOAD_CERT_CTRL", 0, &cert_info, NULL, 0 ) )
        {
            error( "EAP-TLS: Error loading certificate with URI '%s' from engine", certfile );
            goto fail;
        }

        if (cert_info.cert)
        {
            dbglog( "Got the certificate" );
            dbglog( "subject = %s", X509_NAME_oneline( X509_get_subject_name( cert_info.cert ), NULL, 0 ) );
            cert = cert_info.cert;
        }
        else
        {
            warn("EAP-TLS: Cannot load key with URI: '%s'", certfile );
            tls_log_sslerr();
        }
    }
    else
#endif
    {
        if (pkcs12[0])
        {
            input = BIO_new_file(pkcs12, "r");
            if (input == NULL)
            {
                error("EAP-TLS: Cannot open `%s' PKCS12 for input", pkcs12);
                goto fail;
            }

            p12 = d2i_PKCS12_bio(input, NULL);
            BIO_free(input);
            if (!p12)
            {
                error("EAP-TLS: Cannot load PKCS12 certificate");
                goto fail;
            }

            if (PKCS12_parse(p12, passwd, &pkey, &cert, &chain) != 1)
            {
                error("EAP-TLS: Cannot parse PKCS12 certificate, invalid password");
                PKCS12_free(p12);
                goto fail;
            }

            PKCS12_free(p12);
        }
        else 
        {
            if (!SSL_CTX_use_certificate_chain_file(ctx, certfile))
            {
                error( "EAP-TLS: Cannot load certificate %s", certfile );
                goto fail;
            }
        }
    }

    if (cert)
    {
        if (!SSL_CTX_use_certificate(ctx, cert))
        {
            error("EAP-TLS: Cannot use load certificate");
            goto fail;
        }

        if (chain)
        {
            int i;
            for (i = 0; i < sk_X509_num(chain); i++)
            {
                if (!SSL_CTX_add_extra_chain_cert(ctx, sk_X509_value(chain, i)))
                {
                    error("EAP-TLS: Cannot add extra chain certificate");
                    goto fail;
                }
            }
        }
    }

    /*
     *  Check the Before and After dates of the certificate
     */
    ssl = SSL_new(ctx);
    tmp = SSL_get_certificate(ssl);

    ret = X509_cmp_time(X509_get_notBefore(tmp), NULL);
    if (ret == 0)
    {    
        warn( "EAP-TLS: Failed to read certificate notBefore field.");
    }    
    if (ret > 0) 
    {    
        warn( "EAP-TLS: Your certificate is not yet valid!");
    }    

    ret = X509_cmp_time(X509_get_notAfter(tmp), NULL);
    if (ret == 0)
    {    
        warn( "EAP-TLS: Failed to read certificate notAfter field.");
    }    
    if (ret < 0)
    {
        warn( "EAP-TLS: Your certificate has expired!");
    }
    SSL_free(ssl);

#ifndef OPENSSL_NO_ENGINE
    if (pkey_engine)
    {
        PW_CB_DATA  cb_data;

        cb_data.password = passwd;
        cb_data.prompt_info = privkeyfile;

        if (passwd[0] != 0)
        {
            UI_METHOD* transfer_pin = UI_create_method("transfer_pin");

            UI_method_set_writer(transfer_pin,  eaptls_UI_writer);
            UI_method_set_opener(transfer_pin,  eaptls_UI_stub);
            UI_method_set_closer(transfer_pin,  eaptls_UI_stub);
            UI_method_set_flusher(transfer_pin, eaptls_UI_stub);
            UI_method_set_reader(transfer_pin,  eaptls_UI_reader);

            dbglog( "Using our private key URI: '%s' in engine", privkeyfile );
            pkey = ENGINE_load_private_key(pkey_engine, privkeyfile, transfer_pin, &cb_data);

            if (transfer_pin) UI_destroy_method(transfer_pin);
        }
        else {
            dbglog( "Loading private key URI: '%s' from engine", privkeyfile );
            pkey = ENGINE_load_private_key(pkey_engine, privkeyfile, NULL, NULL);
        }
    }
    else 
#endif
    {
        if (!pkey)
        {
            input = BIO_new_file(privkeyfile, "r");
            if (!input)
            {
                error("EAP-TLS: Could not open private key, %s", privkeyfile);
                goto fail;
            }

            pkey = PEM_read_bio_PrivateKey(input, NULL, password_callback, NULL);
            BIO_free(input);
            if (!pkey)
            {
                error("EAP-TLS: Cannot load private key, %s", privkeyfile);
                goto fail;
            }
        }
    }

    if (SSL_CTX_use_PrivateKey(ctx, pkey) != 1)
    {
        error("EAP-TLS: Cannot use private key");
        goto fail;
    }

    if (SSL_CTX_check_private_key(ctx) != 1)
    {
        error("EAP-TLS: Private key fails security check");
        goto fail;
    }

    /* Configure the default options */
    tls_set_opts(ctx);

    /* Set up a SSL Session cache with a callback. This is needed for TLSv1.3+.
     * During the initial handshake the server signals to the client early on
     * that the handshake is finished, even before the client has sent its
     * credentials to the server. The actual connection (and moment that the
     * client sends its credentials) only starts after the arrival of the first
     * session ticket. The 'ssl_new_session_cb' catches this ticket.
     */
    SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
    SSL_CTX_sess_set_new_cb(ctx, ssl_new_session_cb);

    /* Configure the maximum SSL version */
    tls_set_version(ctx, max_tls_version);

    /* Configure the callback */
    if (tls_set_verify(ctx, 5)) {
        goto fail;
    }

    /* Configure CRL check (if any) */
    if (tls_set_crl(ctx, crl_dir, crl_file)) {
        goto fail;
    }

    return ctx;

fail:

    if (cert)
        X509_free(cert);

    if (pkey)
        EVP_PKEY_free(pkey);

    if (chain)
        sk_X509_pop_free(chain, X509_free);

    tls_log_sslerr();
    SSL_CTX_free(ctx);
    return NULL;
}

/*
 * Determine the maximum packet size by looking at the LCP handshake
 */

int eaptls_get_mtu(int unit)
{
    int mtu, mru;

    lcp_options *wo = &lcp_wantoptions[unit];
    lcp_options *go = &lcp_gotoptions[unit];
    lcp_options *ho = &lcp_hisoptions[unit];
    lcp_options *ao = &lcp_allowoptions[unit];

    mtu = ho->neg_mru? ho->mru: PPP_MRU;
    mru = go->neg_mru? MAX(wo->mru, go->mru): PPP_MRU;
    mtu = MIN(MIN(mtu, mru), ao->mru)- PPP_HDRLEN - 10;

    dbglog("MTU = %d", mtu);
    return mtu;
}


/*
 * Init the ssl handshake (server mode)
 */
int eaptls_init_ssl_server(eap_state * esp)
{
    struct eaptls_session *ets;
    char servcertfile[MAXWORDLEN];
    char clicertfile[MAXWORDLEN];
    char cacertfile[MAXWORDLEN];
    char capath[MAXWORDLEN];
    char pkfile[MAXWORDLEN];
    char pkcs12[MAXWORDLEN];

    /*
     * Allocate new eaptls session 
     */
    esp->es_server.ea_session = malloc(sizeof(struct eaptls_session));
    if (!esp->es_server.ea_session)
        fatal("Allocation error");
    ets = esp->es_server.ea_session;

    if (!esp->es_server.ea_peer) {
        error("EAP-TLS: Error: client name not set (BUG)");
        return 0;
    }

    dbglog( "getting eaptls secret" );
    if (!get_eaptls_secret(esp->es_unit, esp->es_server.ea_peer,
                   esp->es_server.ea_name, clicertfile,
                   servcertfile, cacertfile, capath, pkfile, pkcs12, 1)) {
        error( "EAP-TLS: Cannot get secret/password for client \"%s\", server \"%s\"",
                esp->es_server.ea_peer, esp->es_server.ea_name );
        return 0;
    }

    ets->mtu = eaptls_get_mtu(esp->es_unit);

    ets->ctx = eaptls_init_ssl(1, cacertfile, capath, servcertfile, pkfile, pkcs12);
    if (!ets->ctx)
        goto fail;

    if (!(ets->ssl = SSL_new(ets->ctx)))
        goto fail;

    if (tls_set_verify_info(ets->ssl, esp->es_server.ea_peer,
            clicertfile, 0, &ets->info))
        goto fail;

    /*
     * Set auto-retry to avoid timeouts on BIO_read
     */
    SSL_set_mode(ets->ssl, SSL_MODE_AUTO_RETRY);

    /*
     * Initialize the BIOs we use to read/write to ssl engine 
     */
    ets->into_ssl = BIO_new(BIO_s_mem());
    ets->from_ssl = BIO_new(BIO_s_mem());
    SSL_set_bio(ets->ssl, ets->into_ssl, ets->from_ssl);

    SSL_set_msg_callback(ets->ssl, ssl_msg_callback);
    SSL_set_msg_callback_arg(ets->ssl, ets);

    SSL_set_accept_state(ets->ssl);

    ets->tls_v13 = 0;

    ets->data = NULL;
    ets->datalen = 0;
    ets->alert_sent = 0;
    ets->alert_recv = 0;
    return 1;

fail:
    SSL_CTX_free(ets->ctx);
    return 0;
}

/*
 * Init the ssl handshake (client mode)
 */
int eaptls_init_ssl_client(eap_state * esp)
{
    struct eaptls_session *ets;
    char servcertfile[MAXWORDLEN];
    char clicertfile[MAXWORDLEN];
    char cacertfile[MAXWORDLEN];
    char capath[MAXWORDLEN];
    char pkfile[MAXWORDLEN];
    char pkcs12[MAXWORDLEN];

    /*
     * Allocate new eaptls session 
     */
    esp->es_client.ea_session = malloc(sizeof(struct eaptls_session));
    if (!esp->es_client.ea_session)
        fatal("Allocation error");
    ets = esp->es_client.ea_session;
    ets->mtu = eaptls_get_mtu(esp->es_unit);

    dbglog( "calling get_eaptls_secret" );
    if (!get_eaptls_secret(esp->es_unit, esp->es_client.ea_name,
                   esp->es_client.ea_peer, clicertfile,
                   servcertfile, cacertfile, capath, pkfile, pkcs12, 0)) {
        error( "EAP-TLS: Cannot get secret/password for client \"%s\", server \"%s\"",
                esp->es_client.ea_name, esp->es_client.ea_peer);
        return 0;
    }

    dbglog( "calling eaptls_init_ssl" );
    ets->ctx = eaptls_init_ssl(0, cacertfile, capath, clicertfile, pkfile, pkcs12);
    if (!ets->ctx)
        goto fail;

    ets->ssl = SSL_new(ets->ctx);
    if (!ets->ssl)
        goto fail;

    if (tls_set_verify_info(ets->ssl, esp->es_client.ea_peer,
            servcertfile, 0, &ets->info))
        goto fail;

    /*
     * Initialize the BIOs we use to read/write to ssl engine 
     */
    dbglog( "Initializing SSL BIOs" );
    ets->into_ssl = BIO_new(BIO_s_mem());
    ets->from_ssl = BIO_new(BIO_s_mem());
    SSL_set_bio(ets->ssl, ets->into_ssl, ets->from_ssl);

    SSL_set_msg_callback(ets->ssl, ssl_msg_callback);
    SSL_set_msg_callback_arg(ets->ssl, ets);
    SSL_set_connect_state(ets->ssl);

    ets->tls_v13 = 0;

    ets->data = NULL;
    ets->datalen = 0;
    ets->alert_sent = 0;
    ets->alert_recv = 0;
    return 1;

fail:
    dbglog( "eaptls_init_ssl_client: fail" );
    SSL_CTX_free(ets->ctx);
    return 0;

}

void eaptls_free_session(struct eaptls_session *ets)
{
    if (ets->ssl)
        SSL_free(ets->ssl);

    if (ets->ctx)
        SSL_CTX_free(ets->ctx);

    if (ets->info)
        tls_free_verify_info(&ets->info);

    free(ets);
}


int eaptls_is_init_finished(struct eaptls_session *ets)
{
    if (ets->ssl && SSL_is_init_finished(ets->ssl))
    {
        if (ets->tls_v13) 
            return have_session_ticket;
        else
            return 1;
    }

    return 0;
}

/*
 * Handle a received packet, reassembling fragmented messages and
 * passing them to the ssl engine
 */
int eaptls_receive(struct eaptls_session *ets, u_char * inp, int len)
{
    u_char flags;
    u_int tlslen = 0;
    u_char dummy[65536];

    if (len < 1) {
        warn("EAP-TLS: received no or invalid data");
        return 1;
    }
        
    GETCHAR(flags, inp);
    len--;

    if (flags & EAP_TLS_FLAGS_LI && len > 4) {
        /*
         * LenghtIncluded flag set -> this is the first packet of a message
        */

        /*
         * the first 4 octets are the length of the EAP-TLS message
         */
        GETLONG(tlslen, inp);
        len -= 4;

        if (!ets->data) {

            if (tlslen > EAP_TLS_MAX_LEN) {
                error("EAP-TLS: TLS message length > %d, truncated", EAP_TLS_MAX_LEN);
                tlslen = EAP_TLS_MAX_LEN;
            }

            /*
             * Allocate memory for the whole message
            */
            ets->data = malloc(tlslen);
            if (!ets->data)
                fatal("EAP-TLS: allocation error\n");

            ets->datalen = 0;
            ets->tlslen = tlslen;
        }
        else
            warn("EAP-TLS: non-first LI packet? that's odd...");
    }
    else if (!ets->data) {
        /*
         * A non fragmented message without LI flag
        */
 
        ets->data = malloc(len);
        if (!ets->data)
            fatal("EAP-TLS: memory allocation error in eaptls_receive\n");
 
        ets->datalen = 0;
        ets->tlslen = len;
    }

    if (flags & EAP_TLS_FLAGS_MF)
        ets->frag = 1;
    else
        ets->frag = 0;

    if (len < 0) {
        warn("EAP-TLS: received malformed data");
        return 1;
    }

    if (len + ets->datalen > ets->tlslen) {
        warn("EAP-TLS: received data > TLS message length");
        return 1;
    }

    BCOPY(inp, ets->data + ets->datalen, len);
    ets->datalen += len;

    if (!ets->frag) {

        /*
         * If we have the whole message, pass it to ssl 
         */

        if (ets->datalen != ets->tlslen) {
            warn("EAP-TLS: received data != TLS message length");
            return 1;
        }

        if (BIO_write(ets->into_ssl, ets->data, ets->datalen) == -1)
            tls_log_sslerr();

        SSL_read(ets->ssl, dummy, 65536);

        free(ets->data);
        ets->data = NULL;
        ets->datalen = 0;
    }

    return 0;
}

/*
 * Return an eap-tls packet in outp.
 * A TLS message read from the ssl engine is buffered in ets->data.
 * At each call we control if there is buffered data and send a 
 * packet of mtu bytes.
 */
int eaptls_send(struct eaptls_session *ets, u_char ** outp)
{
    bool first = 0;
    int size;
    u_char fromtls[65536];
    int res;
    u_char *start;

    start = *outp;

    if (!ets->data)
    {
        if(!ets->alert_sent)
        {
            res = SSL_read(ets->ssl, fromtls, 65536);
        }

        /*
         * Read from ssl 
         */
        if ((res = BIO_read(ets->from_ssl, fromtls, 65536)) == -1)
        {
            warn("EAP-TLS send: No data from BIO_read");
            return 1;
        }

        ets->datalen = res;

        ets->data = malloc(ets->datalen);
        if (!ets->data)
            fatal("EAP-TLS: memory allocation error in eaptls_send\n");

        BCOPY(fromtls, ets->data, ets->datalen);

        ets->offset = 0;
        first = 1;
    }

    size = ets->datalen - ets->offset;
    
    if (size > ets->mtu) {
        size = ets->mtu;
        ets->frag = 1;
    } else
        ets->frag = 0;

    PUTCHAR(EAPT_TLS, *outp);

    /*
     * Set right flags and length if necessary 
     */
    if (ets->frag && first) {
        PUTCHAR(EAP_TLS_FLAGS_LI | EAP_TLS_FLAGS_MF, *outp);
        PUTLONG(ets->datalen, *outp);
    } else if (ets->frag) {
        PUTCHAR(EAP_TLS_FLAGS_MF, *outp);
    } else
        PUTCHAR(0, *outp);

    /*
     * Copy the data in outp 
     */
    BCOPY(ets->data + ets->offset, *outp, size);
    INCPTR(size, *outp);

    /*
     * Copy the packet in retransmission buffer 
     */
    BCOPY(start, &ets->rtx[0], *outp - start);
    ets->rtx_len = *outp - start;

    ets->offset += size;

    if (ets->offset >= ets->datalen) {

        /*
         * The whole message has been sent 
         */

        free(ets->data);
        ets->data = NULL;
        ets->datalen = 0;
        ets->offset = 0;
    }

    return 0;
}

/*
 * Get the sent packet from the retransmission buffer
 */
void eaptls_retransmit(struct eaptls_session *ets, u_char ** outp)
{
    BCOPY(ets->rtx, *outp, ets->rtx_len);
    INCPTR(ets->rtx_len, *outp);
}

/*
 * Every sent & received message this callback function is invoked,
 * so we know when alert messages have arrived or are sent and
 * we can print debug information about TLS handshake.
 */
void
ssl_msg_callback(int write_p, int version, int content_type,
         const void *buf, size_t len, SSL * ssl, void *arg)
{
    char string[256];
    struct eaptls_session *ets = (struct eaptls_session *)arg;
    unsigned char code;
    const unsigned char*msg = buf;
    int hvers = msg[1] << 8 | msg[2];

    if(write_p)
        strcpy(string, " -> ");
    else
        strcpy(string, " <- ");

    switch(content_type) {

    case SSL3_RT_HEADER:
        strcat(string, "SSL/TLS Header: ");
        switch(hvers) {
        case SSL3_VERSION:
                strcat(string, "SSL 3.0");
                break;
        case TLS1_VERSION:
                strcat(string, "TLS 1.0");
                break;
        case TLS1_1_VERSION:
                strcat(string, "TLS 1.1");
                break;
        case TLS1_2_VERSION:
                strcat(string, "TLS 1.2");
                break;
        default:
            sprintf(string, "SSL/TLS Header: Unknown version (%d)", hvers);
        }
        break;

    case SSL3_RT_ALERT:
        strcat(string, "Alert: ");
        code = msg[1];

        if (write_p) {
            ets->alert_sent = 1;
            ets->alert_sent_desc = code;
        } else {
            ets->alert_recv = 1;
            ets->alert_recv_desc = code;
        }

        strcat(string, SSL_alert_desc_string_long(code));
        break;

    case SSL3_RT_CHANGE_CIPHER_SPEC:
        strcat(string, "ChangeCipherSpec");
        break;

#ifdef SSL3_RT_INNER_CONTENT_TYPE
    case SSL3_RT_INNER_CONTENT_TYPE:
        strcat(string, "InnerContentType (TLS1.3)");
        break;
#endif

    case SSL3_RT_HANDSHAKE:

        strcat(string, "Handshake: ");
        code = msg[0];

        switch(code) {
            case SSL3_MT_HELLO_REQUEST:
                strcat(string,"Hello Request");
                break;
            case SSL3_MT_CLIENT_HELLO:
                strcat(string,"Client Hello");
                break;
            case SSL3_MT_SERVER_HELLO:
                strcat(string,"Server Hello");
                break;
#ifdef SSL3_MT_NEWSESSION_TICKET
            case SSL3_MT_NEWSESSION_TICKET:
                strcat(string,"New Session Ticket");
                break;
#endif
#ifdef SSL3_MT_END_OF_EARLY_DATA
            case SSL3_MT_END_OF_EARLY_DATA:
                strcat(string,"End of Early Data");
                break;
#endif
#ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
            case SSL3_MT_ENCRYPTED_EXTENSIONS:
                strcat(string,"Encryped Extensions");
                break;
#endif
            case SSL3_MT_CERTIFICATE:
                strcat(string,"Certificate");
                break;
            case SSL3_MT_SERVER_KEY_EXCHANGE:
                strcat(string,"Server Key Exchange");
                break;
            case SSL3_MT_CERTIFICATE_REQUEST:
                strcat(string,"Certificate Request");
                break;
            case SSL3_MT_SERVER_DONE:
                strcat(string,"Server Hello Done");
                break;
            case SSL3_MT_CERTIFICATE_VERIFY:
                strcat(string,"Certificate Verify");
                break;
            case SSL3_MT_CLIENT_KEY_EXCHANGE:
                strcat(string,"Client Key Exchange");
                break;
            case SSL3_MT_FINISHED:
                strcat(string,"Finished: ");
                hvers = SSL_version(ssl);
                switch(hvers){
                    case SSL3_VERSION:
                        strcat(string, "SSL 3.0");
                        break;
                    case TLS1_VERSION:
                        strcat(string, "TLS 1.0");
                        break;
                    case TLS1_1_VERSION:
                        strcat(string, "TLS 1.1");
                        break;
                    case TLS1_2_VERSION:
                        strcat(string, "TLS 1.2");
                        break;
#ifdef TLS1_3_VERSION
                    case TLS1_3_VERSION:
                        strcat(string, "TLS 1.3 (experimental)");
                        ets->tls_v13 = 1;
                        break;
#endif
                    default:
                        strcat(string, "Unknown version");
                }
                break;
            default:
                sprintf( string, "Handshake: Unknown SSL3 code received: %d", code );
        }
        break;

    default:
        sprintf( string, "SSL message contains unknown content type: %d", content_type );
    }

    /* Alert messages must always be displayed */
    if(content_type == SSL3_RT_ALERT)
        error("%s", string);
    else
        dbglog("%s", string);
}

int 
ssl_new_session_cb(SSL *s, SSL_SESSION *sess)
{
    dbglog("EAP-TLS: Post-Handshake New Session Ticket arrived:");
    have_session_ticket = 1;

    /* always return success */
    return 1;
}