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