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