46bdca9ad7ded214a3ed97ebccb6bfa9bab9e15c
[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 #include "version.h"
43
44 #ifndef SO_RCVBUF
45 #undef DUMPER_SOCKET_BUFFERING
46 #endif
47
48 /*
49  * Interface functions
50  */
51 static void     bsd_connect(const char *, char *(*)(char *, void *), 
52                         void (*)(void *, security_handle_t *, security_status_t),
53                         void *, void *);
54 static void     bsd_accept(const struct security_driver *,
55                         char *(*)(char *, void *),
56                         int, int,
57                         void (*)(security_handle_t *, pkt_t *),
58                         void *);
59 static void     bsd_close(void *);
60 static void *   bsd_stream_server(void *);
61 static int      bsd_stream_accept(void *);
62 static void *   bsd_stream_client(void *, int);
63 static void     bsd_stream_close(void *);
64 static int      bsd_stream_auth(void *);
65 static int      bsd_stream_id(void *);
66 static void     bsd_stream_read(void *, void (*)(void *, void *, ssize_t), void *);
67 static ssize_t  bsd_stream_read_sync(void *, void **);
68 static void     bsd_stream_read_cancel(void *);
69
70 /*
71  * This is our interface to the outside world
72  */
73 const security_driver_t bsd_security_driver = {
74     "BSD",
75     bsd_connect,
76     bsd_accept,
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     struct servent *se;
128     in_port_t port = 0;
129     struct timeval sequence_time;
130     int sequence;
131     char *handle;
132     int result;
133     struct addrinfo *res, *res_addr;
134     char *canonname;
135     int result_bind;
136
137     assert(hostname != NULL);
138
139     (void)conf_fn;      /* Quiet unused parameter warning */
140     (void)datap;        /* Quiet unused parameter warning */
141
142     bh = alloc(SIZEOF(*bh));
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     if ((se = getservbyname(AMANDA_SERVICE_NAME, "udp")) == NULL)
274         port = AMANDA_SERVICE_DEFAULT;
275     else
276         port = (in_port_t)ntohs(se->s_port);
277     amanda_gettimeofday(&sequence_time);
278     sequence = (int)sequence_time.tv_sec ^ (int)sequence_time.tv_usec;
279     handle=alloc(15);
280     g_snprintf(handle, 14, "000-%08x",  (unsigned)newhandle++);
281     if (udp_inithandle(bh->udp, bh, canonname,
282         (sockaddr_union *)res_addr->ai_addr, port, handle, sequence) < 0) {
283         (*fn)(arg, &bh->sech, S_ERROR);
284         amfree(bh->hostname);
285         amfree(bh);
286     }
287     else {
288         (*fn)(arg, &bh->sech, S_OK);
289     }
290     amfree(handle);
291     amfree(canonname);
292
293     freeaddrinfo(res);
294 }
295
296 /*
297  * Setup to accept new incoming connections
298  */
299 static void
300 bsd_accept(
301     const struct security_driver *      driver,
302     char       *(*conf_fn)(char *, void *),
303     int         in,
304     int         out,
305     void        (*fn)(security_handle_t *, pkt_t *),
306     void       *datap)
307 {
308
309     assert(in >= 0 && out >= 0);
310     assert(fn != NULL);
311
312     (void)out;  /* Quiet unused parameter warning */
313     (void)driver; /* Quiet unused parameter warning */
314     (void)conf_fn;
315     (void)datap;
316
317     /*
318      * We assume in and out point to the same socket, and just use
319      * in.
320      */
321     dgram_socket(&netfd4.dgram, in);
322     dgram_socket(&netfd6.dgram, in);
323
324     /*
325      * Assign the function and return.  When they call recvpkt later,
326      * the recvpkt callback will call this function when it discovers
327      * new incoming connections
328      */
329     netfd4.accept_fn = fn;
330     netfd4.recv_security_ok = &bsd_recv_security_ok;
331     netfd4.prefix_packet = &bsd_prefix_packet;
332     netfd4.driver = &bsd_security_driver;
333
334     udp_addref(&netfd4, &udp_netfd_read_callback);
335 }
336
337 /*
338  * Frees a handle allocated by the above
339  */
340 static void
341 bsd_close(
342     void *      cookie)
343 {
344     struct sec_handle *bh = cookie;
345
346     if(bh->proto_handle == NULL) {
347         return;
348     }
349
350     auth_debug(1, _("bsd: close handle '%s'\n"), bh->proto_handle);
351
352     udp_recvpkt_cancel(bh);
353     if(bh->next) {
354         bh->next->prev = bh->prev;
355     }
356     else {
357         if (!not_init6 && netfd6.bh_last == bh)
358             netfd6.bh_last = bh->prev;
359         else
360             netfd4.bh_last = bh->prev;
361     }
362     if(bh->prev) {
363         bh->prev->next = bh->next;
364     }
365     else {
366         if (!not_init6 && netfd6.bh_first == bh)
367             netfd6.bh_first = bh->next;
368         else
369             netfd4.bh_first = bh->next;
370     }
371
372     amfree(bh->proto_handle);
373     amfree(bh->hostname);
374     amfree(bh);
375 }
376
377 /*
378  * Create the server end of a stream.  For bsd, this means setup a tcp
379  * socket for receiving a connection.
380  */
381 static void *
382 bsd_stream_server(
383     void *      h)
384 {
385     struct sec_stream *bs = NULL;
386     struct sec_handle *bh = h;
387
388     assert(bh != NULL);
389
390     bs = alloc(SIZEOF(*bs));
391     security_streaminit(&bs->secstr, &bsd_security_driver);
392     bs->socket = stream_server(SU_GET_FAMILY(&bh->udp->peer), &bs->port,
393                                (size_t)STREAM_BUFSIZE, (size_t)STREAM_BUFSIZE,
394                                0);
395     if (bs->socket < 0) {
396         security_seterror(&bh->sech,
397             _("can't create server stream: %s"), strerror(errno));
398         amfree(bs);
399         return (NULL);
400     }
401     bs->fd = -1;
402     bs->ev_read = NULL;
403     return (bs);
404 }
405
406 /*
407  * Accepts a new connection on unconnected streams.  Assumes it is ok to
408  * block on accept()
409  */
410 static int
411 bsd_stream_accept(
412     void *      s)
413 {
414     struct sec_stream *bs = s;
415
416     assert(bs != NULL);
417     assert(bs->socket != -1);
418     assert(bs->fd < 0);
419
420     bs->fd = stream_accept(bs->socket, 30, STREAM_BUFSIZE, STREAM_BUFSIZE);
421     if (bs->fd < 0) {
422         security_stream_seterror(&bs->secstr,
423             _("can't accept new stream connection: %s"), strerror(errno));
424         return (-1);
425     }
426     return (0);
427 }
428
429 /*
430  * Return a connected stream
431  */
432 static void *
433 bsd_stream_client(
434     void *      h,
435     int         id)
436 {
437     struct sec_stream *bs = NULL;
438     struct sec_handle *bh = h;
439 #ifdef DUMPER_SOCKET_BUFFERING
440     int rcvbuf = SIZEOF(bs->databuf) * 2;
441 #endif
442
443     assert(bh != NULL);
444
445     bs = alloc(SIZEOF(*bs));
446     security_streaminit(&bs->secstr, &bsd_security_driver);
447     bs->fd = stream_client(bh->hostname, (in_port_t)id,
448         STREAM_BUFSIZE, STREAM_BUFSIZE, &bs->port, 0);
449     if (bs->fd < 0) {
450         security_seterror(&bh->sech,
451             _("can't connect stream to %s port %d: %s"), bh->hostname,
452             id, strerror(errno));
453         amfree(bs);
454         return (NULL);
455     }
456     bs->socket = -1;    /* we're a client */
457     bs->ev_read = NULL;
458 #ifdef DUMPER_SOCKET_BUFFERING
459     setsockopt(bs->fd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf, SIZEOF(rcvbuf));
460 #endif
461     return (bs);
462 }
463
464 /*
465  * Close and unallocate resources for a stream
466  */
467 static void
468 bsd_stream_close(
469     void *      s)
470 {
471     struct sec_stream *bs = s;
472
473     assert(bs != NULL);
474
475     if (bs->fd != -1)
476         aclose(bs->fd);
477     if (bs->socket != -1)
478         aclose(bs->socket);
479     bsd_stream_read_cancel(bs);
480     amfree(bs);
481 }
482
483 /*
484  * Authenticate a stream.  bsd streams have no authentication
485  */
486 static int
487 bsd_stream_auth(
488     void *      s)
489 {
490     (void)s;            /* Quiet unused parameter warning */
491
492     return (0); /* success */
493 }
494
495 /*
496  * Returns the stream id for this stream.  This is just the local port.
497  */
498 static int
499 bsd_stream_id(
500     void *      s)
501 {
502     struct sec_stream *bs = s;
503
504     assert(bs != NULL);
505
506     return ((int)bs->port);
507 }
508
509 /*
510  * Submit a request to read some data.  Calls back with the given function
511  * and arg when completed.
512  */
513 static void
514 bsd_stream_read(
515     void *      s,
516     void        (*fn)(void *, void *, ssize_t),
517     void *      arg)
518 {
519     struct sec_stream *bs = s;
520
521     /*
522      * Only one read request can be active per stream.
523      */
524     if (bs->ev_read != NULL)
525         event_release(bs->ev_read);
526
527     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD, stream_read_callback, bs);
528     bs->fn = fn;
529     bs->arg = arg;
530 }
531
532 /*
533  * Read a chunk of data to a stream.  Blocks until completion.
534  */
535 static ssize_t
536 bsd_stream_read_sync(
537     void *      s,
538     void **     buf)
539 {
540     struct sec_stream *bs = s;
541
542     assert(bs != NULL);
543
544     /*
545      * Only one read request can be active per stream.
546      */
547     if(bs->ev_read != NULL) {
548         return -1;
549     }
550     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD,
551                         stream_read_sync_callback, bs);
552     event_wait(bs->ev_read);
553     *buf = bs->databuf;
554     return (bs->len);
555 }
556
557
558 /*
559  * Callback for bsd_stream_read_sync
560  */
561 static void
562 stream_read_sync_callback(
563     void *      s)
564 {
565     struct sec_stream *bs = s;
566     ssize_t n;
567
568     assert(bs != NULL);
569
570     auth_debug(1, _("bsd: stream_read_callback_sync: fd %d\n"), bs->fd);
571
572     /*
573      * Remove the event first, in case they reschedule it in the callback.
574      */
575     bsd_stream_read_cancel(bs);
576     do {
577         n = read(bs->fd, bs->databuf, sizeof(bs->databuf));
578     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
579     if (n < 0)
580         security_stream_seterror(&bs->secstr, "%s", strerror(errno));
581     bs->len = n;
582 }
583
584 /*
585  * Cancel a previous stream read request.  It's ok if we didn't
586  * have a read scheduled.
587  */
588 static void
589 bsd_stream_read_cancel(
590     void *      s)
591 {
592     struct sec_stream *bs = s;
593
594     assert(bs != NULL);
595     if (bs->ev_read != NULL) {
596         event_release(bs->ev_read);
597         bs->ev_read = NULL;
598     }
599 }
600
601 /*
602  * Callback for bsd_stream_read
603  */
604 static void
605 stream_read_callback(
606     void *      arg)
607 {
608     struct sec_stream *bs = arg;
609     ssize_t n;
610
611     assert(bs != NULL);
612
613     /*
614      * Remove the event first, in case they reschedule it in the callback.
615      */
616     bsd_stream_read_cancel(bs);
617     do {
618         n = read(bs->fd, bs->databuf, SIZEOF(bs->databuf));
619     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
620
621     if (n < 0)
622         security_stream_seterror(&bs->secstr, "%s", strerror(errno));
623
624     (*bs->fn)(bs->arg, bs->databuf, n);
625 }