Coverage Report

Created: 2025-10-10 06:43

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