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