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