Imported Upstream version 3.3.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     struct stat sbuf;
321
322     assert(in >= 0 && out >= 0);
323     assert(fn != NULL);
324
325     (void)out;  /* Quiet unused parameter warning */
326     (void)driver; /* Quiet unused parameter warning */
327     (void)conf_fn;
328     (void)datap;
329
330     /*
331      * We assume in and out point to the same socket, and just use
332      * in.
333      */
334     dgram_socket(&netfd4.dgram, in);
335     dgram_socket(&netfd6.dgram, in);
336
337     /*
338      * Assign the function and return.  When they call recvpkt later,
339      * the recvpkt callback will call this function when it discovers
340      * new incoming connections
341      */
342     netfd4.accept_fn = fn;
343     netfd4.recv_security_ok = &bsd_recv_security_ok;
344     netfd4.prefix_packet = &bsd_prefix_packet;
345     netfd4.driver = &bsd_security_driver;
346
347     /* check if in is a socket */
348     fstat(in, &sbuf);
349     if (S_ISSOCK(sbuf.st_mode)) {
350         udp_addref(&netfd4, &udp_netfd_read_callback);
351     } else {
352         g_warning("input file descriptor is not a socket; cannot use BSD auth");
353     }
354 }
355
356 /*
357  * Frees a handle allocated by the above
358  */
359 static void
360 bsd_close(
361     void *      cookie)
362 {
363     struct sec_handle *bh = cookie;
364
365     if(bh->proto_handle == NULL) {
366         return;
367     }
368
369     auth_debug(1, _("bsd: close handle '%s'\n"), bh->proto_handle);
370
371     udp_recvpkt_cancel(bh);
372     if(bh->next) {
373         bh->next->prev = bh->prev;
374     }
375     else {
376         if (!not_init6 && netfd6.bh_last == bh)
377             netfd6.bh_last = bh->prev;
378         else
379             netfd4.bh_last = bh->prev;
380     }
381     if(bh->prev) {
382         bh->prev->next = bh->next;
383     }
384     else {
385         if (!not_init6 && netfd6.bh_first == bh)
386             netfd6.bh_first = bh->next;
387         else
388             netfd4.bh_first = bh->next;
389     }
390
391     amfree(bh->proto_handle);
392     amfree(bh->hostname);
393     amfree(bh);
394 }
395
396 /*
397  * Create the server end of a stream.  For bsd, this means setup a tcp
398  * socket for receiving a connection.
399  */
400 static void *
401 bsd_stream_server(
402     void *      h)
403 {
404     struct sec_stream *bs = NULL;
405     struct sec_handle *bh = h;
406
407     assert(bh != NULL);
408
409     bs = g_new0(struct sec_stream, 1);
410     security_streaminit(&bs->secstr, &bsd_security_driver);
411     bs->socket = stream_server(SU_GET_FAMILY(&bh->udp->peer), &bs->port,
412                                (size_t)STREAM_BUFSIZE, (size_t)STREAM_BUFSIZE,
413                                0);
414     if (bs->socket < 0) {
415         security_seterror(&bh->sech,
416             _("can't create server stream: %s"), strerror(errno));
417         amfree(bs);
418         return (NULL);
419     }
420     bs->fd = -1;
421     bs->ev_read = NULL;
422     return (bs);
423 }
424
425 /*
426  * Accepts a new connection on unconnected streams.  Assumes it is ok to
427  * block on accept()
428  */
429 static int
430 bsd_stream_accept(
431     void *      s)
432 {
433     struct sec_stream *bs = s;
434
435     assert(bs != NULL);
436     assert(bs->socket != -1);
437     assert(bs->fd < 0);
438
439     bs->fd = stream_accept(bs->socket, 30, STREAM_BUFSIZE, STREAM_BUFSIZE);
440     if (bs->fd < 0) {
441         security_stream_seterror(&bs->secstr,
442             _("can't accept new stream connection: %s"), strerror(errno));
443         return (-1);
444     }
445     return (0);
446 }
447
448 /*
449  * Return a connected stream
450  */
451 static void *
452 bsd_stream_client(
453     void *      h,
454     int         id)
455 {
456     struct sec_stream *bs = NULL;
457     struct sec_handle *bh = h;
458 #ifdef DUMPER_SOCKET_BUFFERING
459     int rcvbuf = SIZEOF(bs->databuf) * 2;
460 #endif
461
462     assert(bh != NULL);
463
464     bs = g_new0(struct sec_stream, 1);
465     security_streaminit(&bs->secstr, &bsd_security_driver);
466     bs->fd = stream_client(bh->hostname, (in_port_t)id,
467         STREAM_BUFSIZE, STREAM_BUFSIZE, &bs->port, 0);
468     if (bs->fd < 0) {
469         security_seterror(&bh->sech,
470             _("can't connect stream to %s port %d: %s"), bh->hostname,
471             id, strerror(errno));
472         amfree(bs);
473         return (NULL);
474     }
475     bs->socket = -1;    /* we're a client */
476     bs->ev_read = NULL;
477 #ifdef DUMPER_SOCKET_BUFFERING
478     setsockopt(bs->fd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf, SIZEOF(rcvbuf));
479 #endif
480     return (bs);
481 }
482
483 /*
484  * Close and unallocate resources for a stream
485  */
486 static void
487 bsd_stream_close(
488     void *      s)
489 {
490     struct sec_stream *bs = s;
491
492     assert(bs != NULL);
493
494     if (bs->fd != -1)
495         aclose(bs->fd);
496     if (bs->socket != -1)
497         aclose(bs->socket);
498     bsd_stream_read_cancel(bs);
499     amfree(bs);
500 }
501
502 /*
503  * Authenticate a stream.  bsd streams have no authentication
504  */
505 static int
506 bsd_stream_auth(
507     void *      s)
508 {
509     (void)s;            /* Quiet unused parameter warning */
510
511     return (0); /* success */
512 }
513
514 /*
515  * Returns the stream id for this stream.  This is just the local port.
516  */
517 static int
518 bsd_stream_id(
519     void *      s)
520 {
521     struct sec_stream *bs = s;
522
523     assert(bs != NULL);
524
525     return ((int)bs->port);
526 }
527
528 /*
529  * Submit a request to read some data.  Calls back with the given function
530  * and arg when completed.
531  */
532 static void
533 bsd_stream_read(
534     void *      s,
535     void        (*fn)(void *, void *, ssize_t),
536     void *      arg)
537 {
538     struct sec_stream *bs = s;
539
540     /*
541      * Only one read request can be active per stream.
542      */
543     if (bs->ev_read != NULL)
544         event_release(bs->ev_read);
545
546     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD, stream_read_callback, bs);
547     bs->fn = fn;
548     bs->arg = arg;
549 }
550
551 /* buffer for bsd_stream_read_sync function */
552 static ssize_t  sync_pktlen;
553 static void    *sync_pkt;
554
555 /*
556  * Read a chunk of data to a stream.  Blocks until completion.
557  */
558 static ssize_t
559 bsd_stream_read_sync(
560     void *      s,
561     void **     buf)
562 {
563     struct sec_stream *bs = s;
564
565     assert(bs != NULL);
566
567     /*
568      * Only one read request can be active per stream.
569      */
570     if(bs->ev_read != NULL) {
571         return -1;
572     }
573     sync_pktlen = 0;
574     sync_pkt = NULL;
575     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD,
576                         stream_read_sync_callback, bs);
577     event_wait(bs->ev_read);
578     *buf = sync_pkt;
579     return (sync_pktlen);
580 }
581
582
583 /*
584  * Callback for bsd_stream_read_sync
585  */
586 static void
587 stream_read_sync_callback(
588     void *      s)
589 {
590     struct sec_stream *bs = s;
591     ssize_t n;
592
593     assert(bs != NULL);
594
595     auth_debug(1, _("bsd: stream_read_callback_sync: fd %d\n"), bs->fd);
596
597     /*
598      * Remove the event first, in case they reschedule it in the callback.
599      */
600     bsd_stream_read_cancel(bs);
601     do {
602         n = read(bs->fd, bs->databuf, sizeof(bs->databuf));
603     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
604     if (n < 0)
605         security_stream_seterror(&bs->secstr, "%s", strerror(errno));
606     bs->len = n;
607     sync_pktlen = bs->len;
608     sync_pkt = malloc(sync_pktlen);
609     memcpy(sync_pkt, bs->databuf, sync_pktlen);
610 }
611
612 /*
613  * Cancel a previous stream read request.  It's ok if we didn't
614  * have a read scheduled.
615  */
616 static void
617 bsd_stream_read_cancel(
618     void *      s)
619 {
620     struct sec_stream *bs = s;
621
622     assert(bs != NULL);
623     if (bs->ev_read != NULL) {
624         event_release(bs->ev_read);
625         bs->ev_read = NULL;
626     }
627 }
628
629 /*
630  * Callback for bsd_stream_read
631  */
632 static void
633 stream_read_callback(
634     void *      arg)
635 {
636     struct sec_stream *bs = arg;
637     ssize_t n;
638
639     assert(bs != NULL);
640
641     /*
642      * Remove the event first, in case they reschedule it in the callback.
643      */
644     bsd_stream_read_cancel(bs);
645     do {
646         n = read(bs->fd, bs->databuf, SIZEOF(bs->databuf));
647     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
648
649     if (n < 0)
650         security_stream_seterror(&bs->secstr, "%s", strerror(errno));
651
652     (*bs->fn)(bs->arg, bs->databuf, n);
653 }