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