Use unused variable
[freeradius.git] / src / main / tls.c
1 /*
2  * tls.c
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2001  hereUare Communications, Inc. <raghud@hereuare.com>
21  * Copyright 2003  Alan DeKok <aland@freeradius.org>
22  * Copyright 2006  The FreeRADIUS server project
23  */
24
25 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include <freeradius-devel/autoconf.h>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/process.h>
31 #include <freeradius-devel/rad_assert.h>
32
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36
37 #ifdef WITH_TLS
38 #ifdef HAVE_OPENSSL_RAND_H
39 #include <openssl/rand.h>
40 #endif
41
42 #ifdef HAVE_OPENSSL_OCSP_H
43 #include <openssl/ocsp.h>
44 #endif
45
46 /* record */
47 static void             record_init(record_t *buf);
48 static void             record_close(record_t *buf);
49 static unsigned int     record_plus(record_t *buf, const void *ptr,
50                                     unsigned int size);
51 static unsigned int     record_minus(record_t *buf, void *ptr,
52                                      unsigned int size);
53
54 #ifdef PSK_MAX_IDENTITY_LEN
55 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
56                                         unsigned char *psk, int max_psk_len)
57 {
58         unsigned int psk_len;
59         fr_tls_server_conf_t *conf;
60
61         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
62                                                        FR_TLS_EX_INDEX_CONF);
63         if (!conf) return 0;
64
65         /*
66          *      FIXME: Look up the PSK password based on the identity!
67          */
68         if (strcmp(identity, conf->psk_identity) != 0) {
69                 return 0;
70         }
71
72         psk_len = strlen(conf->psk_password);
73         if (psk_len > (2 * max_psk_len)) return 0;
74
75         return fr_hex2bin(conf->psk_password, psk, psk_len);
76 }
77
78 static unsigned int psk_client_callback(SSL *ssl, UNUSED const char *hint,
79                                         char *identity, unsigned int max_identity_len,
80                                         unsigned char *psk, unsigned int max_psk_len)
81 {
82         unsigned int psk_len;
83         fr_tls_server_conf_t *conf;
84
85         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
86                                                        FR_TLS_EX_INDEX_CONF);
87         if (!conf) return 0;
88
89         psk_len = strlen(conf->psk_password);
90         if (psk_len > (2 * max_psk_len)) return 0;
91
92         strlcpy(identity, conf->psk_identity, max_identity_len);
93
94         return fr_hex2bin(conf->psk_password, psk, psk_len);
95 }
96
97 #endif
98
99 tls_session_t *tls_new_client_session(fr_tls_server_conf_t *conf, int fd)
100 {
101         int verify_mode;
102         tls_session_t *ssn = NULL;
103         
104         ssn = (tls_session_t *) malloc(sizeof(*ssn));
105         memset(ssn, 0, sizeof(*ssn));
106
107         ssn->ctx = conf->ctx;
108         ssn->ssl = SSL_new(ssn->ctx);
109         rad_assert(ssn->ssl != NULL);
110
111         /*
112          *      Add the message callback to identify what type of
113          *      message/handshake is passed
114          */
115         SSL_set_msg_callback(ssn->ssl, cbtls_msg);
116         SSL_set_msg_callback_arg(ssn->ssl, ssn);
117         SSL_set_info_callback(ssn->ssl, cbtls_info);
118
119         /*
120          *      Always verify the peer certificate.
121          */
122         DEBUG2("Requiring Server certificate");
123         verify_mode = SSL_VERIFY_PEER;
124         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
125         SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
126
127         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
128         SSL_set_fd(ssn->ssl, fd);
129         if (SSL_connect(ssn->ssl) <= 0) {
130                 int err;
131                 while ((err = ERR_get_error())) {
132                         DEBUG("OpenSSL Err says %s",
133                               ERR_error_string(err, NULL));
134                 }
135                 free(ssn);
136                 return NULL;
137         }
138
139         return ssn;
140 }
141
142 tls_session_t *tls_new_session(fr_tls_server_conf_t *conf, REQUEST *request,
143                                int client_cert)
144 {
145         tls_session_t *state = NULL;
146         SSL *new_tls = NULL;
147         int             verify_mode = 0;
148         VALUE_PAIR      *vp;
149
150         /*
151          *      Manually flush the sessions every so often.  If HALF
152          *      of the session lifetime has passed since we last
153          *      flushed, then flush it again.
154          *
155          *      FIXME: Also do it every N sessions?
156          */
157         if (conf->session_cache_enable &&
158             ((conf->session_last_flushed + (conf->session_timeout * 1800)) <= request->timestamp)){
159                 RDEBUG2("Flushing SSL sessions (of #%ld)",
160                         SSL_CTX_sess_number(conf->ctx));
161
162                 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
163                 conf->session_last_flushed = request->timestamp;
164         }
165
166         if ((new_tls = SSL_new(conf->ctx)) == NULL) {
167                 radlog(L_ERR, "SSL: Error creating new SSL: %s",
168                        ERR_error_string(ERR_get_error(), NULL));
169                 return NULL;
170         }
171
172         /* We use the SSL's "app_data" to indicate a call-back */
173         SSL_set_app_data(new_tls, NULL);
174
175         state = (tls_session_t *)malloc(sizeof(*state));
176         memset(state, 0, sizeof(*state));
177         session_init(state);
178
179         state->ctx = conf->ctx;
180         state->ssl = new_tls;
181
182         /*
183          *      Initialize callbacks
184          */
185         state->record_init = record_init;
186         state->record_close = record_close;
187         state->record_plus = record_plus;
188         state->record_minus = record_minus;
189
190         /*
191          *      Create & hook the BIOs to handle the dirty side of the
192          *      SSL.  This is *very important* as we want to handle
193          *      the transmission part.  Now the only IO interface
194          *      that SSL is aware of, is our defined BIO buffers.
195          *
196          *      This means that all SSL IO is done to/from memory,
197          *      and we can update those BIOs from the packets we've
198          *      received.
199          */
200         state->into_ssl = BIO_new(BIO_s_mem());
201         state->from_ssl = BIO_new(BIO_s_mem());
202         SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
203
204         /*
205          *      Add the message callback to identify what type of
206          *      message/handshake is passed
207          */
208         SSL_set_msg_callback(new_tls, cbtls_msg);
209         SSL_set_msg_callback_arg(new_tls, state);
210         SSL_set_info_callback(new_tls, cbtls_info);
211
212         /*
213          *      In Server mode we only accept.
214          */
215         SSL_set_accept_state(state->ssl);
216
217         /*
218          *      Verify the peer certificate, if asked.
219          */
220         if (client_cert) {
221                 RDEBUG2("Requiring client certificate");
222                 verify_mode = SSL_VERIFY_PEER;
223                 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
224                 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
225         }
226         SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
227
228         SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
229         state->length_flag = conf->include_length;
230
231         /*
232          *      We use default fragment size, unless the Framed-MTU
233          *      tells us it's too big.  Note that we do NOT account
234          *      for the EAP-TLS headers if conf->fragment_size is
235          *      large, because that config item looks to be confusing.
236          *
237          *      i.e. it should REALLY be called MTU, and the code here
238          *      should figure out what that means for TLS fragment size.
239          *      asking the administrator to know the internal details
240          *      of EAP-TLS in order to calculate fragment sizes is
241          *      just too much.
242          */
243         state->offset = conf->fragment_size;
244         vp = pairfind(request->packet->vps, PW_FRAMED_MTU, 0);
245         if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->offset)) {
246                 state->offset = vp->vp_integer;
247         }
248
249         if (conf->session_cache_enable) {
250                 state->allow_session_resumption = 1; /* otherwise it's zero */
251         }
252         
253         RDEBUG2("Initiate");
254
255         return state;
256 }
257
258 /*
259  *      Print out some text describing the error.
260  */
261 static int int_ssl_check(REQUEST *request, SSL *s, int ret, const char *text)
262 {
263         int e;
264         unsigned long l;
265
266         if ((l = ERR_get_error()) != 0) {
267                 const char *p = ERR_error_string(l, NULL);
268                 VALUE_PAIR *vp;
269
270                 radlog(L_ERR, "SSL error %s", p);
271
272                 if (request) {
273                         vp = pairmake("Module-Failure-Message", p, T_OP_ADD);
274                         if (vp) pairadd(&request->packet->vps, vp);
275                 }
276         }
277         e = SSL_get_error(s, ret);
278
279         switch(e) {
280                 /*
281                  *      These seem to be harmless and already "dealt
282                  *      with" by our non-blocking environment. NB:
283                  *      "ZERO_RETURN" is the clean "error"
284                  *      indicating a successfully closed SSL
285                  *      tunnel. We let this happen because our IO
286                  *      loop should not appear to have broken on
287                  *      this condition - and outside the IO loop, the
288                  *      "shutdown" state is checked.
289                  *
290                  *      Don't print anything if we ignore the error.
291                  */
292         case SSL_ERROR_NONE:
293         case SSL_ERROR_WANT_READ:
294         case SSL_ERROR_WANT_WRITE:
295         case SSL_ERROR_WANT_X509_LOOKUP:
296         case SSL_ERROR_ZERO_RETURN:
297                 break;
298
299                 /*
300                  *      These seem to be indications of a genuine
301                  *      error that should result in the SSL tunnel
302                  *      being regarded as "dead".
303                  */
304         case SSL_ERROR_SYSCALL:
305                 radlog(L_ERR, "SSL: %s failed in a system call (%d), TLS session fails.",
306                        text, ret);
307                 return 0;
308
309         case SSL_ERROR_SSL:
310                 radlog(L_ERR, "SSL: %s failed inside of TLS (%d), TLS session fails.",
311                        text, ret);
312                 return 0;
313
314         default:
315                 /*
316                  *      For any other errors that (a) exist, and (b)
317                  *      crop up - we need to interpret what to do with
318                  *      them - so "politely inform" the caller that
319                  *      the code needs updating here.
320                  */
321                 radlog(L_ERR, "SSL: FATAL SSL error ..... %d\n", e);
322                 return 0;
323         }
324
325         return 1;
326 }
327
328 /*
329  * We are the server, we always get the dirty data
330  * (Handshake data is also considered as dirty data)
331  * During handshake, since SSL API handles itself,
332  * After clean-up, dirty_out will be filled with
333  * the data required for handshaking. So we check
334  * if dirty_out is empty then we simply send it back.
335  * As of now, if handshake is successful, then we keep going,
336  * otherwise we fail.
337  *
338  * Fill the Bio with the dirty data to clean it
339  * Get the cleaned data from SSL, if it is not Handshake data
340  */
341 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
342 {
343         int err;
344
345         err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
346         if (err != (int) ssn->dirty_in.used) {
347                 RDEBUG("Failed writing %d to SSL BIO: %d", ssn->dirty_in.used,
348                         err);
349                 record_init(&ssn->dirty_in);
350                 return 0;
351         }
352         record_init(&ssn->dirty_in);
353
354         err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
355                        sizeof(ssn->clean_out.data) - ssn->clean_out.used);
356         if (err > 0) {
357                 ssn->clean_out.used += err;
358                 return 1;
359         }
360
361         if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
362                 return 0;
363         }
364
365         /* Some Extra STATE information for easy debugging */
366         if (SSL_is_init_finished(ssn->ssl)) {
367                 DEBUG2("SSL Connection Established\n");
368         }
369         if (SSL_in_init(ssn->ssl)) {
370                 DEBUG2("In SSL Handshake Phase\n");
371         }
372         if (SSL_in_before(ssn->ssl)) {
373                 DEBUG2("Before SSL Handshake Phase\n");
374         }
375         if (SSL_in_accept_init(ssn->ssl)) {
376                 DEBUG2("In SSL Accept mode \n");
377         }
378         if (SSL_in_connect_init(ssn->ssl)) {
379                 DEBUG2("In SSL Connect mode \n");
380         }
381
382         err = BIO_ctrl_pending(ssn->from_ssl);
383         if (err > 0) {
384                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
385                                sizeof(ssn->dirty_out.data));
386                 if (err > 0) {
387                         ssn->dirty_out.used = err;
388
389                 } else if (BIO_should_retry(ssn->from_ssl)) {
390                         record_init(&ssn->dirty_in);
391                         DEBUG2("  tls: Asking for more data in tunnel");
392                         return 1;
393
394                 } else {
395                         int_ssl_check(request, ssn->ssl, err, "BIO_read");
396                         record_init(&ssn->dirty_in);
397                         return 0;
398                 }
399         } else {
400                 DEBUG2("SSL Application Data");
401                 /* Its clean application data, do whatever we want */
402                 record_init(&ssn->clean_out);
403         }
404
405         /* We are done with dirty_in, reinitialize it */
406         record_init(&ssn->dirty_in);
407         return 1;
408 }
409
410 /*
411  *      Take clear-text user data, and encrypt it into the output buffer,
412  *      to send to the client at the other end of the SSL connection.
413  */
414 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
415 {
416         int err;
417
418         /*
419          *      If there's un-encrypted data in 'clean_in', then write
420          *      that data to the SSL session, and then call the BIO function
421          *      to get that encrypted data from the SSL session, into
422          *      a buffer which we can then package into an EAP packet.
423          *
424          *      Based on Server's logic this clean_in is expected to
425          *      contain the data to send to the client.
426          */
427         if (ssn->clean_in.used > 0) {
428                 int written;
429
430                 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
431                 record_minus(&ssn->clean_in, NULL, written);
432
433                 /* Get the dirty data from Bio to send it */
434                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
435                                sizeof(ssn->dirty_out.data));
436                 if (err > 0) {
437                         ssn->dirty_out.used = err;
438                 } else {
439                         int_ssl_check(request, ssn->ssl, err, "handshake_send");
440                 }
441         }
442
443         return 1;
444 }
445
446 void session_init(tls_session_t *ssn)
447 {
448         ssn->ssl = NULL;
449         ssn->into_ssl = ssn->from_ssl = NULL;
450         record_init(&ssn->clean_in);
451         record_init(&ssn->clean_out);
452         record_init(&ssn->dirty_in);
453         record_init(&ssn->dirty_out);
454
455         memset(&ssn->info, 0, sizeof(ssn->info));
456
457         ssn->offset = 0;
458         ssn->fragment = 0;
459         ssn->tls_msg_len = 0;
460         ssn->length_flag = 0;
461         ssn->opaque = NULL;
462         ssn->free_opaque = NULL;
463 }
464
465 void session_close(tls_session_t *ssn)
466 {       
467         SSL_set_quiet_shutdown(ssn->ssl, 1);
468         SSL_shutdown(ssn->ssl);
469
470         if(ssn->ssl)
471                 SSL_free(ssn->ssl);
472
473         record_close(&ssn->clean_in);
474         record_close(&ssn->clean_out);
475         record_close(&ssn->dirty_in);
476         record_close(&ssn->dirty_out);
477         session_init(ssn);
478 }
479
480 void session_free(void *ssn)
481 {
482         tls_session_t *sess = (tls_session_t *)ssn;
483
484         if (!ssn) return;
485
486         /*
487          *      Free any opaque TTLS or PEAP data.
488          */
489         if ((sess->opaque) && (sess->free_opaque)) {
490                 sess->free_opaque(sess->opaque);
491                 sess->opaque = NULL;
492         }
493
494         session_close(sess);
495
496         free(sess);
497 }
498
499 static void record_init(record_t *rec)
500 {
501         rec->used = 0;
502 }
503
504 static void record_close(record_t *rec)
505 {
506         rec->used = 0;
507 }
508
509
510 /*
511  *      Copy data to the intermediate buffer, before we send
512  *      it somewhere.
513  */
514 static unsigned int record_plus(record_t *rec, const void *ptr,
515                                 unsigned int size)
516 {
517         unsigned int added = MAX_RECORD_SIZE - rec->used;
518
519         if(added > size)
520                 added = size;
521         if(added == 0)
522                 return 0;
523         memcpy(rec->data + rec->used, ptr, added);
524         rec->used += added;
525         return added;
526 }
527
528 /*
529  *      Take data from the buffer, and give it to the caller.
530  */
531 static unsigned int record_minus(record_t *rec, void *ptr,
532                                  unsigned int size)
533 {
534         unsigned int taken = rec->used;
535
536         if(taken > size)
537                 taken = size;
538         if(taken == 0)
539                 return 0;
540         if(ptr)
541                 memcpy(ptr, rec->data, taken);
542         rec->used -= taken;
543
544         /*
545          *      This is pretty bad...
546          */
547         if(rec->used > 0)
548                 memmove(rec->data, rec->data + taken, rec->used);
549         return taken;
550 }
551
552 void tls_session_information(tls_session_t *tls_session)
553 {
554         const char *str_write_p, *str_version, *str_content_type = "";
555         const char *str_details1 = "", *str_details2= "";
556         REQUEST *request;
557
558         /*
559          *      Don't print this out in the normal course of
560          *      operations.
561          */
562         if (debug_flag == 0) {
563                 return;
564         }
565
566         str_write_p = tls_session->info.origin ? ">>>" : "<<<";
567
568         switch (tls_session->info.version)
569         {
570         case SSL2_VERSION:
571                 str_version = "SSL 2.0";
572                 break;
573         case SSL3_VERSION:
574                 str_version = "SSL 3.0 ";
575                 break;
576         case TLS1_VERSION:
577                 str_version = "TLS 1.0 ";
578                 break;
579         default:
580                 str_version = "Unknown TLS version";
581                 break;
582         }
583
584         if (tls_session->info.version == SSL3_VERSION ||
585             tls_session->info.version == TLS1_VERSION) {
586                 switch (tls_session->info.content_type) {
587                 case SSL3_RT_CHANGE_CIPHER_SPEC:
588                         str_content_type = "ChangeCipherSpec";
589                         break;
590                 case SSL3_RT_ALERT:
591                         str_content_type = "Alert";
592                         break;
593                 case SSL3_RT_HANDSHAKE:
594                         str_content_type = "Handshake";
595                         break;
596                 case SSL3_RT_APPLICATION_DATA:
597                         str_content_type = "ApplicationData";
598                         break;
599                 default:
600                         str_content_type = "UnknownContentType";
601                         break;
602                 }
603
604                 if (tls_session->info.content_type == SSL3_RT_ALERT) {
605                         str_details1 = ", ???";
606
607                         if (tls_session->info.record_len == 2) {
608
609                                 switch (tls_session->info.alert_level) {
610                                 case SSL3_AL_WARNING:
611                                         str_details1 = ", warning";
612                                         break;
613                                 case SSL3_AL_FATAL:
614                                         str_details1 = ", fatal";
615                                         break;
616                                 }
617
618                                 str_details2 = " ???";
619                                 switch (tls_session->info.alert_description) {
620                                 case SSL3_AD_CLOSE_NOTIFY:
621                                         str_details2 = " close_notify";
622                                         break;
623                                 case SSL3_AD_UNEXPECTED_MESSAGE:
624                                         str_details2 = " unexpected_message";
625                                         break;
626                                 case SSL3_AD_BAD_RECORD_MAC:
627                                         str_details2 = " bad_record_mac";
628                                         break;
629                                 case TLS1_AD_DECRYPTION_FAILED:
630                                         str_details2 = " decryption_failed";
631                                         break;
632                                 case TLS1_AD_RECORD_OVERFLOW:
633                                         str_details2 = " record_overflow";
634                                         break;
635                                 case SSL3_AD_DECOMPRESSION_FAILURE:
636                                         str_details2 = " decompression_failure";
637                                         break;
638                                 case SSL3_AD_HANDSHAKE_FAILURE:
639                                         str_details2 = " handshake_failure";
640                                         break;
641                                 case SSL3_AD_BAD_CERTIFICATE:
642                                         str_details2 = " bad_certificate";
643                                         break;
644                                 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
645                                         str_details2 = " unsupported_certificate";
646                                         break;
647                                 case SSL3_AD_CERTIFICATE_REVOKED:
648                                         str_details2 = " certificate_revoked";
649                                         break;
650                                 case SSL3_AD_CERTIFICATE_EXPIRED:
651                                         str_details2 = " certificate_expired";
652                                         break;
653                                 case SSL3_AD_CERTIFICATE_UNKNOWN:
654                                         str_details2 = " certificate_unknown";
655                                         break;
656                                 case SSL3_AD_ILLEGAL_PARAMETER:
657                                         str_details2 = " illegal_parameter";
658                                         break;
659                                 case TLS1_AD_UNKNOWN_CA:
660                                         str_details2 = " unknown_ca";
661                                         break;
662                                 case TLS1_AD_ACCESS_DENIED:
663                                         str_details2 = " access_denied";
664                                         break;
665                                 case TLS1_AD_DECODE_ERROR:
666                                         str_details2 = " decode_error";
667                                         break;
668                                 case TLS1_AD_DECRYPT_ERROR:
669                                         str_details2 = " decrypt_error";
670                                         break;
671                                 case TLS1_AD_EXPORT_RESTRICTION:
672                                         str_details2 = " export_restriction";
673                                         break;
674                                 case TLS1_AD_PROTOCOL_VERSION:
675                                         str_details2 = " protocol_version";
676                                         break;
677                                 case TLS1_AD_INSUFFICIENT_SECURITY:
678                                         str_details2 = " insufficient_security";
679                                         break;
680                                 case TLS1_AD_INTERNAL_ERROR:
681                                         str_details2 = " internal_error";
682                                         break;
683                                 case TLS1_AD_USER_CANCELLED:
684                                         str_details2 = " user_canceled";
685                                         break;
686                                 case TLS1_AD_NO_RENEGOTIATION:
687                                         str_details2 = " no_renegotiation";
688                                         break;
689                                 }
690                         }
691                 }
692
693                 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
694                         str_details1 = "???";
695
696                         if (tls_session->info.record_len > 0)
697                         switch (tls_session->info.handshake_type)
698                         {
699                         case SSL3_MT_HELLO_REQUEST:
700                                 str_details1 = ", HelloRequest";
701                                 break;
702                         case SSL3_MT_CLIENT_HELLO:
703                                 str_details1 = ", ClientHello";
704                                 break;
705                         case SSL3_MT_SERVER_HELLO:
706                                 str_details1 = ", ServerHello";
707                                 break;
708                         case SSL3_MT_CERTIFICATE:
709                                 str_details1 = ", Certificate";
710                                 break;
711                         case SSL3_MT_SERVER_KEY_EXCHANGE:
712                                 str_details1 = ", ServerKeyExchange";
713                                 break;
714                         case SSL3_MT_CERTIFICATE_REQUEST:
715                                 str_details1 = ", CertificateRequest";
716                                 break;
717                         case SSL3_MT_SERVER_DONE:
718                                 str_details1 = ", ServerHelloDone";
719                                 break;
720                         case SSL3_MT_CERTIFICATE_VERIFY:
721                                 str_details1 = ", CertificateVerify";
722                                 break;
723                         case SSL3_MT_CLIENT_KEY_EXCHANGE:
724                                 str_details1 = ", ClientKeyExchange";
725                                 break;
726                         case SSL3_MT_FINISHED:
727                                 str_details1 = ", Finished";
728                                 break;
729                         }
730                 }
731         }
732
733         snprintf(tls_session->info.info_description, 
734                  sizeof(tls_session->info.info_description),
735                  "%s %s%s [length %04lx]%s%s\n",
736                  str_write_p, str_version, str_content_type,
737                  (unsigned long)tls_session->info.record_len,
738                  str_details1, str_details2);
739
740         request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
741
742         RDEBUG2("%s\n", tls_session->info.info_description);
743 }
744
745 static CONF_PARSER cache_config[] = {
746         { "enable", PW_TYPE_BOOLEAN,
747           offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
748         { "lifetime", PW_TYPE_INTEGER,
749           offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
750         { "max_entries", PW_TYPE_INTEGER,
751           offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
752         { "name", PW_TYPE_STRING_PTR,
753           offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
754         { NULL, -1, 0, NULL, NULL }           /* end the list */
755 };
756
757 static CONF_PARSER verify_config[] = {
758         { "tmpdir", PW_TYPE_STRING_PTR,
759           offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
760         { "client", PW_TYPE_STRING_PTR,
761           offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
762         { NULL, -1, 0, NULL, NULL }           /* end the list */
763 };
764
765 #ifdef HAVE_OPENSSL_OCSP_H
766 static CONF_PARSER ocsp_config[] = {
767         { "enable", PW_TYPE_BOOLEAN,
768           offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
769         { "override_cert_url", PW_TYPE_BOOLEAN,
770           offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
771         { "url", PW_TYPE_STRING_PTR,
772           offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
773         { "use_nonce", PW_TYPE_BOOLEAN,
774           offsetof(fr_tls_server_conf_t, ocsp_use_nonce), NULL, "yes"},
775         { "timeout", PW_TYPE_INTEGER,
776           offsetof(fr_tls_server_conf_t, ocsp_timeout), NULL, "yes"},
777         { "softfail", PW_TYPE_BOOLEAN,
778           offsetof(fr_tls_server_conf_t, ocsp_softfail), NULL, "yes"},
779         { NULL, -1, 0, NULL, NULL }           /* end the list */
780 };
781 #endif
782
783 static CONF_PARSER tls_server_config[] = {
784         { "rsa_key_exchange", PW_TYPE_BOOLEAN,
785           offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
786         { "dh_key_exchange", PW_TYPE_BOOLEAN,
787           offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
788         { "rsa_key_length", PW_TYPE_INTEGER,
789           offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
790         { "dh_key_length", PW_TYPE_INTEGER,
791           offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
792         { "verify_depth", PW_TYPE_INTEGER,
793           offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
794         { "CA_path", PW_TYPE_FILENAME,
795           offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
796         { "pem_file_type", PW_TYPE_BOOLEAN,
797           offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
798         { "private_key_file", PW_TYPE_FILENAME,
799           offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
800         { "certificate_file", PW_TYPE_FILENAME,
801           offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
802         { "CA_file", PW_TYPE_FILENAME,
803           offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
804         { "private_key_password", PW_TYPE_STRING_PTR,
805           offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
806 #ifdef PSK_MAX_IDENTITY_LEN
807         { "psk_identity", PW_TYPE_STRING_PTR,
808           offsetof(fr_tls_server_conf_t, psk_identity), NULL, NULL },
809         { "psk_hexphrase", PW_TYPE_STRING_PTR,
810           offsetof(fr_tls_server_conf_t, psk_password), NULL, NULL },
811 #endif
812         { "dh_file", PW_TYPE_STRING_PTR,
813           offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
814         { "random_file", PW_TYPE_STRING_PTR,
815           offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
816         { "fragment_size", PW_TYPE_INTEGER,
817           offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
818         { "include_length", PW_TYPE_BOOLEAN,
819           offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
820         { "check_crl", PW_TYPE_BOOLEAN,
821           offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
822         { "allow_expired_crl", PW_TYPE_BOOLEAN,
823           offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
824         { "check_cert_cn", PW_TYPE_STRING_PTR,
825           offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
826         { "cipher_list", PW_TYPE_STRING_PTR,
827           offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
828         { "check_cert_issuer", PW_TYPE_STRING_PTR,
829           offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
830         { "make_cert_command", PW_TYPE_STRING_PTR,
831           offsetof(fr_tls_server_conf_t, make_cert_command), NULL, NULL},
832         { "require_client_cert", PW_TYPE_BOOLEAN,
833           offsetof(fr_tls_server_conf_t, require_client_cert), NULL, NULL },
834
835 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
836 #ifndef OPENSSL_NO_ECDH
837         { "ecdh_curve", PW_TYPE_STRING_PTR,
838           offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
839 #endif
840 #endif
841
842         { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
843
844         { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
845
846 #ifdef HAVE_OPENSSL_OCSP_H
847         { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
848 #endif
849
850         { NULL, -1, 0, NULL, NULL }           /* end the list */
851 };
852
853
854 static CONF_PARSER tls_client_config[] = {
855         { "rsa_key_exchange", PW_TYPE_BOOLEAN,
856           offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
857         { "dh_key_exchange", PW_TYPE_BOOLEAN,
858           offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
859         { "rsa_key_length", PW_TYPE_INTEGER,
860           offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
861         { "dh_key_length", PW_TYPE_INTEGER,
862           offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
863         { "verify_depth", PW_TYPE_INTEGER,
864           offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
865         { "CA_path", PW_TYPE_FILENAME,
866           offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
867         { "pem_file_type", PW_TYPE_BOOLEAN,
868           offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
869         { "private_key_file", PW_TYPE_FILENAME,
870           offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
871         { "certificate_file", PW_TYPE_FILENAME,
872           offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
873         { "CA_file", PW_TYPE_FILENAME,
874           offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
875         { "private_key_password", PW_TYPE_STRING_PTR,
876           offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
877         { "dh_file", PW_TYPE_STRING_PTR,
878           offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
879         { "random_file", PW_TYPE_STRING_PTR,
880           offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
881         { "fragment_size", PW_TYPE_INTEGER,
882           offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
883         { "include_length", PW_TYPE_BOOLEAN,
884           offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
885         { "check_crl", PW_TYPE_BOOLEAN,
886           offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
887         { "check_cert_cn", PW_TYPE_STRING_PTR,
888           offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
889         { "cipher_list", PW_TYPE_STRING_PTR,
890           offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
891         { "check_cert_issuer", PW_TYPE_STRING_PTR,
892           offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
893
894 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
895 #ifndef OPENSSL_NO_ECDH
896         { "ecdh_curve", PW_TYPE_STRING_PTR,
897           offsetof(fr_tls_server_conf_t, ecdh_curve), NULL, "prime256v1"},
898 #endif
899 #endif
900
901         { NULL, -1, 0, NULL, NULL }           /* end the list */
902 };
903
904
905 /*
906  *      TODO: Check for the type of key exchange * like conf->dh_key
907  */
908 static int load_dh_params(SSL_CTX *ctx, char *file)
909 {
910         DH *dh = NULL;
911         BIO *bio;
912
913         if ((bio = BIO_new_file(file, "r")) == NULL) {
914                 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
915                 return -1;
916         }
917
918         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
919         BIO_free(bio);
920         if (!dh) {
921                 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters.  DH cipher suites may not work!");
922                 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
923                 return 0;
924         }
925
926         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
927                 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
928                 DH_free(dh);
929                 return -1;
930         }
931
932         DH_free(dh);
933         return 0;
934 }
935
936
937 /*
938  *      Generate ephemeral RSA keys.
939  */
940 static int generate_eph_rsa_key(SSL_CTX *ctx)
941 {
942         RSA *rsa;
943
944         rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
945
946         if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
947                 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
948                 return -1;
949         }
950
951         RSA_free(rsa);
952         return 0;
953 }
954
955
956 /*
957  *      Print debugging messages, and free data.
958  *
959  *      FIXME: Write sessions to some long-term storage, so that
960  *             session resumption can still occur after the server
961  *             restarts.
962  */
963 #define MAX_SESSION_SIZE (256)
964
965 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
966 {
967         size_t size;
968         char buffer[2 * MAX_SESSION_SIZE + 1];
969
970         size = sess->session_id_length;
971         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
972
973         fr_bin2hex(sess->session_id, buffer, size);
974
975         DEBUG2("  SSL: Removing session %s from the cache", buffer);
976
977         return;
978 }
979
980 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
981 {
982         size_t size;
983         char buffer[2 * MAX_SESSION_SIZE + 1];
984
985         size = sess->session_id_length;
986         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
987
988         fr_bin2hex(sess->session_id, buffer, size);
989
990         DEBUG2("  SSL: adding session %s to cache", buffer);
991
992         return 0;
993 }
994
995 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
996                                       unsigned char *data, int len,
997                                       int *copy)
998 {
999         size_t size;
1000         char buffer[2 * MAX_SESSION_SIZE + 1];
1001
1002         size = len;
1003         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1004
1005         fr_bin2hex(data, buffer, size);
1006
1007         DEBUG2("  SSL: Client requested nonexistent cached session %s",
1008                buffer);
1009
1010         *copy = 0;
1011         return NULL;
1012 }
1013
1014 #ifdef HAVE_OPENSSL_OCSP_H
1015 /*
1016  * This function extracts the OCSP Responder URL
1017  * from an existing x509 certificate.
1018  */
1019 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1020                                char **ppath, int *pssl)
1021 {
1022         int i;
1023
1024         AUTHORITY_INFO_ACCESS *aia;
1025         ACCESS_DESCRIPTION *ad;
1026
1027         aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1028
1029         for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1030                 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1031                 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1032                         if (ad->location->type == GEN_URI) {
1033                                 if(OCSP_parse_url(ad->location->d.ia5->data,
1034                                         phost, pport, ppath, pssl))
1035                                         return 1;
1036                         }
1037                 }
1038         }
1039         return 0;
1040 }
1041
1042 /*
1043  * This function sends a OCSP request to a defined OCSP responder
1044  * and checks the OCSP response for correctness.
1045  */
1046
1047 /* Maximum leeway in validity period: default 5 minutes */
1048 #define MAX_VALIDITY_PERIOD     (5 * 60)
1049
1050 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1051                       fr_tls_server_conf_t *conf)
1052 {
1053         OCSP_CERTID *certid;
1054         OCSP_REQUEST *req;
1055         OCSP_RESPONSE *resp = NULL;
1056         OCSP_BASICRESP *bresp = NULL;
1057         char *host = NULL;
1058         char *port = NULL;
1059         char *path = NULL;
1060         int use_ssl = -1;
1061         long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1062         BIO *cbio, *bio_out;
1063         int ocsp_ok = 0;
1064         int status ;
1065         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1066         int reason;
1067 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1068         OCSP_REQ_CTX *ctx;
1069         int rc;
1070         struct timeval now;
1071         struct timeval when;
1072 #endif
1073
1074         /*
1075          * Create OCSP Request
1076          */
1077         certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1078         req = OCSP_REQUEST_new();
1079         OCSP_request_add0_id(req, certid);
1080         if(conf->ocsp_use_nonce) {
1081                 OCSP_request_add1_nonce(req, NULL, 8);
1082         }
1083
1084         /*
1085          * Send OCSP Request and get OCSP Response
1086          */
1087
1088         /* Get OCSP responder URL */
1089         if(conf->ocsp_override_url) {
1090                 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
1091         }
1092         else {
1093                 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1094         }
1095
1096         DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1097
1098         /* Setup BIO socket to OCSP responder */
1099         cbio = BIO_new_connect(host);
1100
1101         bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1102
1103         BIO_set_conn_port(cbio, port);
1104 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1105         BIO_do_connect(cbio);
1106  
1107         /* Send OCSP request and wait for response */
1108         resp = OCSP_sendreq_bio(cbio, path, req);
1109         if (!resp) {
1110                 radlog(L_ERR, "Error: Couldn't get OCSP response");
1111                 ocsp_ok = 2;
1112                 goto ocsp_end;
1113         }
1114 #else
1115         if (conf->ocsp_timeout)
1116                 BIO_set_nbio(cbio, 1);
1117
1118         rc = BIO_do_connect(cbio);
1119         if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1120                 radlog(L_ERR, "Error: Couldn't connect to OCSP responder");
1121                 ocsp_ok = 2;
1122                 goto ocsp_end;
1123         }
1124
1125         ctx = OCSP_sendreq_new(cbio, path, req, -1);
1126         if (!ctx) {
1127                 radlog(L_ERR, "Error: Couldn't send OCSP request");
1128                 ocsp_ok = 2;
1129                 goto ocsp_end;
1130         }
1131
1132         gettimeofday(&when, NULL);
1133         when.tv_sec += conf->ocsp_timeout;
1134
1135         do {
1136                 rc = OCSP_sendreq_nbio(&resp, ctx);
1137                 if (conf->ocsp_timeout) {
1138                         gettimeofday(&now, NULL);
1139                         if (!timercmp(&now, &when, <))
1140                                 break;
1141                 }
1142         } while ((rc == -1) && BIO_should_retry(cbio));
1143
1144         if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1145                 radlog(L_ERR, "Error: OCSP response timed out");
1146                 ocsp_ok = 2;
1147                 goto ocsp_end;
1148         }
1149
1150         OCSP_REQ_CTX_free(ctx);
1151
1152         if (rc == 0) {
1153                 radlog(L_ERR, "Error: Couldn't get OCSP response");
1154                 ocsp_ok = 2;
1155                 goto ocsp_end;
1156         }
1157 #endif
1158
1159         /* Verify OCSP response status */
1160         status = OCSP_response_status(resp);
1161         DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1162         if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1163                 radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status));
1164                 goto ocsp_end;
1165         }
1166         bresp = OCSP_response_get1_basic(resp);
1167         if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1168                 radlog(L_ERR, "Error: OCSP response has wrong nonce value");
1169                 goto ocsp_end;
1170         }
1171         if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1172                 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
1173                 goto ocsp_end;
1174         }
1175
1176         /*      Verify OCSP cert status */
1177         if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1178                                                       &rev, &thisupd, &nextupd)) {
1179                 radlog(L_ERR, "ERROR: No Status found.\n");
1180                 goto ocsp_end;
1181         }
1182
1183         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1184                 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1185                 ERR_print_errors(bio_out);
1186                 goto ocsp_end;
1187         }
1188         BIO_puts(bio_out, "\tThis Update: ");
1189         ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1190         BIO_puts(bio_out, "\n");
1191         BIO_puts(bio_out, "\tNext Update: ");
1192         ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1193         BIO_puts(bio_out, "\n");
1194
1195         switch (status) {
1196         case V_OCSP_CERTSTATUS_GOOD:
1197                 DEBUG2("[oscp] --> Cert status: good");
1198                 ocsp_ok = 1;
1199                 break;
1200
1201         default:
1202                 /* REVOKED / UNKNOWN */
1203                 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1204                 if (reason != -1)
1205                         DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1206                 BIO_puts(bio_out, "\tRevocation Time: ");
1207                 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1208                 BIO_puts(bio_out, "\n");
1209                 break;
1210         }
1211
1212 ocsp_end:
1213         /* Free OCSP Stuff */
1214         OCSP_REQUEST_free(req);
1215         OCSP_RESPONSE_free(resp);
1216         free(host);
1217         free(port);
1218         free(path);
1219         BIO_free_all(cbio);
1220         OCSP_BASICRESP_free(bresp);
1221
1222         switch (ocsp_ok) {
1223         case 1:
1224                 DEBUG2("[ocsp] --> Certificate is valid!");
1225                 break;
1226         case 2:
1227                 if (conf->ocsp_softfail) {
1228                         DEBUG2("[ocsp] --> Unable to check certificate; assuming valid.");
1229                         DEBUG2("[ocsp] --> Warning! This may be insecure.");
1230                         ocsp_ok = 1;
1231                 } else {
1232                         DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1233                         ocsp_ok = 0;
1234                 }
1235                 break;
1236         default:
1237                 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1238                 break;
1239         }
1240
1241         return ocsp_ok;
1242 }
1243 #endif  /* HAVE_OPENSSL_OCSP_H */
1244
1245 /*
1246  *      For creating certificate attributes.
1247  */
1248 static const char *cert_attr_names[6][2] = {
1249   { "TLS-Client-Cert-Serial",           "TLS-Cert-Serial" },
1250   { "TLS-Client-Cert-Expiration",       "TLS-Cert-Expiration" },
1251   { "TLS-Client-Cert-Subject",          "TLS-Cert-Subject" },
1252   { "TLS-Client-Cert-Issuer",           "TLS-Cert-Issuer" },
1253   { "TLS-Client-Cert-Common-Name",      "TLS-Cert-Common-Name" },
1254   { "TLS-Client-Cert-Subject-Alt-Name-Email",   "TLS-Cert-Subject-Alt-Name-Email" }
1255 };
1256
1257 #define FR_TLS_SERIAL           (0)
1258 #define FR_TLS_EXPIRATION       (1)
1259 #define FR_TLS_SUBJECT          (2)
1260 #define FR_TLS_ISSUER           (3)
1261 #define FR_TLS_CN               (4)
1262 #define FR_TLS_SAN_EMAIL        (5)
1263
1264 /*
1265  *      Before trusting a certificate, you must make sure that the
1266  *      certificate is 'valid'. There are several steps that your
1267  *      application can take in determining if a certificate is
1268  *      valid. Commonly used steps are:
1269  *
1270  *      1.Verifying the certificate's signature, and verifying that
1271  *      the certificate has been issued by a trusted Certificate
1272  *      Authority.
1273  *
1274  *      2.Verifying that the certificate is valid for the present date
1275  *      (i.e. it is being presented within its validity dates).
1276  *
1277  *      3.Verifying that the certificate has not been revoked by its
1278  *      issuing Certificate Authority, by checking with respect to a
1279  *      Certificate Revocation List (CRL).
1280  *
1281  *      4.Verifying that the credentials presented by the certificate
1282  *      fulfill additional requirements specific to the application,
1283  *      such as with respect to access control lists or with respect
1284  *      to OCSP (Online Certificate Status Processing).
1285  *
1286  *      NOTE: This callback will be called multiple times based on the
1287  *      depth of the root certificate chain
1288  */
1289 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1290 {
1291         char subject[1024]; /* Used for the subject name */
1292         char issuer[1024]; /* Used for the issuer name */
1293         char common_name[1024];
1294         char cn_str[1024];
1295         char buf[64];
1296         X509 *client_cert;
1297         SSL *ssl;
1298         int err, depth, lookup, loc;
1299         fr_tls_server_conf_t *conf;
1300         int my_ok = ok;
1301         REQUEST *request;
1302         ASN1_INTEGER *sn = NULL;
1303         ASN1_TIME *asn_time = NULL;
1304         VALUE_PAIR **certs;
1305         char **identity;
1306 #ifdef HAVE_OPENSSL_OCSP_H
1307         X509_STORE *ocsp_store = NULL;
1308         X509 *issuer_cert;
1309 #endif
1310
1311         client_cert = X509_STORE_CTX_get_current_cert(ctx);
1312         err = X509_STORE_CTX_get_error(ctx);
1313         depth = X509_STORE_CTX_get_error_depth(ctx);
1314
1315         lookup = depth;
1316
1317         /*
1318          *      Log client/issuing cert.  If there's an error, log
1319          *      issuing cert.
1320          */
1321         if ((lookup > 1) && !my_ok) lookup = 1;
1322
1323         /*
1324          * Retrieve the pointer to the SSL of the connection currently treated
1325          * and the application specific data stored into the SSL object.
1326          */
1327         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1328         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1329         if (!conf) return 1;
1330
1331         request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1332
1333         if (!request) return 1; /* FIXME: outbound TLS */
1334
1335         rad_assert(request != NULL);
1336         certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1337         rad_assert(certs != NULL);
1338         identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1339 #ifdef HAVE_OPENSSL_OCSP_H
1340         ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1341 #endif
1342
1343
1344         /*
1345          *      Get the Serial Number
1346          */
1347         buf[0] = '\0';
1348         sn = X509_get_serialNumber(client_cert);
1349
1350         /*
1351          *      For this next bit, we create the attributes *only* if
1352          *      we're at the client or issuing certificate, AND we
1353          *      have a user identity.  i.e. we don't create the
1354          *      attributes for RadSec connections.
1355          */
1356         if (identity && 
1357             (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1358                 char *p = buf;
1359                 int i;
1360
1361                 for (i = 0; i < sn->length; i++) {
1362                         sprintf(p, "%02x", (unsigned int)sn->data[i]);
1363                         p += 2;
1364                 }
1365                 pairadd(certs,
1366                         pairmake(cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET));
1367         }
1368
1369
1370         /*
1371          *      Get the Expiration Date
1372          */
1373         buf[0] = '\0';
1374         asn_time = X509_get_notAfter(client_cert);
1375         if (identity && (lookup <= 1) && asn_time &&
1376             (asn_time->length < MAX_STRING_LEN)) {
1377                 memcpy(buf, (char*) asn_time->data, asn_time->length);
1378                 buf[asn_time->length] = '\0';
1379                 pairadd(certs,
1380                         pairmake(cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET));
1381         }
1382
1383         /*
1384          *      Get the Subject & Issuer
1385          */
1386         subject[0] = issuer[0] = '\0';
1387         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1388                           sizeof(subject));
1389         subject[sizeof(subject) - 1] = '\0';
1390         if (identity && (lookup <= 1) && subject[0] &&
1391             (strlen(subject) < MAX_STRING_LEN)) {
1392                 pairadd(certs,
1393                         pairmake(cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET));
1394         }
1395
1396         X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1397                           sizeof(issuer));
1398         issuer[sizeof(issuer) - 1] = '\0';
1399         if (identity && (lookup <= 1) && issuer[0] &&
1400             (strlen(issuer) < MAX_STRING_LEN)) {
1401                 pairadd(certs,
1402                         pairmake(cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET));
1403         }
1404
1405         /*
1406          *      Get the Common Name
1407          */
1408         X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1409                                   NID_commonName, common_name, sizeof(common_name));
1410         common_name[sizeof(common_name) - 1] = '\0';
1411         if (identity && (lookup <= 1) && common_name[0] &&
1412             (strlen(common_name) < MAX_STRING_LEN)) {
1413                 pairadd(certs,
1414                         pairmake(cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET));
1415         }
1416
1417 #ifdef GEN_EMAIL
1418         /*
1419          *      Get the RFC822 Subject Alternative Name
1420          */
1421         loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1422         if (lookup <= 1 && loc >= 0) {
1423                 X509_EXTENSION *ext = NULL;
1424                 GENERAL_NAMES *names = NULL;
1425                 int i;
1426
1427                 if ((ext = X509_get_ext(client_cert, loc)) &&
1428                     (names = X509V3_EXT_d2i(ext))) {
1429                         for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1430                                 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1431
1432                                 switch (name->type) {
1433                                 case GEN_EMAIL:
1434                                         if (ASN1_STRING_length(name->d.rfc822Name) >= MAX_STRING_LEN)
1435                                                 break;
1436
1437                                         pairadd(certs,
1438                                                 pairmake(cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1439                                                          ASN1_STRING_data(name->d.rfc822Name), T_OP_SET));
1440                                         break;
1441                                 default:
1442                                         /* XXX TODO handle other SAN types */
1443                                         break;
1444                                 }
1445                         }
1446                 }
1447                 if (names != NULL)
1448                         sk_GENERAL_NAME_free(names);
1449         }
1450 #endif  /* GEN_EMAIL */
1451
1452         /*
1453          *      If the CRL has expired, that might still be OK.
1454          */
1455         if (!my_ok &&
1456             (conf->allow_expired_crl) &&
1457             (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1458                 my_ok = 1;
1459                 X509_STORE_CTX_set_error( ctx, 0 );
1460         }
1461
1462         if (!my_ok) {
1463                 const char *p = X509_verify_cert_error_string(err);
1464                 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
1465                 radius_pairmake(request, &request->packet->vps,
1466                                 "Module-Failure-Message", p, T_OP_SET);
1467                 return my_ok;
1468         }
1469
1470         switch (ctx->error) {
1471
1472         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1473                 radlog(L_ERR, "issuer= %s\n", issuer);
1474                 break;
1475         case X509_V_ERR_CERT_NOT_YET_VALID:
1476         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1477                 radlog(L_ERR, "notBefore=");
1478 #if 0
1479                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1480 #endif
1481                 break;
1482         case X509_V_ERR_CERT_HAS_EXPIRED:
1483         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1484                 radlog(L_ERR, "notAfter=");
1485 #if 0
1486                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1487 #endif
1488                 break;
1489         }
1490
1491         /*
1492          *      If we're at the actual client cert, apply additional
1493          *      checks.
1494          */
1495         if (depth == 0) {
1496                 /*
1497                  *      If the conf tells us to, check cert issuer
1498                  *      against the specified value and fail
1499                  *      verification if they don't match.
1500                  */
1501                 if (conf->check_cert_issuer &&
1502                     (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1503                         radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1504                         my_ok = 0;
1505                 }
1506
1507                 /*
1508                  *      If the conf tells us to, check the CN in the
1509                  *      cert against xlat'ed value, but only if the
1510                  *      previous checks passed.
1511                  */
1512                 if (my_ok && conf->check_cert_cn) {
1513                         if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, request, NULL)) {
1514                                 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
1515                                        conf->check_cert_cn);
1516                                 /* if this fails, fail the verification */
1517                                 my_ok = 0;
1518                         } else {
1519                                 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1520                                 if (strcmp(cn_str, common_name) != 0) {
1521                                         radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1522                                         my_ok = 0;
1523                                 }
1524                         }
1525                 } /* check_cert_cn */
1526
1527 #ifdef HAVE_OPENSSL_OCSP_H
1528                 if (my_ok && conf->ocsp_enable){
1529                         RDEBUG2("--> Starting OCSP Request");
1530                         if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1531                                 radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
1532                         }
1533                         my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1534                 }
1535 #endif
1536
1537                 while (conf->verify_client_cert_cmd) {
1538                         char filename[256];
1539                         int fd;
1540                         FILE *fp;
1541
1542                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1543                                  conf->verify_tmp_dir, progname);
1544                         fd = mkstemp(filename);
1545                         if (fd < 0) {
1546                                 RDEBUG("Failed creating file in %s: %s",
1547                                        conf->verify_tmp_dir, strerror(errno));
1548                                 break;
1549                         }
1550
1551                         fp = fdopen(fd, "w");
1552                         if (!fp) {
1553                                 RDEBUG("Failed opening file %s: %s",
1554                                        filename, strerror(errno));
1555                                 break;
1556                         }
1557
1558                         if (!PEM_write_X509(fp, client_cert)) {
1559                                 fclose(fp);
1560                                 RDEBUG("Failed writing certificate to file");
1561                                 goto do_unlink;
1562                         }
1563                         fclose(fp);
1564
1565                         if (!radius_pairmake(request, &request->packet->vps,
1566                                              "TLS-Client-Cert-Filename",
1567                                              filename, T_OP_SET)) {
1568                                 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1569
1570                                 goto do_unlink;
1571                         }
1572
1573                         RDEBUG("Verifying client certificate: %s",
1574                                conf->verify_client_cert_cmd);
1575                         if (radius_exec_program(conf->verify_client_cert_cmd,
1576                                                 request, 1, NULL, 0,
1577                                                 request->packet->vps,
1578                                                 NULL, 1) != 0) {
1579                                 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
1580                                 my_ok = 0;
1581                         } else {
1582                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
1583                         }
1584
1585                 do_unlink:
1586                         unlink(filename);
1587                         break;
1588                 }
1589
1590
1591         } /* depth == 0 */
1592
1593         if (debug_flag > 0) {
1594                 RDEBUG2("chain-depth=%d, ", depth);
1595                 RDEBUG2("error=%d", err);
1596
1597                 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1598                 RDEBUG2("--> BUF-Name = %s", common_name);
1599                 RDEBUG2("--> subject = %s", subject);
1600                 RDEBUG2("--> issuer  = %s", issuer);
1601                 RDEBUG2("--> verify return:%d", my_ok);
1602         }
1603         return my_ok;
1604 }
1605
1606
1607 #ifdef HAVE_OPENSSL_OCSP_H
1608 /*
1609  *      Create Global X509 revocation store and use it to verify
1610  *      OCSP responses
1611  *
1612  *      - Load the trusted CAs
1613  *      - Load the trusted issuer certificates
1614  */
1615 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1616 {
1617         X509_STORE *store = NULL;
1618
1619         store = X509_STORE_new();
1620
1621         /* Load the CAs we trust */
1622         if (conf->ca_file || conf->ca_path)
1623                 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1624                         radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1625                         radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1626                         return NULL;
1627                 }
1628
1629 #ifdef X509_V_FLAG_CRL_CHECK
1630         if (conf->check_crl)
1631                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1632 #endif
1633         return store;
1634 }
1635 #endif  /* HAVE_OPENSSL_OCSP_H */
1636
1637 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1638 #ifndef OPENSSL_NO_ECDH
1639 static int set_ecdh_curve(SSL_CTX *ctx, const char *ecdh_curve)
1640 {
1641         int      nid; 
1642         EC_KEY  *ecdh; 
1643
1644         if (!ecdh_curve || !*ecdh_curve) return 0;
1645
1646         nid = OBJ_sn2nid(ecdh_curve); 
1647         if (!nid) { 
1648                 radlog(L_ERR, "Unknown ecdh_curve \"%s\"", ecdh_curve);
1649                 return -1;
1650         }
1651
1652         ecdh = EC_KEY_new_by_curve_name(nid); 
1653         if (!ecdh) { 
1654                 radlog(L_ERR, "Unable to create new curve \"%s\"", ecdh_curve);
1655                 return -1;
1656         } 
1657
1658         SSL_CTX_set_tmp_ecdh(ctx, ecdh); 
1659
1660         SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE); 
1661
1662         EC_KEY_free(ecdh);
1663
1664         return 0;
1665 }
1666 #endif
1667 #endif
1668
1669 /* index we use to store cached session VPs
1670  * needs to be dynamic so we can supply a "free" function
1671  */
1672 static int FR_TLS_EX_INDEX_VPS = -1;
1673
1674 /*
1675  * DIE OPENSSL DIE DIE DIE
1676  *
1677  * What a palaver, just to free some data attached the
1678  * session. We need to do this because the "remove" callback
1679  * is called when refcount > 0 sometimes, if another thread
1680  * is using the session
1681  */
1682 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1683                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1684                                 UNUSED long argl, UNUSED void *argp)
1685 {
1686         VALUE_PAIR *vp = data_ptr;
1687         if (!vp) return;
1688
1689         DEBUG2("  Freeing cached session VPs %p", vp);
1690
1691         pairfree(&vp);
1692 }
1693
1694
1695 /*
1696  *      Create Global context SSL and use it in every new session
1697  *
1698  *      - Load the trusted CAs
1699  *      - Load the Private key & the certificate
1700  *      - Set the Context options & Verify options
1701  */
1702 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
1703 {
1704         const SSL_METHOD *meth;
1705         SSL_CTX *ctx;
1706         X509_STORE *certstore;
1707         int verify_mode = SSL_VERIFY_NONE;
1708         int ctx_options = 0;
1709         int type;
1710
1711         /*
1712          *      Add all the default ciphers and message digests
1713          *      Create our context.
1714          */
1715         SSL_library_init();
1716         SSL_load_error_strings();
1717
1718         /*
1719          *      SHA256 is in all versions of OpenSSL, but isn't
1720          *      initialized by default.  It's needed for WiMAX
1721          *      certificates.
1722          */
1723 #ifdef HAVE_OPENSSL_EVP_SHA256
1724         EVP_add_digest(EVP_sha256());
1725 #endif
1726
1727         meth = TLSv1_method();
1728         ctx = SSL_CTX_new(meth);
1729
1730         /*
1731          * Identify the type of certificates that needs to be loaded
1732          */
1733         if (conf->file_type) {
1734                 type = SSL_FILETYPE_PEM;
1735         } else {
1736                 type = SSL_FILETYPE_ASN1;
1737         }
1738
1739         /*
1740          * Set the password to load private key
1741          */
1742         if (conf->private_key_password) {
1743 #ifdef __APPLE__
1744                 /*
1745                  * We don't want to put the private key password in eap.conf, so  check
1746                  * for our special string which indicates we should get the password
1747                  * programmatically. 
1748                  */
1749                 const char* special_string = "Apple:UseCertAdmin";
1750                 if (strncmp(conf->private_key_password,
1751                                         special_string,
1752                                         strlen(special_string)) == 0)
1753                 {
1754                         char cmd[256];
1755                         const long max_password_len = 128;
1756                         snprintf(cmd, sizeof(cmd) - 1,
1757                                          "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
1758                                          conf->private_key_file);
1759
1760                         DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
1761
1762                         FILE* cmd_pipe = popen(cmd, "r");
1763                         if (!cmd_pipe) {
1764                                 radlog(L_ERR, "rlm_eap: %s command failed.      Unable to get private_key_password", cmd);
1765                                 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1766                                 return NULL;
1767                         }
1768
1769                         free(conf->private_key_password);
1770                         conf->private_key_password = malloc(max_password_len * sizeof(char));
1771                         if (!conf->private_key_password) {
1772                                 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
1773                                 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1774                                 pclose(cmd_pipe);
1775                                 return NULL;
1776                         }
1777
1778                         fgets(conf->private_key_password, max_password_len, cmd_pipe);
1779                         pclose(cmd_pipe);
1780
1781                         /* Get rid of newline at end of password. */
1782                         conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
1783                         DEBUG2("rlm_eap:  Password from command = \"%s\"", conf->private_key_password);
1784                 }
1785 #endif
1786                 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
1787                 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
1788         }
1789
1790 #ifdef PSK_MAX_IDENTITY_LEN
1791         if ((conf->psk_identity && !conf->psk_password) ||
1792             (!conf->psk_identity && conf->psk_password) ||
1793             (conf->psk_identity && !*conf->psk_identity) ||
1794             (conf->psk_password && !*conf->psk_password)) {
1795                 radlog(L_ERR, "Invalid PSK Configuration: psk_identity or psk_password are empty");
1796                 return NULL;
1797         }
1798
1799         if (conf->psk_identity) {
1800                 size_t psk_len, hex_len;
1801                 char buffer[PSK_MAX_PSK_LEN];
1802
1803                 if (conf->certificate_file ||
1804                     conf->private_key_password || conf->private_key_file ||
1805                     conf->ca_file || conf->ca_path) {
1806                         radlog(L_ERR, "When PSKs are used, No certificate configuration is permitted");
1807                         return NULL;
1808                 }
1809
1810                 if (client) {
1811                         SSL_CTX_set_psk_client_callback(ctx,
1812                                                         psk_client_callback);
1813                 } else {
1814                         SSL_CTX_set_psk_server_callback(ctx,
1815                                                         psk_server_callback);
1816                 }
1817
1818                 psk_len = strlen(conf->psk_password);
1819                 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
1820                         radlog(L_ERR, "psk_hexphrase is too long (max %d)",
1821                                PSK_MAX_PSK_LEN);
1822                         return NULL;                        
1823                 }
1824
1825                 hex_len = fr_hex2bin(conf->psk_password, buffer, psk_len);
1826                 if (psk_len != (2 * hex_len)) {
1827                         radlog(L_ERR, "psk_hexphrase is not all hex");
1828                         return NULL;                        
1829                 }
1830
1831                 goto post_ca;
1832         }
1833 #else
1834         client = client;        /* -Wunused */
1835 #endif
1836
1837         /*
1838          *      Load our keys and certificates
1839          *
1840          *      If certificates are of type PEM then we can make use
1841          *      of cert chain authentication using openssl api call
1842          *      SSL_CTX_use_certificate_chain_file.  Please see how
1843          *      the cert chain needs to be given in PEM from
1844          *      openSSL.org
1845          */
1846         if (!conf->certificate_file) goto load_ca;
1847
1848         if (type == SSL_FILETYPE_PEM) {
1849                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
1850                         radlog(L_ERR, "Error reading certificate file %s:%s",
1851                                conf->certificate_file,
1852                                ERR_error_string(ERR_get_error(), NULL));
1853                         return NULL;
1854                 }
1855
1856         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
1857                 radlog(L_ERR, "Error reading certificate file %s:%s",
1858                        conf->certificate_file,
1859                        ERR_error_string(ERR_get_error(), NULL));
1860                 return NULL;
1861         }
1862
1863         /* Load the CAs we trust */
1864 load_ca:
1865         if (conf->ca_file || conf->ca_path) {
1866                 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
1867                         radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1868                         radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1869                         return NULL;
1870                 }
1871         }
1872         if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
1873
1874         if (conf->private_key_file) {
1875                 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
1876                         radlog(L_ERR, "Failed reading private key file %s:%s",
1877                                conf->private_key_file,
1878                                ERR_error_string(ERR_get_error(), NULL));
1879                         return NULL;
1880                 }
1881                 
1882                 /*
1883                  * Check if the loaded private key is the right one
1884                  */
1885                 if (!SSL_CTX_check_private_key(ctx)) {
1886                         radlog(L_ERR, "Private key does not match the certificate public key");
1887                         return NULL;
1888                 }
1889         }
1890
1891 #ifdef PSK_MAX_IDENTITY_LEN
1892 post_ca:
1893 #endif
1894
1895         /*
1896          *      Set ctx_options
1897          */
1898         ctx_options |= SSL_OP_NO_SSLv2;
1899         ctx_options |= SSL_OP_NO_SSLv3;
1900 #ifdef SSL_OP_NO_TICKET
1901         ctx_options |= SSL_OP_NO_TICKET ;
1902 #endif
1903
1904         /*
1905          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
1906          *      small subgroup attacks and forward secrecy. Always
1907          *      using
1908          *
1909          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
1910          *      time needed during negotiation, but it is not very
1911          *      large.
1912          */
1913         ctx_options |= SSL_OP_SINGLE_DH_USE;
1914
1915         /*
1916          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
1917          *      in Windows Vista client.
1918          *      http://www.openssl.org/~bodo/tls-cbc.txt
1919          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
1920          */
1921         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1922
1923         SSL_CTX_set_options(ctx, ctx_options);
1924
1925         /*
1926          *      TODO: Set the RSA & DH
1927          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
1928          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
1929          */
1930
1931         /*
1932          *      set the message callback to identify the type of
1933          *      message.  For every new session, there can be a
1934          *      different callback argument.
1935          *
1936          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
1937          */
1938
1939         /*
1940          *      Set eliptical curve crypto configuration.
1941          */
1942 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1943 #ifndef OPENSSL_NO_ECDH
1944         if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
1945                 return NULL;
1946         }
1947 #endif
1948 #endif
1949
1950         /* Set Info callback */
1951         SSL_CTX_set_info_callback(ctx, cbtls_info);
1952
1953         /*
1954          *      Callbacks, etc. for session resumption.
1955          */                                                   
1956         if (conf->session_cache_enable) {
1957                 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
1958                 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
1959                 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
1960
1961                 SSL_CTX_set_quiet_shutdown(ctx, 1);
1962                 if (FR_TLS_EX_INDEX_VPS < 0)
1963                         FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
1964         }
1965
1966         /*
1967          *      Check the certificates for revocation.
1968          */
1969 #ifdef X509_V_FLAG_CRL_CHECK
1970         if (conf->check_crl) {
1971           certstore = SSL_CTX_get_cert_store(ctx);
1972           if (certstore == NULL) {
1973             radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1974             radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
1975             return NULL;
1976           }
1977           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
1978         }
1979 #endif
1980
1981         /*
1982          *      Set verify modes
1983          *      Always verify the peer certificate
1984          */
1985         verify_mode |= SSL_VERIFY_PEER;
1986         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1987         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1988         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
1989
1990         if (conf->verify_depth) {
1991                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
1992         }
1993
1994         /* Load randomness */
1995         if (!(RAND_load_file(conf->random_file, 1024*1024))) {
1996                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1997                 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
1998                 return NULL;
1999         }
2000
2001         /*
2002          * Set the cipher list if we were told to
2003          */
2004         if (conf->cipher_list) {
2005                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2006                         radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
2007                         return NULL;
2008                 }
2009         }
2010
2011         /*
2012          *      Setup session caching
2013          */
2014         if (conf->session_cache_enable) {
2015                 /*
2016                  *      Create a unique context Id per EAP-TLS configuration.
2017                  */
2018                 if (conf->session_id_name) {
2019                         snprintf(conf->session_context_id,
2020                                  sizeof(conf->session_context_id),
2021                                  "FR eap %s",
2022                                  conf->session_id_name);
2023                 } else {
2024                         snprintf(conf->session_context_id,
2025                                  sizeof(conf->session_context_id),
2026                                  "FR eap %p", conf);
2027                 }
2028
2029                 /*
2030                  *      Cache it, and DON'T auto-clear it.
2031                  */
2032                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2033
2034                 SSL_CTX_set_session_id_context(ctx,
2035                                                (unsigned char *) conf->session_context_id,
2036                                                (unsigned int) strlen(conf->session_context_id));
2037
2038                 /*
2039                  *      Our timeout is in hours, this is in seconds.
2040                  */
2041                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2042
2043                 /*
2044                  *      Set the maximum number of entries in the
2045                  *      session cache.
2046                  */
2047                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2048
2049         } else {
2050                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2051         }
2052
2053         return ctx;
2054 }
2055
2056
2057 void tls_server_conf_free(fr_tls_server_conf_t *conf)
2058 {
2059         if (!conf) return;
2060
2061         if (conf->cs) cf_section_parse_free(conf->cs, conf);
2062
2063         if (conf->ctx) SSL_CTX_free(conf->ctx);
2064
2065 #ifdef HAVE_OPENSSL_OCSP_H
2066         if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2067         conf->ocsp_store = NULL;
2068 #endif
2069
2070         memset(conf, 0, sizeof(*conf));
2071         free(conf);
2072 }
2073
2074
2075 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2076 {
2077         fr_tls_server_conf_t *conf;
2078
2079         conf = malloc(sizeof(*conf));
2080         if (!conf) {
2081                 radlog(L_ERR, "Out of memory");
2082                 return NULL;
2083         }
2084         memset(conf, 0, sizeof(*conf));
2085
2086         if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2087         error:
2088                 tls_server_conf_free(conf);
2089                 return NULL;
2090         }
2091
2092         /*
2093          *      Save people from their own stupidity.
2094          */
2095         if (conf->fragment_size < 100) conf->fragment_size = 100;
2096
2097         /*
2098          *      This magic makes the administrators life HUGELY easier
2099          *      on initial deployments.
2100          *
2101          *      If the server starts up in debugging mode, AND the
2102          *      bootstrap command is configured, AND it exists, AND
2103          *      there is no server certificate
2104          */
2105         if (conf->make_cert_command && (debug_flag >= 2)) {
2106                 struct stat buf;
2107
2108                 if ((stat(conf->make_cert_command, &buf) == 0) &&
2109                     (stat(conf->certificate_file, &buf) < 0) &&
2110                     (errno == ENOENT) &&
2111                     (radius_exec_program(conf->make_cert_command, NULL, 1,
2112                                          NULL, 0, NULL, NULL, 0) != 0)) {
2113                         goto error;
2114                 }
2115         }
2116
2117         if (!conf->private_key_file) {
2118                 radlog(L_ERR, "TLS Server requires a private key file");
2119                 goto error;
2120         }
2121
2122         if (!conf->certificate_file) {
2123                 radlog(L_ERR, "TLS Server requires a certificate file");
2124                 goto error;
2125         }
2126
2127         /*
2128          *      Initialize TLS
2129          */
2130         conf->ctx = init_tls_ctx(conf, 0);
2131         if (conf->ctx == NULL) {
2132                 goto error;
2133         }
2134
2135 #ifdef HAVE_OPENSSL_OCSP_H
2136         /*
2137          *      Initialize OCSP Revocation Store
2138          */
2139         if (conf->ocsp_enable) {
2140                 conf->ocsp_store = init_revocation_store(conf);
2141                 if (conf->ocsp_store == NULL) goto error;
2142         }
2143 #endif /*HAVE_OPENSSL_OCSP_H*/
2144
2145         if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2146                 goto error;
2147         }
2148
2149         if (generate_eph_rsa_key(conf->ctx) < 0) {
2150                 goto error;
2151         }
2152
2153         if (conf->verify_tmp_dir) {
2154                 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2155                         radlog(L_ERR, "Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
2156                         goto error;
2157                 }
2158         }
2159
2160         if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2161                 radlog(L_ERR, "You MUST set the verify directory in order to use verify_client_cmd");
2162                 goto error;
2163         }
2164
2165         return conf;
2166 }
2167
2168 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2169 {
2170         fr_tls_server_conf_t *conf;
2171
2172         conf = malloc(sizeof(*conf));
2173         if (!conf) {
2174                 radlog(L_ERR, "Out of memory");
2175                 return NULL;
2176         }
2177         memset(conf, 0, sizeof(*conf));
2178
2179         if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2180         error:
2181                 tls_server_conf_free(conf);
2182                 return NULL;
2183         }
2184
2185         /*
2186          *      Save people from their own stupidity.
2187          */
2188         if (conf->fragment_size < 100) conf->fragment_size = 100;
2189
2190         /*
2191          *      Initialize TLS
2192          */
2193         conf->ctx = init_tls_ctx(conf, 1);
2194         if (conf->ctx == NULL) {
2195                 goto error;
2196         }
2197
2198         if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
2199                 goto error;
2200         }
2201
2202         if (generate_eph_rsa_key(conf->ctx) < 0) {
2203                 goto error;
2204         }
2205
2206         return conf;
2207 }
2208
2209 int tls_success(tls_session_t *ssn, REQUEST *request)
2210 {
2211         VALUE_PAIR *vp, *vps = NULL;
2212         fr_tls_server_conf_t *conf;
2213
2214         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2215         rad_assert(conf != NULL);
2216
2217         /*
2218          *      If there's no session resumption, delete the entry
2219          *      from the cache.  This means either it's disabled
2220          *      globally for this SSL context, OR we were told to
2221          *      disable it for this user.
2222          *
2223          *      This also means you can't turn it on just for one
2224          *      user.
2225          */
2226         if ((!ssn->allow_session_resumption) ||
2227             (((vp = pairfind(request->config_items, 1127, 0)) != NULL) &&
2228              (vp->vp_integer == 0))) {
2229                 SSL_CTX_remove_session(ssn->ctx,
2230                                        ssn->ssl->session);
2231                 ssn->allow_session_resumption = 0;
2232
2233                 /*
2234                  *      If we're in a resumed session and it's
2235                  *      not allowed, 
2236                  */
2237                 if (SSL_session_reused(ssn->ssl)) {
2238                         RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed.");
2239                         return -1;
2240                 }
2241                 
2242                 /*
2243                  *      Else resumption IS allowed, so we store the
2244                  *      user data in the cache.
2245                  */
2246         } else if (!SSL_session_reused(ssn->ssl)) {
2247                 size_t size;
2248                 char buffer[2 * MAX_SESSION_SIZE + 1];
2249
2250                 size = ssn->ssl->session->session_id_length;
2251                 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2252
2253                 fr_bin2hex(ssn->ssl->session->session_id, buffer, size);
2254
2255                 
2256                 vp = paircopy2(request->reply->vps, PW_USER_NAME, 0);
2257                 if (vp) pairadd(&vps, vp);
2258                 
2259                 vp = paircopy2(request->packet->vps, PW_STRIPPED_USER_NAME, 0);
2260                 if (vp) pairadd(&vps, vp);
2261                 
2262                 vp = paircopy2(request->reply->vps, PW_CACHED_SESSION_POLICY, 0);
2263                 if (vp) pairadd(&vps, vp);
2264                 
2265                 if (vps) {
2266                         RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2267                         SSL_SESSION_set_ex_data(ssn->ssl->session,
2268                                                 FR_TLS_EX_INDEX_VPS, vps);
2269                 } else {
2270                         RDEBUG2("WARNING: No information to cache: session caching will be disabled for session %s", buffer);
2271                         SSL_CTX_remove_session(ssn->ctx,
2272                                                ssn->ssl->session);
2273                 }
2274
2275                 /*
2276                  *      Else the session WAS allowed.  Copy the cached
2277                  *      reply.
2278                  */
2279         } else {
2280                 size_t size;
2281                 char buffer[2 * MAX_SESSION_SIZE + 1];
2282
2283                 size = ssn->ssl->session->session_id_length;
2284                 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2285
2286                 fr_bin2hex(ssn->ssl->session->session_id, buffer, size);
2287
2288                
2289                 vp = SSL_SESSION_get_ex_data(ssn->ssl->session,
2290                                              FR_TLS_EX_INDEX_VPS);
2291                 if (!vp) {
2292                         RDEBUG("WARNING: No information in cached session %s", buffer);
2293                         return -1;
2294
2295                 } else {
2296                         RDEBUG("Adding cached attributes for session %s vps %p to the reply:", buffer, vp);
2297                         debug_pair_list(vp);
2298                         pairadd(&request->reply->vps, paircopy(vp));
2299
2300                         /*
2301                          *      Mark the request as resumed.
2302                          */
2303                         vp = pairmake("EAP-Session-Resumed", "1", T_OP_SET);
2304                         if (vp) pairadd(&request->packet->vps, vp);
2305                 }
2306         }
2307
2308         return 0;
2309 }
2310
2311
2312 void tls_fail(tls_session_t *ssn)
2313 {
2314         /*
2315          *      Force the session to NOT be cached.
2316          */
2317         SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2318 }
2319
2320 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2321                                      REQUEST *request)
2322                                      
2323 {
2324         int err;
2325
2326         /*      
2327          *      Decrypt the complete record.
2328          */
2329         err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2330                         ssn->dirty_in.used);
2331         if (err != (int) ssn->dirty_in.used) {
2332                 record_init(&ssn->dirty_in);
2333                 RDEBUG("Failed writing %d to SSL BIO: %d",
2334                        ssn->dirty_in.used, err);
2335                 return FR_TLS_FAIL;
2336         }
2337         
2338         /*
2339          *      Clear the dirty buffer now that we are done with it
2340          *      and init the clean_out buffer to store decrypted data
2341          */
2342         record_init(&ssn->dirty_in);
2343         record_init(&ssn->clean_out);
2344         
2345         /*
2346          *      Read (and decrypt) the tunneled data from the
2347          *      SSL session, and put it into the decrypted
2348          *      data buffer.
2349          */
2350         err = SSL_read(ssn->ssl, ssn->clean_out.data,
2351                        sizeof(ssn->clean_out.data));
2352         
2353         if (err < 0) {
2354                 int code;
2355
2356                 RDEBUG("SSL_read Error");
2357                 
2358                 code = SSL_get_error(ssn->ssl, err);
2359                 switch (code) {
2360                 case SSL_ERROR_WANT_READ:
2361                         return FR_TLS_MORE_FRAGMENTS;
2362                         DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2363                         break;
2364
2365                 case SSL_ERROR_WANT_WRITE:
2366                         DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2367                         break;
2368
2369                 default:
2370                         DEBUG("Error in fragmentation logic: ?");
2371
2372                         /*
2373                          *      FIXME: Call int_ssl_check?
2374                          */
2375                         break;
2376                 }
2377                 return FR_TLS_FAIL;
2378         }
2379         
2380         if (err == 0) {
2381                 RDEBUG("WARNING: No data inside of the tunnel.");
2382         }
2383         
2384         /*
2385          *      Passed all checks, successfully decrypted data
2386          */
2387         ssn->clean_out.used = err;
2388         
2389         return FR_TLS_OK;
2390 }
2391
2392
2393 /*
2394  * Acknowledge received is for one of the following messages sent earlier
2395  * 1. Handshake completed Message, so now send, EAP-Success
2396  * 2. Alert Message, now send, EAP-Failure
2397  * 3. Fragment Message, now send, next Fragment
2398  */
2399 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2400 {
2401         RDEBUG2("Received TLS ACK");
2402
2403         if (ssn == NULL){
2404                 radlog_request(L_ERR, 0, request, "FAIL: Unexpected ACK received.  Could not obtain session information.");
2405                 return FR_TLS_INVALID;
2406         }
2407         if (ssn->info.initialized == 0) {
2408                 RDEBUG("No SSL info available. Waiting for more SSL data.");
2409                 return FR_TLS_REQUEST;
2410         }
2411         if ((ssn->info.content_type == handshake) &&
2412             (ssn->info.origin == 0)) {
2413                 radlog_request(L_ERR, 0, request, "FAIL: ACK without earlier message.");
2414                 return FR_TLS_INVALID;
2415         }
2416
2417         switch (ssn->info.content_type) {
2418         case alert:
2419                 RDEBUG2("ACK alert");
2420                 return FR_TLS_FAIL;
2421
2422         case handshake:
2423                 if ((ssn->info.handshake_type == finished) &&
2424                     (ssn->dirty_out.used == 0)) {
2425                         RDEBUG2("ACK handshake is finished");
2426
2427                         /* 
2428                          *      From now on all the content is
2429                          *      application data set it here as nobody else
2430                          *      sets it.
2431                          */
2432                         ssn->info.content_type = application_data;
2433                         return FR_TLS_SUCCESS;
2434                 } /* else more data to send */
2435
2436                 RDEBUG2("ACK handshake fragment handler");
2437                 /* Fragmentation handler, send next fragment */
2438                 return FR_TLS_REQUEST;
2439
2440         case application_data:
2441                 RDEBUG2("ACK handshake fragment handler in application data");
2442                 return FR_TLS_REQUEST;
2443                                                 
2444                 /*
2445                  *      For the rest of the conditions, switch over
2446                  *      to the default section below.
2447                  */
2448         default:
2449                 RDEBUG2("ACK default");
2450                 radlog_request(L_ERR, 0, request, "Invalid ACK received: %d",
2451                        ssn->info.content_type);
2452                 return FR_TLS_INVALID;
2453         }
2454 }
2455
2456 #endif  /* WITH_TLS */