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