1 /* $OpenBSD: ssh-agent.c,v 1.303 2023/12/18 14:48:08 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The authentication agent program.
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".
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
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.
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.
39 #include <sys/types.h>
40 #include <sys/resource.h>
42 #include <sys/socket.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
50 #include "openbsd-compat/sys-queue.h"
53 #include <openssl/evp.h>
54 #include "openbsd-compat/openssl-compat.h"
89 #include "pathnames.h"
90 #include "ssh-pkcs11.h"
92 #include "myproposal.h"
94 #ifndef DEFAULT_ALLOWED_PROVIDERS
95 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
98 /* Maximum accepted message length */
99 #define AGENT_MAX_LEN (256*1024)
100 /* Maximum bytes to read from client socket */
101 #define AGENT_RBUF_LEN (4096)
102 /* Maximum number of recorded session IDs/hostkeys per connection */
103 #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 #define AGENT_MAX_DEST_CONSTRAINTS 1024
108 /* Maximum number of associated certificate constraints to accept on a key */
109 #define AGENT_MAX_EXT_CERTS 1024
111 /* XXX store hostkey_sid in a refcounted tree */
125 typedef struct socket_entry {
128 struct sshbuf *input;
129 struct sshbuf *output;
130 struct sshbuf *request;
132 struct hostkey_sid *session_ids;
133 int session_bind_attempted;
136 u_int sockets_alloc = 0;
137 SocketEntry *sockets = NULL;
139 typedef struct identity {
140 TAILQ_ENTRY(identity) next;
147 struct dest_constraint *dest_constraints;
148 size_t ndest_constraints;
153 TAILQ_HEAD(idqueue, identity) idlist;
156 /* private key table */
157 struct idtable *idtab;
161 /* pid of shell == parent of agent */
162 pid_t parent_pid = -1;
163 time_t parent_alive_interval = 0;
165 /* pid of process for which cleanup_socket is applicable */
166 pid_t cleanup_pid = 0;
168 /* pathname and directory for AUTH_SOCKET */
169 char socket_name[PATH_MAX];
170 char socket_dir[PATH_MAX];
172 /* Pattern-list of allowed PKCS#11/Security key paths */
173 static char *allowed_providers;
176 * Allows PKCS11 providers or SK keys that use non-internal providers to
177 * be added over a remote connection (identified by session-bind@openssh.com).
179 static int remote_add_provider;
183 #define LOCK_SALT_SIZE 16
184 #define LOCK_ROUNDS 1
186 u_char lock_pwhash[LOCK_SIZE];
187 u_char lock_salt[LOCK_SALT_SIZE];
189 extern char *__progname;
191 /* Default lifetime in seconds (0 == forever) */
192 static int lifetime = 0;
194 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
196 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
197 static int restrict_websafe = 1;
200 * Client connection count; incremented in new_socket() and decremented in
201 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
202 * normally initialized to 1, it will never reach 0. However, if the -x
203 * option is specified, it is initialized to 0 in main(); in that case,
204 * ssh-agent will exit as soon as it has had at least one client but no
207 static int xcount = 1;
210 close_socket(SocketEntry *e)
215 if (e->type == AUTH_CONNECTION) {
216 debug("xcount %d -> %d", xcount, xcount - 1);
221 sshbuf_free(e->input);
222 sshbuf_free(e->output);
223 sshbuf_free(e->request);
224 for (i = 0; i < e->nsession_ids; i++) {
225 sshkey_free(e->session_ids[i].key);
226 sshbuf_free(e->session_ids[i].sid);
228 free(e->session_ids);
229 memset(e, '\0', sizeof(*e));
231 e->type = AUTH_UNUSED;
239 idtab = xcalloc(1, sizeof(*idtab));
240 TAILQ_INIT(&idtab->idlist);
245 free_dest_constraint_hop(struct dest_constraint_hop *dch)
253 for (i = 0; i < dch->nkeys; i++)
254 sshkey_free(dch->keys[i]);
256 free(dch->key_is_ca);
260 free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
264 for (i = 0; i < ndcs; i++) {
265 free_dest_constraint_hop(&dcs[i].from);
266 free_dest_constraint_hop(&dcs[i].to);
272 dup_dest_constraint_hop(const struct dest_constraint_hop *dch,
273 struct dest_constraint_hop *out)
278 out->user = dch->user == NULL ? NULL : xstrdup(dch->user);
279 out->hostname = dch->hostname == NULL ? NULL : xstrdup(dch->hostname);
280 out->is_ca = dch->is_ca;
281 out->nkeys = dch->nkeys;
282 out->keys = out->nkeys == 0 ? NULL :
283 xcalloc(out->nkeys, sizeof(*out->keys));
284 out->key_is_ca = out->nkeys == 0 ? NULL :
285 xcalloc(out->nkeys, sizeof(*out->key_is_ca));
286 for (i = 0; i < dch->nkeys; i++) {
287 if (dch->keys[i] != NULL &&
288 (r = sshkey_from_private(dch->keys[i],
289 &(out->keys[i]))) != 0)
290 fatal_fr(r, "copy key");
291 out->key_is_ca[i] = dch->key_is_ca[i];
295 static struct dest_constraint *
296 dup_dest_constraints(const struct dest_constraint *dcs, size_t ndcs)
299 struct dest_constraint *ret;
303 ret = xcalloc(ndcs, sizeof(*ret));
304 for (i = 0; i < ndcs; i++) {
305 dup_dest_constraint_hop(&dcs[i].from, &ret[i].from);
306 dup_dest_constraint_hop(&dcs[i].to, &ret[i].to);
311 #ifdef DEBUG_CONSTRAINTS
313 dump_dest_constraint_hop(const struct dest_constraint_hop *dch)
318 debug_f("user %s hostname %s is_ca %d nkeys %u",
319 dch->user == NULL ? "(null)" : dch->user,
320 dch->hostname == NULL ? "(null)" : dch->hostname,
321 dch->is_ca, dch->nkeys);
322 for (i = 0; i < dch->nkeys; i++) {
324 if (dch->keys[i] != NULL &&
325 (fp = sshkey_fingerprint(dch->keys[i],
326 SSH_FP_HASH_DEFAULT, SSH_FP_DEFAULT)) == NULL)
327 fatal_f("fingerprint failed");
328 debug_f("key %u/%u: %s%s%s key_is_ca %d", i, dch->nkeys,
329 dch->keys[i] == NULL ? "" : sshkey_ssh_name(dch->keys[i]),
330 dch->keys[i] == NULL ? "" : " ",
331 dch->keys[i] == NULL ? "none" : fp,
336 #endif /* DEBUG_CONSTRAINTS */
339 dump_dest_constraints(const char *context,
340 const struct dest_constraint *dcs, size_t ndcs)
342 #ifdef DEBUG_CONSTRAINTS
345 debug_f("%s: %zu constraints", context, ndcs);
346 for (i = 0; i < ndcs; i++) {
347 debug_f("constraint %zu / %zu: from: ", i, ndcs);
348 dump_dest_constraint_hop(&dcs[i].from);
349 debug_f("constraint %zu / %zu: to: ", i, ndcs);
350 dump_dest_constraint_hop(&dcs[i].to);
352 debug_f("done for %s", context);
353 #endif /* DEBUG_CONSTRAINTS */
357 free_identity(Identity *id)
359 sshkey_free(id->key);
362 free(id->sk_provider);
363 free_dest_constraints(id->dest_constraints, id->ndest_constraints);
368 * Match 'key' against the key/CA list in a destination constraint hop
369 * Returns 0 on success or -1 otherwise.
372 match_key_hop(const char *tag, const struct sshkey *key,
373 const struct dest_constraint_hop *dch)
375 const char *reason = NULL;
376 const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
383 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
384 SSH_FP_DEFAULT)) == NULL)
385 fatal_f("fingerprint failed");
386 debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
387 tag, hostname, sshkey_type(key), fp, dch->nkeys);
389 for (i = 0; i < dch->nkeys; i++) {
390 if (dch->keys[i] == NULL)
393 if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
394 SSH_FP_DEFAULT)) == NULL)
395 fatal_f("fingerprint failed");
396 debug3_f("%s: key %u: %s%s %s", tag, i,
397 dch->key_is_ca[i] ? "CA " : "",
398 sshkey_type(dch->keys[i]), fp);
400 if (!sshkey_is_cert(key)) {
402 if (dch->key_is_ca[i] ||
403 !sshkey_equal(key, dch->keys[i]))
408 if (!dch->key_is_ca[i])
410 if (key->cert == NULL || key->cert->signature_key == NULL)
411 return -1; /* shouldn't happen */
412 if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
414 if (sshkey_cert_check_host(key, hostname, 1,
415 SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
416 debug_f("cert %s / hostname %s rejected: %s",
417 key->cert->key_id, hostname, reason);
425 /* Check destination constraints on an identity against the hostkey/user */
427 permitted_by_dest_constraints(const struct sshkey *fromkey,
428 const struct sshkey *tokey, Identity *id, const char *user,
429 const char **hostnamep)
432 struct dest_constraint *d;
434 if (hostnamep != NULL)
436 for (i = 0; i < id->ndest_constraints; i++) {
437 d = id->dest_constraints + i;
438 /* XXX remove logspam */
439 debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
440 i, d->from.user ? d->from.user : "",
441 d->from.user ? "@" : "",
442 d->from.hostname ? d->from.hostname : "(ORIGIN)",
444 d->to.user ? d->to.user : "", d->to.user ? "@" : "",
445 d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
447 /* Match 'from' key */
448 if (fromkey == NULL) {
449 /* We are matching the first hop */
450 if (d->from.hostname != NULL || d->from.nkeys != 0)
452 } else if (match_key_hop("from", fromkey, &d->from) != 0)
456 if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
459 /* Match user if specified */
460 if (d->to.user != NULL && user != NULL &&
461 !match_pattern(user, d->to.user))
464 /* successfully matched this constraint */
465 if (hostnamep != NULL)
466 *hostnamep = d->to.hostname;
467 debug2_f("allowed for hostname %s",
468 d->to.hostname == NULL ? "*" : d->to.hostname);
472 debug2_f("%s identity \"%s\" not permitted for this destination",
473 sshkey_type(id->key), id->comment);
478 * Check whether hostkeys on a SocketEntry and the optionally specified user
479 * are permitted by the destination constraints on the Identity.
480 * Returns 0 on success or -1 otherwise.
483 identity_permitted(Identity *id, SocketEntry *e, char *user,
484 const char **forward_hostnamep, const char **last_hostnamep)
488 struct hostkey_sid *hks;
489 const struct sshkey *fromkey = NULL;
490 const char *test_user;
493 /* XXX remove logspam */
494 debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
495 "%zu constraints", sshkey_type(id->key), id->comment,
496 e->nsession_ids, id->ndest_constraints);
497 if (id->ndest_constraints == 0)
498 return 0; /* unconstrained */
499 if (e->session_bind_attempted && e->nsession_ids == 0) {
500 error_f("previous session bind failed on socket");
503 if (e->nsession_ids == 0)
504 return 0; /* local use */
506 * Walk through the hops recorded by session_id and try to find a
507 * constraint that satisfies each.
509 for (i = 0; i < e->nsession_ids; i++) {
510 hks = e->session_ids + i;
511 if (hks->key == NULL)
512 fatal_f("internal error: no bound key");
513 /* XXX remove logspam */
515 if (fromkey != NULL &&
516 (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
517 SSH_FP_DEFAULT)) == NULL)
518 fatal_f("fingerprint failed");
519 if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
520 SSH_FP_DEFAULT)) == NULL)
521 fatal_f("fingerprint failed");
522 debug3_f("socketentry fd=%d, entry %zu %s, "
523 "from hostkey %s %s to user %s hostkey %s %s",
524 e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
525 fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
526 fromkey ? fp1 : "", user ? user : "(ANY)",
527 sshkey_type(hks->key), fp2);
531 * Record the hostnames for the initial forwarding and
532 * the final destination.
535 if (i == e->nsession_ids - 1)
538 hp = forward_hostnamep;
539 /* Special handling for final recorded binding */
541 if (i == e->nsession_ids - 1) {
542 /* Can only check user at final hop */
545 * user is only presented for signature requests.
546 * If this is the case, make sure last binding is not
549 if (hks->forwarded && user != NULL) {
550 error_f("tried to sign on forwarding hop");
553 } else if (!hks->forwarded) {
554 error_f("tried to forward though signing bind");
557 if (permitted_by_dest_constraints(fromkey, hks->key, id,
563 * Another special case: if the last bound session ID was for a
564 * forwarding, and this function is not being called to check a sign
565 * request (i.e. no 'user' supplied), then only permit the key if
566 * there is a permission that would allow it to be used at another
567 * destination. This hides keys that are allowed to be used to
568 * authenticate *to* a host but not permitted for *use* beyond it.
570 hks = &e->session_ids[e->nsession_ids - 1];
571 if (hks->forwarded && user == NULL &&
572 permitted_by_dest_constraints(hks->key, NULL, id,
574 debug3_f("key permitted at host but not after");
583 socket_is_remote(SocketEntry *e)
585 return e->session_bind_attempted || (e->nsession_ids != 0);
588 /* return matching private key for given public key */
590 lookup_identity(struct sshkey *key)
594 TAILQ_FOREACH(id, &idtab->idlist, next) {
595 if (sshkey_equal(key, id->key))
601 /* Check confirmation of keysign request */
603 confirm_key(Identity *id, const char *extra)
608 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
610 ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
612 extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
620 send_status(SocketEntry *e, int success)
624 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
625 (r = sshbuf_put_u8(e->output, success ?
626 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
627 fatal_fr(r, "compose");
630 /* send list of supported public keys to 'client' */
632 process_request_identities(SocketEntry *e)
635 struct sshbuf *msg, *keys;
637 u_int i = 0, nentries = 0;
640 debug2_f("entering");
642 if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
643 fatal_f("sshbuf_new failed");
644 TAILQ_FOREACH(id, &idtab->idlist, next) {
645 if ((fp = sshkey_fingerprint(id->key, SSH_FP_HASH_DEFAULT,
646 SSH_FP_DEFAULT)) == NULL)
647 fatal_f("fingerprint failed");
648 debug_f("key %u / %u: %s %s", i++, idtab->nentries,
649 sshkey_ssh_name(id->key), fp);
650 dump_dest_constraints(__func__,
651 id->dest_constraints, id->ndest_constraints);
653 /* identity not visible, don't include in response */
654 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
656 if ((r = sshkey_puts_opts(id->key, keys,
657 SSHKEY_SERIALIZE_INFO)) != 0 ||
658 (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
659 error_fr(r, "compose key/comment");
664 debug2_f("replying with %u allowed of %u available keys",
665 nentries, idtab->nentries);
666 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
667 (r = sshbuf_put_u32(msg, nentries)) != 0 ||
668 (r = sshbuf_putb(msg, keys)) != 0)
669 fatal_fr(r, "compose");
670 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
671 fatal_fr(r, "enqueue");
678 agent_decode_alg(struct sshkey *key, u_int flags)
680 if (key->type == KEY_RSA) {
681 if (flags & SSH_AGENT_RSA_SHA2_256)
682 return "rsa-sha2-256";
683 else if (flags & SSH_AGENT_RSA_SHA2_512)
684 return "rsa-sha2-512";
685 } else if (key->type == KEY_RSA_CERT) {
686 if (flags & SSH_AGENT_RSA_SHA2_256)
687 return "rsa-sha2-256-cert-v01@openssh.com";
688 else if (flags & SSH_AGENT_RSA_SHA2_512)
689 return "rsa-sha2-512-cert-v01@openssh.com";
695 * Attempt to parse the contents of a buffer as a SSH publickey userauth
696 * request, checking its contents for consistency and matching the embedded
697 * key against the one that is being used for signing.
698 * Note: does not modify msg buffer.
699 * Optionally extract the username, session ID and/or hostkey from the request.
702 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
703 char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
705 struct sshbuf *b = NULL, *sess_id = NULL;
706 char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
708 u_char t, sig_follows;
709 struct sshkey *mkey = NULL, *hostkey = NULL;
713 if (sess_idp != NULL)
715 if (hostkeyp != NULL)
717 if ((b = sshbuf_fromb(msg)) == NULL)
718 fatal_f("sshbuf_fromb");
720 /* SSH userauth request */
721 if ((r = sshbuf_froms(b, &sess_id)) != 0)
723 if (sshbuf_len(sess_id) == 0) {
724 r = SSH_ERR_INVALID_FORMAT;
727 if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
728 (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
729 (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
730 (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
731 (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
732 (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
733 (r = sshkey_froms(b, &mkey)) != 0) /* key */
735 if (t != SSH2_MSG_USERAUTH_REQUEST ||
737 strcmp(service, "ssh-connection") != 0 ||
738 !sshkey_equal(expected_key, mkey) ||
739 sshkey_type_from_name(pkalg) != expected_key->type) {
740 r = SSH_ERR_INVALID_FORMAT;
743 if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
744 if ((r = sshkey_froms(b, &hostkey)) != 0)
746 } else if (strcmp(method, "publickey") != 0) {
747 r = SSH_ERR_INVALID_FORMAT;
750 if (sshbuf_len(b) != 0) {
751 r = SSH_ERR_INVALID_FORMAT;
756 debug3_f("well formed userauth");
761 if (sess_idp != NULL) {
765 if (hostkeyp != NULL) {
771 sshbuf_free(sess_id);
777 sshkey_free(hostkey);
782 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
783 * Note: does not modify buffer.
786 parse_sshsig_request(struct sshbuf *msg)
791 if ((b = sshbuf_fromb(msg)) == NULL)
792 fatal_f("sshbuf_fromb");
794 if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
795 (r = sshbuf_consume(b, 6)) != 0 ||
796 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
797 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
798 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
799 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
801 if (sshbuf_len(b) != 0) {
802 r = SSH_ERR_INVALID_FORMAT;
813 * This function inspects a message to be signed by a FIDO key that has a
814 * web-like application string (i.e. one that does not begin with "ssh:".
815 * It checks that the message is one of those expected for SSH operations
816 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
820 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
822 if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
823 debug_f("signed data matches public key userauth request");
826 if (parse_sshsig_request(data) == 0) {
827 debug_f("signed data matches SSHSIG signature request");
831 /* XXX check CA signature operation */
833 error("web-origin key attempting to sign non-SSH message");
838 buf_equal(const struct sshbuf *a, const struct sshbuf *b)
840 if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
841 return SSH_ERR_INVALID_ARGUMENT;
842 if (sshbuf_len(a) != sshbuf_len(b))
843 return SSH_ERR_INVALID_FORMAT;
844 if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
845 return SSH_ERR_INVALID_FORMAT;
851 process_sign_request2(SocketEntry *e)
853 u_char *signature = NULL;
855 u_int compat = 0, flags;
856 int r, ok = -1, retried = 0;
857 char *fp = NULL, *pin = NULL, *prompt = NULL;
858 char *user = NULL, *sig_dest = NULL;
859 const char *fwd_host = NULL, *dest_host = NULL;
860 struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
861 struct sshkey *key = NULL, *hostkey = NULL;
863 struct notifier_ctx *notifier = NULL;
867 if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
868 fatal_f("sshbuf_new failed");
869 if ((r = sshkey_froms(e->request, &key)) != 0 ||
870 (r = sshbuf_get_stringb(e->request, data)) != 0 ||
871 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
872 error_fr(r, "parse");
876 if ((id = lookup_identity(key)) == NULL) {
877 verbose_f("%s key not found", sshkey_type(key));
880 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
881 SSH_FP_DEFAULT)) == NULL)
882 fatal_f("fingerprint failed");
884 if (id->ndest_constraints != 0) {
885 if (e->nsession_ids == 0) {
886 logit_f("refusing use of destination-constrained key "
887 "to sign on unbound connection");
890 if (parse_userauth_request(data, key, &user, &sid,
892 logit_f("refusing use of destination-constrained key "
893 "to sign an unidentified signature");
897 debug_f("user=%s", user);
898 if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
900 /* XXX display fwd_host/dest_host in askpass UI */
902 * Ensure that the session ID is the most recent one
903 * registered on the socket - it should have been bound by
904 * ssh immediately before userauth.
907 e->session_ids[e->nsession_ids - 1].sid) != 0) {
908 error_f("unexpected session ID (%zu listed) on "
909 "signature request for target user %s with "
910 "key %s %s", e->nsession_ids, user,
911 sshkey_type(id->key), fp);
915 * Ensure that the hostkey embedded in the signature matches
916 * the one most recently bound to the socket. An exception is
917 * made for the initial forwarding hop.
919 if (e->nsession_ids > 1 && hostkey == NULL) {
920 error_f("refusing use of destination-constrained key: "
921 "no hostkey recorded in signature for forwarded "
925 if (hostkey != NULL && !sshkey_equal(hostkey,
926 e->session_ids[e->nsession_ids - 1].key)) {
927 error_f("refusing use of destination-constrained key: "
928 "mismatch between hostkey in request and most "
929 "recently bound session");
932 xasprintf(&sig_dest, "public key authentication request for "
933 "user \"%s\" to listed host", user);
935 if (id->confirm && confirm_key(id, sig_dest) != 0) {
936 verbose_f("user refused key");
939 if (sshkey_is_sk(id->key)) {
940 if (restrict_websafe &&
941 strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
942 !check_websafe_message_contents(key, data)) {
943 /* error already logged */
946 if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
947 notifier = notify_start(0,
948 "Confirm user presence for key %s %s%s%s",
949 sshkey_type(id->key), fp,
950 sig_dest == NULL ? "" : "\n",
951 sig_dest == NULL ? "" : sig_dest);
955 if ((r = sshkey_sign(id->key, &signature, &slen,
956 sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
957 id->sk_provider, pin, compat)) != 0) {
958 debug_fr(r, "sshkey_sign");
959 if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
960 r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
961 notify_complete(notifier, NULL);
963 /* XXX include sig_dest */
964 xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
965 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
966 " and confirm user presence " : " ",
967 sshkey_type(id->key), fp);
968 pin = read_passphrase(prompt, RP_USE_ASKPASS);
972 error_fr(r, "sshkey_sign");
977 debug_f("good signature");
979 notify_complete(notifier, "User presence confirmed");
982 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
983 (r = sshbuf_put_string(msg, signature, slen)) != 0)
984 fatal_fr(r, "compose");
985 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
986 fatal_fr(r, "compose failure");
988 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
989 fatal_fr(r, "enqueue");
995 sshkey_free(hostkey);
1002 freezero(pin, strlen(pin));
1007 process_remove_identity(SocketEntry *e)
1010 struct sshkey *key = NULL;
1013 debug2_f("entering");
1014 if ((r = sshkey_froms(e->request, &key)) != 0) {
1015 error_fr(r, "parse key");
1018 if ((id = lookup_identity(key)) == NULL) {
1019 debug_f("key not found");
1022 /* identity not visible, cannot be removed */
1023 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1024 goto done; /* error already logged */
1025 /* We have this key, free it. */
1026 if (idtab->nentries < 1)
1027 fatal_f("internal error: nentries %d", idtab->nentries);
1028 TAILQ_REMOVE(&idtab->idlist, id, next);
1034 send_status(e, success);
1038 process_remove_all_identities(SocketEntry *e)
1042 debug2_f("entering");
1043 /* Loop over all identities and clear the keys. */
1044 for (id = TAILQ_FIRST(&idtab->idlist); id;
1045 id = TAILQ_FIRST(&idtab->idlist)) {
1046 TAILQ_REMOVE(&idtab->idlist, id, next);
1050 /* Mark that there are no identities. */
1051 idtab->nentries = 0;
1057 /* removes expired keys and returns number of seconds until the next expiry */
1061 time_t deadline = 0, now = monotime();
1064 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1065 nxt = TAILQ_NEXT(id, next);
1068 if (now >= id->death) {
1069 debug("expiring key '%s'", id->comment);
1070 TAILQ_REMOVE(&idtab->idlist, id, next);
1074 deadline = (deadline == 0) ? id->death :
1075 MINIMUM(deadline, id->death);
1077 if (deadline == 0 || deadline <= now)
1080 return (deadline - now);
1084 parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
1089 struct sshkey *k = NULL;
1092 memset(dch, '\0', sizeof(*dch));
1093 if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
1094 (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
1095 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1096 error_fr(r, "parse");
1100 error_f("unsupported extensions (len %zu)", elen);
1101 r = SSH_ERR_FEATURE_UNSUPPORTED;
1104 if (*dch->hostname == '\0') {
1105 free(dch->hostname);
1106 dch->hostname = NULL;
1108 if (*dch->user == '\0') {
1112 while (sshbuf_len(b) != 0) {
1113 dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1114 dch->nkeys + 1, sizeof(*dch->keys));
1115 dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1116 dch->nkeys + 1, sizeof(*dch->key_is_ca));
1117 if ((r = sshkey_froms(b, &k)) != 0 ||
1118 (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1120 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1121 SSH_FP_DEFAULT)) == NULL)
1122 fatal_f("fingerprint failed");
1123 debug3_f("%s%s%s: adding %skey %s %s",
1124 dch->user == NULL ? "" : dch->user,
1125 dch->user == NULL ? "" : "@",
1126 dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1128 dch->keys[dch->nkeys] = k;
1129 dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1131 k = NULL; /* transferred */
1141 parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1143 struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1147 debug3_f("entering");
1149 memset(dc, '\0', sizeof(*dc));
1150 if ((r = sshbuf_froms(m, &b)) != 0 ||
1151 (r = sshbuf_froms(b, &frombuf)) != 0 ||
1152 (r = sshbuf_froms(b, &tobuf)) != 0 ||
1153 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1154 error_fr(r, "parse");
1157 if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
1158 (r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
1159 goto out; /* already logged */
1161 error_f("unsupported extensions (len %zu)", elen);
1162 r = SSH_ERR_FEATURE_UNSUPPORTED;
1165 debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1166 dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1167 dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1168 dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1169 /* check consistency */
1170 if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1171 dc->from.user != NULL) {
1172 error_f("inconsistent \"from\" specification");
1173 r = SSH_ERR_INVALID_FORMAT;
1176 if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1177 error_f("incomplete \"to\" specification");
1178 r = SSH_ERR_INVALID_FORMAT;
1185 sshbuf_free(frombuf);
1191 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1192 struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp,
1193 struct sshkey ***certs, size_t *ncerts)
1195 char *ext_name = NULL;
1197 struct sshbuf *b = NULL;
1201 if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1202 error_fr(r, "parse constraint extension");
1205 debug_f("constraint ext %s", ext_name);
1206 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1207 if (sk_providerp == NULL) {
1208 error_f("%s not valid here", ext_name);
1209 r = SSH_ERR_INVALID_FORMAT;
1212 if (*sk_providerp != NULL) {
1213 error_f("%s already set", ext_name);
1214 r = SSH_ERR_INVALID_FORMAT;
1217 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1218 error_fr(r, "parse %s", ext_name);
1221 } else if (strcmp(ext_name,
1222 "restrict-destination-v00@openssh.com") == 0) {
1223 if (*dcsp != NULL) {
1224 error_f("%s already set", ext_name);
1227 if ((r = sshbuf_froms(m, &b)) != 0) {
1228 error_fr(r, "parse %s outer", ext_name);
1231 while (sshbuf_len(b) != 0) {
1232 if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1233 error_f("too many %s constraints", ext_name);
1236 *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1238 if ((r = parse_dest_constraint(b,
1239 *dcsp + (*ndcsp)++)) != 0)
1240 goto out; /* error already logged */
1242 } else if (strcmp(ext_name,
1243 "associated-certs-v00@openssh.com") == 0) {
1244 if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) {
1245 error_f("%s not valid here", ext_name);
1246 r = SSH_ERR_INVALID_FORMAT;
1249 if (*certs != NULL) {
1250 error_f("%s already set", ext_name);
1253 if ((r = sshbuf_get_u8(m, &v)) != 0 ||
1254 (r = sshbuf_froms(m, &b)) != 0) {
1255 error_fr(r, "parse %s", ext_name);
1258 *cert_onlyp = v != 0;
1259 while (sshbuf_len(b) != 0) {
1260 if (*ncerts >= AGENT_MAX_EXT_CERTS) {
1261 error_f("too many %s constraints", ext_name);
1264 *certs = xrecallocarray(*certs, *ncerts, *ncerts + 1,
1266 if ((r = sshkey_froms(b, &k)) != 0) {
1267 error_fr(r, "parse key");
1270 (*certs)[(*ncerts)++] = k;
1273 error_f("unsupported constraint \"%s\"", ext_name);
1274 r = SSH_ERR_FEATURE_UNSUPPORTED;
1286 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1287 u_int *secondsp, int *confirmp, char **sk_providerp,
1288 struct dest_constraint **dcsp, size_t *ndcsp,
1289 int *cert_onlyp, size_t *ncerts, struct sshkey ***certs)
1293 u_int seconds, maxsign = 0;
1295 while (sshbuf_len(m)) {
1296 if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1297 error_fr(r, "parse constraint type");
1301 case SSH_AGENT_CONSTRAIN_LIFETIME:
1303 error_f("lifetime already set");
1304 r = SSH_ERR_INVALID_FORMAT;
1307 if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1308 error_fr(r, "parse lifetime constraint");
1311 *deathp = monotime() + seconds;
1312 *secondsp = seconds;
1314 case SSH_AGENT_CONSTRAIN_CONFIRM:
1315 if (*confirmp != 0) {
1316 error_f("confirm already set");
1317 r = SSH_ERR_INVALID_FORMAT;
1322 case SSH_AGENT_CONSTRAIN_MAXSIGN:
1324 error_f("maxsign not valid here");
1325 r = SSH_ERR_INVALID_FORMAT;
1329 error_f("maxsign already set");
1330 r = SSH_ERR_INVALID_FORMAT;
1333 if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1334 error_fr(r, "parse maxsign constraint");
1337 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1338 error_fr(r, "enable maxsign");
1342 case SSH_AGENT_CONSTRAIN_EXTENSION:
1343 if ((r = parse_key_constraint_extension(m,
1344 sk_providerp, dcsp, ndcsp,
1345 cert_onlyp, certs, ncerts)) != 0)
1346 goto out; /* error already logged */
1349 error_f("Unknown constraint %d", ctype);
1350 r = SSH_ERR_FEATURE_UNSUPPORTED;
1361 process_add_identity(SocketEntry *e)
1364 int success = 0, confirm = 0;
1365 char *fp, *comment = NULL, *sk_provider = NULL;
1366 char canonical_provider[PATH_MAX];
1369 struct dest_constraint *dest_constraints = NULL;
1370 size_t ndest_constraints = 0;
1371 struct sshkey *k = NULL;
1372 int r = SSH_ERR_INTERNAL_ERROR;
1374 debug2_f("entering");
1375 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1377 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1378 error_fr(r, "parse");
1381 if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1382 &sk_provider, &dest_constraints, &ndest_constraints,
1383 NULL, NULL, NULL) != 0) {
1384 error_f("failed to parse constraints");
1385 sshbuf_reset(e->request);
1388 dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1390 if (sk_provider != NULL) {
1391 if (!sshkey_is_sk(k)) {
1392 error("Cannot add provider: %s is not an "
1393 "authenticator-hosted key", sshkey_type(k));
1396 if (strcasecmp(sk_provider, "internal") == 0) {
1397 debug_f("internal provider");
1399 if (socket_is_remote(e) && !remote_add_provider) {
1400 verbose("failed add of SK provider \"%.100s\": "
1401 "remote addition of providers is disabled",
1405 if (realpath(sk_provider, canonical_provider) == NULL) {
1406 verbose("failed provider \"%.100s\": "
1407 "realpath: %s", sk_provider,
1412 sk_provider = xstrdup(canonical_provider);
1413 if (match_pattern_list(sk_provider,
1414 allowed_providers, 0) != 1) {
1415 error("Refusing add key: "
1416 "provider %s not allowed", sk_provider);
1421 if ((r = sshkey_shield_private(k)) != 0) {
1422 error_fr(r, "shield private");
1425 if (lifetime && !death)
1426 death = monotime() + lifetime;
1427 if ((id = lookup_identity(k)) == NULL) {
1428 id = xcalloc(1, sizeof(Identity));
1429 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1430 /* Increment the number of identities. */
1433 /* identity not visible, do not update */
1434 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1435 goto out; /* error already logged */
1436 /* key state might have been updated */
1437 sshkey_free(id->key);
1439 free(id->sk_provider);
1440 free_dest_constraints(id->dest_constraints,
1441 id->ndest_constraints);
1445 id->comment = comment;
1447 id->confirm = confirm;
1448 id->sk_provider = sk_provider;
1449 id->dest_constraints = dest_constraints;
1450 id->ndest_constraints = ndest_constraints;
1452 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1453 SSH_FP_DEFAULT)) == NULL)
1454 fatal_f("sshkey_fingerprint failed");
1455 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1456 "(provider: %s) (destination constraints: %zu)",
1457 sshkey_ssh_name(k), fp, comment, seconds, confirm,
1458 sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1464 dest_constraints = NULL;
1465 ndest_constraints = 0;
1471 free_dest_constraints(dest_constraints, ndest_constraints);
1472 send_status(e, success);
1475 /* XXX todo: encrypt sensitive data with passphrase */
1477 process_lock_agent(SocketEntry *e, int lock)
1479 int r, success = 0, delay;
1481 u_char passwdhash[LOCK_SIZE];
1482 static u_int fail_count = 0;
1485 debug2_f("entering");
1487 * This is deliberately fatal: the user has requested that we lock,
1488 * but we can't parse their request properly. The only safe thing to
1491 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1492 fatal_fr(r, "parse");
1494 debug("empty password not supported");
1495 } else if (locked && !lock) {
1496 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1497 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1498 fatal("bcrypt_pbkdf");
1499 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1500 debug("agent unlocked");
1503 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1506 /* delay in 0.1s increments up to 10s */
1507 if (fail_count < 100)
1509 delay = 100000 * fail_count;
1510 debug("unlock failed, delaying %0.1lf seconds",
1511 (double)delay/1000000);
1514 explicit_bzero(passwdhash, sizeof(passwdhash));
1515 } else if (!locked && lock) {
1516 debug("agent locked");
1518 arc4random_buf(lock_salt, sizeof(lock_salt));
1519 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1520 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1521 fatal("bcrypt_pbkdf");
1524 freezero(passwd, pwlen);
1525 send_status(e, success);
1529 no_identities(SocketEntry *e)
1534 if ((msg = sshbuf_new()) == NULL)
1535 fatal_f("sshbuf_new failed");
1536 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1537 (r = sshbuf_put_u32(msg, 0)) != 0 ||
1538 (r = sshbuf_put_stringb(e->output, msg)) != 0)
1539 fatal_fr(r, "compose");
1543 /* Add an identity to idlist; takes ownership of 'key' and 'comment' */
1545 add_p11_identity(struct sshkey *key, char *comment, const char *provider,
1546 time_t death, int confirm, struct dest_constraint *dest_constraints,
1547 size_t ndest_constraints)
1551 if (lookup_identity(key) != NULL) {
1556 id = xcalloc(1, sizeof(Identity));
1558 id->comment = comment;
1559 id->provider = xstrdup(provider);
1561 id->confirm = confirm;
1562 id->dest_constraints = dup_dest_constraints(dest_constraints,
1564 id->ndest_constraints = ndest_constraints;
1565 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1569 #ifdef ENABLE_PKCS11
1571 process_add_smartcard_key(SocketEntry *e)
1573 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1574 char **comments = NULL;
1575 int r, i, count = 0, success = 0, confirm = 0;
1578 struct sshkey **keys = NULL, *k;
1579 struct dest_constraint *dest_constraints = NULL;
1580 size_t j, ndest_constraints = 0, ncerts = 0;
1581 struct sshkey **certs = NULL;
1584 debug2_f("entering");
1585 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1586 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1587 error_fr(r, "parse");
1590 if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1591 NULL, &dest_constraints, &ndest_constraints, &cert_only,
1592 &ncerts, &certs) != 0) {
1593 error_f("failed to parse constraints");
1596 dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
1597 if (socket_is_remote(e) && !remote_add_provider) {
1598 verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1599 "providers is disabled", provider);
1602 if (realpath(provider, canonical_provider) == NULL) {
1603 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1604 provider, strerror(errno));
1607 if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1608 verbose("refusing PKCS#11 add of \"%.100s\": "
1609 "provider not allowed", canonical_provider);
1612 debug_f("add %.100s", canonical_provider);
1613 if (lifetime && !death)
1614 death = monotime() + lifetime;
1616 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1617 for (i = 0; i < count; i++) {
1618 if (comments[i] == NULL || comments[i][0] == '\0') {
1620 comments[i] = xstrdup(canonical_provider);
1622 for (j = 0; j < ncerts; j++) {
1623 if (!sshkey_is_cert(certs[j]))
1625 if (!sshkey_equal_public(keys[i], certs[j]))
1627 if (pkcs11_make_cert(keys[i], certs[j], &k) != 0)
1629 add_p11_identity(k, xstrdup(comments[i]),
1630 canonical_provider, death, confirm,
1631 dest_constraints, ndest_constraints);
1634 if (!cert_only && lookup_identity(keys[i]) == NULL) {
1635 add_p11_identity(keys[i], comments[i],
1636 canonical_provider, death, confirm,
1637 dest_constraints, ndest_constraints);
1638 keys[i] = NULL; /* transferred */
1639 comments[i] = NULL; /* transferred */
1642 /* XXX update constraints for existing keys */
1643 sshkey_free(keys[i]);
1651 free_dest_constraints(dest_constraints, ndest_constraints);
1652 for (j = 0; j < ncerts; j++)
1653 sshkey_free(certs[j]);
1655 send_status(e, success);
1659 process_remove_smartcard_key(SocketEntry *e)
1661 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1665 debug2_f("entering");
1666 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1667 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1668 error_fr(r, "parse");
1673 if (realpath(provider, canonical_provider) == NULL) {
1674 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1675 provider, strerror(errno));
1679 debug_f("remove %.100s", canonical_provider);
1680 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1681 nxt = TAILQ_NEXT(id, next);
1682 /* Skip file--based keys */
1683 if (id->provider == NULL)
1685 if (!strcmp(canonical_provider, id->provider)) {
1686 TAILQ_REMOVE(&idtab->idlist, id, next);
1691 if (pkcs11_del_provider(canonical_provider) == 0)
1694 error_f("pkcs11_del_provider failed");
1697 send_status(e, success);
1699 #endif /* ENABLE_PKCS11 */
1702 process_ext_session_bind(SocketEntry *e)
1704 int r, sid_match, key_match;
1705 struct sshkey *key = NULL;
1706 struct sshbuf *sid = NULL, *sig = NULL;
1711 debug2_f("entering");
1712 e->session_bind_attempted = 1;
1713 if ((r = sshkey_froms(e->request, &key)) != 0 ||
1714 (r = sshbuf_froms(e->request, &sid)) != 0 ||
1715 (r = sshbuf_froms(e->request, &sig)) != 0 ||
1716 (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1717 error_fr(r, "parse");
1720 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1721 SSH_FP_DEFAULT)) == NULL)
1722 fatal_f("fingerprint failed");
1723 /* check signature with hostkey on session ID */
1724 if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1725 sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1726 error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1729 /* check whether sid/key already recorded */
1730 for (i = 0; i < e->nsession_ids; i++) {
1731 if (!e->session_ids[i].forwarded) {
1732 error_f("attempt to bind session ID to socket "
1733 "previously bound for authentication attempt");
1737 sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1738 key_match = sshkey_equal(key, e->session_ids[i].key);
1739 if (sid_match && key_match) {
1740 debug_f("session ID already recorded for %s %s",
1741 sshkey_type(key), fp);
1744 } else if (sid_match) {
1745 error_f("session ID recorded against different key "
1746 "for %s %s", sshkey_type(key), fp);
1751 * new sid with previously-seen key can happen, e.g. multiple
1752 * connections to the same host.
1755 /* record new key/sid */
1756 if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1757 error_f("too many session IDs recorded");
1760 e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1761 e->nsession_ids + 1, sizeof(*e->session_ids));
1762 i = e->nsession_ids++;
1763 debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1764 AGENT_MAX_SESSION_IDS);
1765 e->session_ids[i].key = key;
1766 e->session_ids[i].forwarded = fwd != 0;
1767 key = NULL; /* transferred */
1768 /* can't transfer sid; it's refcounted and scoped to request's life */
1769 if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1770 fatal_f("sshbuf_new");
1771 if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1772 fatal_fr(r, "sshbuf_putb session ID");
1780 return r == 0 ? 1 : 0;
1784 process_extension(SocketEntry *e)
1789 debug2_f("entering");
1790 if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1791 error_fr(r, "parse");
1794 if (strcmp(name, "session-bind@openssh.com") == 0)
1795 success = process_ext_session_bind(e);
1797 debug_f("unsupported extension \"%s\"", name);
1800 send_status(e, success);
1803 * dispatch incoming message.
1804 * returns 1 on success, 0 for incomplete messages or -1 on error.
1807 process_message(u_int socknum)
1815 if (socknum >= sockets_alloc)
1816 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1817 e = &sockets[socknum];
1819 if (sshbuf_len(e->input) < 5)
1820 return 0; /* Incomplete message header. */
1821 cp = sshbuf_ptr(e->input);
1822 msg_len = PEEK_U32(cp);
1823 if (msg_len > AGENT_MAX_LEN) {
1824 debug_f("socket %u (fd=%d) message too long %u > %u",
1825 socknum, e->fd, msg_len, AGENT_MAX_LEN);
1828 if (sshbuf_len(e->input) < msg_len + 4)
1829 return 0; /* Incomplete message body. */
1831 /* move the current input to e->request */
1832 sshbuf_reset(e->request);
1833 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1834 (r = sshbuf_get_u8(e->request, &type)) != 0) {
1835 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1836 r == SSH_ERR_STRING_TOO_LARGE) {
1837 error_fr(r, "parse");
1840 fatal_fr(r, "parse");
1843 debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1845 /* check whether agent is locked */
1846 if (locked && type != SSH_AGENTC_UNLOCK) {
1847 sshbuf_reset(e->request);
1849 case SSH2_AGENTC_REQUEST_IDENTITIES:
1850 /* send empty lists */
1854 /* send a fail message for all other request types */
1861 case SSH_AGENTC_LOCK:
1862 case SSH_AGENTC_UNLOCK:
1863 process_lock_agent(e, type == SSH_AGENTC_LOCK);
1865 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1866 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1869 case SSH2_AGENTC_SIGN_REQUEST:
1870 process_sign_request2(e);
1872 case SSH2_AGENTC_REQUEST_IDENTITIES:
1873 process_request_identities(e);
1875 case SSH2_AGENTC_ADD_IDENTITY:
1876 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1877 process_add_identity(e);
1879 case SSH2_AGENTC_REMOVE_IDENTITY:
1880 process_remove_identity(e);
1882 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1883 process_remove_all_identities(e);
1885 #ifdef ENABLE_PKCS11
1886 case SSH_AGENTC_ADD_SMARTCARD_KEY:
1887 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1888 process_add_smartcard_key(e);
1890 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1891 process_remove_smartcard_key(e);
1893 #endif /* ENABLE_PKCS11 */
1894 case SSH_AGENTC_EXTENSION:
1895 process_extension(e);
1898 /* Unknown message. Respond with failure. */
1899 error("Unknown message %d", type);
1900 sshbuf_reset(e->request);
1908 new_socket(sock_type type, int fd)
1910 u_int i, old_alloc, new_alloc;
1912 debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1913 (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1914 if (type == AUTH_CONNECTION) {
1915 debug("xcount %d -> %d", xcount, xcount + 1);
1923 for (i = 0; i < sockets_alloc; i++)
1924 if (sockets[i].type == AUTH_UNUSED) {
1926 if ((sockets[i].input = sshbuf_new()) == NULL ||
1927 (sockets[i].output = sshbuf_new()) == NULL ||
1928 (sockets[i].request = sshbuf_new()) == NULL)
1929 fatal_f("sshbuf_new failed");
1930 sockets[i].type = type;
1933 old_alloc = sockets_alloc;
1934 new_alloc = sockets_alloc + 10;
1935 sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1936 sizeof(sockets[0]));
1937 for (i = old_alloc; i < new_alloc; i++)
1938 sockets[i].type = AUTH_UNUSED;
1939 sockets_alloc = new_alloc;
1940 sockets[old_alloc].fd = fd;
1941 if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1942 (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1943 (sockets[old_alloc].request = sshbuf_new()) == NULL)
1944 fatal_f("sshbuf_new failed");
1945 sockets[old_alloc].type = type;
1949 handle_socket_read(u_int socknum)
1951 struct sockaddr_un sunaddr;
1957 slen = sizeof(sunaddr);
1958 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1960 error("accept from AUTH_SOCKET: %s", strerror(errno));
1963 if (getpeereid(fd, &euid, &egid) == -1) {
1964 error("getpeereid %d failed: %s", fd, strerror(errno));
1968 if ((euid != 0) && (getuid() != euid)) {
1969 error("uid mismatch: peer euid %u != uid %u",
1970 (u_int) euid, (u_int) getuid());
1974 new_socket(AUTH_CONNECTION, fd);
1979 handle_conn_read(u_int socknum)
1981 char buf[AGENT_RBUF_LEN];
1985 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1987 if (errno == EAGAIN || errno == EINTR)
1989 error_f("read error on socket %u (fd %d): %s",
1990 socknum, sockets[socknum].fd, strerror(errno));
1994 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1995 fatal_fr(r, "compose");
1996 explicit_bzero(buf, sizeof(buf));
1998 if ((r = process_message(socknum)) == -1)
2007 handle_conn_write(u_int socknum)
2012 if (sshbuf_len(sockets[socknum].output) == 0)
2013 return 0; /* shouldn't happen */
2014 if ((len = write(sockets[socknum].fd,
2015 sshbuf_ptr(sockets[socknum].output),
2016 sshbuf_len(sockets[socknum].output))) <= 0) {
2018 if (errno == EAGAIN || errno == EINTR)
2020 error_f("read error on socket %u (fd %d): %s",
2021 socknum, sockets[socknum].fd, strerror(errno));
2025 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
2026 fatal_fr(r, "consume");
2031 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
2034 u_int socknum, activefds = npfd;
2036 for (i = 0; i < npfd; i++) {
2037 if (pfd[i].revents == 0)
2039 /* Find sockets entry */
2040 for (socknum = 0; socknum < sockets_alloc; socknum++) {
2041 if (sockets[socknum].type != AUTH_SOCKET &&
2042 sockets[socknum].type != AUTH_CONNECTION)
2044 if (pfd[i].fd == sockets[socknum].fd)
2047 if (socknum >= sockets_alloc) {
2048 error_f("no socket for fd %d", pfd[i].fd);
2051 /* Process events */
2052 switch (sockets[socknum].type) {
2054 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
2056 if (npfd > maxfds) {
2057 debug3("out of fds (active %u >= limit %u); "
2058 "skipping accept", activefds, maxfds);
2061 if (handle_socket_read(socknum) == 0)
2064 case AUTH_CONNECTION:
2065 if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
2066 handle_conn_read(socknum) != 0)
2068 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
2069 handle_conn_write(socknum) != 0) {
2072 fatal("activefds == 0 at close_sock");
2073 close_socket(&sockets[socknum]);
2085 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
2087 struct pollfd *pfd = *pfdp;
2088 size_t i, j, npfd = 0;
2092 /* Count active sockets */
2093 for (i = 0; i < sockets_alloc; i++) {
2094 switch (sockets[i].type) {
2096 case AUTH_CONNECTION:
2102 fatal("Unknown socket type %d", sockets[i].type);
2106 if (npfd != *npfdp &&
2107 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
2108 fatal_f("recallocarray failed");
2112 for (i = j = 0; i < sockets_alloc; i++) {
2113 switch (sockets[i].type) {
2115 if (npfd > maxfds) {
2116 debug3("out of fds (active %zu >= limit %u); "
2117 "skipping arming listener", npfd, maxfds);
2120 pfd[j].fd = sockets[i].fd;
2122 pfd[j].events = POLLIN;
2125 case AUTH_CONNECTION:
2126 pfd[j].fd = sockets[i].fd;
2129 * Only prepare to read if we can handle a full-size
2130 * input read buffer and enqueue a max size reply..
2132 if ((r = sshbuf_check_reserve(sockets[i].input,
2133 AGENT_RBUF_LEN)) == 0 &&
2134 (r = sshbuf_check_reserve(sockets[i].output,
2135 AGENT_MAX_LEN)) == 0)
2136 pfd[j].events = POLLIN;
2137 else if (r != SSH_ERR_NO_BUFFER_SPACE)
2138 fatal_fr(r, "reserve");
2139 if (sshbuf_len(sockets[i].output) > 0)
2140 pfd[j].events |= POLLOUT;
2147 deadline = reaper();
2148 if (parent_alive_interval != 0)
2149 deadline = (deadline == 0) ? parent_alive_interval :
2150 MINIMUM(deadline, parent_alive_interval);
2151 if (deadline == 0) {
2152 *timeoutp = -1; /* INFTIM */
2154 if (deadline > INT_MAX / 1000)
2155 *timeoutp = INT_MAX / 1000;
2157 *timeoutp = deadline * 1000;
2163 cleanup_socket(void)
2165 if (cleanup_pid != 0 && getpid() != cleanup_pid)
2169 unlink(socket_name);
2182 cleanup_handler(int sig)
2185 #ifdef ENABLE_PKCS11
2192 check_parent_exists(void)
2195 * If our parent has exited then getppid() will return (pid_t)1,
2196 * so testing for that should be safe.
2198 if (parent_pid != -1 && getppid() != parent_pid) {
2199 /* printf("Parent has died - Authentication agent exiting.\n"); */
2209 "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
2210 " [-O option] [-P allowed_providers] [-t life]\n"
2211 " ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2212 " [-P allowed_providers] [-t life] command [arg ...]\n"
2213 " ssh-agent [-c | -s] -k\n");
2218 main(int ac, char **av)
2220 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
2221 int sock, ch, result, saved_errno;
2222 char *shell, *format, *pidstr, *agentsocket = NULL;
2223 #ifdef HAVE_SETRLIMIT
2227 extern char *optarg;
2229 char pidstrbuf[1 + 3 * sizeof pid];
2232 int timeout = -1; /* INFTIM */
2233 struct pollfd *pfd = NULL;
2237 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2241 (void)setegid(getgid());
2242 (void)setgid(getgid());
2245 platform_disable_tracing(0); /* strict=no */
2247 #ifdef RLIMIT_NOFILE
2248 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2249 fatal("%s: getrlimit: %s", __progname, strerror(errno));
2252 __progname = ssh_get_progname(av[0]);
2255 while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:x")) != -1) {
2258 fingerprint_hash = ssh_digest_alg_by_name(optarg);
2259 if (fingerprint_hash == -1)
2260 fatal("Invalid hash algorithm \"%s\"", optarg);
2271 if (strcmp(optarg, "no-restrict-websafe") == 0)
2272 restrict_websafe = 0;
2273 else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
2274 remote_add_provider = 1;
2276 fatal("Unknown -O option");
2279 if (allowed_providers != NULL)
2280 fatal("-P option already specified");
2281 allowed_providers = xstrdup(optarg);
2289 if (d_flag || D_flag)
2294 if (d_flag || D_flag)
2299 agentsocket = optarg;
2302 if ((lifetime = convtime(optarg)) == -1) {
2303 fprintf(stderr, "Invalid lifetime\n");
2317 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
2320 if (allowed_providers == NULL)
2321 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2323 if (ac == 0 && !c_flag && !s_flag) {
2324 shell = getenv("SHELL");
2325 if (shell != NULL && (len = strlen(shell)) > 2 &&
2326 strncmp(shell + len - 3, "csh", 3) == 0)
2330 const char *errstr = NULL;
2332 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2333 if (pidstr == NULL) {
2334 fprintf(stderr, "%s not set, cannot kill agent\n",
2335 SSH_AGENTPID_ENV_NAME);
2338 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2341 "%s=\"%s\", which is not a good PID: %s\n",
2342 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2345 if (kill(pid, SIGTERM) == -1) {
2349 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
2350 printf(format, SSH_AUTHSOCKET_ENV_NAME);
2351 printf(format, SSH_AGENTPID_ENV_NAME);
2352 printf("echo Agent pid %ld killed;\n", (long)pid);
2357 * Minimum file descriptors:
2358 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2359 * a few spare for libc / stack protectors / sanitisers, etc.
2361 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2362 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2363 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2364 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2365 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2367 parent_pid = getpid();
2369 if (agentsocket == NULL) {
2370 /* Create private directory for agent socket */
2371 mktemp_proto(socket_dir, sizeof(socket_dir));
2372 if (mkdtemp(socket_dir) == NULL) {
2373 perror("mkdtemp: private socket dir");
2376 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
2379 /* Try to use specified agent socket */
2380 socket_dir[0] = '\0';
2381 strlcpy(socket_name, agentsocket, sizeof socket_name);
2385 * Create socket early so it will exist before command gets run from
2388 prev_mask = umask(0177);
2389 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2391 /* XXX - unix_listener() calls error() not perror() */
2392 *socket_name = '\0'; /* Don't unlink any existing file */
2398 * Fork, and have the parent execute the command, if any, or present
2399 * the socket data. The child continues as the authentication agent.
2401 if (D_flag || d_flag) {
2402 log_init(__progname,
2403 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2404 SYSLOG_FACILITY_AUTH, 1);
2405 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2406 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2407 SSH_AUTHSOCKET_ENV_NAME);
2408 printf("echo Agent pid %ld;\n", (long)parent_pid);
2417 if (pid != 0) { /* Parent - execute the given command. */
2419 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2421 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2422 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2423 SSH_AUTHSOCKET_ENV_NAME);
2424 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
2425 SSH_AGENTPID_ENV_NAME);
2426 printf("echo Agent pid %ld;\n", (long)pid);
2429 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2430 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2439 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2441 if (setsid() == -1) {
2442 error("setsid: %s", strerror(errno));
2447 if (stdfd_devnull(1, 1, 1) == -1)
2448 error_f("stdfd_devnull failed");
2450 #ifdef HAVE_SETRLIMIT
2451 /* deny core dumps, since memory contains unencrypted private keys */
2452 rlim.rlim_cur = rlim.rlim_max = 0;
2453 if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2454 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2461 cleanup_pid = getpid();
2463 #ifdef ENABLE_PKCS11
2466 new_socket(AUTH_SOCKET, sock);
2468 parent_alive_interval = 10;
2470 ssh_signal(SIGPIPE, SIG_IGN);
2471 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2472 ssh_signal(SIGHUP, cleanup_handler);
2473 ssh_signal(SIGTERM, cleanup_handler);
2475 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2476 fatal("%s: pledge: %s", __progname, strerror(errno));
2477 platform_pledge_agent();
2480 prepare_poll(&pfd, &npfd, &timeout, maxfds);
2481 result = poll(pfd, npfd, timeout);
2482 saved_errno = errno;
2483 if (parent_alive_interval != 0)
2484 check_parent_exists();
2485 (void) reaper(); /* remove expired keys */
2487 if (saved_errno == EINTR)
2489 fatal("poll: %s", strerror(saved_errno));
2490 } else if (result > 0)
2491 after_poll(pfd, npfd, maxfds);