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