4be79482bb6bc036871bcc539bab6b8c6d133dd2
[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        return;
160     }
161     if (res == NULL) {
162         dbprintf(_("resolve_hostname(%s): no results\n"), hostname);
163         security_seterror(&bh->sech,
164                 _("resolve_hostname(%s): no results\n"), hostname);
165         (*fn)(arg, &bh->sech, S_ERROR);
166        amfree(canonname);
167        return;
168     }
169
170     for (res_addr = res; res_addr != NULL; res_addr = res_addr->ai_next) {
171 #ifdef WORKING_IPV6
172         /* IPv6 socket already bound */
173         if (res_addr->ai_addr->sa_family == AF_INET6 && not_init6 == 0) {
174             break;
175         }
176         /*
177          * Only init the IPv6 socket once
178          */
179         if (res_addr->ai_addr->sa_family == AF_INET6 && not_init6 == 1) {
180             uid_t euid;
181             dgram_zero(&netfd6.dgram);
182
183             euid = geteuid();
184             set_root_privs(1);
185             result_bind = dgram_bind(&netfd6.dgram,
186                                      res_addr->ai_addr->sa_family, &port);
187             set_root_privs(0);
188             if (result_bind != 0) {
189                 continue;
190             }
191             netfd6.handle = NULL;
192             netfd6.pkt.body = NULL;
193             netfd6.recv_security_ok = &bsd_recv_security_ok;
194             netfd6.prefix_packet = &bsd_prefix_packet;
195             /*
196              * We must have a reserved port.  Bomb if we didn't get one.
197              */
198             if (port >= IPPORT_RESERVED) {
199                 security_seterror(&bh->sech,
200                     _("unable to bind to a reserved port (got port %u)"),
201                     (unsigned int)port);
202                 (*fn)(arg, &bh->sech, S_ERROR);
203                 freeaddrinfo(res);
204                 amfree(canonname);
205                 return;
206             }
207             not_init6 = 0;
208             bh->udp = &netfd6;
209             break;
210         }
211 #endif
212
213         /* IPv4 socket already bound */
214         if (res_addr->ai_addr->sa_family == AF_INET && not_init4 == 0) {
215             break;
216         }
217
218         /*
219          * Only init the IPv4 socket once
220          */
221         if (res_addr->ai_addr->sa_family == AF_INET && not_init4 == 1) {
222             uid_t euid;
223             dgram_zero(&netfd4.dgram);
224
225             euid = geteuid();
226             set_root_privs(1);
227             result_bind = dgram_bind(&netfd4.dgram,
228                                      res_addr->ai_addr->sa_family, &port);
229             set_root_privs(0);
230             if (result_bind != 0) {
231                 continue;
232             }
233             netfd4.handle = NULL;
234             netfd4.pkt.body = NULL;
235             netfd4.recv_security_ok = &bsd_recv_security_ok;
236             netfd4.prefix_packet = &bsd_prefix_packet;
237             /*
238              * We must have a reserved port.  Bomb if we didn't get one.
239              */
240             if (port >= IPPORT_RESERVED) {
241                 security_seterror(&bh->sech,
242                     "unable to bind to a reserved port (got port %u)",
243                     (unsigned int)port);
244                 (*fn)(arg, &bh->sech, S_ERROR);
245                 freeaddrinfo(res);
246                 amfree(canonname);
247                 return;
248             }
249             not_init4 = 0;
250             bh->udp = &netfd4;
251             break;
252         }
253     }
254
255     if (res_addr == NULL) {
256         dbprintf(_("Can't bind a socket to connect to %s\n"), hostname);
257         security_seterror(&bh->sech,
258                 _("Can't bind a socket to connect to %s\n"), hostname);
259         (*fn)(arg, &bh->sech, S_ERROR);
260        amfree(canonname);
261        return;
262     }
263
264 #ifdef WORKING_IPV6
265     if (res_addr->ai_addr->sa_family == AF_INET6)
266         bh->udp = &netfd6;
267     else
268 #endif
269         bh->udp = &netfd4;
270
271     auth_debug(1, _("Resolved hostname=%s\n"), canonname);
272     if ((se = getservbyname(AMANDA_SERVICE_NAME, "udp")) == NULL)
273         port = AMANDA_SERVICE_DEFAULT;
274     else
275         port = (in_port_t)ntohs(se->s_port);
276     amanda_gettimeofday(&sequence_time);
277     sequence = (int)sequence_time.tv_sec ^ (int)sequence_time.tv_usec;
278     handle=alloc(15);
279     g_snprintf(handle, 14, "000-%08x",  (unsigned)newhandle++);
280     if (udp_inithandle(bh->udp, bh, canonname,
281         (sockaddr_union *)res_addr->ai_addr, port, handle, sequence) < 0) {
282         (*fn)(arg, &bh->sech, S_ERROR);
283         amfree(bh->hostname);
284         amfree(bh);
285     }
286     else {
287         (*fn)(arg, &bh->sech, S_OK);
288     }
289     amfree(handle);
290     amfree(canonname);
291
292     freeaddrinfo(res);
293 }
294
295 /*
296  * Setup to accept new incoming connections
297  */
298 static void
299 bsd_accept(
300     const struct security_driver *      driver,
301     char       *(*conf_fn)(char *, void *),
302     int         in,
303     int         out,
304     void        (*fn)(security_handle_t *, pkt_t *),
305     void       *datap)
306 {
307
308     assert(in >= 0 && out >= 0);
309     assert(fn != NULL);
310
311     (void)out;  /* Quiet unused parameter warning */
312     (void)driver; /* Quiet unused parameter warning */
313     (void)conf_fn;
314     (void)datap;
315
316     /*
317      * We assume in and out point to the same socket, and just use
318      * in.
319      */
320     dgram_socket(&netfd4.dgram, in);
321     dgram_socket(&netfd6.dgram, in);
322
323     /*
324      * Assign the function and return.  When they call recvpkt later,
325      * the recvpkt callback will call this function when it discovers
326      * new incoming connections
327      */
328     netfd4.accept_fn = fn;
329     netfd4.recv_security_ok = &bsd_recv_security_ok;
330     netfd4.prefix_packet = &bsd_prefix_packet;
331     netfd4.driver = &bsd_security_driver;
332
333     udp_addref(&netfd4, &udp_netfd_read_callback);
334 }
335
336 /*
337  * Frees a handle allocated by the above
338  */
339 static void
340 bsd_close(
341     void *      cookie)
342 {
343     struct sec_handle *bh = cookie;
344
345     if(bh->proto_handle == NULL) {
346         return;
347     }
348
349     auth_debug(1, _("bsd: close handle '%s'\n"), bh->proto_handle);
350
351     udp_recvpkt_cancel(bh);
352     if(bh->next) {
353         bh->next->prev = bh->prev;
354     }
355     else {
356         if (!not_init6 && netfd6.bh_last == bh)
357             netfd6.bh_last = bh->prev;
358         else
359             netfd4.bh_last = bh->prev;
360     }
361     if(bh->prev) {
362         bh->prev->next = bh->next;
363     }
364     else {
365         if (!not_init6 && netfd6.bh_first == bh)
366             netfd6.bh_first = bh->next;
367         else
368             netfd4.bh_first = bh->next;
369     }
370
371     amfree(bh->proto_handle);
372     amfree(bh->hostname);
373     amfree(bh);
374 }
375
376 /*
377  * Create the server end of a stream.  For bsd, this means setup a tcp
378  * socket for receiving a connection.
379  */
380 static void *
381 bsd_stream_server(
382     void *      h)
383 {
384     struct sec_stream *bs = NULL;
385     struct sec_handle *bh = h;
386
387     assert(bh != NULL);
388
389     bs = alloc(SIZEOF(*bs));
390     security_streaminit(&bs->secstr, &bsd_security_driver);
391     bs->socket = stream_server(SU_GET_FAMILY(&bh->udp->peer), &bs->port,
392                                (size_t)STREAM_BUFSIZE, (size_t)STREAM_BUFSIZE,
393                                0);
394     if (bs->socket < 0) {
395         security_seterror(&bh->sech,
396             _("can't create server stream: %s"), strerror(errno));
397         amfree(bs);
398         return (NULL);
399     }
400     bs->fd = -1;
401     bs->ev_read = NULL;
402     return (bs);
403 }
404
405 /*
406  * Accepts a new connection on unconnected streams.  Assumes it is ok to
407  * block on accept()
408  */
409 static int
410 bsd_stream_accept(
411     void *      s)
412 {
413     struct sec_stream *bs = s;
414
415     assert(bs != NULL);
416     assert(bs->socket != -1);
417     assert(bs->fd < 0);
418
419     bs->fd = stream_accept(bs->socket, 30, STREAM_BUFSIZE, STREAM_BUFSIZE);
420     if (bs->fd < 0) {
421         security_stream_seterror(&bs->secstr,
422             _("can't accept new stream connection: %s"), strerror(errno));
423         return (-1);
424     }
425     return (0);
426 }
427
428 /*
429  * Return a connected stream
430  */
431 static void *
432 bsd_stream_client(
433     void *      h,
434     int         id)
435 {
436     struct sec_stream *bs = NULL;
437     struct sec_handle *bh = h;
438 #ifdef DUMPER_SOCKET_BUFFERING
439     int rcvbuf = SIZEOF(bs->databuf) * 2;
440 #endif
441
442     assert(bh != NULL);
443
444     bs = alloc(SIZEOF(*bs));
445     security_streaminit(&bs->secstr, &bsd_security_driver);
446     bs->fd = stream_client(bh->hostname, (in_port_t)id,
447         STREAM_BUFSIZE, STREAM_BUFSIZE, &bs->port, 0);
448     if (bs->fd < 0) {
449         security_seterror(&bh->sech,
450             _("can't connect stream to %s port %d: %s"), bh->hostname,
451             id, strerror(errno));
452         amfree(bs);
453         return (NULL);
454     }
455     bs->socket = -1;    /* we're a client */
456     bs->ev_read = NULL;
457 #ifdef DUMPER_SOCKET_BUFFERING
458     setsockopt(bs->fd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf, SIZEOF(rcvbuf));
459 #endif
460     return (bs);
461 }
462
463 /*
464  * Close and unallocate resources for a stream
465  */
466 static void
467 bsd_stream_close(
468     void *      s)
469 {
470     struct sec_stream *bs = s;
471
472     assert(bs != NULL);
473
474     if (bs->fd != -1)
475         aclose(bs->fd);
476     if (bs->socket != -1)
477         aclose(bs->socket);
478     bsd_stream_read_cancel(bs);
479     amfree(bs);
480 }
481
482 /*
483  * Authenticate a stream.  bsd streams have no authentication
484  */
485 static int
486 bsd_stream_auth(
487     void *      s)
488 {
489     (void)s;            /* Quiet unused parameter warning */
490
491     return (0); /* success */
492 }
493
494 /*
495  * Returns the stream id for this stream.  This is just the local port.
496  */
497 static int
498 bsd_stream_id(
499     void *      s)
500 {
501     struct sec_stream *bs = s;
502
503     assert(bs != NULL);
504
505     return ((int)bs->port);
506 }
507
508 /*
509  * Submit a request to read some data.  Calls back with the given function
510  * and arg when completed.
511  */
512 static void
513 bsd_stream_read(
514     void *      s,
515     void        (*fn)(void *, void *, ssize_t),
516     void *      arg)
517 {
518     struct sec_stream *bs = s;
519
520     /*
521      * Only one read request can be active per stream.
522      */
523     if (bs->ev_read != NULL)
524         event_release(bs->ev_read);
525
526     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD, stream_read_callback, bs);
527     bs->fn = fn;
528     bs->arg = arg;
529 }
530
531 /*
532  * Read a chunk of data to a stream.  Blocks until completion.
533  */
534 static ssize_t
535 bsd_stream_read_sync(
536     void *      s,
537     void **     buf)
538 {
539     struct sec_stream *bs = s;
540
541     assert(bs != NULL);
542
543     /*
544      * Only one read request can be active per stream.
545      */
546     if(bs->ev_read != NULL) {
547         return -1;
548     }
549     bs->ev_read = event_register((event_id_t)bs->fd, EV_READFD,
550                         stream_read_sync_callback, bs);
551     event_wait(bs->ev_read);
552     *buf = bs->databuf;
553     return (bs->len);
554 }
555
556
557 /*
558  * Callback for bsd_stream_read_sync
559  */
560 static void
561 stream_read_sync_callback(
562     void *      s)
563 {
564     struct sec_stream *bs = s;
565     ssize_t n;
566
567     assert(bs != NULL);
568
569     auth_debug(1, _("bsd: stream_read_callback_sync: fd %d\n"), bs->fd);
570
571     /*
572      * Remove the event first, in case they reschedule it in the callback.
573      */
574     bsd_stream_read_cancel(bs);
575     do {
576         n = read(bs->fd, bs->databuf, sizeof(bs->databuf));
577     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
578     if (n < 0)
579         security_stream_seterror(&bs->secstr, strerror(errno));
580     bs->len = n;
581 }
582
583 /*
584  * Cancel a previous stream read request.  It's ok if we didn't
585  * have a read scheduled.
586  */
587 static void
588 bsd_stream_read_cancel(
589     void *      s)
590 {
591     struct sec_stream *bs = s;
592
593     assert(bs != NULL);
594     if (bs->ev_read != NULL) {
595         event_release(bs->ev_read);
596         bs->ev_read = NULL;
597     }
598 }
599
600 /*
601  * Callback for bsd_stream_read
602  */
603 static void
604 stream_read_callback(
605     void *      arg)
606 {
607     struct sec_stream *bs = arg;
608     ssize_t n;
609
610     assert(bs != NULL);
611
612     /*
613      * Remove the event first, in case they reschedule it in the callback.
614      */
615     bsd_stream_read_cancel(bs);
616     do {
617         n = read(bs->fd, bs->databuf, SIZEOF(bs->databuf));
618     } while ((n < 0) && ((errno == EINTR) || (errno == EAGAIN)));
619
620     if (n < 0)
621         security_stream_seterror(&bs->secstr, strerror(errno));
622
623     (*bs->fn)(bs->arg, bs->databuf, n);
624 }