Coverage Report

Created: 2024-09-03 06:03

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