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