1 /* $OpenBSD: misc.c,v 1.185 2023/08/04 06:32:40 dtucker Exp $ */
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2005-2020 Damien Miller. All rights reserved.
5 * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
26 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
68 #ifdef SSH_TUN_OPENBSD
80 /* remove newline at end of string */
86 if (*t == '\n' || *t == '\r') {
96 /* remove whitespace from end of string */
102 if ((i = strlen(s)) == 0)
104 for (i--; i > 0; i--) {
105 if (isspace((unsigned char)s[i]))
110 /* set/unset filedescriptor to non-blocking */
116 val = fcntl(fd, F_GETFL);
118 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
121 if (val & O_NONBLOCK) {
122 debug3("fd %d is O_NONBLOCK", fd);
125 debug2("fd %d setting O_NONBLOCK", fd);
127 if (fcntl(fd, F_SETFL, val) == -1) {
128 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
136 unset_nonblock(int fd)
140 val = fcntl(fd, F_GETFL);
142 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
145 if (!(val & O_NONBLOCK)) {
146 debug3("fd %d is not O_NONBLOCK", fd);
149 debug("fd %d clearing O_NONBLOCK", fd);
151 if (fcntl(fd, F_SETFL, val) == -1) {
152 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
153 fd, strerror(errno));
160 ssh_gai_strerror(int gaierr)
162 if (gaierr == EAI_SYSTEM && errno != 0)
163 return strerror(errno);
164 return gai_strerror(gaierr);
167 /* disable nagle on socket */
175 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
176 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
180 debug2("fd %d is TCP_NODELAY", fd);
184 debug2("fd %d setting TCP_NODELAY", fd);
185 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
186 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
189 /* Allow local port reuse in TIME_WAIT */
191 set_reuseaddr(int fd)
195 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
196 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
202 /* Get/set routing domain */
206 #if defined(HAVE_SYS_GET_RDOMAIN)
207 return sys_get_rdomain(fd);
208 #elif defined(__OpenBSD__)
211 socklen_t len = sizeof(rtable);
213 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
214 error("Failed to get routing domain for fd %d: %s",
215 fd, strerror(errno));
218 xasprintf(&ret, "%d", rtable);
220 #else /* defined(__OpenBSD__) */
226 set_rdomain(int fd, const char *name)
228 #if defined(HAVE_SYS_SET_RDOMAIN)
229 return sys_set_rdomain(fd, name);
230 #elif defined(__OpenBSD__)
235 return 0; /* default table */
237 rtable = (int)strtonum(name, 0, 255, &errstr);
238 if (errstr != NULL) {
239 /* Shouldn't happen */
240 error("Invalid routing domain \"%s\": %s", name, errstr);
243 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
244 &rtable, sizeof(rtable)) == -1) {
245 error("Failed to set routing domain %d on fd %d: %s",
246 rtable, fd, strerror(errno));
250 #else /* defined(__OpenBSD__) */
251 error("Setting routing domain is not supported on this platform");
259 struct sockaddr_storage to;
260 socklen_t tolen = sizeof(to);
262 memset(&to, 0, sizeof(to));
263 if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
266 if (to.ss_family == AF_INET6 &&
267 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
274 set_sock_tos(int fd, int tos)
276 #ifndef IP_TOS_IS_BROKEN
279 switch ((af = get_sock_af(fd))) {
281 /* assume not a socket */
285 debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
286 if (setsockopt(fd, IPPROTO_IP, IP_TOS,
287 &tos, sizeof(tos)) == -1) {
288 error("setsockopt socket %d IP_TOS %d: %s",
289 fd, tos, strerror(errno));
295 debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
296 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
297 &tos, sizeof(tos)) == -1) {
298 error("setsockopt socket %d IPV6_TCLASS %d: %s",
299 fd, tos, strerror(errno));
301 # endif /* IPV6_TCLASS */
304 debug2_f("unsupported socket family %d", af);
307 #endif /* IP_TOS_IS_BROKEN */
311 * Wait up to *timeoutp milliseconds for events on fd. Updates
312 * *timeoutp with time remaining.
313 * Returns 0 if fd ready or -1 on timeout or error (see errno).
316 waitfd(int fd, int *timeoutp, short events)
319 struct timeval t_start;
320 int oerrno, r, have_timeout = (*timeoutp >= 0);
324 for (; !have_timeout || *timeoutp >= 0;) {
325 monotime_tv(&t_start);
326 r = poll(&pfd, 1, *timeoutp);
329 ms_subtract_diff(&t_start, timeoutp);
333 else if (r == -1 && errno != EAGAIN && errno != EINTR)
344 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
345 * *timeoutp with time remaining.
346 * Returns 0 if fd ready or -1 on timeout or error (see errno).
349 waitrfd(int fd, int *timeoutp) {
350 return waitfd(fd, timeoutp, POLLIN);
354 * Attempt a non-blocking connect(2) to the specified address, waiting up to
355 * *timeoutp milliseconds for the connection to complete. If the timeout is
356 * <=0, then wait indefinitely.
358 * Returns 0 on success or -1 on failure.
361 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
362 socklen_t addrlen, int *timeoutp)
365 socklen_t optlen = sizeof(optval);
367 /* No timeout: just do a blocking connect() */
368 if (timeoutp == NULL || *timeoutp <= 0)
369 return connect(sockfd, serv_addr, addrlen);
371 set_nonblock(sockfd);
373 if (connect(sockfd, serv_addr, addrlen) == 0) {
374 /* Succeeded already? */
375 unset_nonblock(sockfd);
377 } else if (errno == EINTR)
379 else if (errno != EINPROGRESS)
384 if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT) == -1)
387 /* Completed or failed */
388 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
389 debug("getsockopt: %s", strerror(errno));
396 unset_nonblock(sockfd);
400 /* Characters considered whitespace in strsep calls. */
401 #define WHITESPACE " \t\r\n"
404 /* return next token in configuration line */
406 strdelim_internal(char **s, int split_equals)
417 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
422 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
423 /* Find matching quote */
424 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
425 return (NULL); /* no matching quote */
428 *s += strspn(*s + 1, WHITESPACE) + 1;
433 /* Allow only one '=' to be skipped */
434 if (split_equals && *s[0] == '=')
438 /* Skip any extra whitespace after first token */
439 *s += strspn(*s + 1, WHITESPACE) + 1;
440 if (split_equals && *s[0] == '=' && !wspace)
441 *s += strspn(*s + 1, WHITESPACE) + 1;
447 * Return next token in configuration line; splts on whitespace or a
448 * single '=' character.
453 return strdelim_internal(s, 1);
457 * Return next token in configuration line; splts on whitespace only.
462 return strdelim_internal(s, 0);
466 pwcopy(struct passwd *pw)
468 struct passwd *copy = xcalloc(1, sizeof(*copy));
470 copy->pw_name = xstrdup(pw->pw_name);
471 copy->pw_passwd = xstrdup(pw->pw_passwd == NULL ? "*" : pw->pw_passwd);
472 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
473 copy->pw_gecos = xstrdup(pw->pw_gecos);
475 copy->pw_uid = pw->pw_uid;
476 copy->pw_gid = pw->pw_gid;
477 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
478 copy->pw_expire = pw->pw_expire;
480 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
481 copy->pw_change = pw->pw_change;
483 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
484 copy->pw_class = xstrdup(pw->pw_class);
486 copy->pw_dir = xstrdup(pw->pw_dir);
487 copy->pw_shell = xstrdup(pw->pw_shell);
492 * Convert ASCII string to TCP/IP port number.
493 * Port must be >=0 and <=65535.
494 * Return -1 if invalid.
497 a2port(const char *s)
503 port = strtonum(s, 0, 65535, &errstr);
506 if ((se = getservbyname(s, "tcp")) != NULL)
507 return ntohs(se->s_port);
512 a2tun(const char *s, int *remote)
514 const char *errstr = NULL;
518 if (remote != NULL) {
519 *remote = SSH_TUNID_ANY;
521 if ((ep = strchr(sp, ':')) == NULL) {
523 return (a2tun(s, NULL));
526 *remote = a2tun(ep, NULL);
527 tun = a2tun(sp, NULL);
529 return (*remote == SSH_TUNID_ERR ? *remote : tun);
532 if (strcasecmp(s, "any") == 0)
533 return (SSH_TUNID_ANY);
535 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
537 return (SSH_TUNID_ERR);
543 #define MINUTES (SECONDS * 60)
544 #define HOURS (MINUTES * 60)
545 #define DAYS (HOURS * 24)
546 #define WEEKS (DAYS * 7)
549 * Convert a time string into seconds; format is
553 * Valid time qualifiers are:
567 * Return -1 if time string is invalid.
570 convtime(const char *s)
572 long total, secs, multiplier;
580 if (p == NULL || *p == '\0')
584 secs = strtol(p, &endp, 10);
586 (errno == ERANGE && (secs == INT_MIN || secs == INT_MAX)) ||
600 multiplier = MINUTES;
617 if (secs > INT_MAX / multiplier)
620 if (total > INT_MAX - secs)
635 fmt_timeframe(time_t t)
638 static char tfbuf[TF_BUFS][TF_LEN]; /* ring buffer */
640 unsigned int sec, min, hrs, day;
641 unsigned long long week;
659 snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
661 snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
663 snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
669 * Returns a standardized host+port identifier string.
670 * Caller must free returned string.
673 put_host_port(const char *host, u_short port)
677 if (port == 0 || port == SSH_DEFAULT_PORT)
678 return(xstrdup(host));
679 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
680 fatal("put_host_port: asprintf: %s", strerror(errno));
681 debug3("put_host_port: %s", hoststr);
686 * Search for next delimiter between hostnames/addresses and ports.
687 * Argument may be modified (for termination).
688 * Returns *cp if parsing succeeds.
689 * *cp is set to the start of the next field, if one was found.
690 * The delimiter char, if present, is stored in delim.
691 * If this is the last field, *cp is set to NULL.
694 hpdelim2(char **cp, char *delim)
698 if (cp == NULL || *cp == NULL)
703 if ((s = strchr(s, ']')) == NULL)
707 } else if ((s = strpbrk(s, ":/")) == NULL)
708 s = *cp + strlen(*cp); /* skip to end (see first case below) */
712 *cp = NULL; /* no more fields*/
719 *s = '\0'; /* terminate */
730 /* The common case: only accept colon as delimiter. */
734 char *r, delim = '\0';
736 r = hpdelim2(cp, &delim);
743 cleanhostname(char *host)
745 if (*host == '[' && host[strlen(host) - 1] == ']') {
746 host[strlen(host) - 1] = '\0';
757 if (*cp == ':') /* Leading colon is part of file name. */
763 if (*cp == '@' && *(cp+1) == '[')
765 if (*cp == ']' && *(cp+1) == ':' && flag)
767 if (*cp == ':' && !flag)
776 * Parse a [user@]host:[path] string.
777 * Caller must free returned user, host and path.
778 * Any of the pointer return arguments may be NULL (useful for syntax checking).
779 * If user was not specified then *userp will be set to NULL.
780 * If host was not specified then *hostp will be set to NULL.
781 * If path was not specified then *pathp will be set to ".".
782 * Returns 0 on success, -1 on failure.
785 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
787 char *user = NULL, *host = NULL, *path = NULL;
800 /* Check for remote syntax: [user@]host:[path] */
801 if ((tmp = colon(sdup)) == NULL)
804 /* Extract optional path */
810 /* Extract optional user and mandatory host */
811 tmp = strrchr(sdup, '@');
814 host = xstrdup(cleanhostname(tmp));
816 user = xstrdup(sdup);
818 host = xstrdup(cleanhostname(sdup));
845 * Parse a [user@]host[:port] string.
846 * Caller must free returned user and host.
847 * Any of the pointer return arguments may be NULL (useful for syntax checking).
848 * If user was not specified then *userp will be set to NULL.
849 * If port was not specified then *portp will be -1.
850 * Returns 0 on success, -1 on failure.
853 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
855 char *sdup, *cp, *tmp;
856 char *user = NULL, *host = NULL;
857 int port = -1, ret = -1;
866 if ((sdup = tmp = strdup(s)) == NULL)
868 /* Extract optional username */
869 if ((cp = strrchr(tmp, '@')) != NULL) {
873 if ((user = strdup(tmp)) == NULL)
877 /* Extract mandatory hostname */
878 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
880 host = xstrdup(cleanhostname(cp));
881 /* Convert and verify optional port */
882 if (tmp != NULL && *tmp != '\0') {
883 if ((port = a2port(tmp)) <= 0)
906 * Converts a two-byte hex string to decimal.
907 * Returns the decimal value or -1 for invalid input.
910 hexchar(const char *s)
912 unsigned char result[2];
915 for (i = 0; i < 2; i++) {
916 if (s[i] >= '0' && s[i] <= '9')
917 result[i] = (unsigned char)(s[i] - '0');
918 else if (s[i] >= 'a' && s[i] <= 'f')
919 result[i] = (unsigned char)(s[i] - 'a') + 10;
920 else if (s[i] >= 'A' && s[i] <= 'F')
921 result[i] = (unsigned char)(s[i] - 'A') + 10;
925 return (result[0] << 4) | result[1];
929 * Decode an url-encoded string.
930 * Returns a newly allocated string on success or NULL on failure.
933 urldecode(const char *src)
939 if ((srclen = strlen(src)) >= SIZE_MAX)
940 fatal_f("input too large");
941 ret = xmalloc(srclen + 1);
942 for (dst = ret; *src != '\0'; src++) {
948 if (!isxdigit((unsigned char)src[1]) ||
949 !isxdigit((unsigned char)src[2]) ||
950 (ch = hexchar(src + 1)) == -1) {
968 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
969 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
970 * Either user or path may be url-encoded (but not host or port).
971 * Caller must free returned user, host and path.
972 * Any of the pointer return arguments may be NULL (useful for syntax checking)
973 * but the scheme must always be specified.
974 * If user was not specified then *userp will be set to NULL.
975 * If port was not specified then *portp will be -1.
976 * If path was not specified then *pathp will be set to NULL.
977 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
980 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
981 int *portp, char **pathp)
983 char *uridup, *cp, *tmp, ch;
984 char *user = NULL, *host = NULL, *path = NULL;
985 int port = -1, ret = -1;
988 len = strlen(scheme);
989 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
1002 uridup = tmp = xstrdup(uri);
1004 /* Extract optional ssh-info (username + connection params) */
1005 if ((cp = strchr(tmp, '@')) != NULL) {
1009 /* Extract username and connection params */
1010 if ((delim = strchr(tmp, ';')) != NULL) {
1011 /* Just ignore connection params for now */
1015 /* Empty username */
1018 if ((user = urldecode(tmp)) == NULL)
1023 /* Extract mandatory hostname */
1024 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
1026 host = xstrdup(cleanhostname(cp));
1027 if (!valid_domain(host, 0, NULL))
1030 if (tmp != NULL && *tmp != '\0') {
1032 /* Convert and verify port. */
1033 if ((cp = strchr(tmp, '/')) != NULL)
1035 if ((port = a2port(tmp)) <= 0)
1037 tmp = cp ? cp + 1 : NULL;
1039 if (tmp != NULL && *tmp != '\0') {
1040 /* Extract optional path */
1041 if ((path = urldecode(tmp)) == NULL)
1047 if (userp != NULL) {
1051 if (hostp != NULL) {
1057 if (pathp != NULL) {
1070 /* function to assist building execv() arguments */
1072 addargs(arglist *args, char *fmt, ...)
1080 r = vasprintf(&cp, fmt, ap);
1083 fatal_f("argument too long");
1085 nalloc = args->nalloc;
1086 if (args->list == NULL) {
1089 } else if (args->num > (256 * 1024))
1090 fatal_f("too many arguments");
1091 else if (args->num >= args->nalloc)
1092 fatal_f("arglist corrupt");
1093 else if (args->num+2 >= nalloc)
1096 args->list = xrecallocarray(args->list, args->nalloc,
1097 nalloc, sizeof(char *));
1098 args->nalloc = nalloc;
1099 args->list[args->num++] = cp;
1100 args->list[args->num] = NULL;
1104 replacearg(arglist *args, u_int which, char *fmt, ...)
1111 r = vasprintf(&cp, fmt, ap);
1114 fatal_f("argument too long");
1115 if (args->list == NULL || args->num >= args->nalloc)
1116 fatal_f("arglist corrupt");
1118 if (which >= args->num)
1119 fatal_f("tried to replace invalid arg %d >= %d",
1121 free(args->list[which]);
1122 args->list[which] = cp;
1126 freeargs(arglist *args)
1132 if (args->list != NULL && args->num < args->nalloc) {
1133 for (i = 0; i < args->num; i++)
1134 free(args->list[i]);
1137 args->nalloc = args->num = 0;
1142 * Expands tildes in the file name. Returns data allocated by xmalloc.
1143 * Warning: this calls getpw*.
1146 tilde_expand(const char *filename, uid_t uid, char **retp)
1148 char *ocopy = NULL, *copy, *s = NULL;
1149 const char *path = NULL, *user = NULL;
1152 int ret = -1, r, slash;
1155 if (*filename != '~') {
1156 *retp = xstrdup(filename);
1159 ocopy = copy = xstrdup(filename + 1);
1161 if (*copy == '\0') /* ~ */
1163 else if (*copy == '/') {
1164 copy += strspn(copy, "/");
1166 path = NULL; /* ~/ */
1168 path = copy; /* ~/path */
1171 if ((path = strchr(copy, '/')) != NULL) {
1172 copy[path - copy] = '\0';
1174 path += strspn(path, "/");
1175 if (*path == '\0') /* ~user/ */
1177 /* else ~user/path */
1182 if ((pw = getpwnam(user)) == NULL) {
1183 error_f("No such user %s", user);
1186 } else if ((pw = getpwuid(uid)) == NULL) {
1187 error_f("No such uid %ld", (long)uid);
1191 /* Make sure directory has a trailing '/' */
1192 slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1194 if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1195 slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1196 error_f("xasprintf failed");
1199 if (r >= PATH_MAX) {
1200 error_f("Path too long");
1214 tilde_expand_filename(const char *filename, uid_t uid)
1218 if (tilde_expand(filename, uid, &ret) != 0)
1224 * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1225 * substitutions. A number of escapes may be specified as
1226 * (char *escape_chars, char *replacement) pairs. The list must be terminated
1227 * by a NULL escape_char. Returns replaced string in memory allocated by
1228 * xmalloc which the caller must free.
1231 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1232 const char *string, va_list ap)
1234 #define EXPAND_MAX_KEYS 16
1235 u_int num_keys = 0, i;
1239 } keys[EXPAND_MAX_KEYS];
1241 int r, missingvar = 0;
1242 char *ret = NULL, *var, *varend, *val;
1245 if ((buf = sshbuf_new()) == NULL)
1246 fatal_f("sshbuf_new failed");
1247 if (parseerror == NULL)
1248 fatal_f("null parseerror arg");
1251 /* Gather keys if we're doing percent expansion. */
1253 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1254 keys[num_keys].key = va_arg(ap, char *);
1255 if (keys[num_keys].key == NULL)
1257 keys[num_keys].repl = va_arg(ap, char *);
1258 if (keys[num_keys].repl == NULL) {
1259 fatal_f("NULL replacement for token %s",
1260 keys[num_keys].key);
1263 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1264 fatal_f("too many keys");
1266 fatal_f("percent expansion without token list");
1270 for (i = 0; *string != '\0'; string++) {
1271 /* Optionally process ${ENVIRONMENT} expansions. */
1272 if (dollar && string[0] == '$' && string[1] == '{') {
1273 string += 2; /* skip over '${' */
1274 if ((varend = strchr(string, '}')) == NULL) {
1275 error_f("environment variable '%s' missing "
1276 "closing '}'", string);
1279 len = varend - string;
1281 error_f("zero-length environment variable");
1284 var = xmalloc(len + 1);
1285 (void)strlcpy(var, string, len + 1);
1286 if ((val = getenv(var)) == NULL) {
1287 error_f("env var ${%s} has no value", var);
1290 debug3_f("expand ${%s} -> '%s'", var, val);
1291 if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1292 fatal_fr(r, "sshbuf_put ${}");
1300 * Process percent expansions if we have a list of TOKENs.
1301 * If we're not doing percent expansion everything just gets
1304 if (*string != '%' || !percent) {
1306 if ((r = sshbuf_put_u8(buf, *string)) != 0)
1307 fatal_fr(r, "sshbuf_put_u8 %%");
1314 if (*string == '\0') {
1315 error_f("invalid format");
1318 for (i = 0; i < num_keys; i++) {
1319 if (strchr(keys[i].key, *string) != NULL) {
1320 if ((r = sshbuf_put(buf, keys[i].repl,
1321 strlen(keys[i].repl))) != 0)
1322 fatal_fr(r, "sshbuf_put %%-repl");
1326 if (i >= num_keys) {
1327 error_f("unknown key %%%c", *string);
1331 if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1332 fatal_f("sshbuf_dup_string failed");
1336 return *parseerror ? NULL : ret;
1337 #undef EXPAND_MAX_KEYS
1341 * Expand only environment variables.
1342 * Note that although this function is variadic like the other similar
1343 * functions, any such arguments will be unused.
1347 dollar_expand(int *parseerr, const char *string, ...)
1353 va_start(ap, string);
1354 ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1356 if (parseerr != NULL)
1362 * Returns expanded string or NULL if a specified environment variable is
1363 * not defined, or calls fatal if the string is invalid.
1366 percent_expand(const char *string, ...)
1372 va_start(ap, string);
1373 ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1381 * Returns expanded string or NULL if a specified environment variable is
1382 * not defined, or calls fatal if the string is invalid.
1385 percent_dollar_expand(const char *string, ...)
1391 va_start(ap, string);
1392 ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1400 tun_open(int tun, int mode, char **ifname)
1402 #if defined(CUSTOM_SYS_TUN_OPEN)
1403 return (sys_tun_open(tun, mode, ifname));
1404 #elif defined(SSH_TUN_OPENBSD)
1408 const char *tunbase = "tun";
1413 if (mode == SSH_TUNMODE_ETHERNET)
1416 /* Open the tunnel device */
1417 if (tun <= SSH_TUNID_MAX) {
1418 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1419 fd = open(name, O_RDWR);
1420 } else if (tun == SSH_TUNID_ANY) {
1421 for (tun = 100; tun >= 0; tun--) {
1422 snprintf(name, sizeof(name), "/dev/%s%d",
1424 if ((fd = open(name, O_RDWR)) >= 0)
1428 debug_f("invalid tunnel %u", tun);
1433 debug_f("%s open: %s", name, strerror(errno));
1437 debug_f("%s mode %d fd %d", name, mode, fd);
1439 /* Bring interface up if it is not already */
1440 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1441 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1444 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1445 debug_f("get interface %s flags: %s", ifr.ifr_name,
1450 if (!(ifr.ifr_flags & IFF_UP)) {
1451 ifr.ifr_flags |= IFF_UP;
1452 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1453 debug_f("activate interface %s: %s", ifr.ifr_name,
1460 *ifname = xstrdup(ifr.ifr_name);
1472 error("Tunnel interfaces are not supported on this platform");
1478 sanitise_stdfd(void)
1482 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1483 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1487 while (++dupfd <= STDERR_FILENO) {
1488 /* Only populate closed fds. */
1489 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1490 if (dup2(nullfd, dupfd) == -1) {
1491 fprintf(stderr, "dup2: %s\n", strerror(errno));
1496 if (nullfd > STDERR_FILENO)
1501 tohex(const void *vp, size_t l)
1503 const u_char *p = (const u_char *)vp;
1508 return xstrdup("tohex: length > 65536");
1512 for (i = 0; i < l; i++) {
1513 snprintf(b, sizeof(b), "%02x", p[i]);
1520 * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1521 * then the separator 'sep' will be prepended before the formatted arguments.
1522 * Extended strings are heap allocated.
1525 xextendf(char **sp, const char *sep, const char *fmt, ...)
1531 xvasprintf(&tmp1, fmt, ap);
1534 if (*sp == NULL || **sp == '\0') {
1539 xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1547 get_u64(const void *vp)
1549 const u_char *p = (const u_char *)vp;
1552 v = (u_int64_t)p[0] << 56;
1553 v |= (u_int64_t)p[1] << 48;
1554 v |= (u_int64_t)p[2] << 40;
1555 v |= (u_int64_t)p[3] << 32;
1556 v |= (u_int64_t)p[4] << 24;
1557 v |= (u_int64_t)p[5] << 16;
1558 v |= (u_int64_t)p[6] << 8;
1559 v |= (u_int64_t)p[7];
1565 get_u32(const void *vp)
1567 const u_char *p = (const u_char *)vp;
1570 v = (u_int32_t)p[0] << 24;
1571 v |= (u_int32_t)p[1] << 16;
1572 v |= (u_int32_t)p[2] << 8;
1573 v |= (u_int32_t)p[3];
1579 get_u32_le(const void *vp)
1581 const u_char *p = (const u_char *)vp;
1584 v = (u_int32_t)p[0];
1585 v |= (u_int32_t)p[1] << 8;
1586 v |= (u_int32_t)p[2] << 16;
1587 v |= (u_int32_t)p[3] << 24;
1593 get_u16(const void *vp)
1595 const u_char *p = (const u_char *)vp;
1598 v = (u_int16_t)p[0] << 8;
1599 v |= (u_int16_t)p[1];
1605 put_u64(void *vp, u_int64_t v)
1607 u_char *p = (u_char *)vp;
1609 p[0] = (u_char)(v >> 56) & 0xff;
1610 p[1] = (u_char)(v >> 48) & 0xff;
1611 p[2] = (u_char)(v >> 40) & 0xff;
1612 p[3] = (u_char)(v >> 32) & 0xff;
1613 p[4] = (u_char)(v >> 24) & 0xff;
1614 p[5] = (u_char)(v >> 16) & 0xff;
1615 p[6] = (u_char)(v >> 8) & 0xff;
1616 p[7] = (u_char)v & 0xff;
1620 put_u32(void *vp, u_int32_t v)
1622 u_char *p = (u_char *)vp;
1624 p[0] = (u_char)(v >> 24) & 0xff;
1625 p[1] = (u_char)(v >> 16) & 0xff;
1626 p[2] = (u_char)(v >> 8) & 0xff;
1627 p[3] = (u_char)v & 0xff;
1631 put_u32_le(void *vp, u_int32_t v)
1633 u_char *p = (u_char *)vp;
1635 p[0] = (u_char)v & 0xff;
1636 p[1] = (u_char)(v >> 8) & 0xff;
1637 p[2] = (u_char)(v >> 16) & 0xff;
1638 p[3] = (u_char)(v >> 24) & 0xff;
1642 put_u16(void *vp, u_int16_t v)
1644 u_char *p = (u_char *)vp;
1646 p[0] = (u_char)(v >> 8) & 0xff;
1647 p[1] = (u_char)v & 0xff;
1651 ms_subtract_diff(struct timeval *start, int *ms)
1653 struct timeval diff, finish;
1655 monotime_tv(&finish);
1656 timersub(&finish, start, &diff);
1657 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1661 ms_to_timespec(struct timespec *ts, int ms)
1665 ts->tv_sec = ms / 1000;
1666 ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1670 monotime_ts(struct timespec *ts)
1673 #if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1674 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
1675 static int gettime_failed = 0;
1677 if (!gettime_failed) {
1678 # ifdef CLOCK_BOOTTIME
1679 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1681 # endif /* CLOCK_BOOTTIME */
1682 # ifdef CLOCK_MONOTONIC
1683 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1685 # endif /* CLOCK_MONOTONIC */
1686 # ifdef CLOCK_REALTIME
1687 /* Not monotonic, but we're almost out of options here. */
1688 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1690 # endif /* CLOCK_REALTIME */
1691 debug3("clock_gettime: %s", strerror(errno));
1694 #endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1695 gettimeofday(&tv, NULL);
1696 ts->tv_sec = tv.tv_sec;
1697 ts->tv_nsec = (long)tv.tv_usec * 1000;
1701 monotime_tv(struct timeval *tv)
1706 tv->tv_sec = ts.tv_sec;
1707 tv->tv_usec = ts.tv_nsec / 1000;
1720 monotime_double(void)
1725 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
1729 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1731 bw->buflen = buflen;
1733 bw->thresh = buflen;
1735 timerclear(&bw->bwstart);
1736 timerclear(&bw->bwend);
1739 /* Callback from read/write loop to insert bandwidth-limiting delays */
1741 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1744 struct timespec ts, rm;
1746 bw->lamt += read_len;
1747 if (!timerisset(&bw->bwstart)) {
1748 monotime_tv(&bw->bwstart);
1751 if (bw->lamt < bw->thresh)
1754 monotime_tv(&bw->bwend);
1755 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1756 if (!timerisset(&bw->bwend))
1760 waitlen = (double)1000000L * bw->lamt / bw->rate;
1762 bw->bwstart.tv_sec = waitlen / 1000000L;
1763 bw->bwstart.tv_usec = waitlen % 1000000L;
1765 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1766 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1768 /* Adjust the wait time */
1769 if (bw->bwend.tv_sec) {
1771 if (bw->thresh < bw->buflen / 4)
1772 bw->thresh = bw->buflen / 4;
1773 } else if (bw->bwend.tv_usec < 10000) {
1775 if (bw->thresh > bw->buflen * 8)
1776 bw->thresh = bw->buflen * 8;
1779 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1780 while (nanosleep(&ts, &rm) == -1) {
1788 monotime_tv(&bw->bwstart);
1791 /* Make a template filename for mk[sd]temp() */
1793 mktemp_proto(char *s, size_t len)
1798 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1799 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1800 if (r > 0 && (size_t)r < len)
1803 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1804 if (r < 0 || (size_t)r >= len)
1805 fatal_f("template string too short");
1808 static const struct {
1812 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1813 { "af11", IPTOS_DSCP_AF11 },
1814 { "af12", IPTOS_DSCP_AF12 },
1815 { "af13", IPTOS_DSCP_AF13 },
1816 { "af21", IPTOS_DSCP_AF21 },
1817 { "af22", IPTOS_DSCP_AF22 },
1818 { "af23", IPTOS_DSCP_AF23 },
1819 { "af31", IPTOS_DSCP_AF31 },
1820 { "af32", IPTOS_DSCP_AF32 },
1821 { "af33", IPTOS_DSCP_AF33 },
1822 { "af41", IPTOS_DSCP_AF41 },
1823 { "af42", IPTOS_DSCP_AF42 },
1824 { "af43", IPTOS_DSCP_AF43 },
1825 { "cs0", IPTOS_DSCP_CS0 },
1826 { "cs1", IPTOS_DSCP_CS1 },
1827 { "cs2", IPTOS_DSCP_CS2 },
1828 { "cs3", IPTOS_DSCP_CS3 },
1829 { "cs4", IPTOS_DSCP_CS4 },
1830 { "cs5", IPTOS_DSCP_CS5 },
1831 { "cs6", IPTOS_DSCP_CS6 },
1832 { "cs7", IPTOS_DSCP_CS7 },
1833 { "ef", IPTOS_DSCP_EF },
1834 { "le", IPTOS_DSCP_LE },
1835 { "lowdelay", IPTOS_LOWDELAY },
1836 { "throughput", IPTOS_THROUGHPUT },
1837 { "reliability", IPTOS_RELIABILITY },
1842 parse_ipqos(const char *cp)
1850 for (i = 0; ipqos[i].name != NULL; i++) {
1851 if (strcasecmp(cp, ipqos[i].name) == 0)
1852 return ipqos[i].value;
1854 /* Try parsing as an integer */
1855 val = strtol(cp, &ep, 0);
1856 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1862 iptos2str(int iptos)
1865 static char iptos_str[sizeof "0xff"];
1867 for (i = 0; ipqos[i].name != NULL; i++) {
1868 if (ipqos[i].value == iptos)
1869 return ipqos[i].name;
1871 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1879 *s = tolower((u_char)*s);
1883 unix_listener(const char *path, int backlog, int unlink_first)
1885 struct sockaddr_un sunaddr;
1886 int saved_errno, sock;
1888 memset(&sunaddr, 0, sizeof(sunaddr));
1889 sunaddr.sun_family = AF_UNIX;
1890 if (strlcpy(sunaddr.sun_path, path,
1891 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1892 error_f("path \"%s\" too long for Unix domain socket", path);
1893 errno = ENAMETOOLONG;
1897 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1899 saved_errno = errno;
1900 error_f("socket: %.100s", strerror(errno));
1901 errno = saved_errno;
1904 if (unlink_first == 1) {
1905 if (unlink(path) != 0 && errno != ENOENT)
1906 error("unlink(%s): %.100s", path, strerror(errno));
1908 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1909 saved_errno = errno;
1910 error_f("cannot bind to path %s: %s", path, strerror(errno));
1912 errno = saved_errno;
1915 if (listen(sock, backlog) == -1) {
1916 saved_errno = errno;
1917 error_f("cannot listen on path %s: %s", path, strerror(errno));
1920 errno = saved_errno;
1927 sock_set_v6only(int s)
1929 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1932 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1933 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1934 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1939 * Compares two strings that maybe be NULL. Returns non-zero if strings
1940 * are both NULL or are identical, returns zero otherwise.
1943 strcmp_maybe_null(const char *a, const char *b)
1945 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1947 if (a != NULL && strcmp(a, b) != 0)
1953 * Compare two forwards, returning non-zero if they are identical or
1957 forward_equals(const struct Forward *a, const struct Forward *b)
1959 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1961 if (a->listen_port != b->listen_port)
1963 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1965 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1967 if (a->connect_port != b->connect_port)
1969 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1971 /* allocated_port and handle are not checked */
1975 /* returns 1 if process is already daemonized, 0 otherwise */
1981 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1983 return 0; /* have controlling terminal */
1986 return 0; /* parent is not init */
1987 if (getsid(0) != getpid())
1988 return 0; /* not session leader */
1989 debug3("already daemonized");
1994 * Splits 's' into an argument vector. Handles quoted string and basic
1995 * escape characters (\\, \", \'). Caller must free the argument vector
1999 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
2001 int r = SSH_ERR_INTERNAL_ERROR;
2002 int argc = 0, quote, i, j;
2003 char *arg, **argv = xcalloc(1, sizeof(*argv));
2008 for (i = 0; s[i] != '\0'; i++) {
2009 /* Skip leading whitespace */
2010 if (s[i] == ' ' || s[i] == '\t')
2012 if (terminate_on_comment && s[i] == '#')
2014 /* Start of a token */
2017 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
2018 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
2021 /* Copy the token in, removing escapes */
2022 for (j = 0; s[i] != '\0'; i++) {
2024 if (s[i + 1] == '\'' ||
2027 (quote == 0 && s[i + 1] == ' ')) {
2031 /* Unrecognised escape */
2034 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
2036 else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
2037 quote = s[i]; /* quote start */
2038 else if (quote != 0 && s[i] == quote)
2039 quote = 0; /* quote end */
2045 /* Ran out of string looking for close quote */
2046 r = SSH_ERR_INVALID_FORMAT;
2059 if (argc != 0 && argv != NULL) {
2060 for (i = 0; i < argc; i++)
2068 * Reassemble an argument vector into a string, quoting and escaping as
2069 * necessary. Caller must free returned string.
2072 argv_assemble(int argc, char **argv)
2076 struct sshbuf *buf, *arg;
2078 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2079 fatal_f("sshbuf_new failed");
2081 for (i = 0; i < argc; i++) {
2084 for (j = 0; argv[i][j] != '\0'; j++) {
2091 r = sshbuf_put_u8(arg, c);
2096 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2100 r = sshbuf_put_u8(arg, c);
2104 fatal_fr(r, "sshbuf_put_u8");
2106 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2107 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2108 (r = sshbuf_putb(buf, arg)) != 0 ||
2109 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2110 fatal_fr(r, "assemble");
2112 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2113 fatal_f("malloc failed");
2114 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2115 ret[sshbuf_len(buf)] = '\0';
2122 argv_next(int *argcp, char ***argvp)
2124 char *ret = (*argvp)[0];
2126 if (*argcp > 0 && ret != NULL) {
2134 argv_consume(int *argcp)
2140 argv_free(char **av, int ac)
2146 for (i = 0; i < ac; i++)
2151 /* Returns 0 if pid exited cleanly, non-zero otherwise */
2153 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2157 while (waitpid(pid, &status, 0) == -1) {
2158 if (errno != EINTR) {
2159 error("%s waitpid: %s", tag, strerror(errno));
2163 if (WIFSIGNALED(status)) {
2164 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2166 } else if (WEXITSTATUS(status) != 0) {
2167 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2168 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2175 * Check a given path for security. This is defined as all components
2176 * of the path to the file must be owned by either the owner of
2177 * of the file or root and no directories must be group or world writable.
2179 * XXX Should any specific check be done for sym links ?
2181 * Takes a file name, its stat information (preferably from fstat() to
2182 * avoid races), the uid of the expected owner, their home directory and an
2183 * error buffer plus max size as arguments.
2185 * Returns 0 on success and -1 on failure
2188 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2189 uid_t uid, char *err, size_t errlen)
2191 char buf[PATH_MAX], homedir[PATH_MAX];
2193 int comparehome = 0;
2196 if (realpath(name, buf) == NULL) {
2197 snprintf(err, errlen, "realpath %s failed: %s", name,
2201 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2204 if (!S_ISREG(stp->st_mode)) {
2205 snprintf(err, errlen, "%s is not a regular file", buf);
2208 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
2209 (stp->st_mode & 022) != 0) {
2210 snprintf(err, errlen, "bad ownership or modes for file %s",
2215 /* for each component of the canonical path, walking upwards */
2217 if ((cp = dirname(buf)) == NULL) {
2218 snprintf(err, errlen, "dirname() failed");
2221 strlcpy(buf, cp, sizeof(buf));
2223 if (stat(buf, &st) == -1 ||
2224 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
2225 (st.st_mode & 022) != 0) {
2226 snprintf(err, errlen,
2227 "bad ownership or modes for directory %s", buf);
2231 /* If are past the homedir then we can stop */
2232 if (comparehome && strcmp(homedir, buf) == 0)
2236 * dirname should always complete with a "/" path,
2237 * but we can be paranoid and check for "." too
2239 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2246 * Version of safe_path() that accepts an open file descriptor to
2249 * Returns 0 on success and -1 on failure
2252 safe_path_fd(int fd, const char *file, struct passwd *pw,
2253 char *err, size_t errlen)
2257 /* check the open file to avoid races */
2258 if (fstat(fd, &st) == -1) {
2259 snprintf(err, errlen, "cannot stat file %s: %s",
2260 file, strerror(errno));
2263 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2267 * Sets the value of the given variable in the environment. If the variable
2268 * already exists, its value is overridden.
2271 child_set_env(char ***envp, u_int *envsizep, const char *name,
2278 if (strchr(name, '=') != NULL) {
2279 error("Invalid environment variable \"%.100s\"", name);
2284 * If we're passed an uninitialized list, allocate a single null
2285 * entry before continuing.
2287 if ((*envp == NULL) != (*envsizep == 0))
2288 fatal_f("environment size mismatch");
2289 if (*envp == NULL && *envsizep == 0) {
2290 *envp = xmalloc(sizeof(char *));
2296 * Find the slot where the value should be stored. If the variable
2297 * already exists, we reuse the slot; otherwise we append a new slot
2298 * at the end of the array, expanding if necessary.
2301 namelen = strlen(name);
2302 for (i = 0; env[i]; i++)
2303 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2306 /* Reuse the slot. */
2309 /* New variable. Expand if necessary. */
2310 envsize = *envsizep;
2311 if (i >= envsize - 1) {
2312 if (envsize >= 1000)
2313 fatal("child_set_env: too many env vars");
2315 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2316 *envsizep = envsize;
2318 /* Need to set the NULL pointer at end of array beyond the new slot. */
2322 /* Allocate space and format the variable in the appropriate slot. */
2324 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2325 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2329 * Check and optionally lowercase a domain name, also removes trailing '.'
2330 * Returns 1 on success and 0 on failure, storing an error message in errstr.
2333 valid_domain(char *name, int makelower, const char **errstr)
2335 size_t i, l = strlen(name);
2336 u_char c, last = '\0';
2337 static char errbuf[256];
2340 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2343 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2344 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2345 "starts with invalid character", name);
2348 for (i = 0; i < l; i++) {
2349 c = tolower((u_char)name[i]);
2352 if (last == '.' && c == '.') {
2353 snprintf(errbuf, sizeof(errbuf), "domain name "
2354 "\"%.100s\" contains consecutive separators", name);
2357 if (c != '.' && c != '-' && !isalnum(c) &&
2358 c != '_') /* technically invalid, but common */ {
2359 snprintf(errbuf, sizeof(errbuf), "domain name "
2360 "\"%.100s\" contains invalid characters", name);
2365 if (name[l - 1] == '.')
2377 * Verify that a environment variable name (not including initial '$') is
2378 * valid; consisting of one or more alphanumeric or underscore characters only.
2379 * Returns 1 on valid, 0 otherwise.
2382 valid_env_name(const char *name)
2386 if (name[0] == '\0')
2388 for (cp = name; *cp != '\0'; cp++) {
2389 if (!isalnum((u_char)*cp) && *cp != '_')
2396 atoi_err(const char *nptr, int *val)
2398 const char *errstr = NULL;
2401 if (nptr == NULL || *nptr == '\0')
2403 num = strtonum(nptr, 0, INT_MAX, &errstr);
2410 parse_absolute_time(const char *s, uint64_t *tp)
2422 if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2425 } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2430 * POSIX strptime says "The application shall ensure that there
2431 * is white-space or other non-alphanumeric characters between
2432 * any two conversion specifications" so arrange things this way.
2435 case 8: /* YYYYMMDD */
2437 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2439 case 12: /* YYYYMMDDHHMM */
2440 fmt = "%Y-%m-%dT%H:%M";
2441 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2442 s, s + 4, s + 6, s + 8, s + 10);
2444 case 14: /* YYYYMMDDHHMMSS */
2445 fmt = "%Y-%m-%dT%H:%M:%S";
2446 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2447 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2450 return SSH_ERR_INVALID_FORMAT;
2453 memset(&tm, 0, sizeof(tm));
2454 if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2455 return SSH_ERR_INVALID_FORMAT;
2457 if ((tt = timegm(&tm)) < 0)
2458 return SSH_ERR_INVALID_FORMAT;
2460 if ((tt = mktime(&tm)) < 0)
2461 return SSH_ERR_INVALID_FORMAT;
2469 format_absolute_time(uint64_t t, char *buf, size_t len)
2471 time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2474 localtime_r(&tt, &tm);
2475 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2478 /* check if path is absolute */
2480 path_absolute(const char *path)
2482 return (*path == '/') ? 1 : 0;
2486 skip_space(char **cpp)
2490 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2495 /* authorized_key-style options parsing helpers */
2498 * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2499 * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2500 * if negated option matches.
2501 * If the option or negated option matches, then *optsp is updated to
2502 * point to the first character after the option.
2505 opt_flag(const char *opt, int allow_negate, const char **optsp)
2507 size_t opt_len = strlen(opt);
2508 const char *opts = *optsp;
2511 if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2515 if (strncasecmp(opts, opt, opt_len) == 0) {
2516 *optsp = opts + opt_len;
2517 return negate ? 0 : 1;
2523 opt_dequote(const char **sp, const char **errstrp)
2525 const char *s = *sp;
2531 *errstrp = "missing start quote";
2535 if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2536 *errstrp = "memory allocation failed";
2539 for (i = 0; *s != '\0' && *s != '"';) {
2540 if (s[0] == '\\' && s[1] == '"')
2545 *errstrp = "missing end quote";
2556 opt_match(const char **opts, const char *term)
2558 if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2559 (*opts)[strlen(term)] == '=') {
2560 *opts += strlen(term) + 1;
2567 opt_array_append2(const char *file, const int line, const char *directive,
2568 char ***array, int **iarray, u_int *lp, const char *s, int i)
2572 fatal("%s line %d: Too many %s entries", file, line, directive);
2574 if (iarray != NULL) {
2575 *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2580 *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2581 (*array)[*lp] = xstrdup(s);
2586 opt_array_append(const char *file, const int line, const char *directive,
2587 char ***array, u_int *lp, const char *s)
2589 opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2593 ssh_signal(int signum, sshsig_t handler)
2595 struct sigaction sa, osa;
2597 /* mask all other signals while in handler */
2598 memset(&sa, 0, sizeof(sa));
2599 sa.sa_handler = handler;
2600 sigfillset(&sa.sa_mask);
2601 #if defined(SA_RESTART) && !defined(NO_SA_RESTART)
2602 if (signum != SIGALRM)
2603 sa.sa_flags = SA_RESTART;
2605 if (sigaction(signum, &sa, &osa) == -1) {
2606 debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2609 return osa.sa_handler;
2613 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2615 int devnull, ret = 0;
2617 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2618 error_f("open %s: %s", _PATH_DEVNULL,
2622 if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2623 (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2624 (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2625 error_f("dup2: %s", strerror(errno));
2628 if (devnull > STDERR_FILENO)
2634 * Runs command in a subprocess with a minimal environment.
2635 * Returns pid on success, 0 on failure.
2636 * The child stdout and stderr maybe captured, left attached or sent to
2637 * /dev/null depending on the contents of flags.
2638 * "tag" is prepended to log messages.
2639 * NB. "command" is only used for logging; the actual command executed is
2643 subprocess(const char *tag, const char *command,
2644 int ac, char **av, FILE **child, u_int flags,
2645 struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2649 int fd, devnull, p[2], i;
2651 char *cp, errmsg[512];
2655 /* If dropping privs, then must specify user and restore function */
2656 if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2657 error("%s: inconsistent arguments", tag); /* XXX fatal? */
2660 if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2661 error("%s: no user for current uid", tag);
2667 debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2668 tag, command, pw->pw_name, flags);
2670 /* Check consistency */
2671 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2672 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2673 error_f("inconsistent flags");
2676 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2677 error_f("inconsistent flags/output");
2682 * If executing an explicit binary, then verify the it exists
2683 * and appears safe-ish to execute
2685 if (!path_absolute(av[0])) {
2686 error("%s path is not absolute", tag);
2689 if (drop_privs != NULL)
2691 if (stat(av[0], &st) == -1) {
2692 error("Could not stat %s \"%s\": %s", tag,
2693 av[0], strerror(errno));
2694 goto restore_return;
2696 if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2697 safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2698 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2699 goto restore_return;
2701 /* Prepare to keep the child's stdout if requested */
2702 if (pipe(p) == -1) {
2703 error("%s: pipe: %s", tag, strerror(errno));
2705 if (restore_privs != NULL)
2709 if (restore_privs != NULL)
2712 switch ((pid = fork())) {
2713 case -1: /* error */
2714 error("%s: fork: %s", tag, strerror(errno));
2719 /* Prepare a minimal environment for the child. */
2720 if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2722 env = xcalloc(sizeof(*env), nenv);
2723 child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2724 child_set_env(&env, &nenv, "USER", pw->pw_name);
2725 child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2726 child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2727 if ((cp = getenv("LANG")) != NULL)
2728 child_set_env(&env, &nenv, "LANG", cp);
2731 for (i = 1; i < NSIG; i++)
2732 ssh_signal(i, SIG_DFL);
2734 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2735 error("%s: open %s: %s", tag, _PATH_DEVNULL,
2739 if (dup2(devnull, STDIN_FILENO) == -1) {
2740 error("%s: dup2: %s", tag, strerror(errno));
2744 /* Set up stdout as requested; leave stderr in place for now. */
2746 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2748 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2750 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2751 error("%s: dup2: %s", tag, strerror(errno));
2754 closefrom(STDERR_FILENO + 1);
2756 if (geteuid() == 0 &&
2757 initgroups(pw->pw_name, pw->pw_gid) == -1) {
2758 error("%s: initgroups(%s, %u): %s", tag,
2759 pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2762 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2763 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2767 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2768 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2772 /* stdin is pointed to /dev/null at this point */
2773 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2774 dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2775 error("%s: dup2: %s", tag, strerror(errno));
2779 execve(av[0], av, env);
2782 error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2783 command, strerror(errno));
2785 default: /* parent */
2790 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2792 else if ((f = fdopen(p[0], "r")) == NULL) {
2793 error("%s: fdopen: %s", tag, strerror(errno));
2795 /* Don't leave zombie child */
2797 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2802 debug3_f("%s pid %ld", tag, (long)pid);
2809 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2813 envlen = strlen(env);
2814 for (i = 0; i < nenvs; i++) {
2815 if (strncmp(envs[i], env, envlen) == 0 &&
2816 envs[i][envlen] == '=') {
2817 return envs[i] + envlen + 1;
2824 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2829 name = xstrdup(env);
2830 if ((cp = strchr(name, '=')) == NULL) {
2832 return NULL; /* not env=val */
2835 ret = lookup_env_in_list(name, envs, nenvs);
2841 * Helpers for managing poll(2)/ppoll(2) timeouts
2842 * Will remember the earliest deadline and return it for use in poll/ppoll.
2845 /* Initialise a poll/ppoll timeout with an indefinite deadline */
2847 ptimeout_init(struct timespec *pt)
2850 * Deliberately invalid for ppoll(2).
2851 * Will be converted to NULL in ptimeout_get_tspec() later.
2857 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2859 ptimeout_deadline_sec(struct timespec *pt, long sec)
2861 if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2867 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2869 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2871 if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2875 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2877 ptimeout_deadline_ms(struct timespec *pt, long ms)
2881 p.tv_sec = ms / 1000;
2882 p.tv_nsec = (ms % 1000) * 1000000;
2883 ptimeout_deadline_tsp(pt, &p);
2886 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
2888 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
2890 struct timespec now, t;
2896 if (timespeccmp(&now, &t, >=))
2897 ptimeout_deadline_sec(pt, 0);
2899 timespecsub(&t, &now, &t);
2900 ptimeout_deadline_tsp(pt, &t);
2904 /* Get a poll(2) timeout value in milliseconds */
2906 ptimeout_get_ms(struct timespec *pt)
2908 if (pt->tv_sec == -1)
2910 if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
2912 return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
2915 /* Get a ppoll(2) timeout value as a timespec pointer */
2917 ptimeout_get_tsp(struct timespec *pt)
2919 return pt->tv_sec == -1 ? NULL : pt;
2922 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
2924 ptimeout_isset(struct timespec *pt)
2926 return pt->tv_sec != -1;
2930 * Returns zero if the library at 'path' contains symbol 's', nonzero
2934 lib_contains_symbol(const char *path, const char *s)
2940 memset(nl, 0, sizeof(nl));
2941 nl[0].n_name = xstrdup(s);
2942 nl[1].n_name = NULL;
2943 if ((r = nlist(path, nl)) == -1) {
2944 error_f("nlist failed for %s", path);
2947 if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
2948 error_f("library %s does not contain symbol %s", path, s);
2956 #else /* HAVE_NLIST_H */
2962 memset(&st, 0, sizeof(st));
2963 if ((fd = open(path, O_RDONLY)) < 0) {
2964 error_f("open %s: %s", path, strerror(errno));
2967 if (fstat(fd, &st) != 0) {
2968 error_f("fstat %s: %s", path, strerror(errno));
2971 if (!S_ISREG(st.st_mode)) {
2972 error_f("%s is not a regular file", path);
2975 if (st.st_size < 0 ||
2976 (size_t)st.st_size < strlen(s) ||
2977 st.st_size >= INT_MAX/2) {
2978 error_f("%s bad size %lld", path, (long long)st.st_size);
2981 sz = (size_t)st.st_size;
2982 if ((m = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED ||
2984 error_f("mmap %s: %s", path, strerror(errno));
2987 if (memmem(m, sz, s, strlen(s)) == NULL) {
2988 error_f("%s does not contain expected string %s", path, s);
2994 if (m != NULL && m != MAP_FAILED)
2998 #endif /* HAVE_NLIST_H */