Coverage Report

Created: 2025-11-24 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssh/ssh-agent.c
Line
Count
Source
1
/* $OpenBSD: ssh-agent.c,v 1.315 2025/11/13 10:35:14 dtucker Exp $ */
2
/*
3
 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4
 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5
 *                    All rights reserved
6
 * The authentication agent program.
7
 *
8
 * As far as I am concerned, the code I have written for this software
9
 * can be used freely for any purpose.  Any derived versions of this
10
 * software must be clearly marked as such, and if the derived work is
11
 * incompatible with the protocol description in the RFC file, it must be
12
 * called by a name other than "ssh" or "Secure Shell".
13
 *
14
 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
15
 *
16
 * Redistribution and use in source and binary forms, with or without
17
 * modification, are permitted provided that the following conditions
18
 * are met:
19
 * 1. Redistributions of source code must retain the above copyright
20
 *    notice, this list of conditions and the following disclaimer.
21
 * 2. Redistributions in binary form must reproduce the above copyright
22
 *    notice, this list of conditions and the following disclaimer in the
23
 *    documentation and/or other materials provided with the distribution.
24
 *
25
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
 */
36
37
#include "includes.h"
38
39
#include <sys/types.h>
40
#include <sys/resource.h>
41
#include <sys/stat.h>
42
#include <sys/socket.h>
43
#include <sys/wait.h>
44
#include <sys/time.h>
45
#include <sys/un.h>
46
#include "openbsd-compat/sys-queue.h"
47
48
#ifdef WITH_OPENSSL
49
#include <openssl/evp.h>
50
#include "openbsd-compat/openssl-compat.h"
51
#endif
52
53
#include <errno.h>
54
#include <fcntl.h>
55
#include <limits.h>
56
#include <paths.h>
57
#include <poll.h>
58
#include <signal.h>
59
#include <stdarg.h>
60
#include <stdio.h>
61
#include <stdlib.h>
62
#include <time.h>
63
#include <string.h>
64
#include <unistd.h>
65
#include <util.h>
66
67
#include "xmalloc.h"
68
#include "ssh.h"
69
#include "ssh2.h"
70
#include "sshbuf.h"
71
#include "sshkey.h"
72
#include "authfd.h"
73
#include "log.h"
74
#include "misc.h"
75
#include "digest.h"
76
#include "ssherr.h"
77
#include "match.h"
78
#include "msg.h"
79
#include "pathnames.h"
80
#include "ssh-pkcs11.h"
81
#include "sk-api.h"
82
#include "myproposal.h"
83
84
#ifndef DEFAULT_ALLOWED_PROVIDERS
85
0
# define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
86
#endif
87
#ifndef DEFAULT_WEBSAFE_ALLOWLIST
88
0
# define DEFAULT_WEBSAFE_ALLOWLIST "ssh:*"
89
#endif
90
91
/* Maximum accepted message length */
92
78.3k
#define AGENT_MAX_LEN   (256*1024)
93
/* Maximum bytes to read from client socket */
94
0
#define AGENT_RBUF_LEN    (4096)
95
/* Maximum number of recorded session IDs/hostkeys per connection */
96
0
#define AGENT_MAX_SESSION_IDS   16
97
/* Maximum size of session ID */
98
0
#define AGENT_MAX_SID_LEN   128
99
/* Maximum number of destination constraints to accept on a key */
100
0
#define AGENT_MAX_DEST_CONSTRAINTS  1024
101
/* Maximum number of associated certificate constraints to accept on a key */
102
0
#define AGENT_MAX_EXT_CERTS   1024
103
104
/* XXX store hostkey_sid in a refcounted tree */
105
106
typedef enum {
107
  AUTH_UNUSED = 0,
108
  AUTH_SOCKET = 1,
109
  AUTH_CONNECTION = 2,
110
} sock_type;
111
112
struct hostkey_sid {
113
  struct sshkey *key;
114
  struct sshbuf *sid;
115
  int forwarded;
116
};
117
118
typedef struct socket_entry {
119
  int fd;
120
  sock_type type;
121
  struct sshbuf *input;
122
  struct sshbuf *output;
123
  struct sshbuf *request;
124
  size_t nsession_ids;
125
  struct hostkey_sid *session_ids;
126
  int session_bind_attempted;
127
} SocketEntry;
128
129
u_int sockets_alloc = 0;
130
SocketEntry *sockets = NULL;
131
132
typedef struct identity {
133
  TAILQ_ENTRY(identity) next;
134
  struct sshkey *key;
135
  char *comment;
136
  char *provider;
137
  time_t death;
138
  u_int confirm;
139
  char *sk_provider;
140
  struct dest_constraint *dest_constraints;
141
  size_t ndest_constraints;
142
} Identity;
143
144
struct idtable {
145
  int nentries;
146
  TAILQ_HEAD(idqueue, identity) idlist;
147
};
148
149
/* private key table */
150
struct idtable *idtab;
151
152
int max_fd = 0;
153
154
/* pid of shell == parent of agent */
155
pid_t parent_pid = -1;
156
time_t parent_alive_interval = 0;
157
158
static sig_atomic_t signalled_exit;
159
static sig_atomic_t signalled_keydrop;
160
161
/* pid of process for which cleanup_socket is applicable */
162
pid_t cleanup_pid = 0;
163
164
/* pathname and directory for AUTH_SOCKET */
165
static char *socket_name;
166
static char socket_dir[PATH_MAX];
167
168
/* Pattern-list of allowed PKCS#11/Security key paths */
169
static char *allowed_providers;
170
171
/*
172
 * Allows PKCS11 providers or SK keys that use non-internal providers to
173
 * be added over a remote connection (identified by session-bind@openssh.com).
174
 */
175
static int remote_add_provider;
176
177
/* locking */
178
3.31k
#define LOCK_SIZE 32
179
#define LOCK_SALT_SIZE  16
180
3.31k
#define LOCK_ROUNDS 1
181
int locked = 0;
182
u_char lock_pwhash[LOCK_SIZE];
183
u_char lock_salt[LOCK_SALT_SIZE];
184
185
extern char *__progname;
186
187
/* Default lifetime in seconds (0 == forever) */
188
static int lifetime = 0;
189
190
static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
191
192
/* Refuse signing of non-SSH messages for web-origin FIDO keys */
193
static int restrict_websafe = 1;
194
static char *websafe_allowlist;
195
196
static void
197
close_socket(SocketEntry *e)
198
1.02k
{
199
1.02k
  size_t i;
200
201
1.02k
  close(e->fd);
202
1.02k
  sshbuf_free(e->input);
203
1.02k
  sshbuf_free(e->output);
204
1.02k
  sshbuf_free(e->request);
205
1.02k
  for (i = 0; i < e->nsession_ids; i++) {
206
0
    sshkey_free(e->session_ids[i].key);
207
0
    sshbuf_free(e->session_ids[i].sid);
208
0
  }
209
1.02k
  free(e->session_ids);
210
1.02k
  memset(e, '\0', sizeof(*e));
211
1.02k
  e->fd = -1;
212
1.02k
  e->type = AUTH_UNUSED;
213
1.02k
}
214
215
static void
216
idtab_init(void)
217
1.02k
{
218
1.02k
  idtab = xcalloc(1, sizeof(*idtab));
219
1.02k
  TAILQ_INIT(&idtab->idlist);
220
1.02k
  idtab->nentries = 0;
221
1.02k
}
222
223
static void
224
free_dest_constraint_hop(struct dest_constraint_hop *dch)
225
0
{
226
0
  u_int i;
227
228
0
  if (dch == NULL)
229
0
    return;
230
0
  free(dch->user);
231
0
  free(dch->hostname);
232
0
  for (i = 0; i < dch->nkeys; i++)
233
0
    sshkey_free(dch->keys[i]);
234
0
  free(dch->keys);
235
0
  free(dch->key_is_ca);
236
0
}
237
238
static void
239
free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
240
18.1k
{
241
18.1k
  size_t i;
242
243
18.1k
  for (i = 0; i < ndcs; i++) {
244
0
    free_dest_constraint_hop(&dcs[i].from);
245
0
    free_dest_constraint_hop(&dcs[i].to);
246
0
  }
247
18.1k
  free(dcs);
248
18.1k
}
249
250
#ifdef ENABLE_PKCS11
251
static void
252
dup_dest_constraint_hop(const struct dest_constraint_hop *dch,
253
    struct dest_constraint_hop *out)
254
0
{
255
0
  u_int i;
256
0
  int r;
257
258
0
  out->user = dch->user == NULL ? NULL : xstrdup(dch->user);
259
0
  out->hostname = dch->hostname == NULL ? NULL : xstrdup(dch->hostname);
260
0
  out->is_ca = dch->is_ca;
261
0
  out->nkeys = dch->nkeys;
262
0
  out->keys = out->nkeys == 0 ? NULL :
263
0
      xcalloc(out->nkeys, sizeof(*out->keys));
264
0
  out->key_is_ca = out->nkeys == 0 ? NULL :
265
0
      xcalloc(out->nkeys, sizeof(*out->key_is_ca));
266
0
  for (i = 0; i < dch->nkeys; i++) {
267
0
    if (dch->keys[i] != NULL &&
268
0
        (r = sshkey_from_private(dch->keys[i],
269
0
        &(out->keys[i]))) != 0)
270
0
      fatal_fr(r, "copy key");
271
0
    out->key_is_ca[i] = dch->key_is_ca[i];
272
0
  }
273
0
}
274
275
static struct dest_constraint *
276
dup_dest_constraints(const struct dest_constraint *dcs, size_t ndcs)
277
0
{
278
0
  size_t i;
279
0
  struct dest_constraint *ret;
280
281
0
  if (ndcs == 0)
282
0
    return NULL;
283
0
  ret = xcalloc(ndcs, sizeof(*ret));
284
0
  for (i = 0; i < ndcs; i++) {
285
0
    dup_dest_constraint_hop(&dcs[i].from, &ret[i].from);
286
0
    dup_dest_constraint_hop(&dcs[i].to, &ret[i].to);
287
0
  }
288
0
  return ret;
289
0
}
290
#endif /* ENABLE_PKCS11 */
291
292
#ifdef DEBUG_CONSTRAINTS
293
static void
294
dump_dest_constraint_hop(const struct dest_constraint_hop *dch)
295
{
296
  u_int i;
297
  char *fp;
298
299
  debug_f("user %s hostname %s is_ca %d nkeys %u",
300
      dch->user == NULL ? "(null)" : dch->user,
301
      dch->hostname == NULL ? "(null)" : dch->hostname,
302
      dch->is_ca, dch->nkeys);
303
  for (i = 0; i < dch->nkeys; i++) {
304
    fp = NULL;
305
    if (dch->keys[i] != NULL &&
306
        (fp = sshkey_fingerprint(dch->keys[i],
307
        SSH_FP_HASH_DEFAULT, SSH_FP_DEFAULT)) == NULL)
308
      fatal_f("fingerprint failed");
309
    debug_f("key %u/%u: %s%s%s key_is_ca %d", i, dch->nkeys,
310
        dch->keys[i] == NULL ? "" : sshkey_ssh_name(dch->keys[i]),
311
        dch->keys[i] == NULL ? "" : " ",
312
        dch->keys[i] == NULL ? "none" : fp,
313
        dch->key_is_ca[i]);
314
    free(fp);
315
  }
316
}
317
#endif /* DEBUG_CONSTRAINTS */
318
319
static void
320
dump_dest_constraints(const char *context,
321
    const struct dest_constraint *dcs, size_t ndcs)
322
13.0k
{
323
#ifdef DEBUG_CONSTRAINTS
324
  size_t i;
325
326
  debug_f("%s: %zu constraints", context, ndcs);
327
  for (i = 0; i < ndcs; i++) {
328
    debug_f("constraint %zu / %zu: from: ", i, ndcs);
329
    dump_dest_constraint_hop(&dcs[i].from);
330
    debug_f("constraint %zu / %zu: to: ", i, ndcs);
331
    dump_dest_constraint_hop(&dcs[i].to);
332
  }
333
  debug_f("done for %s", context);
334
#endif /* DEBUG_CONSTRAINTS */
335
13.0k
}
336
337
static void
338
free_identity(Identity *id)
339
11.1k
{
340
11.1k
  sshkey_free(id->key);
341
11.1k
  free(id->provider);
342
11.1k
  free(id->comment);
343
11.1k
  free(id->sk_provider);
344
11.1k
  free_dest_constraints(id->dest_constraints, id->ndest_constraints);
345
11.1k
  free(id);
346
11.1k
}
347
348
/*
349
 * Match 'key' against the key/CA list in a destination constraint hop
350
 * Returns 0 on success or -1 otherwise.
351
 */
352
static int
353
match_key_hop(const char *tag, const struct sshkey *key,
354
    const struct dest_constraint_hop *dch)
355
0
{
356
0
  const char *reason = NULL;
357
0
  const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
358
0
  u_int i;
359
0
  char *fp;
360
361
0
  if (key == NULL)
362
0
    return -1;
363
  /* XXX logspam */
364
0
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
365
0
      SSH_FP_DEFAULT)) == NULL)
366
0
    fatal_f("fingerprint failed");
367
0
  debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
368
0
      tag, hostname, sshkey_type(key), fp, dch->nkeys);
369
0
  free(fp);
370
0
  for (i = 0; i < dch->nkeys; i++) {
371
0
    if (dch->keys[i] == NULL)
372
0
      return -1;
373
    /* XXX logspam */
374
0
    if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
375
0
        SSH_FP_DEFAULT)) == NULL)
376
0
      fatal_f("fingerprint failed");
377
0
    debug3_f("%s: key %u: %s%s %s", tag, i,
378
0
        dch->key_is_ca[i] ? "CA " : "",
379
0
        sshkey_type(dch->keys[i]), fp);
380
0
    free(fp);
381
0
    if (!sshkey_is_cert(key)) {
382
      /* plain key */
383
0
      if (dch->key_is_ca[i] ||
384
0
          !sshkey_equal(key, dch->keys[i]))
385
0
        continue;
386
0
      return 0;
387
0
    }
388
    /* certificate */
389
0
    if (!dch->key_is_ca[i])
390
0
      continue;
391
0
    if (key->cert == NULL || key->cert->signature_key == NULL)
392
0
      return -1; /* shouldn't happen */
393
0
    if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
394
0
      continue;
395
0
    if (sshkey_cert_check_host(key, hostname, 1,
396
0
        SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
397
0
      debug_f("cert %s / hostname %s rejected: %s",
398
0
          key->cert->key_id, hostname, reason);
399
0
      continue;
400
0
    }
401
0
    return 0;
402
0
  }
403
0
  return -1;
404
0
}
405
406
/* Check destination constraints on an identity against the hostkey/user */
407
static int
408
permitted_by_dest_constraints(const struct sshkey *fromkey,
409
    const struct sshkey *tokey, Identity *id, const char *user,
410
    const char **hostnamep)
411
0
{
412
0
  size_t i;
413
0
  struct dest_constraint *d;
414
415
0
  if (hostnamep != NULL)
416
0
    *hostnamep = NULL;
417
0
  for (i = 0; i < id->ndest_constraints; i++) {
418
0
    d = id->dest_constraints + i;
419
    /* XXX remove logspam */
420
0
    debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
421
0
        i, d->from.user ? d->from.user : "",
422
0
        d->from.user ? "@" : "",
423
0
        d->from.hostname ? d->from.hostname : "(ORIGIN)",
424
0
        d->from.nkeys,
425
0
        d->to.user ? d->to.user : "", d->to.user ? "@" : "",
426
0
        d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
427
428
    /* Match 'from' key */
429
0
    if (fromkey == NULL) {
430
      /* We are matching the first hop */
431
0
      if (d->from.hostname != NULL || d->from.nkeys != 0)
432
0
        continue;
433
0
    } else if (match_key_hop("from", fromkey, &d->from) != 0)
434
0
      continue;
435
436
    /* Match 'to' key */
437
0
    if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
438
0
      continue;
439
440
    /* Match user if specified */
441
0
    if (d->to.user != NULL && user != NULL &&
442
0
        !match_pattern(user, d->to.user))
443
0
      continue;
444
445
    /* successfully matched this constraint */
446
0
    if (hostnamep != NULL)
447
0
      *hostnamep = d->to.hostname;
448
0
    debug2_f("allowed for hostname %s",
449
0
        d->to.hostname == NULL ? "*" : d->to.hostname);
450
0
    return 0;
451
0
  }
452
  /* no match */
453
0
  debug2_f("%s identity \"%s\" not permitted for this destination",
454
0
      sshkey_type(id->key), id->comment);
455
0
  return -1;
456
0
}
457
458
/*
459
 * Check whether hostkeys on a SocketEntry and the optionally specified user
460
 * are permitted by the destination constraints on the Identity.
461
 * Returns 0 on success or -1 otherwise.
462
 */
463
static int
464
identity_permitted(Identity *id, SocketEntry *e, char *user,
465
    const char **forward_hostnamep, const char **last_hostnamep)
466
12.1k
{
467
12.1k
  size_t i;
468
12.1k
  const char **hp;
469
12.1k
  struct hostkey_sid *hks;
470
12.1k
  const struct sshkey *fromkey = NULL;
471
12.1k
  const char *test_user;
472
12.1k
  char *fp1, *fp2;
473
474
  /* XXX remove logspam */
475
12.1k
  debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
476
12.1k
      "%zu constraints", sshkey_type(id->key), id->comment,
477
12.1k
      e->nsession_ids, id->ndest_constraints);
478
12.1k
  if (id->ndest_constraints == 0)
479
12.1k
    return 0; /* unconstrained */
480
0
  if (e->session_bind_attempted && e->nsession_ids == 0) {
481
0
    error_f("previous session bind failed on socket");
482
0
    return -1;
483
0
  }
484
0
  if (e->nsession_ids == 0)
485
0
    return 0; /* local use */
486
  /*
487
   * Walk through the hops recorded by session_id and try to find a
488
   * constraint that satisfies each.
489
   */
490
0
  for (i = 0; i < e->nsession_ids; i++) {
491
0
    hks = e->session_ids + i;
492
0
    if (hks->key == NULL)
493
0
      fatal_f("internal error: no bound key");
494
    /* XXX remove logspam */
495
0
    fp1 = fp2 = NULL;
496
0
    if (fromkey != NULL &&
497
0
        (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
498
0
        SSH_FP_DEFAULT)) == NULL)
499
0
      fatal_f("fingerprint failed");
500
0
    if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
501
0
        SSH_FP_DEFAULT)) == NULL)
502
0
      fatal_f("fingerprint failed");
503
0
    debug3_f("socketentry fd=%d, entry %zu %s, "
504
0
        "from hostkey %s %s to user %s hostkey %s %s",
505
0
        e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
506
0
        fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
507
0
        fromkey ? fp1 : "", user ? user : "(ANY)",
508
0
        sshkey_type(hks->key), fp2);
509
0
    free(fp1);
510
0
    free(fp2);
511
    /*
512
     * Record the hostnames for the initial forwarding and
513
     * the final destination.
514
     */
515
0
    hp = NULL;
516
0
    if (i == e->nsession_ids - 1)
517
0
      hp = last_hostnamep;
518
0
    else if (i == 0)
519
0
      hp = forward_hostnamep;
520
    /* Special handling for final recorded binding */
521
0
    test_user = NULL;
522
0
    if (i == e->nsession_ids - 1) {
523
      /* Can only check user at final hop */
524
0
      test_user = user;
525
      /*
526
       * user is only presented for signature requests.
527
       * If this is the case, make sure last binding is not
528
       * for a forwarding.
529
       */
530
0
      if (hks->forwarded && user != NULL) {
531
0
        error_f("tried to sign on forwarding hop");
532
0
        return -1;
533
0
      }
534
0
    } else if (!hks->forwarded) {
535
0
      error_f("tried to forward though signing bind");
536
0
      return -1;
537
0
    }
538
0
    if (permitted_by_dest_constraints(fromkey, hks->key, id,
539
0
        test_user, hp) != 0)
540
0
      return -1;
541
0
    fromkey = hks->key;
542
0
  }
543
  /*
544
   * Another special case: if the last bound session ID was for a
545
   * forwarding, and this function is not being called to check a sign
546
   * request (i.e. no 'user' supplied), then only permit the key if
547
   * there is a permission that would allow it to be used at another
548
   * destination. This hides keys that are allowed to be used to
549
   * authenticate *to* a host but not permitted for *use* beyond it.
550
   */
551
0
  hks = &e->session_ids[e->nsession_ids - 1];
552
0
  if (hks->forwarded && user == NULL &&
553
0
      permitted_by_dest_constraints(hks->key, NULL, id,
554
0
      NULL, NULL) != 0) {
555
0
    debug3_f("key permitted at host but not after");
556
0
    return -1;
557
0
  }
558
559
  /* success */
560
0
  return 0;
561
0
}
562
563
static int
564
socket_is_remote(SocketEntry *e)
565
28
{
566
28
  return e->session_bind_attempted || (e->nsession_ids != 0);
567
28
}
568
569
/* return matching private key for given public key */
570
static Identity *
571
lookup_identity(struct sshkey *key)
572
2.15k
{
573
2.15k
  Identity *id;
574
575
28.4k
  TAILQ_FOREACH(id, &idtab->idlist, next) {
576
28.4k
    if (sshkey_equal(key, id->key))
577
1.07k
      return (id);
578
28.4k
  }
579
1.07k
  return (NULL);
580
2.15k
}
581
582
/* Check confirmation of keysign request */
583
static int
584
confirm_key(Identity *id, const char *extra)
585
0
{
586
0
  char *p;
587
0
  int ret = -1;
588
589
0
  p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
590
0
  if (p != NULL &&
591
0
      ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
592
0
      id->comment, p,
593
0
      extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
594
0
    ret = 0;
595
0
  free(p);
596
597
0
  return (ret);
598
0
}
599
600
static void
601
send_status(SocketEntry *e, int success)
602
24.6k
{
603
24.6k
  int r;
604
605
24.6k
  if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
606
24.6k
      (r = sshbuf_put_u8(e->output, success ?
607
22.5k
      SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
608
0
    fatal_fr(r, "compose");
609
24.6k
}
610
611
/* send list of supported public keys to 'client' */
612
static void
613
process_request_identities(SocketEntry *e)
614
1.92k
{
615
1.92k
  Identity *id;
616
1.92k
  struct sshbuf *msg, *keys;
617
1.92k
  int r;
618
1.92k
  u_int i = 0, nentries = 0;
619
1.92k
  char *fp;
620
621
1.92k
  debug2_f("entering");
622
623
1.92k
  if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
624
0
    fatal_f("sshbuf_new failed");
625
11.2k
  TAILQ_FOREACH(id, &idtab->idlist, next) {
626
11.2k
    if ((fp = sshkey_fingerprint(id->key, SSH_FP_HASH_DEFAULT,
627
11.2k
        SSH_FP_DEFAULT)) == NULL)
628
0
      fatal_f("fingerprint failed");
629
11.2k
    debug_f("key %u / %u: %s %s", i++, idtab->nentries,
630
11.2k
        sshkey_ssh_name(id->key), fp);
631
11.2k
    dump_dest_constraints(__func__,
632
11.2k
        id->dest_constraints, id->ndest_constraints);
633
11.2k
    free(fp);
634
    /* identity not visible, don't include in response */
635
11.2k
    if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
636
0
      continue;
637
11.2k
    if ((r = sshkey_puts(id->key, keys)) != 0 ||
638
11.2k
        (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
639
0
      error_fr(r, "compose key/comment");
640
0
      continue;
641
0
    }
642
11.2k
    nentries++;
643
11.2k
  }
644
1.92k
  debug2_f("replying with %u allowed of %u available keys",
645
1.92k
      nentries, idtab->nentries);
646
1.92k
  if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
647
1.92k
      (r = sshbuf_put_u32(msg, nentries)) != 0 ||
648
1.92k
      (r = sshbuf_putb(msg, keys)) != 0)
649
0
    fatal_fr(r, "compose");
650
1.92k
  if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
651
0
    fatal_fr(r, "enqueue");
652
1.92k
  sshbuf_free(msg);
653
1.92k
  sshbuf_free(keys);
654
1.92k
}
655
656
657
static char *
658
agent_decode_alg(struct sshkey *key, u_int flags)
659
125
{
660
125
  if (key->type == KEY_RSA) {
661
43
    if (flags & SSH_AGENT_RSA_SHA2_256)
662
22
      return "rsa-sha2-256";
663
21
    else if (flags & SSH_AGENT_RSA_SHA2_512)
664
7
      return "rsa-sha2-512";
665
82
  } else if (key->type == KEY_RSA_CERT) {
666
0
    if (flags & SSH_AGENT_RSA_SHA2_256)
667
0
      return "rsa-sha2-256-cert-v01@openssh.com";
668
0
    else if (flags & SSH_AGENT_RSA_SHA2_512)
669
0
      return "rsa-sha2-512-cert-v01@openssh.com";
670
0
  }
671
96
  return NULL;
672
125
}
673
674
/*
675
 * Attempt to parse the contents of a buffer as a SSH publickey userauth
676
 * request, checking its contents for consistency and matching the embedded
677
 * key against the one that is being used for signing.
678
 * Note: does not modify msg buffer.
679
 * Optionally extract the username, session ID and/or hostkey from the request.
680
 */
681
static int
682
parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
683
    char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
684
0
{
685
0
  struct sshbuf *b = NULL, *sess_id = NULL;
686
0
  char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
687
0
  int r;
688
0
  u_char t, sig_follows;
689
0
  struct sshkey *mkey = NULL, *hostkey = NULL;
690
691
0
  if (userp != NULL)
692
0
    *userp = NULL;
693
0
  if (sess_idp != NULL)
694
0
    *sess_idp = NULL;
695
0
  if (hostkeyp != NULL)
696
0
    *hostkeyp = NULL;
697
0
  if ((b = sshbuf_fromb(msg)) == NULL)
698
0
    fatal_f("sshbuf_fromb");
699
700
  /* SSH userauth request */
701
0
  if ((r = sshbuf_froms(b, &sess_id)) != 0)
702
0
    goto out;
703
0
  if (sshbuf_len(sess_id) == 0) {
704
0
    r = SSH_ERR_INVALID_FORMAT;
705
0
    goto out;
706
0
  }
707
0
  if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
708
0
      (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
709
0
      (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
710
0
      (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
711
0
      (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
712
0
      (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
713
0
      (r = sshkey_froms(b, &mkey)) != 0) /* key */
714
0
    goto out;
715
0
  if (t != SSH2_MSG_USERAUTH_REQUEST ||
716
0
      sig_follows != 1 ||
717
0
      strcmp(service, "ssh-connection") != 0 ||
718
0
      !sshkey_equal(expected_key, mkey) ||
719
0
      sshkey_type_from_name(pkalg) != expected_key->type) {
720
0
    r = SSH_ERR_INVALID_FORMAT;
721
0
    goto out;
722
0
  }
723
0
  if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
724
0
    if ((r = sshkey_froms(b, &hostkey)) != 0)
725
0
      goto out;
726
0
  } else if (strcmp(method, "publickey") != 0) {
727
0
    r = SSH_ERR_INVALID_FORMAT;
728
0
    goto out;
729
0
  }
730
0
  if (sshbuf_len(b) != 0) {
731
0
    r = SSH_ERR_INVALID_FORMAT;
732
0
    goto out;
733
0
  }
734
  /* success */
735
0
  r = 0;
736
0
  debug3_f("well formed userauth");
737
0
  if (userp != NULL) {
738
0
    *userp = user;
739
0
    user = NULL;
740
0
  }
741
0
  if (sess_idp != NULL) {
742
0
    *sess_idp = sess_id;
743
0
    sess_id = NULL;
744
0
  }
745
0
  if (hostkeyp != NULL) {
746
0
    *hostkeyp = hostkey;
747
0
    hostkey = NULL;
748
0
  }
749
0
 out:
750
0
  sshbuf_free(b);
751
0
  sshbuf_free(sess_id);
752
0
  free(user);
753
0
  free(service);
754
0
  free(method);
755
0
  free(pkalg);
756
0
  sshkey_free(mkey);
757
0
  sshkey_free(hostkey);
758
0
  return r;
759
0
}
760
761
/*
762
 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
763
 * Note: does not modify buffer.
764
 */
765
static int
766
parse_sshsig_request(struct sshbuf *msg)
767
0
{
768
0
  int r;
769
0
  struct sshbuf *b;
770
771
0
  if ((b = sshbuf_fromb(msg)) == NULL)
772
0
    fatal_f("sshbuf_fromb");
773
774
0
  if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
775
0
      (r = sshbuf_consume(b, 6)) != 0 ||
776
0
      (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
777
0
      (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
778
0
      (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
779
0
      (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
780
0
    goto out;
781
0
  if (sshbuf_len(b) != 0) {
782
0
    r = SSH_ERR_INVALID_FORMAT;
783
0
    goto out;
784
0
  }
785
  /* success */
786
0
  r = 0;
787
0
 out:
788
0
  sshbuf_free(b);
789
0
  return r;
790
0
}
791
792
/*
793
 * This function inspects a message to be signed by a FIDO key that has a
794
 * web-like application string (i.e. one that does not begin with "ssh:".
795
 * It checks that the message is one of those expected for SSH operations
796
 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
797
 * for the web.
798
 */
799
static int
800
check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
801
0
{
802
0
  if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
803
0
    debug_f("signed data matches public key userauth request");
804
0
    return 1;
805
0
  }
806
0
  if (parse_sshsig_request(data) == 0) {
807
0
    debug_f("signed data matches SSHSIG signature request");
808
0
    return 1;
809
0
  }
810
811
  /* XXX check CA signature operation */
812
813
0
  error("web-origin key attempting to sign non-SSH message");
814
0
  return 0;
815
0
}
816
817
static int
818
buf_equal(const struct sshbuf *a, const struct sshbuf *b)
819
0
{
820
0
  if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
821
0
    return SSH_ERR_INVALID_ARGUMENT;
822
0
  if (sshbuf_len(a) != sshbuf_len(b))
823
0
    return SSH_ERR_INVALID_FORMAT;
824
0
  if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
825
0
    return SSH_ERR_INVALID_FORMAT;
826
0
  return 0;
827
0
}
828
829
/* ssh2 only */
830
static void
831
process_sign_request2(SocketEntry *e)
832
3.41k
{
833
3.41k
  u_char *signature = NULL;
834
3.41k
  size_t slen = 0;
835
3.41k
  u_int compat = 0, flags;
836
3.41k
  int r, ok = -1, retried = 0;
837
3.41k
  char *fp = NULL, *pin = NULL, *prompt = NULL;
838
3.41k
  char *user = NULL, *sig_dest = NULL;
839
3.41k
  const char *fwd_host = NULL, *dest_host = NULL;
840
3.41k
  struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
841
3.41k
  struct sshkey *key = NULL, *hostkey = NULL;
842
3.41k
  struct identity *id;
843
3.41k
  struct notifier_ctx *notifier = NULL;
844
845
3.41k
  debug_f("entering");
846
847
3.41k
  if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
848
0
    fatal_f("sshbuf_new failed");
849
3.41k
  if ((r = sshkey_froms(e->request, &key)) != 0 ||
850
381
      (r = sshbuf_get_stringb(e->request, data)) != 0 ||
851
3.13k
      (r = sshbuf_get_u32(e->request, &flags)) != 0) {
852
3.13k
    error_fr(r, "parse");
853
3.13k
    goto send;
854
3.13k
  }
855
856
272
  if ((id = lookup_identity(key)) == NULL) {
857
147
    verbose_f("%s key not found", sshkey_type(key));
858
147
    goto send;
859
147
  }
860
125
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
861
125
      SSH_FP_DEFAULT)) == NULL)
862
0
    fatal_f("fingerprint failed");
863
864
125
  if (id->ndest_constraints != 0) {
865
0
    if (e->nsession_ids == 0) {
866
0
      logit_f("refusing use of destination-constrained key "
867
0
          "to sign on unbound connection");
868
0
      goto send;
869
0
    }
870
0
    if (parse_userauth_request(data, key, &user, &sid,
871
0
        &hostkey) != 0) {
872
0
      logit_f("refusing use of destination-constrained key "
873
0
         "to sign an unidentified signature");
874
0
      goto send;
875
0
    }
876
    /* XXX logspam */
877
0
    debug_f("user=%s", user);
878
0
    if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
879
0
      goto send;
880
    /* XXX display fwd_host/dest_host in askpass UI */
881
    /*
882
     * Ensure that the session ID is the most recent one
883
     * registered on the socket - it should have been bound by
884
     * ssh immediately before userauth.
885
     */
886
0
    if (buf_equal(sid,
887
0
        e->session_ids[e->nsession_ids - 1].sid) != 0) {
888
0
      error_f("unexpected session ID (%zu listed) on "
889
0
          "signature request for target user %s with "
890
0
          "key %s %s", e->nsession_ids, user,
891
0
          sshkey_type(id->key), fp);
892
0
      goto send;
893
0
    }
894
    /*
895
     * Ensure that the hostkey embedded in the signature matches
896
     * the one most recently bound to the socket. An exception is
897
     * made for the initial forwarding hop.
898
     */
899
0
    if (e->nsession_ids > 1 && hostkey == NULL) {
900
0
      error_f("refusing use of destination-constrained key: "
901
0
          "no hostkey recorded in signature for forwarded "
902
0
          "connection");
903
0
      goto send;
904
0
    }
905
0
    if (hostkey != NULL && !sshkey_equal(hostkey,
906
0
        e->session_ids[e->nsession_ids - 1].key)) {
907
0
      error_f("refusing use of destination-constrained key: "
908
0
          "mismatch between hostkey in request and most "
909
0
          "recently bound session");
910
0
      goto send;
911
0
    }
912
0
    xasprintf(&sig_dest, "public key authentication request for "
913
0
        "user \"%s\" to listed host", user);
914
0
  }
915
125
  if (id->confirm && confirm_key(id, sig_dest) != 0) {
916
0
    verbose_f("user refused key");
917
0
    goto send;
918
0
  }
919
125
  if (sshkey_is_sk(id->key)) {
920
73
    if (restrict_websafe &&
921
73
        match_pattern_list(id->key->sk_application,
922
73
        websafe_allowlist, 0) != 1 &&
923
0
        !check_websafe_message_contents(key, data)) {
924
      /* error already logged */
925
0
      goto send;
926
0
    }
927
73
    if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
928
64
      notifier = notify_start(0,
929
64
          "Confirm user presence for key %s %s%s%s",
930
64
          sshkey_type(id->key), fp,
931
64
          sig_dest == NULL ? "" : "\n",
932
64
          sig_dest == NULL ? "" : sig_dest);
933
64
    }
934
73
  }
935
125
 retry_pin:
936
125
  if ((r = sshkey_sign(id->key, &signature, &slen,
937
125
      sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
938
125
      id->sk_provider, pin, compat)) != 0) {
939
9
    debug_fr(r, "sshkey_sign");
940
9
    if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
941
9
        r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
942
0
      notify_complete(notifier, NULL);
943
0
      notifier = NULL;
944
      /* XXX include sig_dest */
945
0
      xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
946
0
          (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
947
0
          " and confirm user presence " : " ",
948
0
          sshkey_type(id->key), fp);
949
0
      pin = read_passphrase(prompt, RP_USE_ASKPASS);
950
0
      retried = 1;
951
0
      goto retry_pin;
952
0
    }
953
9
    error_fr(r, "sshkey_sign");
954
9
    goto send;
955
9
  }
956
  /* Success */
957
116
  ok = 0;
958
116
  debug_f("good signature");
959
3.41k
 send:
960
3.41k
  notify_complete(notifier, "User presence confirmed");
961
962
3.41k
  if (ok == 0) {
963
116
    if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
964
116
        (r = sshbuf_put_string(msg, signature, slen)) != 0)
965
0
      fatal_fr(r, "compose");
966
3.29k
  } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
967
0
    fatal_fr(r, "compose failure");
968
969
3.41k
  if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
970
0
    fatal_fr(r, "enqueue");
971
972
3.41k
  sshbuf_free(sid);
973
3.41k
  sshbuf_free(data);
974
3.41k
  sshbuf_free(msg);
975
3.41k
  sshkey_free(key);
976
3.41k
  sshkey_free(hostkey);
977
3.41k
  free(fp);
978
3.41k
  free(signature);
979
3.41k
  free(sig_dest);
980
3.41k
  free(user);
981
3.41k
  free(prompt);
982
3.41k
  if (pin != NULL)
983
0
    freezero(pin, strlen(pin));
984
3.41k
}
985
986
/* shared */
987
static void
988
process_remove_identity(SocketEntry *e)
989
1.78k
{
990
1.78k
  int r, success = 0;
991
1.78k
  struct sshkey *key = NULL;
992
1.78k
  Identity *id;
993
994
1.78k
  debug2_f("entering");
995
1.78k
  if ((r = sshkey_froms(e->request, &key)) != 0) {
996
1.73k
    error_fr(r, "parse key");
997
1.73k
    goto done;
998
1.73k
  }
999
56
  if ((id = lookup_identity(key)) == NULL) {
1000
55
    debug_f("key not found");
1001
55
    goto done;
1002
55
  }
1003
  /* identity not visible, cannot be removed */
1004
1
  if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1005
0
    goto done; /* error already logged */
1006
  /* We have this key, free it. */
1007
1
  if (idtab->nentries < 1)
1008
0
    fatal_f("internal error: nentries %d", idtab->nentries);
1009
1
  TAILQ_REMOVE(&idtab->idlist, id, next);
1010
1
  free_identity(id);
1011
1
  idtab->nentries--;
1012
1
  success = 1;
1013
1.78k
 done:
1014
1.78k
  sshkey_free(key);
1015
1.78k
  send_status(e, success);
1016
1.78k
}
1017
1018
static void
1019
remove_all_identities(void)
1020
197
{
1021
197
  Identity *id;
1022
1023
197
  debug2_f("entering");
1024
  /* Loop over all identities and clear the keys. */
1025
1.56k
  for (id = TAILQ_FIRST(&idtab->idlist); id;
1026
1.36k
      id = TAILQ_FIRST(&idtab->idlist)) {
1027
1.36k
    TAILQ_REMOVE(&idtab->idlist, id, next);
1028
1.36k
    free_identity(id);
1029
1.36k
  }
1030
1031
  /* Mark that there are no identities. */
1032
197
  idtab->nentries = 0;
1033
197
}
1034
1035
static void
1036
process_remove_all_identities(SocketEntry *e)
1037
197
{
1038
197
  remove_all_identities();
1039
1040
  /* Send success. */
1041
197
  send_status(e, 1);
1042
197
}
1043
1044
/* removes expired keys and returns number of seconds until the next expiry */
1045
static time_t
1046
reaper(void)
1047
0
{
1048
0
  time_t deadline = 0, now = monotime();
1049
0
  Identity *id, *nxt;
1050
1051
0
  for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1052
0
    nxt = TAILQ_NEXT(id, next);
1053
0
    if (id->death == 0)
1054
0
      continue;
1055
0
    if (now >= id->death) {
1056
0
      debug("expiring key '%s'", id->comment);
1057
0
      TAILQ_REMOVE(&idtab->idlist, id, next);
1058
0
      free_identity(id);
1059
0
      idtab->nentries--;
1060
0
    } else
1061
0
      deadline = (deadline == 0) ? id->death :
1062
0
          MINIMUM(deadline, id->death);
1063
0
  }
1064
0
  if (deadline == 0 || deadline <= now)
1065
0
    return 0;
1066
0
  else
1067
0
    return (deadline - now);
1068
0
}
1069
1070
static int
1071
parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
1072
0
{
1073
0
  u_char key_is_ca;
1074
0
  size_t elen = 0;
1075
0
  int r;
1076
0
  struct sshkey *k = NULL;
1077
0
  char *fp;
1078
1079
0
  memset(dch, '\0', sizeof(*dch));
1080
0
  if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
1081
0
      (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
1082
0
      (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1083
0
    error_fr(r, "parse");
1084
0
    goto out;
1085
0
  }
1086
0
  if (elen != 0) {
1087
0
    error_f("unsupported extensions (len %zu)", elen);
1088
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1089
0
    goto out;
1090
0
  }
1091
0
  if (*dch->hostname == '\0') {
1092
0
    free(dch->hostname);
1093
0
    dch->hostname = NULL;
1094
0
  }
1095
0
  if (*dch->user == '\0') {
1096
0
    free(dch->user);
1097
0
    dch->user = NULL;
1098
0
  }
1099
0
  while (sshbuf_len(b) != 0) {
1100
0
    dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1101
0
        dch->nkeys + 1, sizeof(*dch->keys));
1102
0
    dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1103
0
        dch->nkeys + 1, sizeof(*dch->key_is_ca));
1104
0
    if ((r = sshkey_froms(b, &k)) != 0 ||
1105
0
        (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1106
0
      goto out;
1107
0
    if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1108
0
        SSH_FP_DEFAULT)) == NULL)
1109
0
      fatal_f("fingerprint failed");
1110
0
    debug3_f("%s%s%s: adding %skey %s %s",
1111
0
        dch->user == NULL ? "" : dch->user,
1112
0
        dch->user == NULL ? "" : "@",
1113
0
        dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1114
0
    free(fp);
1115
0
    dch->keys[dch->nkeys] = k;
1116
0
    dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1117
0
    dch->nkeys++;
1118
0
    k = NULL; /* transferred */
1119
0
  }
1120
  /* success */
1121
0
  r = 0;
1122
0
 out:
1123
0
  sshkey_free(k);
1124
0
  return r;
1125
0
}
1126
1127
static int
1128
parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1129
0
{
1130
0
  struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1131
0
  int r;
1132
0
  size_t elen = 0;
1133
1134
0
  debug3_f("entering");
1135
1136
0
  memset(dc, '\0', sizeof(*dc));
1137
0
  if ((r = sshbuf_froms(m, &b)) != 0 ||
1138
0
      (r = sshbuf_froms(b, &frombuf)) != 0 ||
1139
0
      (r = sshbuf_froms(b, &tobuf)) != 0 ||
1140
0
      (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1141
0
    error_fr(r, "parse");
1142
0
    goto out;
1143
0
  }
1144
0
  if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1145
0
      (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1146
0
    goto out; /* already logged */
1147
0
  if (elen != 0) {
1148
0
    error_f("unsupported extensions (len %zu)", elen);
1149
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1150
0
    goto out;
1151
0
  }
1152
0
  debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1153
0
      dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1154
0
      dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1155
0
      dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1156
  /* check consistency */
1157
0
  if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1158
0
      dc->from.user != NULL) {
1159
0
    error_f("inconsistent \"from\" specification");
1160
0
    r = SSH_ERR_INVALID_FORMAT;
1161
0
    goto out;
1162
0
  }
1163
0
  if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1164
0
    error_f("incomplete \"to\" specification");
1165
0
    r = SSH_ERR_INVALID_FORMAT;
1166
0
    goto out;
1167
0
  }
1168
  /* success */
1169
0
  r = 0;
1170
0
 out:
1171
0
  sshbuf_free(b);
1172
0
  sshbuf_free(frombuf);
1173
0
  sshbuf_free(tobuf);
1174
0
  return r;
1175
0
}
1176
1177
static int
1178
parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1179
    struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp,
1180
    struct sshkey ***certs, size_t *ncerts)
1181
12
{
1182
12
  char *ext_name = NULL;
1183
12
  int r;
1184
12
  struct sshbuf *b = NULL;
1185
12
  u_char v;
1186
12
  struct sshkey *k;
1187
1188
12
  if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1189
3
    error_fr(r, "parse constraint extension");
1190
3
    goto out;
1191
3
  }
1192
9
  debug_f("constraint ext %s", ext_name);
1193
9
  if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1194
3
    if (sk_providerp == NULL) {
1195
0
      error_f("%s not valid here", ext_name);
1196
0
      r = SSH_ERR_INVALID_FORMAT;
1197
0
      goto out;
1198
0
    }
1199
3
    if (*sk_providerp != NULL) {
1200
0
      error_f("%s already set", ext_name);
1201
0
      r = SSH_ERR_INVALID_FORMAT;
1202
0
      goto out;
1203
0
    }
1204
3
    if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1205
3
      error_fr(r, "parse %s", ext_name);
1206
3
      goto out;
1207
3
    }
1208
6
  } else if (strcmp(ext_name,
1209
6
      "restrict-destination-v00@openssh.com") == 0) {
1210
0
    if (*dcsp != NULL) {
1211
0
      error_f("%s already set", ext_name);
1212
0
      r = SSH_ERR_INVALID_FORMAT;
1213
0
      goto out;
1214
0
    }
1215
0
    if ((r = sshbuf_froms(m, &b)) != 0) {
1216
0
      error_fr(r, "parse %s outer", ext_name);
1217
0
      goto out;
1218
0
    }
1219
0
    while (sshbuf_len(b) != 0) {
1220
0
      if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1221
0
        error_f("too many %s constraints", ext_name);
1222
0
        r = SSH_ERR_INVALID_FORMAT;
1223
0
        goto out;
1224
0
      }
1225
0
      *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1226
0
          sizeof(**dcsp));
1227
0
      if ((r = parse_dest_constraint(b,
1228
0
          *dcsp + (*ndcsp)++)) != 0)
1229
0
        goto out; /* error already logged */
1230
0
    }
1231
6
  } else if (strcmp(ext_name,
1232
6
      "associated-certs-v00@openssh.com") == 0) {
1233
0
    if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) {
1234
0
      error_f("%s not valid here", ext_name);
1235
0
      r = SSH_ERR_INVALID_FORMAT;
1236
0
      goto out;
1237
0
    }
1238
0
    if (*certs != NULL) {
1239
0
      error_f("%s already set", ext_name);
1240
0
      r = SSH_ERR_INVALID_FORMAT;
1241
0
      goto out;
1242
0
    }
1243
0
    if ((r = sshbuf_get_u8(m, &v)) != 0 ||
1244
0
        (r = sshbuf_froms(m, &b)) != 0) {
1245
0
      error_fr(r, "parse %s", ext_name);
1246
0
      goto out;
1247
0
    }
1248
0
    *cert_onlyp = v != 0;
1249
0
    while (sshbuf_len(b) != 0) {
1250
0
      if (*ncerts >= AGENT_MAX_EXT_CERTS) {
1251
0
        error_f("too many %s constraints", ext_name);
1252
0
        r = SSH_ERR_INVALID_FORMAT;
1253
0
        goto out;
1254
0
      }
1255
0
      *certs = xrecallocarray(*certs, *ncerts, *ncerts + 1,
1256
0
          sizeof(**certs));
1257
0
      if ((r = sshkey_froms(b, &k)) != 0) {
1258
0
        error_fr(r, "parse key");
1259
0
        goto out;
1260
0
      }
1261
0
      (*certs)[(*ncerts)++] = k;
1262
0
    }
1263
6
  } else {
1264
6
    error_f("unsupported constraint \"%s\"", ext_name);
1265
6
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1266
6
    goto out;
1267
6
  }
1268
  /* success */
1269
0
  r = 0;
1270
12
 out:
1271
12
  free(ext_name);
1272
12
  sshbuf_free(b);
1273
12
  return r;
1274
0
}
1275
1276
static int
1277
parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1278
    u_int *secondsp, int *confirmp, char **sk_providerp,
1279
    struct dest_constraint **dcsp, size_t *ndcsp,
1280
    int *cert_onlyp, size_t *ncerts, struct sshkey ***certs)
1281
1.92k
{
1282
1.92k
  u_char ctype;
1283
1.92k
  int r;
1284
1.92k
  u_int seconds;
1285
1286
1.95k
  while (sshbuf_len(m)) {
1287
104
    if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1288
0
      error_fr(r, "parse constraint type");
1289
0
      goto out;
1290
0
    }
1291
104
    switch (ctype) {
1292
74
    case SSH_AGENT_CONSTRAIN_LIFETIME:
1293
74
      if (*deathp != 0) {
1294
20
        error_f("lifetime already set");
1295
20
        r = SSH_ERR_INVALID_FORMAT;
1296
20
        goto out;
1297
20
      }
1298
54
      if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1299
31
        error_fr(r, "parse lifetime constraint");
1300
31
        goto out;
1301
31
      }
1302
23
      *deathp = monotime() + seconds;
1303
23
      *secondsp = seconds;
1304
23
      break;
1305
5
    case SSH_AGENT_CONSTRAIN_CONFIRM:
1306
5
      if (*confirmp != 0) {
1307
1
        error_f("confirm already set");
1308
1
        r = SSH_ERR_INVALID_FORMAT;
1309
1
        goto out;
1310
1
      }
1311
4
      *confirmp = 1;
1312
4
      break;
1313
12
    case SSH_AGENT_CONSTRAIN_EXTENSION:
1314
12
      if ((r = parse_key_constraint_extension(m,
1315
12
          sk_providerp, dcsp, ndcsp,
1316
12
          cert_onlyp, certs, ncerts)) != 0)
1317
12
        goto out; /* error already logged */
1318
0
      break;
1319
13
    default:
1320
13
      error_f("Unknown constraint %d", ctype);
1321
13
      r = SSH_ERR_FEATURE_UNSUPPORTED;
1322
13
      goto out;
1323
104
    }
1324
104
  }
1325
  /* success */
1326
1.85k
  r = 0;
1327
1.92k
 out:
1328
1.92k
  return r;
1329
1.85k
}
1330
1331
static void
1332
process_add_identity(SocketEntry *e)
1333
5.83k
{
1334
5.83k
  Identity *id;
1335
5.83k
  int success = 0, confirm = 0;
1336
5.83k
  char *fp, *comment = NULL, *sk_provider = NULL;
1337
5.83k
  char canonical_provider[PATH_MAX];
1338
5.83k
  time_t death = 0;
1339
5.83k
  u_int seconds = 0;
1340
5.83k
  struct dest_constraint *dest_constraints = NULL;
1341
5.83k
  size_t ndest_constraints = 0;
1342
5.83k
  struct sshkey *k = NULL;
1343
5.83k
  int r = SSH_ERR_INTERNAL_ERROR;
1344
1345
5.83k
  debug2_f("entering");
1346
5.83k
  if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1347
2.25k
      k == NULL ||
1348
3.99k
      (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1349
3.99k
    error_fr(r, "parse");
1350
3.99k
    goto out;
1351
3.99k
  }
1352
1.84k
  if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1353
1.84k
      &sk_provider, &dest_constraints, &ndest_constraints,
1354
1.84k
      NULL, NULL, NULL) != 0) {
1355
22
    error_f("failed to parse constraints");
1356
22
    sshbuf_reset(e->request);
1357
22
    goto out;
1358
22
  }
1359
1.82k
  dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1360
1361
1.82k
  if (sk_provider != NULL) {
1362
0
    if (!sshkey_is_sk(k)) {
1363
0
      error("Cannot add provider: %s is not an "
1364
0
          "authenticator-hosted key", sshkey_type(k));
1365
0
      goto out;
1366
0
    }
1367
0
    if (strcasecmp(sk_provider, "internal") == 0) {
1368
0
      debug_f("internal provider");
1369
0
    } else {
1370
0
      if (socket_is_remote(e) && !remote_add_provider) {
1371
0
        verbose("failed add of SK provider \"%.100s\": "
1372
0
            "remote addition of providers is disabled",
1373
0
            sk_provider);
1374
0
        goto out;
1375
0
      }
1376
0
      if (realpath(sk_provider, canonical_provider) == NULL) {
1377
0
        verbose("failed provider \"%.100s\": "
1378
0
            "realpath: %s", sk_provider,
1379
0
            strerror(errno));
1380
0
        goto out;
1381
0
      }
1382
0
      free(sk_provider);
1383
0
      sk_provider = xstrdup(canonical_provider);
1384
0
      if (match_pattern_list(sk_provider,
1385
0
          allowed_providers, 0) != 1) {
1386
0
        error("Refusing add key: "
1387
0
            "provider %s not allowed", sk_provider);
1388
0
        goto out;
1389
0
      }
1390
0
    }
1391
0
  }
1392
1.82k
  if ((r = sshkey_shield_private(k)) != 0) {
1393
0
    error_fr(r, "shield private");
1394
0
    goto out;
1395
0
  }
1396
1.82k
  if (lifetime && !death)
1397
0
    death = monotime() + lifetime;
1398
1.82k
  if ((id = lookup_identity(k)) == NULL) {
1399
872
    id = xcalloc(1, sizeof(Identity));
1400
872
    TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1401
    /* Increment the number of identities. */
1402
872
    idtab->nentries++;
1403
952
  } else {
1404
    /* identity not visible, do not update */
1405
952
    if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1406
0
      goto out; /* error already logged */
1407
    /* key state might have been updated */
1408
952
    sshkey_free(id->key);
1409
952
    free(id->comment);
1410
952
    free(id->sk_provider);
1411
952
    free_dest_constraints(id->dest_constraints,
1412
952
        id->ndest_constraints);
1413
952
  }
1414
  /* success */
1415
1.82k
  id->key = k;
1416
1.82k
  id->comment = comment;
1417
1.82k
  id->death = death;
1418
1.82k
  id->confirm = confirm;
1419
1.82k
  id->sk_provider = sk_provider;
1420
1.82k
  id->dest_constraints = dest_constraints;
1421
1.82k
  id->ndest_constraints = ndest_constraints;
1422
1423
1.82k
  if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1424
1.82k
      SSH_FP_DEFAULT)) == NULL)
1425
0
    fatal_f("sshkey_fingerprint failed");
1426
1.82k
  debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1427
1.82k
      "(provider: %s) (destination constraints: %zu)",
1428
1.82k
      sshkey_ssh_name(k), fp, comment, seconds, confirm,
1429
1.82k
      sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1430
1.82k
  free(fp);
1431
  /* transferred */
1432
1.82k
  k = NULL;
1433
1.82k
  comment = NULL;
1434
1.82k
  sk_provider = NULL;
1435
1.82k
  dest_constraints = NULL;
1436
1.82k
  ndest_constraints = 0;
1437
1.82k
  success = 1;
1438
5.83k
 out:
1439
5.83k
  free(sk_provider);
1440
5.83k
  free(comment);
1441
5.83k
  sshkey_free(k);
1442
5.83k
  free_dest_constraints(dest_constraints, ndest_constraints);
1443
5.83k
  send_status(e, success);
1444
5.83k
}
1445
1446
/* XXX todo: encrypt sensitive data with passphrase */
1447
static void
1448
process_lock_agent(SocketEntry *e, int lock)
1449
8.52k
{
1450
8.52k
  int r, success = 0, delay;
1451
8.52k
  char *passwd;
1452
8.52k
  u_char passwdhash[LOCK_SIZE];
1453
8.52k
  static u_int fail_count = 0;
1454
8.52k
  size_t pwlen;
1455
1456
8.52k
  debug2_f("entering");
1457
  /*
1458
   * This is deliberately fatal: the user has requested that we lock,
1459
   * but we can't parse their request properly. The only safe thing to
1460
   * do is abort.
1461
   */
1462
8.52k
  if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1463
0
    fatal_fr(r, "parse");
1464
8.52k
  if (pwlen == 0) {
1465
3.74k
    debug("empty password not supported");
1466
4.78k
  } else if (locked && !lock) {
1467
3.31k
    if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1468
3.31k
        passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1469
0
      fatal("bcrypt_pbkdf");
1470
3.31k
    if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1471
3
      debug("agent unlocked");
1472
3
      locked = 0;
1473
3
      fail_count = 0;
1474
3
      explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1475
3
      success = 1;
1476
3.31k
    } else {
1477
      /* delay in 0.1s increments up to 10s */
1478
3.31k
      if (fail_count < 100)
1479
142
        fail_count++;
1480
3.31k
      delay = 100000 * fail_count;
1481
3.31k
      debug("unlock failed, delaying %0.1lf seconds",
1482
3.31k
          (double)delay/1000000);
1483
      // usleep(delay);
1484
3.31k
    }
1485
3.31k
    explicit_bzero(passwdhash, sizeof(passwdhash));
1486
3.31k
  } else if (!locked && lock) {
1487
3
    debug("agent locked");
1488
3
    locked = 1;
1489
3
    arc4random_buf(lock_salt, sizeof(lock_salt));
1490
3
    if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1491
3
        lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1492
0
      fatal("bcrypt_pbkdf");
1493
3
    success = 1;
1494
3
  }
1495
8.52k
  freezero(passwd, pwlen);
1496
8.52k
  send_status(e, success);
1497
8.52k
}
1498
1499
static void
1500
no_identities(SocketEntry *e)
1501
7.32k
{
1502
7.32k
  struct sshbuf *msg;
1503
7.32k
  int r;
1504
1505
7.32k
  if ((msg = sshbuf_new()) == NULL)
1506
0
    fatal_f("sshbuf_new failed");
1507
7.32k
  if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1508
7.32k
      (r = sshbuf_put_u32(msg, 0)) != 0 ||
1509
7.32k
      (r = sshbuf_put_stringb(e->output, msg)) != 0)
1510
0
    fatal_fr(r, "compose");
1511
7.32k
  sshbuf_free(msg);
1512
7.32k
}
1513
1514
#ifdef ENABLE_PKCS11
1515
/* Add an identity to idlist; takes ownership of 'key' and 'comment' */
1516
static void
1517
add_p11_identity(struct sshkey *key, char *comment, const char *provider,
1518
    time_t death, u_int confirm, struct dest_constraint *dest_constraints,
1519
    size_t ndest_constraints)
1520
0
{
1521
0
  Identity *id;
1522
1523
0
  if (lookup_identity(key) != NULL) {
1524
0
    sshkey_free(key);
1525
0
    free(comment);
1526
0
    return;
1527
0
  }
1528
0
  id = xcalloc(1, sizeof(Identity));
1529
0
  id->key = key;
1530
0
  id->comment = comment;
1531
0
  id->provider = xstrdup(provider);
1532
0
  id->death = death;
1533
0
  id->confirm = confirm;
1534
0
  id->dest_constraints = dup_dest_constraints(dest_constraints,
1535
0
      ndest_constraints);
1536
0
  id->ndest_constraints = ndest_constraints;
1537
0
  TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1538
0
  idtab->nentries++;
1539
0
}
1540
1541
static void
1542
process_add_smartcard_key(SocketEntry *e)
1543
301
{
1544
301
  char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1545
301
  char **comments = NULL;
1546
301
  int r, i, count = 0, success = 0, confirm = 0;
1547
301
  u_int seconds = 0;
1548
301
  time_t death = 0;
1549
301
  struct sshkey **keys = NULL, *k;
1550
301
  struct dest_constraint *dest_constraints = NULL;
1551
301
  size_t j, ndest_constraints = 0, ncerts = 0;
1552
301
  struct sshkey **certs = NULL;
1553
301
  int cert_only = 0;
1554
1555
301
  debug2_f("entering");
1556
301
  if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1557
218
      (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1558
218
    error_fr(r, "parse");
1559
218
    goto send;
1560
218
  }
1561
83
  if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1562
83
      NULL, &dest_constraints, &ndest_constraints, &cert_only,
1563
83
      &ncerts, &certs) != 0) {
1564
55
    error_f("failed to parse constraints");
1565
55
    goto send;
1566
55
  }
1567
28
  dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1568
28
  if (socket_is_remote(e) && !remote_add_provider) {
1569
0
    verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1570
0
        "providers is disabled", provider);
1571
0
    goto send;
1572
0
  }
1573
28
  if (realpath(provider, canonical_provider) == NULL) {
1574
16
    verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1575
16
        provider, strerror(errno));
1576
16
    goto send;
1577
16
  }
1578
12
  if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1579
12
    verbose("refusing PKCS#11 add of \"%.100s\": "
1580
12
        "provider not allowed", canonical_provider);
1581
12
    goto send;
1582
12
  }
1583
0
  debug_f("add %.100s", canonical_provider);
1584
0
  if (lifetime && !death)
1585
0
    death = monotime() + lifetime;
1586
1587
0
  count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1588
0
  for (i = 0; i < count; i++) {
1589
0
    if (comments[i] == NULL || comments[i][0] == '\0') {
1590
0
      free(comments[i]);
1591
0
      comments[i] = xstrdup(canonical_provider);
1592
0
    }
1593
0
    for (j = 0; j < ncerts; j++) {
1594
0
      if (!sshkey_is_cert(certs[j]))
1595
0
        continue;
1596
0
      if (!sshkey_equal_public(keys[i], certs[j]))
1597
0
        continue;
1598
0
      if (pkcs11_make_cert(keys[i], certs[j], &k) != 0)
1599
0
        continue;
1600
0
      add_p11_identity(k, xstrdup(comments[i]),
1601
0
          canonical_provider, death, confirm,
1602
0
          dest_constraints, ndest_constraints);
1603
0
      success = 1;
1604
0
    }
1605
0
    if (!cert_only && lookup_identity(keys[i]) == NULL) {
1606
0
      add_p11_identity(keys[i], comments[i],
1607
0
          canonical_provider, death, confirm,
1608
0
          dest_constraints, ndest_constraints);
1609
0
      keys[i] = NULL;   /* transferred */
1610
0
      comments[i] = NULL; /* transferred */
1611
0
      success = 1;
1612
0
    }
1613
    /* XXX update constraints for existing keys */
1614
0
    sshkey_free(keys[i]);
1615
0
    free(comments[i]);
1616
0
  }
1617
301
send:
1618
301
  free(pin);
1619
301
  free(provider);
1620
301
  free(keys);
1621
301
  free(comments);
1622
301
  free_dest_constraints(dest_constraints, ndest_constraints);
1623
301
  for (j = 0; j < ncerts; j++)
1624
0
    sshkey_free(certs[j]);
1625
301
  free(certs);
1626
301
  send_status(e, success);
1627
301
}
1628
1629
static void
1630
process_remove_smartcard_key(SocketEntry *e)
1631
643
{
1632
643
  char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1633
643
  int r, success = 0;
1634
643
  Identity *id, *nxt;
1635
1636
643
  debug2_f("entering");
1637
643
  if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1638
505
      (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1639
505
    error_fr(r, "parse");
1640
505
    goto send;
1641
505
  }
1642
138
  free(pin);
1643
1644
138
  if (realpath(provider, canonical_provider) == NULL) {
1645
22
    verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1646
22
        provider, strerror(errno));
1647
22
    goto send;
1648
22
  }
1649
1650
116
  debug_f("remove %.100s", canonical_provider);
1651
549
  for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1652
433
    nxt = TAILQ_NEXT(id, next);
1653
    /* Skip file--based keys */
1654
433
    if (id->provider == NULL)
1655
433
      continue;
1656
0
    if (!strcmp(canonical_provider, id->provider)) {
1657
0
      TAILQ_REMOVE(&idtab->idlist, id, next);
1658
0
      free_identity(id);
1659
0
      idtab->nentries--;
1660
0
    }
1661
0
  }
1662
116
  if (pkcs11_del_provider(canonical_provider) == 0)
1663
116
    success = 1;
1664
0
  else
1665
0
    error_f("pkcs11_del_provider failed");
1666
643
send:
1667
643
  free(provider);
1668
643
  send_status(e, success);
1669
643
}
1670
#endif /* ENABLE_PKCS11 */
1671
1672
static int
1673
process_ext_session_bind(SocketEntry *e)
1674
0
{
1675
0
  int r, sid_match, key_match;
1676
0
  struct sshkey *key = NULL;
1677
0
  struct sshbuf *sid = NULL, *sig = NULL;
1678
0
  char *fp = NULL;
1679
0
  size_t i;
1680
0
  u_char fwd = 0;
1681
1682
0
  debug2_f("entering");
1683
0
  e->session_bind_attempted = 1;
1684
0
  if ((r = sshkey_froms(e->request, &key)) != 0 ||
1685
0
      (r = sshbuf_froms(e->request, &sid)) != 0 ||
1686
0
      (r = sshbuf_froms(e->request, &sig)) != 0 ||
1687
0
      (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1688
0
    error_fr(r, "parse");
1689
0
    goto out;
1690
0
  }
1691
0
  if (sshbuf_len(sid) > AGENT_MAX_SID_LEN) {
1692
0
    error_f("session ID too long");
1693
0
    goto out;
1694
0
  }
1695
0
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1696
0
      SSH_FP_DEFAULT)) == NULL)
1697
0
    fatal_f("fingerprint failed");
1698
  /* check signature with hostkey on session ID */
1699
0
  if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1700
0
      sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1701
0
    error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1702
0
    goto out;
1703
0
  }
1704
  /* check whether sid/key already recorded */
1705
0
  for (i = 0; i < e->nsession_ids; i++) {
1706
0
    if (!e->session_ids[i].forwarded) {
1707
0
      error_f("attempt to bind session ID to socket "
1708
0
          "previously bound for authentication attempt");
1709
0
      r = -1;
1710
0
      goto out;
1711
0
    }
1712
0
    sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1713
0
    key_match = sshkey_equal(key, e->session_ids[i].key);
1714
0
    if (sid_match && key_match) {
1715
0
      debug_f("session ID already recorded for %s %s",
1716
0
          sshkey_type(key), fp);
1717
0
      r = 0;
1718
0
      goto out;
1719
0
    } else if (sid_match) {
1720
0
      error_f("session ID recorded against different key "
1721
0
          "for %s %s", sshkey_type(key), fp);
1722
0
      r = -1;
1723
0
      goto out;
1724
0
    }
1725
    /*
1726
     * new sid with previously-seen key can happen, e.g. multiple
1727
     * connections to the same host.
1728
     */
1729
0
  }
1730
  /* record new key/sid */
1731
0
  if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1732
0
    error_f("too many session IDs recorded");
1733
0
    r = -1;
1734
0
    goto out;
1735
0
  }
1736
0
  e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1737
0
      e->nsession_ids + 1, sizeof(*e->session_ids));
1738
0
  i = e->nsession_ids++;
1739
0
  debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1740
0
      AGENT_MAX_SESSION_IDS);
1741
0
  e->session_ids[i].key = key;
1742
0
  e->session_ids[i].forwarded = fwd != 0;
1743
0
  key = NULL; /* transferred */
1744
  /* can't transfer sid; it's refcounted and scoped to request's life */
1745
0
  if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1746
0
    fatal_f("sshbuf_new");
1747
0
  if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1748
0
    fatal_fr(r, "sshbuf_putb session ID");
1749
  /* success */
1750
0
  r = 0;
1751
0
 out:
1752
0
  free(fp);
1753
0
  sshkey_free(key);
1754
0
  sshbuf_free(sid);
1755
0
  sshbuf_free(sig);
1756
0
  return r == 0 ? 1 : 0;
1757
0
}
1758
1759
static void
1760
process_extension(SocketEntry *e)
1761
330
{
1762
330
  int r, success = 0;
1763
330
  char *name;
1764
1765
330
  debug2_f("entering");
1766
330
  if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1767
219
    error_fr(r, "parse");
1768
219
    goto send;
1769
219
  }
1770
111
  if (strcmp(name, "session-bind@openssh.com") == 0)
1771
0
    success = process_ext_session_bind(e);
1772
111
  else
1773
111
    debug_f("unsupported extension \"%s\"", name);
1774
111
  free(name);
1775
330
send:
1776
330
  send_status(e, success);
1777
330
}
1778
/*
1779
 * dispatch incoming message.
1780
 * returns 1 on success, 0 for incomplete messages or -1 on error.
1781
 */
1782
static int
1783
process_message(u_int socknum)
1784
78.4k
{
1785
78.4k
  u_int msg_len;
1786
78.4k
  u_char type;
1787
78.4k
  const u_char *cp;
1788
78.4k
  int r;
1789
78.4k
  SocketEntry *e;
1790
1791
78.4k
  if (socknum >= sockets_alloc)
1792
0
    fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1793
78.4k
  e = &sockets[socknum];
1794
1795
78.4k
  if (sshbuf_len(e->input) < 5)
1796
135
    return 0;    /* Incomplete message header. */
1797
78.3k
  cp = sshbuf_ptr(e->input);
1798
78.3k
  msg_len = PEEK_U32(cp);
1799
78.3k
  if (msg_len > AGENT_MAX_LEN) {
1800
419
    debug_f("socket %u (fd=%d) message too long %u > %u",
1801
419
        socknum, e->fd, msg_len, AGENT_MAX_LEN);
1802
419
    return -1;
1803
419
  }
1804
77.9k
  if (sshbuf_len(e->input) < msg_len + 4)
1805
110
    return 0;    /* Incomplete message body. */
1806
1807
  /* move the current input to e->request */
1808
77.8k
  sshbuf_reset(e->request);
1809
77.8k
  if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1810
77.8k
      (r = sshbuf_get_u8(e->request, &type)) != 0) {
1811
40.4k
    if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1812
40.4k
        r == SSH_ERR_STRING_TOO_LARGE) {
1813
40.4k
      error_fr(r, "parse");
1814
40.4k
      return -1;
1815
40.4k
    }
1816
40.4k
    fatal_fr(r, "parse");
1817
40.4k
  }
1818
1819
37.3k
  debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1820
1821
  /* check whether agent is locked */
1822
37.3k
  if (locked && type != SSH_AGENTC_UNLOCK) {
1823
9.73k
    sshbuf_reset(e->request);
1824
9.73k
    switch (type) {
1825
7.32k
    case SSH2_AGENTC_REQUEST_IDENTITIES:
1826
      /* send empty lists */
1827
7.32k
      no_identities(e);
1828
7.32k
      break;
1829
2.41k
    default:
1830
      /* send a fail message for all other request types */
1831
2.41k
      send_status(e, 0);
1832
9.73k
    }
1833
9.73k
    return 1;
1834
9.73k
  }
1835
1836
27.5k
  switch (type) {
1837
5
  case SSH_AGENTC_LOCK:
1838
8.52k
  case SSH_AGENTC_UNLOCK:
1839
8.52k
    process_lock_agent(e, type == SSH_AGENTC_LOCK);
1840
8.52k
    break;
1841
156
  case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1842
156
    process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1843
156
    break;
1844
  /* ssh2 */
1845
3.41k
  case SSH2_AGENTC_SIGN_REQUEST:
1846
3.41k
    process_sign_request2(e);
1847
3.41k
    break;
1848
1.92k
  case SSH2_AGENTC_REQUEST_IDENTITIES:
1849
1.92k
    process_request_identities(e);
1850
1.92k
    break;
1851
1.58k
  case SSH2_AGENTC_ADD_IDENTITY:
1852
5.83k
  case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1853
5.83k
    process_add_identity(e);
1854
5.83k
    break;
1855
1.78k
  case SSH2_AGENTC_REMOVE_IDENTITY:
1856
1.78k
    process_remove_identity(e);
1857
1.78k
    break;
1858
41
  case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1859
41
    process_remove_all_identities(e);
1860
41
    break;
1861
0
#ifdef ENABLE_PKCS11
1862
136
  case SSH_AGENTC_ADD_SMARTCARD_KEY:
1863
301
  case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1864
301
    process_add_smartcard_key(e);
1865
301
    break;
1866
643
  case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1867
643
    process_remove_smartcard_key(e);
1868
643
    break;
1869
0
#endif /* ENABLE_PKCS11 */
1870
330
  case SSH_AGENTC_EXTENSION:
1871
330
    process_extension(e);
1872
330
    break;
1873
4.63k
  default:
1874
    /* Unknown message.  Respond with failure. */
1875
4.63k
    error("Unknown message %d", type);
1876
4.63k
    sshbuf_reset(e->request);
1877
4.63k
    send_status(e, 0);
1878
4.63k
    break;
1879
27.5k
  }
1880
27.5k
  return 1;
1881
27.5k
}
1882
1883
static void
1884
new_socket(sock_type type, int fd)
1885
1.02k
{
1886
1.02k
  u_int i, old_alloc, new_alloc;
1887
1888
1.02k
  debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1889
1.02k
      (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1890
1.02k
  set_nonblock(fd);
1891
1892
1.02k
  if (fd > max_fd)
1893
1
    max_fd = fd;
1894
1895
1.02k
  for (i = 0; i < sockets_alloc; i++)
1896
0
    if (sockets[i].type == AUTH_UNUSED) {
1897
0
      sockets[i].fd = fd;
1898
0
      if ((sockets[i].input = sshbuf_new()) == NULL ||
1899
0
          (sockets[i].output = sshbuf_new()) == NULL ||
1900
0
          (sockets[i].request = sshbuf_new()) == NULL)
1901
0
        fatal_f("sshbuf_new failed");
1902
0
      sockets[i].type = type;
1903
0
      return;
1904
0
    }
1905
1.02k
  old_alloc = sockets_alloc;
1906
1.02k
  new_alloc = sockets_alloc + 10;
1907
1.02k
  sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1908
1.02k
      sizeof(sockets[0]));
1909
11.2k
  for (i = old_alloc; i < new_alloc; i++)
1910
10.2k
    sockets[i].type = AUTH_UNUSED;
1911
1.02k
  sockets_alloc = new_alloc;
1912
1.02k
  sockets[old_alloc].fd = fd;
1913
1.02k
  if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1914
1.02k
      (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1915
1.02k
      (sockets[old_alloc].request = sshbuf_new()) == NULL)
1916
0
    fatal_f("sshbuf_new failed");
1917
1.02k
  sockets[old_alloc].type = type;
1918
1.02k
}
1919
1920
static int
1921
handle_socket_read(u_int socknum)
1922
0
{
1923
0
  struct sockaddr_un sunaddr;
1924
0
  socklen_t slen;
1925
0
  uid_t euid;
1926
0
  gid_t egid;
1927
0
  int fd;
1928
1929
0
  slen = sizeof(sunaddr);
1930
0
  fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1931
0
  if (fd == -1) {
1932
0
    error("accept from AUTH_SOCKET: %s", strerror(errno));
1933
0
    return -1;
1934
0
  }
1935
0
  if (getpeereid(fd, &euid, &egid) == -1) {
1936
0
    error("getpeereid %d failed: %s", fd, strerror(errno));
1937
0
    close(fd);
1938
0
    return -1;
1939
0
  }
1940
0
  if ((euid != 0) && (getuid() != euid)) {
1941
0
    error("uid mismatch: peer euid %u != uid %u",
1942
0
        (u_int) euid, (u_int) getuid());
1943
0
    close(fd);
1944
0
    return -1;
1945
0
  }
1946
0
  new_socket(AUTH_CONNECTION, fd);
1947
0
  return 0;
1948
0
}
1949
1950
static int
1951
handle_conn_read(u_int socknum)
1952
0
{
1953
0
  char buf[AGENT_RBUF_LEN];
1954
0
  ssize_t len;
1955
0
  int r;
1956
1957
0
  if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1958
0
    if (len == -1) {
1959
0
      if (errno == EAGAIN || errno == EINTR)
1960
0
        return 0;
1961
0
      error_f("read error on socket %u (fd %d): %s",
1962
0
          socknum, sockets[socknum].fd, strerror(errno));
1963
0
    }
1964
0
    return -1;
1965
0
  }
1966
0
  if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1967
0
    fatal_fr(r, "compose");
1968
0
  explicit_bzero(buf, sizeof(buf));
1969
0
  for (;;) {
1970
0
    if ((r = process_message(socknum)) == -1)
1971
0
      return -1;
1972
0
    else if (r == 0)
1973
0
      break;
1974
0
  }
1975
0
  return 0;
1976
0
}
1977
1978
static int
1979
handle_conn_write(u_int socknum)
1980
0
{
1981
0
  ssize_t len;
1982
0
  int r;
1983
1984
0
  if (sshbuf_len(sockets[socknum].output) == 0)
1985
0
    return 0; /* shouldn't happen */
1986
0
  if ((len = write(sockets[socknum].fd,
1987
0
      sshbuf_ptr(sockets[socknum].output),
1988
0
      sshbuf_len(sockets[socknum].output))) <= 0) {
1989
0
    if (len == -1) {
1990
0
      if (errno == EAGAIN || errno == EINTR)
1991
0
        return 0;
1992
0
      error_f("read error on socket %u (fd %d): %s",
1993
0
          socknum, sockets[socknum].fd, strerror(errno));
1994
0
    }
1995
0
    return -1;
1996
0
  }
1997
0
  if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1998
0
    fatal_fr(r, "consume");
1999
0
  return 0;
2000
0
}
2001
2002
static void
2003
after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
2004
0
{
2005
0
  size_t i;
2006
0
  u_int socknum, activefds = npfd;
2007
2008
0
  for (i = 0; i < npfd; i++) {
2009
0
    if (pfd[i].revents == 0)
2010
0
      continue;
2011
    /* Find sockets entry */
2012
0
    for (socknum = 0; socknum < sockets_alloc; socknum++) {
2013
0
      if (sockets[socknum].type != AUTH_SOCKET &&
2014
0
          sockets[socknum].type != AUTH_CONNECTION)
2015
0
        continue;
2016
0
      if (pfd[i].fd == sockets[socknum].fd)
2017
0
        break;
2018
0
    }
2019
0
    if (socknum >= sockets_alloc) {
2020
0
      error_f("no socket for fd %d", pfd[i].fd);
2021
0
      continue;
2022
0
    }
2023
    /* Process events */
2024
0
    switch (sockets[socknum].type) {
2025
0
    case AUTH_SOCKET:
2026
0
      if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
2027
0
        break;
2028
0
      if (npfd > maxfds) {
2029
0
        debug3("out of fds (active %u >= limit %u); "
2030
0
            "skipping accept", activefds, maxfds);
2031
0
        break;
2032
0
      }
2033
0
      if (handle_socket_read(socknum) == 0)
2034
0
        activefds++;
2035
0
      break;
2036
0
    case AUTH_CONNECTION:
2037
0
      if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
2038
0
          handle_conn_read(socknum) != 0)
2039
0
        goto close_sock;
2040
0
      if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
2041
0
          handle_conn_write(socknum) != 0) {
2042
0
 close_sock:
2043
0
        if (activefds == 0)
2044
0
          fatal("activefds == 0 at close_sock");
2045
0
        close_socket(&sockets[socknum]);
2046
0
        activefds--;
2047
0
        break;
2048
0
      }
2049
0
      break;
2050
0
    default:
2051
0
      break;
2052
0
    }
2053
0
  }
2054
0
}
2055
2056
static int
2057
prepare_poll(struct pollfd **pfdp, size_t *npfdp, struct timespec *timeoutp, u_int maxfds)
2058
0
{
2059
0
  struct pollfd *pfd = *pfdp;
2060
0
  size_t i, j, npfd = 0;
2061
0
  time_t deadline;
2062
0
  int r;
2063
2064
  /* Count active sockets */
2065
0
  for (i = 0; i < sockets_alloc; i++) {
2066
0
    switch (sockets[i].type) {
2067
0
    case AUTH_SOCKET:
2068
0
    case AUTH_CONNECTION:
2069
0
      npfd++;
2070
0
      break;
2071
0
    case AUTH_UNUSED:
2072
0
      break;
2073
0
    default:
2074
0
      fatal("Unknown socket type %d", sockets[i].type);
2075
0
      break;
2076
0
    }
2077
0
  }
2078
0
  if (npfd != *npfdp &&
2079
0
      (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
2080
0
    fatal_f("recallocarray failed");
2081
0
  *pfdp = pfd;
2082
0
  *npfdp = npfd;
2083
2084
0
  for (i = j = 0; i < sockets_alloc; i++) {
2085
0
    switch (sockets[i].type) {
2086
0
    case AUTH_SOCKET:
2087
0
      if (npfd > maxfds) {
2088
0
        debug3("out of fds (active %zu >= limit %u); "
2089
0
            "skipping arming listener", npfd, maxfds);
2090
0
        break;
2091
0
      }
2092
0
      pfd[j].fd = sockets[i].fd;
2093
0
      pfd[j].revents = 0;
2094
0
      pfd[j].events = POLLIN;
2095
0
      j++;
2096
0
      break;
2097
0
    case AUTH_CONNECTION:
2098
0
      pfd[j].fd = sockets[i].fd;
2099
0
      pfd[j].revents = 0;
2100
      /*
2101
       * Only prepare to read if we can handle a full-size
2102
       * input read buffer and enqueue a max size reply..
2103
       */
2104
0
      if ((r = sshbuf_check_reserve(sockets[i].input,
2105
0
          AGENT_RBUF_LEN)) == 0 &&
2106
0
          (r = sshbuf_check_reserve(sockets[i].output,
2107
0
          AGENT_MAX_LEN)) == 0)
2108
0
        pfd[j].events = POLLIN;
2109
0
      else if (r != SSH_ERR_NO_BUFFER_SPACE)
2110
0
        fatal_fr(r, "reserve");
2111
0
      if (sshbuf_len(sockets[i].output) > 0)
2112
0
        pfd[j].events |= POLLOUT;
2113
0
      j++;
2114
0
      break;
2115
0
    default:
2116
0
      break;
2117
0
    }
2118
0
  }
2119
0
  deadline = reaper();
2120
0
  if (parent_alive_interval != 0)
2121
0
    deadline = (deadline == 0) ? parent_alive_interval :
2122
0
        MINIMUM(deadline, parent_alive_interval);
2123
0
  if (deadline != 0)
2124
0
    ptimeout_deadline_sec(timeoutp, deadline);
2125
0
  return (1);
2126
0
}
2127
2128
static void
2129
cleanup_socket(void)
2130
0
{
2131
0
  if (cleanup_pid != 0 && getpid() != cleanup_pid)
2132
0
    return;
2133
0
  debug_f("cleanup");
2134
0
  if (socket_name != NULL) {
2135
0
    unlink(socket_name);
2136
0
    free(socket_name);
2137
0
    socket_name = NULL;
2138
0
  }
2139
0
  if (socket_dir[0])
2140
0
    rmdir(socket_dir);
2141
0
}
2142
2143
void
2144
cleanup_exit(int i)
2145
0
{
2146
0
  cleanup_socket();
2147
0
#ifdef ENABLE_PKCS11
2148
0
  pkcs11_terminate();
2149
0
#endif
2150
0
  _exit(i);
2151
0
}
2152
2153
static void
2154
cleanup_handler(int sig)
2155
0
{
2156
0
  signalled_exit = sig;
2157
0
}
2158
2159
static void
2160
keydrop_handler(int sig)
2161
0
{
2162
0
  signalled_keydrop = sig;
2163
0
}
2164
2165
static void
2166
check_parent_exists(void)
2167
0
{
2168
  /*
2169
   * If our parent has exited then getppid() will return (pid_t)1,
2170
   * so testing for that should be safe.
2171
   */
2172
0
  if (parent_pid != -1 && getppid() != parent_pid) {
2173
    /* printf("Parent has died - Authentication agent exiting.\n"); */
2174
0
    cleanup_socket();
2175
0
    _exit(2);
2176
0
  }
2177
0
}
2178
2179
static void
2180
usage(void)
2181
0
{
2182
0
  fprintf(stderr,
2183
0
      "usage: ssh-agent [-c | -s] [-DdTU] [-a bind_address] [-E fingerprint_hash]\n"
2184
0
      "                 [-O option] [-P allowed_providers] [-t life]\n"
2185
0
      "       ssh-agent [-TU] [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2186
0
      "                 [-P allowed_providers] [-t life] command [arg ...]\n"
2187
0
      "       ssh-agent [-c | -s] -k\n"
2188
0
      "       ssh-agent -u\n");
2189
0
  exit(1);
2190
0
}
2191
2192
int
2193
main(int ac, char **av)
2194
0
{
2195
0
  int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0;
2196
0
  int s_flag = 0, T_flag = 0, u_flag = 0, U_flag = 0;
2197
0
  int sock = -1, ch, result, saved_errno;
2198
0
  pid_t pid;
2199
0
  char *homedir = NULL, *shell, *format, *pidstr, *agentsocket = NULL;
2200
0
  char *cp, pidstrbuf[1 + 3 * sizeof pid];
2201
0
  char *fdstr;
2202
0
  const char *errstr = NULL;
2203
0
  const char *ccp;
2204
0
#ifdef HAVE_SETRLIMIT
2205
0
  struct rlimit rlim;
2206
0
#endif
2207
0
  extern int optind;
2208
0
  extern char *optarg;
2209
0
  size_t len;
2210
0
  mode_t prev_mask;
2211
0
  struct timespec timeout;
2212
0
  struct pollfd *pfd = NULL;
2213
0
  size_t npfd = 0;
2214
0
  u_int maxfds;
2215
0
  sigset_t nsigset, osigset;
2216
0
  int socket_activated = 0;
2217
2218
  /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2219
0
  sanitise_stdfd();
2220
2221
  /* drop */
2222
0
  (void)setegid(getgid());
2223
0
  (void)setgid(getgid());
2224
2225
0
  platform_disable_tracing(0);  /* strict=no */
2226
2227
0
#ifdef RLIMIT_NOFILE
2228
0
  if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2229
0
    fatal("%s: getrlimit: %s", __progname, strerror(errno));
2230
0
#endif
2231
2232
0
  __progname = ssh_get_progname(av[0]);
2233
0
  seed_rng();
2234
2235
0
  while ((ch = getopt(ac, av, "cDdksTuUE:a:O:P:t:")) != -1) {
2236
0
    switch (ch) {
2237
0
    case 'E':
2238
0
      fingerprint_hash = ssh_digest_alg_by_name(optarg);
2239
0
      if (fingerprint_hash == -1)
2240
0
        fatal("Invalid hash algorithm \"%s\"", optarg);
2241
0
      break;
2242
0
    case 'c':
2243
0
      if (s_flag)
2244
0
        usage();
2245
0
      c_flag++;
2246
0
      break;
2247
0
    case 'k':
2248
0
      k_flag++;
2249
0
      break;
2250
0
    case 'O':
2251
0
      if (strcmp(optarg, "no-restrict-websafe") == 0)
2252
0
        restrict_websafe = 0;
2253
0
      else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
2254
0
        remote_add_provider = 1;
2255
0
      else if ((ccp = strprefix(optarg,
2256
0
          "websafe-allow=", 0)) != NULL) {
2257
0
        if (websafe_allowlist != NULL)
2258
0
          fatal("websafe-allow already set");
2259
0
        websafe_allowlist = xstrdup(ccp);
2260
0
      } else
2261
0
        fatal("Unknown -O option");
2262
0
      break;
2263
0
    case 'P':
2264
0
      if (allowed_providers != NULL)
2265
0
        fatal("-P option already specified");
2266
0
      allowed_providers = xstrdup(optarg);
2267
0
      break;
2268
0
    case 's':
2269
0
      if (c_flag)
2270
0
        usage();
2271
0
      s_flag++;
2272
0
      break;
2273
0
    case 'd':
2274
0
      if (d_flag || D_flag)
2275
0
        usage();
2276
0
      d_flag++;
2277
0
      break;
2278
0
    case 'D':
2279
0
      if (d_flag || D_flag)
2280
0
        usage();
2281
0
      D_flag++;
2282
0
      break;
2283
0
    case 'a':
2284
0
      agentsocket = optarg;
2285
0
      break;
2286
0
    case 't':
2287
0
      if ((lifetime = convtime(optarg)) == -1) {
2288
0
        fprintf(stderr, "Invalid lifetime\n");
2289
0
        usage();
2290
0
      }
2291
0
      break;
2292
0
    case 'T':
2293
0
      T_flag++;
2294
0
      break;
2295
0
    case 'u':
2296
0
      u_flag++;
2297
0
      break;
2298
0
    case 'U':
2299
0
      U_flag++;
2300
0
      break;
2301
0
    default:
2302
0
      usage();
2303
0
    }
2304
0
  }
2305
0
  ac -= optind;
2306
0
  av += optind;
2307
2308
0
  if (ac > 0 &&
2309
0
      (c_flag || k_flag || s_flag || d_flag || D_flag || u_flag))
2310
0
    usage();
2311
2312
0
  log_init(__progname,
2313
0
      d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2314
0
      SYSLOG_FACILITY_AUTH, 1);
2315
2316
0
  if (allowed_providers == NULL)
2317
0
    allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2318
0
  if (websafe_allowlist == NULL)
2319
0
    websafe_allowlist = xstrdup(DEFAULT_WEBSAFE_ALLOWLIST);
2320
2321
0
  if (ac == 0 && !c_flag && !s_flag) {
2322
0
    shell = getenv("SHELL");
2323
0
    if (shell != NULL && (len = strlen(shell)) > 2 &&
2324
0
        strncmp(shell + len - 3, "csh", 3) == 0)
2325
0
      c_flag = 1;
2326
0
  }
2327
0
  if (k_flag) {
2328
0
    pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2329
0
    if (pidstr == NULL) {
2330
0
      fprintf(stderr, "%s not set, cannot kill agent\n",
2331
0
          SSH_AGENTPID_ENV_NAME);
2332
0
      exit(1);
2333
0
    }
2334
0
    pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2335
0
    if (errstr) {
2336
0
      fprintf(stderr,
2337
0
          "%s=\"%s\", which is not a good PID: %s\n",
2338
0
          SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2339
0
      exit(1);
2340
0
    }
2341
0
    if (kill(pid, SIGTERM) == -1) {
2342
0
      perror("kill");
2343
0
      exit(1);
2344
0
    }
2345
0
    format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
2346
0
    printf(format, SSH_AUTHSOCKET_ENV_NAME);
2347
0
    printf(format, SSH_AGENTPID_ENV_NAME);
2348
0
    printf("echo Agent pid %ld killed;\n", (long)pid);
2349
0
    exit(0);
2350
0
  }
2351
0
  if (u_flag) {
2352
0
    if ((homedir = get_homedir()) == NULL)
2353
0
      fatal("Couldn't determine home directory");
2354
0
    agent_cleanup_stale(homedir, u_flag > 1);
2355
0
    printf("Deleted stale agent sockets in ~/%s\n",
2356
0
        _PATH_SSH_AGENT_SOCKET_DIR);
2357
0
    exit(0);
2358
0
  }
2359
2360
  /*
2361
   * Minimum file descriptors:
2362
   * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2363
   * a few spare for libc / stack protectors / sanitisers, etc.
2364
   */
2365
0
#define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2366
0
  if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2367
0
    fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2368
0
        __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2369
0
  maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2370
2371
0
  parent_pid = getpid();
2372
2373
  /* Has the socket been provided via socket activation? */
2374
0
  if (agentsocket == NULL && ac == 0 && (d_flag || D_flag) &&
2375
0
      (pidstr = getenv("LISTEN_PID")) != NULL &&
2376
0
      (fdstr = getenv("LISTEN_FDS")) != NULL) {
2377
0
    if (strcmp(fdstr, "1") != 0) {
2378
0
      fatal("unexpected LISTEN_FDS contents "
2379
0
          "(want: \"1\" got\"%s\"", fdstr);
2380
0
    }
2381
0
    if (fcntl(3, F_GETFL) == -1)
2382
0
      fatal("LISTEN_FDS set but fd 3 unavailable");
2383
0
    pid = (int)strtonum(pidstr, 1, INT_MAX, &errstr);
2384
0
    if (errstr != NULL)
2385
0
      fatal("invalid LISTEN_PID: %s", errstr);
2386
0
    if (pid != getpid())
2387
0
      fatal("bad LISTEN_PID: %d vs pid %d", pid, getpid());
2388
0
    debug("using socket activation on fd=3");
2389
0
    sock = 3;
2390
0
    socket_activated = 1;
2391
0
  }
2392
2393
0
  if (sock == -1 && agentsocket == NULL && !T_flag) {
2394
    /* Default case: ~/.ssh/agent/[socket] */
2395
0
    if ((homedir = get_homedir()) == NULL)
2396
0
      fatal("Couldn't determine home directory");
2397
0
    if (!U_flag)
2398
0
      agent_cleanup_stale(homedir, 0);
2399
0
    if (agent_listener(homedir, "agent", &sock, &socket_name) != 0)
2400
0
      fatal_f("Couldn't prepare agent socket");
2401
0
    free(homedir);
2402
0
  } else if (sock == -1) {
2403
0
    if (T_flag) {
2404
      /*
2405
       * Create private directory for agent socket
2406
       * in $TMPDIR.
2407
       */
2408
0
      mktemp_proto(socket_dir, sizeof(socket_dir));
2409
0
      if (mkdtemp(socket_dir) == NULL) {
2410
0
        perror("mkdtemp: private socket dir");
2411
0
        exit(1);
2412
0
      }
2413
0
      xasprintf(&socket_name, "%s/agent.%ld",
2414
0
          socket_dir, (long)parent_pid);
2415
0
    } else {
2416
      /* Try to use specified agent socket */
2417
0
      socket_dir[0] = '\0';
2418
0
      socket_name = xstrdup(agentsocket);
2419
0
    }
2420
    /* Listen on socket */
2421
0
    prev_mask = umask(0177);
2422
0
    if ((sock = unix_listener(socket_name,
2423
0
        SSH_LISTEN_BACKLOG, 0)) < 0) {
2424
0
      *socket_name = '\0'; /* Don't unlink existing file */
2425
0
      cleanup_exit(1);
2426
0
    }
2427
0
    umask(prev_mask);
2428
0
  }
2429
2430
0
  closefrom(sock == -1 ? STDERR_FILENO + 1 : sock + 1);
2431
2432
  /*
2433
   * Create socket early so it will exist before command gets run from
2434
   * the parent.
2435
   */
2436
0
  if (sock == -1) {
2437
0
    prev_mask = umask(0177);
2438
0
    sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2439
0
    if (sock < 0) {
2440
      /* XXX - unix_listener() calls error() not perror() */
2441
0
      *socket_name = '\0'; /* Don't unlink existing file */
2442
0
      cleanup_exit(1);
2443
0
    }
2444
0
    umask(prev_mask);
2445
0
  }
2446
2447
  /*
2448
   * Fork, and have the parent execute the command, if any, or present
2449
   * the socket data.  The child continues as the authentication agent.
2450
   */
2451
0
  if (D_flag || d_flag) {
2452
0
    log_init(__progname,
2453
0
        d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2454
0
        SYSLOG_FACILITY_AUTH, 1);
2455
0
    if (socket_name != NULL) {
2456
0
      cp = argv_assemble(1, &socket_name);
2457
0
      format = c_flag ?
2458
0
          "setenv %s %s;\n" : "%s=%s; export %s;\n";
2459
0
      printf(format, SSH_AUTHSOCKET_ENV_NAME, cp,
2460
0
          SSH_AUTHSOCKET_ENV_NAME);
2461
0
      free(cp);
2462
0
      printf("echo Agent pid %ld;\n", (long)parent_pid);
2463
0
      fflush(stdout);
2464
0
    }
2465
0
    goto skip;
2466
0
  }
2467
0
  pid = fork();
2468
0
  if (pid == -1) {
2469
0
    perror("fork");
2470
0
    cleanup_exit(1);
2471
0
  }
2472
0
  if (pid != 0) {   /* Parent - execute the given command. */
2473
0
    close(sock);
2474
0
    snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2475
0
    if (ac == 0) {
2476
0
      format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2477
0
      cp = argv_assemble(1, &socket_name);
2478
0
      printf(format, SSH_AUTHSOCKET_ENV_NAME, cp,
2479
0
          SSH_AUTHSOCKET_ENV_NAME);
2480
0
      printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
2481
0
          SSH_AGENTPID_ENV_NAME);
2482
0
      free(cp);
2483
0
      printf("echo Agent pid %ld;\n", (long)pid);
2484
0
      exit(0);
2485
0
    }
2486
0
    if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2487
0
        setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2488
0
      perror("setenv");
2489
0
      exit(1);
2490
0
    }
2491
0
    execvp(av[0], av);
2492
0
    perror(av[0]);
2493
0
    exit(1);
2494
0
  }
2495
  /* child */
2496
0
  log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2497
2498
0
  if (setsid() == -1) {
2499
0
    error("setsid: %s", strerror(errno));
2500
0
    cleanup_exit(1);
2501
0
  }
2502
2503
0
  (void)chdir("/");
2504
0
  if (stdfd_devnull(1, 1, 1) == -1)
2505
0
    error_f("stdfd_devnull failed");
2506
2507
0
#ifdef HAVE_SETRLIMIT
2508
  /* deny core dumps, since memory contains unencrypted private keys */
2509
0
  rlim.rlim_cur = rlim.rlim_max = 0;
2510
0
  if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2511
0
    error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2512
0
    cleanup_exit(1);
2513
0
  }
2514
0
#endif
2515
2516
0
skip:
2517
2518
0
  cleanup_pid = getpid();
2519
2520
0
#ifdef ENABLE_PKCS11
2521
0
  pkcs11_init(0);
2522
0
#endif
2523
0
  new_socket(AUTH_SOCKET, sock);
2524
0
  if (ac > 0)
2525
0
    parent_alive_interval = 10;
2526
0
  idtab_init();
2527
0
  ssh_signal(SIGPIPE, SIG_IGN);
2528
0
  ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2529
0
  ssh_signal(SIGHUP, cleanup_handler);
2530
0
  ssh_signal(SIGTERM, cleanup_handler);
2531
0
  ssh_signal(SIGUSR1, keydrop_handler);
2532
2533
0
  sigemptyset(&nsigset);
2534
0
  sigaddset(&nsigset, SIGINT);
2535
0
  sigaddset(&nsigset, SIGHUP);
2536
0
  sigaddset(&nsigset, SIGTERM);
2537
0
  sigaddset(&nsigset, SIGUSR1);
2538
2539
0
  if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2540
0
    fatal("%s: pledge: %s", __progname, strerror(errno));
2541
0
  platform_pledge_agent();
2542
2543
0
  while (1) {
2544
0
    sigprocmask(SIG_BLOCK, &nsigset, &osigset);
2545
0
    if (signalled_exit != 0) {
2546
0
      logit("exiting on signal %d", (int)signalled_exit);
2547
0
      cleanup_exit((signalled_exit == SIGTERM &&
2548
0
          socket_activated) ? 0 : 2);
2549
0
    }
2550
0
    if (signalled_keydrop) {
2551
0
      logit("signal %d received; removing all keys",
2552
0
          (int)signalled_keydrop);
2553
0
      remove_all_identities();
2554
0
      signalled_keydrop = 0;
2555
0
    }
2556
0
    ptimeout_init(&timeout);
2557
0
    prepare_poll(&pfd, &npfd, &timeout, maxfds);
2558
0
    result = ppoll(pfd, npfd, ptimeout_get_tsp(&timeout), &osigset);
2559
0
    sigprocmask(SIG_SETMASK, &osigset, NULL);
2560
0
    saved_errno = errno;
2561
0
    if (parent_alive_interval != 0)
2562
0
      check_parent_exists();
2563
0
    (void) reaper();  /* remove expired keys */
2564
0
    if (result == -1) {
2565
0
      if (saved_errno == EINTR)
2566
0
        continue;
2567
0
      fatal("poll: %s", strerror(saved_errno));
2568
0
    } else if (result > 0)
2569
0
      after_poll(pfd, npfd, maxfds);
2570
0
  }
2571
  /* NOTREACHED */
2572
0
}