Imported Upstream version 3.2.0
[debian/amanda] / common-src / bsd-security.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1999 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /*
27  * $Id: bsd-security.c,v 1.75 2006/07/19 17:41:14 martinea Exp $
28  *
29  * "BSD" security module
30  */
31
32 #include "amanda.h"
33 #include "util.h"
34 #include "clock.h"
35 #include "dgram.h"
36 #include "event.h"
37 #include "packet.h"
38 #include "security.h"
39 #include "security-util.h"
40 #include "sockaddr-util.h"
41 #include "stream.h"
42
43 #ifndef SO_RCVBUF
44 #undef DUMPER_SOCKET_BUFFERING
45 #endif
46
47 /*
48  * Interface functions
49  */
50 static void     bsd_connect(const char *, char *(*)(char *, void *), 
51                         void (*)(void *, security_handle_t *, security_status_t),
52                         void *, void *);
53 static void     bsd_accept(const struct security_driver *,
54                         char *(*)(char *, void *),
55                         int, int,
56                         void (*)(security_handle_t *, pkt_t *),
57                         void *);
58 static void     bsd_close(void *);
59 static void *   bsd_stream_server(void *);
60 static int      bsd_stream_accept(void *);
61 static void *   bsd_stream_client(void *, int);
62 static void     bsd_stream_close(void *);
63 static int      bsd_stream_auth(void *);
64 static int      bsd_stream_id(void *);
65 static void     bsd_stream_read(void *, void (*)(void *, void *, ssize_t), void *);
66 static ssize_t  bsd_stream_read_sync(void *, void **);
67 static void     bsd_stream_read_cancel(void *);
68
69 /*
70  * This is our interface to the outside world
71  */
72 const security_driver_t bsd_security_driver = {
73     "BSD",
74     bsd_connect,
75     bsd_accept,
76     sec_get_authenticated_peer_name_hostname,
77     bsd_close,
78     udpbsd_sendpkt,
79     udp_recvpkt,
80     udp_recvpkt_cancel,
81     bsd_stream_server,
82     bsd_stream_accept,
83     bsd_stream_client,
84     bsd_stream_close,
85     bsd_stream_auth,
86     bsd_stream_id,
87     tcp_stream_write,
88     bsd_stream_read,
89     bsd_stream_read_sync,
90     bsd_stream_read_cancel,
91     sec_close_connection_none,
92     NULL,
93     NULL
94 };
95
96 /*
97  * This is data local to the datagram socket.  We have one datagram
98  * per process, so it is global.
99  */
100 static udp_handle_t netfd4;
101 static udp_handle_t netfd6;
102 static int not_init4 = 1;
103 static int not_init6 = 1;
104
105 /* generate new handles from here */
106 static int newhandle = 0;
107
108 /*
109  * These are the internal helper functions
110  */
111 static void     stream_read_callback(void *);
112 static void     stream_read_sync_callback(void *);
113
114 /*
115  * Setup and return a handle outgoing to a client
116  */
117
118 static void
119 bsd_connect(
120     const char *        hostname,
121     char *              (*conf_fn)(char *, void *),
122     void                (*fn)(void *, security_handle_t *, security_status_t),
123     void *              arg,
124     void *              datap)
125 {
126     struct sec_handle *bh;
127     in_port_t port = 0;
128     struct timeval sequence_time;
129     int sequence;
130     char *handle;
131     int result;
132     struct addrinfo *res, *res_addr;
133     char *canonname;
134     int result_bind;
135     char *service;
136
137     assert(hostname != NULL);
138
139     (void)conf_fn;      /* Quiet unused parameter warning */
140     (void)datap;        /* Quiet unused parameter warning */
141
142     bh = g_new0(struct sec_handle, 1);
143     bh->proto_handle=NULL;
144     security_handleinit(&bh->sech, &bsd_security_driver);
145
146     result = resolve_hostname(hostname, SOCK_DGRAM, &res, &canonname);
147     if(result != 0) {
148         dbprintf(_("resolve_hostname(%s): %s\n"), hostname, gai_strerror(result));
149         security_seterror(&bh->sech, _("resolve_hostname(%s): %s\n"), hostname,
150                           gai_strerror(result));
151         (*fn)(arg, &bh->sech, S_ERROR);
152         return;
153     }
154     if (canonname == NULL) {
155         dbprintf(_("resolve_hostname(%s) did not return a canonical name\n"), hostname);
156         security_seterror(&bh->sech,
157                 _("resolve_hostname(%s) did not return a canonical name\n"), hostname);
158         (*fn)(arg, &bh->sech, S_ERROR);
159         if (res) freeaddrinfo(res);
160         return;
161     }
162     if (res == NULL) {
163         dbprintf(_("resolve_hostname(%s): no results\n"), hostname);
164         security_seterror(&bh->sech,
165                 _("resolve_hostname(%s): no results\n"), hostname);
166         (*fn)(arg, &bh->sech, S_ERROR);
167         amfree(canonname);
168         return;
169     }
170
171     for (res_addr = res; res_addr != NULL; res_addr = res_addr->ai_next) {
172 #ifdef WORKING_IPV6
173         /* IPv6 socket already bound */
174         if (res_addr->ai_addr->sa_family == AF_INET6 && not_init6 == 0) {
175             break;
176         }
177         /*
178          * Only init the IPv6 socket once
179          */
180         if (res_addr->ai_addr->sa_family == AF_INET6 && not_init6 == 1) {
181             uid_t euid;
182             dgram_zero(&netfd6.dgram);
183
184             euid = geteuid();
185             set_root_privs(1);
186             result_bind = dgram_bind(&netfd6.dgram,
187                                      res_addr->ai_addr->sa_family, &port);
188             set_root_privs(0);
189             if (result_bind != 0) {
190                 continue;
191             }
192             netfd6.handle = NULL;
193             netfd6.pkt.body = NULL;
194             netfd6.recv_security_ok = &bsd_recv_security_ok;
195             netfd6.prefix_packet = &bsd_prefix_packet;
196             /*
197              * We must have a reserved port.  Bomb if we didn't get one.
198              */
199             if (port >= IPPORT_RESERVED) {
200                 security_seterror(&bh->sech,
201                     _("unable to bind to a reserved port (got port %u)"),
202                     (unsigned int)port);
203                 (*fn)(arg, &bh->sech, S_ERROR);
204                 freeaddrinfo(res);
205                 amfree(canonname);
206                 return;
207             }
208             not_init6 = 0;
209             bh->udp = &netfd6;
210             break;
211         }
212 #endif
213
214         /* IPv4 socket already bound */
215         if (res_addr->ai_addr->sa_family == AF_INET && not_init4 == 0) {
216             break;
217         }
218
219         /*
220          * Only init the IPv4 socket once
221          */
222         if (res_addr->ai_addr->sa_family == AF_INET && not_init4 == 1) {
223             uid_t euid;
224             dgram_zero(&netfd4.dgram);
225
226             euid = geteuid();
227             set_root_privs(1);
228             result_bind = dgram_bind(&netfd4.dgram,
229                                      res_addr->ai_addr->sa_family, &port);
230             set_root_privs(0);
231             if (result_bind != 0) {
232                 continue;
233             }
234             netfd4.handle = NULL;
235             netfd4.pkt.body = NULL;
236             netfd4.recv_security_ok = &bsd_recv_security_ok;
237             netfd4.prefix_packet = &bsd_prefix_packet;
238             /*
239              * We must have a reserved port.  Bomb if we didn't get one.
240              */
241             if (port >= IPPORT_RESERVED) {
242                 security_seterror(&bh->sech,
243                     "unable to bind to a reserved port (got port %u)",
244                     (unsigned int)port);
245                 (*fn)(arg, &bh->sech, S_ERROR);
246                 freeaddrinfo(res);
247                 amfree(canonname);
248                 return;
249             }
250             not_init4 = 0;
251             bh->udp = &netfd4;
252             break;
253         }
254     }
255
256     if (res_addr == NULL) {
257         dbprintf(_("Can't bind a socket to connect to %s\n"), hostname);
258         security_seterror(&bh->sech,
259                 _("Can't bind a socket to connect to %s\n"), hostname);
260         (*fn)(arg, &bh->sech, S_ERROR);
261        amfree(canonname);
262        return;
263     }
264
265 #ifdef WORKING_IPV6
266     if (res_addr->ai_addr->sa_family == AF_INET6)
267         bh->udp = &netfd6;
268     else
269 #endif
270         bh->udp = &netfd4;
271
272     auth_debug(1, _("Resolved hostname=%s\n"), canonname);
273
274     if (conf_fn) {
275         service = conf_fn("client_port", datap);
276         if (!service || strlen(service) <= 1)
277             service = "amanda";
278     } else {
279         service = "amanda";
280     }
281     port = find_port_for_service(service, "udp");
282     if (port == 0) {
283         security_seterror(&bh->sech, _("%s/udp unknown protocol"), service);
284         (*fn)(arg, &bh->sech, S_ERROR);
285         amfree(canonname);
286         return;
287     }
288
289     amanda_gettimeofday(&sequence_time);
290     sequence = (int)sequence_time.tv_sec ^ (int)sequence_time.tv_usec;
291     handle=alloc(15);
292     g_snprintf(handle, 14, "000-%08x",  (unsigned)newhandle++);
293     if (udp_inithandle(bh->udp, bh, canonname,
294         (sockaddr_union *)res_addr->ai_addr, port, handle, sequence) < 0) {
295         (*fn)(arg, &bh->sech, S_ERROR);
296         amfree(bh->hostname);
297         amfree(bh);
298     }
299     else {
300         (*fn)(arg, &bh->sech, S_OK);
301     }
302     amfree(handle);
303     amfree(canonname);
304
305     freeaddrinfo(res);
306 }
307
308 /*
309  * Setup to accept new incoming connections
310  */
311 static void
312 bsd_accept(
313     const struct security_driver *      driver,
314     char       *(*conf_fn)(char *, void *),
315     int         in,
316     int         out,
317     void        (*fn)(security_handle_t *, pkt_t *),
318     void       *datap)
319 {
320
321     assert(in >= 0 && out >= 0);
322     assert(fn != NULL);
323
324     (void)out;  /* Quiet unused parameter warning */
325     (void)driver; /* Quiet unused parameter warning */
326     (void)conf_fn;
327     (void)datap;
328
329     /*
330      * We assume in and out point to the same socket, and just use
331      * in.
332      */
333     dgram_socket(&netfd4.dgram, in);
334     dgram_socket(&netfd6.dgram, in);
335
336     /*
337      * Assign the function and return.  When they call recvpkt later,
338      * the recvpkt callback will call this function when it discovers
339      * new incoming connections
340      */
341     netfd4.accept_fn = fn;
342     netfd4.recv_security_ok = &bsd_recv_security_ok;
343     netfd4.prefix_packet = &bsd_prefix_packet;
344     netfd4.driver = &bsd_security_driver;
345
346     udp_addref(&netfd4, &udp_netfd_read_callback);
347 }
348
349 /*
350  * Frees a handle allocated by the above
351  */
352 static void
353 bsd_close(
354     void *      cookie)
355 {
356     struct sec_handle *bh = cookie;
357
358     if(bh->proto_handle == NULL) {
359         return;
360     }
361
362     auth_debug(1, _("bsd: close handle '%s'\n"), bh->proto_handle);
363
364     udp_recvpkt_cancel(bh);
365     if(bh->next) {
366         bh->next->prev = bh->prev;
367     }
368     else {
369         if (!not_init6 && netfd6.bh_last == bh)
370             netfd6.bh_last = bh->prev;
371         else
372             netfd4.bh_last = bh->prev;
373     }
374     if(bh->prev) {
375         bh->prev->next = bh->next;
376     }
377     else {
378         if (!not_init6 && netfd6.bh_first == bh)
379             netfd6.bh_first = bh->next;
380         else
381             netfd4.bh_first = bh->next;
382     }
383
384     amfree(bh->proto_handle);
385     amfree(bh->hostname);
386     amfree(bh);
387 }
388
389 /*
390  * Create the server end of a stream.  For bsd, this means setup a tcp
391  * socket for receiving a connection.
392  */
393 static void *
394 bsd_stream_server(
395     void *      h)
396 {
397     struct sec_stream *bs = NULL;
398     struct sec_handle *bh = h;
399
400     assert(bh != NULL);
401
402     bs = g_new0(struct sec_stream, 1);
403     security_streaminit(&bs->secstr, &bsd_security_driver);
404     bs->socket = stream_server(SU_GET_FAMILY(&bh->udp->peer), &bs->port,
405                                (size_t)STREAM_BUFSIZE, (size_t)STREAM_BUFSIZE,
406                                0);
407     if (bs->socket < 0) {
408         security_seterror(&bh->sech,
409             _("can't create server stream: %s"), strerror(errno));
410         amfree(bs);
411         return (NULL);
412     }
413     bs->fd = -1;
414     bs->ev_read = NULL;
415     return (bs);
416 }
417
418 /*
419  * Accepts a new connection on unconnected streams.  Assumes it is ok to
420  * block on accept()
421  */
422 static int
423 bsd_stream_accept(
424     void *      s)
425 {
426     struct sec_stream *bs = s;
427
428     assert(bs != NULL);
429     assert(bs->socket != -1);
430     assert(bs->fd < 0);
431
432     bs->fd = stream_accept(bs->socket, 30, STREAM_BUFSIZE, STREAM_BUFSIZE);
433     if (bs->fd < 0) {
434         security_stream_seterror(&bs->secstr,
435             _("can't accept new stream connection: %s"), strerror(errno));
436         return (-1);
437     }
438     return (0);
439 }
440
441 /*
442  * Return a connected stream
443  */
444 static void *
445 bsd_stream_client(
446     void *      h,
447     int         id)
448 {
449     struct sec_stream *bs = NULL;
450     struct sec_handle *bh = h;
451 #ifdef DUMPER_SOCKET_BUFFERING
452     int rcvbuf = SIZEOF(bs->databuf) * 2;
453 #endif
454
455     assert(bh != NULL);
456
457     bs = g_new0(struct sec_stream, 1);
458     security_streaminit(&bs->secstr, &bsd_security_driver);
459     bs->fd = stream_client(bh->hostname, (in_port_t)id,
460         STREAM_BUFSIZE, STREAM_BUFSIZE, &bs->port, 0);
461     if (bs->fd < 0) {
462         security_seterror(&bh->sech,
463             _("can't connect stream to %s port %d: %s"), bh->hostname,
464             id, strerror(errno));
465         amfree(bs);
466         return (NULL);
467     }
468     bs->socket = -1;    /* we're a client */
469     bs->ev_read = NULL;
470 #ifdef DUMPER_SOCKET_BUFFERING
471     setsockopt(bs->fd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf, SIZEOF(rcvbuf));
472 #endif
473     return (bs);
474 }
475
476 /*
477  * Close and unallocate resources for a stream
478  */
479 static void
480 bsd_stream_close(
481     void *      s)
482 {
483     struct sec_stream *bs = s;
484
485     assert(bs != NULL);
486
487     if (bs->fd != -1)
488         aclose(bs->fd);
489     if (bs->socket != -1)
490         aclose(bs->socket);
491     bsd_stream_read_cancel(bs);
492     amfree(bs);
493 }
494
495 /*
496  * Authenticate a stream.  bsd streams have no authentication
497  */
498 static int
499 bsd_stream_auth(
500     void *      s)
501 {
502     (void)s;            /* Quiet unused parameter warning */
503
504     return (0); /* success */
505 }
506
507 /*
508  * Returns the stream id for this stream.  This is just the local port.
509  */
510 static int
511 bsd_stream_id(
512     void *      s)
513 {
514     struct sec_stream *bs = s;
515
516     assert(bs != NULL);
517
518     return ((int)bs->port);
519 }
520
521 /*
522  * Submit a request to read some data.  Calls back with the given function
523  * and arg when completed.
524  */
525 static void
526 bsd_stream_read(
527     void *      s,
528     void        (*fn)(void *, void *, ssize_t),
529     void *      arg)
530 {
531     struct sec_stream *bs = s;
532
533     /*
534      * Only one read request can be active per stream.
535      */
536     if (bs->ev_read != NULL)
537         event_release(bs->ev_read);
538
539     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD, stream_read_callback, bs);
540     bs->fn = fn;
541     bs->arg = arg;
542 }
543
544 /* buffer for bsd_stream_read_sync function */
545 static ssize_t  sync_pktlen;
546 static void    *sync_pkt;
547
548 /*
549  * Read a chunk of data to a stream.  Blocks until completion.
550  */
551 static ssize_t
552 bsd_stream_read_sync(
553     void *      s,
554     void **     buf)
555 {
556     struct sec_stream *bs = s;
557
558     assert(bs != NULL);
559
560     /*
561      * Only one read request can be active per stream.
562      */
563     if(bs->ev_read != NULL) {
564         return -1;
565     }
566     sync_pktlen = 0;
567     sync_pkt = NULL;
568     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD,
569                         stream_read_sync_callback, bs);
570     event_wait(bs->ev_read);
571     *buf = sync_pkt;
572     return (sync_pktlen);
573 }
574
575
576 /*
577  * Callback for bsd_stream_read_sync
578  */
579 static void
580 stream_read_sync_callback(
581     void *      s)
582 {
583     struct sec_stream *bs = s;
584     ssize_t n;
585
586     assert(bs != NULL);
587
588     auth_debug(1, _("bsd: stream_read_callback_sync: fd %d\n"), bs->fd);
589
590     /*
591      * Remove the event first, in case they reschedule it in the callback.
592      */
593     bsd_stream_read_cancel(bs);
594     do {
595         n = read(bs->fd, bs->databuf, sizeof(bs->databuf));
596     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
597     if (n < 0)
598         security_stream_seterror(&bs->secstr, "%s", strerror(errno));
599     bs->len = n;
600     sync_pktlen = bs->len;
601     sync_pkt = malloc(sync_pktlen);
602     memcpy(sync_pkt, bs->databuf, sync_pktlen);
603 }
604
605 /*
606  * Cancel a previous stream read request.  It's ok if we didn't
607  * have a read scheduled.
608  */
609 static void
610 bsd_stream_read_cancel(
611     void *      s)
612 {
613     struct sec_stream *bs = s;
614
615     assert(bs != NULL);
616     if (bs->ev_read != NULL) {
617         event_release(bs->ev_read);
618         bs->ev_read = NULL;
619     }
620 }
621
622 /*
623  * Callback for bsd_stream_read
624  */
625 static void
626 stream_read_callback(
627     void *      arg)
628 {
629     struct sec_stream *bs = arg;
630     ssize_t n;
631
632     assert(bs != NULL);
633
634     /*
635      * Remove the event first, in case they reschedule it in the callback.
636      */
637     bsd_stream_read_cancel(bs);
638     do {
639         n = read(bs->fd, bs->databuf, SIZEOF(bs->databuf));
640     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
641
642     if (n < 0)
643         security_stream_seterror(&bs->secstr, "%s", strerror(errno));
644
645     (*bs->fn)(bs->arg, bs->databuf, n);
646 }