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