Pull fix for bug #436 from branch_1_1
[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         err = SSL_read(ssn->ssl, ssn->clean_out.data,
179                        sizeof(ssn->clean_out.data));
180         if (err > 0) {
181                 ssn->clean_out.used = err;
182         } else if (!int_ssl_check(ssn->ssl, err, "SSL_read")) {
183                 return 0;
184         }
185
186         /* Some Extra STATE information for easy debugging */
187         if (SSL_is_init_finished(ssn->ssl)) {
188                 DEBUG2("SSL Connection Established\n");
189         }
190         if (SSL_in_init(ssn->ssl)) {
191                 DEBUG2("In SSL Handshake Phase\n");
192         }
193         if (SSL_in_before(ssn->ssl)) {
194                 DEBUG2("Before SSL Handshake Phase\n");
195         }
196         if (SSL_in_accept_init(ssn->ssl)) {
197                 DEBUG2("In SSL Accept mode \n");
198         }
199         if (SSL_in_connect_init(ssn->ssl)) {
200                 DEBUG2("In SSL Connect mode \n");
201         }
202
203         if (ssn->info.content_type != application_data) {
204                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
205                                sizeof(ssn->dirty_out.data));
206                 if (err > 0) {
207                         ssn->dirty_out.used = err;
208                 } else {
209                         int_ssl_check(ssn->ssl, err, "BIO_read");
210                         record_init(&ssn->dirty_in);
211                         return 0;
212                 }
213         } else {
214                 radlog(L_INFO, "rlm_eap_tls: Application Data");
215                 /* Its clean application data, do whatever we want */
216                 record_init(&ssn->clean_out);
217         }
218
219         /* We are done with dirty_in, reinitialize it */
220         record_init(&ssn->dirty_in);
221         return 1;
222 }
223
224 /*
225  *      Take clear-text user data, and encrypt it into the output buffer,
226  *      to send to the client at the other end of the SSL connection.
227  */
228 int tls_handshake_send(tls_session_t *ssn)
229 {
230         int err;
231
232         /*
233          *      If there's un-encrypted data in 'clean_in', then write
234          *      that data to the SSL session, and then call the BIO function
235          *      to get that encrypted data from the SSL session, into
236          *      a buffer which we can then package into an EAP packet.
237          *
238          *      Based on Server's logic this clean_in is expected to
239          *      contain the data to send to the client.
240          */
241         if (ssn->clean_in.used > 0) {
242                 SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
243
244                 /* Get the dirty data from Bio to send it */
245                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
246                                sizeof(ssn->dirty_out.data));
247                 if (err > 0) {
248                         ssn->dirty_out.used = err;
249                 } else {
250                         int_ssl_check(ssn->ssl, err, "handshake_send");
251                 }
252         }
253
254         record_init(&ssn->clean_in);
255         return 1;
256 }
257
258 void session_init(tls_session_t *ssn)
259 {
260         ssn->ssl = NULL;
261         ssn->into_ssl = ssn->from_ssl = NULL;
262         record_init(&ssn->clean_in);
263         record_init(&ssn->clean_out);
264         record_init(&ssn->dirty_in);
265         record_init(&ssn->dirty_out);
266
267         memset(&ssn->info, 0, sizeof(ssn->info));
268
269         ssn->offset = 0;
270         ssn->fragment = 0;
271         ssn->tls_msg_len = 0;
272         ssn->length_flag = 0;
273         ssn->opaque = NULL;
274         ssn->free_opaque = NULL;
275 }
276
277 void session_close(tls_session_t *ssn)
278 {
279         if(ssn->ssl)
280                 SSL_free(ssn->ssl);
281 #if 0
282 /*
283  * WARNING: SSL_free seems to decrement the reference counts already,
284  *      so doing this might crash the application.
285  */
286         if(ssn->into_ssl)
287                 BIO_free(ssn->into_ssl);
288         if(ssn->from_ssl)
289                 BIO_free(ssn->from_ssl);
290 #endif
291         record_close(&ssn->clean_in);
292         record_close(&ssn->clean_out);
293         record_close(&ssn->dirty_in);
294         record_close(&ssn->dirty_out);
295         session_init(ssn);
296 }
297
298 void session_free(void *ssn)
299 {
300         tls_session_t *sess = (tls_session_t *)ssn;
301
302         if (!ssn) return;
303
304         /*
305          *      Free any opaque TTLS or PEAP data.
306          */
307         if ((sess->opaque) && (sess->free_opaque)) {
308                 sess->free_opaque(sess->opaque);
309                 sess->opaque = NULL;
310         }
311
312         session_close(sess);
313
314         free(sess);
315 }
316
317 static void record_init(record_t *rec)
318 {
319         rec->used = 0;
320 }
321
322 static void record_close(record_t *rec)
323 {
324         rec->used = 0;
325 }
326
327
328 /*
329  *      Copy data to the intermediate buffer, before we send
330  *      it somewhere.
331  */
332 static unsigned int record_plus(record_t *rec, const void *ptr,
333                                 unsigned int size)
334 {
335         unsigned int added = MAX_RECORD_SIZE - rec->used;
336
337         if(added > size)
338                 added = size;
339         if(added == 0)
340                 return 0;
341         memcpy(rec->data + rec->used, ptr, added);
342         rec->used += added;
343         return added;
344 }
345
346 /*
347  *      Take data from the buffer, and give it to the caller.
348  */
349 static unsigned int record_minus(record_t *rec, void *ptr,
350                                  unsigned int size)
351 {
352         unsigned int taken = rec->used;
353
354         if(taken > size)
355                 taken = size;
356         if(taken == 0)
357                 return 0;
358         if(ptr)
359                 memcpy(ptr, rec->data, taken);
360         rec->used -= taken;
361
362         /*
363          *      This is pretty bad...
364          */
365         if(rec->used > 0)
366                 memmove(rec->data, rec->data + taken, rec->used);
367         return taken;
368 }
369
370 void tls_session_information(tls_session_t *tls_session)
371 {
372         const char *str_write_p, *str_version, *str_content_type = "";
373         const char *str_details1 = "", *str_details2= "";
374
375         /*
376          *      Don't print this out in the normal course of
377          *      operations.
378          */
379         if (debug_flag == 0) {
380                 return;
381         }
382
383         str_write_p = tls_session->info.origin ? ">>>" : "<<<";
384
385         switch (tls_session->info.version)
386         {
387         case SSL2_VERSION:
388                 str_version = "SSL 2.0";
389                 break;
390         case SSL3_VERSION:
391                 str_version = "SSL 3.0 ";
392                 break;
393         case TLS1_VERSION:
394                 str_version = "TLS 1.0 ";
395                 break;
396         default:
397                 str_version = "Unknown TLS version";
398                 break;
399         }
400
401         if (tls_session->info.version == SSL3_VERSION ||
402             tls_session->info.version == TLS1_VERSION) {
403                 switch (tls_session->info.content_type) {
404                 case SSL3_RT_CHANGE_CIPHER_SPEC:
405                         str_content_type = "ChangeCipherSpec";
406                         break;
407                 case SSL3_RT_ALERT:
408                         str_content_type = "Alert";
409                         break;
410                 case SSL3_RT_HANDSHAKE:
411                         str_content_type = "Handshake";
412                         break;
413                 case SSL3_RT_APPLICATION_DATA:
414                         str_content_type = "ApplicationData";
415                         break;
416                 default:
417                         str_content_type = "UnknownContentType";
418                         break;
419                 }
420
421                 if (tls_session->info.content_type == SSL3_RT_ALERT) {
422                         str_details1 = ", ???";
423
424                         if (tls_session->info.record_len == 2) {
425
426                                 switch (tls_session->info.alert_level) {
427                                 case SSL3_AL_WARNING:
428                                         str_details1 = ", warning";
429                                         break;
430                                 case SSL3_AL_FATAL:
431                                         str_details1 = ", fatal";
432                                         break;
433                                 }
434
435                                 str_details2 = " ???";
436                                 switch (tls_session->info.alert_description) {
437                                 case SSL3_AD_CLOSE_NOTIFY:
438                                         str_details2 = " close_notify";
439                                         break;
440                                 case SSL3_AD_UNEXPECTED_MESSAGE:
441                                         str_details2 = " unexpected_message";
442                                         break;
443                                 case SSL3_AD_BAD_RECORD_MAC:
444                                         str_details2 = " bad_record_mac";
445                                         break;
446                                 case TLS1_AD_DECRYPTION_FAILED:
447                                         str_details2 = " decryption_failed";
448                                         break;
449                                 case TLS1_AD_RECORD_OVERFLOW:
450                                         str_details2 = " record_overflow";
451                                         break;
452                                 case SSL3_AD_DECOMPRESSION_FAILURE:
453                                         str_details2 = " decompression_failure";
454                                         break;
455                                 case SSL3_AD_HANDSHAKE_FAILURE:
456                                         str_details2 = " handshake_failure";
457                                         break;
458                                 case SSL3_AD_BAD_CERTIFICATE:
459                                         str_details2 = " bad_certificate";
460                                         break;
461                                 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
462                                         str_details2 = " unsupported_certificate";
463                                         break;
464                                 case SSL3_AD_CERTIFICATE_REVOKED:
465                                         str_details2 = " certificate_revoked";
466                                         break;
467                                 case SSL3_AD_CERTIFICATE_EXPIRED:
468                                         str_details2 = " certificate_expired";
469                                         break;
470                                 case SSL3_AD_CERTIFICATE_UNKNOWN:
471                                         str_details2 = " certificate_unknown";
472                                         break;
473                                 case SSL3_AD_ILLEGAL_PARAMETER:
474                                         str_details2 = " illegal_parameter";
475                                         break;
476                                 case TLS1_AD_UNKNOWN_CA:
477                                         str_details2 = " unknown_ca";
478                                         break;
479                                 case TLS1_AD_ACCESS_DENIED:
480                                         str_details2 = " access_denied";
481                                         break;
482                                 case TLS1_AD_DECODE_ERROR:
483                                         str_details2 = " decode_error";
484                                         break;
485                                 case TLS1_AD_DECRYPT_ERROR:
486                                         str_details2 = " decrypt_error";
487                                         break;
488                                 case TLS1_AD_EXPORT_RESTRICTION:
489                                         str_details2 = " export_restriction";
490                                         break;
491                                 case TLS1_AD_PROTOCOL_VERSION:
492                                         str_details2 = " protocol_version";
493                                         break;
494                                 case TLS1_AD_INSUFFICIENT_SECURITY:
495                                         str_details2 = " insufficient_security";
496                                         break;
497                                 case TLS1_AD_INTERNAL_ERROR:
498                                         str_details2 = " internal_error";
499                                         break;
500                                 case TLS1_AD_USER_CANCELLED:
501                                         str_details2 = " user_canceled";
502                                         break;
503                                 case TLS1_AD_NO_RENEGOTIATION:
504                                         str_details2 = " no_renegotiation";
505                                         break;
506                                 }
507                         }
508                 }
509
510                 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
511                         str_details1 = "???";
512
513                         if (tls_session->info.record_len > 0)
514                         switch (tls_session->info.handshake_type)
515                         {
516                         case SSL3_MT_HELLO_REQUEST:
517                                 str_details1 = ", HelloRequest";
518                                 break;
519                         case SSL3_MT_CLIENT_HELLO:
520                                 str_details1 = ", ClientHello";
521                                 break;
522                         case SSL3_MT_SERVER_HELLO:
523                                 str_details1 = ", ServerHello";
524                                 break;
525                         case SSL3_MT_CERTIFICATE:
526                                 str_details1 = ", Certificate";
527                                 break;
528                         case SSL3_MT_SERVER_KEY_EXCHANGE:
529                                 str_details1 = ", ServerKeyExchange";
530                                 break;
531                         case SSL3_MT_CERTIFICATE_REQUEST:
532                                 str_details1 = ", CertificateRequest";
533                                 break;
534                         case SSL3_MT_SERVER_DONE:
535                                 str_details1 = ", ServerHelloDone";
536                                 break;
537                         case SSL3_MT_CERTIFICATE_VERIFY:
538                                 str_details1 = ", CertificateVerify";
539                                 break;
540                         case SSL3_MT_CLIENT_KEY_EXCHANGE:
541                                 str_details1 = ", ClientKeyExchange";
542                                 break;
543                         case SSL3_MT_FINISHED:
544                                 str_details1 = ", Finished";
545                                 break;
546                         }
547                 }
548         }
549
550         sprintf(tls_session->info.info_description, "%s %s%s [length %04lx]%s%s\n",
551                 str_write_p, str_version, str_content_type,
552                 (unsigned long)tls_session->info.record_len, str_details1, str_details2);
553         DEBUG2("  rlm_eap_tls: %s\n", tls_session->info.info_description);
554 }