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