Add compile time checking for config pointers
[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", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
781         { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
782         { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
783         { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
784         { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
785         { NULL, -1, 0, NULL, NULL }        /* end the list */
786 };
787
788 static CONF_PARSER verify_config[] = {
789         { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
790         { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
791         { NULL, -1, 0, NULL, NULL }        /* end the list */
792 };
793
794 #ifdef HAVE_OPENSSL_OCSP_H
795 static CONF_PARSER ocsp_config[] = {
796         { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
797         { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
798         { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
799         { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
800         { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
801         { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "yes" },
802         { NULL, -1, 0, NULL, NULL }        /* end the list */
803 };
804 #endif
805
806 static CONF_PARSER tls_server_config[] = {
807         { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
808         { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
809         { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
810         { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
811         { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
812         { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
813         { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
814         { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
815         { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
816         { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
817         { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
818         { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
819         { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
820 #ifdef PSK_MAX_IDENTITY_LEN
821         { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
822         { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
823 #endif
824         { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
825         { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
826         { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
827         { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
828         { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
829         { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
830         { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
831         { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
832         { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
833         { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
834
835 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
836 #ifndef OPENSSL_NO_ECDH
837         { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
838 #endif
839 #endif
840
841         { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
842
843         { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
844
845 #ifdef HAVE_OPENSSL_OCSP_H
846         { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
847 #endif
848
849         { NULL, -1, 0, NULL, NULL }        /* end the list */
850 };
851
852
853 static CONF_PARSER tls_client_config[] = {
854         { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
855         { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
856         { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
857         { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
858         { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
859         { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
860         { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
861         { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
862         { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
863         { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
864         { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
865         { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
866         { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
867         { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
868         { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
869         { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
870         { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
871         { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
872         { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
873
874 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
875 #ifndef OPENSSL_NO_ECDH
876         { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
877 #endif
878 #endif
879
880         { NULL, -1, 0, NULL, NULL }        /* end the list */
881 };
882
883
884 /*
885  *      TODO: Check for the type of key exchange * like conf->dh_key
886  */
887 static int load_dh_params(SSL_CTX *ctx, char *file)
888 {
889         DH *dh = NULL;
890         BIO *bio;
891
892         if (!file) return 0;
893
894         if ((bio = BIO_new_file(file, "r")) == NULL) {
895                 ERROR("tls: Unable to open DH file - %s", file);
896                 return -1;
897         }
898
899         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
900         BIO_free(bio);
901         if (!dh) {
902                 WARN("tls: Unable to set DH parameters.  DH cipher suites may not work!");
903                 WARN("Fix this by running the OpenSSL command listed in eap.conf");
904                 return 0;
905         }
906
907         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
908                 ERROR("tls: Unable to set DH parameters");
909                 DH_free(dh);
910                 return -1;
911         }
912
913         DH_free(dh);
914         return 0;
915 }
916
917
918 /*
919  *      Generate ephemeral RSA keys.
920  */
921 static int generate_eph_rsa_key(SSL_CTX *ctx)
922 {
923         RSA *rsa;
924
925         rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
926
927         if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
928                 ERROR("tls: Couldn't set ephemeral RSA key");
929                 return -1;
930         }
931
932         RSA_free(rsa);
933         return 0;
934 }
935
936 /* index we use to store cached session VPs
937  * needs to be dynamic so we can supply a "free" function
938  */
939 static int FR_TLS_EX_INDEX_VPS = -1;
940 int FR_TLS_EX_INDEX_CERTS = -1;
941
942 /*
943  *      Print debugging messages, and free data.
944  *
945  *      FIXME: Write sessions to some long-term storage, so that
946  *             session resumption can still occur after the server
947  *             restarts.
948  */
949 #define MAX_SESSION_SIZE (256)
950
951 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
952 {
953         size_t size;
954         char buffer[2 * MAX_SESSION_SIZE + 1];
955         fr_tls_server_conf_t *conf;
956
957         size = sess->session_id_length;
958         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
959
960         fr_bin2hex(buffer, sess->session_id, size);
961
962         DEBUG2("  SSL: Removing session %s from the cache", buffer);
963         conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
964         if (conf && conf->session_cache_path) {
965                 int rv;
966                 char filename[256];
967
968                 /* remove session and any cached VPs */
969                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
970                          conf->session_cache_path, FR_DIR_SEP, buffer);
971                 rv = unlink(filename);
972                 if (rv != 0) {
973                         DEBUG2("  SSL: could not remove persisted session file %s: %s", filename, fr_syserror(errno));
974                 }
975                 /* VPs might be absent; might not have been written to disk yet */
976                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
977                          conf->session_cache_path, FR_DIR_SEP, buffer);
978                 unlink(filename);
979         }
980
981         return;
982 }
983
984 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
985 {
986         size_t size;
987         char buffer[2 * MAX_SESSION_SIZE + 1];
988         fr_tls_server_conf_t *conf;
989         unsigned char *sess_blob = NULL;
990
991         size = sess->session_id_length;
992         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
993
994         fr_bin2hex(buffer, sess->session_id, size);
995
996         DEBUG2("  SSL: adding session %s to cache", buffer);
997
998         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
999         if (conf && conf->session_cache_path) {
1000                 int fd, rv, todo, blob_len;
1001                 char filename[256];
1002                 unsigned char *p;
1003
1004                 /* find out what length data we need */
1005                 blob_len = i2d_SSL_SESSION(sess, NULL);
1006                 if (blob_len < 1) {
1007                         /* something went wrong */
1008                         DEBUG2("  SSL: could not find buffer length to persist session");
1009                         return 0;
1010                 }
1011
1012                 /* alloc and convert to ASN.1 */
1013                 sess_blob = talloc_array(conf, unsigned char, blob_len);
1014                 if (!sess_blob) {
1015                         DEBUG2("  SSL: could not allocate buffer len=%d to persist session", blob_len);
1016                         return 0;
1017                 }
1018                 /* openssl mutates &p */
1019                 p = sess_blob;
1020                 rv = i2d_SSL_SESSION(sess, &p);
1021                 if (rv != blob_len) {
1022                         DEBUG2("  SSL: could not persist session");
1023                         goto error;
1024                 }
1025
1026                 /* open output file */
1027                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1028                          conf->session_cache_path, FR_DIR_SEP, buffer);
1029                 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1030                 if (fd < 0) {
1031                         DEBUG2("  SSL: could not open session file %s: %s", filename, fr_syserror(errno));
1032                         goto error;
1033                 }
1034
1035                 todo = blob_len;
1036                 p = sess_blob;
1037                 while (todo > 0) {
1038                         rv = write(fd, p, todo);
1039                         if (rv < 1) {
1040                                 DEBUG2("  SSL: failed writing session: %s", fr_syserror(errno));
1041                                 close(fd);
1042                                 goto error;
1043                         }
1044                         p += rv;
1045                         todo -= rv;
1046                 }
1047                 close(fd);
1048                 DEBUG2("  SSL: wrote session %s to %s len=%d", buffer, filename, blob_len);
1049         }
1050
1051 error:
1052         if (sess_blob) talloc_free(sess_blob);
1053
1054         return 0;
1055 }
1056
1057 static SSL_SESSION *cbtls_get_session(SSL *ssl,
1058                                       unsigned char *data, int len,
1059                                       int *copy)
1060 {
1061         size_t size;
1062         char buffer[2 * MAX_SESSION_SIZE + 1];
1063         fr_tls_server_conf_t *conf;
1064         TALLOC_CTX *talloc_ctx;
1065
1066         SSL_SESSION *sess = NULL;
1067         unsigned char *sess_data = NULL;
1068         PAIR_LIST *pairlist = NULL;
1069
1070         size = len;
1071         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1072
1073         fr_bin2hex(buffer, data, size);
1074
1075         DEBUG2("  SSL: Client requested cached session %s", buffer);
1076
1077         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1078         talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1079         if (conf && conf->session_cache_path) {
1080                 int rv, fd, todo;
1081                 char filename[256];
1082                 unsigned char *p;
1083                 struct stat st;
1084                 VALUE_PAIR *vp;
1085
1086                 /* read in the cached VPs from the .vps file */
1087                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1088                          conf->session_cache_path, FR_DIR_SEP, buffer);
1089                 rv = pairlist_read(NULL, filename, &pairlist, 1);
1090                 if (rv < 0) {
1091                         /* not safe to un-persist a session w/o VPs */
1092                         DEBUG2("  SSL: could not load persisted VPs for session %s", buffer);
1093                         goto err;
1094                 }
1095
1096                 /* load the actual SSL session */
1097                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1098                          conf->session_cache_path, FR_DIR_SEP, buffer);
1099                 fd = open(filename, O_RDONLY);
1100                 if (fd < 0) {
1101                         DEBUG2("  SSL: could not find persisted session file %s: %s", filename, fr_syserror(errno));
1102                         goto err;
1103                 }
1104
1105                 rv = fstat(fd, &st);
1106                 if (rv < 0) {
1107                         DEBUG2("  SSL: could not stat persisted session file %s: %s", filename, fr_syserror(errno));
1108                         close(fd);
1109                         goto err;
1110                 }
1111
1112                 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1113                 if (!sess_data) {
1114                   DEBUG2("  SSL: could not alloc buffer for persisted session len=%d", (int) st.st_size);
1115                         close(fd);
1116                         goto err;
1117                 }
1118
1119                 p = sess_data;
1120                 todo = st.st_size;
1121                 while (todo > 0) {
1122                         rv = read(fd, p, todo);
1123                         if (rv < 1) {
1124                                 DEBUG2("  SSL: could not read from persisted session: %s", fr_syserror(errno));
1125                                 close(fd);
1126                                 goto err;
1127                         }
1128                         todo -= rv;
1129                         p += rv;
1130                 }
1131                 close(fd);
1132
1133                 /* openssl mutates &p */
1134                 p = sess_data;
1135                 sess = d2i_SSL_SESSION(NULL, (unsigned char const **)(void **) &p, st.st_size);
1136
1137                 if (!sess) {
1138                         DEBUG2("  SSL: OpenSSL failed to load persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1139                         goto err;
1140                 }
1141
1142                 /* cache the VPs into the session */
1143                 vp = paircopy(talloc_ctx, pairlist->reply);
1144                 SSL_SESSION_set_ex_data(sess, FR_TLS_EX_INDEX_VPS, vp);
1145                 DEBUG2("  SSL: Successfully restored session %s", buffer);
1146         }
1147 err:
1148         if (sess_data) talloc_free(sess_data);
1149         if (pairlist) pairlist_free(&pairlist);
1150
1151         *copy = 0;
1152         return sess;
1153 }
1154
1155 #ifdef HAVE_OPENSSL_OCSP_H
1156 /*
1157  * This function extracts the OCSP Responder URL
1158  * from an existing x509 certificate.
1159  */
1160 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
1161                                char **ppath, int *pssl)
1162 {
1163         int i;
1164
1165         AUTHORITY_INFO_ACCESS *aia;
1166         ACCESS_DESCRIPTION *ad;
1167
1168         aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1169
1170         for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1171                 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
1172                 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
1173                         if (ad->location->type == GEN_URI) {
1174                           if(OCSP_parse_url((char *) ad->location->d.ia5->data,
1175                                                   phost, pport, ppath, pssl))
1176                                         return 1;
1177                         }
1178                 }
1179         }
1180         return 0;
1181 }
1182
1183 /*
1184  * This function sends a OCSP request to a defined OCSP responder
1185  * and checks the OCSP response for correctness.
1186  */
1187
1188 /* Maximum leeway in validity period: default 5 minutes */
1189 #define MAX_VALIDITY_PERIOD     (5 * 60)
1190
1191 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1192                       fr_tls_server_conf_t *conf)
1193 {
1194         OCSP_CERTID *certid;
1195         OCSP_REQUEST *req;
1196         OCSP_RESPONSE *resp = NULL;
1197         OCSP_BASICRESP *bresp = NULL;
1198         char *host = NULL;
1199         char *port = NULL;
1200         char *path = NULL;
1201         int use_ssl = -1;
1202         long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1203         BIO *cbio, *bio_out;
1204         int ocsp_ok = 0;
1205         int status ;
1206         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1207         int reason;
1208 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1209         OCSP_REQ_CTX *ctx;
1210         int rc;
1211         struct timeval now;
1212         struct timeval when;
1213 #endif
1214
1215         /*
1216          * Create OCSP Request
1217          */
1218         certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1219         req = OCSP_REQUEST_new();
1220         OCSP_request_add0_id(req, certid);
1221         if(conf->ocsp_use_nonce) {
1222                 OCSP_request_add1_nonce(req, NULL, 8);
1223         }
1224
1225         /*
1226          * Send OCSP Request and get OCSP Response
1227          */
1228
1229         /* Get OCSP responder URL */
1230         if (conf->ocsp_override_url) {
1231                 char *url;
1232
1233                 memcpy(&url, &conf->ocsp_url, sizeof(url));
1234                 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1235                 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1236         }
1237         else {
1238                 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1239         }
1240
1241         if (!host || !port || !path) {
1242                 DEBUG2("[ocsp] - Host / port / path missing.  Not doing OCSP");
1243                 ocsp_ok = 2;
1244                 goto ocsp_skip;
1245         }
1246
1247         DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
1248
1249         /* Setup BIO socket to OCSP responder */
1250         cbio = BIO_new_connect(host);
1251
1252         bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1253
1254         BIO_set_conn_port(cbio, port);
1255 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1256         BIO_do_connect(cbio);
1257
1258         /* Send OCSP request and wait for response */
1259         resp = OCSP_sendreq_bio(cbio, path, req);
1260         if (!resp) {
1261                 ERROR("Couldn't get OCSP response");
1262                 ocsp_ok = 2;
1263                 goto ocsp_end;
1264         }
1265 #else
1266         if (conf->ocsp_timeout)
1267                 BIO_set_nbio(cbio, 1);
1268
1269         rc = BIO_do_connect(cbio);
1270         if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1271                 ERROR("Couldn't connect to OCSP responder");
1272                 ocsp_ok = 2;
1273                 goto ocsp_end;
1274         }
1275
1276         ctx = OCSP_sendreq_new(cbio, path, req, -1);
1277         if (!ctx) {
1278                 ERROR("Couldn't send OCSP request");
1279                 ocsp_ok = 2;
1280                 goto ocsp_end;
1281         }
1282
1283         gettimeofday(&when, NULL);
1284         when.tv_sec += conf->ocsp_timeout;
1285
1286         do {
1287                 rc = OCSP_sendreq_nbio(&resp, ctx);
1288                 if (conf->ocsp_timeout) {
1289                         gettimeofday(&now, NULL);
1290                         if (!timercmp(&now, &when, <))
1291                                 break;
1292                 }
1293         } while ((rc == -1) && BIO_should_retry(cbio));
1294
1295         if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1296                 ERROR("OCSP response timed out");
1297                 ocsp_ok = 2;
1298                 goto ocsp_end;
1299         }
1300
1301         OCSP_REQ_CTX_free(ctx);
1302
1303         if (rc == 0) {
1304                 ERROR("Couldn't get OCSP response");
1305                 ocsp_ok = 2;
1306                 goto ocsp_end;
1307         }
1308 #endif
1309
1310         /* Verify OCSP response status */
1311         status = OCSP_response_status(resp);
1312         DEBUG2("[ocsp] --> Response status: %s",OCSP_response_status_str(status));
1313         if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1314                 ERROR("OCSP response status: %s", OCSP_response_status_str(status));
1315                 goto ocsp_end;
1316         }
1317         bresp = OCSP_response_get1_basic(resp);
1318         if(conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1319                 ERROR("OCSP response has wrong nonce value");
1320                 goto ocsp_end;
1321         }
1322         if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1323                 ERROR("Couldn't verify OCSP basic response");
1324                 goto ocsp_end;
1325         }
1326
1327         /*      Verify OCSP cert status */
1328         if(!OCSP_resp_find_status(bresp, certid, &status, &reason,
1329                                                       &rev, &thisupd, &nextupd)) {
1330                 ERROR("No Status found.\n");
1331                 goto ocsp_end;
1332         }
1333
1334         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1335                 BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1336                 ERR_print_errors(bio_out);
1337                 goto ocsp_end;
1338         }
1339         BIO_puts(bio_out, "\tThis Update: ");
1340         ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1341         BIO_puts(bio_out, "\n");
1342         if (nextupd) {
1343                 BIO_puts(bio_out, "\tNext Update: ");
1344                 ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1345                 BIO_puts(bio_out, "\n");
1346         }
1347
1348         switch (status) {
1349         case V_OCSP_CERTSTATUS_GOOD:
1350                 DEBUG2("[oscp] --> Cert status: good");
1351                 ocsp_ok = 1;
1352                 break;
1353
1354         default:
1355                 /* REVOKED / UNKNOWN */
1356                 DEBUG2("[ocsp] --> Cert status: %s",OCSP_cert_status_str(status));
1357                 if (reason != -1)
1358                         DEBUG2("[ocsp] --> Reason: %s", OCSP_crl_reason_str(reason));
1359                 BIO_puts(bio_out, "\tRevocation Time: ");
1360                 ASN1_GENERALIZEDTIME_print(bio_out, rev);
1361                 BIO_puts(bio_out, "\n");
1362                 break;
1363         }
1364
1365 ocsp_end:
1366         /* Free OCSP Stuff */
1367         OCSP_REQUEST_free(req);
1368         OCSP_RESPONSE_free(resp);
1369         free(host);
1370         free(port);
1371         free(path);
1372         BIO_free_all(cbio);
1373         OCSP_BASICRESP_free(bresp);
1374
1375  ocsp_skip:
1376         switch (ocsp_ok) {
1377         case 1:
1378                 DEBUG2("[ocsp] --> Certificate is valid!");
1379                 break;
1380         case 2:
1381                 if (conf->ocsp_softfail) {
1382                         DEBUG2("[ocsp] --> Unable to check certificate; assuming valid");
1383                         DEBUG2("[ocsp] --> Warning! This may be insecure");
1384                         ocsp_ok = 1;
1385                 } else {
1386                         DEBUG2("[ocsp] --> Unable to check certificate; failing!");
1387                         ocsp_ok = 0;
1388                 }
1389                 break;
1390         default:
1391                 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
1392                 break;
1393         }
1394
1395         return ocsp_ok;
1396 }
1397 #endif  /* HAVE_OPENSSL_OCSP_H */
1398
1399 /*
1400  *      For creating certificate attributes.
1401  */
1402 static char const *cert_attr_names[8][2] = {
1403   { "TLS-Client-Cert-Serial",           "TLS-Cert-Serial" },
1404   { "TLS-Client-Cert-Expiration",       "TLS-Cert-Expiration" },
1405   { "TLS-Client-Cert-Subject",          "TLS-Cert-Subject" },
1406   { "TLS-Client-Cert-Issuer",           "TLS-Cert-Issuer" },
1407   { "TLS-Client-Cert-Common-Name",      "TLS-Cert-Common-Name" },
1408   { "TLS-Client-Cert-Subject-Alt-Name-Email",   "TLS-Cert-Subject-Alt-Name-Email" },
1409   { "TLS-Client-Cert-Subject-Alt-Name-Dns",     "TLS-Cert-Subject-Alt-Name-Dns" },
1410   { "TLS-Client-Cert-Subject-Alt-Name-Upn",     "TLS-Cert-Subject-Alt-Name-Upn" }
1411 };
1412
1413 #define FR_TLS_SERIAL           (0)
1414 #define FR_TLS_EXPIRATION       (1)
1415 #define FR_TLS_SUBJECT          (2)
1416 #define FR_TLS_ISSUER           (3)
1417 #define FR_TLS_CN               (4)
1418 #define FR_TLS_SAN_EMAIL        (5)
1419 #define FR_TLS_SAN_DNS          (6)
1420 #define FR_TLS_SAN_UPN          (7)
1421
1422 /*
1423  *      Before trusting a certificate, you must make sure that the
1424  *      certificate is 'valid'. There are several steps that your
1425  *      application can take in determining if a certificate is
1426  *      valid. Commonly used steps are:
1427  *
1428  *      1.Verifying the certificate's signature, and verifying that
1429  *      the certificate has been issued by a trusted Certificate
1430  *      Authority.
1431  *
1432  *      2.Verifying that the certificate is valid for the present date
1433  *      (i.e. it is being presented within its validity dates).
1434  *
1435  *      3.Verifying that the certificate has not been revoked by its
1436  *      issuing Certificate Authority, by checking with respect to a
1437  *      Certificate Revocation List (CRL).
1438  *
1439  *      4.Verifying that the credentials presented by the certificate
1440  *      fulfill additional requirements specific to the application,
1441  *      such as with respect to access control lists or with respect
1442  *      to OCSP (Online Certificate Status Processing).
1443  *
1444  *      NOTE: This callback will be called multiple times based on the
1445  *      depth of the root certificate chain
1446  */
1447 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1448 {
1449         char subject[1024]; /* Used for the subject name */
1450         char issuer[1024]; /* Used for the issuer name */
1451         char attribute[1024];
1452         char value[1024];
1453         char common_name[1024];
1454         char cn_str[1024];
1455         char buf[64];
1456         X509 *client_cert;
1457         X509_CINF *client_inf;
1458         STACK_OF(X509_EXTENSION) *ext_list;
1459         SSL *ssl;
1460         int err, depth, lookup, loc;
1461         fr_tls_server_conf_t *conf;
1462         int my_ok = ok;
1463         REQUEST *request;
1464         ASN1_INTEGER *sn = NULL;
1465         ASN1_TIME *asn_time = NULL;
1466         VALUE_PAIR **certs;
1467         char **identity;
1468 #ifdef HAVE_OPENSSL_OCSP_H
1469         X509_STORE *ocsp_store = NULL;
1470         X509 *issuer_cert;
1471 #endif
1472         TALLOC_CTX *talloc_ctx;
1473
1474         client_cert = X509_STORE_CTX_get_current_cert(ctx);
1475         err = X509_STORE_CTX_get_error(ctx);
1476         depth = X509_STORE_CTX_get_error_depth(ctx);
1477
1478         lookup = depth;
1479
1480         /*
1481          *      Log client/issuing cert.  If there's an error, log
1482          *      issuing cert.
1483          */
1484         if ((lookup > 1) && !my_ok) lookup = 1;
1485
1486         /*
1487          * Retrieve the pointer to the SSL of the connection currently treated
1488          * and the application specific data stored into the SSL object.
1489          */
1490         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1491         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1492         if (!conf) return 1;
1493
1494         request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1495
1496         if (!request) return 1; /* FIXME: outbound TLS */
1497
1498         rad_assert(request != NULL);
1499         certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1500         rad_assert(certs != NULL);
1501         identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1502 #ifdef HAVE_OPENSSL_OCSP_H
1503         ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1504 #endif
1505
1506         talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1507
1508         /*
1509          *      Get the Serial Number
1510          */
1511         buf[0] = '\0';
1512         sn = X509_get_serialNumber(client_cert);
1513
1514         /*
1515          *      For this next bit, we create the attributes *only* if
1516          *      we're at the client or issuing certificate, AND we
1517          *      have a user identity.  i.e. we don't create the
1518          *      attributes for RadSec connections.
1519          */
1520         if (identity &&
1521             (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1522                 char *p = buf;
1523                 int i;
1524
1525                 for (i = 0; i < sn->length; i++) {
1526                         sprintf(p, "%02x", (unsigned int)sn->data[i]);
1527                         p += 2;
1528                 }
1529                 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1530         }
1531
1532
1533         /*
1534          *      Get the Expiration Date
1535          */
1536         buf[0] = '\0';
1537         asn_time = X509_get_notAfter(client_cert);
1538         if (identity && (lookup <= 1) && asn_time &&
1539             (asn_time->length < (int) sizeof(buf))) {
1540                 memcpy(buf, (char*) asn_time->data, asn_time->length);
1541                 buf[asn_time->length] = '\0';
1542                 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1543         }
1544
1545         /*
1546          *      Get the Subject & Issuer
1547          */
1548         subject[0] = issuer[0] = '\0';
1549         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1550                           sizeof(subject));
1551         subject[sizeof(subject) - 1] = '\0';
1552         if (identity && (lookup <= 1) && subject[0]) {
1553                 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1554         }
1555
1556         X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1557                           sizeof(issuer));
1558         issuer[sizeof(issuer) - 1] = '\0';
1559         if (identity && (lookup <= 1) && issuer[0]) {
1560                 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1561         }
1562
1563         /*
1564          *      Get the Common Name, if there is a subject.
1565          */
1566         X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1567                                   NID_commonName, common_name, sizeof(common_name));
1568         common_name[sizeof(common_name) - 1] = '\0';
1569         if (identity && (lookup <= 1) && common_name[0] && subject[0]) {
1570                 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1571         }
1572
1573         /*
1574          *      Get the RFC822 Subject Alternative Name
1575          */
1576         loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1577         if (lookup <= 1 && loc >= 0) {
1578                 X509_EXTENSION *ext = NULL;
1579                 GENERAL_NAMES *names = NULL;
1580                 int i;
1581
1582                 if ((ext = X509_get_ext(client_cert, loc)) &&
1583                     (names = X509V3_EXT_d2i(ext))) {
1584                         for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1585                                 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1586
1587                                 switch (name->type) {
1588 #ifdef GEN_EMAIL
1589                                 case GEN_EMAIL:
1590                                         pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1591                                                  (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1592                                         break;
1593 #endif  /* GEN_EMAIL */
1594 #ifdef GEN_DNS
1595                                 case GEN_DNS:
1596                                         pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1597                                                  (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1598                                         break;
1599 #endif  /* GEN_DNS */
1600 #ifdef GEN_OTHERNAME
1601                                 case GEN_OTHERNAME:
1602                                         /* look for a MS UPN */
1603                                         if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1604                                             /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1605                                             if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1606                                                 pairmake(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1607                                                          (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1608                                                 break;
1609                                             } else {
1610                                                 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)\n");
1611                                                 break;
1612                                             }
1613                                         }
1614                                         break;
1615 #endif  /* GEN_OTHERNAME */
1616                                 default:
1617                                         /* XXX TODO handle other SAN types */
1618                                         break;
1619                                 }
1620                         }
1621                 }
1622                 if (names != NULL)
1623                         sk_GENERAL_NAME_free(names);
1624         }
1625
1626         /*
1627          *      If the CRL has expired, that might still be OK.
1628          */
1629         if (!my_ok &&
1630             (conf->allow_expired_crl) &&
1631             (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1632                 my_ok = 1;
1633                 X509_STORE_CTX_set_error( ctx, 0 );
1634         }
1635
1636         if (!my_ok) {
1637                 char const *p = X509_verify_cert_error_string(err);
1638                 ERROR("--> verify error:num=%d:%s\n",err, p);
1639                 REDEBUG("SSL says error %d : %s", err, p);
1640                 return my_ok;
1641         }
1642
1643         if (lookup == 0) {
1644                 client_inf = client_cert->cert_info;
1645                 ext_list = client_inf->extensions;
1646         } else {
1647                 ext_list = NULL;
1648         }
1649
1650         /*
1651          *      Grab the X509 extensions, and create attributes out of them.
1652          *      For laziness, we re-use the OpenSSL names
1653          */
1654         if (sk_X509_EXTENSION_num(ext_list) > 0) {
1655                 int i, len;
1656                 char *p;
1657                 BIO *out;
1658
1659                 out = BIO_new(BIO_s_mem());
1660                 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1661
1662                 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1663                         ASN1_OBJECT *obj;
1664                         X509_EXTENSION *ext;
1665                         VALUE_PAIR *vp;
1666
1667                         ext = sk_X509_EXTENSION_value(ext_list, i);
1668
1669                         obj = X509_EXTENSION_get_object(ext);
1670                         i2a_ASN1_OBJECT(out, obj);
1671                         len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1672                         if (len <= 0) continue;
1673
1674                         attribute[16 + len] = '\0';
1675
1676                         X509V3_EXT_print(out, ext, 0, 0);
1677                         len = BIO_read(out, value , sizeof(value) - 1);
1678                         if (len <= 0) continue;
1679
1680                         value[len] = '\0';
1681
1682                         /*
1683                          *      Mash the OpenSSL name to our name, and
1684                          *      create the attribute.
1685                          */
1686                         for (p = value + 16; *p != '\0'; p++) {
1687                                 if (*p == ' ') *p = '-';
1688                         }
1689
1690                         vp = pairmake(talloc_ctx, certs, attribute, value, T_OP_ADD);
1691                         if (vp) debug_pair_list(vp);
1692                 }
1693
1694                 BIO_free_all(out);
1695         }
1696
1697         switch (ctx->error) {
1698
1699         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1700                 ERROR("issuer= %s\n", issuer);
1701                 break;
1702         case X509_V_ERR_CERT_NOT_YET_VALID:
1703         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1704                 ERROR("notBefore=");
1705 #if 0
1706                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1707 #endif
1708                 break;
1709         case X509_V_ERR_CERT_HAS_EXPIRED:
1710         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1711                 ERROR("notAfter=");
1712 #if 0
1713                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1714 #endif
1715                 break;
1716         }
1717
1718         /*
1719          *      If we're at the actual client cert, apply additional
1720          *      checks.
1721          */
1722         if (depth == 0) {
1723                 /*
1724                  *      If the conf tells us to, check cert issuer
1725                  *      against the specified value and fail
1726                  *      verification if they don't match.
1727                  */
1728                 if (conf->check_cert_issuer &&
1729                     (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1730                         AUTH("tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1731                         my_ok = 0;
1732                 }
1733
1734                 /*
1735                  *      If the conf tells us to, check the CN in the
1736                  *      cert against xlat'ed value, but only if the
1737                  *      previous checks passed.
1738                  */
1739                 if (my_ok && conf->check_cert_cn) {
1740                         if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
1741                                 /* if this fails, fail the verification */
1742                                 my_ok = 0;
1743                         } else {
1744                                 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1745                                 if (strcmp(cn_str, common_name) != 0) {
1746                                         AUTH("tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1747                                         my_ok = 0;
1748                                 }
1749                         }
1750                 } /* check_cert_cn */
1751
1752 #ifdef HAVE_OPENSSL_OCSP_H
1753                 if (my_ok && conf->ocsp_enable){
1754                         RDEBUG2("--> Starting OCSP Request");
1755                         if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1756                                 ERROR("Couldn't get issuer_cert for %s", common_name);
1757                         }
1758                         my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1759                 }
1760 #endif
1761
1762                 while (conf->verify_client_cert_cmd) {
1763                         char filename[256];
1764                         int fd;
1765                         FILE *fp;
1766
1767                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1768                                  conf->verify_tmp_dir, progname);
1769                         fd = mkstemp(filename);
1770                         if (fd < 0) {
1771                                 RDEBUG("Failed creating file in %s: %s",
1772                                        conf->verify_tmp_dir, fr_syserror(errno));
1773                                 break;
1774                         }
1775
1776                         fp = fdopen(fd, "w");
1777                         if (!fp) {
1778                                 close(fd);
1779                                 RDEBUG("Failed opening file %s: %s",
1780                                        filename, fr_syserror(errno));
1781                                 break;
1782                         }
1783
1784                         if (!PEM_write_X509(fp, client_cert)) {
1785                                 fclose(fp);
1786                                 RDEBUG("Failed writing certificate to file");
1787                                 goto do_unlink;
1788                         }
1789                         fclose(fp);
1790
1791                         if (!pairmake_packet("TLS-Client-Cert-Filename",
1792                                              filename, T_OP_SET)) {
1793                                 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1794
1795                                 goto do_unlink;
1796                         }
1797
1798                         RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
1799                         if (radius_exec_program(request, conf->verify_client_cert_cmd, true, true, NULL, 0,
1800                                                 EXEC_TIMEOUT, request->packet->vps, NULL) != 0) {
1801                                 AUTH("tls: Certificate CN (%s) fails external verification!", common_name);
1802                                 my_ok = 0;
1803                         } else {
1804                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
1805                         }
1806
1807                 do_unlink:
1808                         unlink(filename);
1809                         break;
1810                 }
1811
1812
1813         } /* depth == 0 */
1814
1815         if (debug_flag > 0) {
1816                 RDEBUG2("chain-depth=%d, ", depth);
1817                 RDEBUG2("error=%d", err);
1818
1819                 if (identity) RDEBUG2("--> User-Name = %s", *identity);
1820                 RDEBUG2("--> BUF-Name = %s", common_name);
1821                 RDEBUG2("--> subject = %s", subject);
1822                 RDEBUG2("--> issuer  = %s", issuer);
1823                 RDEBUG2("--> verify return:%d", my_ok);
1824         }
1825         return my_ok;
1826 }
1827
1828
1829 #ifdef HAVE_OPENSSL_OCSP_H
1830 /*
1831  *      Create Global X509 revocation store and use it to verify
1832  *      OCSP responses
1833  *
1834  *      - Load the trusted CAs
1835  *      - Load the trusted issuer certificates
1836  */
1837 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1838 {
1839         X509_STORE *store = NULL;
1840
1841         store = X509_STORE_new();
1842
1843         /* Load the CAs we trust */
1844         if (conf->ca_file || conf->ca_path)
1845                 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1846                         ERROR("tls: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1847                         ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
1848                         return NULL;
1849                 }
1850
1851 #ifdef X509_V_FLAG_CRL_CHECK
1852         if (conf->check_crl)
1853                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1854 #endif
1855         return store;
1856 }
1857 #endif  /* HAVE_OPENSSL_OCSP_H */
1858
1859 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1860 #ifndef OPENSSL_NO_ECDH
1861 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
1862 {
1863         int      nid;
1864         EC_KEY  *ecdh;
1865
1866         if (!ecdh_curve || !*ecdh_curve) return 0;
1867
1868         nid = OBJ_sn2nid(ecdh_curve);
1869         if (!nid) {
1870                 ERROR("Unknown ecdh_curve \"%s\"", ecdh_curve);
1871                 return -1;
1872         }
1873
1874         ecdh = EC_KEY_new_by_curve_name(nid);
1875         if (!ecdh) {
1876                 ERROR("Unable to create new curve \"%s\"", ecdh_curve);
1877                 return -1;
1878         }
1879
1880         SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1881
1882         SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
1883
1884         EC_KEY_free(ecdh);
1885
1886         return 0;
1887 }
1888 #endif
1889 #endif
1890
1891 /*
1892  * DIE OPENSSL DIE DIE DIE
1893  *
1894  * What a palaver, just to free some data attached the
1895  * session. We need to do this because the "remove" callback
1896  * is called when refcount > 0 sometimes, if another thread
1897  * is using the session
1898  */
1899 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
1900                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1901                                 UNUSED long argl, UNUSED void *argp)
1902 {
1903         VALUE_PAIR *vp = data_ptr;
1904         if (!vp) return;
1905
1906         DEBUG2("  Freeing cached session VPs");;
1907
1908         pairfree(&vp);
1909 }
1910
1911 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
1912                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
1913                                 UNUSED long argl, UNUSED void *argp)
1914 {
1915         VALUE_PAIR **certs = data_ptr;
1916         if (!certs) return;
1917
1918         DEBUG2("  Freeing cached session Certificates");
1919
1920         pairfree(certs);
1921 }
1922
1923 /** Add all the default ciphers and message digests reate our context.
1924  *
1925  * This should be called exactly once from main, before reading the main config
1926  * or initialising any modules.
1927  */
1928 void tls_global_init(void)
1929 {
1930         SSL_load_error_strings();       /* readable error messages (examples show call before library_init) */
1931         SSL_library_init();             /* initialize library */
1932         OpenSSL_add_all_algorithms();   /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
1933         OPENSSL_config(NULL);
1934 }
1935
1936 /** Check for vulnerable versions of libssl
1937  *
1938  * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
1939  * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
1940  */
1941 int tls_global_version_check(char const *acknowledged)
1942 {
1943         uint64_t v;
1944
1945         if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
1946                 bool bad = false;
1947                 size_t i;
1948
1949                 /* Check for bad versions */
1950                 v = (uint64_t) SSLeay();
1951
1952                 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
1953                         libssl_defect_t *defect = &libssl_defects[i];
1954
1955                         if ((v >= defect->low) && (v <= defect->high)) {
1956                                 ERROR("Refusing to start with libssl version %s (in range %s)",
1957                                       ssl_version(), ssl_version_range(defect->low, defect->high));
1958                                 ERROR("Security advisory %s (%s)", defect->id, defect->name);
1959                                 ERROR("%s", defect->comment);
1960
1961                                 bad = true;
1962                         }
1963                 }
1964
1965                 if (bad) {
1966                         INFO("Once you have verified libssl has been correctly patched, "
1967                              "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
1968                         return -1;
1969                 }
1970         }
1971
1972         return 0;
1973 }
1974
1975 /** Free any memory alloced by libssl
1976  *
1977  */
1978 void tls_global_cleanup(void)
1979 {
1980         ERR_remove_state(0);
1981         ENGINE_cleanup();
1982         CONF_modules_unload(1);
1983         ERR_free_strings();
1984         EVP_cleanup();
1985         CRYPTO_cleanup_all_ex_data();
1986 }
1987
1988 /*
1989  *      Create Global context SSL and use it in every new session
1990  *
1991  *      - Load the trusted CAs
1992  *      - Load the Private key & the certificate
1993  *      - Set the Context options & Verify options
1994  */
1995 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf, int client)
1996 {
1997         SSL_CTX *ctx;
1998         X509_STORE *certstore;
1999         int verify_mode = SSL_VERIFY_NONE;
2000         int ctx_options = 0;
2001         int type;
2002
2003         /*
2004          *      SHA256 is in all versions of OpenSSL, but isn't
2005          *      initialized by default.  It's needed for WiMAX
2006          *      certificates.
2007          */
2008 #ifdef HAVE_OPENSSL_EVP_SHA256
2009         EVP_add_digest(EVP_sha256());
2010 #endif
2011
2012         ctx = SSL_CTX_new(TLSv1_method());
2013         if (!ctx) {
2014                 int err;
2015                 while ((err = ERR_get_error())) {
2016                         DEBUG("Failed creating SSL context: %s",
2017                               ERR_error_string(err, NULL));
2018                         return NULL;
2019                 }
2020         }
2021
2022         /*
2023          * Save the config on the context so that callbacks which
2024          * only get SSL_CTX* e.g. session persistence, can get it
2025          */
2026         SSL_CTX_set_app_data(ctx, conf);
2027
2028         /*
2029          * Identify the type of certificates that needs to be loaded
2030          */
2031         if (conf->file_type) {
2032                 type = SSL_FILETYPE_PEM;
2033         } else {
2034                 type = SSL_FILETYPE_ASN1;
2035         }
2036
2037         /*
2038          * Set the password to load private key
2039          */
2040         if (conf->private_key_password) {
2041 #ifdef __APPLE__
2042                 /*
2043                  * We don't want to put the private key password in eap.conf, so  check
2044                  * for our special string which indicates we should get the password
2045                  * programmatically.
2046                  */
2047                 char const* special_string = "Apple:UseCertAdmin";
2048                 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2049                         char cmd[256];
2050                         char *password;
2051                         long const max_password_len = 128;
2052                         snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2053                                  conf->private_key_file);
2054
2055                         DEBUG2("tls: Getting private key passphrase using command \"%s\"", cmd);
2056
2057                         FILE* cmd_pipe = popen(cmd, "r");
2058                         if (!cmd_pipe) {
2059                                 ERROR("TLS: %s command failed.  Unable to get private_key_password", cmd);
2060                                 ERROR("Error reading private_key_file %s", conf->private_key_file);
2061                                 return NULL;
2062                         }
2063
2064                         rad_const_free(conf->private_key_password);
2065                         password = talloc_array(conf, char, max_password_len);
2066                         if (!password) {
2067                                 ERROR("TLS: Can't allocate space for private_key_password");
2068                                 ERROR("TLS: Error reading private_key_file %s", conf->private_key_file);
2069                                 pclose(cmd_pipe);
2070                                 return NULL;
2071                         }
2072
2073                         fgets(password, max_password_len, cmd_pipe);
2074                         pclose(cmd_pipe);
2075
2076                         /* Get rid of newline at end of password. */
2077                         password[strlen(password) - 1] = '\0';
2078
2079                         DEBUG3("tls:  Password from command = \"%s\"", password);
2080                         conf->private_key_password = password;
2081                 }
2082 #endif
2083
2084                 {
2085                         char *password;
2086
2087                         memcpy(&password, &conf->private_key_password, sizeof(password));
2088                         SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2089                         SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2090                 }
2091         }
2092
2093 #ifdef PSK_MAX_IDENTITY_LEN
2094         if ((conf->psk_identity && !conf->psk_password) ||
2095             (!conf->psk_identity && conf->psk_password) ||
2096             (conf->psk_identity && !*conf->psk_identity) ||
2097             (conf->psk_password && !*conf->psk_password)) {
2098                 ERROR("Invalid PSK Configuration: psk_identity or psk_password are empty");
2099                 return NULL;
2100         }
2101
2102         if (conf->psk_identity) {
2103                 size_t psk_len, hex_len;
2104                 char buffer[PSK_MAX_PSK_LEN];
2105
2106                 if (conf->certificate_file ||
2107                     conf->private_key_password || conf->private_key_file ||
2108                     conf->ca_file || conf->ca_path) {
2109                         ERROR("When PSKs are used, No certificate configuration is permitted");
2110                         return NULL;
2111                 }
2112
2113                 if (client) {
2114                         SSL_CTX_set_psk_client_callback(ctx,
2115                                                         psk_client_callback);
2116                 } else {
2117                         SSL_CTX_set_psk_server_callback(ctx,
2118                                                         psk_server_callback);
2119                 }
2120
2121                 psk_len = strlen(conf->psk_password);
2122                 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2123                         ERROR("psk_hexphrase is too long (max %d)",
2124                                PSK_MAX_PSK_LEN);
2125                         return NULL;
2126                 }
2127
2128                 hex_len = fr_hex2bin((uint8_t *) buffer, conf->psk_password, psk_len);
2129                 if (psk_len != (2 * hex_len)) {
2130                         ERROR("psk_hexphrase is not all hex");
2131                         return NULL;
2132                 }
2133
2134                 goto post_ca;
2135         }
2136 #else
2137         (void) client;  /* -Wunused */
2138 #endif
2139
2140         /*
2141          *      Load our keys and certificates
2142          *
2143          *      If certificates are of type PEM then we can make use
2144          *      of cert chain authentication using openssl api call
2145          *      SSL_CTX_use_certificate_chain_file.  Please see how
2146          *      the cert chain needs to be given in PEM from
2147          *      openSSL.org
2148          */
2149         if (!conf->certificate_file) goto load_ca;
2150
2151         if (type == SSL_FILETYPE_PEM) {
2152                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2153                         ERROR("Error reading certificate file %s:%s",
2154                                conf->certificate_file,
2155                                ERR_error_string(ERR_get_error(), NULL));
2156                         return NULL;
2157                 }
2158
2159         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2160                 ERROR("Error reading certificate file %s:%s",
2161                        conf->certificate_file,
2162                        ERR_error_string(ERR_get_error(), NULL));
2163                 return NULL;
2164         }
2165
2166         /* Load the CAs we trust */
2167 load_ca:
2168         if (conf->ca_file || conf->ca_path) {
2169                 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2170                         ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2171                         ERROR("tls: Error reading Trusted root CA list %s",conf->ca_file );
2172                         return NULL;
2173                 }
2174         }
2175         if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2176
2177         if (conf->private_key_file) {
2178                 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2179                         ERROR("Failed reading private key file %s:%s",
2180                                conf->private_key_file,
2181                                ERR_error_string(ERR_get_error(), NULL));
2182                         return NULL;
2183                 }
2184
2185                 /*
2186                  * Check if the loaded private key is the right one
2187                  */
2188                 if (!SSL_CTX_check_private_key(ctx)) {
2189                         ERROR("Private key does not match the certificate public key");
2190                         return NULL;
2191                 }
2192         }
2193
2194 #ifdef PSK_MAX_IDENTITY_LEN
2195 post_ca:
2196 #endif
2197
2198         /*
2199          *      Set ctx_options
2200          */
2201         ctx_options |= SSL_OP_NO_SSLv2;
2202         ctx_options |= SSL_OP_NO_SSLv3;
2203 #ifdef SSL_OP_NO_TICKET
2204         ctx_options |= SSL_OP_NO_TICKET ;
2205 #endif
2206
2207         /*
2208          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
2209          *      small subgroup attacks and forward secrecy. Always
2210          *      using
2211          *
2212          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
2213          *      time needed during negotiation, but it is not very
2214          *      large.
2215          */
2216         ctx_options |= SSL_OP_SINGLE_DH_USE;
2217
2218         /*
2219          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2220          *      in Windows Vista client.
2221          *      http://www.openssl.org/~bodo/tls-cbc.txt
2222          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2223          */
2224         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2225
2226         SSL_CTX_set_options(ctx, ctx_options);
2227
2228         /*
2229          *      TODO: Set the RSA & DH
2230          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2231          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2232          */
2233
2234         /*
2235          *      set the message callback to identify the type of
2236          *      message.  For every new session, there can be a
2237          *      different callback argument.
2238          *
2239          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2240          */
2241
2242         /*
2243          *      Set eliptical curve crypto configuration.
2244          */
2245 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2246 #ifndef OPENSSL_NO_ECDH
2247         if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2248                 return NULL;
2249         }
2250 #endif
2251 #endif
2252
2253         /* Set Info callback */
2254         SSL_CTX_set_info_callback(ctx, cbtls_info);
2255
2256         /*
2257          *      Callbacks, etc. for session resumption.
2258          */
2259         if (conf->session_cache_enable) {
2260                 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2261                 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2262                 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2263
2264                 SSL_CTX_set_quiet_shutdown(ctx, 1);
2265                 if (FR_TLS_EX_INDEX_VPS < 0)
2266                         FR_TLS_EX_INDEX_VPS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2267                 if (FR_TLS_EX_INDEX_CERTS < 0)
2268                         FR_TLS_EX_INDEX_CERTS = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2269         }
2270
2271         /*
2272          *      Check the certificates for revocation.
2273          */
2274 #ifdef X509_V_FLAG_CRL_CHECK
2275         if (conf->check_crl) {
2276           certstore = SSL_CTX_get_cert_store(ctx);
2277           if (certstore == NULL) {
2278             ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2279             ERROR("tls: Error reading Certificate Store");
2280             return NULL;
2281           }
2282           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2283         }
2284 #endif
2285
2286         /*
2287          *      Set verify modes
2288          *      Always verify the peer certificate
2289          */
2290         verify_mode |= SSL_VERIFY_PEER;
2291         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2292         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2293         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2294
2295         if (conf->verify_depth) {
2296                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2297         }
2298
2299         /* Load randomness */
2300         if (conf->random_file) {
2301                 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2302                         ERROR("tls: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2303                         ERROR("tls: Error loading randomness");
2304                         return NULL;
2305                 }
2306         }
2307
2308         /*
2309          * Set the cipher list if we were told to
2310          */
2311         if (conf->cipher_list) {
2312                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2313                         ERROR("tls: Error setting cipher list");
2314                         return NULL;
2315                 }
2316         }
2317
2318         /*
2319          *      Setup session caching
2320          */
2321         if (conf->session_cache_enable) {
2322                 /*
2323                  *      Create a unique context Id per EAP-TLS configuration.
2324                  */
2325                 if (conf->session_id_name) {
2326                         snprintf(conf->session_context_id,
2327                                  sizeof(conf->session_context_id),
2328                                  "FR eap %s",
2329                                  conf->session_id_name);
2330                 } else {
2331                         snprintf(conf->session_context_id,
2332                                  sizeof(conf->session_context_id),
2333                                  "FR eap %p", conf);
2334                 }
2335
2336                 /*
2337                  *      Cache it, and DON'T auto-clear it.
2338                  */
2339                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2340
2341                 SSL_CTX_set_session_id_context(ctx,
2342                                                (unsigned char *) conf->session_context_id,
2343                                                (unsigned int) strlen(conf->session_context_id));
2344
2345                 /*
2346                  *      Our timeout is in hours, this is in seconds.
2347                  */
2348                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2349
2350                 /*
2351                  *      Set the maximum number of entries in the
2352                  *      session cache.
2353                  */
2354                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2355
2356         } else {
2357                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2358         }
2359
2360         return ctx;
2361 }
2362
2363
2364 /*
2365  *      Free TLS client/server config
2366  *      Should not be called outside this code, as a callback is
2367  *      added to automatically free the data when the CONF_SECTION
2368  *      is freed.
2369  */
2370 static int tls_server_conf_free(fr_tls_server_conf_t *conf)
2371 {
2372         if (conf->ctx) SSL_CTX_free(conf->ctx);
2373
2374 #ifdef HAVE_OPENSSL_OCSP_H
2375         if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2376         conf->ocsp_store = NULL;
2377 #endif
2378
2379 #ifndef NDEBUG
2380         memset(conf, 0, sizeof(*conf));
2381 #endif
2382         return 0;
2383 }
2384
2385
2386 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2387 {
2388         fr_tls_server_conf_t *conf;
2389
2390         /*
2391          *      If cs has already been parsed there should be a cached copy
2392          *      of conf already stored, so just return that.
2393          */
2394         conf = cf_data_find(cs, "tls-conf");
2395         if (conf) {
2396                 DEBUG("Using cached TLS configuration from previous invocation");
2397                 return conf;
2398         }
2399
2400         conf = talloc_zero(cs, fr_tls_server_conf_t);
2401         if (!conf) {
2402                 ERROR("Out of memory");
2403                 return NULL;
2404         }
2405
2406         talloc_set_destructor(conf, tls_server_conf_free);
2407
2408         if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2409         error:
2410                 talloc_free(conf);
2411                 return NULL;
2412         }
2413
2414         /*
2415          *      Save people from their own stupidity.
2416          */
2417         if (conf->fragment_size < 100) conf->fragment_size = 100;
2418
2419         if (!conf->private_key_file) {
2420                 ERROR("TLS Server requires a private key file");
2421                 goto error;
2422         }
2423
2424         if (!conf->certificate_file) {
2425                 ERROR("TLS Server requires a certificate file");
2426                 goto error;
2427         }
2428
2429         /*
2430          *      Initialize TLS
2431          */
2432         conf->ctx = init_tls_ctx(conf, 0);
2433         if (conf->ctx == NULL) {
2434                 goto error;
2435         }
2436
2437 #ifdef HAVE_OPENSSL_OCSP_H
2438         /*
2439          *      Initialize OCSP Revocation Store
2440          */
2441         if (conf->ocsp_enable) {
2442                 conf->ocsp_store = init_revocation_store(conf);
2443                 if (conf->ocsp_store == NULL) goto error;
2444         }
2445 #endif /*HAVE_OPENSSL_OCSP_H*/
2446         {
2447                 char *dh_file;
2448
2449                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2450                 if (load_dh_params(conf->ctx, dh_file) < 0) {
2451                         goto error;
2452                 }
2453         }
2454
2455         if (generate_eph_rsa_key(conf->ctx) < 0) {
2456                 goto error;
2457         }
2458
2459         if (conf->verify_tmp_dir) {
2460                 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2461                         ERROR("Failed changing permissions on %s: %s", conf->verify_tmp_dir, fr_syserror(errno));
2462                         goto error;
2463                 }
2464         }
2465
2466         if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2467                 ERROR("You MUST set the verify directory in order to use verify_client_cmd");
2468                 goto error;
2469         }
2470
2471         /*
2472          *      Cache conf in cs in case we're asked to parse this again.
2473          */
2474         cf_data_add(cs, "tls-conf", conf, NULL);
2475
2476         return conf;
2477 }
2478
2479 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2480 {
2481         fr_tls_server_conf_t *conf;
2482
2483         conf = cf_data_find(cs, "tls-conf");
2484         if (conf) {
2485                 DEBUG("Using cached TLS configuration from previous invocation");
2486                 return conf;
2487         }
2488
2489         conf = talloc_zero(cs, fr_tls_server_conf_t);
2490         if (!conf) {
2491                 ERROR("Out of memory");
2492                 return NULL;
2493         }
2494
2495         talloc_set_destructor(conf, tls_server_conf_free);
2496
2497         if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2498         error:
2499                 talloc_free(conf);
2500                 return NULL;
2501         }
2502
2503         /*
2504          *      Save people from their own stupidity.
2505          */
2506         if (conf->fragment_size < 100) conf->fragment_size = 100;
2507
2508         /*
2509          *      Initialize TLS
2510          */
2511         conf->ctx = init_tls_ctx(conf, 1);
2512         if (conf->ctx == NULL) {
2513                 goto error;
2514         }
2515
2516         {
2517                 char *dh_file;
2518
2519                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2520                 if (load_dh_params(conf->ctx, dh_file) < 0) {
2521                         goto error;
2522                 }
2523         }
2524
2525         if (generate_eph_rsa_key(conf->ctx) < 0) {
2526                 goto error;
2527         }
2528
2529         cf_data_add(cs, "tls-conf", conf, NULL);
2530
2531         return conf;
2532 }
2533
2534 int tls_success(tls_session_t *ssn, REQUEST *request)
2535 {
2536         VALUE_PAIR *vp, *vps = NULL;
2537         fr_tls_server_conf_t *conf;
2538         TALLOC_CTX *talloc_ctx;
2539
2540         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2541         rad_assert(conf != NULL);
2542
2543         talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2544
2545         /*
2546          *      If there's no session resumption, delete the entry
2547          *      from the cache.  This means either it's disabled
2548          *      globally for this SSL context, OR we were told to
2549          *      disable it for this user.
2550          *
2551          *      This also means you can't turn it on just for one
2552          *      user.
2553          */
2554         if ((!ssn->allow_session_resumption) ||
2555             (((vp = pairfind(request->config_items, 1127, 0, TAG_ANY)) != NULL) &&
2556              (vp->vp_integer == 0))) {
2557                 SSL_CTX_remove_session(ssn->ctx,
2558                                        ssn->ssl->session);
2559                 ssn->allow_session_resumption = 0;
2560
2561                 /*
2562                  *      If we're in a resumed session and it's
2563                  *      not allowed,
2564                  */
2565                 if (SSL_session_reused(ssn->ssl)) {
2566                         RDEBUG("FAIL: Forcibly stopping session resumption as it is not allowed");
2567                         return -1;
2568                 }
2569
2570                 /*
2571                  *      Else resumption IS allowed, so we store the
2572                  *      user data in the cache.
2573                  */
2574         } else if (!SSL_session_reused(ssn->ssl)) {
2575                 size_t size;
2576                 VALUE_PAIR **certs;
2577                 char buffer[2 * MAX_SESSION_SIZE + 1];
2578
2579                 size = ssn->ssl->session->session_id_length;
2580                 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2581
2582                 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2583
2584                 vp = paircopy2(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2585                 if (vp) pairadd(&vps, vp);
2586
2587                 vp = paircopy2(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2588                 if (vp) pairadd(&vps, vp);
2589
2590                 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2591                 if (vp) pairadd(&vps, vp);
2592
2593                 vp = paircopy2(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2594                 if (vp) pairadd(&vps, vp);
2595
2596                 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CERTS);
2597
2598                 /*
2599                  *      Hmm... the certs should probably be session data.
2600                  */
2601                 if (certs) {
2602                         /*
2603                          *      @todo: some go into reply, others into
2604                          *      request
2605                          */
2606                         pairadd(&vps, paircopy(talloc_ctx, *certs));
2607                 }
2608
2609                 if (vps) {
2610                         RDEBUG2("Saving session %s vps %p in the cache", buffer, vps);
2611                         SSL_SESSION_set_ex_data(ssn->ssl->session,
2612                                                 FR_TLS_EX_INDEX_VPS, vps);
2613                         if (conf->session_cache_path) {
2614                                 /* write the VPs to the cache file */
2615                                 char filename[256], buf[1024];
2616                                 FILE *vp_file;
2617
2618                                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2619                                         conf->session_cache_path, FR_DIR_SEP, buffer
2620                                         );
2621                                 vp_file = fopen(filename, "w");
2622                                 if (vp_file == NULL) {
2623                                         RDEBUG2("Could not write session VPs to persistent cache: %s", fr_syserror(errno));
2624                                 } else {
2625                                         vp_cursor_t cursor;
2626                                         /* generate a dummy user-style entry which is easy to read back */
2627                                         fprintf(vp_file, "# SSL cached session\n");
2628                                         fprintf(vp_file, "%s\n", buffer);
2629                                         for (vp = fr_cursor_init(&cursor, &vps);
2630                                              vp;
2631                                              vp = fr_cursor_next(&cursor)) {
2632                                                 vp_prints(buf, sizeof(buf), vp);
2633                                                 fprintf(vp_file, "\t%s,\n", buf);
2634                                         }
2635                                         fclose(vp_file);
2636                                 }
2637                         }
2638                 } else {
2639                         RWDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
2640                         SSL_CTX_remove_session(ssn->ctx,
2641                                                ssn->ssl->session);
2642                 }
2643
2644                 /*
2645                  *      Else the session WAS allowed.  Copy the cached
2646                  *      reply.
2647                  */
2648         } else {
2649                 size_t size;
2650                 char buffer[2 * MAX_SESSION_SIZE + 1];
2651
2652                 size = ssn->ssl->session->session_id_length;
2653                 if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
2654
2655                 fr_bin2hex(buffer, ssn->ssl->session->session_id, size);
2656
2657                 vps = SSL_SESSION_get_ex_data(ssn->ssl->session,
2658                                              FR_TLS_EX_INDEX_VPS);
2659                 if (!vps) {
2660                         RWDEBUG("No information in cached session %s", buffer);
2661                         return -1;
2662
2663                 } else {
2664                         vp_cursor_t cursor;
2665
2666                         RDEBUG("Adding cached attributes for session %s:", buffer);
2667                         debug_pair_list(vps);
2668
2669                         for (vp = fr_cursor_init(&cursor, &vps);
2670                              vp;
2671                              vp = fr_cursor_next(&cursor)) {
2672                                 /*
2673                                  *      TLS-* attrs get added back to
2674                                  *      the request list.
2675                                  */
2676                                 if ((vp->da->vendor == 0) &&
2677                                     (vp->da->attr >= 1910) &&
2678                                     (vp->da->attr < 1929)) {
2679                                         pairadd(&request->packet->vps,
2680                                                 paircopyvp(request->packet, vp));
2681                                 } else {
2682                                         pairadd(&request->reply->vps,
2683                                                 paircopyvp(request->packet, vp));
2684                                 }
2685                         }
2686
2687                         if (conf->session_cache_path) {
2688                                 /* "touch" the cached session/vp file */
2689                                 char filename[256];
2690
2691                                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
2692                                         conf->session_cache_path, FR_DIR_SEP, buffer
2693                                         );
2694                                 utime(filename, NULL);
2695                                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
2696                                         conf->session_cache_path, FR_DIR_SEP, buffer
2697                                         );
2698                                 utime(filename, NULL);
2699                         }
2700
2701                         /*
2702                          *      Mark the request as resumed.
2703                          */
2704                         pairmake_packet("EAP-Session-Resumed", "1", T_OP_SET);
2705                 }
2706         }
2707
2708         return 0;
2709 }
2710
2711
2712 void tls_fail(tls_session_t *ssn)
2713 {
2714         /*
2715          *      Force the session to NOT be cached.
2716          */
2717         SSL_CTX_remove_session(ssn->ctx, ssn->ssl->session);
2718 }
2719
2720 fr_tls_status_t tls_application_data(tls_session_t *ssn,
2721                                      REQUEST *request)
2722
2723 {
2724         int err;
2725
2726         /*
2727          *      Decrypt the complete record.
2728          */
2729         err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
2730                         ssn->dirty_in.used);
2731         if (err != (int) ssn->dirty_in.used) {
2732                 record_init(&ssn->dirty_in);
2733                 RDEBUG("Failed writing %d to SSL BIO: %d",
2734                        ssn->dirty_in.used, err);
2735                 return FR_TLS_FAIL;
2736         }
2737
2738         /*
2739          *      Clear the dirty buffer now that we are done with it
2740          *      and init the clean_out buffer to store decrypted data
2741          */
2742         record_init(&ssn->dirty_in);
2743         record_init(&ssn->clean_out);
2744
2745         /*
2746          *      Read (and decrypt) the tunneled data from the
2747          *      SSL session, and put it into the decrypted
2748          *      data buffer.
2749          */
2750         err = SSL_read(ssn->ssl, ssn->clean_out.data,
2751                        sizeof(ssn->clean_out.data));
2752
2753         if (err < 0) {
2754                 int code;
2755
2756                 RDEBUG("SSL_read Error");
2757
2758                 code = SSL_get_error(ssn->ssl, err);
2759                 switch (code) {
2760                 case SSL_ERROR_WANT_READ:
2761                         DEBUG("Error in fragmentation logic: SSL_WANT_READ");
2762                         return FR_TLS_MORE_FRAGMENTS;
2763
2764                 case SSL_ERROR_WANT_WRITE:
2765                         DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
2766                         break;
2767
2768                 default:
2769                         DEBUG("Error in fragmentation logic: %s",
2770                               ERR_error_string(code, NULL));
2771
2772                         /*
2773                          *      FIXME: Call int_ssl_check?
2774                          */
2775                         break;
2776                 }
2777                 return FR_TLS_FAIL;
2778         }
2779
2780         if (err == 0) {
2781                 RWDEBUG("No data inside of the tunnel");
2782         }
2783
2784         /*
2785          *      Passed all checks, successfully decrypted data
2786          */
2787         ssn->clean_out.used = err;
2788
2789         return FR_TLS_OK;
2790 }
2791
2792
2793 /*
2794  * Acknowledge received is for one of the following messages sent earlier
2795  * 1. Handshake completed Message, so now send, EAP-Success
2796  * 2. Alert Message, now send, EAP-Failure
2797  * 3. Fragment Message, now send, next Fragment
2798  */
2799 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
2800 {
2801         RDEBUG2("Received TLS ACK");
2802
2803         if (ssn == NULL){
2804                 RERROR("FAIL: Unexpected ACK received.  Could not obtain session information");
2805                 return FR_TLS_INVALID;
2806         }
2807         if (ssn->info.initialized == 0) {
2808                 RDEBUG("No SSL info available. Waiting for more SSL data");
2809                 return FR_TLS_REQUEST;
2810         }
2811         if ((ssn->info.content_type == handshake) &&
2812             (ssn->info.origin == 0)) {
2813                 RERROR("FAIL: ACK without earlier message");
2814                 return FR_TLS_INVALID;
2815         }
2816
2817         switch (ssn->info.content_type) {
2818         case alert:
2819                 RDEBUG2("ACK alert");
2820                 return FR_TLS_FAIL;
2821
2822         case handshake:
2823                 if ((ssn->info.handshake_type == finished) &&
2824                     (ssn->dirty_out.used == 0)) {
2825                         RDEBUG2("ACK handshake is finished");
2826
2827                         /*
2828                          *      From now on all the content is
2829                          *      application data set it here as nobody else
2830                          *      sets it.
2831                          */
2832                         ssn->info.content_type = application_data;
2833                         return FR_TLS_SUCCESS;
2834                 } /* else more data to send */
2835
2836                 RDEBUG2("ACK handshake fragment handler");
2837                 /* Fragmentation handler, send next fragment */
2838                 return FR_TLS_REQUEST;
2839
2840         case application_data:
2841                 RDEBUG2("ACK handshake fragment handler in application data");
2842                 return FR_TLS_REQUEST;
2843
2844                 /*
2845                  *      For the rest of the conditions, switch over
2846                  *      to the default section below.
2847                  */
2848         default:
2849                 RDEBUG2("ACK default");
2850                 RERROR("Invalid ACK received: %d",
2851                        ssn->info.content_type);
2852                 return FR_TLS_INVALID;
2853         }
2854 }
2855
2856 #endif  /* WITH_TLS */
2857