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