Coverage Report

Created: 2024-11-12 06:25

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