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