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