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