There's no need to memset data to zero
[freeradius.git] / src / main / tls_listen.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/radiusd.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/rad_assert.h>
31
32 #ifdef HAVE_SYS_STAT_H
33 #include <sys/stat.h>
34 #endif
35
36 #ifdef WITH_TLS
37 #ifdef HAVE_OPENSSL_RAND_H
38 #include <openssl/rand.h>
39 #endif
40
41 #ifdef HAVE_OPENSSL_OCSP_H
42 #include <openssl/ocsp.h>
43 #endif
44
45 #ifdef HAVE_PTHREAD_H
46 #define PTHREAD_MUTEX_LOCK pthread_mutex_lock
47 #define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
48 #else
49 #define PTHREAD_MUTEX_LOCK(_x)
50 #define PTHREAD_MUTEX_UNLOCK(_x)
51 #endif
52
53 static void dump_hex(const char *msg, const uint8_t *data, size_t data_len)
54 {
55         size_t i;
56
57         if (debug_flag < 3) return;
58
59         printf("%s %d\n", msg, (int) data_len);
60         if (data_len > 256) data_len = 256;
61
62         for (i = 0; i < data_len; i++) {
63                 if ((i & 0x0f) == 0x00) printf ("%02x: ", (unsigned int) i);
64                 printf("%02x ", data[i]);
65                 if ((i & 0x0f) == 0x0f) printf ("\n");
66         }
67         printf("\n");
68         fflush(stdout);
69 }
70
71 static void tls_socket_close(rad_listen_t *listener)
72 {
73         listen_socket_t *sock = listener->data;
74
75         listener->status = RAD_LISTEN_STATUS_REMOVE_FD;
76         listener->tls = NULL; /* parent owns this! */
77         
78         if (sock->parent) {
79                 /*
80                  *      Decrement the number of connections.
81                  */
82                 if (sock->parent->limit.num_connections > 0) {
83                         sock->parent->limit.num_connections--;
84                 }
85                 if (sock->client->limit.num_connections > 0) {
86                         sock->client->limit.num_connections--;
87                 }
88         }
89         
90         /*
91          *      Tell the event handler that an FD has disappeared.
92          */
93         DEBUG("Client has closed connection");
94         event_new_fd(listener);
95         
96         /*
97          *      Do NOT free the listener here.  It's in use by
98          *      a request, and will need to hang around until
99          *      all of the requests are done.
100          *
101          *      It is instead free'd in remove_from_request_hash()
102          */
103 }
104
105 static int tls_socket_write(rad_listen_t *listener, REQUEST *request)
106 {
107         uint8_t *p;
108         ssize_t rcode;
109         listen_socket_t *sock = listener->data;
110
111         p = sock->ssn->dirty_out.data;
112         
113         while (p < (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used)) {
114                 RDEBUG3("Writing to socket %d", request->packet->sockfd);
115                 rcode = write(request->packet->sockfd, p,
116                               (sock->ssn->dirty_out.data + sock->ssn->dirty_out.used) - p);
117                 if (rcode <= 0) {
118                         RDEBUG("Error writing to TLS socket: %s", strerror(errno));
119                         
120                         tls_socket_close(listener);
121                         return 0;
122                 }
123                 p += rcode;
124         }
125
126         sock->ssn->dirty_out.used = 0;
127         
128         return 1;
129 }
130
131
132 static int tls_socket_recv(rad_listen_t *listener)
133 {
134         int doing_init = FALSE;
135         ssize_t rcode;
136         RADIUS_PACKET *packet;
137         REQUEST *request;
138         listen_socket_t *sock = listener->data;
139         fr_tls_status_t status;
140         RADCLIENT *client = sock->client;
141
142         if (!sock->packet) {
143                 sock->packet = rad_alloc(0);
144                 if (!sock->packet) return 0;
145
146                 sock->packet->sockfd = listener->fd;
147                 sock->packet->src_ipaddr = sock->other_ipaddr;
148                 sock->packet->src_port = sock->other_port;
149                 sock->packet->dst_ipaddr = sock->my_ipaddr;
150                 sock->packet->dst_port = sock->my_port;
151
152                 if (sock->request) sock->request->packet = sock->packet;
153         }
154
155         /*
156          *      Allocate a REQUEST for debugging.
157          */
158         if (!sock->request) {
159                 sock->request = request = request_alloc();
160                 if (!sock->request) {
161                         radlog(L_ERR, "Out of memory");
162                         return 0;
163                 }
164
165                 rad_assert(request->packet == NULL);
166                 rad_assert(sock->packet != NULL);
167                 request->packet = sock->packet;
168
169                 request->component = "<core>";
170                 request->component = "<tls-connect>";
171
172                 /*
173                  *      Not sure if we should do this on every packet...
174                  */
175                 request->reply = rad_alloc(0);
176                 if (!request->reply) return 0;
177
178                 request->options = RAD_REQUEST_OPTION_DEBUG2;
179
180                 rad_assert(sock->ssn == NULL);
181
182                 sock->ssn = tls_new_session(listener->tls, sock->request,
183                                             listener->tls->require_client_cert);
184                 if (!sock->ssn) {
185                         request_free(&sock->request);
186                         sock->packet = NULL;
187                         return 0;
188                 }
189
190                 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
191                 SSL_set_ex_data(sock->ssn->ssl, FR_TLS_EX_INDEX_CERTS, (void *)&request->packet->vps);
192
193                 doing_init = TRUE;
194         }
195
196         rad_assert(sock->request != NULL);
197         rad_assert(sock->request->packet != NULL);
198         rad_assert(sock->packet != NULL);
199         rad_assert(sock->ssn != NULL);
200
201         request = sock->request;
202
203         RDEBUG3("Reading from socket %d", request->packet->sockfd);
204         PTHREAD_MUTEX_LOCK(&sock->mutex);
205         rcode = read(request->packet->sockfd,
206                      sock->ssn->dirty_in.data,
207                      sizeof(sock->ssn->dirty_in.data));
208         if ((rcode < 0) && (errno == ECONNRESET)) {
209         do_close:
210                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
211                 tls_socket_close(listener);
212                 return 0;
213         }
214         
215         if (rcode < 0) {
216                 RDEBUG("Error reading TLS socket: %s", strerror(errno));
217                 goto do_close;
218         }
219
220         /*
221          *      Normal socket close.
222          */
223         if (rcode == 0) goto do_close;
224         
225         sock->ssn->dirty_in.used = rcode;
226
227         dump_hex("READ FROM SSL", sock->ssn->dirty_in.data, sock->ssn->dirty_in.used);
228
229         /*
230          *      Catch attempts to use non-SSL.
231          */
232         if (doing_init && (sock->ssn->dirty_in.data[0] != handshake)) {
233                 RDEBUG("Non-TLS data sent to TLS socket: closing");
234                 goto do_close;
235         }
236         
237         /*
238          *      Skip ahead to reading application data.
239          */
240         if (SSL_is_init_finished(sock->ssn->ssl)) goto app;
241
242         if (!tls_handshake_recv(request, sock->ssn)) {
243                 RDEBUG("FAILED in TLS handshake receive");
244                 goto do_close;
245         }
246         
247         if (sock->ssn->dirty_out.used > 0) {
248                 tls_socket_write(listener, request);
249                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
250                 return 0;
251         }
252
253 app:
254         /*
255          *      FIXME: Run the packet through a virtual server in
256          *      order to see if we like the certificate presented by
257          *      the client.
258          */
259
260         status = tls_application_data(sock->ssn, request);
261         RDEBUG("Application data status %d", status);
262
263         if (status == FR_TLS_MORE_FRAGMENTS) {
264                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
265                 return 0;
266         }
267
268         if (sock->ssn->clean_out.used == 0) {
269                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
270                 return 0;
271         }
272
273         dump_hex("TUNNELED DATA", sock->ssn->clean_out.data, sock->ssn->clean_out.used);
274
275         /*
276          *      If the packet is a complete RADIUS packet, return it to
277          *      the caller.  Otherwise...
278          */
279         if ((sock->ssn->clean_out.used < 20) ||
280             (((sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]) != (int) sock->ssn->clean_out.used)) {
281                 RDEBUG("Received bad packet: Length %d contents %d",
282                        sock->ssn->clean_out.used,
283                        (sock->ssn->clean_out.data[2] << 8) | sock->ssn->clean_out.data[3]);
284                 goto do_close;
285         }
286
287         packet = sock->packet;
288         packet->data = rad_malloc(sock->ssn->clean_out.used);
289         packet->data_len = sock->ssn->clean_out.used;
290         sock->ssn->record_minus(&sock->ssn->clean_out, packet->data, packet->data_len);
291         packet->vps = NULL;
292         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
293
294         if (!rad_packet_ok(packet, 0)) {
295                 RDEBUG("Received bad packet: %s", fr_strerror());
296                 tls_socket_close(listener);
297                 return 0;       /* do_close unlocks the mutex */
298         }
299
300         /*
301          *      Copied from src/lib/radius.c, rad_recv();
302          */
303         if (fr_debug_flag) {
304                 char host_ipaddr[128];
305
306                 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
307                         RDEBUG("tls_recv: %s packet from host %s port %d, id=%d, length=%d",
308                                fr_packet_codes[packet->code],
309                                inet_ntop(packet->src_ipaddr.af,
310                                          &packet->src_ipaddr.ipaddr,
311                                          host_ipaddr, sizeof(host_ipaddr)),
312                                packet->src_port,
313                                packet->id, (int) packet->data_len);
314                 } else {
315                         RDEBUG("tls_recv: Packet from host %s port %d code=%d, id=%d, length=%d",
316                                inet_ntop(packet->src_ipaddr.af,
317                                          &packet->src_ipaddr.ipaddr,
318                                          host_ipaddr, sizeof(host_ipaddr)),
319                                packet->src_port,
320                                packet->code,
321                                packet->id, (int) packet->data_len);
322                 }
323         }
324
325         FR_STATS_INC(auth, total_requests);
326
327         return 1;
328 }
329
330
331 int dual_tls_recv(rad_listen_t *listener)
332 {
333         RADIUS_PACKET *packet;
334         REQUEST *request;
335         RAD_REQUEST_FUNP fun = NULL;
336         listen_socket_t *sock = listener->data;
337         RADCLIENT       *client = sock->client;
338
339         if (!tls_socket_recv(listener)) {
340                 return 0;
341         }
342
343         rad_assert(sock->request != NULL);
344         rad_assert(sock->request->packet != NULL);
345         rad_assert(sock->packet != NULL);
346         rad_assert(sock->ssn != NULL);
347
348         request = sock->request;
349         packet = sock->packet;
350
351         /*
352          *      Some sanity checks, based on the packet code.
353          */
354         switch(packet->code) {
355         case PW_AUTHENTICATION_REQUEST:
356                 if (listener->type != RAD_LISTEN_AUTH) goto bad_packet;
357                 FR_STATS_INC(auth, total_requests);
358                 fun = rad_authenticate;
359                 break;
360
361         case PW_ACCOUNTING_REQUEST:
362                 if (listener->type != RAD_LISTEN_ACCT) goto bad_packet;
363                 FR_STATS_INC(acct, total_requests);
364                 fun = rad_accounting;
365                 break;
366
367         case PW_STATUS_SERVER:
368                 if (!mainconfig.status_server) {
369                         FR_STATS_INC(auth, total_unknown_types);
370                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
371                         rad_free(&sock->packet);
372                         request->packet = NULL;
373                         return 0;
374                 }
375                 fun = rad_status_server;
376                 break;
377
378         default:
379         bad_packet:
380                 FR_STATS_INC(auth, total_unknown_types);
381
382                 DEBUG("Invalid packet code %d sent from client %s port %d : IGNORED",
383                       packet->code, client->shortname, packet->src_port);
384                 rad_free(&sock->packet);
385                 request->packet = NULL;
386                 return 0;
387         } /* switch over packet types */
388
389         if (!request_receive(listener, packet, client, fun)) {
390                 FR_STATS_INC(auth, total_packets_dropped);
391                 rad_free(&sock->packet);
392                 request->packet = NULL;
393                 return 0;
394         }
395
396         sock->packet = NULL;    /* we have no need for more partial reads */
397         request->packet = NULL;
398
399         return 1;
400 }
401
402
403 /*
404  *      Send a response packet
405  */
406 int dual_tls_send(rad_listen_t *listener, REQUEST *request)
407 {
408         listen_socket_t *sock = listener->data;
409
410         rad_assert(request->listener == listener);
411         rad_assert(listener->send == dual_tls_send);
412
413         /*
414          *      Accounting reject's are silently dropped.
415          *
416          *      We do it here to avoid polluting the rest of the
417          *      code with this knowledge
418          */
419         if (request->reply->code == 0) return 0;
420
421         /*
422          *      Pack the VPs
423          */
424         if (rad_encode(request->reply, request->packet,
425                        request->client->secret) < 0) {
426                 RDEBUG("Failed encoding packet: %s", fr_strerror());
427                 return 0;
428         }
429
430         /*
431          *      Sign the packet.
432          */
433         if (rad_sign(request->reply, request->packet,
434                        request->client->secret) < 0) {
435                 RDEBUG("Failed signing packet: %s", fr_strerror());
436                 return 0;
437         }
438         
439         PTHREAD_MUTEX_LOCK(&sock->mutex);
440         /*
441          *      Write the packet to the SSL buffers.
442          */
443         sock->ssn->record_plus(&sock->ssn->clean_in,
444                                request->reply->data, request->reply->data_len);
445
446         /*
447          *      Do SSL magic to get encrypted data.
448          */
449         tls_handshake_send(request, sock->ssn);
450
451         /*
452          *      And finally write the data to the socket.
453          */
454         if (sock->ssn->dirty_out.used > 0) {
455                 dump_hex("WRITE TO SSL", sock->ssn->dirty_out.data, sock->ssn->dirty_out.used);
456
457                 tls_socket_write(listener, request);
458         }
459         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
460
461         return 0;
462 }
463
464
465 int proxy_tls_recv(rad_listen_t *listener)
466 {
467         int rcode;
468         size_t length;
469         listen_socket_t *sock = listener->data;
470         char buffer[256];
471         RADIUS_PACKET *packet;
472         uint8_t *data;
473
474         if (!sock->data) sock->data = rad_malloc(sock->ssn->offset);
475         data = sock->data;
476
477         DEBUG3("Proxy SSL socket has data to read");
478         PTHREAD_MUTEX_LOCK(&sock->mutex);
479 redo:
480         rcode = SSL_read(sock->ssn->ssl, data, 4);
481         if (rcode <= 0) {
482                 int err = SSL_get_error(sock->ssn->ssl, rcode);
483                 switch (err) {
484                 case SSL_ERROR_WANT_READ:
485                 case SSL_ERROR_WANT_WRITE:
486                         goto redo;
487
488                 case SSL_ERROR_ZERO_RETURN:
489                         /* remote end sent close_notify, send one back */
490                         SSL_shutdown(sock->ssn->ssl);
491
492                 case SSL_ERROR_SYSCALL:
493                 do_close:
494                         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
495                         tls_socket_close(listener);
496                         return 0;
497
498                 default:
499                         while ((err = ERR_get_error())) {
500                                 DEBUG("proxy recv says %s",
501                                       ERR_error_string(err, NULL));
502                         }
503                         
504                         goto do_close;
505                 }
506         }
507
508         length = (data[2] << 8) | data[3];
509         DEBUG3("Proxy received header saying we have a packet of %u bytes",
510                (unsigned int) length);
511
512         if (length > sock->ssn->offset) {
513                 radlog(L_INFO,
514                        "Received packet will be too large! Set \"fragment_size=%u\"",
515                        (data[2] << 8) | data[3]);
516                 goto do_close;
517         }
518         
519         rcode = SSL_read(sock->ssn->ssl, data + 4, length);
520         if (rcode <= 0) {
521                 switch (SSL_get_error(sock->ssn->ssl, rcode)) {
522                 case SSL_ERROR_WANT_READ:
523                 case SSL_ERROR_WANT_WRITE:
524                         break;
525
526                 case SSL_ERROR_ZERO_RETURN:
527                         /* remote end sent close_notify, send one back */
528                         SSL_shutdown(sock->ssn->ssl);
529                         goto do_close;
530                 default:
531                         goto do_close;
532                 }
533         }
534         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
535
536         packet = rad_alloc(0);
537         packet->sockfd = listener->fd;
538         packet->src_ipaddr = sock->other_ipaddr;
539         packet->src_port = sock->other_port;
540         packet->dst_ipaddr = sock->my_ipaddr;
541         packet->dst_port = sock->my_port;
542         packet->code = data[0];
543         packet->id = data[1];
544         packet->data_len = length;
545         packet->data = rad_malloc(packet->data_len);
546         memcpy(packet->data, data, packet->data_len);
547         memcpy(packet->vector, packet->data + 4, 16);
548
549         /*
550          *      FIXME: Client MIB updates?
551          */
552         switch(packet->code) {
553         case PW_AUTHENTICATION_ACK:
554         case PW_ACCESS_CHALLENGE:
555         case PW_AUTHENTICATION_REJECT:
556                 break;
557
558 #ifdef WITH_ACCOUNTING
559         case PW_ACCOUNTING_RESPONSE:
560                 break;
561 #endif
562
563         default:
564                 /*
565                  *      FIXME: Update MIB for packet types?
566                  */
567                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
568                        "from home server %s port %d - ID %d : IGNORED",
569                        packet->code,
570                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
571                        packet->src_port, packet->id);
572                 rad_free(&packet);
573                 return 0;
574         }
575
576         if (!request_proxy_reply(packet)) {
577                 rad_free(&packet);
578                 return 0;
579         }
580
581         return 1;
582 }
583
584 int proxy_tls_send(rad_listen_t *listener, REQUEST *request)
585 {
586         int rcode;
587         listen_socket_t *sock = listener->data;
588
589         /*
590          *      Normal proxying calls us with the data already
591          *      encoded.  The "ping home server" code does not.  So,
592          *      if there's no packet, encode it here.
593          */
594         if (!request->proxy->data) {
595                 request->proxy_listener->encode(request->proxy_listener,
596                                                 request);
597         }
598
599         DEBUG3("Proxy is writing %u bytes to SSL",
600                (unsigned int) request->proxy->data_len);
601         PTHREAD_MUTEX_LOCK(&sock->mutex);
602         while ((rcode = SSL_write(sock->ssn->ssl, request->proxy->data,
603                                   request->proxy->data_len)) < 0) {
604                 int err;
605                 while ((err = ERR_get_error())) {
606                         DEBUG("proxy SSL_write says %s",
607                               ERR_error_string(err, NULL));
608                 }
609                 PTHREAD_MUTEX_UNLOCK(&sock->mutex);
610                 tls_socket_close(listener);
611                 return 0;
612         }
613         PTHREAD_MUTEX_UNLOCK(&sock->mutex);
614
615         return 1;
616 }
617
618 #endif  /* WITH_TLS */