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