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