Home | History | Annotate | Line # | Download | only in dist
misc.c revision 1.16
      1  1.15  christos /*	$NetBSD: misc.c,v 1.16 2017/10/07 19:39:19 christos Exp $	*/
      2  1.16  christos /* $OpenBSD: misc.c,v 1.113 2017/08/18 05:48:04 djm Exp $ */
      3   1.1  christos /*
      4   1.1  christos  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
      5   1.1  christos  * Copyright (c) 2005,2006 Damien Miller.  All rights reserved.
      6   1.1  christos  *
      7   1.1  christos  * Redistribution and use in source and binary forms, with or without
      8   1.1  christos  * modification, are permitted provided that the following conditions
      9   1.1  christos  * are met:
     10   1.1  christos  * 1. Redistributions of source code must retain the above copyright
     11   1.1  christos  *    notice, this list of conditions and the following disclaimer.
     12   1.1  christos  * 2. Redistributions in binary form must reproduce the above copyright
     13   1.1  christos  *    notice, this list of conditions and the following disclaimer in the
     14   1.1  christos  *    documentation and/or other materials provided with the distribution.
     15   1.1  christos  *
     16   1.1  christos  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17   1.1  christos  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18   1.1  christos  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19   1.1  christos  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20   1.1  christos  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     21   1.1  christos  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22   1.1  christos  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23   1.1  christos  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24   1.1  christos  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     25   1.1  christos  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26   1.1  christos  */
     27   1.1  christos 
     28   1.2  christos #include "includes.h"
     29   1.8  christos __RCSID("$NetBSD: misc.c,v 1.16 2017/10/07 19:39:19 christos Exp $");
     30   1.1  christos #include <sys/types.h>
     31   1.1  christos #include <sys/ioctl.h>
     32   1.1  christos #include <sys/socket.h>
     33  1.16  christos #include <sys/stat.h>
     34  1.12  christos #include <sys/time.h>
     35  1.16  christos #include <sys/wait.h>
     36   1.9  christos #include <sys/un.h>
     37   1.1  christos 
     38   1.1  christos #include <net/if.h>
     39   1.2  christos #include <net/if_tun.h>
     40   1.1  christos #include <netinet/in.h>
     41   1.5  christos #include <netinet/ip.h>
     42   1.1  christos #include <netinet/tcp.h>
     43   1.1  christos 
     44   1.9  christos #include <ctype.h>
     45   1.1  christos #include <errno.h>
     46   1.1  christos #include <fcntl.h>
     47   1.1  christos #include <netdb.h>
     48   1.1  christos #include <paths.h>
     49   1.1  christos #include <pwd.h>
     50  1.16  christos #include <libgen.h>
     51  1.10  christos #include <limits.h>
     52  1.16  christos #include <signal.h>
     53   1.1  christos #include <stdarg.h>
     54   1.1  christos #include <stdio.h>
     55   1.1  christos #include <stdlib.h>
     56   1.1  christos #include <string.h>
     57   1.1  christos #include <unistd.h>
     58   1.1  christos 
     59   1.1  christos #include "xmalloc.h"
     60   1.1  christos #include "misc.h"
     61   1.1  christos #include "log.h"
     62   1.1  christos #include "ssh.h"
     63  1.16  christos #include "sshbuf.h"
     64  1.16  christos #include "ssherr.h"
     65  1.16  christos #include "uidswap.h"
     66   1.1  christos 
     67   1.1  christos /* remove newline at end of string */
     68   1.1  christos char *
     69   1.1  christos chop(char *s)
     70   1.1  christos {
     71   1.1  christos 	char *t = s;
     72   1.1  christos 	while (*t) {
     73   1.1  christos 		if (*t == '\n' || *t == '\r') {
     74   1.1  christos 			*t = '\0';
     75   1.1  christos 			return s;
     76   1.1  christos 		}
     77   1.1  christos 		t++;
     78   1.1  christos 	}
     79   1.1  christos 	return s;
     80   1.1  christos 
     81   1.1  christos }
     82   1.1  christos 
     83   1.1  christos /* set/unset filedescriptor to non-blocking */
     84   1.1  christos int
     85   1.1  christos set_nonblock(int fd)
     86   1.1  christos {
     87   1.1  christos 	int val;
     88   1.1  christos 
     89  1.13  christos 	val = fcntl(fd, F_GETFL);
     90   1.1  christos 	if (val < 0) {
     91  1.13  christos 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
     92   1.1  christos 		return (-1);
     93   1.1  christos 	}
     94   1.1  christos 	if (val & O_NONBLOCK) {
     95   1.1  christos 		debug3("fd %d is O_NONBLOCK", fd);
     96   1.1  christos 		return (0);
     97   1.1  christos 	}
     98   1.1  christos 	debug2("fd %d setting O_NONBLOCK", fd);
     99   1.1  christos 	val |= O_NONBLOCK;
    100   1.1  christos 	if (fcntl(fd, F_SETFL, val) == -1) {
    101   1.1  christos 		debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
    102   1.1  christos 		    strerror(errno));
    103   1.1  christos 		return (-1);
    104   1.1  christos 	}
    105   1.1  christos 	return (0);
    106   1.1  christos }
    107   1.1  christos 
    108   1.1  christos int
    109   1.1  christos unset_nonblock(int fd)
    110   1.1  christos {
    111   1.1  christos 	int val;
    112   1.1  christos 
    113  1.13  christos 	val = fcntl(fd, F_GETFL);
    114   1.1  christos 	if (val < 0) {
    115  1.13  christos 		error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
    116   1.1  christos 		return (-1);
    117   1.1  christos 	}
    118   1.1  christos 	if (!(val & O_NONBLOCK)) {
    119   1.1  christos 		debug3("fd %d is not O_NONBLOCK", fd);
    120   1.1  christos 		return (0);
    121   1.1  christos 	}
    122   1.1  christos 	debug("fd %d clearing O_NONBLOCK", fd);
    123   1.1  christos 	val &= ~O_NONBLOCK;
    124   1.1  christos 	if (fcntl(fd, F_SETFL, val) == -1) {
    125   1.1  christos 		debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
    126   1.1  christos 		    fd, strerror(errno));
    127   1.1  christos 		return (-1);
    128   1.1  christos 	}
    129   1.1  christos 	return (0);
    130   1.1  christos }
    131   1.1  christos 
    132   1.1  christos const char *
    133   1.1  christos ssh_gai_strerror(int gaierr)
    134   1.1  christos {
    135   1.8  christos 	if (gaierr == EAI_SYSTEM && errno != 0)
    136   1.1  christos 		return strerror(errno);
    137   1.1  christos 	return gai_strerror(gaierr);
    138   1.1  christos }
    139   1.1  christos 
    140   1.1  christos /* disable nagle on socket */
    141   1.1  christos void
    142   1.1  christos set_nodelay(int fd)
    143   1.1  christos {
    144   1.1  christos 	int opt;
    145   1.1  christos 	socklen_t optlen;
    146   1.1  christos 
    147   1.1  christos 	optlen = sizeof opt;
    148   1.1  christos 	if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
    149   1.1  christos 		debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
    150   1.1  christos 		return;
    151   1.1  christos 	}
    152   1.1  christos 	if (opt == 1) {
    153   1.1  christos 		debug2("fd %d is TCP_NODELAY", fd);
    154   1.1  christos 		return;
    155   1.1  christos 	}
    156   1.1  christos 	opt = 1;
    157   1.1  christos 	debug2("fd %d setting TCP_NODELAY", fd);
    158   1.1  christos 	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
    159   1.1  christos 		error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
    160   1.1  christos }
    161   1.1  christos 
    162   1.1  christos /* Characters considered whitespace in strsep calls. */
    163   1.1  christos #define WHITESPACE " \t\r\n"
    164   1.1  christos #define QUOTE	"\""
    165   1.1  christos 
    166   1.1  christos /* return next token in configuration line */
    167   1.1  christos char *
    168   1.1  christos strdelim(char **s)
    169   1.1  christos {
    170   1.1  christos 	char *old;
    171   1.1  christos 	int wspace = 0;
    172   1.1  christos 
    173   1.1  christos 	if (*s == NULL)
    174   1.1  christos 		return NULL;
    175   1.1  christos 
    176   1.1  christos 	old = *s;
    177   1.1  christos 
    178   1.1  christos 	*s = strpbrk(*s, WHITESPACE QUOTE "=");
    179   1.1  christos 	if (*s == NULL)
    180   1.1  christos 		return (old);
    181   1.1  christos 
    182   1.1  christos 	if (*s[0] == '\"') {
    183   1.1  christos 		memmove(*s, *s + 1, strlen(*s)); /* move nul too */
    184   1.1  christos 		/* Find matching quote */
    185   1.1  christos 		if ((*s = strpbrk(*s, QUOTE)) == NULL) {
    186   1.1  christos 			return (NULL);		/* no matching quote */
    187   1.1  christos 		} else {
    188   1.1  christos 			*s[0] = '\0';
    189   1.4      adam 			*s += strspn(*s + 1, WHITESPACE) + 1;
    190   1.1  christos 			return (old);
    191   1.1  christos 		}
    192   1.1  christos 	}
    193   1.1  christos 
    194   1.1  christos 	/* Allow only one '=' to be skipped */
    195   1.1  christos 	if (*s[0] == '=')
    196   1.1  christos 		wspace = 1;
    197   1.1  christos 	*s[0] = '\0';
    198   1.1  christos 
    199   1.1  christos 	/* Skip any extra whitespace after first token */
    200   1.1  christos 	*s += strspn(*s + 1, WHITESPACE) + 1;
    201   1.1  christos 	if (*s[0] == '=' && !wspace)
    202   1.1  christos 		*s += strspn(*s + 1, WHITESPACE) + 1;
    203   1.1  christos 
    204   1.1  christos 	return (old);
    205   1.1  christos }
    206   1.1  christos 
    207   1.1  christos struct passwd *
    208   1.1  christos pwcopy(struct passwd *pw)
    209   1.1  christos {
    210   1.1  christos 	struct passwd *copy = xcalloc(1, sizeof(*copy));
    211   1.1  christos 
    212   1.1  christos 	copy->pw_name = xstrdup(pw->pw_name);
    213   1.1  christos 	copy->pw_passwd = xstrdup(pw->pw_passwd);
    214   1.1  christos 	copy->pw_gecos = xstrdup(pw->pw_gecos);
    215   1.1  christos 	copy->pw_uid = pw->pw_uid;
    216   1.1  christos 	copy->pw_gid = pw->pw_gid;
    217   1.1  christos 	copy->pw_expire = pw->pw_expire;
    218   1.1  christos 	copy->pw_change = pw->pw_change;
    219   1.1  christos 	copy->pw_class = xstrdup(pw->pw_class);
    220   1.1  christos 	copy->pw_dir = xstrdup(pw->pw_dir);
    221   1.1  christos 	copy->pw_shell = xstrdup(pw->pw_shell);
    222   1.1  christos 	return copy;
    223   1.1  christos }
    224   1.1  christos 
    225   1.1  christos /*
    226   1.1  christos  * Convert ASCII string to TCP/IP port number.
    227   1.1  christos  * Port must be >=0 and <=65535.
    228   1.1  christos  * Return -1 if invalid.
    229   1.1  christos  */
    230   1.1  christos int
    231   1.1  christos a2port(const char *s)
    232   1.1  christos {
    233   1.1  christos 	long long port;
    234   1.1  christos 	const char *errstr;
    235   1.1  christos 
    236   1.1  christos 	port = strtonum(s, 0, 65535, &errstr);
    237   1.1  christos 	if (errstr != NULL)
    238   1.1  christos 		return -1;
    239   1.1  christos 	return (int)port;
    240   1.1  christos }
    241   1.1  christos 
    242   1.1  christos int
    243   1.1  christos a2tun(const char *s, int *remote)
    244   1.1  christos {
    245   1.1  christos 	const char *errstr = NULL;
    246   1.1  christos 	char *sp, *ep;
    247   1.1  christos 	int tun;
    248   1.1  christos 
    249   1.1  christos 	if (remote != NULL) {
    250   1.1  christos 		*remote = SSH_TUNID_ANY;
    251   1.1  christos 		sp = xstrdup(s);
    252   1.1  christos 		if ((ep = strchr(sp, ':')) == NULL) {
    253   1.8  christos 			free(sp);
    254   1.1  christos 			return (a2tun(s, NULL));
    255   1.1  christos 		}
    256   1.1  christos 		ep[0] = '\0'; ep++;
    257   1.1  christos 		*remote = a2tun(ep, NULL);
    258   1.1  christos 		tun = a2tun(sp, NULL);
    259   1.8  christos 		free(sp);
    260   1.1  christos 		return (*remote == SSH_TUNID_ERR ? *remote : tun);
    261   1.1  christos 	}
    262   1.1  christos 
    263   1.1  christos 	if (strcasecmp(s, "any") == 0)
    264   1.1  christos 		return (SSH_TUNID_ANY);
    265   1.1  christos 
    266   1.1  christos 	tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
    267   1.1  christos 	if (errstr != NULL)
    268   1.1  christos 		return (SSH_TUNID_ERR);
    269   1.1  christos 
    270   1.1  christos 	return (tun);
    271   1.1  christos }
    272   1.1  christos 
    273   1.1  christos #define SECONDS		1
    274   1.1  christos #define MINUTES		(SECONDS * 60)
    275   1.1  christos #define HOURS		(MINUTES * 60)
    276   1.1  christos #define DAYS		(HOURS * 24)
    277   1.1  christos #define WEEKS		(DAYS * 7)
    278   1.1  christos 
    279   1.1  christos /*
    280   1.1  christos  * Convert a time string into seconds; format is
    281   1.1  christos  * a sequence of:
    282   1.1  christos  *      time[qualifier]
    283   1.1  christos  *
    284   1.1  christos  * Valid time qualifiers are:
    285   1.1  christos  *      <none>  seconds
    286   1.1  christos  *      s|S     seconds
    287   1.1  christos  *      m|M     minutes
    288   1.1  christos  *      h|H     hours
    289   1.1  christos  *      d|D     days
    290   1.1  christos  *      w|W     weeks
    291   1.1  christos  *
    292   1.1  christos  * Examples:
    293   1.1  christos  *      90m     90 minutes
    294   1.1  christos  *      1h30m   90 minutes
    295   1.1  christos  *      2d      2 days
    296   1.1  christos  *      1w      1 week
    297   1.1  christos  *
    298   1.1  christos  * Return -1 if time string is invalid.
    299   1.1  christos  */
    300   1.1  christos long
    301   1.1  christos convtime(const char *s)
    302   1.1  christos {
    303  1.15  christos 	long total, secs, multiplier = 1;
    304   1.1  christos 	const char *p;
    305   1.1  christos 	char *endp;
    306   1.1  christos 
    307   1.1  christos 	errno = 0;
    308   1.1  christos 	total = 0;
    309   1.1  christos 	p = s;
    310   1.1  christos 
    311   1.1  christos 	if (p == NULL || *p == '\0')
    312   1.1  christos 		return -1;
    313   1.1  christos 
    314   1.1  christos 	while (*p) {
    315   1.1  christos 		secs = strtol(p, &endp, 10);
    316   1.1  christos 		if (p == endp ||
    317   1.1  christos 		    (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
    318   1.1  christos 		    secs < 0)
    319   1.1  christos 			return -1;
    320   1.1  christos 
    321   1.1  christos 		switch (*endp++) {
    322   1.1  christos 		case '\0':
    323   1.1  christos 			endp--;
    324   1.1  christos 			break;
    325   1.1  christos 		case 's':
    326   1.1  christos 		case 'S':
    327   1.1  christos 			break;
    328   1.1  christos 		case 'm':
    329   1.1  christos 		case 'M':
    330  1.15  christos 			multiplier = MINUTES;
    331   1.1  christos 			break;
    332   1.1  christos 		case 'h':
    333   1.1  christos 		case 'H':
    334  1.15  christos 			multiplier = HOURS;
    335   1.1  christos 			break;
    336   1.1  christos 		case 'd':
    337   1.1  christos 		case 'D':
    338  1.15  christos 			multiplier = DAYS;
    339   1.1  christos 			break;
    340   1.1  christos 		case 'w':
    341   1.1  christos 		case 'W':
    342  1.15  christos 			multiplier = WEEKS;
    343   1.1  christos 			break;
    344   1.1  christos 		default:
    345   1.1  christos 			return -1;
    346   1.1  christos 		}
    347  1.15  christos 		if (secs >= LONG_MAX / multiplier)
    348  1.15  christos 			return -1;
    349  1.15  christos 		secs *= multiplier;
    350  1.15  christos 		if  (total >= LONG_MAX - secs)
    351  1.15  christos 			return -1;
    352   1.1  christos 		total += secs;
    353   1.1  christos 		if (total < 0)
    354   1.1  christos 			return -1;
    355   1.1  christos 		p = endp;
    356   1.1  christos 	}
    357   1.1  christos 
    358   1.1  christos 	return total;
    359   1.1  christos }
    360   1.1  christos 
    361   1.1  christos /*
    362   1.1  christos  * Returns a standardized host+port identifier string.
    363   1.1  christos  * Caller must free returned string.
    364   1.1  christos  */
    365   1.1  christos char *
    366   1.1  christos put_host_port(const char *host, u_short port)
    367   1.1  christos {
    368   1.1  christos 	char *hoststr;
    369   1.1  christos 
    370   1.1  christos 	if (port == 0 || port == SSH_DEFAULT_PORT)
    371   1.1  christos 		return(xstrdup(host));
    372   1.1  christos 	if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
    373   1.1  christos 		fatal("put_host_port: asprintf: %s", strerror(errno));
    374   1.1  christos 	debug3("put_host_port: %s", hoststr);
    375   1.1  christos 	return hoststr;
    376   1.1  christos }
    377   1.1  christos 
    378   1.1  christos /*
    379   1.1  christos  * Search for next delimiter between hostnames/addresses and ports.
    380   1.1  christos  * Argument may be modified (for termination).
    381   1.1  christos  * Returns *cp if parsing succeeds.
    382   1.1  christos  * *cp is set to the start of the next delimiter, if one was found.
    383   1.1  christos  * If this is the last field, *cp is set to NULL.
    384   1.1  christos  */
    385   1.1  christos char *
    386   1.1  christos hpdelim(char **cp)
    387   1.1  christos {
    388   1.1  christos 	char *s, *old;
    389   1.1  christos 
    390   1.1  christos 	if (cp == NULL || *cp == NULL)
    391   1.1  christos 		return NULL;
    392   1.1  christos 
    393   1.1  christos 	old = s = *cp;
    394   1.1  christos 	if (*s == '[') {
    395   1.1  christos 		if ((s = strchr(s, ']')) == NULL)
    396   1.1  christos 			return NULL;
    397   1.1  christos 		else
    398   1.1  christos 			s++;
    399   1.1  christos 	} else if ((s = strpbrk(s, ":/")) == NULL)
    400   1.1  christos 		s = *cp + strlen(*cp); /* skip to end (see first case below) */
    401   1.1  christos 
    402   1.1  christos 	switch (*s) {
    403   1.1  christos 	case '\0':
    404   1.1  christos 		*cp = NULL;	/* no more fields*/
    405   1.1  christos 		break;
    406   1.1  christos 
    407   1.1  christos 	case ':':
    408   1.1  christos 	case '/':
    409   1.1  christos 		*s = '\0';	/* terminate */
    410   1.1  christos 		*cp = s + 1;
    411   1.1  christos 		break;
    412   1.1  christos 
    413   1.1  christos 	default:
    414   1.1  christos 		return NULL;
    415   1.1  christos 	}
    416   1.1  christos 
    417   1.1  christos 	return old;
    418   1.1  christos }
    419   1.1  christos 
    420   1.1  christos char *
    421   1.1  christos cleanhostname(char *host)
    422   1.1  christos {
    423   1.1  christos 	if (*host == '[' && host[strlen(host) - 1] == ']') {
    424   1.1  christos 		host[strlen(host) - 1] = '\0';
    425   1.1  christos 		return (host + 1);
    426   1.1  christos 	} else
    427   1.1  christos 		return host;
    428   1.1  christos }
    429   1.1  christos 
    430   1.1  christos char *
    431   1.1  christos colon(char *cp)
    432   1.1  christos {
    433   1.1  christos 	int flag = 0;
    434   1.1  christos 
    435   1.1  christos 	if (*cp == ':')		/* Leading colon is part of file name. */
    436   1.4      adam 		return NULL;
    437   1.1  christos 	if (*cp == '[')
    438   1.1  christos 		flag = 1;
    439   1.1  christos 
    440   1.1  christos 	for (; *cp; ++cp) {
    441   1.1  christos 		if (*cp == '@' && *(cp+1) == '[')
    442   1.1  christos 			flag = 1;
    443   1.1  christos 		if (*cp == ']' && *(cp+1) == ':' && flag)
    444   1.1  christos 			return (cp+1);
    445   1.1  christos 		if (*cp == ':' && !flag)
    446   1.1  christos 			return (cp);
    447   1.1  christos 		if (*cp == '/')
    448   1.4      adam 			return NULL;
    449   1.1  christos 	}
    450   1.4      adam 	return NULL;
    451   1.1  christos }
    452   1.1  christos 
    453  1.13  christos /*
    454  1.13  christos  * Parse a [user@]host[:port] string.
    455  1.13  christos  * Caller must free returned user and host.
    456  1.13  christos  * Any of the pointer return arguments may be NULL (useful for syntax checking).
    457  1.13  christos  * If user was not specified then *userp will be set to NULL.
    458  1.13  christos  * If port was not specified then *portp will be -1.
    459  1.13  christos  * Returns 0 on success, -1 on failure.
    460  1.13  christos  */
    461  1.13  christos int
    462  1.13  christos parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
    463  1.13  christos {
    464  1.13  christos 	char *sdup, *cp, *tmp;
    465  1.13  christos 	char *user = NULL, *host = NULL;
    466  1.13  christos 	int port = -1, ret = -1;
    467  1.13  christos 
    468  1.13  christos 	if (userp != NULL)
    469  1.13  christos 		*userp = NULL;
    470  1.13  christos 	if (hostp != NULL)
    471  1.13  christos 		*hostp = NULL;
    472  1.13  christos 	if (portp != NULL)
    473  1.13  christos 		*portp = -1;
    474  1.13  christos 
    475  1.13  christos 	if ((sdup = tmp = strdup(s)) == NULL)
    476  1.13  christos 		return -1;
    477  1.13  christos 	/* Extract optional username */
    478  1.13  christos 	if ((cp = strchr(tmp, '@')) != NULL) {
    479  1.13  christos 		*cp = '\0';
    480  1.13  christos 		if (*tmp == '\0')
    481  1.13  christos 			goto out;
    482  1.13  christos 		if ((user = strdup(tmp)) == NULL)
    483  1.13  christos 			goto out;
    484  1.13  christos 		tmp = cp + 1;
    485  1.13  christos 	}
    486  1.13  christos 	/* Extract mandatory hostname */
    487  1.13  christos 	if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
    488  1.13  christos 		goto out;
    489  1.13  christos 	host = xstrdup(cleanhostname(cp));
    490  1.13  christos 	/* Convert and verify optional port */
    491  1.13  christos 	if (tmp != NULL && *tmp != '\0') {
    492  1.13  christos 		if ((port = a2port(tmp)) <= 0)
    493  1.13  christos 			goto out;
    494  1.13  christos 	}
    495  1.13  christos 	/* Success */
    496  1.13  christos 	if (userp != NULL) {
    497  1.13  christos 		*userp = user;
    498  1.13  christos 		user = NULL;
    499  1.13  christos 	}
    500  1.13  christos 	if (hostp != NULL) {
    501  1.13  christos 		*hostp = host;
    502  1.13  christos 		host = NULL;
    503  1.13  christos 	}
    504  1.13  christos 	if (portp != NULL)
    505  1.13  christos 		*portp = port;
    506  1.13  christos 	ret = 0;
    507  1.13  christos  out:
    508  1.13  christos 	free(sdup);
    509  1.13  christos 	free(user);
    510  1.13  christos 	free(host);
    511  1.13  christos 	return ret;
    512  1.13  christos }
    513  1.13  christos 
    514   1.1  christos /* function to assist building execv() arguments */
    515   1.1  christos void
    516   1.5  christos addargs(arglist *args, const char *fmt, ...)
    517   1.1  christos {
    518   1.1  christos 	va_list ap;
    519   1.1  christos 	char *cp;
    520   1.1  christos 	u_int nalloc;
    521   1.1  christos 	int r;
    522   1.1  christos 
    523   1.1  christos 	va_start(ap, fmt);
    524   1.1  christos 	r = vasprintf(&cp, fmt, ap);
    525   1.1  christos 	va_end(ap);
    526   1.1  christos 	if (r == -1)
    527   1.1  christos 		fatal("addargs: argument too long");
    528   1.1  christos 
    529   1.1  christos 	nalloc = args->nalloc;
    530   1.1  christos 	if (args->list == NULL) {
    531   1.1  christos 		nalloc = 32;
    532   1.1  christos 		args->num = 0;
    533   1.1  christos 	} else if (args->num+2 >= nalloc)
    534   1.1  christos 		nalloc *= 2;
    535   1.1  christos 
    536  1.16  christos 	args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
    537   1.1  christos 	args->nalloc = nalloc;
    538   1.1  christos 	args->list[args->num++] = cp;
    539   1.1  christos 	args->list[args->num] = NULL;
    540   1.1  christos }
    541   1.1  christos 
    542   1.1  christos void
    543   1.5  christos replacearg(arglist *args, u_int which, const char *fmt, ...)
    544   1.1  christos {
    545   1.1  christos 	va_list ap;
    546   1.1  christos 	char *cp;
    547   1.1  christos 	int r;
    548   1.1  christos 
    549   1.1  christos 	va_start(ap, fmt);
    550   1.1  christos 	r = vasprintf(&cp, fmt, ap);
    551   1.1  christos 	va_end(ap);
    552   1.1  christos 	if (r == -1)
    553   1.1  christos 		fatal("replacearg: argument too long");
    554   1.1  christos 
    555   1.1  christos 	if (which >= args->num)
    556   1.1  christos 		fatal("replacearg: tried to replace invalid arg %d >= %d",
    557   1.1  christos 		    which, args->num);
    558   1.8  christos 	free(args->list[which]);
    559   1.1  christos 	args->list[which] = cp;
    560   1.1  christos }
    561   1.1  christos 
    562   1.1  christos void
    563   1.1  christos freeargs(arglist *args)
    564   1.1  christos {
    565   1.1  christos 	u_int i;
    566   1.1  christos 
    567   1.1  christos 	if (args->list != NULL) {
    568   1.1  christos 		for (i = 0; i < args->num; i++)
    569   1.8  christos 			free(args->list[i]);
    570   1.8  christos 		free(args->list);
    571   1.1  christos 		args->nalloc = args->num = 0;
    572   1.1  christos 		args->list = NULL;
    573   1.1  christos 	}
    574   1.1  christos }
    575   1.1  christos 
    576   1.1  christos /*
    577   1.1  christos  * Expands tildes in the file name.  Returns data allocated by xmalloc.
    578   1.1  christos  * Warning: this calls getpw*.
    579   1.1  christos  */
    580   1.1  christos char *
    581   1.1  christos tilde_expand_filename(const char *filename, uid_t uid)
    582   1.1  christos {
    583   1.8  christos 	const char *path, *sep;
    584   1.8  christos 	char user[128], *ret, *homedir;
    585   1.1  christos 	struct passwd *pw;
    586   1.1  christos 	u_int len, slash;
    587   1.1  christos 
    588   1.1  christos 	if (*filename != '~')
    589   1.1  christos 		return (xstrdup(filename));
    590   1.1  christos 	filename++;
    591   1.1  christos 
    592   1.1  christos 	path = strchr(filename, '/');
    593   1.1  christos 	if (path != NULL && path > filename) {		/* ~user/path */
    594   1.1  christos 		slash = path - filename;
    595   1.1  christos 		if (slash > sizeof(user) - 1)
    596   1.1  christos 			fatal("tilde_expand_filename: ~username too long");
    597   1.1  christos 		memcpy(user, filename, slash);
    598   1.1  christos 		user[slash] = '\0';
    599   1.1  christos 		if ((pw = getpwnam(user)) == NULL)
    600   1.1  christos 			fatal("tilde_expand_filename: No such user %s", user);
    601   1.2  christos 		homedir = pw->pw_dir;
    602   1.2  christos 	} else {
    603   1.2  christos 		if ((pw = getpwuid(uid)) == NULL)	/* ~/path */
    604   1.2  christos 			fatal("tilde_expand_filename: No such uid %ld",
    605   1.2  christos 			    (long)uid);
    606   1.2  christos 		homedir = pw->pw_dir;
    607   1.2  christos 	}
    608   1.1  christos 
    609   1.1  christos 	/* Make sure directory has a trailing '/' */
    610   1.2  christos 	len = strlen(homedir);
    611   1.8  christos 	if (len == 0 || homedir[len - 1] != '/')
    612   1.8  christos 		sep = "/";
    613   1.8  christos 	else
    614   1.8  christos 		sep = "";
    615   1.1  christos 
    616   1.1  christos 	/* Skip leading '/' from specified path */
    617   1.1  christos 	if (path != NULL)
    618   1.1  christos 		filename = path + 1;
    619   1.8  christos 
    620  1.10  christos 	if (xasprintf(&ret, "%s%s%s", homedir, sep, filename) >= PATH_MAX)
    621   1.1  christos 		fatal("tilde_expand_filename: Path too long");
    622   1.1  christos 
    623   1.8  christos 	return (ret);
    624   1.1  christos }
    625   1.1  christos 
    626   1.1  christos /*
    627   1.1  christos  * Expand a string with a set of %[char] escapes. A number of escapes may be
    628   1.1  christos  * specified as (char *escape_chars, char *replacement) pairs. The list must
    629   1.1  christos  * be terminated by a NULL escape_char. Returns replaced string in memory
    630   1.1  christos  * allocated by xmalloc.
    631   1.1  christos  */
    632   1.1  christos char *
    633   1.1  christos percent_expand(const char *string, ...)
    634   1.1  christos {
    635   1.1  christos #define EXPAND_MAX_KEYS	16
    636   1.4      adam 	u_int num_keys, i, j;
    637   1.1  christos 	struct {
    638   1.1  christos 		const char *key;
    639   1.1  christos 		const char *repl;
    640   1.1  christos 	} keys[EXPAND_MAX_KEYS];
    641   1.1  christos 	char buf[4096];
    642   1.1  christos 	va_list ap;
    643   1.1  christos 
    644   1.1  christos 	/* Gather keys */
    645   1.1  christos 	va_start(ap, string);
    646   1.1  christos 	for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
    647   1.1  christos 		keys[num_keys].key = va_arg(ap, char *);
    648   1.1  christos 		if (keys[num_keys].key == NULL)
    649   1.1  christos 			break;
    650   1.1  christos 		keys[num_keys].repl = va_arg(ap, char *);
    651   1.1  christos 		if (keys[num_keys].repl == NULL)
    652   1.4      adam 			fatal("%s: NULL replacement", __func__);
    653   1.1  christos 	}
    654   1.4      adam 	if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
    655   1.4      adam 		fatal("%s: too many keys", __func__);
    656   1.1  christos 	va_end(ap);
    657   1.1  christos 
    658   1.1  christos 	/* Expand string */
    659   1.1  christos 	*buf = '\0';
    660   1.1  christos 	for (i = 0; *string != '\0'; string++) {
    661   1.1  christos 		if (*string != '%') {
    662   1.1  christos  append:
    663   1.1  christos 			buf[i++] = *string;
    664   1.1  christos 			if (i >= sizeof(buf))
    665   1.4      adam 				fatal("%s: string too long", __func__);
    666   1.1  christos 			buf[i] = '\0';
    667   1.1  christos 			continue;
    668   1.1  christos 		}
    669   1.1  christos 		string++;
    670   1.4      adam 		/* %% case */
    671   1.1  christos 		if (*string == '%')
    672   1.1  christos 			goto append;
    673  1.12  christos 		if (*string == '\0')
    674  1.12  christos 			fatal("%s: invalid format", __func__);
    675   1.1  christos 		for (j = 0; j < num_keys; j++) {
    676   1.1  christos 			if (strchr(keys[j].key, *string) != NULL) {
    677   1.1  christos 				i = strlcat(buf, keys[j].repl, sizeof(buf));
    678   1.1  christos 				if (i >= sizeof(buf))
    679   1.4      adam 					fatal("%s: string too long", __func__);
    680   1.1  christos 				break;
    681   1.1  christos 			}
    682   1.1  christos 		}
    683   1.1  christos 		if (j >= num_keys)
    684   1.4      adam 			fatal("%s: unknown key %%%c", __func__, *string);
    685   1.1  christos 	}
    686   1.1  christos 	return (xstrdup(buf));
    687   1.1  christos #undef EXPAND_MAX_KEYS
    688   1.1  christos }
    689   1.1  christos 
    690   1.1  christos /*
    691   1.1  christos  * Read an entire line from a public key file into a static buffer, discarding
    692   1.1  christos  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
    693   1.1  christos  */
    694   1.1  christos int
    695   1.1  christos read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
    696   1.1  christos    u_long *lineno)
    697   1.1  christos {
    698   1.1  christos 	while (fgets(buf, bufsz, f) != NULL) {
    699   1.1  christos 		if (buf[0] == '\0')
    700   1.1  christos 			continue;
    701   1.1  christos 		(*lineno)++;
    702   1.1  christos 		if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
    703   1.1  christos 			return 0;
    704   1.1  christos 		} else {
    705   1.1  christos 			debug("%s: %s line %lu exceeds size limit", __func__,
    706   1.1  christos 			    filename, *lineno);
    707   1.1  christos 			/* discard remainder of line */
    708   1.1  christos 			while (fgetc(f) != '\n' && !feof(f))
    709   1.1  christos 				;	/* nothing */
    710   1.1  christos 		}
    711   1.1  christos 	}
    712   1.1  christos 	return -1;
    713   1.1  christos }
    714   1.1  christos 
    715   1.1  christos int
    716   1.1  christos tun_open(int tun, int mode)
    717   1.1  christos {
    718   1.1  christos 	struct ifreq ifr;
    719  1.12  christos 	char name[100];
    720  1.12  christos 	int fd = -1, sock;
    721  1.12  christos 	const char *tunbase = "tun";
    722  1.12  christos 
    723  1.12  christos 	if (mode == SSH_TUNMODE_ETHERNET)
    724  1.12  christos 		tunbase = "tap";
    725   1.1  christos 
    726   1.1  christos 	/* Open the tunnel device */
    727   1.1  christos 	if (tun <= SSH_TUNID_MAX) {
    728  1.12  christos 		snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
    729  1.12  christos 		fd = open(name, O_RDWR);
    730   1.1  christos 	} else if (tun == SSH_TUNID_ANY) {
    731   1.1  christos 		for (tun = 100; tun >= 0; tun--) {
    732  1.12  christos 			snprintf(name, sizeof(name), "/dev/%s%d",
    733  1.12  christos 			    tunbase, tun);
    734  1.12  christos 			if ((fd = open(name, O_RDWR)) >= 0)
    735   1.1  christos 				break;
    736   1.1  christos 		}
    737   1.1  christos 	} else {
    738   1.1  christos 		debug("%s: invalid tunnel %u", __func__, tun);
    739  1.12  christos 		return -1;
    740   1.1  christos 	}
    741   1.1  christos 
    742   1.1  christos 	if (fd < 0) {
    743  1.12  christos 		debug("%s: %s open: %s", __func__, name, strerror(errno));
    744  1.12  christos 		return -1;
    745   1.1  christos 	}
    746   1.1  christos 
    747   1.1  christos 
    748  1.12  christos #ifdef TUNSIFHEAD
    749   1.2  christos 	/* Turn on tunnel headers */
    750  1.12  christos 	int flag = 1;
    751   1.2  christos 	if (mode != SSH_TUNMODE_ETHERNET &&
    752   1.2  christos 	    ioctl(fd, TUNSIFHEAD, &flag) == -1) {
    753   1.2  christos 		debug("%s: ioctl(%d, TUNSIFHEAD, 1): %s", __func__, fd,
    754   1.2  christos 		    strerror(errno));
    755   1.2  christos 		close(fd);
    756   1.2  christos 		return -1;
    757   1.2  christos 	}
    758  1.12  christos #endif
    759   1.2  christos 
    760   1.2  christos 	debug("%s: %s mode %d fd %d", __func__, ifr.ifr_name, mode, fd);
    761  1.12  christos 	/* Bring interface up if it is not already */
    762   1.3   jnemeth 	snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
    763   1.1  christos 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
    764   1.1  christos 		goto failed;
    765   1.1  christos 
    766  1.12  christos 	if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
    767  1.12  christos 		debug("%s: get interface %s flags: %s", __func__,
    768  1.12  christos 		    ifr.ifr_name, strerror(errno));
    769   1.1  christos 		goto failed;
    770  1.12  christos 	}
    771   1.1  christos 
    772  1.12  christos 	if (!(ifr.ifr_flags & IFF_UP)) {
    773  1.12  christos 		ifr.ifr_flags |= IFF_UP;
    774  1.12  christos 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
    775  1.12  christos 			debug("%s: activate interface %s: %s", __func__,
    776  1.12  christos 			    ifr.ifr_name, strerror(errno));
    777  1.12  christos 			goto failed;
    778  1.12  christos 		}
    779  1.12  christos 	}
    780   1.1  christos 
    781   1.1  christos 	close(sock);
    782  1.12  christos 	return fd;
    783   1.1  christos 
    784   1.1  christos  failed:
    785   1.1  christos 	if (fd >= 0)
    786   1.1  christos 		close(fd);
    787   1.1  christos 	if (sock >= 0)
    788   1.1  christos 		close(sock);
    789   1.2  christos 	debug("%s: failed to set %s mode %d: %s", __func__, ifr.ifr_name,
    790   1.1  christos 	    mode, strerror(errno));
    791  1.12  christos 	return -1;
    792   1.1  christos }
    793   1.1  christos 
    794   1.1  christos void
    795   1.1  christos sanitise_stdfd(void)
    796   1.1  christos {
    797   1.1  christos 	int nullfd, dupfd;
    798   1.1  christos 
    799   1.1  christos 	if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
    800   1.1  christos 		fprintf(stderr, "Couldn't open /dev/null: %s\n",
    801   1.1  christos 		    strerror(errno));
    802   1.1  christos 		exit(1);
    803   1.1  christos 	}
    804  1.13  christos 	while (++dupfd <= STDERR_FILENO) {
    805  1.13  christos 		/* Only populate closed fds. */
    806  1.13  christos 		if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
    807  1.13  christos 			if (dup2(nullfd, dupfd) == -1) {
    808  1.13  christos 				fprintf(stderr, "dup2: %s\n", strerror(errno));
    809  1.13  christos 				exit(1);
    810  1.13  christos 			}
    811   1.1  christos 		}
    812   1.1  christos 	}
    813  1.13  christos 	if (nullfd > STDERR_FILENO)
    814   1.1  christos 		close(nullfd);
    815   1.1  christos }
    816   1.1  christos 
    817   1.1  christos char *
    818   1.1  christos tohex(const void *vp, size_t l)
    819   1.1  christos {
    820   1.1  christos 	const u_char *p = (const u_char *)vp;
    821   1.1  christos 	char b[3], *r;
    822   1.1  christos 	size_t i, hl;
    823   1.1  christos 
    824   1.1  christos 	if (l > 65536)
    825   1.1  christos 		return xstrdup("tohex: length > 65536");
    826   1.1  christos 
    827   1.1  christos 	hl = l * 2 + 1;
    828   1.1  christos 	r = xcalloc(1, hl);
    829   1.1  christos 	for (i = 0; i < l; i++) {
    830   1.1  christos 		snprintf(b, sizeof(b), "%02x", p[i]);
    831   1.1  christos 		strlcat(r, b, hl);
    832   1.1  christos 	}
    833   1.1  christos 	return (r);
    834   1.1  christos }
    835   1.1  christos 
    836   1.1  christos u_int64_t
    837   1.1  christos get_u64(const void *vp)
    838   1.1  christos {
    839   1.1  christos 	const u_char *p = (const u_char *)vp;
    840   1.1  christos 	u_int64_t v;
    841   1.1  christos 
    842   1.1  christos 	v  = (u_int64_t)p[0] << 56;
    843   1.1  christos 	v |= (u_int64_t)p[1] << 48;
    844   1.1  christos 	v |= (u_int64_t)p[2] << 40;
    845   1.1  christos 	v |= (u_int64_t)p[3] << 32;
    846   1.1  christos 	v |= (u_int64_t)p[4] << 24;
    847   1.1  christos 	v |= (u_int64_t)p[5] << 16;
    848   1.1  christos 	v |= (u_int64_t)p[6] << 8;
    849   1.1  christos 	v |= (u_int64_t)p[7];
    850   1.1  christos 
    851   1.1  christos 	return (v);
    852   1.1  christos }
    853   1.1  christos 
    854   1.1  christos u_int32_t
    855   1.1  christos get_u32(const void *vp)
    856   1.1  christos {
    857   1.1  christos 	const u_char *p = (const u_char *)vp;
    858   1.1  christos 	u_int32_t v;
    859   1.1  christos 
    860   1.1  christos 	v  = (u_int32_t)p[0] << 24;
    861   1.1  christos 	v |= (u_int32_t)p[1] << 16;
    862   1.1  christos 	v |= (u_int32_t)p[2] << 8;
    863   1.1  christos 	v |= (u_int32_t)p[3];
    864   1.1  christos 
    865   1.1  christos 	return (v);
    866   1.1  christos }
    867   1.1  christos 
    868   1.9  christos u_int32_t
    869   1.9  christos get_u32_le(const void *vp)
    870   1.9  christos {
    871   1.9  christos 	const u_char *p = (const u_char *)vp;
    872   1.9  christos 	u_int32_t v;
    873   1.9  christos 
    874   1.9  christos 	v  = (u_int32_t)p[0];
    875   1.9  christos 	v |= (u_int32_t)p[1] << 8;
    876   1.9  christos 	v |= (u_int32_t)p[2] << 16;
    877   1.9  christos 	v |= (u_int32_t)p[3] << 24;
    878   1.9  christos 
    879   1.9  christos 	return (v);
    880   1.9  christos }
    881   1.9  christos 
    882   1.1  christos u_int16_t
    883   1.1  christos get_u16(const void *vp)
    884   1.1  christos {
    885   1.1  christos 	const u_char *p = (const u_char *)vp;
    886   1.1  christos 	u_int16_t v;
    887   1.1  christos 
    888   1.1  christos 	v  = (u_int16_t)p[0] << 8;
    889   1.1  christos 	v |= (u_int16_t)p[1];
    890   1.1  christos 
    891   1.1  christos 	return (v);
    892   1.1  christos }
    893   1.1  christos 
    894   1.1  christos void
    895   1.1  christos put_u64(void *vp, u_int64_t v)
    896   1.1  christos {
    897   1.1  christos 	u_char *p = (u_char *)vp;
    898   1.1  christos 
    899   1.1  christos 	p[0] = (u_char)(v >> 56) & 0xff;
    900   1.1  christos 	p[1] = (u_char)(v >> 48) & 0xff;
    901   1.1  christos 	p[2] = (u_char)(v >> 40) & 0xff;
    902   1.1  christos 	p[3] = (u_char)(v >> 32) & 0xff;
    903   1.1  christos 	p[4] = (u_char)(v >> 24) & 0xff;
    904   1.1  christos 	p[5] = (u_char)(v >> 16) & 0xff;
    905   1.1  christos 	p[6] = (u_char)(v >> 8) & 0xff;
    906   1.1  christos 	p[7] = (u_char)v & 0xff;
    907   1.1  christos }
    908   1.1  christos 
    909   1.1  christos void
    910   1.1  christos put_u32(void *vp, u_int32_t v)
    911   1.1  christos {
    912   1.1  christos 	u_char *p = (u_char *)vp;
    913   1.1  christos 
    914   1.1  christos 	p[0] = (u_char)(v >> 24) & 0xff;
    915   1.1  christos 	p[1] = (u_char)(v >> 16) & 0xff;
    916   1.1  christos 	p[2] = (u_char)(v >> 8) & 0xff;
    917   1.1  christos 	p[3] = (u_char)v & 0xff;
    918   1.1  christos }
    919   1.1  christos 
    920   1.9  christos void
    921   1.9  christos put_u32_le(void *vp, u_int32_t v)
    922   1.9  christos {
    923   1.9  christos 	u_char *p = (u_char *)vp;
    924   1.9  christos 
    925   1.9  christos 	p[0] = (u_char)v & 0xff;
    926   1.9  christos 	p[1] = (u_char)(v >> 8) & 0xff;
    927   1.9  christos 	p[2] = (u_char)(v >> 16) & 0xff;
    928   1.9  christos 	p[3] = (u_char)(v >> 24) & 0xff;
    929   1.9  christos }
    930   1.1  christos 
    931   1.1  christos void
    932   1.1  christos put_u16(void *vp, u_int16_t v)
    933   1.1  christos {
    934   1.1  christos 	u_char *p = (u_char *)vp;
    935   1.1  christos 
    936   1.1  christos 	p[0] = (u_char)(v >> 8) & 0xff;
    937   1.1  christos 	p[1] = (u_char)v & 0xff;
    938   1.1  christos }
    939   1.1  christos 
    940   1.1  christos void
    941   1.1  christos ms_subtract_diff(struct timeval *start, int *ms)
    942   1.1  christos {
    943   1.1  christos 	struct timeval diff, finish;
    944   1.1  christos 
    945   1.1  christos 	gettimeofday(&finish, NULL);
    946   1.1  christos 	timersub(&finish, start, &diff);
    947   1.1  christos 	*ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
    948   1.1  christos }
    949   1.1  christos 
    950   1.1  christos void
    951   1.1  christos ms_to_timeval(struct timeval *tv, int ms)
    952   1.1  christos {
    953   1.1  christos 	if (ms < 0)
    954   1.1  christos 		ms = 0;
    955   1.1  christos 	tv->tv_sec = ms / 1000;
    956   1.1  christos 	tv->tv_usec = (ms % 1000) * 1000;
    957   1.1  christos }
    958   1.1  christos 
    959   1.8  christos time_t
    960   1.8  christos monotime(void)
    961   1.8  christos {
    962   1.8  christos 	struct timespec ts;
    963   1.8  christos 
    964   1.8  christos 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
    965   1.8  christos 		fatal("clock_gettime: %s", strerror(errno));
    966   1.8  christos 
    967   1.8  christos 	return (ts.tv_sec);
    968   1.8  christos }
    969   1.8  christos 
    970  1.13  christos double
    971  1.13  christos monotime_double(void)
    972  1.13  christos {
    973  1.13  christos 	struct timespec ts;
    974  1.13  christos 
    975  1.13  christos 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
    976  1.13  christos 		fatal("clock_gettime: %s", strerror(errno));
    977  1.13  christos 
    978  1.13  christos 	return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
    979  1.13  christos }
    980  1.13  christos 
    981   1.5  christos void
    982   1.5  christos bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
    983   1.5  christos {
    984   1.5  christos 	bw->buflen = buflen;
    985   1.5  christos 	bw->rate = kbps;
    986   1.5  christos 	bw->thresh = bw->rate;
    987   1.5  christos 	bw->lamt = 0;
    988   1.5  christos 	timerclear(&bw->bwstart);
    989   1.5  christos 	timerclear(&bw->bwend);
    990   1.5  christos }
    991   1.5  christos 
    992   1.5  christos /* Callback from read/write loop to insert bandwidth-limiting delays */
    993   1.5  christos void
    994   1.5  christos bandwidth_limit(struct bwlimit *bw, size_t read_len)
    995   1.5  christos {
    996   1.5  christos 	u_int64_t waitlen;
    997   1.5  christos 	struct timespec ts, rm;
    998   1.5  christos 
    999   1.5  christos 	if (!timerisset(&bw->bwstart)) {
   1000   1.5  christos 		gettimeofday(&bw->bwstart, NULL);
   1001   1.5  christos 		return;
   1002   1.5  christos 	}
   1003   1.5  christos 
   1004   1.5  christos 	bw->lamt += read_len;
   1005   1.5  christos 	if (bw->lamt < bw->thresh)
   1006   1.5  christos 		return;
   1007   1.5  christos 
   1008   1.5  christos 	gettimeofday(&bw->bwend, NULL);
   1009   1.5  christos 	timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
   1010   1.5  christos 	if (!timerisset(&bw->bwend))
   1011   1.5  christos 		return;
   1012   1.5  christos 
   1013   1.5  christos 	bw->lamt *= 8;
   1014   1.5  christos 	waitlen = (double)1000000L * bw->lamt / bw->rate;
   1015   1.5  christos 
   1016   1.5  christos 	bw->bwstart.tv_sec = waitlen / 1000000L;
   1017   1.5  christos 	bw->bwstart.tv_usec = waitlen % 1000000L;
   1018   1.5  christos 
   1019   1.5  christos 	if (timercmp(&bw->bwstart, &bw->bwend, >)) {
   1020   1.5  christos 		timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
   1021   1.5  christos 
   1022   1.5  christos 		/* Adjust the wait time */
   1023   1.5  christos 		if (bw->bwend.tv_sec) {
   1024   1.5  christos 			bw->thresh /= 2;
   1025   1.5  christos 			if (bw->thresh < bw->buflen / 4)
   1026   1.5  christos 				bw->thresh = bw->buflen / 4;
   1027   1.5  christos 		} else if (bw->bwend.tv_usec < 10000) {
   1028   1.5  christos 			bw->thresh *= 2;
   1029   1.5  christos 			if (bw->thresh > bw->buflen * 8)
   1030   1.5  christos 				bw->thresh = bw->buflen * 8;
   1031   1.5  christos 		}
   1032   1.5  christos 
   1033   1.5  christos 		TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
   1034   1.5  christos 		while (nanosleep(&ts, &rm) == -1) {
   1035   1.5  christos 			if (errno != EINTR)
   1036   1.5  christos 				break;
   1037   1.5  christos 			ts = rm;
   1038   1.5  christos 		}
   1039   1.5  christos 	}
   1040   1.5  christos 
   1041   1.5  christos 	bw->lamt = 0;
   1042   1.5  christos 	gettimeofday(&bw->bwstart, NULL);
   1043   1.5  christos }
   1044   1.5  christos 
   1045   1.5  christos /* Make a template filename for mk[sd]temp() */
   1046   1.5  christos void
   1047   1.5  christos mktemp_proto(char *s, size_t len)
   1048   1.5  christos {
   1049   1.5  christos 	const char *tmpdir;
   1050   1.5  christos 	int r;
   1051   1.5  christos 
   1052   1.5  christos 	if ((tmpdir = getenv("TMPDIR")) != NULL) {
   1053   1.5  christos 		r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
   1054   1.5  christos 		if (r > 0 && (size_t)r < len)
   1055   1.5  christos 			return;
   1056   1.5  christos 	}
   1057   1.5  christos 	r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
   1058   1.5  christos 	if (r < 0 || (size_t)r >= len)
   1059   1.5  christos 		fatal("%s: template string too short", __func__);
   1060   1.5  christos }
   1061   1.5  christos 
   1062   1.5  christos static const struct {
   1063   1.5  christos 	const char *name;
   1064   1.5  christos 	int value;
   1065   1.5  christos } ipqos[] = {
   1066  1.16  christos 	{ "none", INT_MAX },		/* can't use 0 here; that's CS0 */
   1067   1.5  christos 	{ "af11", IPTOS_DSCP_AF11 },
   1068   1.5  christos 	{ "af12", IPTOS_DSCP_AF12 },
   1069   1.5  christos 	{ "af13", IPTOS_DSCP_AF13 },
   1070   1.7  christos 	{ "af21", IPTOS_DSCP_AF21 },
   1071   1.5  christos 	{ "af22", IPTOS_DSCP_AF22 },
   1072   1.5  christos 	{ "af23", IPTOS_DSCP_AF23 },
   1073   1.5  christos 	{ "af31", IPTOS_DSCP_AF31 },
   1074   1.5  christos 	{ "af32", IPTOS_DSCP_AF32 },
   1075   1.5  christos 	{ "af33", IPTOS_DSCP_AF33 },
   1076   1.5  christos 	{ "af41", IPTOS_DSCP_AF41 },
   1077   1.5  christos 	{ "af42", IPTOS_DSCP_AF42 },
   1078   1.5  christos 	{ "af43", IPTOS_DSCP_AF43 },
   1079   1.5  christos 	{ "cs0", IPTOS_DSCP_CS0 },
   1080   1.5  christos 	{ "cs1", IPTOS_DSCP_CS1 },
   1081   1.5  christos 	{ "cs2", IPTOS_DSCP_CS2 },
   1082   1.5  christos 	{ "cs3", IPTOS_DSCP_CS3 },
   1083   1.5  christos 	{ "cs4", IPTOS_DSCP_CS4 },
   1084   1.5  christos 	{ "cs5", IPTOS_DSCP_CS5 },
   1085   1.5  christos 	{ "cs6", IPTOS_DSCP_CS6 },
   1086   1.5  christos 	{ "cs7", IPTOS_DSCP_CS7 },
   1087   1.5  christos 	{ "ef", IPTOS_DSCP_EF },
   1088   1.5  christos 	{ "lowdelay", IPTOS_LOWDELAY },
   1089   1.5  christos 	{ "throughput", IPTOS_THROUGHPUT },
   1090   1.5  christos 	{ "reliability", IPTOS_RELIABILITY },
   1091   1.5  christos 	{ NULL, -1 }
   1092   1.5  christos };
   1093   1.5  christos 
   1094   1.5  christos int
   1095   1.5  christos parse_ipqos(const char *cp)
   1096   1.5  christos {
   1097   1.5  christos 	u_int i;
   1098   1.5  christos 	char *ep;
   1099   1.5  christos 	long val;
   1100   1.5  christos 
   1101   1.5  christos 	if (cp == NULL)
   1102   1.5  christos 		return -1;
   1103   1.5  christos 	for (i = 0; ipqos[i].name != NULL; i++) {
   1104   1.5  christos 		if (strcasecmp(cp, ipqos[i].name) == 0)
   1105   1.5  christos 			return ipqos[i].value;
   1106   1.5  christos 	}
   1107   1.5  christos 	/* Try parsing as an integer */
   1108   1.5  christos 	val = strtol(cp, &ep, 0);
   1109   1.5  christos 	if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
   1110   1.5  christos 		return -1;
   1111   1.5  christos 	return val;
   1112   1.5  christos }
   1113   1.5  christos 
   1114   1.6  christos const char *
   1115   1.6  christos iptos2str(int iptos)
   1116   1.6  christos {
   1117   1.6  christos 	int i;
   1118   1.6  christos 	static char iptos_str[sizeof "0xff"];
   1119   1.6  christos 
   1120   1.6  christos 	for (i = 0; ipqos[i].name != NULL; i++) {
   1121   1.6  christos 		if (ipqos[i].value == iptos)
   1122   1.6  christos 			return ipqos[i].name;
   1123   1.6  christos 	}
   1124   1.6  christos 	snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
   1125   1.6  christos 	return iptos_str;
   1126   1.6  christos }
   1127   1.6  christos 
   1128   1.9  christos void
   1129   1.9  christos lowercase(char *s)
   1130   1.9  christos {
   1131   1.9  christos 	for (; *s; s++)
   1132   1.9  christos 		*s = tolower((u_char)*s);
   1133   1.9  christos }
   1134   1.9  christos 
   1135   1.4      adam int
   1136   1.9  christos unix_listener(const char *path, int backlog, int unlink_first)
   1137   1.4      adam {
   1138   1.9  christos 	struct sockaddr_un sunaddr;
   1139   1.9  christos 	int saved_errno, sock;
   1140   1.4      adam 
   1141   1.9  christos 	memset(&sunaddr, 0, sizeof(sunaddr));
   1142   1.9  christos 	sunaddr.sun_family = AF_UNIX;
   1143   1.9  christos 	if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
   1144   1.9  christos 		error("%s: \"%s\" too long for Unix domain socket", __func__,
   1145   1.9  christos 		    path);
   1146   1.9  christos 		errno = ENAMETOOLONG;
   1147   1.9  christos 		return -1;
   1148   1.9  christos 	}
   1149   1.9  christos 
   1150   1.9  christos 	sock = socket(PF_UNIX, SOCK_STREAM, 0);
   1151   1.9  christos 	if (sock < 0) {
   1152   1.9  christos 		saved_errno = errno;
   1153   1.9  christos 		error("socket: %.100s", strerror(errno));
   1154   1.9  christos 		errno = saved_errno;
   1155   1.9  christos 		return -1;
   1156   1.9  christos 	}
   1157   1.9  christos 	if (unlink_first == 1) {
   1158   1.9  christos 		if (unlink(path) != 0 && errno != ENOENT)
   1159   1.9  christos 			error("unlink(%s): %.100s", path, strerror(errno));
   1160   1.9  christos 	}
   1161   1.9  christos 	if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
   1162   1.9  christos 		saved_errno = errno;
   1163   1.9  christos 		error("bind: %.100s", strerror(errno));
   1164   1.9  christos 		close(sock);
   1165   1.9  christos 		error("%s: cannot bind to path: %s", __func__, path);
   1166   1.9  christos 		errno = saved_errno;
   1167   1.9  christos 		return -1;
   1168   1.9  christos 	}
   1169   1.9  christos 	if (listen(sock, backlog) < 0) {
   1170   1.9  christos 		saved_errno = errno;
   1171   1.9  christos 		error("listen: %.100s", strerror(errno));
   1172   1.9  christos 		close(sock);
   1173   1.9  christos 		unlink(path);
   1174   1.9  christos 		error("%s: cannot listen on path: %s", __func__, path);
   1175   1.9  christos 		errno = saved_errno;
   1176   1.9  christos 		return -1;
   1177   1.9  christos 	}
   1178   1.9  christos 	return sock;
   1179   1.4      adam }
   1180  1.13  christos 
   1181  1.13  christos /*
   1182  1.13  christos  * Compares two strings that maybe be NULL. Returns non-zero if strings
   1183  1.13  christos  * are both NULL or are identical, returns zero otherwise.
   1184  1.13  christos  */
   1185  1.13  christos static int
   1186  1.13  christos strcmp_maybe_null(const char *a, const char *b)
   1187  1.13  christos {
   1188  1.13  christos 	if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
   1189  1.13  christos 		return 0;
   1190  1.13  christos 	if (a != NULL && strcmp(a, b) != 0)
   1191  1.13  christos 		return 0;
   1192  1.13  christos 	return 1;
   1193  1.13  christos }
   1194  1.13  christos 
   1195  1.13  christos /*
   1196  1.13  christos  * Compare two forwards, returning non-zero if they are identical or
   1197  1.13  christos  * zero otherwise.
   1198  1.13  christos  */
   1199  1.13  christos int
   1200  1.13  christos forward_equals(const struct Forward *a, const struct Forward *b)
   1201  1.13  christos {
   1202  1.13  christos 	if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
   1203  1.13  christos 		return 0;
   1204  1.13  christos 	if (a->listen_port != b->listen_port)
   1205  1.13  christos 		return 0;
   1206  1.13  christos 	if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
   1207  1.13  christos 		return 0;
   1208  1.13  christos 	if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
   1209  1.13  christos 		return 0;
   1210  1.13  christos 	if (a->connect_port != b->connect_port)
   1211  1.13  christos 		return 0;
   1212  1.13  christos 	if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
   1213  1.13  christos 		return 0;
   1214  1.13  christos 	/* allocated_port and handle are not checked */
   1215  1.13  christos 	return 1;
   1216  1.13  christos }
   1217  1.13  christos 
   1218  1.14  christos /* returns 1 if bind to specified port by specified user is permitted */
   1219  1.14  christos int
   1220  1.14  christos bind_permitted(int port, uid_t uid)
   1221  1.14  christos {
   1222  1.14  christos 	if (port < IPPORT_RESERVED && uid != 0)
   1223  1.14  christos 		return 0;
   1224  1.14  christos 	return 1;
   1225  1.14  christos }
   1226  1.14  christos 
   1227  1.14  christos /* returns 1 if process is already daemonized, 0 otherwise */
   1228  1.14  christos int
   1229  1.14  christos daemonized(void)
   1230  1.14  christos {
   1231  1.14  christos 	int fd;
   1232  1.14  christos 
   1233  1.14  christos 	if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
   1234  1.14  christos 		close(fd);
   1235  1.14  christos 		return 0;	/* have controlling terminal */
   1236  1.14  christos 	}
   1237  1.14  christos 	if (getppid() != 1)
   1238  1.14  christos 		return 0;	/* parent is not init */
   1239  1.14  christos 	if (getsid(0) != getpid())
   1240  1.14  christos 		return 0;	/* not session leader */
   1241  1.14  christos 	debug3("already daemonized");
   1242  1.14  christos 	return 1;
   1243  1.14  christos }
   1244  1.16  christos 
   1245  1.16  christos 
   1246  1.16  christos /*
   1247  1.16  christos  * Splits 's' into an argument vector. Handles quoted string and basic
   1248  1.16  christos  * escape characters (\\, \", \'). Caller must free the argument vector
   1249  1.16  christos  * and its members.
   1250  1.16  christos  */
   1251  1.16  christos int
   1252  1.16  christos argv_split(const char *s, int *argcp, char ***argvp)
   1253  1.16  christos {
   1254  1.16  christos 	int r = SSH_ERR_INTERNAL_ERROR;
   1255  1.16  christos 	int argc = 0, quote, i, j;
   1256  1.16  christos 	char *arg, **argv = xcalloc(1, sizeof(*argv));
   1257  1.16  christos 
   1258  1.16  christos 	*argvp = NULL;
   1259  1.16  christos 	*argcp = 0;
   1260  1.16  christos 
   1261  1.16  christos 	for (i = 0; s[i] != '\0'; i++) {
   1262  1.16  christos 		/* Skip leading whitespace */
   1263  1.16  christos 		if (s[i] == ' ' || s[i] == '\t')
   1264  1.16  christos 			continue;
   1265  1.16  christos 
   1266  1.16  christos 		/* Start of a token */
   1267  1.16  christos 		quote = 0;
   1268  1.16  christos 		if (s[i] == '\\' &&
   1269  1.16  christos 		    (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
   1270  1.16  christos 			i++;
   1271  1.16  christos 		else if (s[i] == '\'' || s[i] == '"')
   1272  1.16  christos 			quote = s[i++];
   1273  1.16  christos 
   1274  1.16  christos 		argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
   1275  1.16  christos 		arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
   1276  1.16  christos 		argv[argc] = NULL;
   1277  1.16  christos 
   1278  1.16  christos 		/* Copy the token in, removing escapes */
   1279  1.16  christos 		for (j = 0; s[i] != '\0'; i++) {
   1280  1.16  christos 			if (s[i] == '\\') {
   1281  1.16  christos 				if (s[i + 1] == '\'' ||
   1282  1.16  christos 				    s[i + 1] == '\"' ||
   1283  1.16  christos 				    s[i + 1] == '\\') {
   1284  1.16  christos 					i++; /* Skip '\' */
   1285  1.16  christos 					arg[j++] = s[i];
   1286  1.16  christos 				} else {
   1287  1.16  christos 					/* Unrecognised escape */
   1288  1.16  christos 					arg[j++] = s[i];
   1289  1.16  christos 				}
   1290  1.16  christos 			} else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
   1291  1.16  christos 				break; /* done */
   1292  1.16  christos 			else if (quote != 0 && s[i] == quote)
   1293  1.16  christos 				break; /* done */
   1294  1.16  christos 			else
   1295  1.16  christos 				arg[j++] = s[i];
   1296  1.16  christos 		}
   1297  1.16  christos 		if (s[i] == '\0') {
   1298  1.16  christos 			if (quote != 0) {
   1299  1.16  christos 				/* Ran out of string looking for close quote */
   1300  1.16  christos 				r = SSH_ERR_INVALID_FORMAT;
   1301  1.16  christos 				goto out;
   1302  1.16  christos 			}
   1303  1.16  christos 			break;
   1304  1.16  christos 		}
   1305  1.16  christos 	}
   1306  1.16  christos 	/* Success */
   1307  1.16  christos 	*argcp = argc;
   1308  1.16  christos 	*argvp = argv;
   1309  1.16  christos 	argc = 0;
   1310  1.16  christos 	argv = NULL;
   1311  1.16  christos 	r = 0;
   1312  1.16  christos  out:
   1313  1.16  christos 	if (argc != 0 && argv != NULL) {
   1314  1.16  christos 		for (i = 0; i < argc; i++)
   1315  1.16  christos 			free(argv[i]);
   1316  1.16  christos 		free(argv);
   1317  1.16  christos 	}
   1318  1.16  christos 	return r;
   1319  1.16  christos }
   1320  1.16  christos 
   1321  1.16  christos /*
   1322  1.16  christos  * Reassemble an argument vector into a string, quoting and escaping as
   1323  1.16  christos  * necessary. Caller must free returned string.
   1324  1.16  christos  */
   1325  1.16  christos char *
   1326  1.16  christos argv_assemble(int argc, char **argv)
   1327  1.16  christos {
   1328  1.16  christos 	int i, j, ws, r;
   1329  1.16  christos 	char c, *ret;
   1330  1.16  christos 	struct sshbuf *buf, *arg;
   1331  1.16  christos 
   1332  1.16  christos 	if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
   1333  1.16  christos 		fatal("%s: sshbuf_new failed", __func__);
   1334  1.16  christos 
   1335  1.16  christos 	for (i = 0; i < argc; i++) {
   1336  1.16  christos 		ws = 0;
   1337  1.16  christos 		sshbuf_reset(arg);
   1338  1.16  christos 		for (j = 0; argv[i][j] != '\0'; j++) {
   1339  1.16  christos 			r = 0;
   1340  1.16  christos 			c = argv[i][j];
   1341  1.16  christos 			switch (c) {
   1342  1.16  christos 			case ' ':
   1343  1.16  christos 			case '\t':
   1344  1.16  christos 				ws = 1;
   1345  1.16  christos 				r = sshbuf_put_u8(arg, c);
   1346  1.16  christos 				break;
   1347  1.16  christos 			case '\\':
   1348  1.16  christos 			case '\'':
   1349  1.16  christos 			case '"':
   1350  1.16  christos 				if ((r = sshbuf_put_u8(arg, '\\')) != 0)
   1351  1.16  christos 					break;
   1352  1.16  christos 				/* FALLTHROUGH */
   1353  1.16  christos 			default:
   1354  1.16  christos 				r = sshbuf_put_u8(arg, c);
   1355  1.16  christos 				break;
   1356  1.16  christos 			}
   1357  1.16  christos 			if (r != 0)
   1358  1.16  christos 				fatal("%s: sshbuf_put_u8: %s",
   1359  1.16  christos 				    __func__, ssh_err(r));
   1360  1.16  christos 		}
   1361  1.16  christos 		if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
   1362  1.16  christos 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
   1363  1.16  christos 		    (r = sshbuf_putb(buf, arg)) != 0 ||
   1364  1.16  christos 		    (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
   1365  1.16  christos 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
   1366  1.16  christos 	}
   1367  1.16  christos 	if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
   1368  1.16  christos 		fatal("%s: malloc failed", __func__);
   1369  1.16  christos 	memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
   1370  1.16  christos 	ret[sshbuf_len(buf)] = '\0';
   1371  1.16  christos 	sshbuf_free(buf);
   1372  1.16  christos 	sshbuf_free(arg);
   1373  1.16  christos 	return ret;
   1374  1.16  christos }
   1375  1.16  christos 
   1376  1.16  christos /*
   1377  1.16  christos  * Runs command in a subprocess wuth a minimal environment.
   1378  1.16  christos  * Returns pid on success, 0 on failure.
   1379  1.16  christos  * The child stdout and stderr maybe captured, left attached or sent to
   1380  1.16  christos  * /dev/null depending on the contents of flags.
   1381  1.16  christos  * "tag" is prepended to log messages.
   1382  1.16  christos  * NB. "command" is only used for logging; the actual command executed is
   1383  1.16  christos  * av[0].
   1384  1.16  christos  */
   1385  1.16  christos pid_t
   1386  1.16  christos subprocess(const char *tag, struct passwd *pw, const char *command,
   1387  1.16  christos     int ac, char **av, FILE **child, u_int flags)
   1388  1.16  christos {
   1389  1.16  christos 	FILE *f = NULL;
   1390  1.16  christos 	struct stat st;
   1391  1.16  christos 	int fd, devnull, p[2], i;
   1392  1.16  christos 	pid_t pid;
   1393  1.16  christos 	char *cp, errmsg[512];
   1394  1.16  christos 	u_int envsize;
   1395  1.16  christos 	char **child_env;
   1396  1.16  christos 
   1397  1.16  christos 	if (child != NULL)
   1398  1.16  christos 		*child = NULL;
   1399  1.16  christos 
   1400  1.16  christos 	debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
   1401  1.16  christos 	    tag, command, pw->pw_name, flags);
   1402  1.16  christos 
   1403  1.16  christos 	/* Check consistency */
   1404  1.16  christos 	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
   1405  1.16  christos 	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
   1406  1.16  christos 		error("%s: inconsistent flags", __func__);
   1407  1.16  christos 		return 0;
   1408  1.16  christos 	}
   1409  1.16  christos 	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
   1410  1.16  christos 		error("%s: inconsistent flags/output", __func__);
   1411  1.16  christos 		return 0;
   1412  1.16  christos 	}
   1413  1.16  christos 
   1414  1.16  christos 	/*
   1415  1.16  christos 	 * If executing an explicit binary, then verify the it exists
   1416  1.16  christos 	 * and appears safe-ish to execute
   1417  1.16  christos 	 */
   1418  1.16  christos 	if (*av[0] != '/') {
   1419  1.16  christos 		error("%s path is not absolute", tag);
   1420  1.16  christos 		return 0;
   1421  1.16  christos 	}
   1422  1.16  christos 	temporarily_use_uid(pw);
   1423  1.16  christos 	if (stat(av[0], &st) < 0) {
   1424  1.16  christos 		error("Could not stat %s \"%s\": %s", tag,
   1425  1.16  christos 		    av[0], strerror(errno));
   1426  1.16  christos 		restore_uid();
   1427  1.16  christos 		return 0;
   1428  1.16  christos 	}
   1429  1.16  christos 	if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
   1430  1.16  christos 		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
   1431  1.16  christos 		restore_uid();
   1432  1.16  christos 		return 0;
   1433  1.16  christos 	}
   1434  1.16  christos 	/* Prepare to keep the child's stdout if requested */
   1435  1.16  christos 	if (pipe(p) != 0) {
   1436  1.16  christos 		error("%s: pipe: %s", tag, strerror(errno));
   1437  1.16  christos 		restore_uid();
   1438  1.16  christos 		return 0;
   1439  1.16  christos 	}
   1440  1.16  christos 	restore_uid();
   1441  1.16  christos 
   1442  1.16  christos 	switch ((pid = fork())) {
   1443  1.16  christos 	case -1: /* error */
   1444  1.16  christos 		error("%s: fork: %s", tag, strerror(errno));
   1445  1.16  christos 		close(p[0]);
   1446  1.16  christos 		close(p[1]);
   1447  1.16  christos 		return 0;
   1448  1.16  christos 	case 0: /* child */
   1449  1.16  christos 		/* Prepare a minimal environment for the child. */
   1450  1.16  christos 		envsize = 5;
   1451  1.16  christos 		child_env = xcalloc(sizeof(*child_env), envsize);
   1452  1.16  christos 		child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
   1453  1.16  christos 		child_set_env(&child_env, &envsize, "USER", pw->pw_name);
   1454  1.16  christos 		child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
   1455  1.16  christos 		child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
   1456  1.16  christos 		if ((cp = getenv("LANG")) != NULL)
   1457  1.16  christos 			child_set_env(&child_env, &envsize, "LANG", cp);
   1458  1.16  christos 
   1459  1.16  christos 		for (i = 0; i < NSIG; i++)
   1460  1.16  christos 			signal(i, SIG_DFL);
   1461  1.16  christos 
   1462  1.16  christos 		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
   1463  1.16  christos 			error("%s: open %s: %s", tag, _PATH_DEVNULL,
   1464  1.16  christos 			    strerror(errno));
   1465  1.16  christos 			_exit(1);
   1466  1.16  christos 		}
   1467  1.16  christos 		if (dup2(devnull, STDIN_FILENO) == -1) {
   1468  1.16  christos 			error("%s: dup2: %s", tag, strerror(errno));
   1469  1.16  christos 			_exit(1);
   1470  1.16  christos 		}
   1471  1.16  christos 
   1472  1.16  christos 		/* Set up stdout as requested; leave stderr in place for now. */
   1473  1.16  christos 		fd = -1;
   1474  1.16  christos 		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
   1475  1.16  christos 			fd = p[1];
   1476  1.16  christos 		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
   1477  1.16  christos 			fd = devnull;
   1478  1.16  christos 		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
   1479  1.16  christos 			error("%s: dup2: %s", tag, strerror(errno));
   1480  1.16  christos 			_exit(1);
   1481  1.16  christos 		}
   1482  1.16  christos 		closefrom(STDERR_FILENO + 1);
   1483  1.16  christos 
   1484  1.16  christos 		/* Don't use permanently_set_uid() here to avoid fatal() */
   1485  1.16  christos 		if (setgid(pw->pw_gid) == -1) {
   1486  1.16  christos 			error("%s: setgid %u: %s", tag, (u_int)pw->pw_gid,
   1487  1.16  christos 			    strerror(errno));
   1488  1.16  christos 			_exit(1);
   1489  1.16  christos 		}
   1490  1.16  christos 		if (setuid(pw->pw_uid) == -1) {
   1491  1.16  christos 			error("%s: setuid %u: %s", tag, (u_int)pw->pw_uid,
   1492  1.16  christos 			    strerror(errno));
   1493  1.16  christos 			_exit(1);
   1494  1.16  christos 		}
   1495  1.16  christos 		/* stdin is pointed to /dev/null at this point */
   1496  1.16  christos 		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
   1497  1.16  christos 		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
   1498  1.16  christos 			error("%s: dup2: %s", tag, strerror(errno));
   1499  1.16  christos 			_exit(1);
   1500  1.16  christos 		}
   1501  1.16  christos 
   1502  1.16  christos 		execve(av[0], av, child_env);
   1503  1.16  christos 		error("%s exec \"%s\": %s", tag, command, strerror(errno));
   1504  1.16  christos 		_exit(127);
   1505  1.16  christos 	default: /* parent */
   1506  1.16  christos 		break;
   1507  1.16  christos 	}
   1508  1.16  christos 
   1509  1.16  christos 	close(p[1]);
   1510  1.16  christos 	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
   1511  1.16  christos 		close(p[0]);
   1512  1.16  christos 	else if ((f = fdopen(p[0], "r")) == NULL) {
   1513  1.16  christos 		error("%s: fdopen: %s", tag, strerror(errno));
   1514  1.16  christos 		close(p[0]);
   1515  1.16  christos 		/* Don't leave zombie child */
   1516  1.16  christos 		kill(pid, SIGTERM);
   1517  1.16  christos 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
   1518  1.16  christos 			;
   1519  1.16  christos 		return 0;
   1520  1.16  christos 	}
   1521  1.16  christos 	/* Success */
   1522  1.16  christos 	debug3("%s: %s pid %ld", __func__, tag, (long)pid);
   1523  1.16  christos 	if (child != NULL)
   1524  1.16  christos 		*child = f;
   1525  1.16  christos 	return pid;
   1526  1.16  christos }
   1527  1.16  christos 
   1528  1.16  christos /* Returns 0 if pid exited cleanly, non-zero otherwise */
   1529  1.16  christos int
   1530  1.16  christos exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
   1531  1.16  christos {
   1532  1.16  christos 	int status;
   1533  1.16  christos 
   1534  1.16  christos 	while (waitpid(pid, &status, 0) == -1) {
   1535  1.16  christos 		if (errno != EINTR) {
   1536  1.16  christos 			error("%s: waitpid: %s", tag, strerror(errno));
   1537  1.16  christos 			return -1;
   1538  1.16  christos 		}
   1539  1.16  christos 	}
   1540  1.16  christos 	if (WIFSIGNALED(status)) {
   1541  1.16  christos 		error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
   1542  1.16  christos 		return -1;
   1543  1.16  christos 	} else if (WEXITSTATUS(status) != 0) {
   1544  1.16  christos 		do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
   1545  1.16  christos 		    "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
   1546  1.16  christos 		return -1;
   1547  1.16  christos 	}
   1548  1.16  christos 	return 0;
   1549  1.16  christos }
   1550  1.16  christos 
   1551  1.16  christos /*
   1552  1.16  christos  * Check a given path for security. This is defined as all components
   1553  1.16  christos  * of the path to the file must be owned by either the owner of
   1554  1.16  christos  * of the file or root and no directories must be group or world writable.
   1555  1.16  christos  *
   1556  1.16  christos  * XXX Should any specific check be done for sym links ?
   1557  1.16  christos  *
   1558  1.16  christos  * Takes a file name, its stat information (preferably from fstat() to
   1559  1.16  christos  * avoid races), the uid of the expected owner, their home directory and an
   1560  1.16  christos  * error buffer plus max size as arguments.
   1561  1.16  christos  *
   1562  1.16  christos  * Returns 0 on success and -1 on failure
   1563  1.16  christos  */
   1564  1.16  christos int
   1565  1.16  christos safe_path(const char *name, struct stat *stp, const char *pw_dir,
   1566  1.16  christos     uid_t uid, char *err, size_t errlen)
   1567  1.16  christos {
   1568  1.16  christos 	char buf[PATH_MAX], homedir[PATH_MAX];
   1569  1.16  christos 	char *cp;
   1570  1.16  christos 	int comparehome = 0;
   1571  1.16  christos 	struct stat st;
   1572  1.16  christos 
   1573  1.16  christos 	if (realpath(name, buf) == NULL) {
   1574  1.16  christos 		snprintf(err, errlen, "realpath %s failed: %s", name,
   1575  1.16  christos 		    strerror(errno));
   1576  1.16  christos 		return -1;
   1577  1.16  christos 	}
   1578  1.16  christos 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
   1579  1.16  christos 		comparehome = 1;
   1580  1.16  christos 
   1581  1.16  christos 	if (!S_ISREG(stp->st_mode)) {
   1582  1.16  christos 		snprintf(err, errlen, "%s is not a regular file", buf);
   1583  1.16  christos 		return -1;
   1584  1.16  christos 	}
   1585  1.16  christos 	if ((stp->st_uid != 0 && stp->st_uid != uid) ||
   1586  1.16  christos 	    (stp->st_mode & 022) != 0) {
   1587  1.16  christos 		snprintf(err, errlen, "bad ownership or modes for file %s",
   1588  1.16  christos 		    buf);
   1589  1.16  christos 		return -1;
   1590  1.16  christos 	}
   1591  1.16  christos 
   1592  1.16  christos 	/* for each component of the canonical path, walking upwards */
   1593  1.16  christos 	for (;;) {
   1594  1.16  christos 		if ((cp = dirname(buf)) == NULL) {
   1595  1.16  christos 			snprintf(err, errlen, "dirname() failed");
   1596  1.16  christos 			return -1;
   1597  1.16  christos 		}
   1598  1.16  christos 		strlcpy(buf, cp, sizeof(buf));
   1599  1.16  christos 
   1600  1.16  christos 		if (stat(buf, &st) < 0 ||
   1601  1.16  christos 		    (st.st_uid != 0 && st.st_uid != uid) ||
   1602  1.16  christos 		    (st.st_mode & 022) != 0) {
   1603  1.16  christos 			snprintf(err, errlen,
   1604  1.16  christos 			    "bad ownership or modes for directory %s", buf);
   1605  1.16  christos 			return -1;
   1606  1.16  christos 		}
   1607  1.16  christos 
   1608  1.16  christos 		/* If are past the homedir then we can stop */
   1609  1.16  christos 		if (comparehome && strcmp(homedir, buf) == 0)
   1610  1.16  christos 			break;
   1611  1.16  christos 
   1612  1.16  christos 		/*
   1613  1.16  christos 		 * dirname should always complete with a "/" path,
   1614  1.16  christos 		 * but we can be paranoid and check for "." too
   1615  1.16  christos 		 */
   1616  1.16  christos 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
   1617  1.16  christos 			break;
   1618  1.16  christos 	}
   1619  1.16  christos 	return 0;
   1620  1.16  christos }
   1621  1.16  christos 
   1622  1.16  christos /*
   1623  1.16  christos  * Version of safe_path() that accepts an open file descriptor to
   1624  1.16  christos  * avoid races.
   1625  1.16  christos  *
   1626  1.16  christos  * Returns 0 on success and -1 on failure
   1627  1.16  christos  */
   1628  1.16  christos int
   1629  1.16  christos safe_path_fd(int fd, const char *file, struct passwd *pw,
   1630  1.16  christos     char *err, size_t errlen)
   1631  1.16  christos {
   1632  1.16  christos 	struct stat st;
   1633  1.16  christos 
   1634  1.16  christos 	/* check the open file to avoid races */
   1635  1.16  christos 	if (fstat(fd, &st) < 0) {
   1636  1.16  christos 		snprintf(err, errlen, "cannot stat file %s: %s",
   1637  1.16  christos 		    file, strerror(errno));
   1638  1.16  christos 		return -1;
   1639  1.16  christos 	}
   1640  1.16  christos 	return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
   1641  1.16  christos }
   1642  1.16  christos 
   1643  1.16  christos /*
   1644  1.16  christos  * Sets the value of the given variable in the environment.  If the variable
   1645  1.16  christos  * already exists, its value is overridden.
   1646  1.16  christos  */
   1647  1.16  christos void
   1648  1.16  christos child_set_env(char ***envp, u_int *envsizep, const char *name,
   1649  1.16  christos 	const char *value)
   1650  1.16  christos {
   1651  1.16  christos 	char **env;
   1652  1.16  christos 	u_int envsize;
   1653  1.16  christos 	u_int i, namelen;
   1654  1.16  christos 
   1655  1.16  christos 	if (strchr(name, '=') != NULL) {
   1656  1.16  christos 		error("Invalid environment variable \"%.100s\"", name);
   1657  1.16  christos 		return;
   1658  1.16  christos 	}
   1659  1.16  christos 
   1660  1.16  christos 	/*
   1661  1.16  christos 	 * Find the slot where the value should be stored.  If the variable
   1662  1.16  christos 	 * already exists, we reuse the slot; otherwise we append a new slot
   1663  1.16  christos 	 * at the end of the array, expanding if necessary.
   1664  1.16  christos 	 */
   1665  1.16  christos 	env = *envp;
   1666  1.16  christos 	namelen = strlen(name);
   1667  1.16  christos 	for (i = 0; env[i]; i++)
   1668  1.16  christos 		if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
   1669  1.16  christos 			break;
   1670  1.16  christos 	if (env[i]) {
   1671  1.16  christos 		/* Reuse the slot. */
   1672  1.16  christos 		free(env[i]);
   1673  1.16  christos 	} else {
   1674  1.16  christos 		/* New variable.  Expand if necessary. */
   1675  1.16  christos 		envsize = *envsizep;
   1676  1.16  christos 		if (i >= envsize - 1) {
   1677  1.16  christos 			if (envsize >= 1000)
   1678  1.16  christos 				fatal("child_set_env: too many env vars");
   1679  1.16  christos 			envsize += 50;
   1680  1.16  christos 			env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
   1681  1.16  christos 			*envsizep = envsize;
   1682  1.16  christos 		}
   1683  1.16  christos 		/* Need to set the NULL pointer at end of array beyond the new slot. */
   1684  1.16  christos 		env[i + 1] = NULL;
   1685  1.16  christos 	}
   1686  1.16  christos 
   1687  1.16  christos 	/* Allocate space and format the variable in the appropriate slot. */
   1688  1.16  christos 	env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
   1689  1.16  christos 	snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
   1690  1.16  christos }
   1691  1.16  christos 
   1692