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