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