1 /* $OpenBSD: misc.c,v 1.137 2019/01/23 21:50:56 dtucker Exp $ */
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/types.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
53 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
64 #ifdef SSH_TUN_OPENBSD
76 /* remove newline at end of string */
82 if (*t == '\n' || *t == '\r') {
92 /* set/unset filedescriptor to non-blocking */
98 val = fcntl(fd, F_GETFL);
100 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
103 if (val & O_NONBLOCK) {
104 debug3("fd %d is O_NONBLOCK", fd);
107 debug2("fd %d setting O_NONBLOCK", fd);
109 if (fcntl(fd, F_SETFL, val) == -1) {
110 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
118 unset_nonblock(int fd)
122 val = fcntl(fd, F_GETFL);
124 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
127 if (!(val & O_NONBLOCK)) {
128 debug3("fd %d is not O_NONBLOCK", fd);
131 debug("fd %d clearing O_NONBLOCK", fd);
133 if (fcntl(fd, F_SETFL, val) == -1) {
134 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
135 fd, strerror(errno));
142 ssh_gai_strerror(int gaierr)
144 if (gaierr == EAI_SYSTEM && errno != 0)
145 return strerror(errno);
146 return gai_strerror(gaierr);
149 /* disable nagle on socket */
157 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
158 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
162 debug2("fd %d is TCP_NODELAY", fd);
166 debug2("fd %d setting TCP_NODELAY", fd);
167 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
168 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
171 /* Allow local port reuse in TIME_WAIT */
173 set_reuseaddr(int fd)
177 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
178 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
184 /* Get/set routing domain */
188 #if defined(HAVE_SYS_GET_RDOMAIN)
189 return sys_get_rdomain(fd);
190 #elif defined(__OpenBSD__)
193 socklen_t len = sizeof(rtable);
195 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
196 error("Failed to get routing domain for fd %d: %s",
197 fd, strerror(errno));
200 xasprintf(&ret, "%d", rtable);
202 #else /* defined(__OpenBSD__) */
208 set_rdomain(int fd, const char *name)
210 #if defined(HAVE_SYS_SET_RDOMAIN)
211 return sys_set_rdomain(fd, name);
212 #elif defined(__OpenBSD__)
217 return 0; /* default table */
219 rtable = (int)strtonum(name, 0, 255, &errstr);
220 if (errstr != NULL) {
221 /* Shouldn't happen */
222 error("Invalid routing domain \"%s\": %s", name, errstr);
225 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
226 &rtable, sizeof(rtable)) == -1) {
227 error("Failed to set routing domain %d on fd %d: %s",
228 rtable, fd, strerror(errno));
232 #else /* defined(__OpenBSD__) */
233 error("Setting routing domain is not supported on this platform");
239 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
240 * *timeoutp with time remaining.
241 * Returns 0 if fd ready or -1 on timeout or error (see errno).
244 waitrfd(int fd, int *timeoutp)
247 struct timeval t_start;
250 monotime_tv(&t_start);
253 for (; *timeoutp >= 0;) {
254 r = poll(&pfd, 1, *timeoutp);
256 ms_subtract_diff(&t_start, timeoutp);
260 else if (r == -1 && errno != EAGAIN)
271 * Attempt a non-blocking connect(2) to the specified address, waiting up to
272 * *timeoutp milliseconds for the connection to complete. If the timeout is
273 * <=0, then wait indefinitely.
275 * Returns 0 on success or -1 on failure.
278 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
279 socklen_t addrlen, int *timeoutp)
282 socklen_t optlen = sizeof(optval);
284 /* No timeout: just do a blocking connect() */
285 if (timeoutp == NULL || *timeoutp <= 0)
286 return connect(sockfd, serv_addr, addrlen);
288 set_nonblock(sockfd);
289 if (connect(sockfd, serv_addr, addrlen) == 0) {
290 /* Succeeded already? */
291 unset_nonblock(sockfd);
293 } else if (errno != EINPROGRESS)
296 if (waitrfd(sockfd, timeoutp) == -1)
299 /* Completed or failed */
300 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
301 debug("getsockopt: %s", strerror(errno));
308 unset_nonblock(sockfd);
312 /* Characters considered whitespace in strsep calls. */
313 #define WHITESPACE " \t\r\n"
316 /* return next token in configuration line */
318 strdelim_internal(char **s, int split_equals)
329 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
334 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
335 /* Find matching quote */
336 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
337 return (NULL); /* no matching quote */
340 *s += strspn(*s + 1, WHITESPACE) + 1;
345 /* Allow only one '=' to be skipped */
346 if (split_equals && *s[0] == '=')
350 /* Skip any extra whitespace after first token */
351 *s += strspn(*s + 1, WHITESPACE) + 1;
352 if (split_equals && *s[0] == '=' && !wspace)
353 *s += strspn(*s + 1, WHITESPACE) + 1;
359 * Return next token in configuration line; splts on whitespace or a
360 * single '=' character.
365 return strdelim_internal(s, 1);
369 * Return next token in configuration line; splts on whitespace only.
374 return strdelim_internal(s, 0);
378 pwcopy(struct passwd *pw)
380 struct passwd *copy = xcalloc(1, sizeof(*copy));
382 copy->pw_name = xstrdup(pw->pw_name);
383 copy->pw_passwd = xstrdup(pw->pw_passwd);
384 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
385 copy->pw_gecos = xstrdup(pw->pw_gecos);
387 copy->pw_uid = pw->pw_uid;
388 copy->pw_gid = pw->pw_gid;
389 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
390 copy->pw_expire = pw->pw_expire;
392 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
393 copy->pw_change = pw->pw_change;
395 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
396 copy->pw_class = xstrdup(pw->pw_class);
398 copy->pw_dir = xstrdup(pw->pw_dir);
399 copy->pw_shell = xstrdup(pw->pw_shell);
404 * Convert ASCII string to TCP/IP port number.
405 * Port must be >=0 and <=65535.
406 * Return -1 if invalid.
409 a2port(const char *s)
415 port = strtonum(s, 0, 65535, &errstr);
418 if ((se = getservbyname(s, "tcp")) != NULL)
419 return ntohs(se->s_port);
424 a2tun(const char *s, int *remote)
426 const char *errstr = NULL;
430 if (remote != NULL) {
431 *remote = SSH_TUNID_ANY;
433 if ((ep = strchr(sp, ':')) == NULL) {
435 return (a2tun(s, NULL));
438 *remote = a2tun(ep, NULL);
439 tun = a2tun(sp, NULL);
441 return (*remote == SSH_TUNID_ERR ? *remote : tun);
444 if (strcasecmp(s, "any") == 0)
445 return (SSH_TUNID_ANY);
447 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
449 return (SSH_TUNID_ERR);
455 #define MINUTES (SECONDS * 60)
456 #define HOURS (MINUTES * 60)
457 #define DAYS (HOURS * 24)
458 #define WEEKS (DAYS * 7)
461 * Convert a time string into seconds; format is
465 * Valid time qualifiers are:
479 * Return -1 if time string is invalid.
482 convtime(const char *s)
484 long total, secs, multiplier = 1;
492 if (p == NULL || *p == '\0')
496 secs = strtol(p, &endp, 10);
498 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
511 multiplier = MINUTES;
528 if (secs >= LONG_MAX / multiplier)
531 if (total >= LONG_MAX - secs)
543 * Returns a standardized host+port identifier string.
544 * Caller must free returned string.
547 put_host_port(const char *host, u_short port)
551 if (port == 0 || port == SSH_DEFAULT_PORT)
552 return(xstrdup(host));
553 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
554 fatal("put_host_port: asprintf: %s", strerror(errno));
555 debug3("put_host_port: %s", hoststr);
560 * Search for next delimiter between hostnames/addresses and ports.
561 * Argument may be modified (for termination).
562 * Returns *cp if parsing succeeds.
563 * *cp is set to the start of the next field, if one was found.
564 * The delimiter char, if present, is stored in delim.
565 * If this is the last field, *cp is set to NULL.
568 hpdelim2(char **cp, char *delim)
572 if (cp == NULL || *cp == NULL)
577 if ((s = strchr(s, ']')) == NULL)
581 } else if ((s = strpbrk(s, ":/")) == NULL)
582 s = *cp + strlen(*cp); /* skip to end (see first case below) */
586 *cp = NULL; /* no more fields*/
593 *s = '\0'; /* terminate */
607 return hpdelim2(cp, NULL);
611 cleanhostname(char *host)
613 if (*host == '[' && host[strlen(host) - 1] == ']') {
614 host[strlen(host) - 1] = '\0';
625 if (*cp == ':') /* Leading colon is part of file name. */
631 if (*cp == '@' && *(cp+1) == '[')
633 if (*cp == ']' && *(cp+1) == ':' && flag)
635 if (*cp == ':' && !flag)
644 * Parse a [user@]host:[path] string.
645 * Caller must free returned user, host and path.
646 * Any of the pointer return arguments may be NULL (useful for syntax checking).
647 * If user was not specified then *userp will be set to NULL.
648 * If host was not specified then *hostp will be set to NULL.
649 * If path was not specified then *pathp will be set to ".".
650 * Returns 0 on success, -1 on failure.
653 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
655 char *user = NULL, *host = NULL, *path = NULL;
668 /* Check for remote syntax: [user@]host:[path] */
669 if ((tmp = colon(sdup)) == NULL)
672 /* Extract optional path */
678 /* Extract optional user and mandatory host */
679 tmp = strrchr(sdup, '@');
682 host = xstrdup(cleanhostname(tmp));
684 user = xstrdup(sdup);
686 host = xstrdup(cleanhostname(sdup));
713 * Parse a [user@]host[:port] string.
714 * Caller must free returned user and host.
715 * Any of the pointer return arguments may be NULL (useful for syntax checking).
716 * If user was not specified then *userp will be set to NULL.
717 * If port was not specified then *portp will be -1.
718 * Returns 0 on success, -1 on failure.
721 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
723 char *sdup, *cp, *tmp;
724 char *user = NULL, *host = NULL;
725 int port = -1, ret = -1;
734 if ((sdup = tmp = strdup(s)) == NULL)
736 /* Extract optional username */
737 if ((cp = strrchr(tmp, '@')) != NULL) {
741 if ((user = strdup(tmp)) == NULL)
745 /* Extract mandatory hostname */
746 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
748 host = xstrdup(cleanhostname(cp));
749 /* Convert and verify optional port */
750 if (tmp != NULL && *tmp != '\0') {
751 if ((port = a2port(tmp)) <= 0)
774 * Converts a two-byte hex string to decimal.
775 * Returns the decimal value or -1 for invalid input.
778 hexchar(const char *s)
780 unsigned char result[2];
783 for (i = 0; i < 2; i++) {
784 if (s[i] >= '0' && s[i] <= '9')
785 result[i] = (unsigned char)(s[i] - '0');
786 else if (s[i] >= 'a' && s[i] <= 'f')
787 result[i] = (unsigned char)(s[i] - 'a') + 10;
788 else if (s[i] >= 'A' && s[i] <= 'F')
789 result[i] = (unsigned char)(s[i] - 'A') + 10;
793 return (result[0] << 4) | result[1];
797 * Decode an url-encoded string.
798 * Returns a newly allocated string on success or NULL on failure.
801 urldecode(const char *src)
806 ret = xmalloc(strlen(src) + 1);
807 for (dst = ret; *src != '\0'; src++) {
813 if (!isxdigit((unsigned char)src[1]) ||
814 !isxdigit((unsigned char)src[2]) ||
815 (ch = hexchar(src + 1)) == -1) {
833 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
834 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
835 * Either user or path may be url-encoded (but not host or port).
836 * Caller must free returned user, host and path.
837 * Any of the pointer return arguments may be NULL (useful for syntax checking)
838 * but the scheme must always be specified.
839 * If user was not specified then *userp will be set to NULL.
840 * If port was not specified then *portp will be -1.
841 * If path was not specified then *pathp will be set to NULL.
842 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
845 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
846 int *portp, char **pathp)
848 char *uridup, *cp, *tmp, ch;
849 char *user = NULL, *host = NULL, *path = NULL;
850 int port = -1, ret = -1;
853 len = strlen(scheme);
854 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
867 uridup = tmp = xstrdup(uri);
869 /* Extract optional ssh-info (username + connection params) */
870 if ((cp = strchr(tmp, '@')) != NULL) {
874 /* Extract username and connection params */
875 if ((delim = strchr(tmp, ';')) != NULL) {
876 /* Just ignore connection params for now */
883 if ((user = urldecode(tmp)) == NULL)
888 /* Extract mandatory hostname */
889 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
891 host = xstrdup(cleanhostname(cp));
892 if (!valid_domain(host, 0, NULL))
895 if (tmp != NULL && *tmp != '\0') {
897 /* Convert and verify port. */
898 if ((cp = strchr(tmp, '/')) != NULL)
900 if ((port = a2port(tmp)) <= 0)
902 tmp = cp ? cp + 1 : NULL;
904 if (tmp != NULL && *tmp != '\0') {
905 /* Extract optional path */
906 if ((path = urldecode(tmp)) == NULL)
935 /* function to assist building execv() arguments */
937 addargs(arglist *args, char *fmt, ...)
945 r = vasprintf(&cp, fmt, ap);
948 fatal("addargs: argument too long");
950 nalloc = args->nalloc;
951 if (args->list == NULL) {
954 } else if (args->num+2 >= nalloc)
957 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
958 args->nalloc = nalloc;
959 args->list[args->num++] = cp;
960 args->list[args->num] = NULL;
964 replacearg(arglist *args, u_int which, char *fmt, ...)
971 r = vasprintf(&cp, fmt, ap);
974 fatal("replacearg: argument too long");
976 if (which >= args->num)
977 fatal("replacearg: tried to replace invalid arg %d >= %d",
979 free(args->list[which]);
980 args->list[which] = cp;
984 freeargs(arglist *args)
988 if (args->list != NULL) {
989 for (i = 0; i < args->num; i++)
992 args->nalloc = args->num = 0;
998 * Expands tildes in the file name. Returns data allocated by xmalloc.
999 * Warning: this calls getpw*.
1002 tilde_expand_filename(const char *filename, uid_t uid)
1004 const char *path, *sep;
1005 char user[128], *ret;
1009 if (*filename != '~')
1010 return (xstrdup(filename));
1013 path = strchr(filename, '/');
1014 if (path != NULL && path > filename) { /* ~user/path */
1015 slash = path - filename;
1016 if (slash > sizeof(user) - 1)
1017 fatal("tilde_expand_filename: ~username too long");
1018 memcpy(user, filename, slash);
1020 if ((pw = getpwnam(user)) == NULL)
1021 fatal("tilde_expand_filename: No such user %s", user);
1022 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
1023 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
1025 /* Make sure directory has a trailing '/' */
1026 len = strlen(pw->pw_dir);
1027 if (len == 0 || pw->pw_dir[len - 1] != '/')
1032 /* Skip leading '/' from specified path */
1034 filename = path + 1;
1036 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
1037 fatal("tilde_expand_filename: Path too long");
1043 * Expand a string with a set of %[char] escapes. A number of escapes may be
1044 * specified as (char *escape_chars, char *replacement) pairs. The list must
1045 * be terminated by a NULL escape_char. Returns replaced string in memory
1046 * allocated by xmalloc.
1049 percent_expand(const char *string, ...)
1051 #define EXPAND_MAX_KEYS 16
1052 u_int num_keys, i, j;
1056 } keys[EXPAND_MAX_KEYS];
1061 va_start(ap, string);
1062 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1063 keys[num_keys].key = va_arg(ap, char *);
1064 if (keys[num_keys].key == NULL)
1066 keys[num_keys].repl = va_arg(ap, char *);
1067 if (keys[num_keys].repl == NULL)
1068 fatal("%s: NULL replacement", __func__);
1070 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1071 fatal("%s: too many keys", __func__);
1076 for (i = 0; *string != '\0'; string++) {
1077 if (*string != '%') {
1080 if (i >= sizeof(buf))
1081 fatal("%s: string too long", __func__);
1089 if (*string == '\0')
1090 fatal("%s: invalid format", __func__);
1091 for (j = 0; j < num_keys; j++) {
1092 if (strchr(keys[j].key, *string) != NULL) {
1093 i = strlcat(buf, keys[j].repl, sizeof(buf));
1094 if (i >= sizeof(buf))
1095 fatal("%s: string too long", __func__);
1100 fatal("%s: unknown key %%%c", __func__, *string);
1102 return (xstrdup(buf));
1103 #undef EXPAND_MAX_KEYS
1107 tun_open(int tun, int mode, char **ifname)
1109 #if defined(CUSTOM_SYS_TUN_OPEN)
1110 return (sys_tun_open(tun, mode, ifname));
1111 #elif defined(SSH_TUN_OPENBSD)
1115 const char *tunbase = "tun";
1120 if (mode == SSH_TUNMODE_ETHERNET)
1123 /* Open the tunnel device */
1124 if (tun <= SSH_TUNID_MAX) {
1125 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1126 fd = open(name, O_RDWR);
1127 } else if (tun == SSH_TUNID_ANY) {
1128 for (tun = 100; tun >= 0; tun--) {
1129 snprintf(name, sizeof(name), "/dev/%s%d",
1131 if ((fd = open(name, O_RDWR)) >= 0)
1135 debug("%s: invalid tunnel %u", __func__, tun);
1140 debug("%s: %s open: %s", __func__, name, strerror(errno));
1144 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1146 /* Bring interface up if it is not already */
1147 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1148 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1151 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1152 debug("%s: get interface %s flags: %s", __func__,
1153 ifr.ifr_name, strerror(errno));
1157 if (!(ifr.ifr_flags & IFF_UP)) {
1158 ifr.ifr_flags |= IFF_UP;
1159 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1160 debug("%s: activate interface %s: %s", __func__,
1161 ifr.ifr_name, strerror(errno));
1167 *ifname = xstrdup(ifr.ifr_name);
1179 error("Tunnel interfaces are not supported on this platform");
1185 sanitise_stdfd(void)
1189 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1190 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1194 while (++dupfd <= STDERR_FILENO) {
1195 /* Only populate closed fds. */
1196 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1197 if (dup2(nullfd, dupfd) == -1) {
1198 fprintf(stderr, "dup2: %s\n", strerror(errno));
1203 if (nullfd > STDERR_FILENO)
1208 tohex(const void *vp, size_t l)
1210 const u_char *p = (const u_char *)vp;
1215 return xstrdup("tohex: length > 65536");
1219 for (i = 0; i < l; i++) {
1220 snprintf(b, sizeof(b), "%02x", p[i]);
1227 get_u64(const void *vp)
1229 const u_char *p = (const u_char *)vp;
1232 v = (u_int64_t)p[0] << 56;
1233 v |= (u_int64_t)p[1] << 48;
1234 v |= (u_int64_t)p[2] << 40;
1235 v |= (u_int64_t)p[3] << 32;
1236 v |= (u_int64_t)p[4] << 24;
1237 v |= (u_int64_t)p[5] << 16;
1238 v |= (u_int64_t)p[6] << 8;
1239 v |= (u_int64_t)p[7];
1245 get_u32(const void *vp)
1247 const u_char *p = (const u_char *)vp;
1250 v = (u_int32_t)p[0] << 24;
1251 v |= (u_int32_t)p[1] << 16;
1252 v |= (u_int32_t)p[2] << 8;
1253 v |= (u_int32_t)p[3];
1259 get_u32_le(const void *vp)
1261 const u_char *p = (const u_char *)vp;
1264 v = (u_int32_t)p[0];
1265 v |= (u_int32_t)p[1] << 8;
1266 v |= (u_int32_t)p[2] << 16;
1267 v |= (u_int32_t)p[3] << 24;
1273 get_u16(const void *vp)
1275 const u_char *p = (const u_char *)vp;
1278 v = (u_int16_t)p[0] << 8;
1279 v |= (u_int16_t)p[1];
1285 put_u64(void *vp, u_int64_t v)
1287 u_char *p = (u_char *)vp;
1289 p[0] = (u_char)(v >> 56) & 0xff;
1290 p[1] = (u_char)(v >> 48) & 0xff;
1291 p[2] = (u_char)(v >> 40) & 0xff;
1292 p[3] = (u_char)(v >> 32) & 0xff;
1293 p[4] = (u_char)(v >> 24) & 0xff;
1294 p[5] = (u_char)(v >> 16) & 0xff;
1295 p[6] = (u_char)(v >> 8) & 0xff;
1296 p[7] = (u_char)v & 0xff;
1300 put_u32(void *vp, u_int32_t v)
1302 u_char *p = (u_char *)vp;
1304 p[0] = (u_char)(v >> 24) & 0xff;
1305 p[1] = (u_char)(v >> 16) & 0xff;
1306 p[2] = (u_char)(v >> 8) & 0xff;
1307 p[3] = (u_char)v & 0xff;
1311 put_u32_le(void *vp, u_int32_t v)
1313 u_char *p = (u_char *)vp;
1315 p[0] = (u_char)v & 0xff;
1316 p[1] = (u_char)(v >> 8) & 0xff;
1317 p[2] = (u_char)(v >> 16) & 0xff;
1318 p[3] = (u_char)(v >> 24) & 0xff;
1322 put_u16(void *vp, u_int16_t v)
1324 u_char *p = (u_char *)vp;
1326 p[0] = (u_char)(v >> 8) & 0xff;
1327 p[1] = (u_char)v & 0xff;
1331 ms_subtract_diff(struct timeval *start, int *ms)
1333 struct timeval diff, finish;
1335 monotime_tv(&finish);
1336 timersub(&finish, start, &diff);
1337 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1341 ms_to_timeval(struct timeval *tv, int ms)
1345 tv->tv_sec = ms / 1000;
1346 tv->tv_usec = (ms % 1000) * 1000;
1350 monotime_ts(struct timespec *ts)
1353 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1354 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1355 static int gettime_failed = 0;
1357 if (!gettime_failed) {
1358 # ifdef CLOCK_BOOTTIME
1359 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1361 # endif /* CLOCK_BOOTTIME */
1362 # ifdef CLOCK_MONOTONIC
1363 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1365 # endif /* CLOCK_MONOTONIC */
1366 # ifdef CLOCK_REALTIME
1367 /* Not monotonic, but we're almost out of options here. */
1368 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1370 # endif /* CLOCK_REALTIME */
1371 debug3("clock_gettime: %s", strerror(errno));
1374 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1375 gettimeofday(&tv, NULL);
1376 ts->tv_sec = tv.tv_sec;
1377 ts->tv_nsec = (long)tv.tv_usec * 1000;
1381 monotime_tv(struct timeval *tv)
1386 tv->tv_sec = ts.tv_sec;
1387 tv->tv_usec = ts.tv_nsec / 1000;
1400 monotime_double(void)
1405 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1409 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1411 bw->buflen = buflen;
1413 bw->thresh = buflen;
1415 timerclear(&bw->bwstart);
1416 timerclear(&bw->bwend);
1419 /* Callback from read/write loop to insert bandwidth-limiting delays */
1421 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1424 struct timespec ts, rm;
1426 bw->lamt += read_len;
1427 if (!timerisset(&bw->bwstart)) {
1428 monotime_tv(&bw->bwstart);
1431 if (bw->lamt < bw->thresh)
1434 monotime_tv(&bw->bwend);
1435 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1436 if (!timerisset(&bw->bwend))
1440 waitlen = (double)1000000L * bw->lamt / bw->rate;
1442 bw->bwstart.tv_sec = waitlen / 1000000L;
1443 bw->bwstart.tv_usec = waitlen % 1000000L;
1445 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1446 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1448 /* Adjust the wait time */
1449 if (bw->bwend.tv_sec) {
1451 if (bw->thresh < bw->buflen / 4)
1452 bw->thresh = bw->buflen / 4;
1453 } else if (bw->bwend.tv_usec < 10000) {
1455 if (bw->thresh > bw->buflen * 8)
1456 bw->thresh = bw->buflen * 8;
1459 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1460 while (nanosleep(&ts, &rm) == -1) {
1468 monotime_tv(&bw->bwstart);
1471 /* Make a template filename for mk[sd]temp() */
1473 mktemp_proto(char *s, size_t len)
1478 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1479 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1480 if (r > 0 && (size_t)r < len)
1483 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1484 if (r < 0 || (size_t)r >= len)
1485 fatal("%s: template string too short", __func__);
1488 static const struct {
1492 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1493 { "af11", IPTOS_DSCP_AF11 },
1494 { "af12", IPTOS_DSCP_AF12 },
1495 { "af13", IPTOS_DSCP_AF13 },
1496 { "af21", IPTOS_DSCP_AF21 },
1497 { "af22", IPTOS_DSCP_AF22 },
1498 { "af23", IPTOS_DSCP_AF23 },
1499 { "af31", IPTOS_DSCP_AF31 },
1500 { "af32", IPTOS_DSCP_AF32 },
1501 { "af33", IPTOS_DSCP_AF33 },
1502 { "af41", IPTOS_DSCP_AF41 },
1503 { "af42", IPTOS_DSCP_AF42 },
1504 { "af43", IPTOS_DSCP_AF43 },
1505 { "cs0", IPTOS_DSCP_CS0 },
1506 { "cs1", IPTOS_DSCP_CS1 },
1507 { "cs2", IPTOS_DSCP_CS2 },
1508 { "cs3", IPTOS_DSCP_CS3 },
1509 { "cs4", IPTOS_DSCP_CS4 },
1510 { "cs5", IPTOS_DSCP_CS5 },
1511 { "cs6", IPTOS_DSCP_CS6 },
1512 { "cs7", IPTOS_DSCP_CS7 },
1513 { "ef", IPTOS_DSCP_EF },
1514 { "lowdelay", IPTOS_LOWDELAY },
1515 { "throughput", IPTOS_THROUGHPUT },
1516 { "reliability", IPTOS_RELIABILITY },
1521 parse_ipqos(const char *cp)
1529 for (i = 0; ipqos[i].name != NULL; i++) {
1530 if (strcasecmp(cp, ipqos[i].name) == 0)
1531 return ipqos[i].value;
1533 /* Try parsing as an integer */
1534 val = strtol(cp, &ep, 0);
1535 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1541 iptos2str(int iptos)
1544 static char iptos_str[sizeof "0xff"];
1546 for (i = 0; ipqos[i].name != NULL; i++) {
1547 if (ipqos[i].value == iptos)
1548 return ipqos[i].name;
1550 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1558 *s = tolower((u_char)*s);
1562 unix_listener(const char *path, int backlog, int unlink_first)
1564 struct sockaddr_un sunaddr;
1565 int saved_errno, sock;
1567 memset(&sunaddr, 0, sizeof(sunaddr));
1568 sunaddr.sun_family = AF_UNIX;
1569 if (strlcpy(sunaddr.sun_path, path,
1570 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1571 error("%s: path \"%s\" too long for Unix domain socket",
1573 errno = ENAMETOOLONG;
1577 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1579 saved_errno = errno;
1580 error("%s: socket: %.100s", __func__, strerror(errno));
1581 errno = saved_errno;
1584 if (unlink_first == 1) {
1585 if (unlink(path) != 0 && errno != ENOENT)
1586 error("unlink(%s): %.100s", path, strerror(errno));
1588 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1589 saved_errno = errno;
1590 error("%s: cannot bind to path %s: %s",
1591 __func__, path, strerror(errno));
1593 errno = saved_errno;
1596 if (listen(sock, backlog) < 0) {
1597 saved_errno = errno;
1598 error("%s: cannot listen on path %s: %s",
1599 __func__, path, strerror(errno));
1602 errno = saved_errno;
1609 sock_set_v6only(int s)
1611 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1614 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1615 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1616 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1621 * Compares two strings that maybe be NULL. Returns non-zero if strings
1622 * are both NULL or are identical, returns zero otherwise.
1625 strcmp_maybe_null(const char *a, const char *b)
1627 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1629 if (a != NULL && strcmp(a, b) != 0)
1635 * Compare two forwards, returning non-zero if they are identical or
1639 forward_equals(const struct Forward *a, const struct Forward *b)
1641 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1643 if (a->listen_port != b->listen_port)
1645 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1647 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1649 if (a->connect_port != b->connect_port)
1651 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1653 /* allocated_port and handle are not checked */
1657 /* returns 1 if process is already daemonized, 0 otherwise */
1663 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1665 return 0; /* have controlling terminal */
1668 return 0; /* parent is not init */
1669 if (getsid(0) != getpid())
1670 return 0; /* not session leader */
1671 debug3("already daemonized");
1677 * Splits 's' into an argument vector. Handles quoted string and basic
1678 * escape characters (\\, \", \'). Caller must free the argument vector
1682 argv_split(const char *s, int *argcp, char ***argvp)
1684 int r = SSH_ERR_INTERNAL_ERROR;
1685 int argc = 0, quote, i, j;
1686 char *arg, **argv = xcalloc(1, sizeof(*argv));
1691 for (i = 0; s[i] != '\0'; i++) {
1692 /* Skip leading whitespace */
1693 if (s[i] == ' ' || s[i] == '\t')
1696 /* Start of a token */
1699 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1701 else if (s[i] == '\'' || s[i] == '"')
1704 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1705 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1708 /* Copy the token in, removing escapes */
1709 for (j = 0; s[i] != '\0'; i++) {
1711 if (s[i + 1] == '\'' ||
1717 /* Unrecognised escape */
1720 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1722 else if (quote != 0 && s[i] == quote)
1729 /* Ran out of string looking for close quote */
1730 r = SSH_ERR_INVALID_FORMAT;
1743 if (argc != 0 && argv != NULL) {
1744 for (i = 0; i < argc; i++)
1752 * Reassemble an argument vector into a string, quoting and escaping as
1753 * necessary. Caller must free returned string.
1756 argv_assemble(int argc, char **argv)
1760 struct sshbuf *buf, *arg;
1762 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1763 fatal("%s: sshbuf_new failed", __func__);
1765 for (i = 0; i < argc; i++) {
1768 for (j = 0; argv[i][j] != '\0'; j++) {
1775 r = sshbuf_put_u8(arg, c);
1780 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1784 r = sshbuf_put_u8(arg, c);
1788 fatal("%s: sshbuf_put_u8: %s",
1789 __func__, ssh_err(r));
1791 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1792 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1793 (r = sshbuf_putb(buf, arg)) != 0 ||
1794 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1795 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1797 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1798 fatal("%s: malloc failed", __func__);
1799 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1800 ret[sshbuf_len(buf)] = '\0';
1806 /* Returns 0 if pid exited cleanly, non-zero otherwise */
1808 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1812 while (waitpid(pid, &status, 0) == -1) {
1813 if (errno != EINTR) {
1814 error("%s: waitpid: %s", tag, strerror(errno));
1818 if (WIFSIGNALED(status)) {
1819 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1821 } else if (WEXITSTATUS(status) != 0) {
1822 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1823 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1830 * Check a given path for security. This is defined as all components
1831 * of the path to the file must be owned by either the owner of
1832 * of the file or root and no directories must be group or world writable.
1834 * XXX Should any specific check be done for sym links ?
1836 * Takes a file name, its stat information (preferably from fstat() to
1837 * avoid races), the uid of the expected owner, their home directory and an
1838 * error buffer plus max size as arguments.
1840 * Returns 0 on success and -1 on failure
1843 safe_path(const char *name, struct stat *stp, const char *pw_dir,
1844 uid_t uid, char *err, size_t errlen)
1846 char buf[PATH_MAX], homedir[PATH_MAX];
1848 int comparehome = 0;
1851 if (realpath(name, buf) == NULL) {
1852 snprintf(err, errlen, "realpath %s failed: %s", name,
1856 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1859 if (!S_ISREG(stp->st_mode)) {
1860 snprintf(err, errlen, "%s is not a regular file", buf);
1863 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1864 (stp->st_mode & 022) != 0) {
1865 snprintf(err, errlen, "bad ownership or modes for file %s",
1870 /* for each component of the canonical path, walking upwards */
1872 if ((cp = dirname(buf)) == NULL) {
1873 snprintf(err, errlen, "dirname() failed");
1876 strlcpy(buf, cp, sizeof(buf));
1878 if (stat(buf, &st) < 0 ||
1879 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1880 (st.st_mode & 022) != 0) {
1881 snprintf(err, errlen,
1882 "bad ownership or modes for directory %s", buf);
1886 /* If are past the homedir then we can stop */
1887 if (comparehome && strcmp(homedir, buf) == 0)
1891 * dirname should always complete with a "/" path,
1892 * but we can be paranoid and check for "." too
1894 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1901 * Version of safe_path() that accepts an open file descriptor to
1904 * Returns 0 on success and -1 on failure
1907 safe_path_fd(int fd, const char *file, struct passwd *pw,
1908 char *err, size_t errlen)
1912 /* check the open file to avoid races */
1913 if (fstat(fd, &st) < 0) {
1914 snprintf(err, errlen, "cannot stat file %s: %s",
1915 file, strerror(errno));
1918 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1922 * Sets the value of the given variable in the environment. If the variable
1923 * already exists, its value is overridden.
1926 child_set_env(char ***envp, u_int *envsizep, const char *name,
1933 if (strchr(name, '=') != NULL) {
1934 error("Invalid environment variable \"%.100s\"", name);
1939 * If we're passed an uninitialized list, allocate a single null
1940 * entry before continuing.
1942 if (*envp == NULL && *envsizep == 0) {
1943 *envp = xmalloc(sizeof(char *));
1949 * Find the slot where the value should be stored. If the variable
1950 * already exists, we reuse the slot; otherwise we append a new slot
1951 * at the end of the array, expanding if necessary.
1954 namelen = strlen(name);
1955 for (i = 0; env[i]; i++)
1956 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1959 /* Reuse the slot. */
1962 /* New variable. Expand if necessary. */
1963 envsize = *envsizep;
1964 if (i >= envsize - 1) {
1965 if (envsize >= 1000)
1966 fatal("child_set_env: too many env vars");
1968 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1969 *envsizep = envsize;
1971 /* Need to set the NULL pointer at end of array beyond the new slot. */
1975 /* Allocate space and format the variable in the appropriate slot. */
1977 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1978 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1982 * Check and optionally lowercase a domain name, also removes trailing '.'
1983 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1986 valid_domain(char *name, int makelower, const char **errstr)
1988 size_t i, l = strlen(name);
1989 u_char c, last = '\0';
1990 static char errbuf[256];
1993 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1996 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1997 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1998 "starts with invalid character", name);
2001 for (i = 0; i < l; i++) {
2002 c = tolower((u_char)name[i]);
2005 if (last == '.' && c == '.') {
2006 snprintf(errbuf, sizeof(errbuf), "domain name "
2007 "\"%.100s\" contains consecutive separators", name);
2010 if (c != '.' && c != '-' && !isalnum(c) &&
2011 c != '_') /* technically invalid, but common */ {
2012 snprintf(errbuf, sizeof(errbuf), "domain name "
2013 "\"%.100s\" contains invalid characters", name);
2018 if (name[l - 1] == '.')
2030 * Verify that a environment variable name (not including initial '$') is
2031 * valid; consisting of one or more alphanumeric or underscore characters only.
2032 * Returns 1 on valid, 0 otherwise.
2035 valid_env_name(const char *name)
2039 if (name[0] == '\0')
2041 for (cp = name; *cp != '\0'; cp++) {
2042 if (!isalnum((u_char)*cp) && *cp != '_')
2049 atoi_err(const char *nptr, int *val)
2051 const char *errstr = NULL;
2054 if (nptr == NULL || *nptr == '\0')
2056 num = strtonum(nptr, 0, INT_MAX, &errstr);
2063 parse_absolute_time(const char *s, uint64_t *tp)
2072 * POSIX strptime says "The application shall ensure that there
2073 * is white-space or other non-alphanumeric characters between
2074 * any two conversion specifications" so arrange things this way.
2076 switch (strlen(s)) {
2077 case 8: /* YYYYMMDD */
2079 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2081 case 12: /* YYYYMMDDHHMM */
2082 fmt = "%Y-%m-%dT%H:%M";
2083 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2084 s, s + 4, s + 6, s + 8, s + 10);
2086 case 14: /* YYYYMMDDHHMMSS */
2087 fmt = "%Y-%m-%dT%H:%M:%S";
2088 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2089 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2092 return SSH_ERR_INVALID_FORMAT;
2095 memset(&tm, 0, sizeof(tm));
2096 if (strptime(buf, fmt, &tm) == NULL)
2097 return SSH_ERR_INVALID_FORMAT;
2098 if ((tt = mktime(&tm)) < 0)
2099 return SSH_ERR_INVALID_FORMAT;
2106 format_absolute_time(uint64_t t, char *buf, size_t len)
2108 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2111 localtime_r(&tt, &tm);
2112 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2115 /* check if path is absolute */
2117 path_absolute(const char *path)
2119 return (*path == '/') ? 1 : 0;