Use new RDEBUG macro
[freeradius.git] / src / modules / rlm_eap / libeap / 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 "eap_tls.h"
29
30 /* record */
31 static void             record_init(record_t *buf);
32 static void             record_close(record_t *buf);
33 static unsigned int     record_plus(record_t *buf, const void *ptr,
34                                     unsigned int size);
35 static unsigned int     record_minus(record_t *buf, void *ptr,
36                                      unsigned int size);
37
38 tls_session_t *eaptls_new_session(SSL_CTX *ssl_ctx, int client_cert)
39 {
40         tls_session_t *state = NULL;
41         SSL *new_tls = NULL;
42
43         client_cert = client_cert; /* -Wunused.  See bug #350 */
44
45         if ((new_tls = SSL_new(ssl_ctx)) == NULL) {
46                 radlog(L_ERR, "rlm_eap_tls: Error creating new SSL");
47                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
48                 return NULL;
49         }
50
51         /* We use the SSL's "app_data" to indicate a call-back */
52         SSL_set_app_data(new_tls, NULL);
53
54         state = (tls_session_t *)malloc(sizeof(*state));
55         memset(state, 0, sizeof(*state));
56         session_init(state);
57         state->ssl = new_tls;
58
59         /*
60          *      Initialize callbacks
61          */
62         state->record_init = record_init;
63         state->record_close = record_close;
64         state->record_plus = record_plus;
65         state->record_minus = record_minus;
66
67         /*
68          *      Create & hook the BIOs to handle the dirty side of the
69          *      SSL.  This is *very important* as we want to handle
70          *      the transmission part.  Now the only IO interface
71          *      that SSL is aware of, is our defined BIO buffers.
72          *
73          *      This means that all SSL IO is done to/from memory,
74          *      and we can update those BIOs from the EAP packets we've
75          *      received.
76          */
77         state->into_ssl = BIO_new(BIO_s_mem());
78         state->from_ssl = BIO_new(BIO_s_mem());
79         SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
80
81         /*
82          *      Add the message callback to identify what type of
83          *      message/handshake is passed
84          */
85         SSL_set_msg_callback(new_tls, cbtls_msg);
86         SSL_set_msg_callback_arg(new_tls, state);
87         SSL_set_info_callback(new_tls, cbtls_info);
88
89         /*
90          *      In Server mode we only accept.
91          */
92         SSL_set_accept_state(state->ssl);
93
94         return state;
95 }
96
97 /*
98  *      Print out some text describing the error.
99  */
100 static int int_ssl_check(SSL *s, int ret, const char *text)
101 {
102         int e;
103         unsigned long l;
104
105         if ((l = ERR_get_error()) != 0) {
106                 radlog(L_ERR, "rlm_eap: SSL error %s",
107                        ERR_error_string(l, NULL));
108         }
109         e = SSL_get_error(s, ret);
110
111         switch(e) {
112                 /*
113                  *      These seem to be harmless and already "dealt
114                  *      with" by our non-blocking environment. NB:
115                  *      "ZERO_RETURN" is the clean "error"
116                  *      indicating a successfully closed SSL
117                  *      tunnel. We let this happen because our IO
118                  *      loop should not appear to have broken on
119                  *      this condition - and outside the IO loop, the
120                  *      "shutdown" state is checked.
121                  *
122                  *      Don't print anything if we ignore the error.
123                  */
124         case SSL_ERROR_NONE:
125         case SSL_ERROR_WANT_READ:
126         case SSL_ERROR_WANT_WRITE:
127         case SSL_ERROR_WANT_X509_LOOKUP:
128         case SSL_ERROR_ZERO_RETURN:
129                 break;
130
131                 /*
132                  *      These seem to be indications of a genuine
133                  *      error that should result in the SSL tunnel
134                  *      being regarded as "dead".
135                  */
136         case SSL_ERROR_SYSCALL:
137                 radlog(L_ERR, "rlm_eap_tls: %s failed in a system call (%d), TLS session fails.",
138                        text, ret);
139                 return 0;
140
141         case SSL_ERROR_SSL:
142                 radlog(L_ERR, "rlm_eap_tls: %s failed inside of TLS (%d), TLS session fails.",
143                        text, ret);
144                 return 0;
145
146         default:
147                 /*
148                  *      For any other errors that (a) exist, and (b)
149                  *      crop up - we need to interpret what to do with
150                  *      them - so "politely inform" the caller that
151                  *      the code needs updating here.
152                  */
153                 radlog(L_ERR, "rlm_eap_tls: FATAL SSL error ..... %d\n", e);
154                 return 0;
155         }
156
157         return 1;
158 }
159
160 /*
161  * We are the server, we always get the dirty data
162  * (Handshake data is also considered as dirty data)
163  * During handshake, since SSL API handles itself,
164  * After clean-up, dirty_out will be filled with
165  * the data required for handshaking. So we check
166  * if dirty_out is empty then we simply send it back.
167  * As of now, if handshake is successful, then it is EAP-Success
168  * or else EAP-failure should be sent
169  *
170  * Fill the Bio with the dirty data to clean it
171  * Get the cleaned data from SSL, if it is not Handshake data
172  */
173 int tls_handshake_recv(tls_session_t *ssn)
174 {
175         int err;
176
177         BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
178
179         err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
180                        sizeof(ssn->clean_out.data) - ssn->clean_out.used);
181         if (err > 0) {
182                 ssn->clean_out.used += err;
183                 record_init(&ssn->dirty_in);
184                 return 1;
185         }
186
187         if (!int_ssl_check(ssn->ssl, err, "SSL_read")) {
188                 return 0;
189         }
190
191         /* Some Extra STATE information for easy debugging */
192         if (SSL_is_init_finished(ssn->ssl)) {
193                 DEBUG2("SSL Connection Established\n");
194         }
195         if (SSL_in_init(ssn->ssl)) {
196                 DEBUG2("In SSL Handshake Phase\n");
197         }
198         if (SSL_in_before(ssn->ssl)) {
199                 DEBUG2("Before SSL Handshake Phase\n");
200         }
201         if (SSL_in_accept_init(ssn->ssl)) {
202                 DEBUG2("In SSL Accept mode \n");
203         }
204         if (SSL_in_connect_init(ssn->ssl)) {
205                 DEBUG2("In SSL Connect mode \n");
206         }
207
208         /*
209          *      If we're finished the setup, and doing session
210          *      resumption, (CCS and Finish received, parsed,
211          *      and validated), wind up handshake.
212          */
213 #if 0
214         if (SSL_is_init_finished(ssn->ssl) && (ssn->ssl->hit == 1)) {
215                 record_init(&ssn->dirty_in);
216
217                 /*
218                  *      Magic value. See eaptls_operation().
219                  */
220                 return 0xea; 
221
222         }
223 #endif
224
225         err = BIO_ctrl_pending(ssn->from_ssl);
226         if (err > 0) {
227                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
228                                sizeof(ssn->dirty_out.data));
229                 if (err > 0) {
230                         ssn->dirty_out.used = err;
231
232                 } else if (BIO_should_retry(ssn->from_ssl)) {
233                         record_init(&ssn->dirty_in);
234                         DEBUG2("  tls: Asking for more data in tunnel");
235                         return 1;
236
237                 } else {
238                         int_ssl_check(ssn->ssl, err, "BIO_read");
239                         record_init(&ssn->dirty_in);
240                         return 0;
241                 }
242         } else {
243                 DEBUG2("rlm_eap_tls: Application Data");
244                 /* Its clean application data, do whatever we want */
245                 record_init(&ssn->clean_out);
246         }
247
248         /* We are done with dirty_in, reinitialize it */
249         record_init(&ssn->dirty_in);
250         return 1;
251 }
252
253 /*
254  *      Take clear-text user data, and encrypt it into the output buffer,
255  *      to send to the client at the other end of the SSL connection.
256  */
257 int tls_handshake_send(tls_session_t *ssn)
258 {
259         int err;
260
261         /*
262          *      If there's un-encrypted data in 'clean_in', then write
263          *      that data to the SSL session, and then call the BIO function
264          *      to get that encrypted data from the SSL session, into
265          *      a buffer which we can then package into an EAP packet.
266          *
267          *      Based on Server's logic this clean_in is expected to
268          *      contain the data to send to the client.
269          */
270         if (ssn->clean_in.used > 0) {
271                 int written;
272
273                 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
274                 record_minus(&ssn->clean_in, NULL, written);
275
276
277                 /* Get the dirty data from Bio to send it */
278                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
279                                sizeof(ssn->dirty_out.data));
280                 if (err > 0) {
281                         ssn->dirty_out.used = err;
282                 } else {
283                         int_ssl_check(ssn->ssl, err, "handshake_send");
284                 }
285         }
286
287         return 1;
288 }
289
290 void session_init(tls_session_t *ssn)
291 {
292         ssn->ssl = NULL;
293         ssn->into_ssl = ssn->from_ssl = NULL;
294         record_init(&ssn->clean_in);
295         record_init(&ssn->clean_out);
296         record_init(&ssn->dirty_in);
297         record_init(&ssn->dirty_out);
298
299         memset(&ssn->info, 0, sizeof(ssn->info));
300
301         ssn->offset = 0;
302         ssn->fragment = 0;
303         ssn->tls_msg_len = 0;
304         ssn->length_flag = 0;
305         ssn->opaque = NULL;
306         ssn->free_opaque = NULL;
307 }
308
309 void session_close(tls_session_t *ssn)
310 {
311         if(ssn->ssl)
312                 SSL_free(ssn->ssl);
313 #if 0
314 /*
315  * WARNING: SSL_free seems to decrement the reference counts already,
316  *      so doing this might crash the application.
317  */
318         if(ssn->into_ssl)
319                 BIO_free(ssn->into_ssl);
320         if(ssn->from_ssl)
321                 BIO_free(ssn->from_ssl);
322 #endif
323         record_close(&ssn->clean_in);
324         record_close(&ssn->clean_out);
325         record_close(&ssn->dirty_in);
326         record_close(&ssn->dirty_out);
327         session_init(ssn);
328 }
329
330 void session_free(void *ssn)
331 {
332         tls_session_t *sess = (tls_session_t *)ssn;
333
334         if (!ssn) return;
335
336         /*
337          *      Free any opaque TTLS or PEAP data.
338          */
339         if ((sess->opaque) && (sess->free_opaque)) {
340                 sess->free_opaque(sess->opaque);
341                 sess->opaque = NULL;
342         }
343
344         session_close(sess);
345
346         free(sess);
347 }
348
349 static void record_init(record_t *rec)
350 {
351         rec->used = 0;
352 }
353
354 static void record_close(record_t *rec)
355 {
356         rec->used = 0;
357 }
358
359
360 /*
361  *      Copy data to the intermediate buffer, before we send
362  *      it somewhere.
363  */
364 static unsigned int record_plus(record_t *rec, const void *ptr,
365                                 unsigned int size)
366 {
367         unsigned int added = MAX_RECORD_SIZE - rec->used;
368
369         if(added > size)
370                 added = size;
371         if(added == 0)
372                 return 0;
373         memcpy(rec->data + rec->used, ptr, added);
374         rec->used += added;
375         return added;
376 }
377
378 /*
379  *      Take data from the buffer, and give it to the caller.
380  */
381 static unsigned int record_minus(record_t *rec, void *ptr,
382                                  unsigned int size)
383 {
384         unsigned int taken = rec->used;
385
386         if(taken > size)
387                 taken = size;
388         if(taken == 0)
389                 return 0;
390         if(ptr)
391                 memcpy(ptr, rec->data, taken);
392         rec->used -= taken;
393
394         /*
395          *      This is pretty bad...
396          */
397         if(rec->used > 0)
398                 memmove(rec->data, rec->data + taken, rec->used);
399         return taken;
400 }
401
402 void tls_session_information(tls_session_t *tls_session)
403 {
404         const char *str_write_p, *str_version, *str_content_type = "";
405         const char *str_details1 = "", *str_details2= "";
406         EAP_HANDLER *handler;
407         REQUEST *request;
408
409         /*
410          *      Don't print this out in the normal course of
411          *      operations.
412          */
413         if (debug_flag == 0) {
414                 return;
415         }
416
417         str_write_p = tls_session->info.origin ? ">>>" : "<<<";
418
419         switch (tls_session->info.version)
420         {
421         case SSL2_VERSION:
422                 str_version = "SSL 2.0";
423                 break;
424         case SSL3_VERSION:
425                 str_version = "SSL 3.0 ";
426                 break;
427         case TLS1_VERSION:
428                 str_version = "TLS 1.0 ";
429                 break;
430         default:
431                 str_version = "Unknown TLS version";
432                 break;
433         }
434
435         if (tls_session->info.version == SSL3_VERSION ||
436             tls_session->info.version == TLS1_VERSION) {
437                 switch (tls_session->info.content_type) {
438                 case SSL3_RT_CHANGE_CIPHER_SPEC:
439                         str_content_type = "ChangeCipherSpec";
440                         break;
441                 case SSL3_RT_ALERT:
442                         str_content_type = "Alert";
443                         break;
444                 case SSL3_RT_HANDSHAKE:
445                         str_content_type = "Handshake";
446                         break;
447                 case SSL3_RT_APPLICATION_DATA:
448                         str_content_type = "ApplicationData";
449                         break;
450                 default:
451                         str_content_type = "UnknownContentType";
452                         break;
453                 }
454
455                 if (tls_session->info.content_type == SSL3_RT_ALERT) {
456                         str_details1 = ", ???";
457
458                         if (tls_session->info.record_len == 2) {
459
460                                 switch (tls_session->info.alert_level) {
461                                 case SSL3_AL_WARNING:
462                                         str_details1 = ", warning";
463                                         break;
464                                 case SSL3_AL_FATAL:
465                                         str_details1 = ", fatal";
466                                         break;
467                                 }
468
469                                 str_details2 = " ???";
470                                 switch (tls_session->info.alert_description) {
471                                 case SSL3_AD_CLOSE_NOTIFY:
472                                         str_details2 = " close_notify";
473                                         break;
474                                 case SSL3_AD_UNEXPECTED_MESSAGE:
475                                         str_details2 = " unexpected_message";
476                                         break;
477                                 case SSL3_AD_BAD_RECORD_MAC:
478                                         str_details2 = " bad_record_mac";
479                                         break;
480                                 case TLS1_AD_DECRYPTION_FAILED:
481                                         str_details2 = " decryption_failed";
482                                         break;
483                                 case TLS1_AD_RECORD_OVERFLOW:
484                                         str_details2 = " record_overflow";
485                                         break;
486                                 case SSL3_AD_DECOMPRESSION_FAILURE:
487                                         str_details2 = " decompression_failure";
488                                         break;
489                                 case SSL3_AD_HANDSHAKE_FAILURE:
490                                         str_details2 = " handshake_failure";
491                                         break;
492                                 case SSL3_AD_BAD_CERTIFICATE:
493                                         str_details2 = " bad_certificate";
494                                         break;
495                                 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
496                                         str_details2 = " unsupported_certificate";
497                                         break;
498                                 case SSL3_AD_CERTIFICATE_REVOKED:
499                                         str_details2 = " certificate_revoked";
500                                         break;
501                                 case SSL3_AD_CERTIFICATE_EXPIRED:
502                                         str_details2 = " certificate_expired";
503                                         break;
504                                 case SSL3_AD_CERTIFICATE_UNKNOWN:
505                                         str_details2 = " certificate_unknown";
506                                         break;
507                                 case SSL3_AD_ILLEGAL_PARAMETER:
508                                         str_details2 = " illegal_parameter";
509                                         break;
510                                 case TLS1_AD_UNKNOWN_CA:
511                                         str_details2 = " unknown_ca";
512                                         break;
513                                 case TLS1_AD_ACCESS_DENIED:
514                                         str_details2 = " access_denied";
515                                         break;
516                                 case TLS1_AD_DECODE_ERROR:
517                                         str_details2 = " decode_error";
518                                         break;
519                                 case TLS1_AD_DECRYPT_ERROR:
520                                         str_details2 = " decrypt_error";
521                                         break;
522                                 case TLS1_AD_EXPORT_RESTRICTION:
523                                         str_details2 = " export_restriction";
524                                         break;
525                                 case TLS1_AD_PROTOCOL_VERSION:
526                                         str_details2 = " protocol_version";
527                                         break;
528                                 case TLS1_AD_INSUFFICIENT_SECURITY:
529                                         str_details2 = " insufficient_security";
530                                         break;
531                                 case TLS1_AD_INTERNAL_ERROR:
532                                         str_details2 = " internal_error";
533                                         break;
534                                 case TLS1_AD_USER_CANCELLED:
535                                         str_details2 = " user_canceled";
536                                         break;
537                                 case TLS1_AD_NO_RENEGOTIATION:
538                                         str_details2 = " no_renegotiation";
539                                         break;
540                                 }
541                         }
542                 }
543
544                 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
545                         str_details1 = "???";
546
547                         if (tls_session->info.record_len > 0)
548                         switch (tls_session->info.handshake_type)
549                         {
550                         case SSL3_MT_HELLO_REQUEST:
551                                 str_details1 = ", HelloRequest";
552                                 break;
553                         case SSL3_MT_CLIENT_HELLO:
554                                 str_details1 = ", ClientHello";
555                                 break;
556                         case SSL3_MT_SERVER_HELLO:
557                                 str_details1 = ", ServerHello";
558                                 break;
559                         case SSL3_MT_CERTIFICATE:
560                                 str_details1 = ", Certificate";
561                                 break;
562                         case SSL3_MT_SERVER_KEY_EXCHANGE:
563                                 str_details1 = ", ServerKeyExchange";
564                                 break;
565                         case SSL3_MT_CERTIFICATE_REQUEST:
566                                 str_details1 = ", CertificateRequest";
567                                 break;
568                         case SSL3_MT_SERVER_DONE:
569                                 str_details1 = ", ServerHelloDone";
570                                 break;
571                         case SSL3_MT_CERTIFICATE_VERIFY:
572                                 str_details1 = ", CertificateVerify";
573                                 break;
574                         case SSL3_MT_CLIENT_KEY_EXCHANGE:
575                                 str_details1 = ", ClientKeyExchange";
576                                 break;
577                         case SSL3_MT_FINISHED:
578                                 str_details1 = ", Finished";
579                                 break;
580                         }
581                 }
582         }
583
584         snprintf(tls_session->info.info_description, 
585                  sizeof(tls_session->info.info_description),
586                  "%s %s%s [length %04lx]%s%s\n",
587                  str_write_p, str_version, str_content_type,
588                  (unsigned long)tls_session->info.record_len,
589                  str_details1, str_details2);
590
591         handler = (EAP_HANDLER *)SSL_get_ex_data(tls_session->ssl, 0);
592         if (handler) {
593                 request = handler->request;
594         } else {
595                 request = NULL;
596         }
597
598         RDEBUG2("%s\n", tls_session->info.info_description);
599 }