Coverage Report

Created: 2024-06-18 06:24

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