Coverage Report

Created: 2024-02-11 06:22

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