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