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