Annotation of src/usr.bin/ssh/misc.c, Revision 1.167
1.167 ! dtucker 1: /* $OpenBSD: misc.c,v 1.166 2021/06/08 06:54:40 djm Exp $ */
1.1 markus 2: /*
3: * Copyright (c) 2000 Markus Friedl. All rights reserved.
1.148 djm 4: * Copyright (c) 2005-2020 Damien Miller. All rights reserved.
5: * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
1.1 markus 6: *
1.148 djm 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.
1.1 markus 10: *
1.148 djm 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.
1.1 markus 18: */
19:
1.148 djm 20:
1.64 deraadt 21: #include <sys/types.h>
1.45 stevesk 22: #include <sys/ioctl.h>
1.53 stevesk 23: #include <sys/socket.h>
1.112 djm 24: #include <sys/stat.h>
1.101 dtucker 25: #include <sys/time.h>
1.112 djm 26: #include <sys/wait.h>
1.94 millert 27: #include <sys/un.h>
1.38 stevesk 28:
29: #include <net/if.h>
1.53 stevesk 30: #include <netinet/in.h>
1.83 djm 31: #include <netinet/ip.h>
1.44 stevesk 32: #include <netinet/tcp.h>
1.133 naddy 33: #include <arpa/inet.h>
1.43 stevesk 34:
1.92 djm 35: #include <ctype.h>
1.58 stevesk 36: #include <errno.h>
1.55 stevesk 37: #include <fcntl.h>
1.66 dtucker 38: #include <netdb.h>
1.43 stevesk 39: #include <paths.h>
1.54 stevesk 40: #include <pwd.h>
1.112 djm 41: #include <libgen.h>
1.96 deraadt 42: #include <limits.h>
1.136 djm 43: #include <poll.h>
1.112 djm 44: #include <signal.h>
1.57 stevesk 45: #include <stdarg.h>
1.63 stevesk 46: #include <stdio.h>
1.62 stevesk 47: #include <stdlib.h>
1.60 stevesk 48: #include <string.h>
1.59 stevesk 49: #include <unistd.h>
1.1 markus 50:
1.64 deraadt 51: #include "xmalloc.h"
1.1 markus 52: #include "misc.h"
53: #include "log.h"
1.56 dtucker 54: #include "ssh.h"
1.112 djm 55: #include "sshbuf.h"
56: #include "ssherr.h"
1.1 markus 57:
1.12 markus 58: /* remove newline at end of string */
1.1 markus 59: char *
60: chop(char *s)
61: {
62: char *t = s;
63: while (*t) {
1.13 deraadt 64: if (*t == '\n' || *t == '\r') {
1.1 markus 65: *t = '\0';
66: return s;
67: }
68: t++;
69: }
70: return s;
71:
72: }
73:
1.166 djm 74: /* remove whitespace from end of string */
75: void
76: rtrim(char *s)
77: {
78: size_t i;
79:
80: if ((i = strlen(s)) == 0)
81: return;
82: for (i--; i > 0; i--) {
83: if (isspace((int)s[i]))
84: s[i] = '\0';
85: }
86: }
87:
1.12 markus 88: /* set/unset filedescriptor to non-blocking */
1.24 djm 89: int
1.1 markus 90: set_nonblock(int fd)
91: {
92: int val;
1.8 markus 93:
1.103 krw 94: val = fcntl(fd, F_GETFL);
1.139 deraadt 95: if (val == -1) {
1.103 krw 96: error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
1.24 djm 97: return (-1);
1.1 markus 98: }
99: if (val & O_NONBLOCK) {
1.24 djm 100: debug3("fd %d is O_NONBLOCK", fd);
101: return (0);
1.1 markus 102: }
1.21 markus 103: debug2("fd %d setting O_NONBLOCK", fd);
1.1 markus 104: val |= O_NONBLOCK;
1.24 djm 105: if (fcntl(fd, F_SETFL, val) == -1) {
106: debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
107: strerror(errno));
108: return (-1);
109: }
110: return (0);
1.8 markus 111: }
112:
1.24 djm 113: int
1.8 markus 114: unset_nonblock(int fd)
115: {
116: int val;
117:
1.103 krw 118: val = fcntl(fd, F_GETFL);
1.139 deraadt 119: if (val == -1) {
1.103 krw 120: error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
1.24 djm 121: return (-1);
1.8 markus 122: }
123: if (!(val & O_NONBLOCK)) {
1.24 djm 124: debug3("fd %d is not O_NONBLOCK", fd);
125: return (0);
1.8 markus 126: }
1.10 markus 127: debug("fd %d clearing O_NONBLOCK", fd);
1.8 markus 128: val &= ~O_NONBLOCK;
1.24 djm 129: if (fcntl(fd, F_SETFL, val) == -1) {
130: debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
1.18 markus 131: fd, strerror(errno));
1.24 djm 132: return (-1);
133: }
134: return (0);
1.66 dtucker 135: }
136:
137: const char *
138: ssh_gai_strerror(int gaierr)
139: {
1.91 djm 140: if (gaierr == EAI_SYSTEM && errno != 0)
1.67 dtucker 141: return strerror(errno);
142: return gai_strerror(gaierr);
1.15 stevesk 143: }
144:
145: /* disable nagle on socket */
146: void
147: set_nodelay(int fd)
148: {
1.17 stevesk 149: int opt;
150: socklen_t optlen;
1.15 stevesk 151:
1.16 stevesk 152: optlen = sizeof opt;
153: if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
1.23 markus 154: debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
1.16 stevesk 155: return;
156: }
157: if (opt == 1) {
158: debug2("fd %d is TCP_NODELAY", fd);
159: return;
160: }
161: opt = 1;
1.20 markus 162: debug2("fd %d setting TCP_NODELAY", fd);
1.16 stevesk 163: if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
1.15 stevesk 164: error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1.117 djm 165: }
166:
167: /* Allow local port reuse in TIME_WAIT */
168: int
169: set_reuseaddr(int fd)
170: {
171: int on = 1;
172:
173: if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
174: error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
175: return -1;
176: }
177: return 0;
178: }
179:
1.118 djm 180: /* Get/set routing domain */
181: char *
182: get_rdomain(int fd)
183: {
184: int rtable;
185: char *ret;
186: socklen_t len = sizeof(rtable);
187:
188: if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
189: error("Failed to get routing domain for fd %d: %s",
190: fd, strerror(errno));
191: return NULL;
192: }
193: xasprintf(&ret, "%d", rtable);
194: return ret;
195: }
196:
1.117 djm 197: int
198: set_rdomain(int fd, const char *name)
199: {
200: int rtable;
201: const char *errstr;
202:
203: if (name == NULL)
204: return 0; /* default table */
205:
206: rtable = (int)strtonum(name, 0, 255, &errstr);
207: if (errstr != NULL) {
208: /* Shouldn't happen */
209: error("Invalid routing domain \"%s\": %s", name, errstr);
210: return -1;
211: }
212: if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
213: &rtable, sizeof(rtable)) == -1) {
214: error("Failed to set routing domain %d on fd %d: %s",
215: rtable, fd, strerror(errno));
216: return -1;
217: }
1.136 djm 218: return 0;
1.156 djm 219: }
220:
221: int
222: get_sock_af(int fd)
223: {
224: struct sockaddr_storage to;
225: socklen_t tolen = sizeof(to);
226:
227: memset(&to, 0, sizeof(to));
228: if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
229: return -1;
230: return to.ss_family;
231: }
232:
233: void
234: set_sock_tos(int fd, int tos)
235: {
236: int af;
237:
238: switch ((af = get_sock_af(fd))) {
239: case -1:
240: /* assume not a socket */
241: break;
242: case AF_INET:
243: debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
244: if (setsockopt(fd, IPPROTO_IP, IP_TOS,
245: &tos, sizeof(tos)) == -1) {
246: error("setsockopt socket %d IP_TOS %d: %s:",
247: fd, tos, strerror(errno));
248: }
249: break;
250: case AF_INET6:
251: debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
252: if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
253: &tos, sizeof(tos)) == -1) {
254: error("setsockopt socket %d IPV6_TCLASS %d: %.100s:",
255: fd, tos, strerror(errno));
256: }
257: break;
258: default:
259: debug2_f("unsupported socket family %d", af);
260: break;
261: }
1.136 djm 262: }
263:
264: /*
1.143 dtucker 265: * Wait up to *timeoutp milliseconds for events on fd. Updates
1.136 djm 266: * *timeoutp with time remaining.
267: * Returns 0 if fd ready or -1 on timeout or error (see errno).
268: */
1.143 dtucker 269: static int
270: waitfd(int fd, int *timeoutp, short events)
1.136 djm 271: {
272: struct pollfd pfd;
273: struct timeval t_start;
274: int oerrno, r;
275:
276: pfd.fd = fd;
1.143 dtucker 277: pfd.events = events;
1.136 djm 278: for (; *timeoutp >= 0;) {
1.159 dtucker 279: monotime_tv(&t_start);
1.136 djm 280: r = poll(&pfd, 1, *timeoutp);
281: oerrno = errno;
282: ms_subtract_diff(&t_start, timeoutp);
283: errno = oerrno;
284: if (r > 0)
285: return 0;
1.153 djm 286: else if (r == -1 && errno != EAGAIN && errno != EINTR)
1.136 djm 287: return -1;
288: else if (r == 0)
289: break;
290: }
291: /* timeout */
292: errno = ETIMEDOUT;
293: return -1;
294: }
295:
296: /*
1.143 dtucker 297: * Wait up to *timeoutp milliseconds for fd to be readable. Updates
298: * *timeoutp with time remaining.
299: * Returns 0 if fd ready or -1 on timeout or error (see errno).
300: */
301: int
302: waitrfd(int fd, int *timeoutp) {
303: return waitfd(fd, timeoutp, POLLIN);
304: }
305:
306: /*
1.136 djm 307: * Attempt a non-blocking connect(2) to the specified address, waiting up to
308: * *timeoutp milliseconds for the connection to complete. If the timeout is
309: * <=0, then wait indefinitely.
310: *
311: * Returns 0 on success or -1 on failure.
312: */
313: int
314: timeout_connect(int sockfd, const struct sockaddr *serv_addr,
315: socklen_t addrlen, int *timeoutp)
316: {
317: int optval = 0;
318: socklen_t optlen = sizeof(optval);
319:
320: /* No timeout: just do a blocking connect() */
321: if (timeoutp == NULL || *timeoutp <= 0)
322: return connect(sockfd, serv_addr, addrlen);
323:
324: set_nonblock(sockfd);
1.153 djm 325: for (;;) {
326: if (connect(sockfd, serv_addr, addrlen) == 0) {
327: /* Succeeded already? */
328: unset_nonblock(sockfd);
329: return 0;
330: } else if (errno == EINTR)
331: continue;
332: else if (errno != EINPROGRESS)
333: return -1;
334: break;
335: }
1.136 djm 336:
1.143 dtucker 337: if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT) == -1)
1.136 djm 338: return -1;
339:
340: /* Completed or failed */
341: if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
342: debug("getsockopt: %s", strerror(errno));
343: return -1;
344: }
345: if (optval != 0) {
346: errno = optval;
347: return -1;
348: }
349: unset_nonblock(sockfd);
1.117 djm 350: return 0;
1.72 reyk 351: }
352:
1.1 markus 353: /* Characters considered whitespace in strsep calls. */
354: #define WHITESPACE " \t\r\n"
1.46 dtucker 355: #define QUOTE "\""
1.1 markus 356:
1.12 markus 357: /* return next token in configuration line */
1.129 djm 358: static char *
359: strdelim_internal(char **s, int split_equals)
1.1 markus 360: {
1.126 djm 361: char *old;
1.1 markus 362: int wspace = 0;
363:
364: if (*s == NULL)
365: return NULL;
366:
367: old = *s;
368:
1.129 djm 369: *s = strpbrk(*s,
370: split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
1.1 markus 371: if (*s == NULL)
372: return (old);
373:
1.46 dtucker 374: if (*s[0] == '\"') {
375: memmove(*s, *s + 1, strlen(*s)); /* move nul too */
376: /* Find matching quote */
1.126 djm 377: if ((*s = strpbrk(*s, QUOTE)) == NULL) {
378: return (NULL); /* no matching quote */
379: } else {
380: *s[0] = '\0';
381: *s += strspn(*s + 1, WHITESPACE) + 1;
382: return (old);
1.46 dtucker 383: }
384: }
385:
1.1 markus 386: /* Allow only one '=' to be skipped */
1.129 djm 387: if (split_equals && *s[0] == '=')
1.1 markus 388: wspace = 1;
389: *s[0] = '\0';
390:
1.46 dtucker 391: /* Skip any extra whitespace after first token */
1.1 markus 392: *s += strspn(*s + 1, WHITESPACE) + 1;
1.129 djm 393: if (split_equals && *s[0] == '=' && !wspace)
1.1 markus 394: *s += strspn(*s + 1, WHITESPACE) + 1;
395:
396: return (old);
1.129 djm 397: }
398:
399: /*
400: * Return next token in configuration line; splts on whitespace or a
401: * single '=' character.
402: */
403: char *
404: strdelim(char **s)
405: {
406: return strdelim_internal(s, 1);
407: }
408:
409: /*
410: * Return next token in configuration line; splts on whitespace only.
411: */
412: char *
413: strdelimw(char **s)
414: {
415: return strdelim_internal(s, 0);
1.2 markus 416: }
417:
418: struct passwd *
419: pwcopy(struct passwd *pw)
420: {
1.49 djm 421: struct passwd *copy = xcalloc(1, sizeof(*copy));
1.4 deraadt 422:
1.2 markus 423: copy->pw_name = xstrdup(pw->pw_name);
424: copy->pw_passwd = xstrdup(pw->pw_passwd);
1.4 deraadt 425: copy->pw_gecos = xstrdup(pw->pw_gecos);
1.2 markus 426: copy->pw_uid = pw->pw_uid;
427: copy->pw_gid = pw->pw_gid;
1.11 markus 428: copy->pw_expire = pw->pw_expire;
429: copy->pw_change = pw->pw_change;
1.2 markus 430: copy->pw_class = xstrdup(pw->pw_class);
431: copy->pw_dir = xstrdup(pw->pw_dir);
432: copy->pw_shell = xstrdup(pw->pw_shell);
433: return copy;
1.5 stevesk 434: }
435:
1.12 markus 436: /*
437: * Convert ASCII string to TCP/IP port number.
1.70 djm 438: * Port must be >=0 and <=65535.
439: * Return -1 if invalid.
1.12 markus 440: */
441: int
442: a2port(const char *s)
1.5 stevesk 443: {
1.133 naddy 444: struct servent *se;
1.70 djm 445: long long port;
446: const char *errstr;
1.5 stevesk 447:
1.70 djm 448: port = strtonum(s, 0, 65535, &errstr);
1.133 naddy 449: if (errstr == NULL)
450: return (int)port;
451: if ((se = getservbyname(s, "tcp")) != NULL)
452: return ntohs(se->s_port);
453: return -1;
1.9 stevesk 454: }
455:
1.36 reyk 456: int
457: a2tun(const char *s, int *remote)
458: {
459: const char *errstr = NULL;
460: char *sp, *ep;
461: int tun;
462:
463: if (remote != NULL) {
1.37 reyk 464: *remote = SSH_TUNID_ANY;
1.36 reyk 465: sp = xstrdup(s);
466: if ((ep = strchr(sp, ':')) == NULL) {
1.89 djm 467: free(sp);
1.36 reyk 468: return (a2tun(s, NULL));
469: }
470: ep[0] = '\0'; ep++;
471: *remote = a2tun(ep, NULL);
472: tun = a2tun(sp, NULL);
1.89 djm 473: free(sp);
1.37 reyk 474: return (*remote == SSH_TUNID_ERR ? *remote : tun);
1.36 reyk 475: }
476:
477: if (strcasecmp(s, "any") == 0)
1.37 reyk 478: return (SSH_TUNID_ANY);
1.36 reyk 479:
1.37 reyk 480: tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
481: if (errstr != NULL)
482: return (SSH_TUNID_ERR);
1.36 reyk 483:
484: return (tun);
485: }
486:
1.9 stevesk 487: #define SECONDS 1
488: #define MINUTES (SECONDS * 60)
489: #define HOURS (MINUTES * 60)
490: #define DAYS (HOURS * 24)
491: #define WEEKS (DAYS * 7)
492:
1.12 markus 493: /*
494: * Convert a time string into seconds; format is
495: * a sequence of:
496: * time[qualifier]
497: *
498: * Valid time qualifiers are:
499: * <none> seconds
500: * s|S seconds
501: * m|M minutes
502: * h|H hours
503: * d|D days
504: * w|W weeks
505: *
506: * Examples:
507: * 90m 90 minutes
508: * 1h30m 90 minutes
509: * 2d 2 days
510: * 1w 1 week
511: *
512: * Return -1 if time string is invalid.
513: */
1.158 dtucker 514: int
1.12 markus 515: convtime(const char *s)
1.9 stevesk 516: {
1.149 dtucker 517: long total, secs, multiplier;
1.9 stevesk 518: const char *p;
519: char *endp;
520:
521: errno = 0;
522: total = 0;
523: p = s;
524:
525: if (p == NULL || *p == '\0')
526: return -1;
527:
528: while (*p) {
529: secs = strtol(p, &endp, 10);
530: if (p == endp ||
1.158 dtucker 531: (errno == ERANGE && (secs == INT_MIN || secs == INT_MAX)) ||
1.9 stevesk 532: secs < 0)
533: return -1;
534:
1.149 dtucker 535: multiplier = 1;
1.9 stevesk 536: switch (*endp++) {
537: case '\0':
538: endp--;
1.48 deraadt 539: break;
1.9 stevesk 540: case 's':
541: case 'S':
542: break;
543: case 'm':
544: case 'M':
1.108 dtucker 545: multiplier = MINUTES;
1.9 stevesk 546: break;
547: case 'h':
548: case 'H':
1.108 dtucker 549: multiplier = HOURS;
1.9 stevesk 550: break;
551: case 'd':
552: case 'D':
1.108 dtucker 553: multiplier = DAYS;
1.9 stevesk 554: break;
555: case 'w':
556: case 'W':
1.108 dtucker 557: multiplier = WEEKS;
1.9 stevesk 558: break;
559: default:
560: return -1;
561: }
1.160 dtucker 562: if (secs > INT_MAX / multiplier)
1.108 dtucker 563: return -1;
564: secs *= multiplier;
1.160 dtucker 565: if (total > INT_MAX - secs)
1.108 dtucker 566: return -1;
1.9 stevesk 567: total += secs;
568: if (total < 0)
569: return -1;
570: p = endp;
571: }
572:
573: return total;
1.148 djm 574: }
575:
576: #define TF_BUFS 8
577: #define TF_LEN 9
578:
579: const char *
580: fmt_timeframe(time_t t)
581: {
582: char *buf;
583: static char tfbuf[TF_BUFS][TF_LEN]; /* ring buffer */
584: static int idx = 0;
585: unsigned int sec, min, hrs, day;
586: unsigned long long week;
587:
588: buf = tfbuf[idx++];
589: if (idx == TF_BUFS)
590: idx = 0;
591:
592: week = t;
593:
594: sec = week % 60;
595: week /= 60;
596: min = week % 60;
597: week /= 60;
598: hrs = week % 24;
599: week /= 24;
600: day = week % 7;
601: week /= 7;
602:
603: if (week > 0)
604: snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
605: else if (day > 0)
606: snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
607: else
608: snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
609:
610: return (buf);
1.56 dtucker 611: }
612:
613: /*
614: * Returns a standardized host+port identifier string.
615: * Caller must free returned string.
616: */
617: char *
618: put_host_port(const char *host, u_short port)
619: {
620: char *hoststr;
621:
622: if (port == 0 || port == SSH_DEFAULT_PORT)
623: return(xstrdup(host));
1.138 deraadt 624: if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
1.56 dtucker 625: fatal("put_host_port: asprintf: %s", strerror(errno));
626: debug3("put_host_port: %s", hoststr);
627: return hoststr;
1.28 djm 628: }
629:
630: /*
631: * Search for next delimiter between hostnames/addresses and ports.
632: * Argument may be modified (for termination).
633: * Returns *cp if parsing succeeds.
1.114 millert 634: * *cp is set to the start of the next field, if one was found.
635: * The delimiter char, if present, is stored in delim.
1.28 djm 636: * If this is the last field, *cp is set to NULL.
637: */
1.137 dtucker 638: char *
1.114 millert 639: hpdelim2(char **cp, char *delim)
1.28 djm 640: {
641: char *s, *old;
642:
643: if (cp == NULL || *cp == NULL)
644: return NULL;
645:
646: old = s = *cp;
647: if (*s == '[') {
648: if ((s = strchr(s, ']')) == NULL)
649: return NULL;
650: else
651: s++;
652: } else if ((s = strpbrk(s, ":/")) == NULL)
653: s = *cp + strlen(*cp); /* skip to end (see first case below) */
654:
655: switch (*s) {
656: case '\0':
657: *cp = NULL; /* no more fields*/
658: break;
1.29 deraadt 659:
1.28 djm 660: case ':':
661: case '/':
1.114 millert 662: if (delim != NULL)
663: *delim = *s;
1.28 djm 664: *s = '\0'; /* terminate */
665: *cp = s + 1;
666: break;
1.29 deraadt 667:
1.28 djm 668: default:
669: return NULL;
670: }
671:
672: return old;
1.6 mouring 673: }
674:
675: char *
1.114 millert 676: hpdelim(char **cp)
677: {
678: return hpdelim2(cp, NULL);
679: }
680:
681: char *
1.6 mouring 682: cleanhostname(char *host)
683: {
684: if (*host == '[' && host[strlen(host) - 1] == ']') {
685: host[strlen(host) - 1] = '\0';
686: return (host + 1);
687: } else
688: return host;
689: }
690:
691: char *
692: colon(char *cp)
693: {
694: int flag = 0;
695:
696: if (*cp == ':') /* Leading colon is part of file name. */
1.76 djm 697: return NULL;
1.6 mouring 698: if (*cp == '[')
699: flag = 1;
700:
701: for (; *cp; ++cp) {
702: if (*cp == '@' && *(cp+1) == '[')
703: flag = 1;
704: if (*cp == ']' && *(cp+1) == ':' && flag)
705: return (cp+1);
706: if (*cp == ':' && !flag)
707: return (cp);
708: if (*cp == '/')
1.76 djm 709: return NULL;
1.6 mouring 710: }
1.76 djm 711: return NULL;
1.105 djm 712: }
713:
714: /*
1.114 millert 715: * Parse a [user@]host:[path] string.
716: * Caller must free returned user, host and path.
717: * Any of the pointer return arguments may be NULL (useful for syntax checking).
718: * If user was not specified then *userp will be set to NULL.
719: * If host was not specified then *hostp will be set to NULL.
720: * If path was not specified then *pathp will be set to ".".
721: * Returns 0 on success, -1 on failure.
722: */
723: int
724: parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
725: {
726: char *user = NULL, *host = NULL, *path = NULL;
727: char *sdup, *tmp;
728: int ret = -1;
729:
730: if (userp != NULL)
731: *userp = NULL;
732: if (hostp != NULL)
733: *hostp = NULL;
734: if (pathp != NULL)
735: *pathp = NULL;
736:
1.116 millert 737: sdup = xstrdup(s);
1.114 millert 738:
739: /* Check for remote syntax: [user@]host:[path] */
740: if ((tmp = colon(sdup)) == NULL)
741: goto out;
742:
743: /* Extract optional path */
744: *tmp++ = '\0';
745: if (*tmp == '\0')
746: tmp = ".";
747: path = xstrdup(tmp);
748:
749: /* Extract optional user and mandatory host */
750: tmp = strrchr(sdup, '@');
751: if (tmp != NULL) {
752: *tmp++ = '\0';
753: host = xstrdup(cleanhostname(tmp));
754: if (*sdup != '\0')
755: user = xstrdup(sdup);
756: } else {
757: host = xstrdup(cleanhostname(sdup));
758: user = NULL;
759: }
760:
761: /* Success */
762: if (userp != NULL) {
763: *userp = user;
764: user = NULL;
765: }
766: if (hostp != NULL) {
767: *hostp = host;
768: host = NULL;
1.116 millert 769: }
1.114 millert 770: if (pathp != NULL) {
771: *pathp = path;
772: path = NULL;
1.116 millert 773: }
1.114 millert 774: ret = 0;
775: out:
776: free(sdup);
777: free(user);
778: free(host);
779: free(path);
780: return ret;
781: }
782:
783: /*
1.105 djm 784: * Parse a [user@]host[:port] string.
785: * Caller must free returned user and host.
786: * Any of the pointer return arguments may be NULL (useful for syntax checking).
787: * If user was not specified then *userp will be set to NULL.
788: * If port was not specified then *portp will be -1.
789: * Returns 0 on success, -1 on failure.
790: */
791: int
792: parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
793: {
794: char *sdup, *cp, *tmp;
795: char *user = NULL, *host = NULL;
796: int port = -1, ret = -1;
797:
798: if (userp != NULL)
799: *userp = NULL;
800: if (hostp != NULL)
801: *hostp = NULL;
802: if (portp != NULL)
803: *portp = -1;
804:
805: if ((sdup = tmp = strdup(s)) == NULL)
806: return -1;
807: /* Extract optional username */
1.114 millert 808: if ((cp = strrchr(tmp, '@')) != NULL) {
1.105 djm 809: *cp = '\0';
810: if (*tmp == '\0')
811: goto out;
812: if ((user = strdup(tmp)) == NULL)
813: goto out;
814: tmp = cp + 1;
815: }
816: /* Extract mandatory hostname */
817: if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
818: goto out;
819: host = xstrdup(cleanhostname(cp));
820: /* Convert and verify optional port */
821: if (tmp != NULL && *tmp != '\0') {
822: if ((port = a2port(tmp)) <= 0)
823: goto out;
824: }
825: /* Success */
826: if (userp != NULL) {
827: *userp = user;
828: user = NULL;
829: }
830: if (hostp != NULL) {
831: *hostp = host;
832: host = NULL;
833: }
834: if (portp != NULL)
835: *portp = port;
836: ret = 0;
837: out:
838: free(sdup);
839: free(user);
840: free(host);
841: return ret;
1.7 mouring 842: }
843:
1.114 millert 844: /*
845: * Converts a two-byte hex string to decimal.
846: * Returns the decimal value or -1 for invalid input.
847: */
848: static int
849: hexchar(const char *s)
850: {
851: unsigned char result[2];
852: int i;
853:
854: for (i = 0; i < 2; i++) {
855: if (s[i] >= '0' && s[i] <= '9')
856: result[i] = (unsigned char)(s[i] - '0');
857: else if (s[i] >= 'a' && s[i] <= 'f')
858: result[i] = (unsigned char)(s[i] - 'a') + 10;
859: else if (s[i] >= 'A' && s[i] <= 'F')
860: result[i] = (unsigned char)(s[i] - 'A') + 10;
861: else
862: return -1;
863: }
864: return (result[0] << 4) | result[1];
865: }
866:
867: /*
868: * Decode an url-encoded string.
869: * Returns a newly allocated string on success or NULL on failure.
870: */
871: static char *
872: urldecode(const char *src)
873: {
874: char *ret, *dst;
875: int ch;
876:
877: ret = xmalloc(strlen(src) + 1);
878: for (dst = ret; *src != '\0'; src++) {
879: switch (*src) {
880: case '+':
881: *dst++ = ' ';
882: break;
883: case '%':
884: if (!isxdigit((unsigned char)src[1]) ||
885: !isxdigit((unsigned char)src[2]) ||
886: (ch = hexchar(src + 1)) == -1) {
887: free(ret);
888: return NULL;
889: }
890: *dst++ = ch;
891: src += 2;
892: break;
893: default:
894: *dst++ = *src;
895: break;
896: }
897: }
898: *dst = '\0';
899:
900: return ret;
901: }
902:
903: /*
904: * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
905: * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
906: * Either user or path may be url-encoded (but not host or port).
907: * Caller must free returned user, host and path.
908: * Any of the pointer return arguments may be NULL (useful for syntax checking)
909: * but the scheme must always be specified.
910: * If user was not specified then *userp will be set to NULL.
911: * If port was not specified then *portp will be -1.
912: * If path was not specified then *pathp will be set to NULL.
913: * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
914: */
915: int
916: parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
917: int *portp, char **pathp)
918: {
919: char *uridup, *cp, *tmp, ch;
920: char *user = NULL, *host = NULL, *path = NULL;
921: int port = -1, ret = -1;
922: size_t len;
923:
924: len = strlen(scheme);
925: if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
926: return 1;
927: uri += len + 3;
928:
929: if (userp != NULL)
930: *userp = NULL;
931: if (hostp != NULL)
932: *hostp = NULL;
933: if (portp != NULL)
934: *portp = -1;
935: if (pathp != NULL)
936: *pathp = NULL;
937:
938: uridup = tmp = xstrdup(uri);
939:
940: /* Extract optional ssh-info (username + connection params) */
941: if ((cp = strchr(tmp, '@')) != NULL) {
942: char *delim;
943:
944: *cp = '\0';
945: /* Extract username and connection params */
946: if ((delim = strchr(tmp, ';')) != NULL) {
947: /* Just ignore connection params for now */
948: *delim = '\0';
949: }
950: if (*tmp == '\0') {
951: /* Empty username */
952: goto out;
953: }
954: if ((user = urldecode(tmp)) == NULL)
955: goto out;
956: tmp = cp + 1;
957: }
958:
959: /* Extract mandatory hostname */
960: if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
961: goto out;
962: host = xstrdup(cleanhostname(cp));
963: if (!valid_domain(host, 0, NULL))
964: goto out;
965:
966: if (tmp != NULL && *tmp != '\0') {
967: if (ch == ':') {
968: /* Convert and verify port. */
969: if ((cp = strchr(tmp, '/')) != NULL)
970: *cp = '\0';
971: if ((port = a2port(tmp)) <= 0)
972: goto out;
973: tmp = cp ? cp + 1 : NULL;
974: }
975: if (tmp != NULL && *tmp != '\0') {
976: /* Extract optional path */
977: if ((path = urldecode(tmp)) == NULL)
978: goto out;
979: }
980: }
981:
982: /* Success */
983: if (userp != NULL) {
984: *userp = user;
985: user = NULL;
986: }
987: if (hostp != NULL) {
988: *hostp = host;
989: host = NULL;
990: }
991: if (portp != NULL)
992: *portp = port;
993: if (pathp != NULL) {
994: *pathp = path;
995: path = NULL;
996: }
997: ret = 0;
998: out:
999: free(uridup);
1000: free(user);
1001: free(host);
1002: free(path);
1003: return ret;
1004: }
1005:
1.12 markus 1006: /* function to assist building execv() arguments */
1.7 mouring 1007: void
1008: addargs(arglist *args, char *fmt, ...)
1009: {
1010: va_list ap;
1.42 djm 1011: char *cp;
1.25 avsm 1012: u_int nalloc;
1.42 djm 1013: int r;
1.7 mouring 1014:
1015: va_start(ap, fmt);
1.42 djm 1016: r = vasprintf(&cp, fmt, ap);
1.7 mouring 1017: va_end(ap);
1.42 djm 1018: if (r == -1)
1019: fatal("addargs: argument too long");
1.7 mouring 1020:
1.22 markus 1021: nalloc = args->nalloc;
1.7 mouring 1022: if (args->list == NULL) {
1.22 markus 1023: nalloc = 32;
1.7 mouring 1024: args->num = 0;
1.22 markus 1025: } else if (args->num+2 >= nalloc)
1026: nalloc *= 2;
1.7 mouring 1027:
1.110 deraadt 1028: args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
1.22 markus 1029: args->nalloc = nalloc;
1.42 djm 1030: args->list[args->num++] = cp;
1.7 mouring 1031: args->list[args->num] = NULL;
1.42 djm 1032: }
1033:
1034: void
1035: replacearg(arglist *args, u_int which, char *fmt, ...)
1036: {
1037: va_list ap;
1038: char *cp;
1039: int r;
1040:
1041: va_start(ap, fmt);
1042: r = vasprintf(&cp, fmt, ap);
1043: va_end(ap);
1044: if (r == -1)
1045: fatal("replacearg: argument too long");
1046:
1047: if (which >= args->num)
1048: fatal("replacearg: tried to replace invalid arg %d >= %d",
1049: which, args->num);
1.89 djm 1050: free(args->list[which]);
1.42 djm 1051: args->list[which] = cp;
1052: }
1053:
1054: void
1055: freeargs(arglist *args)
1056: {
1057: u_int i;
1058:
1059: if (args->list != NULL) {
1060: for (i = 0; i < args->num; i++)
1.89 djm 1061: free(args->list[i]);
1062: free(args->list);
1.42 djm 1063: args->nalloc = args->num = 0;
1064: args->list = NULL;
1065: }
1.30 djm 1066: }
1067:
1068: /*
1069: * Expands tildes in the file name. Returns data allocated by xmalloc.
1070: * Warning: this calls getpw*.
1071: */
1072: char *
1073: tilde_expand_filename(const char *filename, uid_t uid)
1074: {
1.87 tedu 1075: const char *path, *sep;
1076: char user[128], *ret;
1.30 djm 1077: struct passwd *pw;
1.32 djm 1078: u_int len, slash;
1.30 djm 1079:
1080: if (*filename != '~')
1081: return (xstrdup(filename));
1082: filename++;
1083:
1084: path = strchr(filename, '/');
1085: if (path != NULL && path > filename) { /* ~user/path */
1.32 djm 1086: slash = path - filename;
1087: if (slash > sizeof(user) - 1)
1.30 djm 1088: fatal("tilde_expand_filename: ~username too long");
1.32 djm 1089: memcpy(user, filename, slash);
1090: user[slash] = '\0';
1.30 djm 1091: if ((pw = getpwnam(user)) == NULL)
1092: fatal("tilde_expand_filename: No such user %s", user);
1093: } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
1.69 dtucker 1094: fatal("tilde_expand_filename: No such uid %ld", (long)uid);
1.30 djm 1095:
1096: /* Make sure directory has a trailing '/' */
1097: len = strlen(pw->pw_dir);
1.88 tedu 1098: if (len == 0 || pw->pw_dir[len - 1] != '/')
1.87 tedu 1099: sep = "/";
1100: else
1101: sep = "";
1.30 djm 1102:
1103: /* Skip leading '/' from specified path */
1104: if (path != NULL)
1105: filename = path + 1;
1.87 tedu 1106:
1.96 deraadt 1107: if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
1.30 djm 1108: fatal("tilde_expand_filename: Path too long");
1109:
1.87 tedu 1110: return (ret);
1.31 djm 1111: }
1112:
1113: /*
1.150 dtucker 1114: * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1115: * substitutions. A number of escapes may be specified as
1116: * (char *escape_chars, char *replacement) pairs. The list must be terminated
1117: * by a NULL escape_char. Returns replaced string in memory allocated by
1118: * xmalloc which the caller must free.
1.31 djm 1119: */
1.150 dtucker 1120: static char *
1121: vdollar_percent_expand(int *parseerror, int dollar, int percent,
1122: const char *string, va_list ap)
1.31 djm 1123: {
1124: #define EXPAND_MAX_KEYS 16
1.150 dtucker 1125: u_int num_keys = 0, i;
1.31 djm 1126: struct {
1127: const char *key;
1128: const char *repl;
1129: } keys[EXPAND_MAX_KEYS];
1.140 djm 1130: struct sshbuf *buf;
1.150 dtucker 1131: int r, missingvar = 0;
1132: char *ret = NULL, *var, *varend, *val;
1133: size_t len;
1.140 djm 1134:
1135: if ((buf = sshbuf_new()) == NULL)
1.155 djm 1136: fatal_f("sshbuf_new failed");
1.150 dtucker 1137: if (parseerror == NULL)
1.155 djm 1138: fatal_f("null parseerror arg");
1.150 dtucker 1139: *parseerror = 1;
1140:
1141: /* Gather keys if we're doing percent expansion. */
1142: if (percent) {
1143: for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1144: keys[num_keys].key = va_arg(ap, char *);
1145: if (keys[num_keys].key == NULL)
1146: break;
1147: keys[num_keys].repl = va_arg(ap, char *);
1.155 djm 1148: if (keys[num_keys].repl == NULL) {
1149: fatal_f("NULL replacement for token %s",
1150: keys[num_keys].key);
1151: }
1.150 dtucker 1152: }
1153: if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1.155 djm 1154: fatal_f("too many keys");
1.150 dtucker 1155: if (num_keys == 0)
1.155 djm 1156: fatal_f("percent expansion without token list");
1.31 djm 1157: }
1158:
1159: /* Expand string */
1160: for (i = 0; *string != '\0'; string++) {
1.150 dtucker 1161: /* Optionally process ${ENVIRONMENT} expansions. */
1162: if (dollar && string[0] == '$' && string[1] == '{') {
1163: string += 2; /* skip over '${' */
1164: if ((varend = strchr(string, '}')) == NULL) {
1.155 djm 1165: error_f("environment variable '%s' missing "
1.164 djm 1166: "closing '}'", string);
1.150 dtucker 1167: goto out;
1168: }
1169: len = varend - string;
1170: if (len == 0) {
1.155 djm 1171: error_f("zero-length environment variable");
1.150 dtucker 1172: goto out;
1173: }
1174: var = xmalloc(len + 1);
1175: (void)strlcpy(var, string, len + 1);
1176: if ((val = getenv(var)) == NULL) {
1.155 djm 1177: error_f("env var ${%s} has no value", var);
1.150 dtucker 1178: missingvar = 1;
1179: } else {
1.155 djm 1180: debug3_f("expand ${%s} -> '%s'", var, val);
1.150 dtucker 1181: if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1.155 djm 1182: fatal_fr(r, "sshbuf_put ${}");
1.150 dtucker 1183: }
1184: free(var);
1185: string += len;
1186: continue;
1187: }
1188:
1189: /*
1190: * Process percent expansions if we have a list of TOKENs.
1191: * If we're not doing percent expansion everything just gets
1192: * appended here.
1193: */
1194: if (*string != '%' || !percent) {
1.31 djm 1195: append:
1.155 djm 1196: if ((r = sshbuf_put_u8(buf, *string)) != 0)
1197: fatal_fr(r, "sshbuf_put_u8 %%");
1.31 djm 1198: continue;
1199: }
1200: string++;
1.73 djm 1201: /* %% case */
1.31 djm 1202: if (*string == '%')
1203: goto append;
1.150 dtucker 1204: if (*string == '\0') {
1.155 djm 1205: error_f("invalid format");
1.150 dtucker 1206: goto out;
1207: }
1.140 djm 1208: for (i = 0; i < num_keys; i++) {
1209: if (strchr(keys[i].key, *string) != NULL) {
1210: if ((r = sshbuf_put(buf, keys[i].repl,
1.155 djm 1211: strlen(keys[i].repl))) != 0)
1212: fatal_fr(r, "sshbuf_put %%-repl");
1.31 djm 1213: break;
1214: }
1215: }
1.150 dtucker 1216: if (i >= num_keys) {
1.155 djm 1217: error_f("unknown key %%%c", *string);
1.150 dtucker 1218: goto out;
1219: }
1.31 djm 1220: }
1.150 dtucker 1221: if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1.155 djm 1222: fatal_f("sshbuf_dup_string failed");
1.150 dtucker 1223: *parseerror = 0;
1224: out:
1.140 djm 1225: sshbuf_free(buf);
1.150 dtucker 1226: return *parseerror ? NULL : ret;
1227: #undef EXPAND_MAX_KEYS
1228: }
1229:
1.152 dtucker 1230: /*
1231: * Expand only environment variables.
1232: * Note that although this function is variadic like the other similar
1233: * functions, any such arguments will be unused.
1234: */
1235:
1.150 dtucker 1236: char *
1.152 dtucker 1237: dollar_expand(int *parseerr, const char *string, ...)
1.150 dtucker 1238: {
1239: char *ret;
1240: int err;
1.152 dtucker 1241: va_list ap;
1.150 dtucker 1242:
1.152 dtucker 1243: va_start(ap, string);
1244: ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1245: va_end(ap);
1.150 dtucker 1246: if (parseerr != NULL)
1247: *parseerr = err;
1248: return ret;
1249: }
1250:
1251: /*
1252: * Returns expanded string or NULL if a specified environment variable is
1253: * not defined, or calls fatal if the string is invalid.
1254: */
1255: char *
1256: percent_expand(const char *string, ...)
1257: {
1258: char *ret;
1259: int err;
1260: va_list ap;
1261:
1262: va_start(ap, string);
1263: ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1264: va_end(ap);
1265: if (err)
1.155 djm 1266: fatal_f("failed");
1.150 dtucker 1267: return ret;
1268: }
1269:
1270: /*
1271: * Returns expanded string or NULL if a specified environment variable is
1272: * not defined, or calls fatal if the string is invalid.
1273: */
1274: char *
1275: percent_dollar_expand(const char *string, ...)
1276: {
1277: char *ret;
1278: int err;
1279: va_list ap;
1280:
1281: va_start(ap, string);
1282: ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1283: va_end(ap);
1284: if (err)
1.155 djm 1285: fatal_f("failed");
1.140 djm 1286: return ret;
1.36 reyk 1287: }
1288:
1289: int
1.115 djm 1290: tun_open(int tun, int mode, char **ifname)
1.36 reyk 1291: {
1.37 reyk 1292: struct ifreq ifr;
1.36 reyk 1293: char name[100];
1.37 reyk 1294: int fd = -1, sock;
1.99 sthen 1295: const char *tunbase = "tun";
1296:
1.115 djm 1297: if (ifname != NULL)
1298: *ifname = NULL;
1299:
1.99 sthen 1300: if (mode == SSH_TUNMODE_ETHERNET)
1301: tunbase = "tap";
1.36 reyk 1302:
1.37 reyk 1303: /* Open the tunnel device */
1304: if (tun <= SSH_TUNID_MAX) {
1.99 sthen 1305: snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1.37 reyk 1306: fd = open(name, O_RDWR);
1307: } else if (tun == SSH_TUNID_ANY) {
1308: for (tun = 100; tun >= 0; tun--) {
1.99 sthen 1309: snprintf(name, sizeof(name), "/dev/%s%d",
1310: tunbase, tun);
1.37 reyk 1311: if ((fd = open(name, O_RDWR)) >= 0)
1312: break;
1.36 reyk 1313: }
1314: } else {
1.155 djm 1315: debug_f("invalid tunnel %u", tun);
1.98 djm 1316: return -1;
1.37 reyk 1317: }
1318:
1.139 deraadt 1319: if (fd == -1) {
1.155 djm 1320: debug_f("%s open: %s", name, strerror(errno));
1.98 djm 1321: return -1;
1.36 reyk 1322: }
1.37 reyk 1323:
1.155 djm 1324: debug_f("%s mode %d fd %d", name, mode, fd);
1.37 reyk 1325:
1.99 sthen 1326: /* Bring interface up if it is not already */
1327: snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1328: if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1.37 reyk 1329: goto failed;
1330:
1.98 djm 1331: if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1.155 djm 1332: debug_f("get interface %s flags: %s", ifr.ifr_name,
1333: strerror(errno));
1.37 reyk 1334: goto failed;
1.98 djm 1335: }
1.40 reyk 1336:
1.98 djm 1337: if (!(ifr.ifr_flags & IFF_UP)) {
1338: ifr.ifr_flags |= IFF_UP;
1339: if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1.155 djm 1340: debug_f("activate interface %s: %s", ifr.ifr_name,
1341: strerror(errno));
1.98 djm 1342: goto failed;
1343: }
1344: }
1.115 djm 1345:
1346: if (ifname != NULL)
1347: *ifname = xstrdup(ifr.ifr_name);
1.37 reyk 1348:
1349: close(sock);
1.98 djm 1350: return fd;
1.37 reyk 1351:
1352: failed:
1353: if (fd >= 0)
1354: close(fd);
1355: if (sock >= 0)
1356: close(sock);
1.98 djm 1357: return -1;
1.35 djm 1358: }
1359:
1360: void
1361: sanitise_stdfd(void)
1362: {
1.41 djm 1363: int nullfd, dupfd;
1.35 djm 1364:
1.41 djm 1365: if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1.71 tobias 1366: fprintf(stderr, "Couldn't open /dev/null: %s\n",
1367: strerror(errno));
1.35 djm 1368: exit(1);
1369: }
1.103 krw 1370: while (++dupfd <= STDERR_FILENO) {
1371: /* Only populate closed fds. */
1372: if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1373: if (dup2(nullfd, dupfd) == -1) {
1374: fprintf(stderr, "dup2: %s\n", strerror(errno));
1375: exit(1);
1376: }
1.35 djm 1377: }
1378: }
1.103 krw 1379: if (nullfd > STDERR_FILENO)
1.35 djm 1380: close(nullfd);
1.1 markus 1381: }
1.33 djm 1382:
1383: char *
1.52 djm 1384: tohex(const void *vp, size_t l)
1.33 djm 1385: {
1.52 djm 1386: const u_char *p = (const u_char *)vp;
1.33 djm 1387: char b[3], *r;
1.52 djm 1388: size_t i, hl;
1389:
1390: if (l > 65536)
1391: return xstrdup("tohex: length > 65536");
1.33 djm 1392:
1393: hl = l * 2 + 1;
1.49 djm 1394: r = xcalloc(1, hl);
1.33 djm 1395: for (i = 0; i < l; i++) {
1.52 djm 1396: snprintf(b, sizeof(b), "%02x", p[i]);
1.33 djm 1397: strlcat(r, b, hl);
1398: }
1399: return (r);
1400: }
1.145 djm 1401:
1402: /*
1403: * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1404: * then the separator 'sep' will be prepended before the formatted arguments.
1405: * Extended strings are heap allocated.
1406: */
1407: void
1408: xextendf(char **sp, const char *sep, const char *fmt, ...)
1409: {
1410: va_list ap;
1411: char *tmp1, *tmp2;
1412:
1413: va_start(ap, fmt);
1414: xvasprintf(&tmp1, fmt, ap);
1415: va_end(ap);
1416:
1417: if (*sp == NULL || **sp == '\0') {
1418: free(*sp);
1419: *sp = tmp1;
1420: return;
1421: }
1422: xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1423: free(tmp1);
1424: free(*sp);
1425: *sp = tmp2;
1426: }
1427:
1.33 djm 1428:
1.52 djm 1429: u_int64_t
1430: get_u64(const void *vp)
1431: {
1432: const u_char *p = (const u_char *)vp;
1433: u_int64_t v;
1434:
1435: v = (u_int64_t)p[0] << 56;
1436: v |= (u_int64_t)p[1] << 48;
1437: v |= (u_int64_t)p[2] << 40;
1438: v |= (u_int64_t)p[3] << 32;
1439: v |= (u_int64_t)p[4] << 24;
1440: v |= (u_int64_t)p[5] << 16;
1441: v |= (u_int64_t)p[6] << 8;
1442: v |= (u_int64_t)p[7];
1443:
1444: return (v);
1445: }
1446:
1447: u_int32_t
1448: get_u32(const void *vp)
1449: {
1450: const u_char *p = (const u_char *)vp;
1451: u_int32_t v;
1452:
1453: v = (u_int32_t)p[0] << 24;
1454: v |= (u_int32_t)p[1] << 16;
1455: v |= (u_int32_t)p[2] << 8;
1456: v |= (u_int32_t)p[3];
1457:
1458: return (v);
1459: }
1460:
1.93 djm 1461: u_int32_t
1462: get_u32_le(const void *vp)
1463: {
1464: const u_char *p = (const u_char *)vp;
1465: u_int32_t v;
1466:
1467: v = (u_int32_t)p[0];
1468: v |= (u_int32_t)p[1] << 8;
1469: v |= (u_int32_t)p[2] << 16;
1470: v |= (u_int32_t)p[3] << 24;
1471:
1472: return (v);
1473: }
1474:
1.52 djm 1475: u_int16_t
1476: get_u16(const void *vp)
1477: {
1478: const u_char *p = (const u_char *)vp;
1479: u_int16_t v;
1480:
1481: v = (u_int16_t)p[0] << 8;
1482: v |= (u_int16_t)p[1];
1483:
1484: return (v);
1485: }
1486:
1487: void
1488: put_u64(void *vp, u_int64_t v)
1489: {
1490: u_char *p = (u_char *)vp;
1491:
1492: p[0] = (u_char)(v >> 56) & 0xff;
1493: p[1] = (u_char)(v >> 48) & 0xff;
1494: p[2] = (u_char)(v >> 40) & 0xff;
1495: p[3] = (u_char)(v >> 32) & 0xff;
1496: p[4] = (u_char)(v >> 24) & 0xff;
1497: p[5] = (u_char)(v >> 16) & 0xff;
1498: p[6] = (u_char)(v >> 8) & 0xff;
1499: p[7] = (u_char)v & 0xff;
1500: }
1501:
1502: void
1503: put_u32(void *vp, u_int32_t v)
1504: {
1505: u_char *p = (u_char *)vp;
1506:
1507: p[0] = (u_char)(v >> 24) & 0xff;
1508: p[1] = (u_char)(v >> 16) & 0xff;
1509: p[2] = (u_char)(v >> 8) & 0xff;
1510: p[3] = (u_char)v & 0xff;
1511: }
1512:
1.93 djm 1513: void
1514: put_u32_le(void *vp, u_int32_t v)
1515: {
1516: u_char *p = (u_char *)vp;
1517:
1518: p[0] = (u_char)v & 0xff;
1519: p[1] = (u_char)(v >> 8) & 0xff;
1520: p[2] = (u_char)(v >> 16) & 0xff;
1521: p[3] = (u_char)(v >> 24) & 0xff;
1522: }
1.52 djm 1523:
1524: void
1525: put_u16(void *vp, u_int16_t v)
1526: {
1527: u_char *p = (u_char *)vp;
1528:
1529: p[0] = (u_char)(v >> 8) & 0xff;
1530: p[1] = (u_char)v & 0xff;
1531: }
1.68 dtucker 1532:
1533: void
1534: ms_subtract_diff(struct timeval *start, int *ms)
1535: {
1536: struct timeval diff, finish;
1537:
1.119 dtucker 1538: monotime_tv(&finish);
1539: timersub(&finish, start, &diff);
1.68 dtucker 1540: *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1541: }
1542:
1543: void
1544: ms_to_timeval(struct timeval *tv, int ms)
1545: {
1546: if (ms < 0)
1547: ms = 0;
1548: tv->tv_sec = ms / 1000;
1549: tv->tv_usec = (ms % 1000) * 1000;
1.90 dtucker 1550: }
1551:
1.119 dtucker 1552: void
1553: monotime_ts(struct timespec *ts)
1554: {
1555: if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
1556: fatal("clock_gettime: %s", strerror(errno));
1557: }
1558:
1559: void
1560: monotime_tv(struct timeval *tv)
1561: {
1562: struct timespec ts;
1563:
1564: monotime_ts(&ts);
1565: tv->tv_sec = ts.tv_sec;
1566: tv->tv_usec = ts.tv_nsec / 1000;
1567: }
1568:
1.90 dtucker 1569: time_t
1570: monotime(void)
1571: {
1572: struct timespec ts;
1573:
1.119 dtucker 1574: monotime_ts(&ts);
1.90 dtucker 1575: return (ts.tv_sec);
1.102 dtucker 1576: }
1577:
1578: double
1579: monotime_double(void)
1580: {
1581: struct timespec ts;
1582:
1.119 dtucker 1583: monotime_ts(&ts);
1584: return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
1.81 djm 1585: }
1586:
1587: void
1588: bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1589: {
1590: bw->buflen = buflen;
1591: bw->rate = kbps;
1.135 dtucker 1592: bw->thresh = buflen;
1.81 djm 1593: bw->lamt = 0;
1594: timerclear(&bw->bwstart);
1595: timerclear(&bw->bwend);
1.135 dtucker 1596: }
1.81 djm 1597:
1598: /* Callback from read/write loop to insert bandwidth-limiting delays */
1599: void
1600: bandwidth_limit(struct bwlimit *bw, size_t read_len)
1601: {
1602: u_int64_t waitlen;
1603: struct timespec ts, rm;
1604:
1.135 dtucker 1605: bw->lamt += read_len;
1.81 djm 1606: if (!timerisset(&bw->bwstart)) {
1.119 dtucker 1607: monotime_tv(&bw->bwstart);
1.81 djm 1608: return;
1609: }
1610: if (bw->lamt < bw->thresh)
1611: return;
1612:
1.119 dtucker 1613: monotime_tv(&bw->bwend);
1.81 djm 1614: timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1615: if (!timerisset(&bw->bwend))
1616: return;
1617:
1618: bw->lamt *= 8;
1619: waitlen = (double)1000000L * bw->lamt / bw->rate;
1620:
1621: bw->bwstart.tv_sec = waitlen / 1000000L;
1622: bw->bwstart.tv_usec = waitlen % 1000000L;
1623:
1624: if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1625: timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1626:
1627: /* Adjust the wait time */
1628: if (bw->bwend.tv_sec) {
1629: bw->thresh /= 2;
1630: if (bw->thresh < bw->buflen / 4)
1631: bw->thresh = bw->buflen / 4;
1632: } else if (bw->bwend.tv_usec < 10000) {
1633: bw->thresh *= 2;
1634: if (bw->thresh > bw->buflen * 8)
1635: bw->thresh = bw->buflen * 8;
1636: }
1637:
1638: TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1639: while (nanosleep(&ts, &rm) == -1) {
1640: if (errno != EINTR)
1641: break;
1642: ts = rm;
1643: }
1644: }
1645:
1646: bw->lamt = 0;
1.119 dtucker 1647: monotime_tv(&bw->bwstart);
1.84 djm 1648: }
1649:
1650: /* Make a template filename for mk[sd]temp() */
1651: void
1652: mktemp_proto(char *s, size_t len)
1653: {
1654: const char *tmpdir;
1655: int r;
1656:
1657: if ((tmpdir = getenv("TMPDIR")) != NULL) {
1658: r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1659: if (r > 0 && (size_t)r < len)
1660: return;
1661: }
1662: r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1663: if (r < 0 || (size_t)r >= len)
1.155 djm 1664: fatal_f("template string too short");
1.68 dtucker 1665: }
1.83 djm 1666:
1667: static const struct {
1668: const char *name;
1669: int value;
1670: } ipqos[] = {
1.111 djm 1671: { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1.83 djm 1672: { "af11", IPTOS_DSCP_AF11 },
1673: { "af12", IPTOS_DSCP_AF12 },
1674: { "af13", IPTOS_DSCP_AF13 },
1.86 djm 1675: { "af21", IPTOS_DSCP_AF21 },
1.83 djm 1676: { "af22", IPTOS_DSCP_AF22 },
1677: { "af23", IPTOS_DSCP_AF23 },
1678: { "af31", IPTOS_DSCP_AF31 },
1679: { "af32", IPTOS_DSCP_AF32 },
1680: { "af33", IPTOS_DSCP_AF33 },
1681: { "af41", IPTOS_DSCP_AF41 },
1682: { "af42", IPTOS_DSCP_AF42 },
1683: { "af43", IPTOS_DSCP_AF43 },
1684: { "cs0", IPTOS_DSCP_CS0 },
1685: { "cs1", IPTOS_DSCP_CS1 },
1686: { "cs2", IPTOS_DSCP_CS2 },
1687: { "cs3", IPTOS_DSCP_CS3 },
1688: { "cs4", IPTOS_DSCP_CS4 },
1689: { "cs5", IPTOS_DSCP_CS5 },
1690: { "cs6", IPTOS_DSCP_CS6 },
1691: { "cs7", IPTOS_DSCP_CS7 },
1692: { "ef", IPTOS_DSCP_EF },
1.146 djm 1693: { "le", IPTOS_DSCP_LE },
1.83 djm 1694: { "lowdelay", IPTOS_LOWDELAY },
1695: { "throughput", IPTOS_THROUGHPUT },
1696: { "reliability", IPTOS_RELIABILITY },
1697: { NULL, -1 }
1698: };
1699:
1700: int
1701: parse_ipqos(const char *cp)
1702: {
1703: u_int i;
1704: char *ep;
1705: long val;
1706:
1707: if (cp == NULL)
1708: return -1;
1709: for (i = 0; ipqos[i].name != NULL; i++) {
1710: if (strcasecmp(cp, ipqos[i].name) == 0)
1711: return ipqos[i].value;
1712: }
1713: /* Try parsing as an integer */
1714: val = strtol(cp, &ep, 0);
1715: if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1716: return -1;
1717: return val;
1718: }
1719:
1.85 stevesk 1720: const char *
1721: iptos2str(int iptos)
1722: {
1723: int i;
1724: static char iptos_str[sizeof "0xff"];
1725:
1726: for (i = 0; ipqos[i].name != NULL; i++) {
1727: if (ipqos[i].value == iptos)
1728: return ipqos[i].name;
1729: }
1730: snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1731: return iptos_str;
1.92 djm 1732: }
1733:
1734: void
1735: lowercase(char *s)
1736: {
1737: for (; *s; s++)
1738: *s = tolower((u_char)*s);
1.94 millert 1739: }
1740:
1741: int
1742: unix_listener(const char *path, int backlog, int unlink_first)
1743: {
1744: struct sockaddr_un sunaddr;
1745: int saved_errno, sock;
1746:
1747: memset(&sunaddr, 0, sizeof(sunaddr));
1748: sunaddr.sun_family = AF_UNIX;
1.121 djm 1749: if (strlcpy(sunaddr.sun_path, path,
1750: sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1.155 djm 1751: error_f("path \"%s\" too long for Unix domain socket", path);
1.94 millert 1752: errno = ENAMETOOLONG;
1753: return -1;
1754: }
1755:
1756: sock = socket(PF_UNIX, SOCK_STREAM, 0);
1.139 deraadt 1757: if (sock == -1) {
1.94 millert 1758: saved_errno = errno;
1.155 djm 1759: error_f("socket: %.100s", strerror(errno));
1.94 millert 1760: errno = saved_errno;
1761: return -1;
1762: }
1763: if (unlink_first == 1) {
1764: if (unlink(path) != 0 && errno != ENOENT)
1765: error("unlink(%s): %.100s", path, strerror(errno));
1766: }
1.139 deraadt 1767: if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1.94 millert 1768: saved_errno = errno;
1.155 djm 1769: error_f("cannot bind to path %s: %s", path, strerror(errno));
1.122 djm 1770: close(sock);
1.94 millert 1771: errno = saved_errno;
1772: return -1;
1773: }
1.139 deraadt 1774: if (listen(sock, backlog) == -1) {
1.94 millert 1775: saved_errno = errno;
1.155 djm 1776: error_f("cannot listen on path %s: %s", path, strerror(errno));
1.94 millert 1777: close(sock);
1778: unlink(path);
1779: errno = saved_errno;
1780: return -1;
1781: }
1782: return sock;
1.85 stevesk 1783: }
1.104 djm 1784:
1785: /*
1786: * Compares two strings that maybe be NULL. Returns non-zero if strings
1787: * are both NULL or are identical, returns zero otherwise.
1788: */
1789: static int
1790: strcmp_maybe_null(const char *a, const char *b)
1791: {
1792: if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1793: return 0;
1794: if (a != NULL && strcmp(a, b) != 0)
1795: return 0;
1796: return 1;
1797: }
1798:
1799: /*
1800: * Compare two forwards, returning non-zero if they are identical or
1801: * zero otherwise.
1802: */
1803: int
1804: forward_equals(const struct Forward *a, const struct Forward *b)
1805: {
1806: if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1807: return 0;
1808: if (a->listen_port != b->listen_port)
1809: return 0;
1810: if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1811: return 0;
1812: if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1813: return 0;
1814: if (a->connect_port != b->connect_port)
1815: return 0;
1816: if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1817: return 0;
1818: /* allocated_port and handle are not checked */
1.107 dtucker 1819: return 1;
1820: }
1821:
1822: /* returns 1 if process is already daemonized, 0 otherwise */
1823: int
1824: daemonized(void)
1825: {
1826: int fd;
1827:
1828: if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1829: close(fd);
1830: return 0; /* have controlling terminal */
1831: }
1832: if (getppid() != 1)
1833: return 0; /* parent is not init */
1834: if (getsid(0) != getpid())
1835: return 0; /* not session leader */
1836: debug3("already daemonized");
1.106 dtucker 1837: return 1;
1838: }
1.112 djm 1839:
1840: /*
1841: * Splits 's' into an argument vector. Handles quoted string and basic
1842: * escape characters (\\, \", \'). Caller must free the argument vector
1843: * and its members.
1844: */
1845: int
1.166 djm 1846: argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
1.112 djm 1847: {
1848: int r = SSH_ERR_INTERNAL_ERROR;
1849: int argc = 0, quote, i, j;
1850: char *arg, **argv = xcalloc(1, sizeof(*argv));
1851:
1852: *argvp = NULL;
1853: *argcp = 0;
1854:
1855: for (i = 0; s[i] != '\0'; i++) {
1856: /* Skip leading whitespace */
1857: if (s[i] == ' ' || s[i] == '\t')
1858: continue;
1.166 djm 1859: if (terminate_on_comment && s[i] == '#')
1860: break;
1.112 djm 1861: /* Start of a token */
1862: quote = 0;
1863:
1864: argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1865: arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1866: argv[argc] = NULL;
1867:
1868: /* Copy the token in, removing escapes */
1869: for (j = 0; s[i] != '\0'; i++) {
1870: if (s[i] == '\\') {
1871: if (s[i + 1] == '\'' ||
1872: s[i + 1] == '\"' ||
1.166 djm 1873: s[i + 1] == '\\' ||
1874: (quote == 0 && s[i + 1] == ' ')) {
1.112 djm 1875: i++; /* Skip '\' */
1876: arg[j++] = s[i];
1877: } else {
1878: /* Unrecognised escape */
1879: arg[j++] = s[i];
1880: }
1881: } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1882: break; /* done */
1.163 djm 1883: else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
1884: quote = s[i]; /* quote start */
1.112 djm 1885: else if (quote != 0 && s[i] == quote)
1.163 djm 1886: quote = 0; /* quote end */
1.112 djm 1887: else
1888: arg[j++] = s[i];
1889: }
1890: if (s[i] == '\0') {
1891: if (quote != 0) {
1892: /* Ran out of string looking for close quote */
1893: r = SSH_ERR_INVALID_FORMAT;
1894: goto out;
1895: }
1896: break;
1897: }
1898: }
1899: /* Success */
1900: *argcp = argc;
1901: *argvp = argv;
1902: argc = 0;
1903: argv = NULL;
1904: r = 0;
1905: out:
1906: if (argc != 0 && argv != NULL) {
1907: for (i = 0; i < argc; i++)
1908: free(argv[i]);
1909: free(argv);
1910: }
1911: return r;
1912: }
1913:
1914: /*
1915: * Reassemble an argument vector into a string, quoting and escaping as
1916: * necessary. Caller must free returned string.
1917: */
1918: char *
1919: argv_assemble(int argc, char **argv)
1920: {
1921: int i, j, ws, r;
1922: char c, *ret;
1923: struct sshbuf *buf, *arg;
1924:
1925: if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1.155 djm 1926: fatal_f("sshbuf_new failed");
1.112 djm 1927:
1928: for (i = 0; i < argc; i++) {
1929: ws = 0;
1930: sshbuf_reset(arg);
1931: for (j = 0; argv[i][j] != '\0'; j++) {
1932: r = 0;
1933: c = argv[i][j];
1934: switch (c) {
1935: case ' ':
1936: case '\t':
1937: ws = 1;
1938: r = sshbuf_put_u8(arg, c);
1939: break;
1940: case '\\':
1941: case '\'':
1942: case '"':
1943: if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1944: break;
1945: /* FALLTHROUGH */
1946: default:
1947: r = sshbuf_put_u8(arg, c);
1948: break;
1949: }
1950: if (r != 0)
1.155 djm 1951: fatal_fr(r, "sshbuf_put_u8");
1.112 djm 1952: }
1953: if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1954: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1955: (r = sshbuf_putb(buf, arg)) != 0 ||
1956: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1.155 djm 1957: fatal_fr(r, "assemble");
1.112 djm 1958: }
1959: if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1.155 djm 1960: fatal_f("malloc failed");
1.112 djm 1961: memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1962: ret[sshbuf_len(buf)] = '\0';
1963: sshbuf_free(buf);
1964: sshbuf_free(arg);
1965: return ret;
1.166 djm 1966: }
1967:
1968: char *
1969: argv_next(int *argcp, char ***argvp)
1970: {
1971: char *ret = (*argvp)[0];
1972:
1973: if (*argcp > 0 && ret != NULL) {
1974: (*argcp)--;
1975: (*argvp)++;
1976: }
1977: return ret;
1978: }
1979:
1980: void
1981: argv_consume(int *argcp)
1982: {
1983: *argcp = 0;
1984: }
1985:
1986: void
1987: argv_free(char **av, int ac)
1988: {
1989: int i;
1990:
1991: if (av == NULL)
1992: return;
1993: for (i = 0; i < ac; i++)
1994: free(av[i]);
1995: free(av);
1.112 djm 1996: }
1997:
1998: /* Returns 0 if pid exited cleanly, non-zero otherwise */
1999: int
1.113 djm 2000: exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1.112 djm 2001: {
2002: int status;
2003:
2004: while (waitpid(pid, &status, 0) == -1) {
2005: if (errno != EINTR) {
1.155 djm 2006: error("%s waitpid: %s", tag, strerror(errno));
1.112 djm 2007: return -1;
2008: }
2009: }
2010: if (WIFSIGNALED(status)) {
2011: error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2012: return -1;
2013: } else if (WEXITSTATUS(status) != 0) {
1.113 djm 2014: do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2015: "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1.112 djm 2016: return -1;
2017: }
2018: return 0;
2019: }
2020:
2021: /*
2022: * Check a given path for security. This is defined as all components
2023: * of the path to the file must be owned by either the owner of
2024: * of the file or root and no directories must be group or world writable.
2025: *
2026: * XXX Should any specific check be done for sym links ?
2027: *
2028: * Takes a file name, its stat information (preferably from fstat() to
2029: * avoid races), the uid of the expected owner, their home directory and an
2030: * error buffer plus max size as arguments.
2031: *
2032: * Returns 0 on success and -1 on failure
2033: */
2034: int
2035: safe_path(const char *name, struct stat *stp, const char *pw_dir,
2036: uid_t uid, char *err, size_t errlen)
2037: {
2038: char buf[PATH_MAX], homedir[PATH_MAX];
2039: char *cp;
2040: int comparehome = 0;
2041: struct stat st;
2042:
2043: if (realpath(name, buf) == NULL) {
2044: snprintf(err, errlen, "realpath %s failed: %s", name,
2045: strerror(errno));
2046: return -1;
2047: }
2048: if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2049: comparehome = 1;
2050:
2051: if (!S_ISREG(stp->st_mode)) {
2052: snprintf(err, errlen, "%s is not a regular file", buf);
2053: return -1;
2054: }
2055: if ((stp->st_uid != 0 && stp->st_uid != uid) ||
2056: (stp->st_mode & 022) != 0) {
2057: snprintf(err, errlen, "bad ownership or modes for file %s",
2058: buf);
2059: return -1;
2060: }
2061:
2062: /* for each component of the canonical path, walking upwards */
2063: for (;;) {
2064: if ((cp = dirname(buf)) == NULL) {
2065: snprintf(err, errlen, "dirname() failed");
2066: return -1;
2067: }
2068: strlcpy(buf, cp, sizeof(buf));
2069:
1.139 deraadt 2070: if (stat(buf, &st) == -1 ||
1.112 djm 2071: (st.st_uid != 0 && st.st_uid != uid) ||
2072: (st.st_mode & 022) != 0) {
2073: snprintf(err, errlen,
2074: "bad ownership or modes for directory %s", buf);
2075: return -1;
2076: }
2077:
2078: /* If are past the homedir then we can stop */
2079: if (comparehome && strcmp(homedir, buf) == 0)
2080: break;
2081:
2082: /*
2083: * dirname should always complete with a "/" path,
2084: * but we can be paranoid and check for "." too
2085: */
2086: if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2087: break;
2088: }
2089: return 0;
2090: }
2091:
2092: /*
2093: * Version of safe_path() that accepts an open file descriptor to
2094: * avoid races.
2095: *
2096: * Returns 0 on success and -1 on failure
2097: */
2098: int
2099: safe_path_fd(int fd, const char *file, struct passwd *pw,
2100: char *err, size_t errlen)
2101: {
2102: struct stat st;
2103:
2104: /* check the open file to avoid races */
1.139 deraadt 2105: if (fstat(fd, &st) == -1) {
1.112 djm 2106: snprintf(err, errlen, "cannot stat file %s: %s",
2107: file, strerror(errno));
2108: return -1;
2109: }
2110: return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2111: }
2112:
2113: /*
2114: * Sets the value of the given variable in the environment. If the variable
2115: * already exists, its value is overridden.
2116: */
2117: void
2118: child_set_env(char ***envp, u_int *envsizep, const char *name,
2119: const char *value)
2120: {
2121: char **env;
2122: u_int envsize;
2123: u_int i, namelen;
2124:
2125: if (strchr(name, '=') != NULL) {
2126: error("Invalid environment variable \"%.100s\"", name);
2127: return;
2128: }
2129:
2130: /*
2131: * Find the slot where the value should be stored. If the variable
2132: * already exists, we reuse the slot; otherwise we append a new slot
2133: * at the end of the array, expanding if necessary.
2134: */
2135: env = *envp;
2136: namelen = strlen(name);
2137: for (i = 0; env[i]; i++)
2138: if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2139: break;
2140: if (env[i]) {
2141: /* Reuse the slot. */
2142: free(env[i]);
2143: } else {
2144: /* New variable. Expand if necessary. */
2145: envsize = *envsizep;
2146: if (i >= envsize - 1) {
2147: if (envsize >= 1000)
2148: fatal("child_set_env: too many env vars");
2149: envsize += 50;
2150: env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2151: *envsizep = envsize;
2152: }
2153: /* Need to set the NULL pointer at end of array beyond the new slot. */
2154: env[i + 1] = NULL;
2155: }
2156:
2157: /* Allocate space and format the variable in the appropriate slot. */
1.125 djm 2158: /* XXX xasprintf */
1.112 djm 2159: env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2160: snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2161: }
2162:
1.114 millert 2163: /*
2164: * Check and optionally lowercase a domain name, also removes trailing '.'
2165: * Returns 1 on success and 0 on failure, storing an error message in errstr.
2166: */
2167: int
2168: valid_domain(char *name, int makelower, const char **errstr)
2169: {
2170: size_t i, l = strlen(name);
2171: u_char c, last = '\0';
2172: static char errbuf[256];
2173:
2174: if (l == 0) {
2175: strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2176: goto bad;
2177: }
2178: if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2179: snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2180: "starts with invalid character", name);
2181: goto bad;
2182: }
2183: for (i = 0; i < l; i++) {
2184: c = tolower((u_char)name[i]);
2185: if (makelower)
2186: name[i] = (char)c;
2187: if (last == '.' && c == '.') {
2188: snprintf(errbuf, sizeof(errbuf), "domain name "
2189: "\"%.100s\" contains consecutive separators", name);
2190: goto bad;
2191: }
2192: if (c != '.' && c != '-' && !isalnum(c) &&
2193: c != '_') /* technically invalid, but common */ {
2194: snprintf(errbuf, sizeof(errbuf), "domain name "
2195: "\"%.100s\" contains invalid characters", name);
2196: goto bad;
2197: }
2198: last = c;
2199: }
2200: if (name[l - 1] == '.')
2201: name[l - 1] = '\0';
2202: if (errstr != NULL)
2203: *errstr = NULL;
2204: return 1;
2205: bad:
2206: if (errstr != NULL)
2207: *errstr = errbuf;
2208: return 0;
1.132 djm 2209: }
2210:
2211: /*
2212: * Verify that a environment variable name (not including initial '$') is
2213: * valid; consisting of one or more alphanumeric or underscore characters only.
2214: * Returns 1 on valid, 0 otherwise.
2215: */
2216: int
2217: valid_env_name(const char *name)
2218: {
2219: const char *cp;
2220:
2221: if (name[0] == '\0')
2222: return 0;
2223: for (cp = name; *cp != '\0'; cp++) {
2224: if (!isalnum((u_char)*cp) && *cp != '_')
2225: return 0;
2226: }
2227: return 1;
1.120 dtucker 2228: }
2229:
2230: const char *
2231: atoi_err(const char *nptr, int *val)
2232: {
2233: const char *errstr = NULL;
2234: long long num;
2235:
2236: if (nptr == NULL || *nptr == '\0')
2237: return "missing";
2238: num = strtonum(nptr, 0, INT_MAX, &errstr);
2239: if (errstr == NULL)
2240: *val = (int)num;
2241: return errstr;
1.127 djm 2242: }
2243:
2244: int
2245: parse_absolute_time(const char *s, uint64_t *tp)
2246: {
2247: struct tm tm;
2248: time_t tt;
2249: char buf[32], *fmt;
2250:
2251: *tp = 0;
2252:
2253: /*
2254: * POSIX strptime says "The application shall ensure that there
2255: * is white-space or other non-alphanumeric characters between
2256: * any two conversion specifications" so arrange things this way.
2257: */
2258: switch (strlen(s)) {
2259: case 8: /* YYYYMMDD */
2260: fmt = "%Y-%m-%d";
2261: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2262: break;
2263: case 12: /* YYYYMMDDHHMM */
2264: fmt = "%Y-%m-%dT%H:%M";
2265: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2266: s, s + 4, s + 6, s + 8, s + 10);
2267: break;
2268: case 14: /* YYYYMMDDHHMMSS */
2269: fmt = "%Y-%m-%dT%H:%M:%S";
2270: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2271: s, s + 4, s + 6, s + 8, s + 10, s + 12);
2272: break;
2273: default:
2274: return SSH_ERR_INVALID_FORMAT;
2275: }
2276:
2277: memset(&tm, 0, sizeof(tm));
2278: if (strptime(buf, fmt, &tm) == NULL)
2279: return SSH_ERR_INVALID_FORMAT;
2280: if ((tt = mktime(&tm)) < 0)
2281: return SSH_ERR_INVALID_FORMAT;
2282: /* success */
2283: *tp = (uint64_t)tt;
2284: return 0;
2285: }
2286:
1.167 ! dtucker 2287: /* On OpenBSD time_t is int64_t which is long long. */
! 2288: #ifndef SSH_TIME_T_MAX
! 2289: # define SSH_TIME_T_MAX LLONG_MAX
! 2290: #endif
! 2291:
1.127 djm 2292: void
2293: format_absolute_time(uint64_t t, char *buf, size_t len)
2294: {
1.167 ! dtucker 2295: time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
1.127 djm 2296: struct tm tm;
2297:
2298: localtime_r(&tt, &tm);
2299: strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
1.134 djm 2300: }
2301:
2302: /* check if path is absolute */
2303: int
2304: path_absolute(const char *path)
2305: {
2306: return (*path == '/') ? 1 : 0;
1.141 djm 2307: }
2308:
2309: void
2310: skip_space(char **cpp)
2311: {
2312: char *cp;
2313:
2314: for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2315: ;
2316: *cpp = cp;
1.114 millert 2317: }
1.142 djm 2318:
2319: /* authorized_key-style options parsing helpers */
2320:
2321: /*
2322: * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2323: * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2324: * if negated option matches.
2325: * If the option or negated option matches, then *optsp is updated to
2326: * point to the first character after the option.
2327: */
2328: int
2329: opt_flag(const char *opt, int allow_negate, const char **optsp)
2330: {
2331: size_t opt_len = strlen(opt);
2332: const char *opts = *optsp;
2333: int negate = 0;
2334:
2335: if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2336: opts += 3;
2337: negate = 1;
2338: }
2339: if (strncasecmp(opts, opt, opt_len) == 0) {
2340: *optsp = opts + opt_len;
2341: return negate ? 0 : 1;
2342: }
2343: return -1;
2344: }
2345:
2346: char *
2347: opt_dequote(const char **sp, const char **errstrp)
2348: {
2349: const char *s = *sp;
2350: char *ret;
2351: size_t i;
2352:
2353: *errstrp = NULL;
2354: if (*s != '"') {
2355: *errstrp = "missing start quote";
2356: return NULL;
2357: }
2358: s++;
2359: if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2360: *errstrp = "memory allocation failed";
2361: return NULL;
2362: }
2363: for (i = 0; *s != '\0' && *s != '"';) {
2364: if (s[0] == '\\' && s[1] == '"')
2365: s++;
2366: ret[i++] = *s++;
2367: }
2368: if (*s == '\0') {
2369: *errstrp = "missing end quote";
2370: free(ret);
2371: return NULL;
2372: }
2373: ret[i] = '\0';
2374: s++;
2375: *sp = s;
2376: return ret;
2377: }
2378:
2379: int
2380: opt_match(const char **opts, const char *term)
2381: {
2382: if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2383: (*opts)[strlen(term)] == '=') {
2384: *opts += strlen(term) + 1;
2385: return 1;
2386: }
2387: return 0;
1.161 markus 2388: }
2389:
2390: void
2391: opt_array_append2(const char *file, const int line, const char *directive,
2392: char ***array, int **iarray, u_int *lp, const char *s, int i)
2393: {
2394:
2395: if (*lp >= INT_MAX)
2396: fatal("%s line %d: Too many %s entries", file, line, directive);
2397:
2398: if (iarray != NULL) {
2399: *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2400: sizeof(**iarray));
2401: (*iarray)[*lp] = i;
2402: }
2403:
2404: *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2405: (*array)[*lp] = xstrdup(s);
2406: (*lp)++;
2407: }
2408:
2409: void
2410: opt_array_append(const char *file, const int line, const char *directive,
2411: char ***array, u_int *lp, const char *s)
2412: {
2413: opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
1.142 djm 2414: }
2415:
1.144 dtucker 2416: sshsig_t
2417: ssh_signal(int signum, sshsig_t handler)
2418: {
2419: struct sigaction sa, osa;
2420:
2421: /* mask all other signals while in handler */
1.147 dtucker 2422: memset(&sa, 0, sizeof(sa));
1.144 dtucker 2423: sa.sa_handler = handler;
2424: sigfillset(&sa.sa_mask);
2425: if (signum != SIGALRM)
2426: sa.sa_flags = SA_RESTART;
2427: if (sigaction(signum, &sa, &osa) == -1) {
2428: debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2429: return SIG_ERR;
2430: }
2431: return osa.sa_handler;
1.154 djm 2432: }
2433:
2434: int
2435: stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2436: {
2437: int devnull, ret = 0;
2438:
2439: if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1.155 djm 2440: error_f("open %s: %s", _PATH_DEVNULL,
1.154 djm 2441: strerror(errno));
2442: return -1;
2443: }
2444: if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2445: (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2446: (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
1.155 djm 2447: error_f("dup2: %s", strerror(errno));
1.154 djm 2448: ret = -1;
2449: }
2450: if (devnull > STDERR_FILENO)
2451: close(devnull);
2452: return ret;
1.157 djm 2453: }
2454:
2455: /*
2456: * Runs command in a subprocess with a minimal environment.
2457: * Returns pid on success, 0 on failure.
2458: * The child stdout and stderr maybe captured, left attached or sent to
2459: * /dev/null depending on the contents of flags.
2460: * "tag" is prepended to log messages.
2461: * NB. "command" is only used for logging; the actual command executed is
2462: * av[0].
2463: */
2464: pid_t
2465: subprocess(const char *tag, const char *command,
2466: int ac, char **av, FILE **child, u_int flags,
2467: struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2468: {
2469: FILE *f = NULL;
2470: struct stat st;
2471: int fd, devnull, p[2], i;
2472: pid_t pid;
2473: char *cp, errmsg[512];
2474: u_int nenv = 0;
2475: char **env = NULL;
2476:
2477: /* If dropping privs, then must specify user and restore function */
2478: if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2479: error("%s: inconsistent arguments", tag); /* XXX fatal? */
2480: return 0;
2481: }
2482: if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2483: error("%s: no user for current uid", tag);
2484: return 0;
2485: }
2486: if (child != NULL)
2487: *child = NULL;
2488:
2489: debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2490: tag, command, pw->pw_name, flags);
2491:
2492: /* Check consistency */
2493: if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2494: (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2495: error_f("inconsistent flags");
2496: return 0;
2497: }
2498: if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2499: error_f("inconsistent flags/output");
2500: return 0;
2501: }
2502:
2503: /*
2504: * If executing an explicit binary, then verify the it exists
2505: * and appears safe-ish to execute
2506: */
2507: if (!path_absolute(av[0])) {
2508: error("%s path is not absolute", tag);
2509: return 0;
2510: }
2511: if (drop_privs != NULL)
2512: drop_privs(pw);
2513: if (stat(av[0], &st) == -1) {
2514: error("Could not stat %s \"%s\": %s", tag,
2515: av[0], strerror(errno));
2516: goto restore_return;
2517: }
2518: if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2519: safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2520: error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2521: goto restore_return;
2522: }
2523: /* Prepare to keep the child's stdout if requested */
2524: if (pipe(p) == -1) {
2525: error("%s: pipe: %s", tag, strerror(errno));
2526: restore_return:
2527: if (restore_privs != NULL)
2528: restore_privs();
2529: return 0;
2530: }
2531: if (restore_privs != NULL)
2532: restore_privs();
2533:
2534: switch ((pid = fork())) {
2535: case -1: /* error */
2536: error("%s: fork: %s", tag, strerror(errno));
2537: close(p[0]);
2538: close(p[1]);
2539: return 0;
2540: case 0: /* child */
2541: /* Prepare a minimal environment for the child. */
2542: if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2543: nenv = 5;
2544: env = xcalloc(sizeof(*env), nenv);
2545: child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2546: child_set_env(&env, &nenv, "USER", pw->pw_name);
2547: child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2548: child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2549: if ((cp = getenv("LANG")) != NULL)
2550: child_set_env(&env, &nenv, "LANG", cp);
2551: }
2552:
1.162 dtucker 2553: for (i = 1; i < NSIG; i++)
1.157 djm 2554: ssh_signal(i, SIG_DFL);
2555:
2556: if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2557: error("%s: open %s: %s", tag, _PATH_DEVNULL,
2558: strerror(errno));
2559: _exit(1);
2560: }
2561: if (dup2(devnull, STDIN_FILENO) == -1) {
2562: error("%s: dup2: %s", tag, strerror(errno));
2563: _exit(1);
2564: }
2565:
2566: /* Set up stdout as requested; leave stderr in place for now. */
2567: fd = -1;
2568: if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2569: fd = p[1];
2570: else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2571: fd = devnull;
2572: if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2573: error("%s: dup2: %s", tag, strerror(errno));
2574: _exit(1);
2575: }
2576: closefrom(STDERR_FILENO + 1);
2577:
2578: if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2579: error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2580: strerror(errno));
2581: _exit(1);
2582: }
2583: if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2584: error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2585: strerror(errno));
2586: _exit(1);
2587: }
2588: /* stdin is pointed to /dev/null at this point */
2589: if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2590: dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2591: error("%s: dup2: %s", tag, strerror(errno));
2592: _exit(1);
2593: }
2594: if (env != NULL)
2595: execve(av[0], av, env);
2596: else
2597: execv(av[0], av);
2598: error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2599: command, strerror(errno));
2600: _exit(127);
2601: default: /* parent */
2602: break;
2603: }
2604:
2605: close(p[1]);
2606: if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2607: close(p[0]);
2608: else if ((f = fdopen(p[0], "r")) == NULL) {
2609: error("%s: fdopen: %s", tag, strerror(errno));
2610: close(p[0]);
2611: /* Don't leave zombie child */
2612: kill(pid, SIGTERM);
2613: while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2614: ;
2615: return 0;
2616: }
2617: /* Success */
2618: debug3_f("%s pid %ld", tag, (long)pid);
2619: if (child != NULL)
2620: *child = f;
2621: return pid;
1.165 djm 2622: }
2623:
2624: const char *
2625: lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2626: {
2627: size_t i, envlen;
2628:
2629: envlen = strlen(env);
2630: for (i = 0; i < nenvs; i++) {
2631: if (strncmp(envs[i], env, envlen) == 0 &&
2632: envs[i][envlen] == '=') {
2633: return envs[i] + envlen + 1;
2634: }
2635: }
2636: return NULL;
1.144 dtucker 2637: }