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