Coverage Report

Created: 2025-08-29 06:46

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