Coverage Report

Created: 2026-12-01 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hpn-ssh/misc-agent.c
Line
Count
Source
1
/* $OpenBSD: misc-agent.c,v 1.11 2026/09/22 22:29:27 djm Exp $ */
2
/*
3
 * Copyright (c) 2025 Damien Miller <djm@mindrot.org>
4
 *
5
 * Permission to use, copy, modify, and distribute this software for any
6
 * purpose with or without fee is hereby granted, provided that the above
7
 * copyright notice and this permission notice appear in all copies.
8
 *
9
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
 */
17
18
#include "includes.h"
19
20
#include <sys/types.h>
21
#include <sys/socket.h>
22
#include <sys/stat.h>
23
#include <sys/un.h>
24
25
#include <dirent.h>
26
#include <errno.h>
27
#include <fcntl.h>
28
#include <netdb.h>
29
#include <stdlib.h>
30
#include <string.h>
31
#include <time.h>
32
#include <unistd.h>
33
#include <libgen.h>
34
35
#include "digest.h"
36
#include "log.h"
37
#include "misc.h"
38
#include "pathnames.h"
39
#include "ssh.h"
40
#include "xmalloc.h"
41
42
/* stuff shared by agent listeners (ssh-agent and sshd agent forwarding) */
43
44
0
#define SOCKET_HOSTNAME_HASHLEN 10 /* length of hostname hash in socket path */
45
46
/* used for presenting random strings in unix_listener_tmp and hostname_hash */
47
static const char presentation_chars[] =
48
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
49
50
/* returns a text-encoded hash of the hostname of specified length (max 64) */
51
static char *
52
hostname_hash(size_t len)
53
0
{
54
0
  char hostname[NI_MAXHOST], p[65];
55
0
  u_char hash[64];
56
0
  int r;
57
0
  size_t l, i;
58
59
0
  l = ssh_digest_bytes(SSH_DIGEST_SHA512);
60
0
  if (len > 64) {
61
0
    error_f("bad length %zu >= max %zd", len, l);
62
0
    return NULL;
63
0
  }
64
0
  if (gethostname(hostname, sizeof(hostname)) == -1) {
65
0
    error_f("gethostname: %s", strerror(errno));
66
0
    return NULL;
67
0
  }
68
0
  if ((r = ssh_digest_memory(SSH_DIGEST_SHA512,
69
0
      hostname, strlen(hostname), hash, sizeof(hash))) != 0) {
70
0
    error_fr(r, "ssh_digest_memory");
71
0
    return NULL;
72
0
  }
73
0
  memset(p, '\0', sizeof(p));
74
0
  for (i = 0; i < l; i++)
75
0
    p[i] = presentation_chars[
76
0
        hash[i] % (sizeof(presentation_chars) - 1)];
77
  /* debug3_f("hostname \"%s\" => hash \"%s\"", hostname, p); */
78
0
  p[len] = '\0';
79
0
  return xstrdup(p);
80
0
}
81
82
static char *
83
agent_hostname_hash(void)
84
0
{
85
0
  return hostname_hash(SOCKET_HOSTNAME_HASHLEN);
86
0
}
87
88
/*
89
 * Creates a unix listener at a mkstemp(3)-style path, e.g. "/dir/sock.XXXXXX"
90
 * Supplied path is modified to the actual one used.
91
 */
92
static int
93
unix_listener_tmp(char *path, int backlog)
94
0
{
95
0
  struct sockaddr_un sunaddr;
96
0
  int good, sock = -1;
97
0
  size_t i, xstart;
98
0
  mode_t prev_mask;
99
100
  /* Find first 'X' template character back from end of string */
101
0
  xstart = strlen(path);
102
0
  while (xstart > 0 && path[xstart - 1] == 'X')
103
0
    xstart--;
104
105
0
  memset(&sunaddr, 0, sizeof(sunaddr));
106
0
  sunaddr.sun_family = AF_UNIX;
107
0
  prev_mask = umask(0177);
108
0
  for (good = 0; !good;) {
109
0
    sock = -1;
110
    /* Randomise path suffix */
111
0
    for (i = xstart; path[i] != '\0'; i++) {
112
0
      path[i] = presentation_chars[
113
0
          arc4random_uniform(sizeof(presentation_chars)-1)];
114
0
    }
115
0
    debug_f("trying path \"%s\"", path);
116
117
0
    if (strlcpy(sunaddr.sun_path, path,
118
0
        sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
119
0
      error_f("path \"%s\" too long for Unix domain socket",
120
0
          path);
121
0
      break;
122
0
    }
123
124
0
    if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
125
0
      error_f("socket: %.100s", strerror(errno));
126
0
      break;
127
0
    }
128
0
    if (bind(sock, (struct sockaddr *)&sunaddr,
129
0
        sizeof(sunaddr)) == -1) {
130
0
      if (errno == EADDRINUSE) {
131
0
        error_f("bind \"%s\": %.100s",
132
0
            path, strerror(errno));
133
0
        close(sock);
134
0
        sock = -1;
135
0
        continue;
136
0
      }
137
0
      error_f("bind \"%s\": %.100s", path, strerror(errno));
138
0
      break;
139
0
    }
140
0
    if (listen(sock, backlog) == -1) {
141
0
      error_f("listen \"%s\": %s", path, strerror(errno));
142
0
      break;
143
0
    }
144
0
    good = 1;
145
0
  }
146
0
  umask(prev_mask);
147
0
  if (good) {
148
0
    debug3_f("listening on unix socket \"%s\" as fd=%d",
149
0
        path, sock);
150
0
  } else if (sock != -1) {
151
0
    close(sock);
152
0
    sock = -1;
153
0
  }
154
0
  return sock;
155
0
}
156
157
/*
158
 * Shared directory case (e.g. /tmp): create a temporary directory
159
 * for the socket.
160
 */
161
static int
162
agent_listener_shared(const char *parent_dir, pid_t pid, const char *tag,
163
    int *sockp, char **pathp, char **dirp)
164
0
{
165
0
  char *dir = NULL, *path = NULL;
166
0
  int sock, ret = -1;
167
0
  mode_t prev_mask;
168
169
0
  *pathp = *dirp = NULL;
170
0
  xasprintf(&dir, "%s/ssh-XXXXXXXXXXXX", parent_dir);
171
0
  if (mkdtemp(dir) == NULL) {
172
0
    error_f("failed to create temporary directory "
173
0
        "in \"%s\": %s", dir, strerror(errno));
174
0
    goto out;
175
0
  }
176
0
  xasprintf(&path, "%s/agent.%s.%ld", dir, tag, (long)pid);
177
0
  prev_mask = umask(0177);
178
0
  if ((sock = unix_listener(path, SSH_LISTEN_BACKLOG, 0)) < 0) {
179
    /* Error already logged */
180
0
    umask(prev_mask);
181
0
    if (rmdir(dir) != 0)
182
0
      error_f("rmdir \"%s\": %s", dir, strerror(errno));
183
0
    goto out;
184
0
  }
185
0
  umask(prev_mask);
186
187
  /* Success */
188
0
  *dirp = dir;
189
0
  dir = NULL; /* transferred */
190
0
  *pathp = path;
191
0
  path = NULL; /* transferred */
192
0
  *sockp = sock;
193
0
  ret = 0;
194
0
 out:
195
0
  free(dir);
196
0
  free(path);
197
0
  return ret;
198
0
}
199
200
/*
201
 * User-specific directory case (e.g. ~/.ssh/agent): ensure directory
202
 * exists, and use a temp socket name under it.
203
 */
204
static int
205
agent_listener_user(const char *dir, pid_t pid, const char *tag,
206
    int *sockp, char **pathp)
207
0
{
208
0
  char *hostnamehash = NULL, *path = NULL;
209
0
  int sock, ret = -1;
210
211
0
  if ((hostnamehash = hostname_hash(SOCKET_HOSTNAME_HASHLEN)) == NULL)
212
0
    return -1;
213
0
  xasprintf(&path, "%s/s.%s.%s.%lld.XXXXXXXXXX",
214
0
      dir, hostnamehash, tag, (long long)pid);
215
0
  if (mkdir_path(dir, 0700) != 0) {
216
0
    error_f("failed to create agent socket parent directory");
217
0
    goto out;
218
0
  }
219
0
  if ((sock = unix_listener_tmp(path, SSH_LISTEN_BACKLOG)) == -1) {
220
    /* error already logged */
221
0
    goto out;
222
0
  }
223
  /* Success */
224
0
  *pathp = path;
225
0
  path = NULL; /* transferred */
226
0
  *sockp = sock;
227
0
  ret = 0;
228
0
 out:
229
0
  free(hostnamehash);
230
0
  free(path);
231
0
  return ret;
232
0
}
233
234
static char *
235
expand_pathspec(const char *path, const char *username,
236
    uid_t uid, const char *homedir)
237
0
{
238
0
  char *uidbuf = NULL, *dir = NULL, *tmp = NULL;
239
240
0
  xasprintf(&uidbuf, "%lld", (long long)uid);
241
242
0
  if ((tmp = percent_expand(path, "u", username, "U", uidbuf,
243
0
      "h", homedir, NULL)) == NULL) {
244
0
    error_f("failed to percent-expand agent socket directory");
245
0
    goto out;
246
0
  }
247
0
  if (tilde_expand(tmp, uid, &dir) != 0) {
248
0
    error_f("failed to user-expand agent socket directory");
249
0
    goto out;
250
0
  }
251
0
  if (dir[0] != '/') {
252
    /* Assume it's relative to the home directory */
253
0
    free(tmp);
254
0
    tmp = dir;
255
0
    xasprintf(&dir, "%s/%s", homedir, tmp);
256
0
  }
257
0
 out:
258
0
  free(uidbuf);
259
0
  free(tmp);
260
0
  return dir;
261
0
}
262
263
int
264
agent_listener(const char *pathspec, const char *username, uid_t uid,
265
    const char *homedir, pid_t pid, const char *tag, int *sockp,
266
    char **pathp, char **dirp)
267
0
{
268
0
  int sock = -1, ret = -1;
269
0
  char *path = NULL, *dir = NULL;
270
271
0
  *sockp = -1;
272
0
  *pathp = *dirp = NULL;
273
274
0
  if (pathspec == NULL || pathspec[0] == '\0') {
275
0
    error_f("no agent path specified");
276
0
    return -1;
277
0
  }
278
0
  if (strncmp(pathspec, "shared:", 7) == 0) {
279
0
    if (pathspec[7] != '/') {
280
0
      error_f("shared agent socket paths must be absolute");
281
0
      goto out;
282
0
    }
283
0
    if ((dir = expand_pathspec(pathspec + 7,
284
0
        username, uid, homedir)) == NULL) {
285
      /* Error already logged */
286
0
      goto out;
287
0
    }
288
0
    if (agent_listener_shared(dir, pid, tag,
289
0
        &sock, &path, dirp) != 0) {
290
      /* Error already logged */
291
0
      goto out;
292
0
    }
293
0
  } else if (strncmp(pathspec, "user:", 5) == 0) {
294
0
    if ((dir = expand_pathspec(pathspec + 5,
295
0
        username, uid, homedir)) == NULL) {
296
      /* Error already logged */
297
0
      goto out;
298
0
    }
299
0
    if (agent_listener_user(dir, pid, tag, &sock, &path) != 0) {
300
      /* Error already logged */
301
0
      goto out;
302
0
    }
303
0
  } else {
304
    /* Shouldn't happen */
305
0
    error_f("unsupported agent path specification %s", pathspec);
306
0
    goto out;
307
0
  }
308
309
  /* success */
310
0
  ret = 0;
311
0
  *sockp = sock;
312
0
  *pathp = path;
313
0
  path = NULL; /* transferred */
314
0
 out:
315
0
  free(path);
316
0
  free(dir);
317
0
  return ret;
318
0
}
319
320
int
321
agent_listener_cleanup(const char *pathspec, const char *sockpath,
322
    const char *sockdir)
323
0
{
324
0
  if (sockpath == NULL)
325
0
    return 0;
326
0
  if (unlink(sockpath) != 0) {
327
0
    error_f("unlink \"%s\": %s", sockpath, strerror(errno));
328
0
    return -1;
329
0
  }
330
0
  debug3_f("removed socket %s", sockpath);
331
332
0
  if (pathspec == NULL)
333
0
    return 0;
334
0
  if (strncmp(pathspec, "shared:", 7) == 0 && sockdir != NULL) {
335
0
    if (rmdir(sockdir) != 0) {
336
0
      error_f("rmdir \"%s\": %s", sockdir, strerror(errno));
337
0
      return -1;
338
0
    }
339
0
    debug3_f("removed socket directory %s", sockdir);
340
0
  }
341
342
0
  return 0;
343
0
}
344
345
static int
346
socket_is_stale(const char *path)
347
0
{
348
0
  int fd, r;
349
0
  struct sockaddr_un sunaddr;
350
0
  socklen_t l = sizeof(r);
351
352
  /* attempt non-blocking connect on socket */
353
0
  memset(&sunaddr, '\0', sizeof(sunaddr));
354
0
  sunaddr.sun_family = AF_UNIX;
355
0
  if (strlcpy(sunaddr.sun_path, path,
356
0
      sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
357
0
    debug_f("path for \"%s\" too long for sockaddr_un", path);
358
0
    return 0;
359
0
  }
360
0
  if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
361
0
    error_f("socket: %s", strerror(errno));
362
0
    return 0;
363
0
  }
364
0
  set_nonblock(fd);
365
  /* a socket without a listener should yield an error immediately */
366
0
  if (connect(fd, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
367
0
    debug_f("connect \"%s\": %s", path, strerror(errno));
368
0
    close(fd);
369
0
    return 1;
370
0
  }
371
0
  if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &r, &l) == -1) {
372
0
    debug_f("getsockopt: %s", strerror(errno));
373
0
    close(fd);
374
0
    return 0;
375
0
  }
376
0
  if (r != 0) {
377
0
    debug_f("socket error on %s: %s", path, strerror(errno));
378
0
    close(fd);
379
0
    return 1;
380
0
  }
381
0
  close(fd);
382
0
  debug_f("socket %s seems still active", path);
383
0
  return 0;
384
0
}
385
386
#ifndef HAVE_FSTATAT
387
# define fstatat(x, y, buf, z) lstat(path, buf)
388
#endif
389
#ifndef HAVE_UNLINKAT
390
# define unlinkat(x, y, z) unlink(path)
391
#endif
392
393
void
394
agent_cleanup_stale(const char *pathspec, const char *username, uid_t uid,
395
    const char *homedir, int ignore_hosthash)
396
0
{
397
0
  DIR *d = NULL;
398
0
  struct dirent *dp;
399
0
  struct stat sb;
400
0
  char *prefix = NULL, *dir = NULL, *path;
401
0
  struct timespec now, sub, *mtimp = NULL;
402
403
  /* Only clean up user socket directories */
404
0
  if (pathspec == NULL || strncmp(pathspec, "user:", 5) != 0)
405
0
    return;
406
407
0
  if ((dir = expand_pathspec(pathspec + 5,
408
0
      username, uid, homedir)) == NULL)
409
0
    return; /* error already logged */
410
411
0
  debug_f("cleanup %s", dir);
412
413
  /* Only consider sockets last modified > 1 hour ago */
414
0
  if (clock_gettime(CLOCK_REALTIME, &now) != 0) {
415
0
    error_f("clock_gettime: %s", strerror(errno));
416
0
    goto out;
417
0
  }
418
0
  sub.tv_sec = 60 * 60;
419
0
  sub.tv_nsec = 0;
420
0
  timespecsub(&now, &sub, &now);
421
422
  /* Only consider sockets from the same hostname */
423
0
  if (!ignore_hosthash) {
424
0
    if ((path = agent_hostname_hash()) == NULL) {
425
0
      error_f("couldn't get hostname hash");
426
0
      goto out;
427
0
    }
428
0
    xasprintf(&prefix, "s.%s.", path);
429
0
    free(path);
430
0
  }
431
432
0
  if ((d = opendir(dir)) == NULL) {
433
0
    if (errno != ENOENT)
434
0
      error_f("opendir \"%s\": %s", dir, strerror(errno));
435
0
    goto out;
436
0
  }
437
0
  while ((dp = readdir(d)) != NULL) {
438
#ifdef HAVE_DIRENT_D_TYPE
439
    if (dp->d_type != DT_SOCK && dp->d_type != DT_UNKNOWN)
440
      continue;
441
#endif
442
0
    if (fstatat(dirfd(d), dp->d_name,
443
0
        &sb, AT_SYMLINK_NOFOLLOW) != 0 && errno != ENOENT) {
444
0
      error_f("stat \"%s/%s\": %s",
445
0
          dir, dp->d_name, strerror(errno));
446
0
      continue;
447
0
    }
448
0
    if (!S_ISSOCK(sb.st_mode))
449
0
      continue;
450
0
#ifdef HAVE_STRUCT_STAT_ST_MTIM
451
0
    mtimp = &sb.st_mtim;
452
#else
453
    sub.tv_sec = sb.st_mtime;
454
    sub.tv_nsec = 0;
455
    mtimp = &sub;
456
#endif
457
0
    if (timespeccmp(mtimp, &now, >)) {
458
0
      debug3_f("Ignoring recent socket \"%s/%s\"",
459
0
          dir, dp->d_name);
460
0
      continue;
461
0
    }
462
0
    if (!ignore_hosthash &&
463
0
        strncmp(dp->d_name, prefix, strlen(prefix)) != 0) {
464
0
      debug3_f("Ignoring socket \"%s/%s\" "
465
0
          "from different host", dir, dp->d_name);
466
0
      continue;
467
0
    }
468
0
    xasprintf(&path, "%s/%s", dir, dp->d_name);
469
0
    if (socket_is_stale(path)) {
470
0
      debug_f("cleanup stale socket %s", path);
471
0
      unlinkat(dirfd(d), dp->d_name, 0);
472
0
    }
473
0
    free(path);
474
0
  }
475
0
 out:
476
0
  if (d != NULL)
477
0
    closedir(d);
478
0
  free(dir);
479
0
  free(prefix);
480
0
}
481
482
#undef unlinkat
483
#undef fstatat