Coverage Report

Created: 2023-06-07 07:08

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