Coverage Report

Created: 2026-03-21 06:18

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.324 2026/03/10 07:27:14 djm 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/time.h>
41
#include <sys/queue.h>
42
#include <sys/resource.h>
43
#include <sys/socket.h>
44
#include <sys/stat.h>
45
#include <sys/un.h>
46
#include <sys/wait.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 <paths.h>
56
#include <poll.h>
57
#include <signal.h>
58
#include <stdlib.h>
59
#include <stdio.h>
60
#include <string.h>
61
#include <stdarg.h>
62
#include <limits.h>
63
#include <time.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
122k
#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
5.70k
#define LOCK_SIZE 32
179
#define LOCK_SALT_SIZE  16
180
5.70k
#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.67k
{
199
1.67k
  size_t i;
200
201
1.67k
  close(e->fd);
202
1.67k
  sshbuf_free(e->input);
203
1.67k
  sshbuf_free(e->output);
204
1.67k
  sshbuf_free(e->request);
205
1.67k
  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.67k
  free(e->session_ids);
210
1.67k
  memset(e, '\0', sizeof(*e));
211
1.67k
  e->fd = -1;
212
1.67k
  e->type = AUTH_UNUSED;
213
1.67k
}
214
215
static void
216
idtab_init(void)
217
1.67k
{
218
1.67k
  idtab = xcalloc(1, sizeof(*idtab));
219
1.67k
  TAILQ_INIT(&idtab->idlist);
220
1.67k
  idtab->nentries = 0;
221
1.67k
}
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
16.7k
{
241
16.7k
  size_t i;
242
243
16.7k
  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
16.7k
  free(dcs);
248
16.7k
}
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
40
{
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
40
}
336
337
static void
338
free_identity(Identity *id)
339
16.7k
{
340
16.7k
  sshkey_free(id->key);
341
16.7k
  free(id->provider);
342
16.7k
  free(id->comment);
343
16.7k
  free(id->sk_provider);
344
16.7k
  free_dest_constraints(id->dest_constraints, id->ndest_constraints);
345
16.7k
  free(id);
346
16.7k
}
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,
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
40
{
467
40
  size_t i;
468
40
  const char **hp;
469
40
  struct hostkey_sid *hks;
470
40
  const struct sshkey *fromkey = NULL;
471
40
  const char *test_user;
472
40
  char *fp1, *fp2;
473
474
  /* XXX remove logspam */
475
40
  debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
476
40
      "%zu constraints", sshkey_type(id->key), id->comment,
477
40
      e->nsession_ids, id->ndest_constraints);
478
40
  if (id->ndest_constraints == 0)
479
40
    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
0
{
566
0
  return e->session_bind_attempted || (e->nsession_ids != 0);
567
0
}
568
569
/* return matching private key for given public key */
570
static Identity *
571
lookup_identity(struct sshkey *key)
572
0
{
573
0
  Identity *id;
574
575
0
  TAILQ_FOREACH(id, &idtab->idlist, next) {
576
0
    if (sshkey_equal(key, id->key))
577
0
      return (id);
578
0
  }
579
0
  return (NULL);
580
0
}
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_generic(SocketEntry *e, u_int code)
602
41.0k
{
603
41.0k
  int r;
604
605
41.0k
  if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
606
41.0k
      (r = sshbuf_put_u8(e->output, code)) != 0)
607
0
    fatal_fr(r, "compose");
608
41.0k
}
609
610
static void
611
send_status(SocketEntry *e, int success)
612
41.0k
{
613
41.0k
  return send_status_generic(e,
614
41.0k
      success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
615
41.0k
}
616
617
/* send list of supported public keys to 'client' */
618
static void
619
process_request_identities(SocketEntry *e)
620
4
{
621
4
  Identity *id;
622
4
  struct sshbuf *msg, *keys;
623
4
  int r;
624
4
  u_int i = 0, nentries = 0;
625
4
  char *fp;
626
627
4
  debug2_f("entering");
628
629
4
  if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
630
0
    fatal_f("sshbuf_new failed");
631
40
  TAILQ_FOREACH(id, &idtab->idlist, next) {
632
40
    if ((fp = sshkey_fingerprint(id->key, SSH_FP_HASH_DEFAULT,
633
40
        SSH_FP_DEFAULT)) == NULL)
634
0
      fatal_f("fingerprint failed");
635
40
    debug_f("key %u / %u: %s %s", i++, idtab->nentries,
636
40
        sshkey_ssh_name(id->key), fp);
637
40
    dump_dest_constraints(__func__,
638
40
        id->dest_constraints, id->ndest_constraints);
639
40
    free(fp);
640
    /* identity not visible, don't include in response */
641
40
    if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
642
0
      continue;
643
40
    if ((r = sshkey_puts(id->key, keys)) != 0 ||
644
40
        (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
645
0
      error_fr(r, "compose key/comment");
646
0
      continue;
647
0
    }
648
40
    nentries++;
649
40
  }
650
4
  debug2_f("replying with %u allowed of %u available keys",
651
4
      nentries, idtab->nentries);
652
4
  if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
653
4
      (r = sshbuf_put_u32(msg, nentries)) != 0 ||
654
4
      (r = sshbuf_putb(msg, keys)) != 0)
655
0
    fatal_fr(r, "compose");
656
4
  if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
657
0
    fatal_fr(r, "enqueue");
658
4
  sshbuf_free(msg);
659
4
  sshbuf_free(keys);
660
4
}
661
662
663
static char *
664
agent_decode_alg(struct sshkey *key, u_int flags)
665
0
{
666
0
  if (key->type == KEY_RSA) {
667
0
    if (flags & SSH_AGENT_RSA_SHA2_256)
668
0
      return "rsa-sha2-256";
669
0
    else if (flags & SSH_AGENT_RSA_SHA2_512)
670
0
      return "rsa-sha2-512";
671
0
  } else if (key->type == KEY_RSA_CERT) {
672
0
    if (flags & SSH_AGENT_RSA_SHA2_256)
673
0
      return "rsa-sha2-256-cert-v01@openssh.com";
674
0
    else if (flags & SSH_AGENT_RSA_SHA2_512)
675
0
      return "rsa-sha2-512-cert-v01@openssh.com";
676
0
  }
677
0
  return NULL;
678
0
}
679
680
/*
681
 * Attempt to parse the contents of a buffer as a SSH publickey userauth
682
 * request, checking its contents for consistency and matching the embedded
683
 * key against the one that is being used for signing.
684
 * Note: does not modify msg buffer.
685
 * Optionally extract the username, session ID and/or hostkey from the request.
686
 */
687
static int
688
parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
689
    char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
690
0
{
691
0
  struct sshbuf *b = NULL, *sess_id = NULL;
692
0
  char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
693
0
  int r;
694
0
  u_char t, sig_follows;
695
0
  struct sshkey *mkey = NULL, *hostkey = NULL;
696
697
0
  if (userp != NULL)
698
0
    *userp = NULL;
699
0
  if (sess_idp != NULL)
700
0
    *sess_idp = NULL;
701
0
  if (hostkeyp != NULL)
702
0
    *hostkeyp = NULL;
703
0
  if ((b = sshbuf_fromb(msg)) == NULL)
704
0
    fatal_f("sshbuf_fromb");
705
706
  /* SSH userauth request */
707
0
  if ((r = sshbuf_froms(b, &sess_id)) != 0)
708
0
    goto out;
709
0
  if (sshbuf_len(sess_id) == 0) {
710
0
    r = SSH_ERR_INVALID_FORMAT;
711
0
    goto out;
712
0
  }
713
0
  if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
714
0
      (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
715
0
      (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
716
0
      (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
717
0
      (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
718
0
      (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
719
0
      (r = sshkey_froms(b, &mkey)) != 0) /* key */
720
0
    goto out;
721
0
  if (t != SSH2_MSG_USERAUTH_REQUEST ||
722
0
      sig_follows != 1 ||
723
0
      strcmp(service, "ssh-connection") != 0 ||
724
0
      !sshkey_equal(expected_key, mkey) ||
725
0
      sshkey_type_from_name(pkalg) != expected_key->type) {
726
0
    r = SSH_ERR_INVALID_FORMAT;
727
0
    goto out;
728
0
  }
729
0
  if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
730
0
    if ((r = sshkey_froms(b, &hostkey)) != 0)
731
0
      goto out;
732
0
  } else if (strcmp(method, "publickey") != 0) {
733
0
    r = SSH_ERR_INVALID_FORMAT;
734
0
    goto out;
735
0
  }
736
0
  if (sshbuf_len(b) != 0) {
737
0
    r = SSH_ERR_INVALID_FORMAT;
738
0
    goto out;
739
0
  }
740
  /* success */
741
0
  r = 0;
742
0
  debug3_f("well formed userauth");
743
0
  if (userp != NULL) {
744
0
    *userp = user;
745
0
    user = NULL;
746
0
  }
747
0
  if (sess_idp != NULL) {
748
0
    *sess_idp = sess_id;
749
0
    sess_id = NULL;
750
0
  }
751
0
  if (hostkeyp != NULL) {
752
0
    *hostkeyp = hostkey;
753
0
    hostkey = NULL;
754
0
  }
755
0
 out:
756
0
  sshbuf_free(b);
757
0
  sshbuf_free(sess_id);
758
0
  free(user);
759
0
  free(service);
760
0
  free(method);
761
0
  free(pkalg);
762
0
  sshkey_free(mkey);
763
0
  sshkey_free(hostkey);
764
0
  return r;
765
0
}
766
767
/*
768
 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
769
 * Note: does not modify buffer.
770
 */
771
static int
772
parse_sshsig_request(struct sshbuf *msg)
773
0
{
774
0
  int r;
775
0
  struct sshbuf *b;
776
777
0
  if ((b = sshbuf_fromb(msg)) == NULL)
778
0
    fatal_f("sshbuf_fromb");
779
780
0
  if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
781
0
      (r = sshbuf_consume(b, 6)) != 0 ||
782
0
      (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
783
0
      (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
784
0
      (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
785
0
      (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
786
0
    goto out;
787
0
  if (sshbuf_len(b) != 0) {
788
0
    r = SSH_ERR_INVALID_FORMAT;
789
0
    goto out;
790
0
  }
791
  /* success */
792
0
  r = 0;
793
0
 out:
794
0
  sshbuf_free(b);
795
0
  return r;
796
0
}
797
798
/*
799
 * This function inspects a message to be signed by a FIDO key that has a
800
 * web-like application string (i.e. one that does not begin with "ssh:".
801
 * It checks that the message is one of those expected for SSH operations
802
 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
803
 * for the web.
804
 */
805
static int
806
check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
807
0
{
808
0
  if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
809
0
    debug_f("signed data matches public key userauth request");
810
0
    return 1;
811
0
  }
812
0
  if (parse_sshsig_request(data) == 0) {
813
0
    debug_f("signed data matches SSHSIG signature request");
814
0
    return 1;
815
0
  }
816
817
  /* XXX check CA signature operation */
818
819
0
  error("web-origin key attempting to sign non-SSH message");
820
0
  return 0;
821
0
}
822
823
static int
824
buf_equal(const struct sshbuf *a, const struct sshbuf *b)
825
0
{
826
0
  if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
827
0
    return SSH_ERR_INVALID_ARGUMENT;
828
0
  if (sshbuf_len(a) != sshbuf_len(b))
829
0
    return SSH_ERR_INVALID_FORMAT;
830
0
  if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
831
0
    return SSH_ERR_INVALID_FORMAT;
832
0
  return 0;
833
0
}
834
835
/* ssh2 only */
836
static void
837
process_sign_request2(SocketEntry *e)
838
41
{
839
41
  u_char *signature = NULL;
840
41
  size_t slen = 0;
841
41
  u_int compat = 0, flags;
842
41
  int r, ok = -1, retried = 0;
843
41
  char *fp = NULL, *pin = NULL, *prompt = NULL;
844
41
  char *user = NULL, *sig_dest = NULL;
845
41
  const char *fwd_host = NULL, *dest_host = NULL;
846
41
  struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
847
41
  struct sshkey *key = NULL, *hostkey = NULL;
848
41
  struct identity *id;
849
41
  struct notifier_ctx *notifier = NULL;
850
851
41
  debug_f("entering");
852
853
41
  if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
854
0
    fatal_f("sshbuf_new failed");
855
41
  if ((r = sshkey_froms(e->request, &key)) != 0 ||
856
0
      (r = sshbuf_get_stringb(e->request, data)) != 0 ||
857
41
      (r = sshbuf_get_u32(e->request, &flags)) != 0) {
858
41
    error_fr(r, "parse");
859
41
    goto send;
860
41
  }
861
862
0
  if ((id = lookup_identity(key)) == NULL) {
863
0
    verbose_f("%s key not found", sshkey_type(key));
864
0
    goto send;
865
0
  }
866
0
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
867
0
      SSH_FP_DEFAULT)) == NULL)
868
0
    fatal_f("fingerprint failed");
869
870
0
  if (id->ndest_constraints != 0) {
871
0
    if (e->nsession_ids == 0) {
872
0
      logit_f("refusing use of destination-constrained key "
873
0
          "to sign on unbound connection");
874
0
      goto send;
875
0
    }
876
0
    if (parse_userauth_request(data, key, &user, &sid,
877
0
        &hostkey) != 0) {
878
0
      logit_f("refusing use of destination-constrained key "
879
0
         "to sign an unidentified signature");
880
0
      goto send;
881
0
    }
882
    /* XXX logspam */
883
0
    debug_f("user=%s", user);
884
0
    if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
885
0
      goto send;
886
    /* XXX display fwd_host/dest_host in askpass UI */
887
    /*
888
     * Ensure that the session ID is the most recent one
889
     * registered on the socket - it should have been bound by
890
     * ssh immediately before userauth.
891
     */
892
0
    if (buf_equal(sid,
893
0
        e->session_ids[e->nsession_ids - 1].sid) != 0) {
894
0
      error_f("unexpected session ID (%zu listed) on "
895
0
          "signature request for target user %s with "
896
0
          "key %s %s", e->nsession_ids, user,
897
0
          sshkey_type(id->key), fp);
898
0
      goto send;
899
0
    }
900
    /*
901
     * Ensure that the hostkey embedded in the signature matches
902
     * the one most recently bound to the socket. An exception is
903
     * made for the initial forwarding hop.
904
     */
905
0
    if (e->nsession_ids > 1 && hostkey == NULL) {
906
0
      error_f("refusing use of destination-constrained key: "
907
0
          "no hostkey recorded in signature for forwarded "
908
0
          "connection");
909
0
      goto send;
910
0
    }
911
0
    if (hostkey != NULL && !sshkey_equal(hostkey,
912
0
        e->session_ids[e->nsession_ids - 1].key)) {
913
0
      error_f("refusing use of destination-constrained key: "
914
0
          "mismatch between hostkey in request and most "
915
0
          "recently bound session");
916
0
      goto send;
917
0
    }
918
0
    xasprintf(&sig_dest, "public key authentication request for "
919
0
        "user \"%s\" to listed host", user);
920
0
  }
921
0
  if (id->confirm && confirm_key(id, sig_dest) != 0) {
922
0
    verbose_f("user refused key");
923
0
    goto send;
924
0
  }
925
0
  if (sshkey_is_sk(id->key)) {
926
0
    if (restrict_websafe &&
927
0
        match_pattern_list(id->key->sk_application,
928
0
        websafe_allowlist, 0) != 1 &&
929
0
        !check_websafe_message_contents(key, data)) {
930
      /* error already logged */
931
0
      goto send;
932
0
    }
933
0
    if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
934
0
      notifier = notify_start(0,
935
0
          "Confirm user presence for key %s %s%s%s",
936
0
          sshkey_type(id->key), fp,
937
0
          sig_dest == NULL ? "" : "\n",
938
0
          sig_dest == NULL ? "" : sig_dest);
939
0
    }
940
0
  }
941
0
 retry_pin:
942
0
  if ((r = sshkey_sign(id->key, &signature, &slen,
943
0
      sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
944
0
      id->sk_provider, pin, compat)) != 0) {
945
0
    debug_fr(r, "sshkey_sign");
946
0
    if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
947
0
        r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
948
0
      notify_complete(notifier, NULL);
949
0
      notifier = NULL;
950
      /* XXX include sig_dest */
951
0
      xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
952
0
          (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
953
0
          " and confirm user presence " : " ",
954
0
          sshkey_type(id->key), fp);
955
0
      pin = read_passphrase(prompt, RP_USE_ASKPASS);
956
0
      retried = 1;
957
0
      goto retry_pin;
958
0
    }
959
0
    error_fr(r, "sshkey_sign");
960
0
    goto send;
961
0
  }
962
  /* Success */
963
0
  ok = 0;
964
0
  debug_f("good signature");
965
41
 send:
966
41
  notify_complete(notifier, "User presence confirmed");
967
968
41
  if (ok == 0) {
969
0
    if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
970
0
        (r = sshbuf_put_string(msg, signature, slen)) != 0)
971
0
      fatal_fr(r, "compose");
972
41
  } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
973
0
    fatal_fr(r, "compose failure");
974
975
41
  if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
976
0
    fatal_fr(r, "enqueue");
977
978
41
  sshbuf_free(sid);
979
41
  sshbuf_free(data);
980
41
  sshbuf_free(msg);
981
41
  sshkey_free(key);
982
41
  sshkey_free(hostkey);
983
41
  free(fp);
984
41
  free(signature);
985
41
  free(sig_dest);
986
41
  free(user);
987
41
  free(prompt);
988
41
  if (pin != NULL)
989
0
    freezero(pin, strlen(pin));
990
41
}
991
992
/* shared */
993
static void
994
process_remove_identity(SocketEntry *e)
995
7
{
996
7
  int r, success = 0;
997
7
  struct sshkey *key = NULL;
998
7
  Identity *id;
999
1000
7
  debug2_f("entering");
1001
7
  if ((r = sshkey_froms(e->request, &key)) != 0) {
1002
7
    error_fr(r, "parse key");
1003
7
    goto done;
1004
7
  }
1005
0
  if ((id = lookup_identity(key)) == NULL) {
1006
0
    debug_f("key not found");
1007
0
    goto done;
1008
0
  }
1009
  /* identity not visible, cannot be removed */
1010
0
  if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1011
0
    goto done; /* error already logged */
1012
  /* We have this key, free it. */
1013
0
  if (idtab->nentries < 1)
1014
0
    fatal_f("internal error: nentries %d", idtab->nentries);
1015
0
  TAILQ_REMOVE(&idtab->idlist, id, next);
1016
0
  free_identity(id);
1017
0
  idtab->nentries--;
1018
0
  success = 1;
1019
7
 done:
1020
7
  sshkey_free(key);
1021
7
  send_status(e, success);
1022
7
}
1023
1024
static void
1025
remove_all_identities(void)
1026
4
{
1027
4
  Identity *id;
1028
1029
4
  debug2_f("entering");
1030
  /* Loop over all identities and clear the keys. */
1031
34
  for (id = TAILQ_FIRST(&idtab->idlist); id;
1032
30
      id = TAILQ_FIRST(&idtab->idlist)) {
1033
30
    TAILQ_REMOVE(&idtab->idlist, id, next);
1034
30
    free_identity(id);
1035
30
  }
1036
1037
  /* Mark that there are no identities. */
1038
4
  idtab->nentries = 0;
1039
4
}
1040
1041
static void
1042
process_remove_all_identities(SocketEntry *e)
1043
4
{
1044
4
  remove_all_identities();
1045
1046
  /* Send success. */
1047
4
  send_status(e, 1);
1048
4
}
1049
1050
/* removes expired keys and returns number of seconds until the next expiry */
1051
static time_t
1052
reaper(void)
1053
0
{
1054
0
  time_t deadline = 0, now = monotime();
1055
0
  Identity *id, *nxt;
1056
1057
0
  for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1058
0
    nxt = TAILQ_NEXT(id, next);
1059
0
    if (id->death == 0)
1060
0
      continue;
1061
0
    if (now >= id->death) {
1062
0
      debug("expiring key '%s'", id->comment);
1063
0
      TAILQ_REMOVE(&idtab->idlist, id, next);
1064
0
      free_identity(id);
1065
0
      idtab->nentries--;
1066
0
    } else
1067
0
      deadline = (deadline == 0) ? id->death :
1068
0
          MINIMUM(deadline, id->death);
1069
0
  }
1070
0
  if (deadline == 0 || deadline <= now)
1071
0
    return 0;
1072
0
  else
1073
0
    return (deadline - now);
1074
0
}
1075
1076
static int
1077
parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
1078
0
{
1079
0
  u_char key_is_ca;
1080
0
  size_t elen = 0;
1081
0
  int r;
1082
0
  struct sshkey *k = NULL;
1083
0
  char *fp;
1084
1085
0
  memset(dch, '\0', sizeof(*dch));
1086
0
  if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
1087
0
      (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
1088
0
      (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1089
0
    error_fr(r, "parse");
1090
0
    goto out;
1091
0
  }
1092
0
  if (elen != 0) {
1093
0
    error_f("unsupported extensions (len %zu)", elen);
1094
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1095
0
    goto out;
1096
0
  }
1097
0
  if (*dch->hostname == '\0') {
1098
0
    free(dch->hostname);
1099
0
    dch->hostname = NULL;
1100
0
  }
1101
0
  if (*dch->user == '\0') {
1102
0
    free(dch->user);
1103
0
    dch->user = NULL;
1104
0
  }
1105
0
  while (sshbuf_len(b) != 0) {
1106
0
    dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1107
0
        dch->nkeys + 1, sizeof(*dch->keys));
1108
0
    dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1109
0
        dch->nkeys + 1, sizeof(*dch->key_is_ca));
1110
0
    if ((r = sshkey_froms(b, &k)) != 0 ||
1111
0
        (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1112
0
      goto out;
1113
0
    if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1114
0
        SSH_FP_DEFAULT)) == NULL)
1115
0
      fatal_f("fingerprint failed");
1116
0
    debug3_f("%s%s%s: adding %skey %s %s",
1117
0
        dch->user == NULL ? "" : dch->user,
1118
0
        dch->user == NULL ? "" : "@",
1119
0
        dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1120
0
    free(fp);
1121
0
    dch->keys[dch->nkeys] = k;
1122
0
    dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1123
0
    dch->nkeys++;
1124
0
    k = NULL; /* transferred */
1125
0
  }
1126
  /* success */
1127
0
  r = 0;
1128
0
 out:
1129
0
  sshkey_free(k);
1130
0
  return r;
1131
0
}
1132
1133
static int
1134
parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1135
0
{
1136
0
  struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1137
0
  int r;
1138
0
  size_t elen = 0;
1139
1140
0
  debug3_f("entering");
1141
1142
0
  memset(dc, '\0', sizeof(*dc));
1143
0
  if ((r = sshbuf_froms(m, &b)) != 0 ||
1144
0
      (r = sshbuf_froms(b, &frombuf)) != 0 ||
1145
0
      (r = sshbuf_froms(b, &tobuf)) != 0 ||
1146
0
      (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1147
0
    error_fr(r, "parse");
1148
0
    goto out;
1149
0
  }
1150
0
  if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1151
0
      (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1152
0
    goto out; /* already logged */
1153
0
  if (elen != 0) {
1154
0
    error_f("unsupported extensions (len %zu)", elen);
1155
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1156
0
    goto out;
1157
0
  }
1158
0
  debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1159
0
      dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1160
0
      dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1161
0
      dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1162
  /* check consistency */
1163
0
  if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1164
0
      dc->from.user != NULL) {
1165
0
    error_f("inconsistent \"from\" specification");
1166
0
    r = SSH_ERR_INVALID_FORMAT;
1167
0
    goto out;
1168
0
  }
1169
0
  if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1170
0
    error_f("incomplete \"to\" specification");
1171
0
    r = SSH_ERR_INVALID_FORMAT;
1172
0
    goto out;
1173
0
  }
1174
  /* success */
1175
0
  r = 0;
1176
0
 out:
1177
0
  sshbuf_free(b);
1178
0
  sshbuf_free(frombuf);
1179
0
  sshbuf_free(tobuf);
1180
0
  return r;
1181
0
}
1182
1183
static int
1184
parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1185
    struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp,
1186
    struct sshkey ***certs, size_t *ncerts)
1187
0
{
1188
0
  char *ext_name = NULL;
1189
0
  int r;
1190
0
  struct sshbuf *b = NULL;
1191
0
  u_char v;
1192
0
  struct sshkey *k;
1193
1194
0
  if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1195
0
    error_fr(r, "parse constraint extension");
1196
0
    goto out;
1197
0
  }
1198
0
  debug_f("constraint ext %s", ext_name);
1199
0
  if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1200
0
    if (sk_providerp == NULL) {
1201
0
      error_f("%s not valid here", ext_name);
1202
0
      r = SSH_ERR_INVALID_FORMAT;
1203
0
      goto out;
1204
0
    }
1205
0
    if (*sk_providerp != NULL) {
1206
0
      error_f("%s already set", ext_name);
1207
0
      r = SSH_ERR_INVALID_FORMAT;
1208
0
      goto out;
1209
0
    }
1210
0
    if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1211
0
      error_fr(r, "parse %s", ext_name);
1212
0
      goto out;
1213
0
    }
1214
0
  } else if (strcmp(ext_name,
1215
0
      "restrict-destination-v00@openssh.com") == 0) {
1216
0
    if (*dcsp != NULL) {
1217
0
      error_f("%s already set", ext_name);
1218
0
      r = SSH_ERR_INVALID_FORMAT;
1219
0
      goto out;
1220
0
    }
1221
0
    if ((r = sshbuf_froms(m, &b)) != 0) {
1222
0
      error_fr(r, "parse %s outer", ext_name);
1223
0
      goto out;
1224
0
    }
1225
0
    while (sshbuf_len(b) != 0) {
1226
0
      if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1227
0
        error_f("too many %s constraints", ext_name);
1228
0
        r = SSH_ERR_INVALID_FORMAT;
1229
0
        goto out;
1230
0
      }
1231
0
      *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1232
0
          sizeof(**dcsp));
1233
0
      if ((r = parse_dest_constraint(b,
1234
0
          *dcsp + (*ndcsp)++)) != 0)
1235
0
        goto out; /* error already logged */
1236
0
    }
1237
0
  } else if (strcmp(ext_name,
1238
0
      "associated-certs-v00@openssh.com") == 0) {
1239
0
    if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) {
1240
0
      error_f("%s not valid here", ext_name);
1241
0
      r = SSH_ERR_INVALID_FORMAT;
1242
0
      goto out;
1243
0
    }
1244
0
    if (*certs != NULL) {
1245
0
      error_f("%s already set", ext_name);
1246
0
      r = SSH_ERR_INVALID_FORMAT;
1247
0
      goto out;
1248
0
    }
1249
0
    if ((r = sshbuf_get_u8(m, &v)) != 0 ||
1250
0
        (r = sshbuf_froms(m, &b)) != 0) {
1251
0
      error_fr(r, "parse %s", ext_name);
1252
0
      goto out;
1253
0
    }
1254
0
    *cert_onlyp = v != 0;
1255
0
    while (sshbuf_len(b) != 0) {
1256
0
      if (*ncerts >= AGENT_MAX_EXT_CERTS) {
1257
0
        error_f("too many %s constraints", ext_name);
1258
0
        r = SSH_ERR_INVALID_FORMAT;
1259
0
        goto out;
1260
0
      }
1261
0
      *certs = xrecallocarray(*certs, *ncerts, *ncerts + 1,
1262
0
          sizeof(**certs));
1263
0
      if ((r = sshkey_froms(b, &k)) != 0) {
1264
0
        error_fr(r, "parse key");
1265
0
        goto out;
1266
0
      }
1267
0
      (*certs)[(*ncerts)++] = k;
1268
0
    }
1269
0
  } else {
1270
0
    error_f("unsupported constraint \"%s\"", ext_name);
1271
0
    r = SSH_ERR_FEATURE_UNSUPPORTED;
1272
0
    goto out;
1273
0
  }
1274
  /* success */
1275
0
  r = 0;
1276
0
 out:
1277
0
  free(ext_name);
1278
0
  sshbuf_free(b);
1279
0
  return r;
1280
0
}
1281
1282
static int
1283
parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1284
    u_int *secondsp, int *confirmp, char **sk_providerp,
1285
    struct dest_constraint **dcsp, size_t *ndcsp,
1286
    int *cert_onlyp, size_t *ncerts, struct sshkey ***certs)
1287
0
{
1288
0
  u_char ctype;
1289
0
  int r;
1290
0
  u_int seconds;
1291
1292
0
  while (sshbuf_len(m)) {
1293
0
    if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1294
0
      error_fr(r, "parse constraint type");
1295
0
      goto out;
1296
0
    }
1297
0
    switch (ctype) {
1298
0
    case SSH_AGENT_CONSTRAIN_LIFETIME:
1299
0
      if (*deathp != 0) {
1300
0
        error_f("lifetime already set");
1301
0
        r = SSH_ERR_INVALID_FORMAT;
1302
0
        goto out;
1303
0
      }
1304
0
      if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1305
0
        error_fr(r, "parse lifetime constraint");
1306
0
        goto out;
1307
0
      }
1308
0
      *deathp = monotime() + seconds;
1309
0
      *secondsp = seconds;
1310
0
      break;
1311
0
    case SSH_AGENT_CONSTRAIN_CONFIRM:
1312
0
      if (*confirmp != 0) {
1313
0
        error_f("confirm already set");
1314
0
        r = SSH_ERR_INVALID_FORMAT;
1315
0
        goto out;
1316
0
      }
1317
0
      *confirmp = 1;
1318
0
      break;
1319
0
    case SSH_AGENT_CONSTRAIN_EXTENSION:
1320
0
      if ((r = parse_key_constraint_extension(m,
1321
0
          sk_providerp, dcsp, ndcsp,
1322
0
          cert_onlyp, certs, ncerts)) != 0)
1323
0
        goto out; /* error already logged */
1324
0
      break;
1325
0
    default:
1326
0
      error_f("Unknown constraint %d", ctype);
1327
0
      r = SSH_ERR_FEATURE_UNSUPPORTED;
1328
0
      goto out;
1329
0
    }
1330
0
  }
1331
  /* success */
1332
0
  r = 0;
1333
0
 out:
1334
0
  return r;
1335
0
}
1336
1337
static void
1338
process_add_identity(SocketEntry *e)
1339
10
{
1340
10
  Identity *id;
1341
10
  int success = 0, confirm = 0;
1342
10
  char *fp, *comment = NULL, *sk_provider = NULL;
1343
10
  char canonical_provider[PATH_MAX];
1344
10
  time_t death = 0;
1345
10
  u_int seconds = 0;
1346
10
  struct dest_constraint *dest_constraints = NULL;
1347
10
  size_t ndest_constraints = 0;
1348
10
  struct sshkey *k = NULL;
1349
10
  int r = SSH_ERR_INTERNAL_ERROR;
1350
1351
10
  debug2_f("entering");
1352
10
  if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1353
0
      k == NULL ||
1354
10
      (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1355
10
    error_fr(r, "parse");
1356
10
    goto out;
1357
10
  }
1358
0
  if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1359
0
      &sk_provider, &dest_constraints, &ndest_constraints,
1360
0
      NULL, NULL, NULL) != 0) {
1361
0
    error_f("failed to parse constraints");
1362
0
    sshbuf_reset(e->request);
1363
0
    goto out;
1364
0
  }
1365
0
  dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1366
1367
0
  if (sk_provider != NULL) {
1368
0
    if (!sshkey_is_sk(k)) {
1369
0
      error("Cannot add provider: %s is not an "
1370
0
          "authenticator-hosted key", sshkey_type(k));
1371
0
      goto out;
1372
0
    }
1373
0
    if (strcasecmp(sk_provider, "internal") == 0) {
1374
0
      debug_f("internal provider");
1375
0
    } else {
1376
0
      if (socket_is_remote(e) && !remote_add_provider) {
1377
0
        verbose("failed add of SK provider \"%.100s\": "
1378
0
            "remote addition of providers is disabled",
1379
0
            sk_provider);
1380
0
        goto out;
1381
0
      }
1382
0
      if (realpath(sk_provider, canonical_provider) == NULL) {
1383
0
        verbose("failed provider \"%.100s\": "
1384
0
            "realpath: %s", sk_provider,
1385
0
            strerror(errno));
1386
0
        goto out;
1387
0
      }
1388
0
      free(sk_provider);
1389
0
      sk_provider = xstrdup(canonical_provider);
1390
0
      if (match_pattern_list(sk_provider,
1391
0
          allowed_providers, 0) != 1) {
1392
0
        error("Refusing add key: "
1393
0
            "provider %s not allowed", sk_provider);
1394
0
        goto out;
1395
0
      }
1396
0
    }
1397
0
  }
1398
0
  if ((r = sshkey_shield_private(k)) != 0) {
1399
0
    error_fr(r, "shield private");
1400
0
    goto out;
1401
0
  }
1402
0
  if (lifetime && !death)
1403
0
    death = monotime() + lifetime;
1404
0
  if ((id = lookup_identity(k)) == NULL) {
1405
0
    id = xcalloc(1, sizeof(Identity));
1406
0
    TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1407
    /* Increment the number of identities. */
1408
0
    idtab->nentries++;
1409
0
  } else {
1410
    /* identity not visible, do not update */
1411
0
    if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1412
0
      goto out; /* error already logged */
1413
    /* key state might have been updated */
1414
0
    sshkey_free(id->key);
1415
0
    free(id->comment);
1416
0
    free(id->sk_provider);
1417
0
    free_dest_constraints(id->dest_constraints,
1418
0
        id->ndest_constraints);
1419
0
  }
1420
  /* success */
1421
0
  id->key = k;
1422
0
  id->comment = comment;
1423
0
  id->death = death;
1424
0
  id->confirm = confirm;
1425
0
  id->sk_provider = sk_provider;
1426
0
  id->dest_constraints = dest_constraints;
1427
0
  id->ndest_constraints = ndest_constraints;
1428
1429
0
  if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1430
0
      SSH_FP_DEFAULT)) == NULL)
1431
0
    fatal_f("sshkey_fingerprint failed");
1432
0
  debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1433
0
      "(provider: %s) (destination constraints: %zu)",
1434
0
      sshkey_ssh_name(k), fp, comment, seconds, confirm,
1435
0
      sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1436
0
  free(fp);
1437
  /* transferred */
1438
0
  k = NULL;
1439
0
  comment = NULL;
1440
0
  sk_provider = NULL;
1441
0
  dest_constraints = NULL;
1442
0
  ndest_constraints = 0;
1443
0
  success = 1;
1444
10
 out:
1445
10
  free(sk_provider);
1446
10
  free(comment);
1447
10
  sshkey_free(k);
1448
10
  free_dest_constraints(dest_constraints, ndest_constraints);
1449
10
  send_status(e, success);
1450
10
}
1451
1452
/* XXX todo: encrypt sensitive data with passphrase */
1453
static void
1454
process_lock_agent(SocketEntry *e, int lock)
1455
9.00k
{
1456
9.00k
  int r, success = 0, delay;
1457
9.00k
  char *passwd;
1458
9.00k
  u_char passwdhash[LOCK_SIZE];
1459
9.00k
  static u_int fail_count = 0;
1460
9.00k
  size_t pwlen;
1461
1462
9.00k
  debug2_f("entering");
1463
  /*
1464
   * This is deliberately fatal: the user has requested that we lock,
1465
   * but we can't parse their request properly. The only safe thing to
1466
   * do is abort.
1467
   */
1468
9.00k
  if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1469
0
    fatal_fr(r, "parse");
1470
9.00k
  if (pwlen == 0) {
1471
3.30k
    debug("empty password not supported");
1472
5.70k
  } else if (locked && !lock) {
1473
5.70k
    if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1474
5.70k
        passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1475
0
      fatal("bcrypt_pbkdf");
1476
5.70k
    if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1477
0
      debug("agent unlocked");
1478
0
      locked = 0;
1479
0
      fail_count = 0;
1480
0
      explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1481
0
      success = 1;
1482
5.70k
    } else {
1483
      /* delay in 0.1s increments up to 10s */
1484
5.70k
      if (fail_count < 100)
1485
100
        fail_count++;
1486
5.70k
      delay = 100000 * fail_count;
1487
5.70k
      debug("unlock failed, delaying %0.1lf seconds",
1488
5.70k
          (double)delay/1000000);
1489
      // usleep(delay);
1490
5.70k
    }
1491
5.70k
    explicit_bzero(passwdhash, sizeof(passwdhash));
1492
5.70k
  } else if (!locked && lock) {
1493
1
    debug("agent locked");
1494
1
    locked = 1;
1495
1
    arc4random_buf(lock_salt, sizeof(lock_salt));
1496
1
    if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1497
1
        lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1498
0
      fatal("bcrypt_pbkdf");
1499
1
    success = 1;
1500
1
  }
1501
9.00k
  freezero(passwd, pwlen);
1502
9.00k
  send_status(e, success);
1503
9.00k
}
1504
1505
static void
1506
no_identities(SocketEntry *e)
1507
9.11k
{
1508
9.11k
  struct sshbuf *msg;
1509
9.11k
  int r;
1510
1511
9.11k
  if ((msg = sshbuf_new()) == NULL)
1512
0
    fatal_f("sshbuf_new failed");
1513
9.11k
  if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1514
9.11k
      (r = sshbuf_put_u32(msg, 0)) != 0 ||
1515
9.11k
      (r = sshbuf_put_stringb(e->output, msg)) != 0)
1516
0
    fatal_fr(r, "compose");
1517
9.11k
  sshbuf_free(msg);
1518
9.11k
}
1519
1520
#ifdef ENABLE_PKCS11
1521
/* Add an identity to idlist; takes ownership of 'key' and 'comment' */
1522
static void
1523
add_p11_identity(struct sshkey *key, char *comment, const char *provider,
1524
    time_t death, u_int confirm, struct dest_constraint *dest_constraints,
1525
    size_t ndest_constraints)
1526
0
{
1527
0
  Identity *id;
1528
1529
0
  if (lookup_identity(key) != NULL) {
1530
0
    sshkey_free(key);
1531
0
    free(comment);
1532
0
    return;
1533
0
  }
1534
0
  id = xcalloc(1, sizeof(Identity));
1535
0
  id->key = key;
1536
0
  id->comment = comment;
1537
0
  id->provider = xstrdup(provider);
1538
0
  id->death = death;
1539
0
  id->confirm = confirm;
1540
0
  id->dest_constraints = dup_dest_constraints(dest_constraints,
1541
0
      ndest_constraints);
1542
0
  id->ndest_constraints = ndest_constraints;
1543
0
  TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1544
0
  idtab->nentries++;
1545
0
}
1546
1547
static void
1548
process_add_smartcard_key(SocketEntry *e)
1549
18
{
1550
18
  char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1551
18
  char **comments = NULL;
1552
18
  int r, i, count = 0, success = 0, confirm = 0;
1553
18
  u_int seconds = 0;
1554
18
  time_t death = 0;
1555
18
  struct sshkey **keys = NULL, *k;
1556
18
  struct dest_constraint *dest_constraints = NULL;
1557
18
  size_t j, ndest_constraints = 0, ncerts = 0;
1558
18
  struct sshkey **certs = NULL;
1559
18
  int cert_only = 0;
1560
1561
18
  debug2_f("entering");
1562
18
  if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1563
18
      (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1564
18
    error_fr(r, "parse");
1565
18
    goto send;
1566
18
  }
1567
0
  if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1568
0
      NULL, &dest_constraints, &ndest_constraints, &cert_only,
1569
0
      &ncerts, &certs) != 0) {
1570
0
    error_f("failed to parse constraints");
1571
0
    goto send;
1572
0
  }
1573
0
  dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1574
0
  if (socket_is_remote(e) && !remote_add_provider) {
1575
0
    verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1576
0
        "providers is disabled", provider);
1577
0
    goto send;
1578
0
  }
1579
0
  if (realpath(provider, canonical_provider) == NULL) {
1580
0
    verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1581
0
        provider, strerror(errno));
1582
0
    goto send;
1583
0
  }
1584
0
  if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1585
0
    verbose("refusing PKCS#11 add of \"%.100s\": "
1586
0
        "provider not allowed", canonical_provider);
1587
0
    goto send;
1588
0
  }
1589
0
  debug_f("add %.100s", canonical_provider);
1590
0
  if (lifetime && !death)
1591
0
    death = monotime() + lifetime;
1592
1593
0
  count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1594
0
  for (i = 0; i < count; i++) {
1595
0
    if (comments[i] == NULL || comments[i][0] == '\0') {
1596
0
      free(comments[i]);
1597
0
      comments[i] = xstrdup(canonical_provider);
1598
0
    }
1599
0
    for (j = 0; j < ncerts; j++) {
1600
0
      if (!sshkey_is_cert(certs[j]))
1601
0
        continue;
1602
0
      if (!sshkey_equal_public(keys[i], certs[j]))
1603
0
        continue;
1604
0
      if (pkcs11_make_cert(keys[i], certs[j], &k) != 0)
1605
0
        continue;
1606
0
      add_p11_identity(k, xstrdup(comments[i]),
1607
0
          canonical_provider, death, confirm,
1608
0
          dest_constraints, ndest_constraints);
1609
0
      success = 1;
1610
0
    }
1611
0
    if (!cert_only && lookup_identity(keys[i]) == NULL) {
1612
0
      add_p11_identity(keys[i], comments[i],
1613
0
          canonical_provider, death, confirm,
1614
0
          dest_constraints, ndest_constraints);
1615
0
      keys[i] = NULL;   /* transferred */
1616
0
      comments[i] = NULL; /* transferred */
1617
0
      success = 1;
1618
0
    }
1619
    /* XXX update constraints for existing keys */
1620
0
    sshkey_free(keys[i]);
1621
0
    free(comments[i]);
1622
0
  }
1623
18
send:
1624
18
  free(pin);
1625
18
  free(provider);
1626
18
  free(keys);
1627
18
  free(comments);
1628
18
  free_dest_constraints(dest_constraints, ndest_constraints);
1629
18
  for (j = 0; j < ncerts; j++)
1630
0
    sshkey_free(certs[j]);
1631
18
  free(certs);
1632
18
  send_status(e, success);
1633
18
}
1634
1635
static void
1636
process_remove_smartcard_key(SocketEntry *e)
1637
17
{
1638
17
  char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1639
17
  int r, success = 0;
1640
17
  Identity *id, *nxt;
1641
1642
17
  debug2_f("entering");
1643
17
  if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1644
17
      (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1645
17
    error_fr(r, "parse");
1646
17
    goto send;
1647
17
  }
1648
0
  free(pin);
1649
1650
0
  if (realpath(provider, canonical_provider) == NULL) {
1651
0
    verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1652
0
        provider, strerror(errno));
1653
0
    goto send;
1654
0
  }
1655
1656
0
  debug_f("remove %.100s", canonical_provider);
1657
0
  for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1658
0
    nxt = TAILQ_NEXT(id, next);
1659
    /* Skip file--based keys */
1660
0
    if (id->provider == NULL)
1661
0
      continue;
1662
0
    if (!strcmp(canonical_provider, id->provider)) {
1663
0
      TAILQ_REMOVE(&idtab->idlist, id, next);
1664
0
      free_identity(id);
1665
0
      idtab->nentries--;
1666
0
    }
1667
0
  }
1668
0
  if (pkcs11_del_provider(canonical_provider) == 0)
1669
0
    success = 1;
1670
0
  else
1671
0
    error_f("pkcs11_del_provider failed");
1672
17
send:
1673
17
  free(provider);
1674
17
  send_status(e, success);
1675
17
}
1676
#endif /* ENABLE_PKCS11 */
1677
1678
static int
1679
process_ext_session_bind(SocketEntry *e)
1680
0
{
1681
0
  int r, sid_match, key_match;
1682
0
  struct sshkey *key = NULL;
1683
0
  struct sshbuf *sid = NULL, *sig = NULL;
1684
0
  char *fp = NULL;
1685
0
  size_t i;
1686
0
  u_char fwd = 0;
1687
1688
0
  debug2_f("entering");
1689
0
  e->session_bind_attempted = 1;
1690
0
  if ((r = sshkey_froms(e->request, &key)) != 0 ||
1691
0
      (r = sshbuf_froms(e->request, &sid)) != 0 ||
1692
0
      (r = sshbuf_froms(e->request, &sig)) != 0 ||
1693
0
      (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1694
0
    error_fr(r, "parse");
1695
0
    goto out;
1696
0
  }
1697
0
  if (sshbuf_len(sid) > AGENT_MAX_SID_LEN) {
1698
0
    error_f("session ID too long");
1699
0
    goto out;
1700
0
  }
1701
0
  if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1702
0
      SSH_FP_DEFAULT)) == NULL)
1703
0
    fatal_f("fingerprint failed");
1704
  /* check signature with hostkey on session ID */
1705
0
  if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1706
0
      sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1707
0
    error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1708
0
    goto out;
1709
0
  }
1710
  /* check whether sid/key already recorded */
1711
0
  for (i = 0; i < e->nsession_ids; i++) {
1712
0
    if (!e->session_ids[i].forwarded) {
1713
0
      error_f("attempt to bind session ID to socket "
1714
0
          "previously bound for authentication attempt");
1715
0
      r = -1;
1716
0
      goto out;
1717
0
    }
1718
0
    sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1719
0
    key_match = sshkey_equal(key, e->session_ids[i].key);
1720
0
    if (sid_match && key_match) {
1721
0
      debug_f("session ID already recorded for %s %s",
1722
0
          sshkey_type(key), fp);
1723
0
      r = 0;
1724
0
      goto out;
1725
0
    } else if (sid_match) {
1726
0
      error_f("session ID recorded against different key "
1727
0
          "for %s %s", sshkey_type(key), fp);
1728
0
      r = -1;
1729
0
      goto out;
1730
0
    }
1731
    /*
1732
     * new sid with previously-seen key can happen, e.g. multiple
1733
     * connections to the same host.
1734
     */
1735
0
  }
1736
  /* record new key/sid */
1737
0
  if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1738
0
    error_f("too many session IDs recorded");
1739
0
    r = -1;
1740
0
    goto out;
1741
0
  }
1742
0
  e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1743
0
      e->nsession_ids + 1, sizeof(*e->session_ids));
1744
0
  i = e->nsession_ids++;
1745
0
  debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1746
0
      AGENT_MAX_SESSION_IDS);
1747
0
  e->session_ids[i].key = key;
1748
0
  e->session_ids[i].forwarded = fwd != 0;
1749
0
  key = NULL; /* transferred */
1750
  /* can't transfer sid; it's refcounted and scoped to request's life */
1751
0
  if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1752
0
    fatal_f("sshbuf_new");
1753
0
  if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1754
0
    fatal_fr(r, "sshbuf_putb session ID");
1755
  /* success */
1756
0
  r = 0;
1757
0
 out:
1758
0
  free(fp);
1759
0
  sshkey_free(key);
1760
0
  sshbuf_free(sid);
1761
0
  sshbuf_free(sig);
1762
0
  return r == 0 ? 1 : 0;
1763
0
}
1764
1765
static int
1766
process_ext_query(SocketEntry *e)
1767
0
{
1768
0
  int r;
1769
0
  struct sshbuf *msg = NULL;
1770
1771
0
  debug2_f("entering");
1772
0
  if ((msg = sshbuf_new()) == NULL)
1773
0
    fatal_f("sshbuf_new failed");
1774
0
  if ((r = sshbuf_put_u8(msg, SSH_AGENT_EXTENSION_RESPONSE)) != 0 ||
1775
0
      (r = sshbuf_put_cstring(msg, "query")) != 0 ||
1776
      /* string[]     supported extension types */
1777
0
      (r = sshbuf_put_cstring(msg, "session-bind@openssh.com")) != 0)
1778
0
    fatal_fr(r, "compose");
1779
0
  if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
1780
0
    fatal_fr(r, "enqueue");
1781
0
  sshbuf_free(msg);
1782
0
  return 1;
1783
0
}
1784
1785
static void
1786
process_extension(SocketEntry *e)
1787
4
{
1788
4
  int r, success = 0;
1789
4
  char *name;
1790
1791
4
  debug2_f("entering");
1792
4
  if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1793
3
    error_fr(r, "parse");
1794
3
    send_status(e, 0);
1795
3
    return;
1796
3
  }
1797
1798
1
  if (strcmp(name, "query") == 0)
1799
0
    success = process_ext_query(e);
1800
1
  else if (strcmp(name, "session-bind@openssh.com") == 0)
1801
0
    success = process_ext_session_bind(e);
1802
1
  else {
1803
1
    debug_f("unsupported extension \"%s\"", name);
1804
1
    free(name);
1805
1
    send_status(e, 0);
1806
1
    return;
1807
1
  }
1808
0
  free(name);
1809
  /* Agent failures are signalled with a different error code */
1810
0
  send_status_generic(e,
1811
0
      success ? SSH_AGENT_SUCCESS : SSH_AGENT_EXTENSION_FAILURE);
1812
0
}
1813
1814
/*
1815
 * dispatch incoming message.
1816
 * returns 1 on success, 0 for incomplete messages or -1 on error.
1817
 */
1818
static int
1819
process_message(u_int socknum)
1820
122k
{
1821
122k
  u_int msg_len;
1822
122k
  u_char type;
1823
122k
  const u_char *cp;
1824
122k
  int r;
1825
122k
  SocketEntry *e;
1826
1827
122k
  if (socknum >= sockets_alloc)
1828
0
    fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1829
122k
  e = &sockets[socknum];
1830
1831
122k
  if (sshbuf_len(e->input) < 5)
1832
188
    return 0;    /* Incomplete message header. */
1833
122k
  cp = sshbuf_ptr(e->input);
1834
122k
  msg_len = PEEK_U32(cp);
1835
122k
  if (msg_len > AGENT_MAX_LEN) {
1836
768
    debug_f("socket %u (fd=%d) message too long %u > %u",
1837
768
        socknum, e->fd, msg_len, AGENT_MAX_LEN);
1838
768
    return -1;
1839
768
  }
1840
121k
  if (sshbuf_len(e->input) < msg_len + 4)
1841
279
    return 0;    /* Incomplete message body. */
1842
1843
  /* move the current input to e->request */
1844
121k
  sshbuf_reset(e->request);
1845
121k
  if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1846
121k
      (r = sshbuf_get_u8(e->request, &type)) != 0) {
1847
71.3k
    if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1848
71.3k
        r == SSH_ERR_STRING_TOO_LARGE) {
1849
71.3k
      error_fr(r, "parse");
1850
71.3k
      return -1;
1851
71.3k
    }
1852
71.3k
    fatal_fr(r, "parse");
1853
71.3k
  }
1854
1855
50.1k
  debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1856
1857
  /* check whether agent is locked */
1858
50.1k
  if (locked && type != SSH_AGENTC_UNLOCK) {
1859
41.0k
    sshbuf_reset(e->request);
1860
41.0k
    switch (type) {
1861
9.11k
    case SSH2_AGENTC_REQUEST_IDENTITIES:
1862
      /* send empty lists */
1863
9.11k
      no_identities(e);
1864
9.11k
      break;
1865
31.9k
    default:
1866
      /* send a fail message for all other request types */
1867
31.9k
      send_status(e, 0);
1868
41.0k
    }
1869
41.0k
    return 1;
1870
41.0k
  }
1871
1872
9.11k
  switch (type) {
1873
2
  case SSH_AGENTC_LOCK:
1874
9.00k
  case SSH_AGENTC_UNLOCK:
1875
9.00k
    process_lock_agent(e, type == SSH_AGENTC_LOCK);
1876
9.00k
    break;
1877
1
  case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1878
1
    process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1879
1
    break;
1880
  /* ssh2 */
1881
41
  case SSH2_AGENTC_SIGN_REQUEST:
1882
41
    process_sign_request2(e);
1883
41
    break;
1884
4
  case SSH2_AGENTC_REQUEST_IDENTITIES:
1885
4
    process_request_identities(e);
1886
4
    break;
1887
6
  case SSH2_AGENTC_ADD_IDENTITY:
1888
10
  case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1889
10
    process_add_identity(e);
1890
10
    break;
1891
7
  case SSH2_AGENTC_REMOVE_IDENTITY:
1892
7
    process_remove_identity(e);
1893
7
    break;
1894
3
  case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1895
3
    process_remove_all_identities(e);
1896
3
    break;
1897
0
#ifdef ENABLE_PKCS11
1898
12
  case SSH_AGENTC_ADD_SMARTCARD_KEY:
1899
18
  case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1900
18
    process_add_smartcard_key(e);
1901
18
    break;
1902
17
  case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1903
17
    process_remove_smartcard_key(e);
1904
17
    break;
1905
0
#endif /* ENABLE_PKCS11 */
1906
4
  case SSH_AGENTC_EXTENSION:
1907
4
    process_extension(e);
1908
4
    break;
1909
8
  default:
1910
    /* Unknown message.  Respond with failure. */
1911
8
    error("Unknown message %d", type);
1912
8
    sshbuf_reset(e->request);
1913
8
    send_status(e, 0);
1914
8
    break;
1915
9.11k
  }
1916
9.11k
  return 1;
1917
9.11k
}
1918
1919
static void
1920
new_socket(sock_type type, int fd)
1921
1.67k
{
1922
1.67k
  u_int i, old_alloc, new_alloc;
1923
1924
1.67k
  debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1925
1.67k
      (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1926
1.67k
  set_nonblock(fd);
1927
1928
1.67k
  if (fd > max_fd)
1929
1
    max_fd = fd;
1930
1931
1.67k
  for (i = 0; i < sockets_alloc; i++)
1932
0
    if (sockets[i].type == AUTH_UNUSED) {
1933
0
      sockets[i].fd = fd;
1934
0
      if ((sockets[i].input = sshbuf_new()) == NULL ||
1935
0
          (sockets[i].output = sshbuf_new()) == NULL ||
1936
0
          (sockets[i].request = sshbuf_new()) == NULL)
1937
0
        fatal_f("sshbuf_new failed");
1938
0
      sockets[i].type = type;
1939
0
      return;
1940
0
    }
1941
1.67k
  old_alloc = sockets_alloc;
1942
1.67k
  new_alloc = sockets_alloc + 10;
1943
1.67k
  sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1944
1.67k
      sizeof(sockets[0]));
1945
18.3k
  for (i = old_alloc; i < new_alloc; i++)
1946
16.7k
    sockets[i].type = AUTH_UNUSED;
1947
1.67k
  sockets_alloc = new_alloc;
1948
1.67k
  sockets[old_alloc].fd = fd;
1949
1.67k
  if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1950
1.67k
      (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1951
1.67k
      (sockets[old_alloc].request = sshbuf_new()) == NULL)
1952
0
    fatal_f("sshbuf_new failed");
1953
1.67k
  sockets[old_alloc].type = type;
1954
1.67k
}
1955
1956
static int
1957
handle_socket_read(u_int socknum)
1958
0
{
1959
0
  struct sockaddr_un sunaddr;
1960
0
  socklen_t slen;
1961
0
  uid_t euid;
1962
0
  gid_t egid;
1963
0
  int fd;
1964
1965
0
  slen = sizeof(sunaddr);
1966
0
  fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1967
0
  if (fd == -1) {
1968
0
    error("accept from AUTH_SOCKET: %s", strerror(errno));
1969
0
    return -1;
1970
0
  }
1971
0
  if (getpeereid(fd, &euid, &egid) == -1) {
1972
0
    error("getpeereid %d failed: %s", fd, strerror(errno));
1973
0
    close(fd);
1974
0
    return -1;
1975
0
  }
1976
0
  if ((euid != 0) && (getuid() != euid)) {
1977
0
    error("uid mismatch: peer euid %u != uid %u",
1978
0
        (u_int) euid, (u_int) getuid());
1979
0
    close(fd);
1980
0
    return -1;
1981
0
  }
1982
0
  new_socket(AUTH_CONNECTION, fd);
1983
0
  return 0;
1984
0
}
1985
1986
static int
1987
handle_conn_read(u_int socknum)
1988
0
{
1989
0
  char buf[AGENT_RBUF_LEN];
1990
0
  ssize_t len;
1991
0
  int r;
1992
1993
0
  if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1994
0
    if (len == -1) {
1995
0
      if (errno == EAGAIN || errno == EINTR)
1996
0
        return 0;
1997
0
      error_f("read error on socket %u (fd %d): %s",
1998
0
          socknum, sockets[socknum].fd, strerror(errno));
1999
0
    }
2000
0
    return -1;
2001
0
  }
2002
0
  if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
2003
0
    fatal_fr(r, "compose");
2004
0
  explicit_bzero(buf, sizeof(buf));
2005
0
  for (;;) {
2006
0
    if ((r = process_message(socknum)) == -1)
2007
0
      return -1;
2008
0
    else if (r == 0)
2009
0
      break;
2010
0
  }
2011
0
  return 0;
2012
0
}
2013
2014
static int
2015
handle_conn_write(u_int socknum)
2016
0
{
2017
0
  ssize_t len;
2018
0
  int r;
2019
2020
0
  if (sshbuf_len(sockets[socknum].output) == 0)
2021
0
    return 0; /* shouldn't happen */
2022
0
  if ((len = write(sockets[socknum].fd,
2023
0
      sshbuf_ptr(sockets[socknum].output),
2024
0
      sshbuf_len(sockets[socknum].output))) <= 0) {
2025
0
    if (len == -1) {
2026
0
      if (errno == EAGAIN || errno == EINTR)
2027
0
        return 0;
2028
0
      error_f("read error on socket %u (fd %d): %s",
2029
0
          socknum, sockets[socknum].fd, strerror(errno));
2030
0
    }
2031
0
    return -1;
2032
0
  }
2033
0
  if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
2034
0
    fatal_fr(r, "consume");
2035
0
  return 0;
2036
0
}
2037
2038
static void
2039
after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
2040
0
{
2041
0
  size_t i;
2042
0
  u_int socknum, activefds = npfd;
2043
2044
0
  for (i = 0; i < npfd; i++) {
2045
0
    if (pfd[i].revents == 0)
2046
0
      continue;
2047
    /* Find sockets entry */
2048
0
    for (socknum = 0; socknum < sockets_alloc; socknum++) {
2049
0
      if (sockets[socknum].type != AUTH_SOCKET &&
2050
0
          sockets[socknum].type != AUTH_CONNECTION)
2051
0
        continue;
2052
0
      if (pfd[i].fd == sockets[socknum].fd)
2053
0
        break;
2054
0
    }
2055
0
    if (socknum >= sockets_alloc) {
2056
0
      error_f("no socket for fd %d", pfd[i].fd);
2057
0
      continue;
2058
0
    }
2059
    /* Process events */
2060
0
    switch (sockets[socknum].type) {
2061
0
    case AUTH_SOCKET:
2062
0
      if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
2063
0
        break;
2064
0
      if (npfd > maxfds) {
2065
0
        debug3("out of fds (active %u >= limit %u); "
2066
0
            "skipping accept", activefds, maxfds);
2067
0
        break;
2068
0
      }
2069
0
      if (handle_socket_read(socknum) == 0)
2070
0
        activefds++;
2071
0
      break;
2072
0
    case AUTH_CONNECTION:
2073
0
      if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
2074
0
          handle_conn_read(socknum) != 0)
2075
0
        goto close_sock;
2076
0
      if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
2077
0
          handle_conn_write(socknum) != 0) {
2078
0
 close_sock:
2079
0
        if (activefds == 0)
2080
0
          fatal("activefds == 0 at close_sock");
2081
0
        close_socket(&sockets[socknum]);
2082
0
        activefds--;
2083
0
        break;
2084
0
      }
2085
0
      break;
2086
0
    default:
2087
0
      break;
2088
0
    }
2089
0
  }
2090
0
}
2091
2092
static int
2093
prepare_poll(struct pollfd **pfdp, size_t *npfdp, struct timespec *timeoutp, u_int maxfds)
2094
0
{
2095
0
  struct pollfd *pfd = *pfdp;
2096
0
  size_t i, j, npfd = 0;
2097
0
  time_t deadline;
2098
0
  int r;
2099
2100
  /* Count active sockets */
2101
0
  for (i = 0; i < sockets_alloc; i++) {
2102
0
    switch (sockets[i].type) {
2103
0
    case AUTH_SOCKET:
2104
0
    case AUTH_CONNECTION:
2105
0
      npfd++;
2106
0
      break;
2107
0
    case AUTH_UNUSED:
2108
0
      break;
2109
0
    default:
2110
0
      fatal("Unknown socket type %d", sockets[i].type);
2111
0
      break;
2112
0
    }
2113
0
  }
2114
0
  if (npfd != *npfdp &&
2115
0
      (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
2116
0
    fatal_f("recallocarray failed");
2117
0
  *pfdp = pfd;
2118
0
  *npfdp = npfd;
2119
2120
0
  for (i = j = 0; i < sockets_alloc; i++) {
2121
0
    switch (sockets[i].type) {
2122
0
    case AUTH_SOCKET:
2123
0
      if (npfd > maxfds) {
2124
0
        debug3("out of fds (active %zu >= limit %u); "
2125
0
            "skipping arming listener", npfd, maxfds);
2126
0
        break;
2127
0
      }
2128
0
      pfd[j].fd = sockets[i].fd;
2129
0
      pfd[j].revents = 0;
2130
0
      pfd[j].events = POLLIN;
2131
0
      j++;
2132
0
      break;
2133
0
    case AUTH_CONNECTION:
2134
0
      pfd[j].fd = sockets[i].fd;
2135
0
      pfd[j].revents = 0;
2136
      /*
2137
       * Only prepare to read if we can handle a full-size
2138
       * input read buffer and enqueue a max size reply..
2139
       */
2140
0
      if ((r = sshbuf_check_reserve(sockets[i].input,
2141
0
          AGENT_RBUF_LEN)) == 0 &&
2142
0
          (r = sshbuf_check_reserve(sockets[i].output,
2143
0
          AGENT_MAX_LEN)) == 0)
2144
0
        pfd[j].events = POLLIN;
2145
0
      else if (r != SSH_ERR_NO_BUFFER_SPACE)
2146
0
        fatal_fr(r, "reserve");
2147
0
      if (sshbuf_len(sockets[i].output) > 0)
2148
0
        pfd[j].events |= POLLOUT;
2149
0
      j++;
2150
0
      break;
2151
0
    default:
2152
0
      break;
2153
0
    }
2154
0
  }
2155
0
  deadline = reaper();
2156
0
  if (parent_alive_interval != 0)
2157
0
    deadline = (deadline == 0) ? parent_alive_interval :
2158
0
        MINIMUM(deadline, parent_alive_interval);
2159
0
  if (deadline != 0)
2160
0
    ptimeout_deadline_sec(timeoutp, deadline);
2161
0
  return (1);
2162
0
}
2163
2164
static void
2165
cleanup_socket(void)
2166
0
{
2167
0
  if (cleanup_pid != 0 && getpid() != cleanup_pid)
2168
0
    return;
2169
0
  debug_f("cleanup");
2170
0
  if (socket_name != NULL) {
2171
0
    unlink(socket_name);
2172
0
    free(socket_name);
2173
0
    socket_name = NULL;
2174
0
  }
2175
0
  if (socket_dir[0])
2176
0
    rmdir(socket_dir);
2177
0
}
2178
2179
void
2180
cleanup_exit(int i)
2181
0
{
2182
0
  cleanup_socket();
2183
0
#ifdef ENABLE_PKCS11
2184
0
  pkcs11_terminate();
2185
0
#endif
2186
0
  _exit(i);
2187
0
}
2188
2189
static void
2190
cleanup_handler(int sig)
2191
0
{
2192
0
  signalled_exit = sig;
2193
0
}
2194
2195
static void
2196
keydrop_handler(int sig)
2197
0
{
2198
0
  signalled_keydrop = sig;
2199
0
}
2200
2201
static void
2202
check_parent_exists(void)
2203
0
{
2204
  /*
2205
   * If our parent has exited then getppid() will return (pid_t)1,
2206
   * so testing for that should be safe.
2207
   */
2208
0
  if (parent_pid != -1 && getppid() != parent_pid) {
2209
    /* printf("Parent has died - Authentication agent exiting.\n"); */
2210
0
    cleanup_socket();
2211
0
    _exit(2);
2212
0
  }
2213
0
}
2214
2215
static void
2216
usage(void)
2217
0
{
2218
0
  fprintf(stderr,
2219
0
      "usage: ssh-agent [-c | -s] [-DdTU] [-a bind_address] [-E fingerprint_hash]\n"
2220
0
      "                 [-O option] [-P allowed_providers] [-t life]\n"
2221
0
      "       ssh-agent [-TU] [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2222
0
      "                 [-P allowed_providers] [-t life] command [arg ...]\n"
2223
0
      "       ssh-agent [-c | -s] -k\n"
2224
0
      "       ssh-agent -u\n");
2225
0
  exit(1);
2226
0
}
2227
2228
int
2229
main(int ac, char **av)
2230
0
{
2231
0
  int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0;
2232
0
  int s_flag = 0, T_flag = 0, u_flag = 0, U_flag = 0;
2233
0
  int sock = -1, ch, result, saved_errno;
2234
0
  pid_t pid;
2235
0
  char *homedir = NULL, *shell, *format, *pidstr, *agentsocket = NULL;
2236
0
  char *cp, pidstrbuf[1 + 3 * sizeof pid];
2237
0
  char *fdstr;
2238
0
  const char *errstr = NULL;
2239
0
  const char *ccp;
2240
0
#ifdef HAVE_SETRLIMIT
2241
0
  struct rlimit rlim;
2242
0
#endif
2243
0
  extern int optind;
2244
0
  extern char *optarg;
2245
0
  size_t len;
2246
0
  mode_t prev_mask;
2247
0
  struct timespec timeout;
2248
0
  struct pollfd *pfd = NULL;
2249
0
  size_t npfd = 0;
2250
0
  u_int maxfds;
2251
0
  sigset_t nsigset, osigset;
2252
0
  int socket_activated = 0;
2253
2254
  /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2255
0
  sanitise_stdfd();
2256
2257
  /* drop */
2258
0
  (void)setegid(getgid());
2259
0
  (void)setgid(getgid());
2260
2261
0
  platform_disable_tracing(0);  /* strict=no */
2262
2263
0
#ifdef RLIMIT_NOFILE
2264
0
  if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2265
0
    fatal("%s: getrlimit: %s", __progname, strerror(errno));
2266
0
#endif
2267
2268
0
  __progname = ssh_get_progname(av[0]);
2269
0
  seed_rng();
2270
2271
0
  while ((ch = getopt(ac, av, "cDdksTuUE:a:O:P:t:")) != -1) {
2272
0
    switch (ch) {
2273
0
    case 'E':
2274
0
      fingerprint_hash = ssh_digest_alg_by_name(optarg);
2275
0
      if (fingerprint_hash == -1)
2276
0
        fatal("Invalid hash algorithm \"%s\"", optarg);
2277
0
      break;
2278
0
    case 'c':
2279
0
      if (s_flag)
2280
0
        usage();
2281
0
      c_flag++;
2282
0
      break;
2283
0
    case 'k':
2284
0
      k_flag++;
2285
0
      break;
2286
0
    case 'O':
2287
0
      if (strcmp(optarg, "no-restrict-websafe") == 0)
2288
0
        restrict_websafe = 0;
2289
0
      else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
2290
0
        remote_add_provider = 1;
2291
0
      else if ((ccp = strprefix(optarg,
2292
0
          "websafe-allow=", 0)) != NULL) {
2293
0
        if (websafe_allowlist != NULL)
2294
0
          fatal("websafe-allow already set");
2295
0
        websafe_allowlist = xstrdup(ccp);
2296
0
      } else
2297
0
        fatal("Unknown -O option");
2298
0
      break;
2299
0
    case 'P':
2300
0
      if (allowed_providers != NULL)
2301
0
        fatal("-P option already specified");
2302
0
      allowed_providers = xstrdup(optarg);
2303
0
      break;
2304
0
    case 's':
2305
0
      if (c_flag)
2306
0
        usage();
2307
0
      s_flag++;
2308
0
      break;
2309
0
    case 'd':
2310
0
      if (d_flag || D_flag)
2311
0
        usage();
2312
0
      d_flag++;
2313
0
      break;
2314
0
    case 'D':
2315
0
      if (d_flag || D_flag)
2316
0
        usage();
2317
0
      D_flag++;
2318
0
      break;
2319
0
    case 'a':
2320
0
      agentsocket = optarg;
2321
0
      break;
2322
0
    case 't':
2323
0
      if ((lifetime = convtime(optarg)) == -1) {
2324
0
        fprintf(stderr, "Invalid lifetime\n");
2325
0
        usage();
2326
0
      }
2327
0
      break;
2328
0
    case 'T':
2329
0
      T_flag++;
2330
0
      break;
2331
0
    case 'u':
2332
0
      u_flag++;
2333
0
      break;
2334
0
    case 'U':
2335
0
      U_flag++;
2336
0
      break;
2337
0
    default:
2338
0
      usage();
2339
0
    }
2340
0
  }
2341
0
  ac -= optind;
2342
0
  av += optind;
2343
2344
0
  if (ac > 0 &&
2345
0
      (c_flag || k_flag || s_flag || d_flag || D_flag || u_flag))
2346
0
    usage();
2347
2348
0
  log_init(__progname,
2349
0
      d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2350
0
      SYSLOG_FACILITY_AUTH, 1);
2351
2352
0
  if (allowed_providers == NULL)
2353
0
    allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2354
0
  if (websafe_allowlist == NULL)
2355
0
    websafe_allowlist = xstrdup(DEFAULT_WEBSAFE_ALLOWLIST);
2356
2357
0
  if (ac == 0 && !c_flag && !s_flag) {
2358
0
    shell = getenv("SHELL");
2359
0
    if (shell != NULL && (len = strlen(shell)) > 2 &&
2360
0
        strncmp(shell + len - 3, "csh", 3) == 0)
2361
0
      c_flag = 1;
2362
0
  }
2363
0
  if (k_flag) {
2364
0
    pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2365
0
    if (pidstr == NULL) {
2366
0
      fprintf(stderr, "%s not set, cannot kill agent\n",
2367
0
          SSH_AGENTPID_ENV_NAME);
2368
0
      exit(1);
2369
0
    }
2370
0
    pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2371
0
    if (errstr) {
2372
0
      fprintf(stderr,
2373
0
          "%s=\"%s\", which is not a good PID: %s\n",
2374
0
          SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2375
0
      exit(1);
2376
0
    }
2377
0
    if (kill(pid, SIGTERM) == -1) {
2378
0
      perror("kill");
2379
0
      exit(1);
2380
0
    }
2381
0
    format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
2382
0
    printf(format, SSH_AUTHSOCKET_ENV_NAME);
2383
0
    printf(format, SSH_AGENTPID_ENV_NAME);
2384
0
    printf("echo Agent pid %ld killed;\n", (long)pid);
2385
0
    exit(0);
2386
0
  }
2387
0
  if (u_flag) {
2388
0
    if ((homedir = get_homedir()) == NULL)
2389
0
      fatal("Couldn't determine home directory");
2390
0
    agent_cleanup_stale(homedir, u_flag > 1);
2391
0
    printf("Deleted stale agent sockets in ~/%s\n",
2392
0
        _PATH_SSH_AGENT_SOCKET_DIR);
2393
0
    exit(0);
2394
0
  }
2395
2396
  /*
2397
   * Minimum file descriptors:
2398
   * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2399
   * a few spare for libc / stack protectors / sanitisers, etc.
2400
   */
2401
0
#define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2402
0
  if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2403
0
    fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2404
0
        __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2405
0
  maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2406
2407
0
  parent_pid = getpid();
2408
2409
  /* Has the socket been provided via socket activation? */
2410
0
  if (agentsocket == NULL && ac == 0 && (d_flag || D_flag) &&
2411
0
      (pidstr = getenv("LISTEN_PID")) != NULL &&
2412
0
      (fdstr = getenv("LISTEN_FDS")) != NULL) {
2413
0
    if (strcmp(fdstr, "1") != 0) {
2414
0
      fatal("unexpected LISTEN_FDS contents "
2415
0
          "(want: \"1\" got\"%s\"", fdstr);
2416
0
    }
2417
0
    if (fcntl(3, F_GETFL) == -1)
2418
0
      fatal("LISTEN_FDS set but fd 3 unavailable");
2419
0
    pid = (int)strtonum(pidstr, 1, INT_MAX, &errstr);
2420
0
    if (errstr != NULL)
2421
0
      fatal("invalid LISTEN_PID: %s", errstr);
2422
0
    if (pid != getpid())
2423
0
      fatal("bad LISTEN_PID: %d vs pid %d", pid, getpid());
2424
0
    debug("using socket activation on fd=3");
2425
0
    sock = 3;
2426
0
    socket_activated = 1;
2427
0
  }
2428
2429
0
  if (sock == -1 && agentsocket == NULL && !T_flag) {
2430
    /* Default case: ~/.ssh/agent/[socket] */
2431
0
    if ((homedir = get_homedir()) == NULL)
2432
0
      fatal("Couldn't determine home directory");
2433
0
    if (!U_flag)
2434
0
      agent_cleanup_stale(homedir, 0);
2435
0
    if (agent_listener(homedir, "agent", &sock, &socket_name) != 0)
2436
0
      fatal_f("Couldn't prepare agent socket");
2437
0
    free(homedir);
2438
0
  } else if (sock == -1) {
2439
0
    if (T_flag) {
2440
      /*
2441
       * Create private directory for agent socket
2442
       * in $TMPDIR.
2443
       */
2444
0
      mktemp_proto(socket_dir, sizeof(socket_dir));
2445
0
      if (mkdtemp(socket_dir) == NULL) {
2446
0
        perror("mkdtemp: private socket dir");
2447
0
        exit(1);
2448
0
      }
2449
0
      xasprintf(&socket_name, "%s/agent.%ld",
2450
0
          socket_dir, (long)parent_pid);
2451
0
    } else {
2452
      /* Try to use specified agent socket */
2453
0
      socket_dir[0] = '\0';
2454
0
      socket_name = xstrdup(agentsocket);
2455
0
    }
2456
    /* Listen on socket */
2457
0
    prev_mask = umask(0177);
2458
0
    if ((sock = unix_listener(socket_name,
2459
0
        SSH_LISTEN_BACKLOG, 0)) < 0) {
2460
0
      *socket_name = '\0'; /* Don't unlink existing file */
2461
0
      cleanup_exit(1);
2462
0
    }
2463
0
    umask(prev_mask);
2464
0
  }
2465
2466
0
  closefrom(sock == -1 ? STDERR_FILENO + 1 : sock + 1);
2467
2468
  /*
2469
   * Create socket early so it will exist before command gets run from
2470
   * the parent.
2471
   */
2472
0
  if (sock == -1) {
2473
0
    prev_mask = umask(0177);
2474
0
    sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2475
0
    if (sock < 0) {
2476
      /* XXX - unix_listener() calls error() not perror() */
2477
0
      *socket_name = '\0'; /* Don't unlink existing file */
2478
0
      cleanup_exit(1);
2479
0
    }
2480
0
    umask(prev_mask);
2481
0
  }
2482
2483
  /*
2484
   * Fork, and have the parent execute the command, if any, or present
2485
   * the socket data.  The child continues as the authentication agent.
2486
   */
2487
0
  if (D_flag || d_flag) {
2488
0
    log_init(__progname,
2489
0
        d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2490
0
        SYSLOG_FACILITY_AUTH, 1);
2491
0
    if (socket_name != NULL) {
2492
0
      cp = argv_assemble(1, &socket_name);
2493
0
      format = c_flag ?
2494
0
          "setenv %s %s;\n" : "%s=%s; export %s;\n";
2495
0
      printf(format, SSH_AUTHSOCKET_ENV_NAME, cp,
2496
0
          SSH_AUTHSOCKET_ENV_NAME);
2497
0
      free(cp);
2498
0
      printf("echo Agent pid %ld;\n", (long)parent_pid);
2499
0
      fflush(stdout);
2500
0
    }
2501
0
    goto skip;
2502
0
  }
2503
0
  pid = fork();
2504
0
  if (pid == -1) {
2505
0
    perror("fork");
2506
0
    cleanup_exit(1);
2507
0
  }
2508
0
  if (pid != 0) {   /* Parent - execute the given command. */
2509
0
    close(sock);
2510
0
    snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2511
0
    if (ac == 0) {
2512
0
      format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2513
0
      cp = argv_assemble(1, &socket_name);
2514
0
      printf(format, SSH_AUTHSOCKET_ENV_NAME, cp,
2515
0
          SSH_AUTHSOCKET_ENV_NAME);
2516
0
      printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
2517
0
          SSH_AGENTPID_ENV_NAME);
2518
0
      free(cp);
2519
0
      printf("echo Agent pid %ld;\n", (long)pid);
2520
0
      exit(0);
2521
0
    }
2522
0
    if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2523
0
        setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2524
0
      perror("setenv");
2525
0
      exit(1);
2526
0
    }
2527
0
    execvp(av[0], av);
2528
0
    perror(av[0]);
2529
0
    exit(1);
2530
0
  }
2531
  /* child */
2532
0
  log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2533
2534
0
  if (setsid() == -1) {
2535
0
    error("setsid: %s", strerror(errno));
2536
0
    cleanup_exit(1);
2537
0
  }
2538
2539
0
  (void)chdir("/");
2540
0
  if (stdfd_devnull(1, 1, 1) == -1)
2541
0
    error_f("stdfd_devnull failed");
2542
2543
0
#ifdef HAVE_SETRLIMIT
2544
  /* deny core dumps, since memory contains unencrypted private keys */
2545
0
  rlim.rlim_cur = rlim.rlim_max = 0;
2546
0
  if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2547
0
    error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2548
0
    cleanup_exit(1);
2549
0
  }
2550
0
#endif
2551
2552
0
skip:
2553
2554
0
  cleanup_pid = getpid();
2555
2556
0
#ifdef ENABLE_PKCS11
2557
0
  pkcs11_init(0);
2558
0
#endif
2559
0
  new_socket(AUTH_SOCKET, sock);
2560
0
  if (ac > 0)
2561
0
    parent_alive_interval = 10;
2562
0
  idtab_init();
2563
0
  ssh_signal(SIGPIPE, SIG_IGN);
2564
0
  ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2565
0
  ssh_signal(SIGHUP, cleanup_handler);
2566
0
  ssh_signal(SIGTERM, cleanup_handler);
2567
0
  ssh_signal(SIGUSR1, keydrop_handler);
2568
2569
0
  sigemptyset(&nsigset);
2570
0
  sigaddset(&nsigset, SIGINT);
2571
0
  sigaddset(&nsigset, SIGHUP);
2572
0
  sigaddset(&nsigset, SIGTERM);
2573
0
  sigaddset(&nsigset, SIGUSR1);
2574
2575
0
  if (unveil("/", "r") == -1)
2576
0
    fatal("%s: unveil /: %s", __progname, strerror(errno));
2577
0
  if ((ccp = getenv("SSH_SK_HELPER")) == NULL || *ccp == '\0')
2578
0
    ccp = _PATH_SSH_SK_HELPER;
2579
0
  if (unveil(ccp, "x") == -1)
2580
0
    fatal("%s: unveil %s: %s", __progname, ccp, strerror(errno));
2581
0
  if ((ccp = getenv("SSH_PKCS11_HELPER")) == NULL || *ccp == '\0')
2582
0
    ccp = _PATH_SSH_PKCS11_HELPER;
2583
0
  if (unveil(ccp, "x") == -1)
2584
0
    fatal("%s: unveil %s: %s", __progname, ccp, strerror(errno));
2585
0
  if ((ccp = getenv("SSH_ASKPASS")) == NULL || *ccp == '\0')
2586
0
    ccp = _PATH_SSH_ASKPASS_DEFAULT;
2587
0
  if (unveil(ccp, "x") == -1)
2588
0
    fatal("%s: unveil %s: %s", __progname, ccp, strerror(errno));
2589
0
  if (unveil("/dev/null", "rw") == -1)
2590
0
    fatal("%s: unveil /dev/null: %s", __progname, strerror(errno));
2591
0
  if (pledge("stdio rpath cpath wpath unix id proc exec", NULL) == -1)
2592
0
    fatal("%s: pledge: %s", __progname, strerror(errno));
2593
0
  platform_pledge_agent();
2594
2595
0
  while (1) {
2596
0
    sigprocmask(SIG_BLOCK, &nsigset, &osigset);
2597
0
    if (signalled_exit != 0) {
2598
0
      logit("exiting on signal %d", (int)signalled_exit);
2599
0
      cleanup_exit((signalled_exit == SIGTERM &&
2600
0
          socket_activated) ? 0 : 2);
2601
0
    }
2602
0
    if (signalled_keydrop) {
2603
0
      logit("signal %d received; removing all keys",
2604
0
          (int)signalled_keydrop);
2605
0
      remove_all_identities();
2606
0
      signalled_keydrop = 0;
2607
0
    }
2608
0
    ptimeout_init(&timeout);
2609
0
    prepare_poll(&pfd, &npfd, &timeout, maxfds);
2610
0
    result = ppoll(pfd, npfd, ptimeout_get_tsp(&timeout), &osigset);
2611
0
    sigprocmask(SIG_SETMASK, &osigset, NULL);
2612
0
    saved_errno = errno;
2613
0
    if (parent_alive_interval != 0)
2614
0
      check_parent_exists();
2615
0
    (void) reaper();  /* remove expired keys */
2616
0
    if (result == -1) {
2617
0
      if (saved_errno == EINTR)
2618
0
        continue;
2619
0
      fatal("poll: %s", strerror(saved_errno));
2620
0
    } else if (result > 0)
2621
0
      after_poll(pfd, npfd, maxfds);
2622
0
  }
2623
  /* NOTREACHED */
2624
0
}