Coverage Report

Created: 2025-11-17 06:37

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