1 /* $OpenBSD: misc.c,v 1.85 2011/03/29 18:54:17 stevesk 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>
32 #include <sys/param.h>
41 #include <netinet/in.h>
42 #include <netinet/in_systm.h>
43 #include <netinet/ip.h>
44 #include <netinet/tcp.h>
54 #ifdef SSH_TUN_OPENBSD
63 /* remove newline at end of string */
69 if (*t == '\n' || *t == '\r') {
79 /* set/unset filedescriptor to non-blocking */
85 val = fcntl(fd, F_GETFL, 0);
87 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
90 if (val & O_NONBLOCK) {
91 debug3("fd %d is O_NONBLOCK", fd);
94 debug2("fd %d setting O_NONBLOCK", fd);
96 if (fcntl(fd, F_SETFL, val) == -1) {
97 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
105 unset_nonblock(int fd)
109 val = fcntl(fd, F_GETFL, 0);
111 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
114 if (!(val & O_NONBLOCK)) {
115 debug3("fd %d is not O_NONBLOCK", fd);
118 debug("fd %d clearing O_NONBLOCK", fd);
120 if (fcntl(fd, F_SETFL, val) == -1) {
121 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
122 fd, strerror(errno));
129 ssh_gai_strerror(int gaierr)
131 if (gaierr == EAI_SYSTEM)
132 return strerror(errno);
133 return gai_strerror(gaierr);
136 /* disable nagle on socket */
144 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
145 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
149 debug2("fd %d is TCP_NODELAY", fd);
153 debug2("fd %d setting TCP_NODELAY", fd);
154 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
155 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
158 /* Characters considered whitespace in strsep calls. */
159 #define WHITESPACE " \t\r\n"
162 /* return next token in configuration line */
174 *s = strpbrk(*s, WHITESPACE QUOTE "=");
179 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
180 /* Find matching quote */
181 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
182 return (NULL); /* no matching quote */
185 *s += strspn(*s + 1, WHITESPACE) + 1;
190 /* Allow only one '=' to be skipped */
195 /* Skip any extra whitespace after first token */
196 *s += strspn(*s + 1, WHITESPACE) + 1;
197 if (*s[0] == '=' && !wspace)
198 *s += strspn(*s + 1, WHITESPACE) + 1;
204 pwcopy(struct passwd *pw)
206 struct passwd *copy = xcalloc(1, sizeof(*copy));
208 copy->pw_name = xstrdup(pw->pw_name);
209 copy->pw_passwd = xstrdup(pw->pw_passwd);
210 copy->pw_gecos = xstrdup(pw->pw_gecos);
211 copy->pw_uid = pw->pw_uid;
212 copy->pw_gid = pw->pw_gid;
213 #ifdef HAVE_PW_EXPIRE_IN_PASSWD
214 copy->pw_expire = pw->pw_expire;
216 #ifdef HAVE_PW_CHANGE_IN_PASSWD
217 copy->pw_change = pw->pw_change;
219 #ifdef HAVE_PW_CLASS_IN_PASSWD
220 copy->pw_class = xstrdup(pw->pw_class);
222 copy->pw_dir = xstrdup(pw->pw_dir);
223 copy->pw_shell = xstrdup(pw->pw_shell);
228 pwfree(struct passwd *pw)
231 xfree(pw->pw_passwd);
233 #ifdef HAVE_PW_CLASS_IN_PASSWD
242 * Convert ASCII string to TCP/IP port number.
243 * Port must be >=0 and <=65535.
244 * Return -1 if invalid.
247 a2port(const char *s)
252 port = strtonum(s, 0, 65535, &errstr);
259 a2tun(const char *s, int *remote)
261 const char *errstr = NULL;
265 if (remote != NULL) {
266 *remote = SSH_TUNID_ANY;
268 if ((ep = strchr(sp, ':')) == NULL) {
270 return (a2tun(s, NULL));
273 *remote = a2tun(ep, NULL);
274 tun = a2tun(sp, NULL);
276 return (*remote == SSH_TUNID_ERR ? *remote : tun);
279 if (strcasecmp(s, "any") == 0)
280 return (SSH_TUNID_ANY);
282 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
284 return (SSH_TUNID_ERR);
290 #define MINUTES (SECONDS * 60)
291 #define HOURS (MINUTES * 60)
292 #define DAYS (HOURS * 24)
293 #define WEEKS (DAYS * 7)
296 * Convert a time string into seconds; format is
300 * Valid time qualifiers are:
314 * Return -1 if time string is invalid.
317 convtime(const char *s)
327 if (p == NULL || *p == '\0')
331 secs = strtol(p, &endp, 10);
333 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
373 * Returns a standardized host+port identifier string.
374 * Caller must free returned string.
377 put_host_port(const char *host, u_short port)
381 if (port == 0 || port == SSH_DEFAULT_PORT)
382 return(xstrdup(host));
383 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
384 fatal("put_host_port: asprintf: %s", strerror(errno));
385 debug3("put_host_port: %s", hoststr);
390 * Search for next delimiter between hostnames/addresses and ports.
391 * Argument may be modified (for termination).
392 * Returns *cp if parsing succeeds.
393 * *cp is set to the start of the next delimiter, if one was found.
394 * If this is the last field, *cp is set to NULL.
401 if (cp == NULL || *cp == NULL)
406 if ((s = strchr(s, ']')) == NULL)
410 } else if ((s = strpbrk(s, ":/")) == NULL)
411 s = *cp + strlen(*cp); /* skip to end (see first case below) */
415 *cp = NULL; /* no more fields*/
420 *s = '\0'; /* terminate */
432 cleanhostname(char *host)
434 if (*host == '[' && host[strlen(host) - 1] == ']') {
435 host[strlen(host) - 1] = '\0';
446 if (*cp == ':') /* Leading colon is part of file name. */
452 if (*cp == '@' && *(cp+1) == '[')
454 if (*cp == ']' && *(cp+1) == ':' && flag)
456 if (*cp == ':' && !flag)
464 /* function to assist building execv() arguments */
466 addargs(arglist *args, char *fmt, ...)
474 r = vasprintf(&cp, fmt, ap);
477 fatal("addargs: argument too long");
479 nalloc = args->nalloc;
480 if (args->list == NULL) {
483 } else if (args->num+2 >= nalloc)
486 args->list = xrealloc(args->list, nalloc, sizeof(char *));
487 args->nalloc = nalloc;
488 args->list[args->num++] = cp;
489 args->list[args->num] = NULL;
493 replacearg(arglist *args, u_int which, char *fmt, ...)
500 r = vasprintf(&cp, fmt, ap);
503 fatal("replacearg: argument too long");
505 if (which >= args->num)
506 fatal("replacearg: tried to replace invalid arg %d >= %d",
508 xfree(args->list[which]);
509 args->list[which] = cp;
513 freeargs(arglist *args)
517 if (args->list != NULL) {
518 for (i = 0; i < args->num; i++)
519 xfree(args->list[i]);
521 args->nalloc = args->num = 0;
527 * Expands tildes in the file name. Returns data allocated by xmalloc.
528 * Warning: this calls getpw*.
531 tilde_expand_filename(const char *filename, uid_t uid)
534 char user[128], ret[MAXPATHLEN];
538 if (*filename != '~')
539 return (xstrdup(filename));
542 path = strchr(filename, '/');
543 if (path != NULL && path > filename) { /* ~user/path */
544 slash = path - filename;
545 if (slash > sizeof(user) - 1)
546 fatal("tilde_expand_filename: ~username too long");
547 memcpy(user, filename, slash);
549 if ((pw = getpwnam(user)) == NULL)
550 fatal("tilde_expand_filename: No such user %s", user);
551 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
552 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
554 if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
555 fatal("tilde_expand_filename: Path too long");
557 /* Make sure directory has a trailing '/' */
558 len = strlen(pw->pw_dir);
559 if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
560 strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
561 fatal("tilde_expand_filename: Path too long");
563 /* Skip leading '/' from specified path */
566 if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
567 fatal("tilde_expand_filename: Path too long");
569 return (xstrdup(ret));
573 * Expand a string with a set of %[char] escapes. A number of escapes may be
574 * specified as (char *escape_chars, char *replacement) pairs. The list must
575 * be terminated by a NULL escape_char. Returns replaced string in memory
576 * allocated by xmalloc.
579 percent_expand(const char *string, ...)
581 #define EXPAND_MAX_KEYS 16
582 u_int num_keys, i, j;
586 } keys[EXPAND_MAX_KEYS];
591 va_start(ap, string);
592 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
593 keys[num_keys].key = va_arg(ap, char *);
594 if (keys[num_keys].key == NULL)
596 keys[num_keys].repl = va_arg(ap, char *);
597 if (keys[num_keys].repl == NULL)
598 fatal("%s: NULL replacement", __func__);
600 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
601 fatal("%s: too many keys", __func__);
606 for (i = 0; *string != '\0'; string++) {
607 if (*string != '%') {
610 if (i >= sizeof(buf))
611 fatal("%s: string too long", __func__);
619 for (j = 0; j < num_keys; j++) {
620 if (strchr(keys[j].key, *string) != NULL) {
621 i = strlcat(buf, keys[j].repl, sizeof(buf));
622 if (i >= sizeof(buf))
623 fatal("%s: string too long", __func__);
628 fatal("%s: unknown key %%%c", __func__, *string);
630 return (xstrdup(buf));
631 #undef EXPAND_MAX_KEYS
635 * Read an entire line from a public key file into a static buffer, discarding
636 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
639 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
642 while (fgets(buf, bufsz, f) != NULL) {
646 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
649 debug("%s: %s line %lu exceeds size limit", __func__,
651 /* discard remainder of line */
652 while (fgetc(f) != '\n' && !feof(f))
660 secure_permissions(struct stat *st, uid_t uid)
662 if (st->st_uid != 0 && st->st_uid != uid)
664 if ((st->st_mode & 002) != 0)
666 if ((st->st_mode & 020) != 0) {
667 /* If the file is group-writable, the group in question must
668 * have exactly one member, namely the file's owner.
669 * (Zero-member groups are typically used by setgid
670 * binaries, and are unlikely to be suitable.)
676 gr = getgrgid(st->st_gid);
680 /* Check primary group memberships. */
681 while ((pw = getpwent()) != NULL) {
682 if (pw->pw_gid == gr->gr_gid) {
684 if (pw->pw_uid != uid)
690 pw = getpwuid(st->st_uid);
694 /* Check supplementary group memberships. */
697 if (strcmp(pw->pw_name, gr->gr_mem[0]) ||
709 tun_open(int tun, int mode)
711 #if defined(CUSTOM_SYS_TUN_OPEN)
712 return (sys_tun_open(tun, mode));
713 #elif defined(SSH_TUN_OPENBSD)
718 /* Open the tunnel device */
719 if (tun <= SSH_TUNID_MAX) {
720 snprintf(name, sizeof(name), "/dev/tun%d", tun);
721 fd = open(name, O_RDWR);
722 } else if (tun == SSH_TUNID_ANY) {
723 for (tun = 100; tun >= 0; tun--) {
724 snprintf(name, sizeof(name), "/dev/tun%d", tun);
725 if ((fd = open(name, O_RDWR)) >= 0)
729 debug("%s: invalid tunnel %u", __func__, tun);
734 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
738 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
740 /* Set the tunnel device operation mode */
741 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
742 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
745 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
748 /* Set interface mode */
749 ifr.ifr_flags &= ~IFF_UP;
750 if (mode == SSH_TUNMODE_ETHERNET)
751 ifr.ifr_flags |= IFF_LINK0;
753 ifr.ifr_flags &= ~IFF_LINK0;
754 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
757 /* Bring interface up */
758 ifr.ifr_flags |= IFF_UP;
759 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
770 debug("%s: failed to set %s mode %d: %s", __func__, name,
771 mode, strerror(errno));
774 error("Tunnel interfaces are not supported on this platform");
784 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
785 fprintf(stderr, "Couldn't open /dev/null: %s\n",
789 while (++dupfd <= 2) {
790 /* Only clobber closed fds */
791 if (fcntl(dupfd, F_GETFL, 0) >= 0)
793 if (dup2(nullfd, dupfd) == -1) {
794 fprintf(stderr, "dup2: %s\n", strerror(errno));
803 tohex(const void *vp, size_t l)
805 const u_char *p = (const u_char *)vp;
810 return xstrdup("tohex: length > 65536");
814 for (i = 0; i < l; i++) {
815 snprintf(b, sizeof(b), "%02x", p[i]);
822 get_u64(const void *vp)
824 const u_char *p = (const u_char *)vp;
827 v = (u_int64_t)p[0] << 56;
828 v |= (u_int64_t)p[1] << 48;
829 v |= (u_int64_t)p[2] << 40;
830 v |= (u_int64_t)p[3] << 32;
831 v |= (u_int64_t)p[4] << 24;
832 v |= (u_int64_t)p[5] << 16;
833 v |= (u_int64_t)p[6] << 8;
834 v |= (u_int64_t)p[7];
840 get_u32(const void *vp)
842 const u_char *p = (const u_char *)vp;
845 v = (u_int32_t)p[0] << 24;
846 v |= (u_int32_t)p[1] << 16;
847 v |= (u_int32_t)p[2] << 8;
848 v |= (u_int32_t)p[3];
854 get_u16(const void *vp)
856 const u_char *p = (const u_char *)vp;
859 v = (u_int16_t)p[0] << 8;
860 v |= (u_int16_t)p[1];
866 put_u64(void *vp, u_int64_t v)
868 u_char *p = (u_char *)vp;
870 p[0] = (u_char)(v >> 56) & 0xff;
871 p[1] = (u_char)(v >> 48) & 0xff;
872 p[2] = (u_char)(v >> 40) & 0xff;
873 p[3] = (u_char)(v >> 32) & 0xff;
874 p[4] = (u_char)(v >> 24) & 0xff;
875 p[5] = (u_char)(v >> 16) & 0xff;
876 p[6] = (u_char)(v >> 8) & 0xff;
877 p[7] = (u_char)v & 0xff;
881 put_u32(void *vp, u_int32_t v)
883 u_char *p = (u_char *)vp;
885 p[0] = (u_char)(v >> 24) & 0xff;
886 p[1] = (u_char)(v >> 16) & 0xff;
887 p[2] = (u_char)(v >> 8) & 0xff;
888 p[3] = (u_char)v & 0xff;
893 put_u16(void *vp, u_int16_t v)
895 u_char *p = (u_char *)vp;
897 p[0] = (u_char)(v >> 8) & 0xff;
898 p[1] = (u_char)v & 0xff;
902 ms_subtract_diff(struct timeval *start, int *ms)
904 struct timeval diff, finish;
906 gettimeofday(&finish, NULL);
907 timersub(&finish, start, &diff);
908 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
912 ms_to_timeval(struct timeval *tv, int ms)
916 tv->tv_sec = ms / 1000;
917 tv->tv_usec = (ms % 1000) * 1000;
921 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
925 bw->thresh = bw->rate;
927 timerclear(&bw->bwstart);
928 timerclear(&bw->bwend);
931 /* Callback from read/write loop to insert bandwidth-limiting delays */
933 bandwidth_limit(struct bwlimit *bw, size_t read_len)
936 struct timespec ts, rm;
938 if (!timerisset(&bw->bwstart)) {
939 gettimeofday(&bw->bwstart, NULL);
943 bw->lamt += read_len;
944 if (bw->lamt < bw->thresh)
947 gettimeofday(&bw->bwend, NULL);
948 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
949 if (!timerisset(&bw->bwend))
953 waitlen = (double)1000000L * bw->lamt / bw->rate;
955 bw->bwstart.tv_sec = waitlen / 1000000L;
956 bw->bwstart.tv_usec = waitlen % 1000000L;
958 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
959 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
961 /* Adjust the wait time */
962 if (bw->bwend.tv_sec) {
964 if (bw->thresh < bw->buflen / 4)
965 bw->thresh = bw->buflen / 4;
966 } else if (bw->bwend.tv_usec < 10000) {
968 if (bw->thresh > bw->buflen * 8)
969 bw->thresh = bw->buflen * 8;
972 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
973 while (nanosleep(&ts, &rm) == -1) {
981 gettimeofday(&bw->bwstart, NULL);
984 /* Make a template filename for mk[sd]temp() */
986 mktemp_proto(char *s, size_t len)
991 if ((tmpdir = getenv("TMPDIR")) != NULL) {
992 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
993 if (r > 0 && (size_t)r < len)
996 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
997 if (r < 0 || (size_t)r >= len)
998 fatal("%s: template string too short", __func__);
1001 static const struct {
1005 { "af11", IPTOS_DSCP_AF11 },
1006 { "af12", IPTOS_DSCP_AF12 },
1007 { "af13", IPTOS_DSCP_AF13 },
1008 { "af14", IPTOS_DSCP_AF21 },
1009 { "af22", IPTOS_DSCP_AF22 },
1010 { "af23", IPTOS_DSCP_AF23 },
1011 { "af31", IPTOS_DSCP_AF31 },
1012 { "af32", IPTOS_DSCP_AF32 },
1013 { "af33", IPTOS_DSCP_AF33 },
1014 { "af41", IPTOS_DSCP_AF41 },
1015 { "af42", IPTOS_DSCP_AF42 },
1016 { "af43", IPTOS_DSCP_AF43 },
1017 { "cs0", IPTOS_DSCP_CS0 },
1018 { "cs1", IPTOS_DSCP_CS1 },
1019 { "cs2", IPTOS_DSCP_CS2 },
1020 { "cs3", IPTOS_DSCP_CS3 },
1021 { "cs4", IPTOS_DSCP_CS4 },
1022 { "cs5", IPTOS_DSCP_CS5 },
1023 { "cs6", IPTOS_DSCP_CS6 },
1024 { "cs7", IPTOS_DSCP_CS7 },
1025 { "ef", IPTOS_DSCP_EF },
1026 { "lowdelay", IPTOS_LOWDELAY },
1027 { "throughput", IPTOS_THROUGHPUT },
1028 { "reliability", IPTOS_RELIABILITY },
1033 parse_ipqos(const char *cp)
1041 for (i = 0; ipqos[i].name != NULL; i++) {
1042 if (strcasecmp(cp, ipqos[i].name) == 0)
1043 return ipqos[i].value;
1045 /* Try parsing as an integer */
1046 val = strtol(cp, &ep, 0);
1047 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1053 iptos2str(int iptos)
1056 static char iptos_str[sizeof "0xff"];
1058 for (i = 0; ipqos[i].name != NULL; i++) {
1059 if (ipqos[i].value == iptos)
1060 return ipqos[i].name;
1062 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1066 sock_set_v6only(int s)
1071 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1072 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1073 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));