1 /* $OpenBSD: misc.c,v 1.59 2006/07/17 01:31:09 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/ioctl.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <netinet/tcp.h>
45 #ifdef SSH_TUN_OPENBSD
54 /* remove newline at end of string */
60 if (*t == '\n' || *t == '\r') {
70 /* set/unset filedescriptor to non-blocking */
76 val = fcntl(fd, F_GETFL, 0);
78 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
81 if (val & O_NONBLOCK) {
82 debug3("fd %d is O_NONBLOCK", fd);
85 debug2("fd %d setting O_NONBLOCK", fd);
87 if (fcntl(fd, F_SETFL, val) == -1) {
88 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
96 unset_nonblock(int fd)
100 val = fcntl(fd, F_GETFL, 0);
102 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
105 if (!(val & O_NONBLOCK)) {
106 debug3("fd %d is not O_NONBLOCK", fd);
109 debug("fd %d clearing O_NONBLOCK", fd);
111 if (fcntl(fd, F_SETFL, val) == -1) {
112 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
113 fd, strerror(errno));
119 /* disable nagle on socket */
127 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
128 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
132 debug2("fd %d is TCP_NODELAY", fd);
136 debug2("fd %d setting TCP_NODELAY", fd);
137 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
138 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
141 /* Characters considered whitespace in strsep calls. */
142 #define WHITESPACE " \t\r\n"
145 /* return next token in configuration line */
157 *s = strpbrk(*s, WHITESPACE QUOTE "=");
162 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
163 /* Find matching quote */
164 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
165 return (NULL); /* no matching quote */
172 /* Allow only one '=' to be skipped */
177 /* Skip any extra whitespace after first token */
178 *s += strspn(*s + 1, WHITESPACE) + 1;
179 if (*s[0] == '=' && !wspace)
180 *s += strspn(*s + 1, WHITESPACE) + 1;
186 pwcopy(struct passwd *pw)
188 struct passwd *copy = xcalloc(1, sizeof(*copy));
190 copy->pw_name = xstrdup(pw->pw_name);
191 copy->pw_passwd = xstrdup(pw->pw_passwd);
192 copy->pw_gecos = xstrdup(pw->pw_gecos);
193 copy->pw_uid = pw->pw_uid;
194 copy->pw_gid = pw->pw_gid;
195 #ifdef HAVE_PW_EXPIRE_IN_PASSWD
196 copy->pw_expire = pw->pw_expire;
198 #ifdef HAVE_PW_CHANGE_IN_PASSWD
199 copy->pw_change = pw->pw_change;
201 #ifdef HAVE_PW_CLASS_IN_PASSWD
202 copy->pw_class = xstrdup(pw->pw_class);
204 copy->pw_dir = xstrdup(pw->pw_dir);
205 copy->pw_shell = xstrdup(pw->pw_shell);
210 * Convert ASCII string to TCP/IP port number.
211 * Port must be >0 and <=65535.
212 * Return 0 if invalid.
215 a2port(const char *s)
221 port = strtol(s, &endp, 0);
222 if (s == endp || *endp != '\0' ||
223 (errno == ERANGE && (port == LONG_MIN || port == LONG_MAX)) ||
224 port <= 0 || port > 65535)
231 a2tun(const char *s, int *remote)
233 const char *errstr = NULL;
237 if (remote != NULL) {
238 *remote = SSH_TUNID_ANY;
240 if ((ep = strchr(sp, ':')) == NULL) {
242 return (a2tun(s, NULL));
245 *remote = a2tun(ep, NULL);
246 tun = a2tun(sp, NULL);
248 return (*remote == SSH_TUNID_ERR ? *remote : tun);
251 if (strcasecmp(s, "any") == 0)
252 return (SSH_TUNID_ANY);
254 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
256 return (SSH_TUNID_ERR);
262 #define MINUTES (SECONDS * 60)
263 #define HOURS (MINUTES * 60)
264 #define DAYS (HOURS * 24)
265 #define WEEKS (DAYS * 7)
268 * Convert a time string into seconds; format is
272 * Valid time qualifiers are:
286 * Return -1 if time string is invalid.
289 convtime(const char *s)
299 if (p == NULL || *p == '\0')
303 secs = strtol(p, &endp, 10);
305 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
345 * Returns a standardized host+port identifier string.
346 * Caller must free returned string.
349 put_host_port(const char *host, u_short port)
353 if (port == 0 || port == SSH_DEFAULT_PORT)
354 return(xstrdup(host));
355 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
356 fatal("put_host_port: asprintf: %s", strerror(errno));
357 debug3("put_host_port: %s", hoststr);
362 * Search for next delimiter between hostnames/addresses and ports.
363 * Argument may be modified (for termination).
364 * Returns *cp if parsing succeeds.
365 * *cp is set to the start of the next delimiter, if one was found.
366 * If this is the last field, *cp is set to NULL.
373 if (cp == NULL || *cp == NULL)
378 if ((s = strchr(s, ']')) == NULL)
382 } else if ((s = strpbrk(s, ":/")) == NULL)
383 s = *cp + strlen(*cp); /* skip to end (see first case below) */
387 *cp = NULL; /* no more fields*/
392 *s = '\0'; /* terminate */
404 cleanhostname(char *host)
406 if (*host == '[' && host[strlen(host) - 1] == ']') {
407 host[strlen(host) - 1] = '\0';
418 if (*cp == ':') /* Leading colon is part of file name. */
424 if (*cp == '@' && *(cp+1) == '[')
426 if (*cp == ']' && *(cp+1) == ':' && flag)
428 if (*cp == ':' && !flag)
436 /* function to assist building execv() arguments */
438 addargs(arglist *args, char *fmt, ...)
446 r = vasprintf(&cp, fmt, ap);
449 fatal("addargs: argument too long");
451 nalloc = args->nalloc;
452 if (args->list == NULL) {
455 } else if (args->num+2 >= nalloc)
458 args->list = xrealloc(args->list, nalloc, sizeof(char *));
459 args->nalloc = nalloc;
460 args->list[args->num++] = cp;
461 args->list[args->num] = NULL;
465 replacearg(arglist *args, u_int which, char *fmt, ...)
472 r = vasprintf(&cp, fmt, ap);
475 fatal("replacearg: argument too long");
477 if (which >= args->num)
478 fatal("replacearg: tried to replace invalid arg %d >= %d",
480 xfree(args->list[which]);
481 args->list[which] = cp;
485 freeargs(arglist *args)
489 if (args->list != NULL) {
490 for (i = 0; i < args->num; i++)
491 xfree(args->list[i]);
493 args->nalloc = args->num = 0;
499 * Expands tildes in the file name. Returns data allocated by xmalloc.
500 * Warning: this calls getpw*.
503 tilde_expand_filename(const char *filename, uid_t uid)
506 char user[128], ret[MAXPATHLEN];
510 if (*filename != '~')
511 return (xstrdup(filename));
514 path = strchr(filename, '/');
515 if (path != NULL && path > filename) { /* ~user/path */
516 slash = path - filename;
517 if (slash > sizeof(user) - 1)
518 fatal("tilde_expand_filename: ~username too long");
519 memcpy(user, filename, slash);
521 if ((pw = getpwnam(user)) == NULL)
522 fatal("tilde_expand_filename: No such user %s", user);
523 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
524 fatal("tilde_expand_filename: No such uid %d", uid);
526 if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
527 fatal("tilde_expand_filename: Path too long");
529 /* Make sure directory has a trailing '/' */
530 len = strlen(pw->pw_dir);
531 if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
532 strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
533 fatal("tilde_expand_filename: Path too long");
535 /* Skip leading '/' from specified path */
538 if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
539 fatal("tilde_expand_filename: Path too long");
541 return (xstrdup(ret));
545 * Expand a string with a set of %[char] escapes. A number of escapes may be
546 * specified as (char *escape_chars, char *replacement) pairs. The list must
547 * be terminated by a NULL escape_char. Returns replaced string in memory
548 * allocated by xmalloc.
551 percent_expand(const char *string, ...)
553 #define EXPAND_MAX_KEYS 16
557 } keys[EXPAND_MAX_KEYS];
558 u_int num_keys, i, j;
563 va_start(ap, string);
564 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
565 keys[num_keys].key = va_arg(ap, char *);
566 if (keys[num_keys].key == NULL)
568 keys[num_keys].repl = va_arg(ap, char *);
569 if (keys[num_keys].repl == NULL)
570 fatal("percent_expand: NULL replacement");
574 if (num_keys >= EXPAND_MAX_KEYS)
575 fatal("percent_expand: too many keys");
579 for (i = 0; *string != '\0'; string++) {
580 if (*string != '%') {
583 if (i >= sizeof(buf))
584 fatal("percent_expand: string too long");
591 for (j = 0; j < num_keys; j++) {
592 if (strchr(keys[j].key, *string) != NULL) {
593 i = strlcat(buf, keys[j].repl, sizeof(buf));
594 if (i >= sizeof(buf))
595 fatal("percent_expand: string too long");
600 fatal("percent_expand: unknown key %%%c", *string);
602 return (xstrdup(buf));
603 #undef EXPAND_MAX_KEYS
607 * Read an entire line from a public key file into a static buffer, discarding
608 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
611 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
614 while (fgets(buf, bufsz, f) != NULL) {
616 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
619 debug("%s: %s line %lu exceeds size limit", __func__,
621 /* discard remainder of line */
622 while (fgetc(f) != '\n' && !feof(f))
630 tun_open(int tun, int mode)
632 #if defined(CUSTOM_SYS_TUN_OPEN)
633 return (sys_tun_open(tun, mode));
634 #elif defined(SSH_TUN_OPENBSD)
639 /* Open the tunnel device */
640 if (tun <= SSH_TUNID_MAX) {
641 snprintf(name, sizeof(name), "/dev/tun%d", tun);
642 fd = open(name, O_RDWR);
643 } else if (tun == SSH_TUNID_ANY) {
644 for (tun = 100; tun >= 0; tun--) {
645 snprintf(name, sizeof(name), "/dev/tun%d", tun);
646 if ((fd = open(name, O_RDWR)) >= 0)
650 debug("%s: invalid tunnel %u", __func__, tun);
655 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
659 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
661 /* Set the tunnel device operation mode */
662 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
663 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
666 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
669 /* Set interface mode */
670 ifr.ifr_flags &= ~IFF_UP;
671 if (mode == SSH_TUNMODE_ETHERNET)
672 ifr.ifr_flags |= IFF_LINK0;
674 ifr.ifr_flags &= ~IFF_LINK0;
675 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
678 /* Bring interface up */
679 ifr.ifr_flags |= IFF_UP;
680 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
691 debug("%s: failed to set %s mode %d: %s", __func__, name,
692 mode, strerror(errno));
695 error("Tunnel interfaces are not supported on this platform");
705 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
706 fprintf(stderr, "Couldn't open /dev/null: %s", strerror(errno));
709 while (++dupfd <= 2) {
710 /* Only clobber closed fds */
711 if (fcntl(dupfd, F_GETFL, 0) >= 0)
713 if (dup2(nullfd, dupfd) == -1) {
714 fprintf(stderr, "dup2: %s", strerror(errno));
723 tohex(const void *vp, size_t l)
725 const u_char *p = (const u_char *)vp;
730 return xstrdup("tohex: length > 65536");
734 for (i = 0; i < l; i++) {
735 snprintf(b, sizeof(b), "%02x", p[i]);
742 get_u64(const void *vp)
744 const u_char *p = (const u_char *)vp;
747 v = (u_int64_t)p[0] << 56;
748 v |= (u_int64_t)p[1] << 48;
749 v |= (u_int64_t)p[2] << 40;
750 v |= (u_int64_t)p[3] << 32;
751 v |= (u_int64_t)p[4] << 24;
752 v |= (u_int64_t)p[5] << 16;
753 v |= (u_int64_t)p[6] << 8;
754 v |= (u_int64_t)p[7];
760 get_u32(const void *vp)
762 const u_char *p = (const u_char *)vp;
765 v = (u_int32_t)p[0] << 24;
766 v |= (u_int32_t)p[1] << 16;
767 v |= (u_int32_t)p[2] << 8;
768 v |= (u_int32_t)p[3];
774 get_u16(const void *vp)
776 const u_char *p = (const u_char *)vp;
779 v = (u_int16_t)p[0] << 8;
780 v |= (u_int16_t)p[1];
786 put_u64(void *vp, u_int64_t v)
788 u_char *p = (u_char *)vp;
790 p[0] = (u_char)(v >> 56) & 0xff;
791 p[1] = (u_char)(v >> 48) & 0xff;
792 p[2] = (u_char)(v >> 40) & 0xff;
793 p[3] = (u_char)(v >> 32) & 0xff;
794 p[4] = (u_char)(v >> 24) & 0xff;
795 p[5] = (u_char)(v >> 16) & 0xff;
796 p[6] = (u_char)(v >> 8) & 0xff;
797 p[7] = (u_char)v & 0xff;
801 put_u32(void *vp, u_int32_t v)
803 u_char *p = (u_char *)vp;
805 p[0] = (u_char)(v >> 24) & 0xff;
806 p[1] = (u_char)(v >> 16) & 0xff;
807 p[2] = (u_char)(v >> 8) & 0xff;
808 p[3] = (u_char)v & 0xff;
813 put_u16(void *vp, u_int16_t v)
815 u_char *p = (u_char *)vp;
817 p[0] = (u_char)(v >> 8) & 0xff;
818 p[1] = (u_char)v & 0xff;