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