Coverage Report

Created: 2025-11-01 07:09

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