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