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