Coverage Report

Created: 2026-02-26 06:46

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