1 /* $OpenBSD: misc.c,v 1.127 2018/03/12 00:52:01 djm 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>
33 #include <sys/sysctl.h>
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
53 #include <netinet/tcp.h>
63 #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");
238 /* Characters considered whitespace in strsep calls. */
239 #define WHITESPACE " \t\r\n"
242 /* return next token in configuration line */
254 *s = strpbrk(*s, 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 */
275 /* Skip any extra whitespace after first token */
276 *s += strspn(*s + 1, WHITESPACE) + 1;
277 if (*s[0] == '=' && !wspace)
278 *s += strspn(*s + 1, WHITESPACE) + 1;
284 pwcopy(struct passwd *pw)
286 struct passwd *copy = xcalloc(1, sizeof(*copy));
288 copy->pw_name = xstrdup(pw->pw_name);
289 copy->pw_passwd = xstrdup(pw->pw_passwd);
290 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
291 copy->pw_gecos = xstrdup(pw->pw_gecos);
293 copy->pw_uid = pw->pw_uid;
294 copy->pw_gid = pw->pw_gid;
295 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
296 copy->pw_expire = pw->pw_expire;
298 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
299 copy->pw_change = pw->pw_change;
301 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
302 copy->pw_class = xstrdup(pw->pw_class);
304 copy->pw_dir = xstrdup(pw->pw_dir);
305 copy->pw_shell = xstrdup(pw->pw_shell);
310 * Convert ASCII string to TCP/IP port number.
311 * Port must be >=0 and <=65535.
312 * Return -1 if invalid.
315 a2port(const char *s)
320 port = strtonum(s, 0, 65535, &errstr);
327 a2tun(const char *s, int *remote)
329 const char *errstr = NULL;
333 if (remote != NULL) {
334 *remote = SSH_TUNID_ANY;
336 if ((ep = strchr(sp, ':')) == NULL) {
338 return (a2tun(s, NULL));
341 *remote = a2tun(ep, NULL);
342 tun = a2tun(sp, NULL);
344 return (*remote == SSH_TUNID_ERR ? *remote : tun);
347 if (strcasecmp(s, "any") == 0)
348 return (SSH_TUNID_ANY);
350 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
352 return (SSH_TUNID_ERR);
358 #define MINUTES (SECONDS * 60)
359 #define HOURS (MINUTES * 60)
360 #define DAYS (HOURS * 24)
361 #define WEEKS (DAYS * 7)
364 * Convert a time string into seconds; format is
368 * Valid time qualifiers are:
382 * Return -1 if time string is invalid.
385 convtime(const char *s)
387 long total, secs, multiplier = 1;
395 if (p == NULL || *p == '\0')
399 secs = strtol(p, &endp, 10);
401 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
414 multiplier = MINUTES;
431 if (secs >= LONG_MAX / multiplier)
434 if (total >= LONG_MAX - secs)
446 * Returns a standardized host+port identifier string.
447 * Caller must free returned string.
450 put_host_port(const char *host, u_short port)
454 if (port == 0 || port == SSH_DEFAULT_PORT)
455 return(xstrdup(host));
456 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
457 fatal("put_host_port: asprintf: %s", strerror(errno));
458 debug3("put_host_port: %s", hoststr);
463 * Search for next delimiter between hostnames/addresses and ports.
464 * Argument may be modified (for termination).
465 * Returns *cp if parsing succeeds.
466 * *cp is set to the start of the next field, if one was found.
467 * The delimiter char, if present, is stored in delim.
468 * If this is the last field, *cp is set to NULL.
471 hpdelim2(char **cp, char *delim)
475 if (cp == NULL || *cp == NULL)
480 if ((s = strchr(s, ']')) == NULL)
484 } else if ((s = strpbrk(s, ":/")) == NULL)
485 s = *cp + strlen(*cp); /* skip to end (see first case below) */
489 *cp = NULL; /* no more fields*/
496 *s = '\0'; /* terminate */
510 return hpdelim2(cp, NULL);
514 cleanhostname(char *host)
516 if (*host == '[' && host[strlen(host) - 1] == ']') {
517 host[strlen(host) - 1] = '\0';
528 if (*cp == ':') /* Leading colon is part of file name. */
534 if (*cp == '@' && *(cp+1) == '[')
536 if (*cp == ']' && *(cp+1) == ':' && flag)
538 if (*cp == ':' && !flag)
547 * Parse a [user@]host:[path] string.
548 * Caller must free returned user, host and path.
549 * Any of the pointer return arguments may be NULL (useful for syntax checking).
550 * If user was not specified then *userp will be set to NULL.
551 * If host was not specified then *hostp will be set to NULL.
552 * If path was not specified then *pathp will be set to ".".
553 * Returns 0 on success, -1 on failure.
556 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
558 char *user = NULL, *host = NULL, *path = NULL;
571 /* Check for remote syntax: [user@]host:[path] */
572 if ((tmp = colon(sdup)) == NULL)
575 /* Extract optional path */
581 /* Extract optional user and mandatory host */
582 tmp = strrchr(sdup, '@');
585 host = xstrdup(cleanhostname(tmp));
587 user = xstrdup(sdup);
589 host = xstrdup(cleanhostname(sdup));
616 * Parse a [user@]host[:port] string.
617 * Caller must free returned user and host.
618 * Any of the pointer return arguments may be NULL (useful for syntax checking).
619 * If user was not specified then *userp will be set to NULL.
620 * If port was not specified then *portp will be -1.
621 * Returns 0 on success, -1 on failure.
624 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
626 char *sdup, *cp, *tmp;
627 char *user = NULL, *host = NULL;
628 int port = -1, ret = -1;
637 if ((sdup = tmp = strdup(s)) == NULL)
639 /* Extract optional username */
640 if ((cp = strrchr(tmp, '@')) != NULL) {
644 if ((user = strdup(tmp)) == NULL)
648 /* Extract mandatory hostname */
649 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
651 host = xstrdup(cleanhostname(cp));
652 /* Convert and verify optional port */
653 if (tmp != NULL && *tmp != '\0') {
654 if ((port = a2port(tmp)) <= 0)
677 * Converts a two-byte hex string to decimal.
678 * Returns the decimal value or -1 for invalid input.
681 hexchar(const char *s)
683 unsigned char result[2];
686 for (i = 0; i < 2; i++) {
687 if (s[i] >= '0' && s[i] <= '9')
688 result[i] = (unsigned char)(s[i] - '0');
689 else if (s[i] >= 'a' && s[i] <= 'f')
690 result[i] = (unsigned char)(s[i] - 'a') + 10;
691 else if (s[i] >= 'A' && s[i] <= 'F')
692 result[i] = (unsigned char)(s[i] - 'A') + 10;
696 return (result[0] << 4) | result[1];
700 * Decode an url-encoded string.
701 * Returns a newly allocated string on success or NULL on failure.
704 urldecode(const char *src)
709 ret = xmalloc(strlen(src) + 1);
710 for (dst = ret; *src != '\0'; src++) {
716 if (!isxdigit((unsigned char)src[1]) ||
717 !isxdigit((unsigned char)src[2]) ||
718 (ch = hexchar(src + 1)) == -1) {
736 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
737 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
738 * Either user or path may be url-encoded (but not host or port).
739 * Caller must free returned user, host and path.
740 * Any of the pointer return arguments may be NULL (useful for syntax checking)
741 * but the scheme must always be specified.
742 * If user was not specified then *userp will be set to NULL.
743 * If port was not specified then *portp will be -1.
744 * If path was not specified then *pathp will be set to NULL.
745 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
748 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
749 int *portp, char **pathp)
751 char *uridup, *cp, *tmp, ch;
752 char *user = NULL, *host = NULL, *path = NULL;
753 int port = -1, ret = -1;
756 len = strlen(scheme);
757 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
770 uridup = tmp = xstrdup(uri);
772 /* Extract optional ssh-info (username + connection params) */
773 if ((cp = strchr(tmp, '@')) != NULL) {
777 /* Extract username and connection params */
778 if ((delim = strchr(tmp, ';')) != NULL) {
779 /* Just ignore connection params for now */
786 if ((user = urldecode(tmp)) == NULL)
791 /* Extract mandatory hostname */
792 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
794 host = xstrdup(cleanhostname(cp));
795 if (!valid_domain(host, 0, NULL))
798 if (tmp != NULL && *tmp != '\0') {
800 /* Convert and verify port. */
801 if ((cp = strchr(tmp, '/')) != NULL)
803 if ((port = a2port(tmp)) <= 0)
805 tmp = cp ? cp + 1 : NULL;
807 if (tmp != NULL && *tmp != '\0') {
808 /* Extract optional path */
809 if ((path = urldecode(tmp)) == NULL)
838 /* function to assist building execv() arguments */
840 addargs(arglist *args, char *fmt, ...)
848 r = vasprintf(&cp, fmt, ap);
851 fatal("addargs: argument too long");
853 nalloc = args->nalloc;
854 if (args->list == NULL) {
857 } else if (args->num+2 >= nalloc)
860 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
861 args->nalloc = nalloc;
862 args->list[args->num++] = cp;
863 args->list[args->num] = NULL;
867 replacearg(arglist *args, u_int which, char *fmt, ...)
874 r = vasprintf(&cp, fmt, ap);
877 fatal("replacearg: argument too long");
879 if (which >= args->num)
880 fatal("replacearg: tried to replace invalid arg %d >= %d",
882 free(args->list[which]);
883 args->list[which] = cp;
887 freeargs(arglist *args)
891 if (args->list != NULL) {
892 for (i = 0; i < args->num; i++)
895 args->nalloc = args->num = 0;
901 * Expands tildes in the file name. Returns data allocated by xmalloc.
902 * Warning: this calls getpw*.
905 tilde_expand_filename(const char *filename, uid_t uid)
907 const char *path, *sep;
908 char user[128], *ret;
912 if (*filename != '~')
913 return (xstrdup(filename));
916 path = strchr(filename, '/');
917 if (path != NULL && path > filename) { /* ~user/path */
918 slash = path - filename;
919 if (slash > sizeof(user) - 1)
920 fatal("tilde_expand_filename: ~username too long");
921 memcpy(user, filename, slash);
923 if ((pw = getpwnam(user)) == NULL)
924 fatal("tilde_expand_filename: No such user %s", user);
925 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
926 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
928 /* Make sure directory has a trailing '/' */
929 len = strlen(pw->pw_dir);
930 if (len == 0 || pw->pw_dir[len - 1] != '/')
935 /* Skip leading '/' from specified path */
939 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
940 fatal("tilde_expand_filename: Path too long");
946 * Expand a string with a set of %[char] escapes. A number of escapes may be
947 * specified as (char *escape_chars, char *replacement) pairs. The list must
948 * be terminated by a NULL escape_char. Returns replaced string in memory
949 * allocated by xmalloc.
952 percent_expand(const char *string, ...)
954 #define EXPAND_MAX_KEYS 16
955 u_int num_keys, i, j;
959 } keys[EXPAND_MAX_KEYS];
964 va_start(ap, string);
965 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
966 keys[num_keys].key = va_arg(ap, char *);
967 if (keys[num_keys].key == NULL)
969 keys[num_keys].repl = va_arg(ap, char *);
970 if (keys[num_keys].repl == NULL)
971 fatal("%s: NULL replacement", __func__);
973 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
974 fatal("%s: too many keys", __func__);
979 for (i = 0; *string != '\0'; string++) {
980 if (*string != '%') {
983 if (i >= sizeof(buf))
984 fatal("%s: string too long", __func__);
993 fatal("%s: invalid format", __func__);
994 for (j = 0; j < num_keys; j++) {
995 if (strchr(keys[j].key, *string) != NULL) {
996 i = strlcat(buf, keys[j].repl, sizeof(buf));
997 if (i >= sizeof(buf))
998 fatal("%s: string too long", __func__);
1003 fatal("%s: unknown key %%%c", __func__, *string);
1005 return (xstrdup(buf));
1006 #undef EXPAND_MAX_KEYS
1010 * Read an entire line from a public key file into a static buffer, discarding
1011 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
1014 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
1017 while (fgets(buf, bufsz, f) != NULL) {
1021 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
1024 debug("%s: %s line %lu exceeds size limit", __func__,
1026 /* discard remainder of line */
1027 while (fgetc(f) != '\n' && !feof(f))
1035 tun_open(int tun, int mode, char **ifname)
1037 #if defined(CUSTOM_SYS_TUN_OPEN)
1038 return (sys_tun_open(tun, mode, ifname));
1039 #elif defined(SSH_TUN_OPENBSD)
1043 const char *tunbase = "tun";
1048 if (mode == SSH_TUNMODE_ETHERNET)
1051 /* Open the tunnel device */
1052 if (tun <= SSH_TUNID_MAX) {
1053 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1054 fd = open(name, O_RDWR);
1055 } else if (tun == SSH_TUNID_ANY) {
1056 for (tun = 100; tun >= 0; tun--) {
1057 snprintf(name, sizeof(name), "/dev/%s%d",
1059 if ((fd = open(name, O_RDWR)) >= 0)
1063 debug("%s: invalid tunnel %u", __func__, tun);
1068 debug("%s: %s open: %s", __func__, name, strerror(errno));
1072 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1074 /* Bring interface up if it is not already */
1075 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1076 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1079 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1080 debug("%s: get interface %s flags: %s", __func__,
1081 ifr.ifr_name, strerror(errno));
1085 if (!(ifr.ifr_flags & IFF_UP)) {
1086 ifr.ifr_flags |= IFF_UP;
1087 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1088 debug("%s: activate interface %s: %s", __func__,
1089 ifr.ifr_name, strerror(errno));
1095 *ifname = xstrdup(ifr.ifr_name);
1107 error("Tunnel interfaces are not supported on this platform");
1113 sanitise_stdfd(void)
1117 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1118 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1122 while (++dupfd <= STDERR_FILENO) {
1123 /* Only populate closed fds. */
1124 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1125 if (dup2(nullfd, dupfd) == -1) {
1126 fprintf(stderr, "dup2: %s\n", strerror(errno));
1131 if (nullfd > STDERR_FILENO)
1136 tohex(const void *vp, size_t l)
1138 const u_char *p = (const u_char *)vp;
1143 return xstrdup("tohex: length > 65536");
1147 for (i = 0; i < l; i++) {
1148 snprintf(b, sizeof(b), "%02x", p[i]);
1155 get_u64(const void *vp)
1157 const u_char *p = (const u_char *)vp;
1160 v = (u_int64_t)p[0] << 56;
1161 v |= (u_int64_t)p[1] << 48;
1162 v |= (u_int64_t)p[2] << 40;
1163 v |= (u_int64_t)p[3] << 32;
1164 v |= (u_int64_t)p[4] << 24;
1165 v |= (u_int64_t)p[5] << 16;
1166 v |= (u_int64_t)p[6] << 8;
1167 v |= (u_int64_t)p[7];
1173 get_u32(const void *vp)
1175 const u_char *p = (const u_char *)vp;
1178 v = (u_int32_t)p[0] << 24;
1179 v |= (u_int32_t)p[1] << 16;
1180 v |= (u_int32_t)p[2] << 8;
1181 v |= (u_int32_t)p[3];
1187 get_u32_le(const void *vp)
1189 const u_char *p = (const u_char *)vp;
1192 v = (u_int32_t)p[0];
1193 v |= (u_int32_t)p[1] << 8;
1194 v |= (u_int32_t)p[2] << 16;
1195 v |= (u_int32_t)p[3] << 24;
1201 get_u16(const void *vp)
1203 const u_char *p = (const u_char *)vp;
1206 v = (u_int16_t)p[0] << 8;
1207 v |= (u_int16_t)p[1];
1213 put_u64(void *vp, u_int64_t v)
1215 u_char *p = (u_char *)vp;
1217 p[0] = (u_char)(v >> 56) & 0xff;
1218 p[1] = (u_char)(v >> 48) & 0xff;
1219 p[2] = (u_char)(v >> 40) & 0xff;
1220 p[3] = (u_char)(v >> 32) & 0xff;
1221 p[4] = (u_char)(v >> 24) & 0xff;
1222 p[5] = (u_char)(v >> 16) & 0xff;
1223 p[6] = (u_char)(v >> 8) & 0xff;
1224 p[7] = (u_char)v & 0xff;
1228 put_u32(void *vp, u_int32_t v)
1230 u_char *p = (u_char *)vp;
1232 p[0] = (u_char)(v >> 24) & 0xff;
1233 p[1] = (u_char)(v >> 16) & 0xff;
1234 p[2] = (u_char)(v >> 8) & 0xff;
1235 p[3] = (u_char)v & 0xff;
1239 put_u32_le(void *vp, u_int32_t v)
1241 u_char *p = (u_char *)vp;
1243 p[0] = (u_char)v & 0xff;
1244 p[1] = (u_char)(v >> 8) & 0xff;
1245 p[2] = (u_char)(v >> 16) & 0xff;
1246 p[3] = (u_char)(v >> 24) & 0xff;
1250 put_u16(void *vp, u_int16_t v)
1252 u_char *p = (u_char *)vp;
1254 p[0] = (u_char)(v >> 8) & 0xff;
1255 p[1] = (u_char)v & 0xff;
1259 ms_subtract_diff(struct timeval *start, int *ms)
1261 struct timeval diff, finish;
1263 monotime_tv(&finish);
1264 timersub(&finish, start, &diff);
1265 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1269 ms_to_timeval(struct timeval *tv, int ms)
1273 tv->tv_sec = ms / 1000;
1274 tv->tv_usec = (ms % 1000) * 1000;
1278 monotime_ts(struct timespec *ts)
1281 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1282 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1283 static int gettime_failed = 0;
1285 if (!gettime_failed) {
1286 # ifdef CLOCK_BOOTTIME
1287 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1289 # endif /* CLOCK_BOOTTIME */
1290 # ifdef CLOCK_MONOTONIC
1291 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1293 # endif /* CLOCK_MONOTONIC */
1294 # ifdef CLOCK_REALTIME
1295 /* Not monotonic, but we're almost out of options here. */
1296 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1298 # endif /* CLOCK_REALTIME */
1299 debug3("clock_gettime: %s", strerror(errno));
1302 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1303 gettimeofday(&tv, NULL);
1304 ts->tv_sec = tv.tv_sec;
1305 ts->tv_nsec = (long)tv.tv_usec * 1000;
1309 monotime_tv(struct timeval *tv)
1314 tv->tv_sec = ts.tv_sec;
1315 tv->tv_usec = ts.tv_nsec / 1000;
1328 monotime_double(void)
1333 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1337 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1339 bw->buflen = buflen;
1341 bw->thresh = bw->rate;
1343 timerclear(&bw->bwstart);
1344 timerclear(&bw->bwend);
1347 /* Callback from read/write loop to insert bandwidth-limiting delays */
1349 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1352 struct timespec ts, rm;
1354 if (!timerisset(&bw->bwstart)) {
1355 monotime_tv(&bw->bwstart);
1359 bw->lamt += read_len;
1360 if (bw->lamt < bw->thresh)
1363 monotime_tv(&bw->bwend);
1364 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1365 if (!timerisset(&bw->bwend))
1369 waitlen = (double)1000000L * bw->lamt / bw->rate;
1371 bw->bwstart.tv_sec = waitlen / 1000000L;
1372 bw->bwstart.tv_usec = waitlen % 1000000L;
1374 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1375 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1377 /* Adjust the wait time */
1378 if (bw->bwend.tv_sec) {
1380 if (bw->thresh < bw->buflen / 4)
1381 bw->thresh = bw->buflen / 4;
1382 } else if (bw->bwend.tv_usec < 10000) {
1384 if (bw->thresh > bw->buflen * 8)
1385 bw->thresh = bw->buflen * 8;
1388 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1389 while (nanosleep(&ts, &rm) == -1) {
1397 monotime_tv(&bw->bwstart);
1400 /* Make a template filename for mk[sd]temp() */
1402 mktemp_proto(char *s, size_t len)
1407 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1408 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1409 if (r > 0 && (size_t)r < len)
1412 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1413 if (r < 0 || (size_t)r >= len)
1414 fatal("%s: template string too short", __func__);
1417 static const struct {
1421 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1422 { "af11", IPTOS_DSCP_AF11 },
1423 { "af12", IPTOS_DSCP_AF12 },
1424 { "af13", IPTOS_DSCP_AF13 },
1425 { "af21", IPTOS_DSCP_AF21 },
1426 { "af22", IPTOS_DSCP_AF22 },
1427 { "af23", IPTOS_DSCP_AF23 },
1428 { "af31", IPTOS_DSCP_AF31 },
1429 { "af32", IPTOS_DSCP_AF32 },
1430 { "af33", IPTOS_DSCP_AF33 },
1431 { "af41", IPTOS_DSCP_AF41 },
1432 { "af42", IPTOS_DSCP_AF42 },
1433 { "af43", IPTOS_DSCP_AF43 },
1434 { "cs0", IPTOS_DSCP_CS0 },
1435 { "cs1", IPTOS_DSCP_CS1 },
1436 { "cs2", IPTOS_DSCP_CS2 },
1437 { "cs3", IPTOS_DSCP_CS3 },
1438 { "cs4", IPTOS_DSCP_CS4 },
1439 { "cs5", IPTOS_DSCP_CS5 },
1440 { "cs6", IPTOS_DSCP_CS6 },
1441 { "cs7", IPTOS_DSCP_CS7 },
1442 { "ef", IPTOS_DSCP_EF },
1443 { "lowdelay", IPTOS_LOWDELAY },
1444 { "throughput", IPTOS_THROUGHPUT },
1445 { "reliability", IPTOS_RELIABILITY },
1450 parse_ipqos(const char *cp)
1458 for (i = 0; ipqos[i].name != NULL; i++) {
1459 if (strcasecmp(cp, ipqos[i].name) == 0)
1460 return ipqos[i].value;
1462 /* Try parsing as an integer */
1463 val = strtol(cp, &ep, 0);
1464 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1470 iptos2str(int iptos)
1473 static char iptos_str[sizeof "0xff"];
1475 for (i = 0; ipqos[i].name != NULL; i++) {
1476 if (ipqos[i].value == iptos)
1477 return ipqos[i].name;
1479 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1487 *s = tolower((u_char)*s);
1491 unix_listener(const char *path, int backlog, int unlink_first)
1493 struct sockaddr_un sunaddr;
1494 int saved_errno, sock;
1496 memset(&sunaddr, 0, sizeof(sunaddr));
1497 sunaddr.sun_family = AF_UNIX;
1498 if (strlcpy(sunaddr.sun_path, path,
1499 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1500 error("%s: path \"%s\" too long for Unix domain socket",
1502 errno = ENAMETOOLONG;
1506 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1508 saved_errno = errno;
1509 error("%s: socket: %.100s", __func__, strerror(errno));
1510 errno = saved_errno;
1513 if (unlink_first == 1) {
1514 if (unlink(path) != 0 && errno != ENOENT)
1515 error("unlink(%s): %.100s", path, strerror(errno));
1517 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1518 saved_errno = errno;
1519 error("%s: cannot bind to path %s: %s",
1520 __func__, path, strerror(errno));
1522 errno = saved_errno;
1525 if (listen(sock, backlog) < 0) {
1526 saved_errno = errno;
1527 error("%s: cannot listen on path %s: %s",
1528 __func__, path, strerror(errno));
1531 errno = saved_errno;
1538 sock_set_v6only(int s)
1540 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1543 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1544 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1545 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1550 * Compares two strings that maybe be NULL. Returns non-zero if strings
1551 * are both NULL or are identical, returns zero otherwise.
1554 strcmp_maybe_null(const char *a, const char *b)
1556 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1558 if (a != NULL && strcmp(a, b) != 0)
1564 * Compare two forwards, returning non-zero if they are identical or
1568 forward_equals(const struct Forward *a, const struct Forward *b)
1570 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1572 if (a->listen_port != b->listen_port)
1574 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1576 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1578 if (a->connect_port != b->connect_port)
1580 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1582 /* allocated_port and handle are not checked */
1587 ipport_reserved(void)
1591 size_t len = sizeof(old);
1593 ret = sysctlbyname("net.inet.ip.portrange.reservedhigh",
1594 &old, &len, NULL, 0);
1598 return (IPPORT_RESERVED);
1601 /* returns 1 if bind to specified port by specified user is permitted */
1603 bind_permitted(int port, uid_t uid)
1606 if (port < ipport_reserved() && uid != 0)
1611 /* returns 1 if process is already daemonized, 0 otherwise */
1617 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1619 return 0; /* have controlling terminal */
1622 return 0; /* parent is not init */
1623 if (getsid(0) != getpid())
1624 return 0; /* not session leader */
1625 debug3("already daemonized");
1631 * Splits 's' into an argument vector. Handles quoted string and basic
1632 * escape characters (\\, \", \'). Caller must free the argument vector
1636 argv_split(const char *s, int *argcp, char ***argvp)
1638 int r = SSH_ERR_INTERNAL_ERROR;
1639 int argc = 0, quote, i, j;
1640 char *arg, **argv = xcalloc(1, sizeof(*argv));
1645 for (i = 0; s[i] != '\0'; i++) {
1646 /* Skip leading whitespace */
1647 if (s[i] == ' ' || s[i] == '\t')
1650 /* Start of a token */
1653 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1655 else if (s[i] == '\'' || s[i] == '"')
1658 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1659 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1662 /* Copy the token in, removing escapes */
1663 for (j = 0; s[i] != '\0'; i++) {
1665 if (s[i + 1] == '\'' ||
1671 /* Unrecognised escape */
1674 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1676 else if (quote != 0 && s[i] == quote)
1683 /* Ran out of string looking for close quote */
1684 r = SSH_ERR_INVALID_FORMAT;
1697 if (argc != 0 && argv != NULL) {
1698 for (i = 0; i < argc; i++)
1706 * Reassemble an argument vector into a string, quoting and escaping as
1707 * necessary. Caller must free returned string.
1710 argv_assemble(int argc, char **argv)
1714 struct sshbuf *buf, *arg;
1716 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1717 fatal("%s: sshbuf_new failed", __func__);
1719 for (i = 0; i < argc; i++) {
1722 for (j = 0; argv[i][j] != '\0'; j++) {
1729 r = sshbuf_put_u8(arg, c);
1734 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1738 r = sshbuf_put_u8(arg, c);
1742 fatal("%s: sshbuf_put_u8: %s",
1743 __func__, ssh_err(r));
1745 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1746 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1747 (r = sshbuf_putb(buf, arg)) != 0 ||
1748 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1749 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1751 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1752 fatal("%s: malloc failed", __func__);
1753 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1754 ret[sshbuf_len(buf)] = '\0';
1760 /* Returns 0 if pid exited cleanly, non-zero otherwise */
1762 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1766 while (waitpid(pid, &status, 0) == -1) {
1767 if (errno != EINTR) {
1768 error("%s: waitpid: %s", tag, strerror(errno));
1772 if (WIFSIGNALED(status)) {
1773 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1775 } else if (WEXITSTATUS(status) != 0) {
1776 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1777 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1784 * Check a given path for security. This is defined as all components
1785 * of the path to the file must be owned by either the owner of
1786 * of the file or root and no directories must be group or world writable.
1788 * XXX Should any specific check be done for sym links ?
1790 * Takes a file name, its stat information (preferably from fstat() to
1791 * avoid races), the uid of the expected owner, their home directory and an
1792 * error buffer plus max size as arguments.
1794 * Returns 0 on success and -1 on failure
1797 safe_path(const char *name, struct stat *stp, const char *pw_dir,
1798 uid_t uid, char *err, size_t errlen)
1800 char buf[PATH_MAX], homedir[PATH_MAX];
1802 int comparehome = 0;
1805 if (realpath(name, buf) == NULL) {
1806 snprintf(err, errlen, "realpath %s failed: %s", name,
1810 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1813 if (!S_ISREG(stp->st_mode)) {
1814 snprintf(err, errlen, "%s is not a regular file", buf);
1817 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1818 (stp->st_mode & 022) != 0) {
1819 snprintf(err, errlen, "bad ownership or modes for file %s",
1824 /* for each component of the canonical path, walking upwards */
1826 if ((cp = dirname(buf)) == NULL) {
1827 snprintf(err, errlen, "dirname() failed");
1830 strlcpy(buf, cp, sizeof(buf));
1832 if (stat(buf, &st) < 0 ||
1833 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1834 (st.st_mode & 022) != 0) {
1835 snprintf(err, errlen,
1836 "bad ownership or modes for directory %s", buf);
1840 /* If are past the homedir then we can stop */
1841 if (comparehome && strcmp(homedir, buf) == 0)
1845 * dirname should always complete with a "/" path,
1846 * but we can be paranoid and check for "." too
1848 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1855 * Version of safe_path() that accepts an open file descriptor to
1858 * Returns 0 on success and -1 on failure
1861 safe_path_fd(int fd, const char *file, struct passwd *pw,
1862 char *err, size_t errlen)
1866 /* check the open file to avoid races */
1867 if (fstat(fd, &st) < 0) {
1868 snprintf(err, errlen, "cannot stat file %s: %s",
1869 file, strerror(errno));
1872 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1876 * Sets the value of the given variable in the environment. If the variable
1877 * already exists, its value is overridden.
1880 child_set_env(char ***envp, u_int *envsizep, const char *name,
1887 if (strchr(name, '=') != NULL) {
1888 error("Invalid environment variable \"%.100s\"", name);
1893 * If we're passed an uninitialized list, allocate a single null
1894 * entry before continuing.
1896 if (*envp == NULL && *envsizep == 0) {
1897 *envp = xmalloc(sizeof(char *));
1903 * Find the slot where the value should be stored. If the variable
1904 * already exists, we reuse the slot; otherwise we append a new slot
1905 * at the end of the array, expanding if necessary.
1908 namelen = strlen(name);
1909 for (i = 0; env[i]; i++)
1910 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1913 /* Reuse the slot. */
1916 /* New variable. Expand if necessary. */
1917 envsize = *envsizep;
1918 if (i >= envsize - 1) {
1919 if (envsize >= 1000)
1920 fatal("child_set_env: too many env vars");
1922 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1923 *envsizep = envsize;
1925 /* Need to set the NULL pointer at end of array beyond the new slot. */
1929 /* Allocate space and format the variable in the appropriate slot. */
1931 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1932 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1936 * Check and optionally lowercase a domain name, also removes trailing '.'
1937 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1940 valid_domain(char *name, int makelower, const char **errstr)
1942 size_t i, l = strlen(name);
1943 u_char c, last = '\0';
1944 static char errbuf[256];
1947 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
1950 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
1951 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
1952 "starts with invalid character", name);
1955 for (i = 0; i < l; i++) {
1956 c = tolower((u_char)name[i]);
1959 if (last == '.' && c == '.') {
1960 snprintf(errbuf, sizeof(errbuf), "domain name "
1961 "\"%.100s\" contains consecutive separators", name);
1964 if (c != '.' && c != '-' && !isalnum(c) &&
1965 c != '_') /* technically invalid, but common */ {
1966 snprintf(errbuf, sizeof(errbuf), "domain name "
1967 "\"%.100s\" contains invalid characters", name);
1972 if (name[l - 1] == '.')
1984 atoi_err(const char *nptr, int *val)
1986 const char *errstr = NULL;
1989 if (nptr == NULL || *nptr == '\0')
1991 num = strtonum(nptr, 0, INT_MAX, &errstr);
1998 parse_absolute_time(const char *s, uint64_t *tp)
2007 * POSIX strptime says "The application shall ensure that there
2008 * is white-space or other non-alphanumeric characters between
2009 * any two conversion specifications" so arrange things this way.
2011 switch (strlen(s)) {
2012 case 8: /* YYYYMMDD */
2014 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2016 case 12: /* YYYYMMDDHHMM */
2017 fmt = "%Y-%m-%dT%H:%M";
2018 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2019 s, s + 4, s + 6, s + 8, s + 10);
2021 case 14: /* YYYYMMDDHHMMSS */
2022 fmt = "%Y-%m-%dT%H:%M:%S";
2023 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2024 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2027 return SSH_ERR_INVALID_FORMAT;
2030 memset(&tm, 0, sizeof(tm));
2031 if (strptime(buf, fmt, &tm) == NULL)
2032 return SSH_ERR_INVALID_FORMAT;
2033 if ((tt = mktime(&tm)) < 0)
2034 return SSH_ERR_INVALID_FORMAT;
2041 format_absolute_time(uint64_t t, char *buf, size_t len)
2043 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2046 localtime_r(&tt, &tm);
2047 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);