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