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