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