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