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