Annotation of src/usr.bin/ssh/misc.c, Revision 1.192
1.192 ! deraadt 1: /* $OpenBSD: misc.c,v 1.191 2024/04/02 09:52:14 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: {
1793: u_int i;
1794: char *ep;
1795: long val;
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 */
1804: val = strtol(cp, &ep, 0);
1805: if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
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;
1910: }
1911:
1912: /* returns 1 if process is already daemonized, 0 otherwise */
1913: int
1914: daemonized(void)
1915: {
1916: int fd;
1917:
1918: if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1919: close(fd);
1920: return 0; /* have controlling terminal */
1921: }
1922: if (getppid() != 1)
1923: return 0; /* parent is not init */
1924: if (getsid(0) != getpid())
1925: return 0; /* not session leader */
1926: debug3("already daemonized");
1.106 dtucker 1927: return 1;
1928: }
1.112 djm 1929:
1930: /*
1931: * Splits 's' into an argument vector. Handles quoted string and basic
1932: * escape characters (\\, \", \'). Caller must free the argument vector
1933: * and its members.
1934: */
1935: int
1.166 djm 1936: argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
1.112 djm 1937: {
1938: int r = SSH_ERR_INTERNAL_ERROR;
1939: int argc = 0, quote, i, j;
1940: char *arg, **argv = xcalloc(1, sizeof(*argv));
1941:
1942: *argvp = NULL;
1943: *argcp = 0;
1944:
1945: for (i = 0; s[i] != '\0'; i++) {
1946: /* Skip leading whitespace */
1947: if (s[i] == ' ' || s[i] == '\t')
1948: continue;
1.166 djm 1949: if (terminate_on_comment && s[i] == '#')
1950: break;
1.112 djm 1951: /* Start of a token */
1952: quote = 0;
1953:
1954: argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1955: arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1956: argv[argc] = NULL;
1957:
1958: /* Copy the token in, removing escapes */
1959: for (j = 0; s[i] != '\0'; i++) {
1960: if (s[i] == '\\') {
1961: if (s[i + 1] == '\'' ||
1962: s[i + 1] == '\"' ||
1.166 djm 1963: s[i + 1] == '\\' ||
1964: (quote == 0 && s[i + 1] == ' ')) {
1.112 djm 1965: i++; /* Skip '\' */
1966: arg[j++] = s[i];
1967: } else {
1968: /* Unrecognised escape */
1969: arg[j++] = s[i];
1970: }
1971: } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1972: break; /* done */
1.163 djm 1973: else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
1974: quote = s[i]; /* quote start */
1.112 djm 1975: else if (quote != 0 && s[i] == quote)
1.163 djm 1976: quote = 0; /* quote end */
1.112 djm 1977: else
1978: arg[j++] = s[i];
1979: }
1980: if (s[i] == '\0') {
1981: if (quote != 0) {
1982: /* Ran out of string looking for close quote */
1983: r = SSH_ERR_INVALID_FORMAT;
1984: goto out;
1985: }
1986: break;
1987: }
1988: }
1989: /* Success */
1990: *argcp = argc;
1991: *argvp = argv;
1992: argc = 0;
1993: argv = NULL;
1994: r = 0;
1995: out:
1996: if (argc != 0 && argv != NULL) {
1997: for (i = 0; i < argc; i++)
1998: free(argv[i]);
1999: free(argv);
2000: }
2001: return r;
2002: }
2003:
2004: /*
2005: * Reassemble an argument vector into a string, quoting and escaping as
2006: * necessary. Caller must free returned string.
2007: */
2008: char *
2009: argv_assemble(int argc, char **argv)
2010: {
2011: int i, j, ws, r;
2012: char c, *ret;
2013: struct sshbuf *buf, *arg;
2014:
2015: if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1.155 djm 2016: fatal_f("sshbuf_new failed");
1.112 djm 2017:
2018: for (i = 0; i < argc; i++) {
2019: ws = 0;
2020: sshbuf_reset(arg);
2021: for (j = 0; argv[i][j] != '\0'; j++) {
2022: r = 0;
2023: c = argv[i][j];
2024: switch (c) {
2025: case ' ':
2026: case '\t':
2027: ws = 1;
2028: r = sshbuf_put_u8(arg, c);
2029: break;
2030: case '\\':
2031: case '\'':
2032: case '"':
2033: if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2034: break;
2035: /* FALLTHROUGH */
2036: default:
2037: r = sshbuf_put_u8(arg, c);
2038: break;
2039: }
2040: if (r != 0)
1.155 djm 2041: fatal_fr(r, "sshbuf_put_u8");
1.112 djm 2042: }
2043: if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2044: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2045: (r = sshbuf_putb(buf, arg)) != 0 ||
2046: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1.155 djm 2047: fatal_fr(r, "assemble");
1.112 djm 2048: }
2049: if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1.155 djm 2050: fatal_f("malloc failed");
1.112 djm 2051: memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2052: ret[sshbuf_len(buf)] = '\0';
2053: sshbuf_free(buf);
2054: sshbuf_free(arg);
2055: return ret;
1.166 djm 2056: }
2057:
2058: char *
2059: argv_next(int *argcp, char ***argvp)
2060: {
2061: char *ret = (*argvp)[0];
2062:
2063: if (*argcp > 0 && ret != NULL) {
2064: (*argcp)--;
2065: (*argvp)++;
2066: }
2067: return ret;
2068: }
2069:
2070: void
2071: argv_consume(int *argcp)
2072: {
2073: *argcp = 0;
2074: }
2075:
2076: void
2077: argv_free(char **av, int ac)
2078: {
2079: int i;
2080:
2081: if (av == NULL)
2082: return;
2083: for (i = 0; i < ac; i++)
2084: free(av[i]);
2085: free(av);
1.112 djm 2086: }
2087:
2088: /* Returns 0 if pid exited cleanly, non-zero otherwise */
2089: int
1.113 djm 2090: exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1.112 djm 2091: {
2092: int status;
2093:
2094: while (waitpid(pid, &status, 0) == -1) {
2095: if (errno != EINTR) {
1.155 djm 2096: error("%s waitpid: %s", tag, strerror(errno));
1.112 djm 2097: return -1;
2098: }
2099: }
2100: if (WIFSIGNALED(status)) {
2101: error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2102: return -1;
2103: } else if (WEXITSTATUS(status) != 0) {
1.113 djm 2104: do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2105: "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1.112 djm 2106: return -1;
2107: }
2108: return 0;
2109: }
2110:
2111: /*
2112: * Check a given path for security. This is defined as all components
2113: * of the path to the file must be owned by either the owner of
2114: * of the file or root and no directories must be group or world writable.
2115: *
2116: * XXX Should any specific check be done for sym links ?
2117: *
2118: * Takes a file name, its stat information (preferably from fstat() to
2119: * avoid races), the uid of the expected owner, their home directory and an
2120: * error buffer plus max size as arguments.
2121: *
2122: * Returns 0 on success and -1 on failure
2123: */
2124: int
2125: safe_path(const char *name, struct stat *stp, const char *pw_dir,
2126: uid_t uid, char *err, size_t errlen)
2127: {
2128: char buf[PATH_MAX], homedir[PATH_MAX];
2129: char *cp;
2130: int comparehome = 0;
2131: struct stat st;
2132:
2133: if (realpath(name, buf) == NULL) {
2134: snprintf(err, errlen, "realpath %s failed: %s", name,
2135: strerror(errno));
2136: return -1;
2137: }
2138: if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2139: comparehome = 1;
2140:
2141: if (!S_ISREG(stp->st_mode)) {
2142: snprintf(err, errlen, "%s is not a regular file", buf);
2143: return -1;
2144: }
2145: if ((stp->st_uid != 0 && stp->st_uid != uid) ||
2146: (stp->st_mode & 022) != 0) {
2147: snprintf(err, errlen, "bad ownership or modes for file %s",
2148: buf);
2149: return -1;
2150: }
2151:
2152: /* for each component of the canonical path, walking upwards */
2153: for (;;) {
2154: if ((cp = dirname(buf)) == NULL) {
2155: snprintf(err, errlen, "dirname() failed");
2156: return -1;
2157: }
2158: strlcpy(buf, cp, sizeof(buf));
2159:
1.139 deraadt 2160: if (stat(buf, &st) == -1 ||
1.112 djm 2161: (st.st_uid != 0 && st.st_uid != uid) ||
2162: (st.st_mode & 022) != 0) {
2163: snprintf(err, errlen,
2164: "bad ownership or modes for directory %s", buf);
2165: return -1;
2166: }
2167:
2168: /* If are past the homedir then we can stop */
2169: if (comparehome && strcmp(homedir, buf) == 0)
2170: break;
2171:
2172: /*
2173: * dirname should always complete with a "/" path,
2174: * but we can be paranoid and check for "." too
2175: */
2176: if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2177: break;
2178: }
2179: return 0;
2180: }
2181:
2182: /*
2183: * Version of safe_path() that accepts an open file descriptor to
2184: * avoid races.
2185: *
2186: * Returns 0 on success and -1 on failure
2187: */
2188: int
2189: safe_path_fd(int fd, const char *file, struct passwd *pw,
2190: char *err, size_t errlen)
2191: {
2192: struct stat st;
2193:
2194: /* check the open file to avoid races */
1.139 deraadt 2195: if (fstat(fd, &st) == -1) {
1.112 djm 2196: snprintf(err, errlen, "cannot stat file %s: %s",
2197: file, strerror(errno));
2198: return -1;
2199: }
2200: return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2201: }
2202:
2203: /*
2204: * Sets the value of the given variable in the environment. If the variable
2205: * already exists, its value is overridden.
2206: */
2207: void
2208: child_set_env(char ***envp, u_int *envsizep, const char *name,
2209: const char *value)
2210: {
2211: char **env;
2212: u_int envsize;
2213: u_int i, namelen;
2214:
2215: if (strchr(name, '=') != NULL) {
2216: error("Invalid environment variable \"%.100s\"", name);
2217: return;
2218: }
2219:
2220: /*
2221: * Find the slot where the value should be stored. If the variable
2222: * already exists, we reuse the slot; otherwise we append a new slot
2223: * at the end of the array, expanding if necessary.
2224: */
2225: env = *envp;
2226: namelen = strlen(name);
2227: for (i = 0; env[i]; i++)
2228: if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2229: break;
2230: if (env[i]) {
2231: /* Reuse the slot. */
2232: free(env[i]);
2233: } else {
2234: /* New variable. Expand if necessary. */
2235: envsize = *envsizep;
2236: if (i >= envsize - 1) {
2237: if (envsize >= 1000)
2238: fatal("child_set_env: too many env vars");
2239: envsize += 50;
2240: env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2241: *envsizep = envsize;
2242: }
2243: /* Need to set the NULL pointer at end of array beyond the new slot. */
2244: env[i + 1] = NULL;
2245: }
2246:
2247: /* Allocate space and format the variable in the appropriate slot. */
1.125 djm 2248: /* XXX xasprintf */
1.112 djm 2249: env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2250: snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2251: }
2252:
1.114 millert 2253: /*
2254: * Check and optionally lowercase a domain name, also removes trailing '.'
2255: * Returns 1 on success and 0 on failure, storing an error message in errstr.
2256: */
2257: int
2258: valid_domain(char *name, int makelower, const char **errstr)
2259: {
2260: size_t i, l = strlen(name);
2261: u_char c, last = '\0';
2262: static char errbuf[256];
2263:
2264: if (l == 0) {
2265: strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2266: goto bad;
2267: }
2268: if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2269: snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2270: "starts with invalid character", name);
2271: goto bad;
2272: }
2273: for (i = 0; i < l; i++) {
2274: c = tolower((u_char)name[i]);
2275: if (makelower)
2276: name[i] = (char)c;
2277: if (last == '.' && c == '.') {
2278: snprintf(errbuf, sizeof(errbuf), "domain name "
2279: "\"%.100s\" contains consecutive separators", name);
2280: goto bad;
2281: }
2282: if (c != '.' && c != '-' && !isalnum(c) &&
2283: c != '_') /* technically invalid, but common */ {
2284: snprintf(errbuf, sizeof(errbuf), "domain name "
2285: "\"%.100s\" contains invalid characters", name);
2286: goto bad;
2287: }
2288: last = c;
2289: }
2290: if (name[l - 1] == '.')
2291: name[l - 1] = '\0';
2292: if (errstr != NULL)
2293: *errstr = NULL;
2294: return 1;
2295: bad:
2296: if (errstr != NULL)
2297: *errstr = errbuf;
2298: return 0;
1.132 djm 2299: }
2300:
2301: /*
2302: * Verify that a environment variable name (not including initial '$') is
2303: * valid; consisting of one or more alphanumeric or underscore characters only.
2304: * Returns 1 on valid, 0 otherwise.
2305: */
2306: int
2307: valid_env_name(const char *name)
2308: {
2309: const char *cp;
2310:
2311: if (name[0] == '\0')
2312: return 0;
2313: for (cp = name; *cp != '\0'; cp++) {
2314: if (!isalnum((u_char)*cp) && *cp != '_')
2315: return 0;
2316: }
2317: return 1;
1.120 dtucker 2318: }
2319:
2320: const char *
2321: atoi_err(const char *nptr, int *val)
2322: {
2323: const char *errstr = NULL;
2324:
2325: if (nptr == NULL || *nptr == '\0')
2326: return "missing";
1.192 ! deraadt 2327: *val = strtonum(nptr, 0, INT_MAX, &errstr);
1.120 dtucker 2328: return errstr;
1.127 djm 2329: }
2330:
2331: int
2332: parse_absolute_time(const char *s, uint64_t *tp)
2333: {
2334: struct tm tm;
2335: time_t tt;
2336: char buf[32], *fmt;
1.177 djm 2337: const char *cp;
2338: size_t l;
2339: int is_utc = 0;
1.127 djm 2340:
2341: *tp = 0;
2342:
1.177 djm 2343: l = strlen(s);
2344: if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2345: is_utc = 1;
2346: l--;
2347: } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2348: is_utc = 1;
2349: l -= 3;
2350: }
1.127 djm 2351: /*
2352: * POSIX strptime says "The application shall ensure that there
2353: * is white-space or other non-alphanumeric characters between
2354: * any two conversion specifications" so arrange things this way.
2355: */
1.177 djm 2356: switch (l) {
1.127 djm 2357: case 8: /* YYYYMMDD */
2358: fmt = "%Y-%m-%d";
2359: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2360: break;
2361: case 12: /* YYYYMMDDHHMM */
2362: fmt = "%Y-%m-%dT%H:%M";
2363: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2364: s, s + 4, s + 6, s + 8, s + 10);
2365: break;
2366: case 14: /* YYYYMMDDHHMMSS */
2367: fmt = "%Y-%m-%dT%H:%M:%S";
2368: snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2369: s, s + 4, s + 6, s + 8, s + 10, s + 12);
2370: break;
2371: default:
2372: return SSH_ERR_INVALID_FORMAT;
2373: }
2374:
2375: memset(&tm, 0, sizeof(tm));
1.177 djm 2376: if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
1.127 djm 2377: return SSH_ERR_INVALID_FORMAT;
1.177 djm 2378: if (is_utc) {
2379: if ((tt = timegm(&tm)) < 0)
2380: return SSH_ERR_INVALID_FORMAT;
2381: } else {
2382: if ((tt = mktime(&tm)) < 0)
2383: return SSH_ERR_INVALID_FORMAT;
2384: }
1.127 djm 2385: /* success */
2386: *tp = (uint64_t)tt;
2387: return 0;
2388: }
1.167 dtucker 2389:
1.127 djm 2390: void
2391: format_absolute_time(uint64_t t, char *buf, size_t len)
2392: {
1.167 dtucker 2393: time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
1.127 djm 2394: struct tm tm;
2395:
2396: localtime_r(&tt, &tm);
2397: strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
1.188 djm 2398: }
2399:
2400: /*
2401: * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
2402: * Returns 0 on success or non-zero on failure.
2403: * Caller must free *typep.
2404: */
2405: int
2406: parse_pattern_interval(const char *s, char **typep, int *secsp)
2407: {
2408: char *cp, *sdup;
2409: int secs;
2410:
2411: if (typep != NULL)
2412: *typep = NULL;
2413: if (secsp != NULL)
2414: *secsp = 0;
2415: if (s == NULL)
2416: return -1;
2417: sdup = xstrdup(s);
2418:
2419: if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
2420: free(sdup);
2421: return -1;
2422: }
2423: *cp++ = '\0';
2424: if ((secs = convtime(cp)) < 0) {
2425: free(sdup);
2426: return -1;
2427: }
2428: /* success */
2429: if (typep != NULL)
2430: *typep = xstrdup(sdup);
2431: if (secsp != NULL)
2432: *secsp = secs;
2433: free(sdup);
2434: return 0;
1.134 djm 2435: }
2436:
2437: /* check if path is absolute */
2438: int
2439: path_absolute(const char *path)
2440: {
2441: return (*path == '/') ? 1 : 0;
1.141 djm 2442: }
2443:
2444: void
2445: skip_space(char **cpp)
2446: {
2447: char *cp;
2448:
2449: for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2450: ;
2451: *cpp = cp;
1.114 millert 2452: }
1.142 djm 2453:
2454: /* authorized_key-style options parsing helpers */
2455:
2456: /*
2457: * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2458: * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2459: * if negated option matches.
2460: * If the option or negated option matches, then *optsp is updated to
2461: * point to the first character after the option.
2462: */
2463: int
2464: opt_flag(const char *opt, int allow_negate, const char **optsp)
2465: {
2466: size_t opt_len = strlen(opt);
2467: const char *opts = *optsp;
2468: int negate = 0;
2469:
2470: if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2471: opts += 3;
2472: negate = 1;
2473: }
2474: if (strncasecmp(opts, opt, opt_len) == 0) {
2475: *optsp = opts + opt_len;
2476: return negate ? 0 : 1;
2477: }
2478: return -1;
2479: }
2480:
2481: char *
2482: opt_dequote(const char **sp, const char **errstrp)
2483: {
2484: const char *s = *sp;
2485: char *ret;
2486: size_t i;
2487:
2488: *errstrp = NULL;
2489: if (*s != '"') {
2490: *errstrp = "missing start quote";
2491: return NULL;
2492: }
2493: s++;
2494: if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2495: *errstrp = "memory allocation failed";
2496: return NULL;
2497: }
2498: for (i = 0; *s != '\0' && *s != '"';) {
2499: if (s[0] == '\\' && s[1] == '"')
2500: s++;
2501: ret[i++] = *s++;
2502: }
2503: if (*s == '\0') {
2504: *errstrp = "missing end quote";
2505: free(ret);
2506: return NULL;
2507: }
2508: ret[i] = '\0';
2509: s++;
2510: *sp = s;
2511: return ret;
2512: }
2513:
2514: int
2515: opt_match(const char **opts, const char *term)
2516: {
2517: if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2518: (*opts)[strlen(term)] == '=') {
2519: *opts += strlen(term) + 1;
2520: return 1;
2521: }
2522: return 0;
1.161 markus 2523: }
2524:
2525: void
2526: opt_array_append2(const char *file, const int line, const char *directive,
2527: char ***array, int **iarray, u_int *lp, const char *s, int i)
2528: {
2529:
2530: if (*lp >= INT_MAX)
2531: fatal("%s line %d: Too many %s entries", file, line, directive);
2532:
2533: if (iarray != NULL) {
2534: *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2535: sizeof(**iarray));
2536: (*iarray)[*lp] = i;
2537: }
2538:
2539: *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2540: (*array)[*lp] = xstrdup(s);
2541: (*lp)++;
2542: }
2543:
2544: void
2545: opt_array_append(const char *file, const int line, const char *directive,
2546: char ***array, u_int *lp, const char *s)
2547: {
2548: opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
1.190 djm 2549: }
2550:
2551: void
2552: opt_array_free2(char **array, int **iarray, u_int l)
2553: {
2554: u_int i;
2555:
2556: if (array == NULL || l == 0)
2557: return;
2558: for (i = 0; i < l; i++)
2559: free(array[i]);
2560: free(array);
2561: free(iarray);
1.142 djm 2562: }
2563:
1.144 dtucker 2564: sshsig_t
2565: ssh_signal(int signum, sshsig_t handler)
2566: {
2567: struct sigaction sa, osa;
2568:
2569: /* mask all other signals while in handler */
1.147 dtucker 2570: memset(&sa, 0, sizeof(sa));
1.144 dtucker 2571: sa.sa_handler = handler;
2572: sigfillset(&sa.sa_mask);
2573: if (signum != SIGALRM)
2574: sa.sa_flags = SA_RESTART;
2575: if (sigaction(signum, &sa, &osa) == -1) {
2576: debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2577: return SIG_ERR;
2578: }
2579: return osa.sa_handler;
1.154 djm 2580: }
2581:
2582: int
2583: stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2584: {
2585: int devnull, ret = 0;
2586:
2587: if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1.155 djm 2588: error_f("open %s: %s", _PATH_DEVNULL,
1.154 djm 2589: strerror(errno));
2590: return -1;
2591: }
2592: if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2593: (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2594: (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
1.155 djm 2595: error_f("dup2: %s", strerror(errno));
1.154 djm 2596: ret = -1;
2597: }
2598: if (devnull > STDERR_FILENO)
2599: close(devnull);
2600: return ret;
1.157 djm 2601: }
2602:
2603: /*
2604: * Runs command in a subprocess with a minimal environment.
2605: * Returns pid on success, 0 on failure.
2606: * The child stdout and stderr maybe captured, left attached or sent to
2607: * /dev/null depending on the contents of flags.
2608: * "tag" is prepended to log messages.
2609: * NB. "command" is only used for logging; the actual command executed is
2610: * av[0].
2611: */
2612: pid_t
2613: subprocess(const char *tag, const char *command,
2614: int ac, char **av, FILE **child, u_int flags,
2615: struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2616: {
2617: FILE *f = NULL;
2618: struct stat st;
2619: int fd, devnull, p[2], i;
2620: pid_t pid;
2621: char *cp, errmsg[512];
2622: u_int nenv = 0;
2623: char **env = NULL;
2624:
2625: /* If dropping privs, then must specify user and restore function */
2626: if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2627: error("%s: inconsistent arguments", tag); /* XXX fatal? */
2628: return 0;
2629: }
2630: if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2631: error("%s: no user for current uid", tag);
2632: return 0;
2633: }
2634: if (child != NULL)
2635: *child = NULL;
2636:
2637: debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2638: tag, command, pw->pw_name, flags);
2639:
2640: /* Check consistency */
2641: if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2642: (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2643: error_f("inconsistent flags");
2644: return 0;
2645: }
2646: if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2647: error_f("inconsistent flags/output");
2648: return 0;
2649: }
2650:
2651: /*
2652: * If executing an explicit binary, then verify the it exists
2653: * and appears safe-ish to execute
2654: */
2655: if (!path_absolute(av[0])) {
2656: error("%s path is not absolute", tag);
2657: return 0;
2658: }
2659: if (drop_privs != NULL)
2660: drop_privs(pw);
2661: if (stat(av[0], &st) == -1) {
2662: error("Could not stat %s \"%s\": %s", tag,
2663: av[0], strerror(errno));
2664: goto restore_return;
2665: }
2666: if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2667: safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2668: error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2669: goto restore_return;
2670: }
2671: /* Prepare to keep the child's stdout if requested */
2672: if (pipe(p) == -1) {
2673: error("%s: pipe: %s", tag, strerror(errno));
2674: restore_return:
2675: if (restore_privs != NULL)
2676: restore_privs();
2677: return 0;
2678: }
2679: if (restore_privs != NULL)
2680: restore_privs();
2681:
2682: switch ((pid = fork())) {
2683: case -1: /* error */
2684: error("%s: fork: %s", tag, strerror(errno));
2685: close(p[0]);
2686: close(p[1]);
2687: return 0;
2688: case 0: /* child */
2689: /* Prepare a minimal environment for the child. */
2690: if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2691: nenv = 5;
2692: env = xcalloc(sizeof(*env), nenv);
2693: child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2694: child_set_env(&env, &nenv, "USER", pw->pw_name);
2695: child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2696: child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2697: if ((cp = getenv("LANG")) != NULL)
2698: child_set_env(&env, &nenv, "LANG", cp);
2699: }
2700:
1.162 dtucker 2701: for (i = 1; i < NSIG; i++)
1.157 djm 2702: ssh_signal(i, SIG_DFL);
2703:
2704: if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2705: error("%s: open %s: %s", tag, _PATH_DEVNULL,
2706: strerror(errno));
2707: _exit(1);
2708: }
2709: if (dup2(devnull, STDIN_FILENO) == -1) {
2710: error("%s: dup2: %s", tag, strerror(errno));
2711: _exit(1);
2712: }
2713:
2714: /* Set up stdout as requested; leave stderr in place for now. */
2715: fd = -1;
2716: if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2717: fd = p[1];
2718: else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2719: fd = devnull;
2720: if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2721: error("%s: dup2: %s", tag, strerror(errno));
2722: _exit(1);
2723: }
2724: closefrom(STDERR_FILENO + 1);
2725:
1.170 djm 2726: if (geteuid() == 0 &&
2727: initgroups(pw->pw_name, pw->pw_gid) == -1) {
2728: error("%s: initgroups(%s, %u): %s", tag,
2729: pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2730: _exit(1);
2731: }
1.157 djm 2732: if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2733: error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2734: strerror(errno));
2735: _exit(1);
2736: }
2737: if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2738: error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2739: strerror(errno));
2740: _exit(1);
2741: }
2742: /* stdin is pointed to /dev/null at this point */
2743: if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2744: dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2745: error("%s: dup2: %s", tag, strerror(errno));
2746: _exit(1);
2747: }
2748: if (env != NULL)
2749: execve(av[0], av, env);
2750: else
2751: execv(av[0], av);
2752: error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2753: command, strerror(errno));
2754: _exit(127);
2755: default: /* parent */
2756: break;
2757: }
2758:
2759: close(p[1]);
2760: if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2761: close(p[0]);
2762: else if ((f = fdopen(p[0], "r")) == NULL) {
2763: error("%s: fdopen: %s", tag, strerror(errno));
2764: close(p[0]);
2765: /* Don't leave zombie child */
2766: kill(pid, SIGTERM);
2767: while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2768: ;
2769: return 0;
2770: }
2771: /* Success */
2772: debug3_f("%s pid %ld", tag, (long)pid);
2773: if (child != NULL)
2774: *child = f;
2775: return pid;
1.165 djm 2776: }
2777:
2778: const char *
2779: lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2780: {
2781: size_t i, envlen;
2782:
2783: envlen = strlen(env);
2784: for (i = 0; i < nenvs; i++) {
2785: if (strncmp(envs[i], env, envlen) == 0 &&
2786: envs[i][envlen] == '=') {
2787: return envs[i] + envlen + 1;
2788: }
2789: }
2790: return NULL;
1.176 djm 2791: }
2792:
2793: const char *
2794: lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2795: {
2796: char *name, *cp;
2797: const char *ret;
2798:
2799: name = xstrdup(env);
2800: if ((cp = strchr(name, '=')) == NULL) {
2801: free(name);
2802: return NULL; /* not env=val */
2803: }
2804: *cp = '\0';
2805: ret = lookup_env_in_list(name, envs, nenvs);
2806: free(name);
2807: return ret;
1.180 djm 2808: }
2809:
2810: /*
2811: * Helpers for managing poll(2)/ppoll(2) timeouts
2812: * Will remember the earliest deadline and return it for use in poll/ppoll.
2813: */
2814:
2815: /* Initialise a poll/ppoll timeout with an indefinite deadline */
2816: void
2817: ptimeout_init(struct timespec *pt)
2818: {
2819: /*
2820: * Deliberately invalid for ppoll(2).
2821: * Will be converted to NULL in ptimeout_get_tspec() later.
2822: */
2823: pt->tv_sec = -1;
2824: pt->tv_nsec = 0;
2825: }
2826:
2827: /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2828: void
2829: ptimeout_deadline_sec(struct timespec *pt, long sec)
2830: {
2831: if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2832: pt->tv_sec = sec;
2833: pt->tv_nsec = 0;
2834: }
2835: }
2836:
2837: /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2838: static void
2839: ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2840: {
2841: if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2842: *pt = *p;
2843: }
2844:
2845: /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2846: void
2847: ptimeout_deadline_ms(struct timespec *pt, long ms)
2848: {
2849: struct timespec p;
2850:
2851: p.tv_sec = ms / 1000;
2852: p.tv_nsec = (ms % 1000) * 1000000;
2853: ptimeout_deadline_tsp(pt, &p);
2854: }
2855:
1.187 djm 2856: /* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
1.180 djm 2857: void
1.187 djm 2858: ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
1.180 djm 2859: {
2860: struct timespec now, t;
2861:
2862: monotime_ts(&now);
2863:
1.187 djm 2864: if (timespeccmp(&now, when, >=)) {
2865: /* 'when' is now or in the past. Timeout ASAP */
2866: pt->tv_sec = 0;
2867: pt->tv_nsec = 0;
2868: } else {
2869: timespecsub(when, &now, &t);
1.180 djm 2870: ptimeout_deadline_tsp(pt, &t);
2871: }
1.187 djm 2872: }
2873:
2874: /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
2875: void
2876: ptimeout_deadline_monotime(struct timespec *pt, time_t when)
2877: {
2878: struct timespec t;
2879:
2880: t.tv_sec = when;
2881: t.tv_nsec = 0;
2882: ptimeout_deadline_monotime_tsp(pt, &t);
1.180 djm 2883: }
2884:
2885: /* Get a poll(2) timeout value in milliseconds */
2886: int
2887: ptimeout_get_ms(struct timespec *pt)
2888: {
2889: if (pt->tv_sec == -1)
2890: return -1;
2891: if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
2892: return INT_MAX;
2893: return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
2894: }
2895:
2896: /* Get a ppoll(2) timeout value as a timespec pointer */
2897: struct timespec *
2898: ptimeout_get_tsp(struct timespec *pt)
2899: {
2900: return pt->tv_sec == -1 ? NULL : pt;
2901: }
2902:
2903: /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
2904: int
2905: ptimeout_isset(struct timespec *pt)
2906: {
2907: return pt->tv_sec != -1;
1.184 djm 2908: }
2909:
2910: /*
2911: * Returns zero if the library at 'path' contains symbol 's', nonzero
2912: * otherwise.
2913: */
2914: int
2915: lib_contains_symbol(const char *path, const char *s)
2916: {
2917: struct nlist nl[2];
2918: int ret = -1, r;
2919:
2920: memset(nl, 0, sizeof(nl));
2921: nl[0].n_name = xstrdup(s);
2922: nl[1].n_name = NULL;
2923: if ((r = nlist(path, nl)) == -1) {
2924: error_f("nlist failed for %s", path);
2925: goto out;
2926: }
2927: if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
2928: error_f("library %s does not contain symbol %s", path, s);
2929: goto out;
2930: }
2931: /* success */
2932: ret = 0;
2933: out:
2934: free(nl[0].n_name);
2935: return ret;
1.144 dtucker 2936: }