1 /* $OpenBSD: misc.c,v 1.133 2018/10/05 14:26:09 naddy 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>
49 #include <netinet/in.h>
50 #include <netinet/in_systm.h>
51 #include <netinet/ip.h>
52 #include <netinet/tcp.h>
53 #include <arpa/inet.h>
63 #ifdef SSH_TUN_OPENBSD
75 /* remove newline at end of string */
81 if (*t == '\n' || *t == '\r') {
91 /* set/unset filedescriptor to non-blocking */
97 val = fcntl(fd, F_GETFL);
99 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
102 if (val & O_NONBLOCK) {
103 debug3("fd %d is O_NONBLOCK", fd);
106 debug2("fd %d setting O_NONBLOCK", fd);
108 if (fcntl(fd, F_SETFL, val) == -1) {
109 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
117 unset_nonblock(int fd)
121 val = fcntl(fd, F_GETFL);
123 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
126 if (!(val & O_NONBLOCK)) {
127 debug3("fd %d is not O_NONBLOCK", fd);
130 debug("fd %d clearing O_NONBLOCK", fd);
132 if (fcntl(fd, F_SETFL, val) == -1) {
133 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
134 fd, strerror(errno));
141 ssh_gai_strerror(int gaierr)
143 if (gaierr == EAI_SYSTEM && errno != 0)
144 return strerror(errno);
145 return gai_strerror(gaierr);
148 /* disable nagle on socket */
156 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
157 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
161 debug2("fd %d is TCP_NODELAY", fd);
165 debug2("fd %d setting TCP_NODELAY", fd);
166 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
167 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
170 /* Allow local port reuse in TIME_WAIT */
172 set_reuseaddr(int fd)
176 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
177 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
183 /* Get/set routing domain */
187 #if defined(HAVE_SYS_GET_RDOMAIN)
188 return sys_get_rdomain(fd);
189 #elif defined(__OpenBSD__)
192 socklen_t len = sizeof(rtable);
194 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
195 error("Failed to get routing domain for fd %d: %s",
196 fd, strerror(errno));
199 xasprintf(&ret, "%d", rtable);
201 #else /* defined(__OpenBSD__) */
207 set_rdomain(int fd, const char *name)
209 #if defined(HAVE_SYS_SET_RDOMAIN)
210 return sys_set_rdomain(fd, name);
211 #elif defined(__OpenBSD__)
216 return 0; /* default table */
218 rtable = (int)strtonum(name, 0, 255, &errstr);
219 if (errstr != NULL) {
220 /* Shouldn't happen */
221 error("Invalid routing domain \"%s\": %s", name, errstr);
224 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
225 &rtable, sizeof(rtable)) == -1) {
226 error("Failed to set routing domain %d on fd %d: %s",
227 rtable, fd, strerror(errno));
231 #else /* defined(__OpenBSD__) */
232 error("Setting routing domain is not supported on this platform");
237 /* Characters considered whitespace in strsep calls. */
238 #define WHITESPACE " \t\r\n"
241 /* return next token in configuration line */
243 strdelim_internal(char **s, int split_equals)
254 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
259 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
260 /* Find matching quote */
261 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
262 return (NULL); /* no matching quote */
265 *s += strspn(*s + 1, WHITESPACE) + 1;
270 /* Allow only one '=' to be skipped */
271 if (split_equals && *s[0] == '=')
275 /* Skip any extra whitespace after first token */
276 *s += strspn(*s + 1, WHITESPACE) + 1;
277 if (split_equals && *s[0] == '=' && !wspace)
278 *s += strspn(*s + 1, WHITESPACE) + 1;
284 * Return next token in configuration line; splts on whitespace or a
285 * single '=' character.
290 return strdelim_internal(s, 1);
294 * Return next token in configuration line; splts on whitespace only.
299 return strdelim_internal(s, 0);
303 pwcopy(struct passwd *pw)
305 struct passwd *copy = xcalloc(1, sizeof(*copy));
307 copy->pw_name = xstrdup(pw->pw_name);
308 copy->pw_passwd = xstrdup(pw->pw_passwd);
309 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
310 copy->pw_gecos = xstrdup(pw->pw_gecos);
312 copy->pw_uid = pw->pw_uid;
313 copy->pw_gid = pw->pw_gid;
314 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
315 copy->pw_expire = pw->pw_expire;
317 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
318 copy->pw_change = pw->pw_change;
320 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
321 copy->pw_class = xstrdup(pw->pw_class);
323 copy->pw_dir = xstrdup(pw->pw_dir);
324 copy->pw_shell = xstrdup(pw->pw_shell);
329 * Convert ASCII string to TCP/IP port number.
330 * Port must be >=0 and <=65535.
331 * Return -1 if invalid.
334 a2port(const char *s)
340 port = strtonum(s, 0, 65535, &errstr);
343 if ((se = getservbyname(s, "tcp")) != NULL)
344 return ntohs(se->s_port);
349 a2tun(const char *s, int *remote)
351 const char *errstr = NULL;
355 if (remote != NULL) {
356 *remote = SSH_TUNID_ANY;
358 if ((ep = strchr(sp, ':')) == NULL) {
360 return (a2tun(s, NULL));
363 *remote = a2tun(ep, NULL);
364 tun = a2tun(sp, NULL);
366 return (*remote == SSH_TUNID_ERR ? *remote : tun);
369 if (strcasecmp(s, "any") == 0)
370 return (SSH_TUNID_ANY);
372 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
374 return (SSH_TUNID_ERR);
380 #define MINUTES (SECONDS * 60)
381 #define HOURS (MINUTES * 60)
382 #define DAYS (HOURS * 24)
383 #define WEEKS (DAYS * 7)
386 * Convert a time string into seconds; format is
390 * Valid time qualifiers are:
404 * Return -1 if time string is invalid.
407 convtime(const char *s)
409 long total, secs, multiplier = 1;
417 if (p == NULL || *p == '\0')
421 secs = strtol(p, &endp, 10);
423 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
436 multiplier = MINUTES;
453 if (secs >= LONG_MAX / multiplier)
456 if (total >= LONG_MAX - secs)
468 * Returns a standardized host+port identifier string.
469 * Caller must free returned string.
472 put_host_port(const char *host, u_short port)
476 if (port == 0 || port == SSH_DEFAULT_PORT)
477 return(xstrdup(host));
478 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
479 fatal("put_host_port: asprintf: %s", strerror(errno));
480 debug3("put_host_port: %s", hoststr);
485 * Search for next delimiter between hostnames/addresses and ports.
486 * Argument may be modified (for termination).
487 * Returns *cp if parsing succeeds.
488 * *cp is set to the start of the next field, if one was found.
489 * The delimiter char, if present, is stored in delim.
490 * If this is the last field, *cp is set to NULL.
493 hpdelim2(char **cp, char *delim)
497 if (cp == NULL || *cp == NULL)
502 if ((s = strchr(s, ']')) == NULL)
506 } else if ((s = strpbrk(s, ":/")) == NULL)
507 s = *cp + strlen(*cp); /* skip to end (see first case below) */
511 *cp = NULL; /* no more fields*/
518 *s = '\0'; /* terminate */
532 return hpdelim2(cp, NULL);
536 cleanhostname(char *host)
538 if (*host == '[' && host[strlen(host) - 1] == ']') {
539 host[strlen(host) - 1] = '\0';
550 if (*cp == ':') /* Leading colon is part of file name. */
556 if (*cp == '@' && *(cp+1) == '[')
558 if (*cp == ']' && *(cp+1) == ':' && flag)
560 if (*cp == ':' && !flag)
569 * Parse a [user@]host:[path] string.
570 * Caller must free returned user, host and path.
571 * Any of the pointer return arguments may be NULL (useful for syntax checking).
572 * If user was not specified then *userp will be set to NULL.
573 * If host was not specified then *hostp will be set to NULL.
574 * If path was not specified then *pathp will be set to ".".
575 * Returns 0 on success, -1 on failure.
578 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
580 char *user = NULL, *host = NULL, *path = NULL;
593 /* Check for remote syntax: [user@]host:[path] */
594 if ((tmp = colon(sdup)) == NULL)
597 /* Extract optional path */
603 /* Extract optional user and mandatory host */
604 tmp = strrchr(sdup, '@');
607 host = xstrdup(cleanhostname(tmp));
609 user = xstrdup(sdup);
611 host = xstrdup(cleanhostname(sdup));
638 * Parse a [user@]host[:port] string.
639 * Caller must free returned user and host.
640 * Any of the pointer return arguments may be NULL (useful for syntax checking).
641 * If user was not specified then *userp will be set to NULL.
642 * If port was not specified then *portp will be -1.
643 * Returns 0 on success, -1 on failure.
646 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
648 char *sdup, *cp, *tmp;
649 char *user = NULL, *host = NULL;
650 int port = -1, ret = -1;
659 if ((sdup = tmp = strdup(s)) == NULL)
661 /* Extract optional username */
662 if ((cp = strrchr(tmp, '@')) != NULL) {
666 if ((user = strdup(tmp)) == NULL)
670 /* Extract mandatory hostname */
671 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
673 host = xstrdup(cleanhostname(cp));
674 /* Convert and verify optional port */
675 if (tmp != NULL && *tmp != '\0') {
676 if ((port = a2port(tmp)) <= 0)
699 * Converts a two-byte hex string to decimal.
700 * Returns the decimal value or -1 for invalid input.
703 hexchar(const char *s)
705 unsigned char result[2];
708 for (i = 0; i < 2; i++) {
709 if (s[i] >= '0' && s[i] <= '9')
710 result[i] = (unsigned char)(s[i] - '0');
711 else if (s[i] >= 'a' && s[i] <= 'f')
712 result[i] = (unsigned char)(s[i] - 'a') + 10;
713 else if (s[i] >= 'A' && s[i] <= 'F')
714 result[i] = (unsigned char)(s[i] - 'A') + 10;
718 return (result[0] << 4) | result[1];
722 * Decode an url-encoded string.
723 * Returns a newly allocated string on success or NULL on failure.
726 urldecode(const char *src)
731 ret = xmalloc(strlen(src) + 1);
732 for (dst = ret; *src != '\0'; src++) {
738 if (!isxdigit((unsigned char)src[1]) ||
739 !isxdigit((unsigned char)src[2]) ||
740 (ch = hexchar(src + 1)) == -1) {
758 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
759 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
760 * Either user or path may be url-encoded (but not host or port).
761 * Caller must free returned user, host and path.
762 * Any of the pointer return arguments may be NULL (useful for syntax checking)
763 * but the scheme must always be specified.
764 * If user was not specified then *userp will be set to NULL.
765 * If port was not specified then *portp will be -1.
766 * If path was not specified then *pathp will be set to NULL.
767 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
770 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
771 int *portp, char **pathp)
773 char *uridup, *cp, *tmp, ch;
774 char *user = NULL, *host = NULL, *path = NULL;
775 int port = -1, ret = -1;
778 len = strlen(scheme);
779 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
792 uridup = tmp = xstrdup(uri);
794 /* Extract optional ssh-info (username + connection params) */
795 if ((cp = strchr(tmp, '@')) != NULL) {
799 /* Extract username and connection params */
800 if ((delim = strchr(tmp, ';')) != NULL) {
801 /* Just ignore connection params for now */
808 if ((user = urldecode(tmp)) == NULL)
813 /* Extract mandatory hostname */
814 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
816 host = xstrdup(cleanhostname(cp));
817 if (!valid_domain(host, 0, NULL))
820 if (tmp != NULL && *tmp != '\0') {
822 /* Convert and verify port. */
823 if ((cp = strchr(tmp, '/')) != NULL)
825 if ((port = a2port(tmp)) <= 0)
827 tmp = cp ? cp + 1 : NULL;
829 if (tmp != NULL && *tmp != '\0') {
830 /* Extract optional path */
831 if ((path = urldecode(tmp)) == NULL)
860 /* function to assist building execv() arguments */
862 addargs(arglist *args, char *fmt, ...)
870 r = vasprintf(&cp, fmt, ap);
873 fatal("addargs: argument too long");
875 nalloc = args->nalloc;
876 if (args->list == NULL) {
879 } else if (args->num+2 >= nalloc)
882 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
883 args->nalloc = nalloc;
884 args->list[args->num++] = cp;
885 args->list[args->num] = NULL;
889 replacearg(arglist *args, u_int which, char *fmt, ...)
896 r = vasprintf(&cp, fmt, ap);
899 fatal("replacearg: argument too long");
901 if (which >= args->num)
902 fatal("replacearg: tried to replace invalid arg %d >= %d",
904 free(args->list[which]);
905 args->list[which] = cp;
909 freeargs(arglist *args)
913 if (args->list != NULL) {
914 for (i = 0; i < args->num; i++)
917 args->nalloc = args->num = 0;
923 * Expands tildes in the file name. Returns data allocated by xmalloc.
924 * Warning: this calls getpw*.
927 tilde_expand_filename(const char *filename, uid_t uid)
929 const char *path, *sep;
930 char user[128], *ret;
934 if (*filename != '~')
935 return (xstrdup(filename));
938 path = strchr(filename, '/');
939 if (path != NULL && path > filename) { /* ~user/path */
940 slash = path - filename;
941 if (slash > sizeof(user) - 1)
942 fatal("tilde_expand_filename: ~username too long");
943 memcpy(user, filename, slash);
945 if ((pw = getpwnam(user)) == NULL)
946 fatal("tilde_expand_filename: No such user %s", user);
947 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
948 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
950 /* Make sure directory has a trailing '/' */
951 len = strlen(pw->pw_dir);
952 if (len == 0 || pw->pw_dir[len - 1] != '/')
957 /* Skip leading '/' from specified path */
961 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
962 fatal("tilde_expand_filename: Path too long");
968 * Expand a string with a set of %[char] escapes. A number of escapes may be
969 * specified as (char *escape_chars, char *replacement) pairs. The list must
970 * be terminated by a NULL escape_char. Returns replaced string in memory
971 * allocated by xmalloc.
974 percent_expand(const char *string, ...)
976 #define EXPAND_MAX_KEYS 16
977 u_int num_keys, i, j;
981 } keys[EXPAND_MAX_KEYS];
986 va_start(ap, string);
987 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
988 keys[num_keys].key = va_arg(ap, char *);
989 if (keys[num_keys].key == NULL)
991 keys[num_keys].repl = va_arg(ap, char *);
992 if (keys[num_keys].repl == NULL)
993 fatal("%s: NULL replacement", __func__);
995 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
996 fatal("%s: too many keys", __func__);
1001 for (i = 0; *string != '\0'; string++) {
1002 if (*string != '%') {
1005 if (i >= sizeof(buf))
1006 fatal("%s: string too long", __func__);
1014 if (*string == '\0')
1015 fatal("%s: invalid format", __func__);
1016 for (j = 0; j < num_keys; j++) {
1017 if (strchr(keys[j].key, *string) != NULL) {
1018 i = strlcat(buf, keys[j].repl, sizeof(buf));
1019 if (i >= sizeof(buf))
1020 fatal("%s: string too long", __func__);
1025 fatal("%s: unknown key %%%c", __func__, *string);
1027 return (xstrdup(buf));
1028 #undef EXPAND_MAX_KEYS
1032 tun_open(int tun, int mode, char **ifname)
1034 #if defined(CUSTOM_SYS_TUN_OPEN)
1035 return (sys_tun_open(tun, mode, ifname));
1036 #elif defined(SSH_TUN_OPENBSD)
1040 const char *tunbase = "tun";
1045 if (mode == SSH_TUNMODE_ETHERNET)
1048 /* Open the tunnel device */
1049 if (tun <= SSH_TUNID_MAX) {
1050 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1051 fd = open(name, O_RDWR);
1052 } else if (tun == SSH_TUNID_ANY) {
1053 for (tun = 100; tun >= 0; tun--) {
1054 snprintf(name, sizeof(name), "/dev/%s%d",
1056 if ((fd = open(name, O_RDWR)) >= 0)
1060 debug("%s: invalid tunnel %u", __func__, tun);
1065 debug("%s: %s open: %s", __func__, name, strerror(errno));
1069 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1071 /* Bring interface up if it is not already */
1072 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1073 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1076 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1077 debug("%s: get interface %s flags: %s", __func__,
1078 ifr.ifr_name, strerror(errno));
1082 if (!(ifr.ifr_flags & IFF_UP)) {
1083 ifr.ifr_flags |= IFF_UP;
1084 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1085 debug("%s: activate interface %s: %s", __func__,
1086 ifr.ifr_name, strerror(errno));
1092 *ifname = xstrdup(ifr.ifr_name);
1104 error("Tunnel interfaces are not supported on this platform");
1110 sanitise_stdfd(void)
1114 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1115 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1119 while (++dupfd <= STDERR_FILENO) {
1120 /* Only populate closed fds. */
1121 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1122 if (dup2(nullfd, dupfd) == -1) {
1123 fprintf(stderr, "dup2: %s\n", strerror(errno));
1128 if (nullfd > STDERR_FILENO)
1133 tohex(const void *vp, size_t l)
1135 const u_char *p = (const u_char *)vp;
1140 return xstrdup("tohex: length > 65536");
1144 for (i = 0; i < l; i++) {
1145 snprintf(b, sizeof(b), "%02x", p[i]);
1152 get_u64(const void *vp)
1154 const u_char *p = (const u_char *)vp;
1157 v = (u_int64_t)p[0] << 56;
1158 v |= (u_int64_t)p[1] << 48;
1159 v |= (u_int64_t)p[2] << 40;
1160 v |= (u_int64_t)p[3] << 32;
1161 v |= (u_int64_t)p[4] << 24;
1162 v |= (u_int64_t)p[5] << 16;
1163 v |= (u_int64_t)p[6] << 8;
1164 v |= (u_int64_t)p[7];
1170 get_u32(const void *vp)
1172 const u_char *p = (const u_char *)vp;
1175 v = (u_int32_t)p[0] << 24;
1176 v |= (u_int32_t)p[1] << 16;
1177 v |= (u_int32_t)p[2] << 8;
1178 v |= (u_int32_t)p[3];
1184 get_u32_le(const void *vp)
1186 const u_char *p = (const u_char *)vp;
1189 v = (u_int32_t)p[0];
1190 v |= (u_int32_t)p[1] << 8;
1191 v |= (u_int32_t)p[2] << 16;
1192 v |= (u_int32_t)p[3] << 24;
1198 get_u16(const void *vp)
1200 const u_char *p = (const u_char *)vp;
1203 v = (u_int16_t)p[0] << 8;
1204 v |= (u_int16_t)p[1];
1210 put_u64(void *vp, u_int64_t v)
1212 u_char *p = (u_char *)vp;
1214 p[0] = (u_char)(v >> 56) & 0xff;
1215 p[1] = (u_char)(v >> 48) & 0xff;
1216 p[2] = (u_char)(v >> 40) & 0xff;
1217 p[3] = (u_char)(v >> 32) & 0xff;
1218 p[4] = (u_char)(v >> 24) & 0xff;
1219 p[5] = (u_char)(v >> 16) & 0xff;
1220 p[6] = (u_char)(v >> 8) & 0xff;
1221 p[7] = (u_char)v & 0xff;
1225 put_u32(void *vp, u_int32_t v)
1227 u_char *p = (u_char *)vp;
1229 p[0] = (u_char)(v >> 24) & 0xff;
1230 p[1] = (u_char)(v >> 16) & 0xff;
1231 p[2] = (u_char)(v >> 8) & 0xff;
1232 p[3] = (u_char)v & 0xff;
1236 put_u32_le(void *vp, u_int32_t v)
1238 u_char *p = (u_char *)vp;
1240 p[0] = (u_char)v & 0xff;
1241 p[1] = (u_char)(v >> 8) & 0xff;
1242 p[2] = (u_char)(v >> 16) & 0xff;
1243 p[3] = (u_char)(v >> 24) & 0xff;
1247 put_u16(void *vp, u_int16_t v)
1249 u_char *p = (u_char *)vp;
1251 p[0] = (u_char)(v >> 8) & 0xff;
1252 p[1] = (u_char)v & 0xff;
1256 ms_subtract_diff(struct timeval *start, int *ms)
1258 struct timeval diff, finish;
1260 monotime_tv(&finish);
1261 timersub(&finish, start, &diff);
1262 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1266 ms_to_timeval(struct timeval *tv, int ms)
1270 tv->tv_sec = ms / 1000;
1271 tv->tv_usec = (ms % 1000) * 1000;
1275 monotime_ts(struct timespec *ts)
1278 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1279 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1280 static int gettime_failed = 0;
1282 if (!gettime_failed) {
1283 # ifdef CLOCK_BOOTTIME
1284 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1286 # endif /* CLOCK_BOOTTIME */
1287 # ifdef CLOCK_MONOTONIC
1288 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1290 # endif /* CLOCK_MONOTONIC */
1291 # ifdef CLOCK_REALTIME
1292 /* Not monotonic, but we're almost out of options here. */
1293 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1295 # endif /* CLOCK_REALTIME */
1296 debug3("clock_gettime: %s", strerror(errno));
1299 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1300 gettimeofday(&tv, NULL);
1301 ts->tv_sec = tv.tv_sec;
1302 ts->tv_nsec = (long)tv.tv_usec * 1000;
1306 monotime_tv(struct timeval *tv)
1311 tv->tv_sec = ts.tv_sec;
1312 tv->tv_usec = ts.tv_nsec / 1000;
1325 monotime_double(void)
1330 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1334 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1336 bw->buflen = buflen;
1338 bw->thresh = bw->rate;
1340 timerclear(&bw->bwstart);
1341 timerclear(&bw->bwend);
1344 /* Callback from read/write loop to insert bandwidth-limiting delays */
1346 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1349 struct timespec ts, rm;
1351 if (!timerisset(&bw->bwstart)) {
1352 monotime_tv(&bw->bwstart);
1356 bw->lamt += read_len;
1357 if (bw->lamt < bw->thresh)
1360 monotime_tv(&bw->bwend);
1361 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1362 if (!timerisset(&bw->bwend))
1366 waitlen = (double)1000000L * bw->lamt / bw->rate;
1368 bw->bwstart.tv_sec = waitlen / 1000000L;
1369 bw->bwstart.tv_usec = waitlen % 1000000L;
1371 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1372 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1374 /* Adjust the wait time */
1375 if (bw->bwend.tv_sec) {
1377 if (bw->thresh < bw->buflen / 4)
1378 bw->thresh = bw->buflen / 4;
1379 } else if (bw->bwend.tv_usec < 10000) {
1381 if (bw->thresh > bw->buflen * 8)
1382 bw->thresh = bw->buflen * 8;
1385 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1386 while (nanosleep(&ts, &rm) == -1) {
1394 monotime_tv(&bw->bwstart);
1397 /* Make a template filename for mk[sd]temp() */
1399 mktemp_proto(char *s, size_t len)
1404 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1405 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1406 if (r > 0 && (size_t)r < len)
1409 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1410 if (r < 0 || (size_t)r >= len)
1411 fatal("%s: template string too short", __func__);
1414 static const struct {
1418 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1419 { "af11", IPTOS_DSCP_AF11 },
1420 { "af12", IPTOS_DSCP_AF12 },
1421 { "af13", IPTOS_DSCP_AF13 },
1422 { "af21", IPTOS_DSCP_AF21 },
1423 { "af22", IPTOS_DSCP_AF22 },
1424 { "af23", IPTOS_DSCP_AF23 },
1425 { "af31", IPTOS_DSCP_AF31 },
1426 { "af32", IPTOS_DSCP_AF32 },
1427 { "af33", IPTOS_DSCP_AF33 },
1428 { "af41", IPTOS_DSCP_AF41 },
1429 { "af42", IPTOS_DSCP_AF42 },
1430 { "af43", IPTOS_DSCP_AF43 },
1431 { "cs0", IPTOS_DSCP_CS0 },
1432 { "cs1", IPTOS_DSCP_CS1 },
1433 { "cs2", IPTOS_DSCP_CS2 },
1434 { "cs3", IPTOS_DSCP_CS3 },
1435 { "cs4", IPTOS_DSCP_CS4 },
1436 { "cs5", IPTOS_DSCP_CS5 },
1437 { "cs6", IPTOS_DSCP_CS6 },
1438 { "cs7", IPTOS_DSCP_CS7 },
1439 { "ef", IPTOS_DSCP_EF },
1440 { "lowdelay", IPTOS_LOWDELAY },
1441 { "throughput", IPTOS_THROUGHPUT },
1442 { "reliability", IPTOS_RELIABILITY },
1447 parse_ipqos(const char *cp)
1455 for (i = 0; ipqos[i].name != NULL; i++) {
1456 if (strcasecmp(cp, ipqos[i].name) == 0)
1457 return ipqos[i].value;
1459 /* Try parsing as an integer */
1460 val = strtol(cp, &ep, 0);
1461 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1467 iptos2str(int iptos)
1470 static char iptos_str[sizeof "0xff"];
1472 for (i = 0; ipqos[i].name != NULL; i++) {
1473 if (ipqos[i].value == iptos)
1474 return ipqos[i].name;
1476 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1484 *s = tolower((u_char)*s);
1488 unix_listener(const char *path, int backlog, int unlink_first)
1490 struct sockaddr_un sunaddr;
1491 int saved_errno, sock;
1493 memset(&sunaddr, 0, sizeof(sunaddr));
1494 sunaddr.sun_family = AF_UNIX;
1495 if (strlcpy(sunaddr.sun_path, path,
1496 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1497 error("%s: path \"%s\" too long for Unix domain socket",
1499 errno = ENAMETOOLONG;
1503 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1505 saved_errno = errno;
1506 error("%s: socket: %.100s", __func__, strerror(errno));
1507 errno = saved_errno;
1510 if (unlink_first == 1) {
1511 if (unlink(path) != 0 && errno != ENOENT)
1512 error("unlink(%s): %.100s", path, strerror(errno));
1514 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1515 saved_errno = errno;
1516 error("%s: cannot bind to path %s: %s",
1517 __func__, path, strerror(errno));
1519 errno = saved_errno;
1522 if (listen(sock, backlog) < 0) {
1523 saved_errno = errno;
1524 error("%s: cannot listen on path %s: %s",
1525 __func__, path, strerror(errno));
1528 errno = saved_errno;
1535 sock_set_v6only(int s)
1537 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1540 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1541 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1542 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1547 * Compares two strings that maybe be NULL. Returns non-zero if strings
1548 * are both NULL or are identical, returns zero otherwise.
1551 strcmp_maybe_null(const char *a, const char *b)
1553 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1555 if (a != NULL && strcmp(a, b) != 0)
1561 * Compare two forwards, returning non-zero if they are identical or
1565 forward_equals(const struct Forward *a, const struct Forward *b)
1567 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1569 if (a->listen_port != b->listen_port)
1571 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1573 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1575 if (a->connect_port != b->connect_port)
1577 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1579 /* allocated_port and handle are not checked */
1583 /* returns 1 if process is already daemonized, 0 otherwise */
1589 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1591 return 0; /* have controlling terminal */
1594 return 0; /* parent is not init */
1595 if (getsid(0) != getpid())
1596 return 0; /* not session leader */
1597 debug3("already daemonized");
1603 * Splits 's' into an argument vector. Handles quoted string and basic
1604 * escape characters (\\, \", \'). Caller must free the argument vector
1608 argv_split(const char *s, int *argcp, char ***argvp)
1610 int r = SSH_ERR_INTERNAL_ERROR;
1611 int argc = 0, quote, i, j;
1612 char *arg, **argv = xcalloc(1, sizeof(*argv));
1617 for (i = 0; s[i] != '\0'; i++) {
1618 /* Skip leading whitespace */
1619 if (s[i] == ' ' || s[i] == '\t')
1622 /* Start of a token */
1625 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1627 else if (s[i] == '\'' || s[i] == '"')
1630 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1631 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1634 /* Copy the token in, removing escapes */
1635 for (j = 0; s[i] != '\0'; i++) {
1637 if (s[i + 1] == '\'' ||
1643 /* Unrecognised escape */
1646 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1648 else if (quote != 0 && s[i] == quote)
1655 /* Ran out of string looking for close quote */
1656 r = SSH_ERR_INVALID_FORMAT;
1669 if (argc != 0 && argv != NULL) {
1670 for (i = 0; i < argc; i++)
1678 * Reassemble an argument vector into a string, quoting and escaping as
1679 * necessary. Caller must free returned string.
1682 argv_assemble(int argc, char **argv)
1686 struct sshbuf *buf, *arg;
1688 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1689 fatal("%s: sshbuf_new failed", __func__);
1691 for (i = 0; i < argc; i++) {
1694 for (j = 0; argv[i][j] != '\0'; j++) {
1701 r = sshbuf_put_u8(arg, c);
1706 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1710 r = sshbuf_put_u8(arg, c);
1714 fatal("%s: sshbuf_put_u8: %s",
1715 __func__, ssh_err(r));
1717 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1718 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1719 (r = sshbuf_putb(buf, arg)) != 0 ||
1720 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1721 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1723 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1724 fatal("%s: malloc failed", __func__);
1725 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1726 ret[sshbuf_len(buf)] = '\0';
1732 /* Returns 0 if pid exited cleanly, non-zero otherwise */
1734 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1738 while (waitpid(pid, &status, 0) == -1) {
1739 if (errno != EINTR) {
1740 error("%s: waitpid: %s", tag, strerror(errno));
1744 if (WIFSIGNALED(status)) {
1745 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1747 } else if (WEXITSTATUS(status) != 0) {
1748 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1749 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1756 * Check a given path for security. This is defined as all components
1757 * of the path to the file must be owned by either the owner of
1758 * of the file or root and no directories must be group or world writable.
1760 * XXX Should any specific check be done for sym links ?
1762 * Takes a file name, its stat information (preferably from fstat() to
1763 * avoid races), the uid of the expected owner, their home directory and an
1764 * error buffer plus max size as arguments.
1766 * Returns 0 on success and -1 on failure
1769 safe_path(const char *name, struct stat *stp, const char *pw_dir,
1770 uid_t uid, char *err, size_t errlen)
1772 char buf[PATH_MAX], homedir[PATH_MAX];
1774 int comparehome = 0;
1777 if (realpath(name, buf) == NULL) {
1778 snprintf(err, errlen, "realpath %s failed: %s", name,
1782 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1785 if (!S_ISREG(stp->st_mode)) {
1786 snprintf(err, errlen, "%s is not a regular file", buf);
1789 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1790 (stp->st_mode & 022) != 0) {
1791 snprintf(err, errlen, "bad ownership or modes for file %s",
1796 /* for each component of the canonical path, walking upwards */
1798 if ((cp = dirname(buf)) == NULL) {
1799 snprintf(err, errlen, "dirname() failed");
1802 strlcpy(buf, cp, sizeof(buf));
1804 if (stat(buf, &st) < 0 ||
1805 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1806 (st.st_mode & 022) != 0) {
1807 snprintf(err, errlen,
1808 "bad ownership or modes for directory %s", buf);
1812 /* If are past the homedir then we can stop */
1813 if (comparehome && strcmp(homedir, buf) == 0)
1817 * dirname should always complete with a "/" path,
1818 * but we can be paranoid and check for "." too
1820 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1827 * Version of safe_path() that accepts an open file descriptor to
1830 * Returns 0 on success and -1 on failure
1833 safe_path_fd(int fd, const char *file, struct passwd *pw,
1834 char *err, size_t errlen)
1838 /* check the open file to avoid races */
1839 if (fstat(fd, &st) < 0) {
1840 snprintf(err, errlen, "cannot stat file %s: %s",
1841 file, strerror(errno));
1844 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1848 * Sets the value of the given variable in the environment. If the variable
1849 * already exists, its value is overridden.
1852 child_set_env(char ***envp, u_int *envsizep, const char *name,
1859 if (strchr(name, '=') != NULL) {
1860 error("Invalid environment variable \"%.100s\"", name);
1865 * If we're passed an uninitialized list, allocate a single null
1866 * entry before continuing.
1868 if (*envp == NULL && *envsizep == 0) {
1869 *envp = xmalloc(sizeof(char *));
1875 * Find the slot where the value should be stored. If the variable
1876 * already exists, we reuse the slot; otherwise we append a new slot
1877 * at the end of the array, expanding if necessary.
1880 namelen = strlen(name);
1881 for (i = 0; env[i]; i++)
1882 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1885 /* Reuse the slot. */
1888 /* New variable. Expand if necessary. */
1889 envsize = *envsizep;
1890 if (i >= envsize - 1) {
1891 if (envsize >= 1000)
1892 fatal("child_set_env: too many env vars");
1894 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1895 *envsizep = envsize;
1897 /* Need to set the NULL pointer at end of array beyond the new slot. */
1901 /* Allocate space and format the variable in the appropriate slot. */
1903 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1904 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1908 * Check and optionally lowercase a domain name, also removes trailing '.'
1909 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1912 valid_domain(char *name, int makelower, const char **errstr)
1914 size_t i, l = strlen(name);
1915 u_char c, last = '\0';
1916 static char errbuf[256];
1919 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1922 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1923 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1924 "starts with invalid character", name);
1927 for (i = 0; i < l; i++) {
1928 c = tolower((u_char)name[i]);
1931 if (last == '.' && c == '.') {
1932 snprintf(errbuf, sizeof(errbuf), "domain name "
1933 "\"%.100s\" contains consecutive separators", name);
1936 if (c != '.' && c != '-' && !isalnum(c) &&
1937 c != '_') /* technically invalid, but common */ {
1938 snprintf(errbuf, sizeof(errbuf), "domain name "
1939 "\"%.100s\" contains invalid characters", name);
1944 if (name[l - 1] == '.')
1956 * Verify that a environment variable name (not including initial '$') is
1957 * valid; consisting of one or more alphanumeric or underscore characters only.
1958 * Returns 1 on valid, 0 otherwise.
1961 valid_env_name(const char *name)
1965 if (name[0] == '\0')
1967 for (cp = name; *cp != '\0'; cp++) {
1968 if (!isalnum((u_char)*cp) && *cp != '_')
1975 atoi_err(const char *nptr, int *val)
1977 const char *errstr = NULL;
1980 if (nptr == NULL || *nptr == '\0')
1982 num = strtonum(nptr, 0, INT_MAX, &errstr);
1989 parse_absolute_time(const char *s, uint64_t *tp)
1998 * POSIX strptime says "The application shall ensure that there
1999 * is white-space or other non-alphanumeric characters between
2000 * any two conversion specifications" so arrange things this way.
2002 switch (strlen(s)) {
2003 case 8: /* YYYYMMDD */
2005 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2007 case 12: /* YYYYMMDDHHMM */
2008 fmt = "%Y-%m-%dT%H:%M";
2009 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2010 s, s + 4, s + 6, s + 8, s + 10);
2012 case 14: /* YYYYMMDDHHMMSS */
2013 fmt = "%Y-%m-%dT%H:%M:%S";
2014 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2015 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2018 return SSH_ERR_INVALID_FORMAT;
2021 memset(&tm, 0, sizeof(tm));
2022 if (strptime(buf, fmt, &tm) == NULL)
2023 return SSH_ERR_INVALID_FORMAT;
2024 if ((tt = mktime(&tm)) < 0)
2025 return SSH_ERR_INVALID_FORMAT;
2032 format_absolute_time(uint64_t t, char *buf, size_t len)
2034 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2037 localtime_r(&tt, &tm);
2038 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);