xref: /netbsd-src/crypto/external/bsd/openssh/dist/misc.c (revision 1c7715dda22cf2bd169e2f84953c050393e8fe9c)
1 /*	$NetBSD: misc.c,v 1.37 2024/07/08 22:33:43 christos Exp $	*/
2 /* $OpenBSD: misc.c,v 1.196 2024/06/06 17:15:25 djm Exp $ */
3 
4 /*
5  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
6  * Copyright (c) 2005-2020 Damien Miller.  All rights reserved.
7  * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 
22 #include "includes.h"
23 __RCSID("$NetBSD: misc.c,v 1.37 2024/07/08 22:33:43 christos Exp $");
24 
25 #include <sys/types.h>
26 #include <sys/ioctl.h>
27 #include <sys/socket.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30 #include <sys/wait.h>
31 #include <sys/un.h>
32 
33 #include <net/if.h>
34 #include <net/if_tun.h>
35 #include <netinet/in.h>
36 #include <netinet/ip.h>
37 #include <netinet/tcp.h>
38 #include <arpa/inet.h>
39 
40 #include <ctype.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <netdb.h>
44 #include <paths.h>
45 #include <pwd.h>
46 #include <libgen.h>
47 #include <limits.h>
48 #include <nlist.h>
49 #include <poll.h>
50 #include <signal.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdint.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 
58 #include "xmalloc.h"
59 #include "misc.h"
60 #include "log.h"
61 #include "ssh.h"
62 #include "sshbuf.h"
63 #include "ssherr.h"
64 
65 /* remove newline at end of string */
66 char *
chop(char * s)67 chop(char *s)
68 {
69 	char *t = s;
70 	while (*t) {
71 		if (*t == '\n' || *t == '\r') {
72 			*t = '\0';
73 			return s;
74 		}
75 		t++;
76 	}
77 	return s;
78 
79 }
80 
81 /* remove whitespace from end of string */
82 void
rtrim(char * s)83 rtrim(char *s)
84 {
85 	size_t i;
86 
87 	if ((i = strlen(s)) == 0)
88 		return;
89 	for (i--; i > 0; i--) {
90 		if (isspace((unsigned char)s[i]))
91 			s[i] = '\0';
92 	}
93 }
94 
95 /* set/unset filedescriptor to non-blocking */
96 int
set_nonblock(int fd)97 set_nonblock(int fd)
98 {
99 	int val;
100 
101 	val = fcntl(fd, F_GETFL);
102 	if (val == -1) {
103 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
104 		return (-1);
105 	}
106 	if (val & O_NONBLOCK) {
107 		debug3("fd %d is O_NONBLOCK", fd);
108 		return (0);
109 	}
110 	debug2("fd %d setting O_NONBLOCK", fd);
111 	val |= O_NONBLOCK;
112 	if (fcntl(fd, F_SETFL, val) == -1) {
113 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
114 		    strerror(errno));
115 		return (-1);
116 	}
117 	return (0);
118 }
119 
120 int
unset_nonblock(int fd)121 unset_nonblock(int fd)
122 {
123 	int val;
124 
125 	val = fcntl(fd, F_GETFL);
126 	if (val == -1) {
127 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
128 		return (-1);
129 	}
130 	if (!(val & O_NONBLOCK)) {
131 		debug3("fd %d is not O_NONBLOCK", fd);
132 		return (0);
133 	}
134 	debug("fd %d clearing O_NONBLOCK", fd);
135 	val &= ~O_NONBLOCK;
136 	if (fcntl(fd, F_SETFL, val) == -1) {
137 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
138 		    fd, strerror(errno));
139 		return (-1);
140 	}
141 	return (0);
142 }
143 
144 const char *
ssh_gai_strerror(int gaierr)145 ssh_gai_strerror(int gaierr)
146 {
147 	if (gaierr == EAI_SYSTEM && errno != 0)
148 		return strerror(errno);
149 	return gai_strerror(gaierr);
150 }
151 
152 /* disable nagle on socket */
153 void
set_nodelay(int fd)154 set_nodelay(int fd)
155 {
156 	int opt;
157 	socklen_t optlen;
158 
159 	optlen = sizeof opt;
160 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
161 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
162 		return;
163 	}
164 	if (opt == 1) {
165 		debug2("fd %d is TCP_NODELAY", fd);
166 		return;
167 	}
168 	opt = 1;
169 	debug2("fd %d setting TCP_NODELAY", fd);
170 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
171 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
172 }
173 
174 /* Allow local port reuse in TIME_WAIT */
175 int
set_reuseaddr(int fd)176 set_reuseaddr(int fd)
177 {
178 	int on = 1;
179 
180 	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
181 		error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
182 		return -1;
183 	}
184 	return 0;
185 }
186 
187 /* Get/set routing domain */
188 char *
get_rdomain(int fd)189 get_rdomain(int fd)
190 {
191 #ifdef SO_RTABLE
192 	int rtable;
193 	char *ret;
194 	socklen_t len = sizeof(rtable);
195 
196 	if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
197 		error("Failed to get routing domain for fd %d: %s",
198 		    fd, strerror(errno));
199 		return NULL;
200 	}
201 	xasprintf(&ret, "%d", rtable);
202 	return ret;
203 #else
204 	return NULL;
205 #endif
206 }
207 
208 int
set_rdomain(int fd,const char * name)209 set_rdomain(int fd, const char *name)
210 {
211 #ifdef SO_RTABLE
212 	int rtable;
213 	const char *errstr;
214 
215 	if (name == NULL)
216 		return 0; /* default table */
217 
218 	rtable = (int)strtonum(name, 0, 255, &errstr);
219 	if (errstr != NULL) {
220 		/* Shouldn't happen */
221 		error("Invalid routing domain \"%s\": %s", name, errstr);
222 		return -1;
223 	}
224 	if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
225 	    &rtable, sizeof(rtable)) == -1) {
226 		error("Failed to set routing domain %d on fd %d: %s",
227 		    rtable, fd, strerror(errno));
228 		return -1;
229 	}
230 	return 0;
231 #else
232 	return -1;
233 #endif
234 }
235 
236 int
get_sock_af(int fd)237 get_sock_af(int fd)
238 {
239 	struct sockaddr_storage to;
240 	socklen_t tolen = sizeof(to);
241 
242 	memset(&to, 0, sizeof(to));
243 	if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
244 		return -1;
245 	return to.ss_family;
246 }
247 
248 void
set_sock_tos(int fd,int tos)249 set_sock_tos(int fd, int tos)
250 {
251 	int af;
252 
253 	switch ((af = get_sock_af(fd))) {
254 	case -1:
255 		/* assume not a socket */
256 		break;
257 	case AF_INET:
258 		debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
259 		if (setsockopt(fd, IPPROTO_IP, IP_TOS,
260 		    &tos, sizeof(tos)) == -1) {
261 			error("setsockopt socket %d IP_TOS %d: %s",
262 			    fd, tos, strerror(errno));
263 		}
264 		break;
265 	case AF_INET6:
266 		debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
267 		if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
268 		    &tos, sizeof(tos)) == -1) {
269 			error("setsockopt socket %d IPV6_TCLASS %d: %s",
270 			    fd, tos, strerror(errno));
271 		}
272 		break;
273 	default:
274 		debug2_f("unsupported socket family %d", af);
275 		break;
276 	}
277 }
278 
279 /*
280  * Wait up to *timeoutp milliseconds for events on fd. Updates
281  * *timeoutp with time remaining.
282  * Returns 0 if fd ready or -1 on timeout or error (see errno).
283  */
284 static int
waitfd(int fd,int * timeoutp,short events,volatile sig_atomic_t * stop)285 waitfd(int fd, int *timeoutp, short events, volatile sig_atomic_t *stop)
286 {
287 	struct pollfd pfd;
288 	struct timespec timeout;
289 	int oerrno, r;
290 	sigset_t nsigset, osigset;
291 
292 	if (timeoutp && *timeoutp == -1)
293 		timeoutp = NULL;
294 	pfd.fd = fd;
295 	pfd.events = events;
296 	ptimeout_init(&timeout);
297 	if (timeoutp != NULL)
298 		ptimeout_deadline_ms(&timeout, *timeoutp);
299 	if (stop != NULL)
300 		sigfillset(&nsigset);
301 	for (; timeoutp == NULL || *timeoutp >= 0;) {
302 		if (stop != NULL) {
303 			sigprocmask(SIG_BLOCK, &nsigset, &osigset);
304 			if (*stop) {
305 				sigprocmask(SIG_SETMASK, &osigset, NULL);
306 				errno = EINTR;
307 				return -1;
308 			}
309 		}
310 		r = ppoll(&pfd, 1, ptimeout_get_tsp(&timeout),
311 		    stop != NULL ? &osigset : NULL);
312 		oerrno = errno;
313 		if (stop != NULL)
314 			sigprocmask(SIG_SETMASK, &osigset, NULL);
315 		if (timeoutp)
316 			*timeoutp = ptimeout_get_ms(&timeout);
317 		errno = oerrno;
318 		if (r > 0)
319 			return 0;
320 		else if (r == -1 && errno != EAGAIN && errno != EINTR)
321 			return -1;
322 		else if (r == 0)
323 			break;
324 	}
325 	/* timeout */
326 	errno = ETIMEDOUT;
327 	return -1;
328 }
329 
330 /*
331  * Wait up to *timeoutp milliseconds for fd to be readable. Updates
332  * *timeoutp with time remaining.
333  * Returns 0 if fd ready or -1 on timeout or error (see errno).
334  */
335 int
waitrfd(int fd,int * timeoutp,volatile sig_atomic_t * stop)336 waitrfd(int fd, int *timeoutp, volatile sig_atomic_t *stop) {
337 	return waitfd(fd, timeoutp, POLLIN, stop);
338 }
339 
340 /*
341  * Attempt a non-blocking connect(2) to the specified address, waiting up to
342  * *timeoutp milliseconds for the connection to complete. If the timeout is
343  * <=0, then wait indefinitely.
344  *
345  * Returns 0 on success or -1 on failure.
346  */
347 int
timeout_connect(int sockfd,const struct sockaddr * serv_addr,socklen_t addrlen,int * timeoutp)348 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
349     socklen_t addrlen, int *timeoutp)
350 {
351 	int optval = 0;
352 	socklen_t optlen = sizeof(optval);
353 
354 	/* No timeout: just do a blocking connect() */
355 	if (timeoutp == NULL || *timeoutp <= 0)
356 		return connect(sockfd, serv_addr, addrlen);
357 
358 	set_nonblock(sockfd);
359 	for (;;) {
360 		if (connect(sockfd, serv_addr, addrlen) == 0) {
361 			/* Succeeded already? */
362 			unset_nonblock(sockfd);
363 			return 0;
364 		} else if (errno == EINTR)
365 			continue;
366 		else if (errno != EINPROGRESS)
367 			return -1;
368 		break;
369 	}
370 
371 	if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT, NULL) == -1)
372 		return -1;
373 
374 	/* Completed or failed */
375 	if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
376 		debug("getsockopt: %s", strerror(errno));
377 		return -1;
378 	}
379 	if (optval != 0) {
380 		errno = optval;
381 		return -1;
382 	}
383 	unset_nonblock(sockfd);
384 	return 0;
385 }
386 
387 /* Characters considered whitespace in strsep calls. */
388 #define WHITESPACE " \t\r\n"
389 #define QUOTE	"\""
390 
391 /* return next token in configuration line */
392 static char *
strdelim_internal(char ** s,int split_equals)393 strdelim_internal(char **s, int split_equals)
394 {
395 	char *old;
396 	int wspace = 0;
397 
398 	if (*s == NULL)
399 		return NULL;
400 
401 	old = *s;
402 
403 	*s = strpbrk(*s,
404 	    split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
405 	if (*s == NULL)
406 		return (old);
407 
408 	if (*s[0] == '\"') {
409 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
410 		/* Find matching quote */
411 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
412 			return (NULL);		/* no matching quote */
413 		} else {
414 			*s[0] = '\0';
415 			*s += strspn(*s + 1, WHITESPACE) + 1;
416 			return (old);
417 		}
418 	}
419 
420 	/* Allow only one '=' to be skipped */
421 	if (split_equals && *s[0] == '=')
422 		wspace = 1;
423 	*s[0] = '\0';
424 
425 	/* Skip any extra whitespace after first token */
426 	*s += strspn(*s + 1, WHITESPACE) + 1;
427 	if (split_equals && *s[0] == '=' && !wspace)
428 		*s += strspn(*s + 1, WHITESPACE) + 1;
429 
430 	return (old);
431 }
432 
433 /*
434  * Return next token in configuration line; splts on whitespace or a
435  * single '=' character.
436  */
437 char *
strdelim(char ** s)438 strdelim(char **s)
439 {
440 	return strdelim_internal(s, 1);
441 }
442 
443 /*
444  * Return next token in configuration line; splts on whitespace only.
445  */
446 char *
strdelimw(char ** s)447 strdelimw(char **s)
448 {
449 	return strdelim_internal(s, 0);
450 }
451 
452 struct passwd *
pwcopy(struct passwd * pw)453 pwcopy(struct passwd *pw)
454 {
455 	struct passwd *copy = xcalloc(1, sizeof(*copy));
456 
457 	copy->pw_name = xstrdup(pw->pw_name);
458 	copy->pw_passwd = xstrdup(pw->pw_passwd);
459 	copy->pw_gecos = xstrdup(pw->pw_gecos);
460 	copy->pw_uid = pw->pw_uid;
461 	copy->pw_gid = pw->pw_gid;
462 	copy->pw_expire = pw->pw_expire;
463 	copy->pw_change = pw->pw_change;
464 	copy->pw_class = xstrdup(pw->pw_class);
465 	copy->pw_dir = xstrdup(pw->pw_dir);
466 	copy->pw_shell = xstrdup(pw->pw_shell);
467 	return copy;
468 }
469 
470 /*
471  * Convert ASCII string to TCP/IP port number.
472  * Port must be >=0 and <=65535.
473  * Return -1 if invalid.
474  */
475 int
a2port(const char * s)476 a2port(const char *s)
477 {
478 	struct servent *se;
479 	long long port;
480 	const char *errstr;
481 
482 	port = strtonum(s, 0, 65535, &errstr);
483 	if (errstr == NULL)
484 		return (int)port;
485 	if ((se = getservbyname(s, "tcp")) != NULL)
486 		return ntohs(se->s_port);
487 	return -1;
488 }
489 
490 int
a2tun(const char * s,int * remote)491 a2tun(const char *s, int *remote)
492 {
493 	const char *errstr = NULL;
494 	char *sp, *ep;
495 	int tun;
496 
497 	if (remote != NULL) {
498 		*remote = SSH_TUNID_ANY;
499 		sp = xstrdup(s);
500 		if ((ep = strchr(sp, ':')) == NULL) {
501 			free(sp);
502 			return (a2tun(s, NULL));
503 		}
504 		ep[0] = '\0'; ep++;
505 		*remote = a2tun(ep, NULL);
506 		tun = a2tun(sp, NULL);
507 		free(sp);
508 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
509 	}
510 
511 	if (strcasecmp(s, "any") == 0)
512 		return (SSH_TUNID_ANY);
513 
514 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
515 	if (errstr != NULL)
516 		return (SSH_TUNID_ERR);
517 
518 	return (tun);
519 }
520 
521 #define SECONDS		1
522 #define MINUTES		(SECONDS * 60)
523 #define HOURS		(MINUTES * 60)
524 #define DAYS		(HOURS * 24)
525 #define WEEKS		(DAYS * 7)
526 
527 static char *
scandigits(char * s)528 scandigits(char *s)
529 {
530 	while (isdigit((unsigned char)*s))
531 		s++;
532 	return s;
533 }
534 
535 /*
536  * Convert a time string into seconds; format is
537  * a sequence of:
538  *      time[qualifier]
539  *
540  * Valid time qualifiers are:
541  *      <none>  seconds
542  *      s|S     seconds
543  *      m|M     minutes
544  *      h|H     hours
545  *      d|D     days
546  *      w|W     weeks
547  *
548  * Examples:
549  *      90m     90 minutes
550  *      1h30m   90 minutes
551  *      2d      2 days
552  *      1w      1 week
553  *
554  * Return -1 if time string is invalid.
555  */
556 int
convtime(const char * s)557 convtime(const char *s)
558 {
559 	int secs, total = 0, multiplier;
560 	char *p, *os, *np, c = 0;
561 	const char *errstr;
562 
563 	if (s == NULL || *s == '\0')
564 		return -1;
565 	p = os = strdup(s);	/* deal with const */
566 	if (os == NULL)
567 		return -1;
568 
569 	while (*p) {
570 		np = scandigits(p);
571 		if (np) {
572 			c = *np;
573 			*np = '\0';
574 		}
575 		secs = (int)strtonum(p, 0, INT_MAX, &errstr);
576 		if (errstr)
577 			goto fail;
578 		*np = c;
579 
580 		multiplier = 1;
581 		switch (c) {
582 		case '\0':
583 			np--;	/* back up */
584 			break;
585 		case 's':
586 		case 'S':
587 			break;
588 		case 'm':
589 		case 'M':
590 			multiplier = MINUTES;
591 			break;
592 		case 'h':
593 		case 'H':
594 			multiplier = HOURS;
595 			break;
596 		case 'd':
597 		case 'D':
598 			multiplier = DAYS;
599 			break;
600 		case 'w':
601 		case 'W':
602 			multiplier = WEEKS;
603 			break;
604 		default:
605 			goto fail;
606 		}
607 		if (secs > INT_MAX / multiplier)
608 			goto fail;
609 		secs *= multiplier;
610 		if  (total > INT_MAX - secs)
611 			goto fail;
612 		total += secs;
613 		if (total < 0)
614 			goto fail;
615 		p = ++np;
616 	}
617 	free(os);
618 	return total;
619 fail:
620 	free(os);
621 	return -1;
622 }
623 
624 #define TF_BUFS	8
625 #define TF_LEN	21
626 
627 const char *
fmt_timeframe(time_t t)628 fmt_timeframe(time_t t)
629 {
630 	char		*buf;
631 	static char	 tfbuf[TF_BUFS][TF_LEN];	/* ring buffer */
632 	static int	 idx = 0;
633 	unsigned int	 sec, min, hrs, day;
634 	unsigned long long	week;
635 
636 	buf = tfbuf[idx++];
637 	if (idx == TF_BUFS)
638 		idx = 0;
639 
640 	week = t;
641 
642 	sec = week % 60;
643 	week /= 60;
644 	min = week % 60;
645 	week /= 60;
646 	hrs = week % 24;
647 	week /= 24;
648 	day = week % 7;
649 	week /= 7;
650 
651 	if (week > 0)
652 		snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
653 	else if (day > 0)
654 		snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
655 	else
656 		snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
657 
658 	return (buf);
659 }
660 
661 /*
662  * Returns a standardized host+port identifier string.
663  * Caller must free returned string.
664  */
665 char *
put_host_port(const char * host,u_short port)666 put_host_port(const char *host, u_short port)
667 {
668 	char *hoststr;
669 
670 	if (port == 0 || port == SSH_DEFAULT_PORT)
671 		return(xstrdup(host));
672 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
673 		fatal("put_host_port: asprintf: %s", strerror(errno));
674 	debug3("put_host_port: %s", hoststr);
675 	return hoststr;
676 }
677 
678 /*
679  * Search for next delimiter between hostnames/addresses and ports.
680  * Argument may be modified (for termination).
681  * Returns *cp if parsing succeeds.
682  * *cp is set to the start of the next field, if one was found.
683  * The delimiter char, if present, is stored in delim.
684  * If this is the last field, *cp is set to NULL.
685  */
686 char *
hpdelim2(char ** cp,char * delim)687 hpdelim2(char **cp, char *delim)
688 {
689 	char *s, *old;
690 
691 	if (cp == NULL || *cp == NULL)
692 		return NULL;
693 
694 	old = s = *cp;
695 	if (*s == '[') {
696 		if ((s = strchr(s, ']')) == NULL)
697 			return NULL;
698 		else
699 			s++;
700 	} else if ((s = strpbrk(s, ":/")) == NULL)
701 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
702 
703 	switch (*s) {
704 	case '\0':
705 		*cp = NULL;	/* no more fields*/
706 		break;
707 
708 	case ':':
709 	case '/':
710 		if (delim != NULL)
711 			*delim = *s;
712 		*s = '\0';	/* terminate */
713 		*cp = s + 1;
714 		break;
715 
716 	default:
717 		return NULL;
718 	}
719 
720 	return old;
721 }
722 
723 /* The common case: only accept colon as delimiter. */
724 char *
hpdelim(char ** cp)725 hpdelim(char **cp)
726 {
727 	char *r, delim = '\0';
728 
729 	r =  hpdelim2(cp, &delim);
730 	if (delim == '/')
731 		return NULL;
732 	return r;
733 }
734 
735 char *
cleanhostname(char * host)736 cleanhostname(char *host)
737 {
738 	if (*host == '[' && host[strlen(host) - 1] == ']') {
739 		host[strlen(host) - 1] = '\0';
740 		return (host + 1);
741 	} else
742 		return host;
743 }
744 
745 char *
colon(char * cp)746 colon(char *cp)
747 {
748 	int flag = 0;
749 
750 	if (*cp == ':')		/* Leading colon is part of file name. */
751 		return NULL;
752 	if (*cp == '[')
753 		flag = 1;
754 
755 	for (; *cp; ++cp) {
756 		if (*cp == '@' && *(cp+1) == '[')
757 			flag = 1;
758 		if (*cp == ']' && *(cp+1) == ':' && flag)
759 			return (cp+1);
760 		if (*cp == ':' && !flag)
761 			return (cp);
762 		if (*cp == '/')
763 			return NULL;
764 	}
765 	return NULL;
766 }
767 
768 /*
769  * Parse a [user@]host:[path] string.
770  * Caller must free returned user, host and path.
771  * Any of the pointer return arguments may be NULL (useful for syntax checking).
772  * If user was not specified then *userp will be set to NULL.
773  * If host was not specified then *hostp will be set to NULL.
774  * If path was not specified then *pathp will be set to ".".
775  * Returns 0 on success, -1 on failure.
776  */
777 int
parse_user_host_path(const char * s,char ** userp,char ** hostp,char ** pathp)778 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
779 {
780 	char *user = NULL, *host = NULL, *path = NULL;
781 	char *sdup, *tmp;
782 	int ret = -1;
783 
784 	if (userp != NULL)
785 		*userp = NULL;
786 	if (hostp != NULL)
787 		*hostp = NULL;
788 	if (pathp != NULL)
789 		*pathp = NULL;
790 
791 	sdup = xstrdup(s);
792 
793 	/* Check for remote syntax: [user@]host:[path] */
794 	if ((tmp = colon(sdup)) == NULL)
795 		goto out;
796 
797 	/* Extract optional path */
798 	*tmp++ = '\0';
799 	if (*tmp == '\0')
800 		tmp = __UNCONST(".");
801 	path = xstrdup(tmp);
802 
803 	/* Extract optional user and mandatory host */
804 	tmp = strrchr(sdup, '@');
805 	if (tmp != NULL) {
806 		*tmp++ = '\0';
807 		host = xstrdup(cleanhostname(tmp));
808 		if (*sdup != '\0')
809 			user = xstrdup(sdup);
810 	} else {
811 		host = xstrdup(cleanhostname(sdup));
812 		user = NULL;
813 	}
814 
815 	/* Success */
816 	if (userp != NULL) {
817 		*userp = user;
818 		user = NULL;
819 	}
820 	if (hostp != NULL) {
821 		*hostp = host;
822 		host = NULL;
823 	}
824 	if (pathp != NULL) {
825 		*pathp = path;
826 		path = NULL;
827 	}
828 	ret = 0;
829 out:
830 	free(sdup);
831 	free(user);
832 	free(host);
833 	free(path);
834 	return ret;
835 }
836 
837 /*
838  * Parse a [user@]host[:port] string.
839  * Caller must free returned user and host.
840  * Any of the pointer return arguments may be NULL (useful for syntax checking).
841  * If user was not specified then *userp will be set to NULL.
842  * If port was not specified then *portp will be -1.
843  * Returns 0 on success, -1 on failure.
844  */
845 int
parse_user_host_port(const char * s,char ** userp,char ** hostp,int * portp)846 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
847 {
848 	char *sdup, *cp, *tmp;
849 	char *user = NULL, *host = NULL;
850 	int port = -1, ret = -1;
851 
852 	if (userp != NULL)
853 		*userp = NULL;
854 	if (hostp != NULL)
855 		*hostp = NULL;
856 	if (portp != NULL)
857 		*portp = -1;
858 
859 	if ((sdup = tmp = strdup(s)) == NULL)
860 		return -1;
861 	/* Extract optional username */
862 	if ((cp = strrchr(tmp, '@')) != NULL) {
863 		*cp = '\0';
864 		if (*tmp == '\0')
865 			goto out;
866 		if ((user = strdup(tmp)) == NULL)
867 			goto out;
868 		tmp = cp + 1;
869 	}
870 	/* Extract mandatory hostname */
871 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
872 		goto out;
873 	host = xstrdup(cleanhostname(cp));
874 	/* Convert and verify optional port */
875 	if (tmp != NULL && *tmp != '\0') {
876 		if ((port = a2port(tmp)) <= 0)
877 			goto out;
878 	}
879 	/* Success */
880 	if (userp != NULL) {
881 		*userp = user;
882 		user = NULL;
883 	}
884 	if (hostp != NULL) {
885 		*hostp = host;
886 		host = NULL;
887 	}
888 	if (portp != NULL)
889 		*portp = port;
890 	ret = 0;
891  out:
892 	free(sdup);
893 	free(user);
894 	free(host);
895 	return ret;
896 }
897 
898 /*
899  * Converts a two-byte hex string to decimal.
900  * Returns the decimal value or -1 for invalid input.
901  */
902 static int
hexchar(const char * s)903 hexchar(const char *s)
904 {
905 	unsigned char result[2];
906 	int i;
907 
908 	for (i = 0; i < 2; i++) {
909 		if (s[i] >= '0' && s[i] <= '9')
910 			result[i] = (unsigned char)(s[i] - '0');
911 		else if (s[i] >= 'a' && s[i] <= 'f')
912 			result[i] = (unsigned char)(s[i] - 'a') + 10;
913 		else if (s[i] >= 'A' && s[i] <= 'F')
914 			result[i] = (unsigned char)(s[i] - 'A') + 10;
915 		else
916 			return -1;
917 	}
918 	return (result[0] << 4) | result[1];
919 }
920 
921 /*
922  * Decode an url-encoded string.
923  * Returns a newly allocated string on success or NULL on failure.
924  */
925 static char *
urldecode(const char * src)926 urldecode(const char *src)
927 {
928 	char *ret, *dst;
929 	int ch;
930 	size_t srclen;
931 
932 	if ((srclen = strlen(src)) >= SIZE_MAX)
933 		fatal_f("input too large");
934 	ret = xmalloc(srclen + 1);
935 	for (dst = ret; *src != '\0'; src++) {
936 		switch (*src) {
937 		case '+':
938 			*dst++ = ' ';
939 			break;
940 		case '%':
941 			if (!isxdigit((unsigned char)src[1]) ||
942 			    !isxdigit((unsigned char)src[2]) ||
943 			    (ch = hexchar(src + 1)) == -1) {
944 				free(ret);
945 				return NULL;
946 			}
947 			*dst++ = ch;
948 			src += 2;
949 			break;
950 		default:
951 			*dst++ = *src;
952 			break;
953 		}
954 	}
955 	*dst = '\0';
956 
957 	return ret;
958 }
959 
960 /*
961  * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
962  * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
963  * Either user or path may be url-encoded (but not host or port).
964  * Caller must free returned user, host and path.
965  * Any of the pointer return arguments may be NULL (useful for syntax checking)
966  * but the scheme must always be specified.
967  * If user was not specified then *userp will be set to NULL.
968  * If port was not specified then *portp will be -1.
969  * If path was not specified then *pathp will be set to NULL.
970  * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
971  */
972 int
parse_uri(const char * scheme,const char * uri,char ** userp,char ** hostp,int * portp,char ** pathp)973 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
974     int *portp, char **pathp)
975 {
976 	char *uridup, *cp, *tmp, ch;
977 	char *user = NULL, *host = NULL, *path = NULL;
978 	int port = -1, ret = -1;
979 	size_t len;
980 
981 	len = strlen(scheme);
982 	if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
983 		return 1;
984 	uri += len + 3;
985 
986 	if (userp != NULL)
987 		*userp = NULL;
988 	if (hostp != NULL)
989 		*hostp = NULL;
990 	if (portp != NULL)
991 		*portp = -1;
992 	if (pathp != NULL)
993 		*pathp = NULL;
994 
995 	uridup = tmp = xstrdup(uri);
996 
997 	/* Extract optional ssh-info (username + connection params) */
998 	if ((cp = strchr(tmp, '@')) != NULL) {
999 		char *delim;
1000 
1001 		*cp = '\0';
1002 		/* Extract username and connection params */
1003 		if ((delim = strchr(tmp, ';')) != NULL) {
1004 			/* Just ignore connection params for now */
1005 			*delim = '\0';
1006 		}
1007 		if (*tmp == '\0') {
1008 			/* Empty username */
1009 			goto out;
1010 		}
1011 		if ((user = urldecode(tmp)) == NULL)
1012 			goto out;
1013 		tmp = cp + 1;
1014 	}
1015 
1016 	/* Extract mandatory hostname */
1017 	if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
1018 		goto out;
1019 	host = xstrdup(cleanhostname(cp));
1020 	if (!valid_domain(host, 0, NULL))
1021 		goto out;
1022 
1023 	if (tmp != NULL && *tmp != '\0') {
1024 		if (ch == ':') {
1025 			/* Convert and verify port. */
1026 			if ((cp = strchr(tmp, '/')) != NULL)
1027 				*cp = '\0';
1028 			if ((port = a2port(tmp)) <= 0)
1029 				goto out;
1030 			tmp = cp ? cp + 1 : NULL;
1031 		}
1032 		if (tmp != NULL && *tmp != '\0') {
1033 			/* Extract optional path */
1034 			if ((path = urldecode(tmp)) == NULL)
1035 				goto out;
1036 		}
1037 	}
1038 
1039 	/* Success */
1040 	if (userp != NULL) {
1041 		*userp = user;
1042 		user = NULL;
1043 	}
1044 	if (hostp != NULL) {
1045 		*hostp = host;
1046 		host = NULL;
1047 	}
1048 	if (portp != NULL)
1049 		*portp = port;
1050 	if (pathp != NULL) {
1051 		*pathp = path;
1052 		path = NULL;
1053 	}
1054 	ret = 0;
1055  out:
1056 	free(uridup);
1057 	free(user);
1058 	free(host);
1059 	free(path);
1060 	return ret;
1061 }
1062 
1063 /* function to assist building execv() arguments */
1064 void
addargs(arglist * args,const char * fmt,...)1065 addargs(arglist *args, const char *fmt, ...)
1066 {
1067 	va_list ap;
1068 	char *cp;
1069 	u_int nalloc;
1070 	int r;
1071 
1072 	va_start(ap, fmt);
1073 	r = vasprintf(&cp, fmt, ap);
1074 	va_end(ap);
1075 	if (r == -1)
1076 		fatal_f("argument too long");
1077 
1078 	nalloc = args->nalloc;
1079 	if (args->list == NULL) {
1080 		nalloc = 32;
1081 		args->num = 0;
1082 	} else if (args->num > (256 * 1024))
1083 		fatal_f("too many arguments");
1084 	else if (args->num >= args->nalloc)
1085 		fatal_f("arglist corrupt");
1086 	else if (args->num+2 >= nalloc)
1087 		nalloc *= 2;
1088 
1089 	args->list = xrecallocarray(args->list, args->nalloc,
1090 	    nalloc, sizeof(char *));
1091 	args->nalloc = nalloc;
1092 	args->list[args->num++] = cp;
1093 	args->list[args->num] = NULL;
1094 }
1095 
1096 void
replacearg(arglist * args,u_int which,const char * fmt,...)1097 replacearg(arglist *args, u_int which, const char *fmt, ...)
1098 {
1099 	va_list ap;
1100 	char *cp;
1101 	int r;
1102 
1103 	va_start(ap, fmt);
1104 	r = vasprintf(&cp, fmt, ap);
1105 	va_end(ap);
1106 	if (r == -1)
1107 		fatal_f("argument too long");
1108 	if (args->list == NULL || args->num >= args->nalloc)
1109 		fatal_f("arglist corrupt");
1110 
1111 	if (which >= args->num)
1112 		fatal_f("tried to replace invalid arg %d >= %d",
1113 		    which, args->num);
1114 	free(args->list[which]);
1115 	args->list[which] = cp;
1116 }
1117 
1118 void
freeargs(arglist * args)1119 freeargs(arglist *args)
1120 {
1121 	u_int i;
1122 
1123 	if (args == NULL)
1124 		return;
1125 	if (args->list != NULL && args->num < args->nalloc) {
1126 		for (i = 0; i < args->num; i++)
1127 			free(args->list[i]);
1128 		free(args->list);
1129 	}
1130 	args->nalloc = args->num = 0;
1131 	args->list = NULL;
1132 }
1133 
1134 /*
1135  * Expands tildes in the file name.  Returns data allocated by xmalloc.
1136  * Warning: this calls getpw*.
1137  */
1138 int
tilde_expand(const char * filename,uid_t uid,char ** retp)1139 tilde_expand(const char *filename, uid_t uid, char **retp)
1140 {
1141 	char *ocopy = NULL, *copy, *s = NULL;
1142 	const char *path = NULL, *user = NULL;
1143 	struct passwd *pw;
1144 	size_t len;
1145 	int ret = -1, r, slash;
1146 
1147 	*retp = NULL;
1148 	if (*filename != '~') {
1149 		*retp = xstrdup(filename);
1150 		return 0;
1151 	}
1152 	ocopy = copy = xstrdup(filename + 1);
1153 
1154 	if (*copy == '\0')				/* ~ */
1155 		path = NULL;
1156 	else if (*copy == '/') {
1157 		copy += strspn(copy, "/");
1158 		if (*copy == '\0')
1159 			path = NULL;			/* ~/ */
1160 		else
1161 			path = copy;			/* ~/path */
1162 	} else {
1163 		user = copy;
1164 		if ((path = strchr(copy, '/')) != NULL) {
1165 			copy[path - copy] = '\0';
1166 			path++;
1167 			path += strspn(path, "/");
1168 			if (*path == '\0')		/* ~user/ */
1169 				path = NULL;
1170 			/* else				 ~user/path */
1171 		}
1172 		/* else					~user */
1173 	}
1174 	if (user != NULL) {
1175 		if ((pw = getpwnam(user)) == NULL) {
1176 			error_f("No such user %s", user);
1177 			goto out;
1178 		}
1179 	} else if ((pw = getpwuid(uid)) == NULL) {
1180 		error_f("No such uid %ld", (long)uid);
1181 		goto out;
1182 	}
1183 
1184 	/* Make sure directory has a trailing '/' */
1185 	slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1186 
1187 	if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1188 	    slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1189 		error_f("xasprintf failed");
1190 		goto out;
1191 	}
1192 	if (r >= PATH_MAX) {
1193 		error_f("Path too long");
1194 		goto out;
1195 	}
1196 	/* success */
1197 	ret = 0;
1198 	*retp = s;
1199 	s = NULL;
1200  out:
1201 	free(s);
1202 	free(ocopy);
1203 	return ret;
1204 }
1205 
1206 char *
tilde_expand_filename(const char * filename,uid_t uid)1207 tilde_expand_filename(const char *filename, uid_t uid)
1208 {
1209 	char *ret;
1210 
1211 	if (tilde_expand(filename, uid, &ret) != 0)
1212 		cleanup_exit(255);
1213 	return ret;
1214 }
1215 
1216 /*
1217  * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1218  * substitutions.  A number of escapes may be specified as
1219  * (char *escape_chars, char *replacement) pairs. The list must be terminated
1220  * by a NULL escape_char. Returns replaced string in memory allocated by
1221  * xmalloc which the caller must free.
1222  */
1223 static char *
vdollar_percent_expand(int * parseerror,int dollar,int percent,const char * string,va_list ap)1224 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1225     const char *string, va_list ap)
1226 {
1227 #define EXPAND_MAX_KEYS	64
1228 	u_int num_keys = 0, i;
1229 	struct {
1230 		const char *key;
1231 		const char *repl;
1232 	} keys[EXPAND_MAX_KEYS];
1233 	struct sshbuf *buf;
1234 	int r, missingvar = 0;
1235 	char *ret = NULL, *var, *varend, *val;
1236 	size_t len;
1237 
1238 	if ((buf = sshbuf_new()) == NULL)
1239 		fatal_f("sshbuf_new failed");
1240 	if (parseerror == NULL)
1241 		fatal_f("null parseerror arg");
1242 	*parseerror = 1;
1243 
1244 	/* Gather keys if we're doing percent expansion. */
1245 	if (percent) {
1246 		for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1247 			keys[num_keys].key = va_arg(ap, char *);
1248 			if (keys[num_keys].key == NULL)
1249 				break;
1250 			keys[num_keys].repl = va_arg(ap, char *);
1251 			if (keys[num_keys].repl == NULL) {
1252 				fatal_f("NULL replacement for token %s",
1253 				    keys[num_keys].key);
1254 			}
1255 		}
1256 		if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1257 			fatal_f("too many keys");
1258 		if (num_keys == 0)
1259 			fatal_f("percent expansion without token list");
1260 	}
1261 
1262 	/* Expand string */
1263 	for (i = 0; *string != '\0'; string++) {
1264 		/* Optionally process ${ENVIRONMENT} expansions. */
1265 		if (dollar && string[0] == '$' && string[1] == '{') {
1266 			string += 2;  /* skip over '${' */
1267 			if ((varend = strchr(string, '}')) == NULL) {
1268 				error_f("environment variable '%s' missing "
1269 				    "closing '}'", string);
1270 				goto out;
1271 			}
1272 			len = varend - string;
1273 			if (len == 0) {
1274 				error_f("zero-length environment variable");
1275 				goto out;
1276 			}
1277 			var = xmalloc(len + 1);
1278 			(void)strlcpy(var, string, len + 1);
1279 			if ((val = getenv(var)) == NULL) {
1280 				error_f("env var ${%s} has no value", var);
1281 				missingvar = 1;
1282 			} else {
1283 				debug3_f("expand ${%s} -> '%s'", var, val);
1284 				if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1285 					fatal_fr(r, "sshbuf_put ${}");
1286 			}
1287 			free(var);
1288 			string += len;
1289 			continue;
1290 		}
1291 
1292 		/*
1293 		 * Process percent expansions if we have a list of TOKENs.
1294 		 * If we're not doing percent expansion everything just gets
1295 		 * appended here.
1296 		 */
1297 		if (*string != '%' || !percent) {
1298  append:
1299 			if ((r = sshbuf_put_u8(buf, *string)) != 0)
1300 				fatal_fr(r, "sshbuf_put_u8 %%");
1301 			continue;
1302 		}
1303 		string++;
1304 		/* %% case */
1305 		if (*string == '%')
1306 			goto append;
1307 		if (*string == '\0') {
1308 			error_f("invalid format");
1309 			goto out;
1310 		}
1311 		for (i = 0; i < num_keys; i++) {
1312 			if (strchr(keys[i].key, *string) != NULL) {
1313 				if ((r = sshbuf_put(buf, keys[i].repl,
1314 				    strlen(keys[i].repl))) != 0)
1315 					fatal_fr(r, "sshbuf_put %%-repl");
1316 				break;
1317 			}
1318 		}
1319 		if (i >= num_keys) {
1320 			error_f("unknown key %%%c", *string);
1321 			goto out;
1322 		}
1323 	}
1324 	if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1325 		fatal_f("sshbuf_dup_string failed");
1326 	*parseerror = 0;
1327  out:
1328 	sshbuf_free(buf);
1329 	return *parseerror ? NULL : ret;
1330 #undef EXPAND_MAX_KEYS
1331 }
1332 
1333 /*
1334  * Expand only environment variables.
1335  * Note that although this function is variadic like the other similar
1336  * functions, any such arguments will be unused.
1337  */
1338 
1339 char *
dollar_expand(int * parseerr,const char * string,...)1340 dollar_expand(int *parseerr, const char *string, ...)
1341 {
1342 	char *ret;
1343 	int err;
1344 	va_list ap;
1345 
1346 	va_start(ap, string);
1347 	ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1348 	va_end(ap);
1349 	if (parseerr != NULL)
1350 		*parseerr = err;
1351 	return ret;
1352 }
1353 
1354 /*
1355  * Returns expanded string or NULL if a specified environment variable is
1356  * not defined, or calls fatal if the string is invalid.
1357  */
1358 char *
percent_expand(const char * string,...)1359 percent_expand(const char *string, ...)
1360 {
1361 	char *ret;
1362 	int err;
1363 	va_list ap;
1364 
1365 	va_start(ap, string);
1366 	ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1367 	va_end(ap);
1368 	if (err)
1369 		fatal_f("failed");
1370 	return ret;
1371 }
1372 
1373 /*
1374  * Returns expanded string or NULL if a specified environment variable is
1375  * not defined, or calls fatal if the string is invalid.
1376  */
1377 char *
percent_dollar_expand(const char * string,...)1378 percent_dollar_expand(const char *string, ...)
1379 {
1380 	char *ret;
1381 	int err;
1382 	va_list ap;
1383 
1384 	va_start(ap, string);
1385 	ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1386 	va_end(ap);
1387 	if (err)
1388 		fatal_f("failed");
1389 	return ret;
1390 }
1391 
1392 int
tun_open(int tun,int mode,char ** ifname)1393 tun_open(int tun, int mode, char **ifname)
1394 {
1395 	struct ifreq ifr;
1396 	char name[100];
1397 	int fd = -1, sock;
1398 	const char *tunbase = "tun";
1399 
1400 	if (ifname != NULL)
1401 		*ifname = NULL;
1402 
1403 	if (mode == SSH_TUNMODE_ETHERNET)
1404 		tunbase = "tap";
1405 
1406 	/* Open the tunnel device */
1407 	if (tun <= SSH_TUNID_MAX) {
1408 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1409 		fd = open(name, O_RDWR);
1410 	} else if (tun == SSH_TUNID_ANY) {
1411 		for (tun = 100; tun >= 0; tun--) {
1412 			snprintf(name, sizeof(name), "/dev/%s%d",
1413 			    tunbase, tun);
1414 			if ((fd = open(name, O_RDWR)) >= 0)
1415 				break;
1416 		}
1417 	} else {
1418 		debug_f("invalid tunnel %u", tun);
1419 		return -1;
1420 	}
1421 
1422 	if (fd == -1) {
1423 		debug_f("%s open: %s", name, strerror(errno));
1424 		return -1;
1425 	}
1426 
1427 	debug_f("%s mode %d fd %d", name, mode, fd);
1428 
1429 #ifdef TUNSIFHEAD
1430 	/* Turn on tunnel headers */
1431 	int flag = 1;
1432 	if (mode != SSH_TUNMODE_ETHERNET &&
1433 	    ioctl(fd, TUNSIFHEAD, &flag) == -1) {
1434 		debug("%s: ioctl(%d, TUNSIFHEAD, 1): %s", __func__, fd,
1435 		    strerror(errno));
1436 		close(fd);
1437 		return -1;
1438 	}
1439 #endif
1440 
1441 	debug("%s: %s mode %d fd %d", __func__, ifr.ifr_name, mode, fd);
1442 	/* Bring interface up if it is not already */
1443 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1444 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1445 		goto failed;
1446 
1447 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1448 		debug_f("get interface %s flags: %s", ifr.ifr_name,
1449 		    strerror(errno));
1450 		goto failed;
1451 	}
1452 
1453 	if (!(ifr.ifr_flags & IFF_UP)) {
1454 		ifr.ifr_flags |= IFF_UP;
1455 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1456 			debug_f("activate interface %s: %s", ifr.ifr_name,
1457 			    strerror(errno));
1458 			goto failed;
1459 		}
1460 	}
1461 
1462 	if (ifname != NULL)
1463 		*ifname = xstrdup(ifr.ifr_name);
1464 
1465 	close(sock);
1466 	return fd;
1467 
1468  failed:
1469 	if (fd >= 0)
1470 		close(fd);
1471 	if (sock >= 0)
1472 		close(sock);
1473 	debug("%s: failed to set %s mode %d: %s", __func__, ifr.ifr_name,
1474 	    mode, strerror(errno));
1475 	return -1;
1476 }
1477 
1478 void
sanitise_stdfd(void)1479 sanitise_stdfd(void)
1480 {
1481 	int nullfd, dupfd;
1482 
1483 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1484 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
1485 		    strerror(errno));
1486 		exit(1);
1487 	}
1488 	while (++dupfd <= STDERR_FILENO) {
1489 		/* Only populate closed fds. */
1490 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1491 			if (dup2(nullfd, dupfd) == -1) {
1492 				fprintf(stderr, "dup2: %s\n", strerror(errno));
1493 				exit(1);
1494 			}
1495 		}
1496 	}
1497 	if (nullfd > STDERR_FILENO)
1498 		close(nullfd);
1499 }
1500 
1501 char *
tohex(const void * vp,size_t l)1502 tohex(const void *vp, size_t l)
1503 {
1504 	const u_char *p = (const u_char *)vp;
1505 	char b[3], *r;
1506 	size_t i, hl;
1507 
1508 	if (l > 65536)
1509 		return xstrdup("tohex: length > 65536");
1510 
1511 	hl = l * 2 + 1;
1512 	r = xcalloc(1, hl);
1513 	for (i = 0; i < l; i++) {
1514 		snprintf(b, sizeof(b), "%02x", p[i]);
1515 		strlcat(r, b, hl);
1516 	}
1517 	return (r);
1518 }
1519 
1520 /*
1521  * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1522  * then the separator 'sep' will be prepended before the formatted arguments.
1523  * Extended strings are heap allocated.
1524  */
1525 void
xextendf(char ** sp,const char * sep,const char * fmt,...)1526 xextendf(char **sp, const char *sep, const char *fmt, ...)
1527 {
1528 	va_list ap;
1529 	char *tmp1, *tmp2;
1530 
1531 	va_start(ap, fmt);
1532 	xvasprintf(&tmp1, fmt, ap);
1533 	va_end(ap);
1534 
1535 	if (*sp == NULL || **sp == '\0') {
1536 		free(*sp);
1537 		*sp = tmp1;
1538 		return;
1539 	}
1540 	xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1541 	free(tmp1);
1542 	free(*sp);
1543 	*sp = tmp2;
1544 }
1545 
1546 
1547 u_int64_t
get_u64(const void * vp)1548 get_u64(const void *vp)
1549 {
1550 	const u_char *p = (const u_char *)vp;
1551 	u_int64_t v;
1552 
1553 	v  = (u_int64_t)p[0] << 56;
1554 	v |= (u_int64_t)p[1] << 48;
1555 	v |= (u_int64_t)p[2] << 40;
1556 	v |= (u_int64_t)p[3] << 32;
1557 	v |= (u_int64_t)p[4] << 24;
1558 	v |= (u_int64_t)p[5] << 16;
1559 	v |= (u_int64_t)p[6] << 8;
1560 	v |= (u_int64_t)p[7];
1561 
1562 	return (v);
1563 }
1564 
1565 u_int32_t
get_u32(const void * vp)1566 get_u32(const void *vp)
1567 {
1568 	const u_char *p = (const u_char *)vp;
1569 	u_int32_t v;
1570 
1571 	v  = (u_int32_t)p[0] << 24;
1572 	v |= (u_int32_t)p[1] << 16;
1573 	v |= (u_int32_t)p[2] << 8;
1574 	v |= (u_int32_t)p[3];
1575 
1576 	return (v);
1577 }
1578 
1579 u_int32_t
get_u32_le(const void * vp)1580 get_u32_le(const void *vp)
1581 {
1582 	const u_char *p = (const u_char *)vp;
1583 	u_int32_t v;
1584 
1585 	v  = (u_int32_t)p[0];
1586 	v |= (u_int32_t)p[1] << 8;
1587 	v |= (u_int32_t)p[2] << 16;
1588 	v |= (u_int32_t)p[3] << 24;
1589 
1590 	return (v);
1591 }
1592 
1593 u_int16_t
get_u16(const void * vp)1594 get_u16(const void *vp)
1595 {
1596 	const u_char *p = (const u_char *)vp;
1597 	u_int16_t v;
1598 
1599 	v  = (u_int16_t)p[0] << 8;
1600 	v |= (u_int16_t)p[1];
1601 
1602 	return (v);
1603 }
1604 
1605 void
put_u64(void * vp,u_int64_t v)1606 put_u64(void *vp, u_int64_t v)
1607 {
1608 	u_char *p = (u_char *)vp;
1609 
1610 	p[0] = (u_char)(v >> 56) & 0xff;
1611 	p[1] = (u_char)(v >> 48) & 0xff;
1612 	p[2] = (u_char)(v >> 40) & 0xff;
1613 	p[3] = (u_char)(v >> 32) & 0xff;
1614 	p[4] = (u_char)(v >> 24) & 0xff;
1615 	p[5] = (u_char)(v >> 16) & 0xff;
1616 	p[6] = (u_char)(v >> 8) & 0xff;
1617 	p[7] = (u_char)v & 0xff;
1618 }
1619 
1620 void
put_u32(void * vp,u_int32_t v)1621 put_u32(void *vp, u_int32_t v)
1622 {
1623 	u_char *p = (u_char *)vp;
1624 
1625 	p[0] = (u_char)(v >> 24) & 0xff;
1626 	p[1] = (u_char)(v >> 16) & 0xff;
1627 	p[2] = (u_char)(v >> 8) & 0xff;
1628 	p[3] = (u_char)v & 0xff;
1629 }
1630 
1631 void
put_u32_le(void * vp,u_int32_t v)1632 put_u32_le(void *vp, u_int32_t v)
1633 {
1634 	u_char *p = (u_char *)vp;
1635 
1636 	p[0] = (u_char)v & 0xff;
1637 	p[1] = (u_char)(v >> 8) & 0xff;
1638 	p[2] = (u_char)(v >> 16) & 0xff;
1639 	p[3] = (u_char)(v >> 24) & 0xff;
1640 }
1641 
1642 void
put_u16(void * vp,u_int16_t v)1643 put_u16(void *vp, u_int16_t v)
1644 {
1645 	u_char *p = (u_char *)vp;
1646 
1647 	p[0] = (u_char)(v >> 8) & 0xff;
1648 	p[1] = (u_char)v & 0xff;
1649 }
1650 
1651 void
ms_subtract_diff(struct timeval * start,int * ms)1652 ms_subtract_diff(struct timeval *start, int *ms)
1653 {
1654 	struct timeval diff, finish;
1655 
1656 	monotime_tv(&finish);
1657 	timersub(&finish, start, &diff);
1658 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1659 }
1660 
1661 void
ms_to_timespec(struct timespec * ts,int ms)1662 ms_to_timespec(struct timespec *ts, int ms)
1663 {
1664 	if (ms < 0)
1665 		ms = 0;
1666 	ts->tv_sec = ms / 1000;
1667 	ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1668 }
1669 
1670 void
monotime_ts(struct timespec * ts)1671 monotime_ts(struct timespec *ts)
1672 {
1673 	if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
1674 		fatal("clock_gettime: %s", strerror(errno));
1675 }
1676 
1677 void
monotime_tv(struct timeval * tv)1678 monotime_tv(struct timeval *tv)
1679 {
1680 	struct timespec ts;
1681 
1682 	monotime_ts(&ts);
1683 	tv->tv_sec = ts.tv_sec;
1684 	tv->tv_usec = ts.tv_nsec / 1000;
1685 }
1686 
1687 time_t
monotime(void)1688 monotime(void)
1689 {
1690 	struct timespec ts;
1691 
1692 	monotime_ts(&ts);
1693 	return (ts.tv_sec);
1694 }
1695 
1696 double
monotime_double(void)1697 monotime_double(void)
1698 {
1699 	struct timespec ts;
1700 
1701 	monotime_ts(&ts);
1702 	return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
1703 }
1704 
1705 void
bandwidth_limit_init(struct bwlimit * bw,u_int64_t kbps,size_t buflen)1706 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1707 {
1708 	bw->buflen = buflen;
1709 	bw->rate = kbps;
1710 	bw->thresh = buflen;
1711 	bw->lamt = 0;
1712 	timerclear(&bw->bwstart);
1713 	timerclear(&bw->bwend);
1714 }
1715 
1716 /* Callback from read/write loop to insert bandwidth-limiting delays */
1717 void
bandwidth_limit(struct bwlimit * bw,size_t read_len)1718 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1719 {
1720 	u_int64_t waitlen;
1721 	struct timespec ts, rm;
1722 
1723 	bw->lamt += read_len;
1724 	if (!timerisset(&bw->bwstart)) {
1725 		monotime_tv(&bw->bwstart);
1726 		return;
1727 	}
1728 	if (bw->lamt < bw->thresh)
1729 		return;
1730 
1731 	monotime_tv(&bw->bwend);
1732 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1733 	if (!timerisset(&bw->bwend))
1734 		return;
1735 
1736 	bw->lamt *= 8;
1737 	waitlen = (double)1000000L * bw->lamt / bw->rate;
1738 
1739 	bw->bwstart.tv_sec = waitlen / 1000000L;
1740 	bw->bwstart.tv_usec = waitlen % 1000000L;
1741 
1742 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1743 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1744 
1745 		/* Adjust the wait time */
1746 		if (bw->bwend.tv_sec) {
1747 			bw->thresh /= 2;
1748 			if (bw->thresh < bw->buflen / 4)
1749 				bw->thresh = bw->buflen / 4;
1750 		} else if (bw->bwend.tv_usec < 10000) {
1751 			bw->thresh *= 2;
1752 			if (bw->thresh > bw->buflen * 8)
1753 				bw->thresh = bw->buflen * 8;
1754 		}
1755 
1756 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1757 		while (nanosleep(&ts, &rm) == -1) {
1758 			if (errno != EINTR)
1759 				break;
1760 			ts = rm;
1761 		}
1762 	}
1763 
1764 	bw->lamt = 0;
1765 	monotime_tv(&bw->bwstart);
1766 }
1767 
1768 /* Make a template filename for mk[sd]temp() */
1769 void
mktemp_proto(char * s,size_t len)1770 mktemp_proto(char *s, size_t len)
1771 {
1772 	const char *tmpdir;
1773 	int r;
1774 
1775 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
1776 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1777 		if (r > 0 && (size_t)r < len)
1778 			return;
1779 	}
1780 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1781 	if (r < 0 || (size_t)r >= len)
1782 		fatal_f("template string too short");
1783 }
1784 
1785 static const struct {
1786 	const char *name;
1787 	int value;
1788 } ipqos[] = {
1789 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
1790 	{ "af11", IPTOS_DSCP_AF11 },
1791 	{ "af12", IPTOS_DSCP_AF12 },
1792 	{ "af13", IPTOS_DSCP_AF13 },
1793 	{ "af21", IPTOS_DSCP_AF21 },
1794 	{ "af22", IPTOS_DSCP_AF22 },
1795 	{ "af23", IPTOS_DSCP_AF23 },
1796 	{ "af31", IPTOS_DSCP_AF31 },
1797 	{ "af32", IPTOS_DSCP_AF32 },
1798 	{ "af33", IPTOS_DSCP_AF33 },
1799 	{ "af41", IPTOS_DSCP_AF41 },
1800 	{ "af42", IPTOS_DSCP_AF42 },
1801 	{ "af43", IPTOS_DSCP_AF43 },
1802 	{ "cs0", IPTOS_DSCP_CS0 },
1803 	{ "cs1", IPTOS_DSCP_CS1 },
1804 	{ "cs2", IPTOS_DSCP_CS2 },
1805 	{ "cs3", IPTOS_DSCP_CS3 },
1806 	{ "cs4", IPTOS_DSCP_CS4 },
1807 	{ "cs5", IPTOS_DSCP_CS5 },
1808 	{ "cs6", IPTOS_DSCP_CS6 },
1809 	{ "cs7", IPTOS_DSCP_CS7 },
1810 	{ "ef", IPTOS_DSCP_EF },
1811 #ifdef IPTOS_DSCP_LE
1812 	{ "le", IPTOS_DSCP_LE },
1813 #endif
1814 	{ "lowdelay", IPTOS_LOWDELAY },
1815 	{ "throughput", IPTOS_THROUGHPUT },
1816 	{ "reliability", IPTOS_RELIABILITY },
1817 	{ NULL, -1 }
1818 };
1819 
1820 int
parse_ipqos(const char * cp)1821 parse_ipqos(const char *cp)
1822 {
1823 	const char *errstr;
1824 	u_int i;
1825 	int val;
1826 
1827 	if (cp == NULL)
1828 		return -1;
1829 	for (i = 0; ipqos[i].name != NULL; i++) {
1830 		if (strcasecmp(cp, ipqos[i].name) == 0)
1831 			return ipqos[i].value;
1832 	}
1833 	/* Try parsing as an integer */
1834 	val = (int)strtonum(cp, 0, 255, &errstr);
1835 	if (errstr)
1836 		return -1;
1837 	return val;
1838 }
1839 
1840 const char *
iptos2str(int iptos)1841 iptos2str(int iptos)
1842 {
1843 	int i;
1844 	static char iptos_str[sizeof "0xff"];
1845 
1846 	for (i = 0; ipqos[i].name != NULL; i++) {
1847 		if (ipqos[i].value == iptos)
1848 			return ipqos[i].name;
1849 	}
1850 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1851 	return iptos_str;
1852 }
1853 
1854 void
lowercase(char * s)1855 lowercase(char *s)
1856 {
1857 	for (; *s; s++)
1858 		*s = tolower((u_char)*s);
1859 }
1860 
1861 int
unix_listener(const char * path,int backlog,int unlink_first)1862 unix_listener(const char *path, int backlog, int unlink_first)
1863 {
1864 	struct sockaddr_un sunaddr;
1865 	int saved_errno, sock;
1866 
1867 	memset(&sunaddr, 0, sizeof(sunaddr));
1868 	sunaddr.sun_family = AF_UNIX;
1869 	if (strlcpy(sunaddr.sun_path, path,
1870 	    sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1871 		error_f("path \"%s\" too long for Unix domain socket", path);
1872 		errno = ENAMETOOLONG;
1873 		return -1;
1874 	}
1875 
1876 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
1877 	if (sock == -1) {
1878 		saved_errno = errno;
1879 		error_f("socket: %.100s", strerror(errno));
1880 		errno = saved_errno;
1881 		return -1;
1882 	}
1883 	if (unlink_first == 1) {
1884 		if (unlink(path) != 0 && errno != ENOENT)
1885 			error("unlink(%s): %.100s", path, strerror(errno));
1886 	}
1887 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1888 		saved_errno = errno;
1889 		error_f("cannot bind to path %s: %s", path, strerror(errno));
1890 		close(sock);
1891 		errno = saved_errno;
1892 		return -1;
1893 	}
1894 	if (listen(sock, backlog) == -1) {
1895 		saved_errno = errno;
1896 		error_f("cannot listen on path %s: %s", path, strerror(errno));
1897 		close(sock);
1898 		unlink(path);
1899 		errno = saved_errno;
1900 		return -1;
1901 	}
1902 	return sock;
1903 }
1904 
1905 /*
1906  * Compares two strings that maybe be NULL. Returns non-zero if strings
1907  * are both NULL or are identical, returns zero otherwise.
1908  */
1909 static int
strcmp_maybe_null(const char * a,const char * b)1910 strcmp_maybe_null(const char *a, const char *b)
1911 {
1912 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1913 		return 0;
1914 	if (a != NULL && strcmp(a, b) != 0)
1915 		return 0;
1916 	return 1;
1917 }
1918 
1919 /*
1920  * Compare two forwards, returning non-zero if they are identical or
1921  * zero otherwise.
1922  */
1923 int
forward_equals(const struct Forward * a,const struct Forward * b)1924 forward_equals(const struct Forward *a, const struct Forward *b)
1925 {
1926 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1927 		return 0;
1928 	if (a->listen_port != b->listen_port)
1929 		return 0;
1930 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1931 		return 0;
1932 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1933 		return 0;
1934 	if (a->connect_port != b->connect_port)
1935 		return 0;
1936 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1937 		return 0;
1938 	/* allocated_port and handle are not checked */
1939 	return 1;
1940 }
1941 
1942 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
1943 int
permitopen_port(const char * p)1944 permitopen_port(const char *p)
1945 {
1946 	int port;
1947 
1948 	if (strcmp(p, "*") == 0)
1949 		return FWD_PERMIT_ANY_PORT;
1950 	if ((port = a2port(p)) > 0)
1951 		return port;
1952 	return -1;
1953 }
1954 
1955 /* returns 1 if process is already daemonized, 0 otherwise */
1956 int
daemonized(void)1957 daemonized(void)
1958 {
1959 	int fd;
1960 
1961 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1962 		close(fd);
1963 		return 0;	/* have controlling terminal */
1964 	}
1965 	if (getppid() != 1)
1966 		return 0;	/* parent is not init */
1967 	if (getsid(0) != getpid())
1968 		return 0;	/* not session leader */
1969 	debug3("already daemonized");
1970 	return 1;
1971 }
1972 
1973 /*
1974  * Splits 's' into an argument vector. Handles quoted string and basic
1975  * escape characters (\\, \", \'). Caller must free the argument vector
1976  * and its members.
1977  */
1978 int
argv_split(const char * s,int * argcp,char *** argvp,int terminate_on_comment)1979 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
1980 {
1981 	int r = SSH_ERR_INTERNAL_ERROR;
1982 	int argc = 0, quote, i, j;
1983 	char *arg, **argv = xcalloc(1, sizeof(*argv));
1984 
1985 	*argvp = NULL;
1986 	*argcp = 0;
1987 
1988 	for (i = 0; s[i] != '\0'; i++) {
1989 		/* Skip leading whitespace */
1990 		if (s[i] == ' ' || s[i] == '\t')
1991 			continue;
1992 		if (terminate_on_comment && s[i] == '#')
1993 			break;
1994 		/* Start of a token */
1995 		quote = 0;
1996 
1997 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1998 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1999 		argv[argc] = NULL;
2000 
2001 		/* Copy the token in, removing escapes */
2002 		for (j = 0; s[i] != '\0'; i++) {
2003 			if (s[i] == '\\') {
2004 				if (s[i + 1] == '\'' ||
2005 				    s[i + 1] == '\"' ||
2006 				    s[i + 1] == '\\' ||
2007 				    (quote == 0 && s[i + 1] == ' ')) {
2008 					i++; /* Skip '\' */
2009 					arg[j++] = s[i];
2010 				} else {
2011 					/* Unrecognised escape */
2012 					arg[j++] = s[i];
2013 				}
2014 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
2015 				break; /* done */
2016 			else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
2017 				quote = s[i]; /* quote start */
2018 			else if (quote != 0 && s[i] == quote)
2019 				quote = 0; /* quote end */
2020 			else
2021 				arg[j++] = s[i];
2022 		}
2023 		if (s[i] == '\0') {
2024 			if (quote != 0) {
2025 				/* Ran out of string looking for close quote */
2026 				r = SSH_ERR_INVALID_FORMAT;
2027 				goto out;
2028 			}
2029 			break;
2030 		}
2031 	}
2032 	/* Success */
2033 	*argcp = argc;
2034 	*argvp = argv;
2035 	argc = 0;
2036 	argv = NULL;
2037 	r = 0;
2038  out:
2039 	if (argc != 0 && argv != NULL) {
2040 		for (i = 0; i < argc; i++)
2041 			free(argv[i]);
2042 		free(argv);
2043 	}
2044 	return r;
2045 }
2046 
2047 /*
2048  * Reassemble an argument vector into a string, quoting and escaping as
2049  * necessary. Caller must free returned string.
2050  */
2051 char *
argv_assemble(int argc,char ** argv)2052 argv_assemble(int argc, char **argv)
2053 {
2054 	int i, j, ws, r;
2055 	char c, *ret;
2056 	struct sshbuf *buf, *arg;
2057 
2058 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2059 		fatal_f("sshbuf_new failed");
2060 
2061 	for (i = 0; i < argc; i++) {
2062 		ws = 0;
2063 		sshbuf_reset(arg);
2064 		for (j = 0; argv[i][j] != '\0'; j++) {
2065 			r = 0;
2066 			c = argv[i][j];
2067 			switch (c) {
2068 			case ' ':
2069 			case '\t':
2070 				ws = 1;
2071 				r = sshbuf_put_u8(arg, c);
2072 				break;
2073 			case '\\':
2074 			case '\'':
2075 			case '"':
2076 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2077 					break;
2078 				/* FALLTHROUGH */
2079 			default:
2080 				r = sshbuf_put_u8(arg, c);
2081 				break;
2082 			}
2083 			if (r != 0)
2084 				fatal_fr(r, "sshbuf_put_u8");
2085 		}
2086 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2087 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2088 		    (r = sshbuf_putb(buf, arg)) != 0 ||
2089 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2090 			fatal_fr(r, "assemble");
2091 	}
2092 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2093 		fatal_f("malloc failed");
2094 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2095 	ret[sshbuf_len(buf)] = '\0';
2096 	sshbuf_free(buf);
2097 	sshbuf_free(arg);
2098 	return ret;
2099 }
2100 
2101 char *
argv_next(int * argcp,char *** argvp)2102 argv_next(int *argcp, char ***argvp)
2103 {
2104 	char *ret = (*argvp)[0];
2105 
2106 	if (*argcp > 0 && ret != NULL) {
2107 		(*argcp)--;
2108 		(*argvp)++;
2109 	}
2110 	return ret;
2111 }
2112 
2113 void
argv_consume(int * argcp)2114 argv_consume(int *argcp)
2115 {
2116 	*argcp = 0;
2117 }
2118 
2119 void
argv_free(char ** av,int ac)2120 argv_free(char **av, int ac)
2121 {
2122 	int i;
2123 
2124 	if (av == NULL)
2125 		return;
2126 	for (i = 0; i < ac; i++)
2127 		free(av[i]);
2128 	free(av);
2129 }
2130 
2131 /* Returns 0 if pid exited cleanly, non-zero otherwise */
2132 int
exited_cleanly(pid_t pid,const char * tag,const char * cmd,int quiet)2133 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2134 {
2135 	int status;
2136 
2137 	while (waitpid(pid, &status, 0) == -1) {
2138 		if (errno != EINTR) {
2139 			error("%s waitpid: %s", tag, strerror(errno));
2140 			return -1;
2141 		}
2142 	}
2143 	if (WIFSIGNALED(status)) {
2144 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2145 		return -1;
2146 	} else if (WEXITSTATUS(status) != 0) {
2147 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2148 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2149 		return -1;
2150 	}
2151 	return 0;
2152 }
2153 
2154 /*
2155  * Check a given path for security. This is defined as all components
2156  * of the path to the file must be owned by either the owner of
2157  * of the file or root and no directories must be group or world writable.
2158  *
2159  * XXX Should any specific check be done for sym links ?
2160  *
2161  * Takes a file name, its stat information (preferably from fstat() to
2162  * avoid races), the uid of the expected owner, their home directory and an
2163  * error buffer plus max size as arguments.
2164  *
2165  * Returns 0 on success and -1 on failure
2166  */
2167 int
safe_path(const char * name,struct stat * stp,const char * pw_dir,uid_t uid,char * err,size_t errlen)2168 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2169     uid_t uid, char *err, size_t errlen)
2170 {
2171 	char buf[PATH_MAX], homedir[PATH_MAX];
2172 	char *cp;
2173 	int comparehome = 0;
2174 	struct stat st;
2175 
2176 	if (realpath(name, buf) == NULL) {
2177 		snprintf(err, errlen, "realpath %s failed: %s", name,
2178 		    strerror(errno));
2179 		return -1;
2180 	}
2181 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2182 		comparehome = 1;
2183 
2184 	if (!S_ISREG(stp->st_mode)) {
2185 		snprintf(err, errlen, "%s is not a regular file", buf);
2186 		return -1;
2187 	}
2188 	if ((stp->st_uid != 0 && stp->st_uid != uid) ||
2189 	    (stp->st_mode & 022) != 0) {
2190 		snprintf(err, errlen, "bad ownership or modes for file %s",
2191 		    buf);
2192 		return -1;
2193 	}
2194 
2195 	/* for each component of the canonical path, walking upwards */
2196 	for (;;) {
2197 		if ((cp = dirname(buf)) == NULL) {
2198 			snprintf(err, errlen, "dirname() failed");
2199 			return -1;
2200 		}
2201 		strlcpy(buf, cp, sizeof(buf));
2202 
2203 		if (stat(buf, &st) == -1 ||
2204 		    (st.st_uid != 0 && st.st_uid != uid) ||
2205 		    (st.st_mode & 022) != 0) {
2206 			snprintf(err, errlen,
2207 			    "bad ownership or modes for directory %s", buf);
2208 			return -1;
2209 		}
2210 
2211 		/* If are past the homedir then we can stop */
2212 		if (comparehome && strcmp(homedir, buf) == 0)
2213 			break;
2214 
2215 		/*
2216 		 * dirname should always complete with a "/" path,
2217 		 * but we can be paranoid and check for "." too
2218 		 */
2219 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2220 			break;
2221 	}
2222 	return 0;
2223 }
2224 
2225 /*
2226  * Version of safe_path() that accepts an open file descriptor to
2227  * avoid races.
2228  *
2229  * Returns 0 on success and -1 on failure
2230  */
2231 int
safe_path_fd(int fd,const char * file,struct passwd * pw,char * err,size_t errlen)2232 safe_path_fd(int fd, const char *file, struct passwd *pw,
2233     char *err, size_t errlen)
2234 {
2235 	struct stat st;
2236 
2237 	/* check the open file to avoid races */
2238 	if (fstat(fd, &st) == -1) {
2239 		snprintf(err, errlen, "cannot stat file %s: %s",
2240 		    file, strerror(errno));
2241 		return -1;
2242 	}
2243 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2244 }
2245 
2246 /*
2247  * Sets the value of the given variable in the environment.  If the variable
2248  * already exists, its value is overridden.
2249  */
2250 void
child_set_env(char *** envp,u_int * envsizep,const char * name,const char * value)2251 child_set_env(char ***envp, u_int *envsizep, const char *name,
2252 	const char *value)
2253 {
2254 	char **env;
2255 	u_int envsize;
2256 	u_int i, namelen;
2257 
2258 	if (strchr(name, '=') != NULL) {
2259 		error("Invalid environment variable \"%.100s\"", name);
2260 		return;
2261 	}
2262 
2263 	/*
2264 	 * Find the slot where the value should be stored.  If the variable
2265 	 * already exists, we reuse the slot; otherwise we append a new slot
2266 	 * at the end of the array, expanding if necessary.
2267 	 */
2268 	env = *envp;
2269 	namelen = strlen(name);
2270 	for (i = 0; env[i]; i++)
2271 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2272 			break;
2273 	if (env[i]) {
2274 		/* Reuse the slot. */
2275 		free(env[i]);
2276 	} else {
2277 		/* New variable.  Expand if necessary. */
2278 		envsize = *envsizep;
2279 		if (i >= envsize - 1) {
2280 			if (envsize >= 1000)
2281 				fatal("child_set_env: too many env vars");
2282 			envsize += 50;
2283 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2284 			*envsizep = envsize;
2285 		}
2286 		/* Need to set the NULL pointer at end of array beyond the new slot. */
2287 		env[i + 1] = NULL;
2288 	}
2289 
2290 	/* Allocate space and format the variable in the appropriate slot. */
2291 	/* XXX xasprintf */
2292 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2293 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2294 }
2295 
2296 /*
2297  * Check and optionally lowercase a domain name, also removes trailing '.'
2298  * Returns 1 on success and 0 on failure, storing an error message in errstr.
2299  */
2300 int
valid_domain(char * name,int makelower,const char ** errstr)2301 valid_domain(char *name, int makelower, const char **errstr)
2302 {
2303 	size_t i, l = strlen(name);
2304 	u_char c, last = '\0';
2305 	static char errbuf[256];
2306 
2307 	if (l == 0) {
2308 		strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2309 		goto bad;
2310 	}
2311 	if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2312 		snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2313 		    "starts with invalid character", name);
2314 		goto bad;
2315 	}
2316 	for (i = 0; i < l; i++) {
2317 		c = tolower((u_char)name[i]);
2318 		if (makelower)
2319 			name[i] = (char)c;
2320 		if (last == '.' && c == '.') {
2321 			snprintf(errbuf, sizeof(errbuf), "domain name "
2322 			    "\"%.100s\" contains consecutive separators", name);
2323 			goto bad;
2324 		}
2325 		if (c != '.' && c != '-' && !isalnum(c) &&
2326 		    c != '_') /* technically invalid, but common */ {
2327 			snprintf(errbuf, sizeof(errbuf), "domain name "
2328 			    "\"%.100s\" contains invalid characters", name);
2329 			goto bad;
2330 		}
2331 		last = c;
2332 	}
2333 	if (name[l - 1] == '.')
2334 		name[l - 1] = '\0';
2335 	if (errstr != NULL)
2336 		*errstr = NULL;
2337 	return 1;
2338 bad:
2339 	if (errstr != NULL)
2340 		*errstr = errbuf;
2341 	return 0;
2342 }
2343 
2344 /*
2345  * Verify that a environment variable name (not including initial '$') is
2346  * valid; consisting of one or more alphanumeric or underscore characters only.
2347  * Returns 1 on valid, 0 otherwise.
2348  */
2349 int
valid_env_name(const char * name)2350 valid_env_name(const char *name)
2351 {
2352 	const char *cp;
2353 
2354 	if (name[0] == '\0')
2355 		return 0;
2356 	for (cp = name; *cp != '\0'; cp++) {
2357 		if (!isalnum((u_char)*cp) && *cp != '_')
2358 			return 0;
2359 	}
2360 	return 1;
2361 }
2362 
2363 const char *
atoi_err(const char * nptr,int * val)2364 atoi_err(const char *nptr, int *val)
2365 {
2366 	const char *errstr = NULL;
2367 
2368 	if (nptr == NULL || *nptr == '\0')
2369 		return "missing";
2370 	*val = strtonum(nptr, 0, INT_MAX, &errstr);
2371 	return errstr;
2372 }
2373 
2374 int
parse_absolute_time(const char * s,uint64_t * tp)2375 parse_absolute_time(const char *s, uint64_t *tp)
2376 {
2377 	struct tm tm;
2378 	time_t tt;
2379 	char buf[32];
2380 	const char *fmt, *cp;
2381 	size_t l;
2382 	int is_utc = 0;
2383 
2384 	*tp = 0;
2385 
2386 	l = strlen(s);
2387 	if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2388 		is_utc = 1;
2389 		l--;
2390 	} else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2391 		is_utc = 1;
2392 		l -= 3;
2393 	}
2394 	/*
2395 	 * POSIX strptime says "The application shall ensure that there
2396 	 * is white-space or other non-alphanumeric characters between
2397 	 * any two conversion specifications" so arrange things this way.
2398 	 */
2399 	switch (l) {
2400 	case 8: /* YYYYMMDD */
2401 		fmt = "%Y-%m-%d";
2402 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2403 		break;
2404 	case 12: /* YYYYMMDDHHMM */
2405 		fmt = "%Y-%m-%dT%H:%M";
2406 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2407 		    s, s + 4, s + 6, s + 8, s + 10);
2408 		break;
2409 	case 14: /* YYYYMMDDHHMMSS */
2410 		fmt = "%Y-%m-%dT%H:%M:%S";
2411 		snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2412 		    s, s + 4, s + 6, s + 8, s + 10, s + 12);
2413 		break;
2414 	default:
2415 		return SSH_ERR_INVALID_FORMAT;
2416 	}
2417 
2418 	memset(&tm, 0, sizeof(tm));
2419 	if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2420 		return SSH_ERR_INVALID_FORMAT;
2421 	if (is_utc) {
2422 		if ((tt = timegm(&tm)) < 0)
2423 			return SSH_ERR_INVALID_FORMAT;
2424 	} else {
2425 		if ((tt = mktime(&tm)) < 0)
2426 			return SSH_ERR_INVALID_FORMAT;
2427 	}
2428 	/* success */
2429 	*tp = (uint64_t)tt;
2430 	return 0;
2431 }
2432 
2433 void
format_absolute_time(uint64_t t,char * buf,size_t len)2434 format_absolute_time(uint64_t t, char *buf, size_t len)
2435 {
2436 	time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2437 	struct tm tm;
2438 
2439 	localtime_r(&tt, &tm);
2440 	strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2441 }
2442 
2443 /*
2444  * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
2445  * Returns 0 on success or non-zero on failure.
2446  * Caller must free *typep.
2447  */
2448 int
parse_pattern_interval(const char * s,char ** typep,int * secsp)2449 parse_pattern_interval(const char *s, char **typep, int *secsp)
2450 {
2451 	char *cp, *sdup;
2452 	int secs;
2453 
2454 	if (typep != NULL)
2455 		*typep = NULL;
2456 	if (secsp != NULL)
2457 		*secsp = 0;
2458 	if (s == NULL)
2459 		return -1;
2460 	sdup = xstrdup(s);
2461 
2462 	if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
2463 		free(sdup);
2464 		return -1;
2465 	}
2466 	*cp++ = '\0';
2467 	if ((secs = convtime(cp)) < 0) {
2468 		free(sdup);
2469 		return -1;
2470 	}
2471 	/* success */
2472 	if (typep != NULL)
2473 		*typep = xstrdup(sdup);
2474 	if (secsp != NULL)
2475 		*secsp = secs;
2476 	free(sdup);
2477 	return 0;
2478 }
2479 
2480 /* check if path is absolute */
2481 int
path_absolute(const char * path)2482 path_absolute(const char *path)
2483 {
2484 	return (*path == '/') ? 1 : 0;
2485 }
2486 
2487 void
skip_space(char ** cpp)2488 skip_space(char **cpp)
2489 {
2490 	char *cp;
2491 
2492 	for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2493 		;
2494 	*cpp = cp;
2495 }
2496 
2497 /* authorized_key-style options parsing helpers */
2498 
2499 /*
2500  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2501  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2502  * if negated option matches.
2503  * If the option or negated option matches, then *optsp is updated to
2504  * point to the first character after the option.
2505  */
2506 int
opt_flag(const char * opt,int allow_negate,const char ** optsp)2507 opt_flag(const char *opt, int allow_negate, const char **optsp)
2508 {
2509 	size_t opt_len = strlen(opt);
2510 	const char *opts = *optsp;
2511 	int negate = 0;
2512 
2513 	if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2514 		opts += 3;
2515 		negate = 1;
2516 	}
2517 	if (strncasecmp(opts, opt, opt_len) == 0) {
2518 		*optsp = opts + opt_len;
2519 		return negate ? 0 : 1;
2520 	}
2521 	return -1;
2522 }
2523 
2524 char *
opt_dequote(const char ** sp,const char ** errstrp)2525 opt_dequote(const char **sp, const char **errstrp)
2526 {
2527 	const char *s = *sp;
2528 	char *ret;
2529 	size_t i;
2530 
2531 	*errstrp = NULL;
2532 	if (*s != '"') {
2533 		*errstrp = "missing start quote";
2534 		return NULL;
2535 	}
2536 	s++;
2537 	if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2538 		*errstrp = "memory allocation failed";
2539 		return NULL;
2540 	}
2541 	for (i = 0; *s != '\0' && *s != '"';) {
2542 		if (s[0] == '\\' && s[1] == '"')
2543 			s++;
2544 		ret[i++] = *s++;
2545 	}
2546 	if (*s == '\0') {
2547 		*errstrp = "missing end quote";
2548 		free(ret);
2549 		return NULL;
2550 	}
2551 	ret[i] = '\0';
2552 	s++;
2553 	*sp = s;
2554 	return ret;
2555 }
2556 
2557 int
opt_match(const char ** opts,const char * term)2558 opt_match(const char **opts, const char *term)
2559 {
2560 	if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2561 	    (*opts)[strlen(term)] == '=') {
2562 		*opts += strlen(term) + 1;
2563 		return 1;
2564 	}
2565 	return 0;
2566 }
2567 
2568 void
opt_array_append2(const char * file,const int line,const char * directive,char *** array,int ** iarray,u_int * lp,const char * s,int i)2569 opt_array_append2(const char *file, const int line, const char *directive,
2570     char ***array, int **iarray, u_int *lp, const char *s, int i)
2571 {
2572 
2573 	if (*lp >= INT_MAX)
2574 		fatal("%s line %d: Too many %s entries", file, line, directive);
2575 
2576 	if (iarray != NULL) {
2577 		*iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2578 		    sizeof(**iarray));
2579 		(*iarray)[*lp] = i;
2580 	}
2581 
2582 	*array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2583 	(*array)[*lp] = xstrdup(s);
2584 	(*lp)++;
2585 }
2586 
2587 void
opt_array_append(const char * file,const int line,const char * directive,char *** array,u_int * lp,const char * s)2588 opt_array_append(const char *file, const int line, const char *directive,
2589     char ***array, u_int *lp, const char *s)
2590 {
2591 	opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2592 }
2593 
2594 void
opt_array_free2(char ** array,int ** iarray,u_int l)2595 opt_array_free2(char **array, int **iarray, u_int l)
2596 {
2597 	u_int i;
2598 
2599 	if (array == NULL || l == 0)
2600 		return;
2601 	for (i = 0; i < l; i++)
2602 		free(array[i]);
2603 	free(array);
2604 	free(iarray);
2605 }
2606 
2607 sshsig_t
ssh_signal(int signum,sshsig_t handler)2608 ssh_signal(int signum, sshsig_t handler)
2609 {
2610 	struct sigaction sa, osa;
2611 
2612 	/* mask all other signals while in handler */
2613 	memset(&sa, 0, sizeof(sa));
2614 	sa.sa_handler = handler;
2615 	sigfillset(&sa.sa_mask);
2616 	if (signum != SIGALRM)
2617 		sa.sa_flags = SA_RESTART;
2618 	if (sigaction(signum, &sa, &osa) == -1) {
2619 		debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2620 		return SIG_ERR;
2621 	}
2622 	return osa.sa_handler;
2623 }
2624 
2625 int
stdfd_devnull(int do_stdin,int do_stdout,int do_stderr)2626 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2627 {
2628 	int devnull, ret = 0;
2629 
2630 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2631 		error_f("open %s: %s", _PATH_DEVNULL,
2632 		    strerror(errno));
2633 		return -1;
2634 	}
2635 	if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2636 	    (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2637 	    (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2638 		error_f("dup2: %s", strerror(errno));
2639 		ret = -1;
2640 	}
2641 	if (devnull > STDERR_FILENO)
2642 		close(devnull);
2643 	return ret;
2644 }
2645 
2646 /*
2647  * Runs command in a subprocess with a minimal environment.
2648  * Returns pid on success, 0 on failure.
2649  * The child stdout and stderr maybe captured, left attached or sent to
2650  * /dev/null depending on the contents of flags.
2651  * "tag" is prepended to log messages.
2652  * NB. "command" is only used for logging; the actual command executed is
2653  * av[0].
2654  */
2655 pid_t
subprocess(const char * tag,const char * command,int ac,char ** av,FILE ** child,u_int flags,struct passwd * pw,privdrop_fn * drop_privs,privrestore_fn * restore_privs)2656 subprocess(const char *tag, const char *command,
2657     int ac, char **av, FILE **child, u_int flags,
2658     struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2659 {
2660 	FILE *f = NULL;
2661 	struct stat st;
2662 	int fd, devnull, p[2], i;
2663 	pid_t pid;
2664 	char *cp, errmsg[512];
2665 	u_int nenv = 0;
2666 	char **env = NULL;
2667 
2668 	/* If dropping privs, then must specify user and restore function */
2669 	if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2670 		error("%s: inconsistent arguments", tag); /* XXX fatal? */
2671 		return 0;
2672 	}
2673 	if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2674 		error("%s: no user for current uid", tag);
2675 		return 0;
2676 	}
2677 	if (child != NULL)
2678 		*child = NULL;
2679 
2680 	debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2681 	    tag, command, pw->pw_name, flags);
2682 
2683 	/* Check consistency */
2684 	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2685 	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2686 		error_f("inconsistent flags");
2687 		return 0;
2688 	}
2689 	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2690 		error_f("inconsistent flags/output");
2691 		return 0;
2692 	}
2693 
2694 	/*
2695 	 * If executing an explicit binary, then verify the it exists
2696 	 * and appears safe-ish to execute
2697 	 */
2698 	if (!path_absolute(av[0])) {
2699 		error("%s path is not absolute", tag);
2700 		return 0;
2701 	}
2702 	if (drop_privs != NULL)
2703 		drop_privs(pw);
2704 	if (stat(av[0], &st) == -1) {
2705 		error("Could not stat %s \"%s\": %s", tag,
2706 		    av[0], strerror(errno));
2707 		goto restore_return;
2708 	}
2709 	if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2710 	    safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2711 		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2712 		goto restore_return;
2713 	}
2714 	/* Prepare to keep the child's stdout if requested */
2715 	if (pipe(p) == -1) {
2716 		error("%s: pipe: %s", tag, strerror(errno));
2717  restore_return:
2718 		if (restore_privs != NULL)
2719 			restore_privs();
2720 		return 0;
2721 	}
2722 	if (restore_privs != NULL)
2723 		restore_privs();
2724 
2725 	switch ((pid = fork())) {
2726 	case -1: /* error */
2727 		error("%s: fork: %s", tag, strerror(errno));
2728 		close(p[0]);
2729 		close(p[1]);
2730 		return 0;
2731 	case 0: /* child */
2732 		/* Prepare a minimal environment for the child. */
2733 		if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2734 			nenv = 5;
2735 			env = xcalloc(sizeof(*env), nenv);
2736 			child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2737 			child_set_env(&env, &nenv, "USER", pw->pw_name);
2738 			child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2739 			child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2740 			if ((cp = getenv("LANG")) != NULL)
2741 				child_set_env(&env, &nenv, "LANG", cp);
2742 		}
2743 
2744 		for (i = 1; i < NSIG; i++)
2745 			ssh_signal(i, SIG_DFL);
2746 
2747 		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2748 			error("%s: open %s: %s", tag, _PATH_DEVNULL,
2749 			    strerror(errno));
2750 			_exit(1);
2751 		}
2752 		if (dup2(devnull, STDIN_FILENO) == -1) {
2753 			error("%s: dup2: %s", tag, strerror(errno));
2754 			_exit(1);
2755 		}
2756 
2757 		/* Set up stdout as requested; leave stderr in place for now. */
2758 		fd = -1;
2759 		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2760 			fd = p[1];
2761 		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2762 			fd = devnull;
2763 		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2764 			error("%s: dup2: %s", tag, strerror(errno));
2765 			_exit(1);
2766 		}
2767 		closefrom(STDERR_FILENO + 1);
2768 
2769 #ifdef __NetBSD__
2770 #define setresgid(a, b, c)      setgid(a)
2771 #define setresuid(a, b, c)      setuid(a)
2772 #endif
2773 
2774 		if (geteuid() == 0 &&
2775 		    initgroups(pw->pw_name, pw->pw_gid) == -1) {
2776 			error("%s: initgroups(%s, %u): %s", tag,
2777 			    pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2778 			_exit(1);
2779 		}
2780 		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2781 			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2782 			    strerror(errno));
2783 			_exit(1);
2784 		}
2785 		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2786 			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2787 			    strerror(errno));
2788 			_exit(1);
2789 		}
2790 		/* stdin is pointed to /dev/null at this point */
2791 		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2792 		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2793 			error("%s: dup2: %s", tag, strerror(errno));
2794 			_exit(1);
2795 		}
2796 		if (env != NULL)
2797 			execve(av[0], av, env);
2798 		else
2799 			execv(av[0], av);
2800 		error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2801 		    command, strerror(errno));
2802 		_exit(127);
2803 	default: /* parent */
2804 		break;
2805 	}
2806 
2807 	close(p[1]);
2808 	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2809 		close(p[0]);
2810 	else if ((f = fdopen(p[0], "r")) == NULL) {
2811 		error("%s: fdopen: %s", tag, strerror(errno));
2812 		close(p[0]);
2813 		/* Don't leave zombie child */
2814 		kill(pid, SIGTERM);
2815 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2816 			;
2817 		return 0;
2818 	}
2819 	/* Success */
2820 	debug3_f("%s pid %ld", tag, (long)pid);
2821 	if (child != NULL)
2822 		*child = f;
2823 	return pid;
2824 }
2825 
2826 const char *
lookup_env_in_list(const char * env,char * const * envs,size_t nenvs)2827 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2828 {
2829 	size_t i, envlen;
2830 
2831 	envlen = strlen(env);
2832 	for (i = 0; i < nenvs; i++) {
2833 		if (strncmp(envs[i], env, envlen) == 0 &&
2834 		    envs[i][envlen] == '=') {
2835 			return envs[i] + envlen + 1;
2836 		}
2837 	}
2838 	return NULL;
2839 }
2840 
2841 const char *
lookup_setenv_in_list(const char * env,char * const * envs,size_t nenvs)2842 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2843 {
2844 	char *name, *cp;
2845 	const char *ret;
2846 
2847 	name = xstrdup(env);
2848 	if ((cp = strchr(name, '=')) == NULL) {
2849 		free(name);
2850 		return NULL; /* not env=val */
2851 	}
2852 	*cp = '\0';
2853 	ret = lookup_env_in_list(name, envs, nenvs);
2854 	free(name);
2855 	return ret;
2856 }
2857 
2858 /*
2859  * Helpers for managing poll(2)/ppoll(2) timeouts
2860  * Will remember the earliest deadline and return it for use in poll/ppoll.
2861  */
2862 
2863 /* Initialise a poll/ppoll timeout with an indefinite deadline */
2864 void
ptimeout_init(struct timespec * pt)2865 ptimeout_init(struct timespec *pt)
2866 {
2867 	/*
2868 	 * Deliberately invalid for ppoll(2).
2869 	 * Will be converted to NULL in ptimeout_get_tspec() later.
2870 	 */
2871 	pt->tv_sec = -1;
2872 	pt->tv_nsec = 0;
2873 }
2874 
2875 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2876 void
ptimeout_deadline_sec(struct timespec * pt,long sec)2877 ptimeout_deadline_sec(struct timespec *pt, long sec)
2878 {
2879 	if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2880 		pt->tv_sec = sec;
2881 		pt->tv_nsec = 0;
2882 	}
2883 }
2884 
2885 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2886 static void
ptimeout_deadline_tsp(struct timespec * pt,struct timespec * p)2887 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2888 {
2889 	if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2890 		*pt = *p;
2891 }
2892 
2893 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2894 void
ptimeout_deadline_ms(struct timespec * pt,long ms)2895 ptimeout_deadline_ms(struct timespec *pt, long ms)
2896 {
2897 	struct timespec p;
2898 
2899 	p.tv_sec = ms / 1000;
2900 	p.tv_nsec = (ms % 1000) * 1000000;
2901 	ptimeout_deadline_tsp(pt, &p);
2902 }
2903 
2904 /* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
2905 void
ptimeout_deadline_monotime_tsp(struct timespec * pt,struct timespec * when)2906 ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
2907 {
2908 	struct timespec now, t;
2909 
2910 	monotime_ts(&now);
2911 
2912 	if (timespeccmp(&now, when, >=)) {
2913 		/* 'when' is now or in the past. Timeout ASAP */
2914 		pt->tv_sec = 0;
2915 		pt->tv_nsec = 0;
2916 	} else {
2917 		timespecsub(when, &now, &t);
2918 		ptimeout_deadline_tsp(pt, &t);
2919 	}
2920 }
2921 
2922 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
2923 void
ptimeout_deadline_monotime(struct timespec * pt,time_t when)2924 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
2925 {
2926 	struct timespec t;
2927 
2928 	t.tv_sec = when;
2929 	t.tv_nsec = 0;
2930 	ptimeout_deadline_monotime_tsp(pt, &t);
2931 }
2932 
2933 /* Get a poll(2) timeout value in milliseconds */
2934 int
ptimeout_get_ms(struct timespec * pt)2935 ptimeout_get_ms(struct timespec *pt)
2936 {
2937 	if (pt->tv_sec == -1)
2938 		return -1;
2939 	if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
2940 		return INT_MAX;
2941 	return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
2942 }
2943 
2944 /* Get a ppoll(2) timeout value as a timespec pointer */
2945 struct timespec *
ptimeout_get_tsp(struct timespec * pt)2946 ptimeout_get_tsp(struct timespec *pt)
2947 {
2948 	return pt->tv_sec == -1 ? NULL : pt;
2949 }
2950 
2951 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
2952 int
ptimeout_isset(struct timespec * pt)2953 ptimeout_isset(struct timespec *pt)
2954 {
2955 	return pt->tv_sec != -1;
2956 }
2957 
2958 /*
2959  * Returns zero if the library at 'path' contains symbol 's', nonzero
2960  * otherwise.
2961  */
2962 int
lib_contains_symbol(const char * path,const char * s)2963 lib_contains_symbol(const char *path, const char *s)
2964 {
2965 	struct nlist nl[2];
2966 	int ret = -1, r;
2967 	char *name;
2968 
2969 	memset(nl, 0, sizeof(nl));
2970 	nl[0].n_name = name = xstrdup(s);
2971 	nl[1].n_name = NULL;
2972 	if ((r = nlist(path, nl)) == -1) {
2973 		error_f("nlist failed for %s", path);
2974 		goto out;
2975 	}
2976 	if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
2977 		error_f("library %s does not contain symbol %s", path, s);
2978 		goto out;
2979 	}
2980 	/* success */
2981 	ret = 0;
2982  out:
2983 	free(name);
2984 	return ret;
2985 }
2986 
2987 int
signal_is_crash(int sig)2988 signal_is_crash(int sig)
2989 {
2990 	switch (sig) {
2991 	case SIGSEGV:
2992 	case SIGBUS:
2993 	case SIGTRAP:
2994 	case SIGSYS:
2995 	case SIGFPE:
2996 	case SIGILL:
2997 	case SIGABRT:
2998 		return 1;
2999 	}
3000 	return 0;
3001 }
3002