1 /* $OpenBSD: ssh-agent.c,v 1.287 2022/01/14 03:43:48 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.
40 #include <sys/types.h>
41 #include <sys/resource.h>
43 #include <sys/socket.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
51 #include "openbsd-compat/sys-queue.h"
54 #include <openssl/evp.h>
55 #include "openbsd-compat/openssl-compat.h"
92 #include "pathnames.h"
93 #include "ssh-pkcs11.h"
95 #include "myproposal.h"
97 #ifndef DEFAULT_ALLOWED_PROVIDERS
98 # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
101 /* Maximum accepted message length */
102 #define AGENT_MAX_LEN (256*1024)
103 /* Maximum bytes to read from client socket */
104 #define AGENT_RBUF_LEN (4096)
105 /* Maximum number of recorded session IDs/hostkeys per connection */
106 #define AGENT_MAX_SESSION_IDS 16
107 /* Maximum size of session ID */
108 #define AGENT_MAX_SID_LEN 128
109 /* Maximum number of destination constraints to accept on a key */
110 #define AGENT_MAX_DEST_CONSTRAINTS 1024
112 /* XXX store hostkey_sid in a refcounted tree */
126 typedef struct socket_entry {
129 struct sshbuf *input;
130 struct sshbuf *output;
131 struct sshbuf *request;
133 struct hostkey_sid *session_ids;
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;
177 #define LOCK_SALT_SIZE 16
178 #define LOCK_ROUNDS 1
180 u_char lock_pwhash[LOCK_SIZE];
181 u_char lock_salt[LOCK_SALT_SIZE];
183 extern char *__progname;
185 /* Default lifetime in seconds (0 == forever) */
186 static int lifetime = 0;
188 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
190 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
191 static int restrict_websafe = 1;
194 * Client connection count; incremented in new_socket() and decremented in
195 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
196 * normally initialized to 1, it will never reach 0. However, if the -x
197 * option is specified, it is initialized to 0 in main(); in that case,
198 * ssh-agent will exit as soon as it has had at least one client but no
201 static int xcount = 1;
204 close_socket(SocketEntry *e)
209 if (e->type == AUTH_CONNECTION) {
210 debug("xcount %d -> %d", xcount, xcount - 1);
215 sshbuf_free(e->input);
216 sshbuf_free(e->output);
217 sshbuf_free(e->request);
218 for (i = 0; i < e->nsession_ids; i++) {
219 sshkey_free(e->session_ids[i].key);
220 sshbuf_free(e->session_ids[i].sid);
222 free(e->session_ids);
223 memset(e, '\0', sizeof(*e));
225 e->type = AUTH_UNUSED;
233 idtab = xcalloc(1, sizeof(*idtab));
234 TAILQ_INIT(&idtab->idlist);
239 free_dest_constraint_hop(struct dest_constraint_hop *dch)
247 for (i = 0; i < dch->nkeys; i++)
248 sshkey_free(dch->keys[i]);
250 free(dch->key_is_ca);
254 free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
258 for (i = 0; i < ndcs; i++) {
259 free_dest_constraint_hop(&dcs[i].from);
260 free_dest_constraint_hop(&dcs[i].to);
266 free_identity(Identity *id)
268 sshkey_free(id->key);
271 free(id->sk_provider);
272 free_dest_constraints(id->dest_constraints, id->ndest_constraints);
277 * Match 'key' against the key/CA list in a destination constraint hop
278 * Returns 0 on success or -1 otherwise.
281 match_key_hop(const char *tag, const struct sshkey *key,
282 const struct dest_constraint_hop *dch)
284 const char *reason = NULL;
285 const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
292 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
293 SSH_FP_DEFAULT)) == NULL)
294 fatal_f("fingerprint failed");
295 debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
296 tag, hostname, sshkey_type(key), fp, dch->nkeys);
298 for (i = 0; i < dch->nkeys; i++) {
299 if (dch->keys[i] == NULL)
302 if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
303 SSH_FP_DEFAULT)) == NULL)
304 fatal_f("fingerprint failed");
305 debug3_f("%s: key %u: %s%s %s", tag, i,
306 dch->key_is_ca[i] ? "CA " : "",
307 sshkey_type(dch->keys[i]), fp);
309 if (!sshkey_is_cert(key)) {
311 if (dch->key_is_ca[i] ||
312 !sshkey_equal(key, dch->keys[i]))
317 if (!dch->key_is_ca[i])
319 if (key->cert == NULL || key->cert->signature_key == NULL)
320 return -1; /* shouldn't happen */
321 if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
323 if (sshkey_cert_check_host(key, hostname, 1,
324 SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
325 debug_f("cert %s / hostname %s rejected: %s",
326 key->cert->key_id, hostname, reason);
334 /* Check destination constraints on an identity against the hostkey/user */
336 permitted_by_dest_constraints(const struct sshkey *fromkey,
337 const struct sshkey *tokey, Identity *id, const char *user,
338 const char **hostnamep)
341 struct dest_constraint *d;
343 if (hostnamep != NULL)
345 for (i = 0; i < id->ndest_constraints; i++) {
346 d = id->dest_constraints + i;
347 /* XXX remove logspam */
348 debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
349 i, d->from.user ? d->from.user : "",
350 d->from.user ? "@" : "",
351 d->from.hostname ? d->from.hostname : "(ORIGIN)",
353 d->to.user ? d->to.user : "", d->to.user ? "@" : "",
354 d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
356 /* Match 'from' key */
357 if (fromkey == NULL) {
358 /* We are matching the first hop */
359 if (d->from.hostname != NULL || d->from.nkeys != 0)
361 } else if (match_key_hop("from", fromkey, &d->from) != 0)
365 if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
368 /* Match user if specified */
369 if (d->to.user != NULL && user != NULL &&
370 !match_pattern(user, d->to.user))
373 /* successfully matched this constraint */
374 if (hostnamep != NULL)
375 *hostnamep = d->to.hostname;
376 debug2_f("allowed for hostname %s",
377 d->to.hostname == NULL ? "*" : d->to.hostname);
381 debug2_f("%s identity \"%s\" not permitted for this destination",
382 sshkey_type(id->key), id->comment);
387 * Check whether hostkeys on a SocketEntry and the optionally specified user
388 * are permitted by the destination constraints on the Identity.
389 * Returns 0 on success or -1 otherwise.
392 identity_permitted(Identity *id, SocketEntry *e, char *user,
393 const char **forward_hostnamep, const char **last_hostnamep)
397 struct hostkey_sid *hks;
398 const struct sshkey *fromkey = NULL;
399 const char *test_user;
402 /* XXX remove logspam */
403 debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
404 "%zu constraints", sshkey_type(id->key), id->comment,
405 e->nsession_ids, id->ndest_constraints);
406 if (id->ndest_constraints == 0)
407 return 0; /* unconstrained */
408 if (e->nsession_ids == 0)
409 return 0; /* local use */
411 * Walk through the hops recorded by session_id and try to find a
412 * constraint that satisfies each.
414 for (i = 0; i < e->nsession_ids; i++) {
415 hks = e->session_ids + i;
416 if (hks->key == NULL)
417 fatal_f("internal error: no bound key");
418 /* XXX remove logspam */
420 if (fromkey != NULL &&
421 (fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
422 SSH_FP_DEFAULT)) == NULL)
423 fatal_f("fingerprint failed");
424 if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
425 SSH_FP_DEFAULT)) == NULL)
426 fatal_f("fingerprint failed");
427 debug3_f("socketentry fd=%d, entry %zu %s, "
428 "from hostkey %s %s to user %s hostkey %s %s",
429 e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
430 fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
431 fromkey ? fp1 : "", user ? user : "(ANY)",
432 sshkey_type(hks->key), fp2);
436 * Record the hostnames for the initial forwarding and
437 * the final destination.
440 if (i == e->nsession_ids - 1)
443 hp = forward_hostnamep;
444 /* Special handling for final recorded binding */
446 if (i == e->nsession_ids - 1) {
447 /* Can only check user at final hop */
450 * user is only presented for signature requests.
451 * If this is the case, make sure last binding is not
454 if (hks->forwarded && user != NULL) {
455 error_f("tried to sign on forwarding hop");
458 } else if (!hks->forwarded) {
459 error_f("tried to forward though signing bind");
462 if (permitted_by_dest_constraints(fromkey, hks->key, id,
468 * Another special case: if the last bound session ID was for a
469 * forwarding, and this function is not being called to check a sign
470 * request (i.e. no 'user' supplied), then only permit the key if
471 * there is a permission that would allow it to be used at another
472 * destination. This hides keys that are allowed to be used to
473 * authenticate *to* a host but not permitted for *use* beyond it.
475 hks = &e->session_ids[e->nsession_ids - 1];
476 if (hks->forwarded && user == NULL &&
477 permitted_by_dest_constraints(hks->key, NULL, id,
479 debug3_f("key permitted at host but not after");
487 /* return matching private key for given public key */
489 lookup_identity(struct sshkey *key)
493 TAILQ_FOREACH(id, &idtab->idlist, next) {
494 if (sshkey_equal(key, id->key))
500 /* Check confirmation of keysign request */
502 confirm_key(Identity *id, const char *extra)
507 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
509 ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
511 extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
519 send_status(SocketEntry *e, int success)
523 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
524 (r = sshbuf_put_u8(e->output, success ?
525 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
526 fatal_fr(r, "compose");
529 /* send list of supported public keys to 'client' */
531 process_request_identities(SocketEntry *e)
534 struct sshbuf *msg, *keys;
538 debug2_f("entering");
540 if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
541 fatal_f("sshbuf_new failed");
542 TAILQ_FOREACH(id, &idtab->idlist, next) {
543 /* identity not visible, don't include in response */
544 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
546 if ((r = sshkey_puts_opts(id->key, keys,
547 SSHKEY_SERIALIZE_INFO)) != 0 ||
548 (r = sshbuf_put_cstring(keys, id->comment)) != 0) {
549 error_fr(r, "compose key/comment");
554 debug2_f("replying with %u allowed of %u available keys",
555 nentries, idtab->nentries);
556 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
557 (r = sshbuf_put_u32(msg, nentries)) != 0 ||
558 (r = sshbuf_putb(msg, keys)) != 0)
559 fatal_fr(r, "compose");
560 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
561 fatal_fr(r, "enqueue");
568 agent_decode_alg(struct sshkey *key, u_int flags)
570 if (key->type == KEY_RSA) {
571 if (flags & SSH_AGENT_RSA_SHA2_256)
572 return "rsa-sha2-256";
573 else if (flags & SSH_AGENT_RSA_SHA2_512)
574 return "rsa-sha2-512";
575 } else if (key->type == KEY_RSA_CERT) {
576 if (flags & SSH_AGENT_RSA_SHA2_256)
577 return "rsa-sha2-256-cert-v01@openssh.com";
578 else if (flags & SSH_AGENT_RSA_SHA2_512)
579 return "rsa-sha2-512-cert-v01@openssh.com";
585 * Attempt to parse the contents of a buffer as a SSH publickey userauth
586 * request, checking its contents for consistency and matching the embedded
587 * key against the one that is being used for signing.
588 * Note: does not modify msg buffer.
589 * Optionally extract the username, session ID and/or hostkey from the request.
592 parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
593 char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
595 struct sshbuf *b = NULL, *sess_id = NULL;
596 char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
598 u_char t, sig_follows;
599 struct sshkey *mkey = NULL, *hostkey = NULL;
603 if (sess_idp != NULL)
605 if (hostkeyp != NULL)
607 if ((b = sshbuf_fromb(msg)) == NULL)
608 fatal_f("sshbuf_fromb");
610 /* SSH userauth request */
611 if ((r = sshbuf_froms(b, &sess_id)) != 0)
613 if (sshbuf_len(sess_id) == 0) {
614 r = SSH_ERR_INVALID_FORMAT;
617 if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
618 (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
619 (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
620 (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
621 (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
622 (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
623 (r = sshkey_froms(b, &mkey)) != 0) /* key */
625 if (t != SSH2_MSG_USERAUTH_REQUEST ||
627 strcmp(service, "ssh-connection") != 0 ||
628 !sshkey_equal(expected_key, mkey) ||
629 sshkey_type_from_name(pkalg) != expected_key->type) {
630 r = SSH_ERR_INVALID_FORMAT;
633 if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
634 if ((r = sshkey_froms(b, &hostkey)) != 0)
636 } else if (strcmp(method, "publickey") != 0) {
637 r = SSH_ERR_INVALID_FORMAT;
640 if (sshbuf_len(b) != 0) {
641 r = SSH_ERR_INVALID_FORMAT;
646 debug3_f("well formed userauth");
651 if (sess_idp != NULL) {
655 if (hostkeyp != NULL) {
661 sshbuf_free(sess_id);
667 sshkey_free(hostkey);
672 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
673 * Note: does not modify buffer.
676 parse_sshsig_request(struct sshbuf *msg)
681 if ((b = sshbuf_fromb(msg)) == NULL)
682 fatal_f("sshbuf_fromb");
684 if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
685 (r = sshbuf_consume(b, 6)) != 0 ||
686 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
687 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
688 (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
689 (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
691 if (sshbuf_len(b) != 0) {
692 r = SSH_ERR_INVALID_FORMAT;
703 * This function inspects a message to be signed by a FIDO key that has a
704 * web-like application string (i.e. one that does not begin with "ssh:".
705 * It checks that the message is one of those expected for SSH operations
706 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
710 check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
712 if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
713 debug_f("signed data matches public key userauth request");
716 if (parse_sshsig_request(data) == 0) {
717 debug_f("signed data matches SSHSIG signature request");
721 /* XXX check CA signature operation */
723 error("web-origin key attempting to sign non-SSH message");
728 buf_equal(const struct sshbuf *a, const struct sshbuf *b)
730 if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
731 return SSH_ERR_INVALID_ARGUMENT;
732 if (sshbuf_len(a) != sshbuf_len(b))
733 return SSH_ERR_INVALID_FORMAT;
734 if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
735 return SSH_ERR_INVALID_FORMAT;
741 process_sign_request2(SocketEntry *e)
743 u_char *signature = NULL;
745 u_int compat = 0, flags;
746 int r, ok = -1, retried = 0;
747 char *fp = NULL, *pin = NULL, *prompt = NULL;
748 char *user = NULL, *sig_dest = NULL;
749 const char *fwd_host = NULL, *dest_host = NULL;
750 struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
751 struct sshkey *key = NULL, *hostkey = NULL;
753 struct notifier_ctx *notifier = NULL;
757 if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
758 fatal_f("sshbuf_new failed");
759 if ((r = sshkey_froms(e->request, &key)) != 0 ||
760 (r = sshbuf_get_stringb(e->request, data)) != 0 ||
761 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
762 error_fr(r, "parse");
766 if ((id = lookup_identity(key)) == NULL) {
767 verbose_f("%s key not found", sshkey_type(key));
770 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
771 SSH_FP_DEFAULT)) == NULL)
772 fatal_f("fingerprint failed");
774 if (id->ndest_constraints != 0) {
775 if (e->nsession_ids == 0) {
776 logit_f("refusing use of destination-constrained key "
777 "to sign on unbound connection");
780 if (parse_userauth_request(data, key, &user, &sid,
782 logit_f("refusing use of destination-constrained key "
783 "to sign an unidentified signature");
787 debug_f("user=%s", user);
788 if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
790 /* XXX display fwd_host/dest_host in askpass UI */
792 * Ensure that the session ID is the most recent one
793 * registered on the socket - it should have been bound by
794 * ssh immediately before userauth.
797 e->session_ids[e->nsession_ids - 1].sid) != 0) {
798 error_f("unexpected session ID (%zu listed) on "
799 "signature request for target user %s with "
800 "key %s %s", e->nsession_ids, user,
801 sshkey_type(id->key), fp);
805 * Ensure that the hostkey embedded in the signature matches
806 * the one most recently bound to the socket. An exception is
807 * made for the initial forwarding hop.
809 if (e->nsession_ids > 1 && hostkey == NULL) {
810 error_f("refusing use of destination-constrained key: "
811 "no hostkey recorded in signature for forwarded "
815 if (hostkey != NULL && !sshkey_equal(hostkey,
816 e->session_ids[e->nsession_ids - 1].key)) {
817 error_f("refusing use of destination-constrained key: "
818 "mismatch between hostkey in request and most "
819 "recently bound session");
822 xasprintf(&sig_dest, "public key authentication request for "
823 "user \"%s\" to listed host", user);
825 if (id->confirm && confirm_key(id, sig_dest) != 0) {
826 verbose_f("user refused key");
829 if (sshkey_is_sk(id->key)) {
830 if (strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
831 !check_websafe_message_contents(key, data)) {
832 /* error already logged */
835 if ((id->key->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
836 /* XXX include sig_dest */
837 xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
838 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
839 " and confirm user presence " : " ",
840 sshkey_type(id->key), fp);
841 pin = read_passphrase(prompt, RP_USE_ASKPASS);
844 } else if ((id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
845 notifier = notify_start(0,
846 "Confirm user presence for key %s %s%s%s",
847 sshkey_type(id->key), fp,
848 sig_dest == NULL ? "" : "\n",
849 sig_dest == NULL ? "" : sig_dest);
853 if ((r = sshkey_sign(id->key, &signature, &slen,
854 sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
855 id->sk_provider, pin, compat)) != 0) {
856 debug_fr(r, "sshkey_sign");
857 if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
858 r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
860 notify_complete(notifier, NULL);
863 /* XXX include sig_dest */
864 xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
865 (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
866 " and confirm user presence " : " ",
867 sshkey_type(id->key), fp);
868 pin = read_passphrase(prompt, RP_USE_ASKPASS);
872 error_fr(r, "sshkey_sign");
878 notify_complete(notifier, "User presence confirmed");
881 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
882 (r = sshbuf_put_string(msg, signature, slen)) != 0)
883 fatal_fr(r, "compose");
884 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
885 fatal_fr(r, "compose failure");
887 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
888 fatal_fr(r, "enqueue");
894 sshkey_free(hostkey);
901 freezero(pin, strlen(pin));
906 process_remove_identity(SocketEntry *e)
909 struct sshkey *key = NULL;
912 debug2_f("entering");
913 if ((r = sshkey_froms(e->request, &key)) != 0) {
914 error_fr(r, "parse key");
917 if ((id = lookup_identity(key)) == NULL) {
918 debug_f("key not found");
921 /* identity not visible, cannot be removed */
922 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
923 goto done; /* error already logged */
924 /* We have this key, free it. */
925 if (idtab->nentries < 1)
926 fatal_f("internal error: nentries %d", idtab->nentries);
927 TAILQ_REMOVE(&idtab->idlist, id, next);
933 send_status(e, success);
937 process_remove_all_identities(SocketEntry *e)
941 debug2_f("entering");
942 /* Loop over all identities and clear the keys. */
943 for (id = TAILQ_FIRST(&idtab->idlist); id;
944 id = TAILQ_FIRST(&idtab->idlist)) {
945 TAILQ_REMOVE(&idtab->idlist, id, next);
949 /* Mark that there are no identities. */
956 /* removes expired keys and returns number of seconds until the next expiry */
960 time_t deadline = 0, now = monotime();
963 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
964 nxt = TAILQ_NEXT(id, next);
967 if (now >= id->death) {
968 debug("expiring key '%s'", id->comment);
969 TAILQ_REMOVE(&idtab->idlist, id, next);
973 deadline = (deadline == 0) ? id->death :
974 MINIMUM(deadline, id->death);
976 if (deadline == 0 || deadline <= now)
979 return (deadline - now);
983 parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
988 struct sshkey *k = NULL;
991 memset(dch, '\0', sizeof(*dch));
992 if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
993 (r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
994 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
995 error_fr(r, "parse");
999 error_f("unsupported extensions (len %zu)", elen);
1000 r = SSH_ERR_FEATURE_UNSUPPORTED;
1003 if (*dch->hostname == '\0') {
1004 free(dch->hostname);
1005 dch->hostname = NULL;
1007 if (*dch->user == '\0') {
1011 while (sshbuf_len(b) != 0) {
1012 dch->keys = xrecallocarray(dch->keys, dch->nkeys,
1013 dch->nkeys + 1, sizeof(*dch->keys));
1014 dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
1015 dch->nkeys + 1, sizeof(*dch->key_is_ca));
1016 if ((r = sshkey_froms(b, &k)) != 0 ||
1017 (r = sshbuf_get_u8(b, &key_is_ca)) != 0)
1019 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1020 SSH_FP_DEFAULT)) == NULL)
1021 fatal_f("fingerprint failed");
1022 debug3_f("%s%s%s: adding %skey %s %s",
1023 dch->user == NULL ? "" : dch->user,
1024 dch->user == NULL ? "" : "@",
1025 dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
1027 dch->keys[dch->nkeys] = k;
1028 dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
1030 k = NULL; /* transferred */
1040 parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
1042 struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
1046 debug3_f("entering");
1048 memset(dc, '\0', sizeof(*dc));
1049 if ((r = sshbuf_froms(m, &b)) != 0 ||
1050 (r = sshbuf_froms(b, &frombuf)) != 0 ||
1051 (r = sshbuf_froms(b, &tobuf)) != 0 ||
1052 (r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
1053 error_fr(r, "parse");
1056 if ((r = parse_dest_constraint_hop(frombuf, &dc->from) != 0) ||
1057 (r = parse_dest_constraint_hop(tobuf, &dc->to) != 0))
1058 goto out; /* already logged */
1060 error_f("unsupported extensions (len %zu)", elen);
1061 r = SSH_ERR_FEATURE_UNSUPPORTED;
1064 debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1065 dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
1066 dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
1067 dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
1068 /* check consistency */
1069 if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
1070 dc->from.user != NULL) {
1071 error_f("inconsistent \"from\" specification");
1072 r = SSH_ERR_INVALID_FORMAT;
1075 if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
1076 error_f("incomplete \"to\" specification");
1077 r = SSH_ERR_INVALID_FORMAT;
1084 sshbuf_free(frombuf);
1090 parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
1091 struct dest_constraint **dcsp, size_t *ndcsp)
1093 char *ext_name = NULL;
1095 struct sshbuf *b = NULL;
1097 if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
1098 error_fr(r, "parse constraint extension");
1101 debug_f("constraint ext %s", ext_name);
1102 if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
1103 if (sk_providerp == NULL) {
1104 error_f("%s not valid here", ext_name);
1105 r = SSH_ERR_INVALID_FORMAT;
1108 if (*sk_providerp != NULL) {
1109 error_f("%s already set", ext_name);
1110 r = SSH_ERR_INVALID_FORMAT;
1113 if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
1114 error_fr(r, "parse %s", ext_name);
1117 } else if (strcmp(ext_name,
1118 "restrict-destination-v00@openssh.com") == 0) {
1119 if (*dcsp != NULL) {
1120 error_f("%s already set", ext_name);
1123 if ((r = sshbuf_froms(m, &b)) != 0) {
1124 error_fr(r, "parse %s outer", ext_name);
1127 while (sshbuf_len(b) != 0) {
1128 if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
1129 error_f("too many %s constraints", ext_name);
1132 *dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
1134 if ((r = parse_dest_constraint(b,
1135 *dcsp + (*ndcsp)++)) != 0)
1136 goto out; /* error already logged */
1139 error_f("unsupported constraint \"%s\"", ext_name);
1140 r = SSH_ERR_FEATURE_UNSUPPORTED;
1152 parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
1153 u_int *secondsp, int *confirmp, char **sk_providerp,
1154 struct dest_constraint **dcsp, size_t *ndcsp)
1158 u_int seconds, maxsign = 0;
1160 while (sshbuf_len(m)) {
1161 if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
1162 error_fr(r, "parse constraint type");
1166 case SSH_AGENT_CONSTRAIN_LIFETIME:
1168 error_f("lifetime already set");
1169 r = SSH_ERR_INVALID_FORMAT;
1172 if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
1173 error_fr(r, "parse lifetime constraint");
1176 *deathp = monotime() + seconds;
1177 *secondsp = seconds;
1179 case SSH_AGENT_CONSTRAIN_CONFIRM:
1180 if (*confirmp != 0) {
1181 error_f("confirm already set");
1182 r = SSH_ERR_INVALID_FORMAT;
1187 case SSH_AGENT_CONSTRAIN_MAXSIGN:
1189 error_f("maxsign not valid here");
1190 r = SSH_ERR_INVALID_FORMAT;
1194 error_f("maxsign already set");
1195 r = SSH_ERR_INVALID_FORMAT;
1198 if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
1199 error_fr(r, "parse maxsign constraint");
1202 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
1203 error_fr(r, "enable maxsign");
1207 case SSH_AGENT_CONSTRAIN_EXTENSION:
1208 if ((r = parse_key_constraint_extension(m,
1209 sk_providerp, dcsp, ndcsp)) != 0)
1210 goto out; /* error already logged */
1213 error_f("Unknown constraint %d", ctype);
1214 r = SSH_ERR_FEATURE_UNSUPPORTED;
1225 process_add_identity(SocketEntry *e)
1228 int success = 0, confirm = 0;
1229 char *fp, *comment = NULL, *sk_provider = NULL;
1230 char canonical_provider[PATH_MAX];
1233 struct dest_constraint *dest_constraints = NULL;
1234 size_t ndest_constraints = 0;
1235 struct sshkey *k = NULL;
1236 int r = SSH_ERR_INTERNAL_ERROR;
1238 debug2_f("entering");
1239 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
1241 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
1242 error_fr(r, "parse");
1245 if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
1246 &sk_provider, &dest_constraints, &ndest_constraints) != 0) {
1247 error_f("failed to parse constraints");
1248 sshbuf_reset(e->request);
1252 if (sk_provider != NULL) {
1253 if (!sshkey_is_sk(k)) {
1254 error("Cannot add provider: %s is not an "
1255 "authenticator-hosted key", sshkey_type(k));
1258 if (strcasecmp(sk_provider, "internal") == 0) {
1259 debug_f("internal provider");
1261 if (realpath(sk_provider, canonical_provider) == NULL) {
1262 verbose("failed provider \"%.100s\": "
1263 "realpath: %s", sk_provider,
1268 sk_provider = xstrdup(canonical_provider);
1269 if (match_pattern_list(sk_provider,
1270 allowed_providers, 0) != 1) {
1271 error("Refusing add key: "
1272 "provider %s not allowed", sk_provider);
1277 if ((r = sshkey_shield_private(k)) != 0) {
1278 error_fr(r, "shield private");
1281 if (lifetime && !death)
1282 death = monotime() + lifetime;
1283 if ((id = lookup_identity(k)) == NULL) {
1284 id = xcalloc(1, sizeof(Identity));
1285 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1286 /* Increment the number of identities. */
1289 /* identity not visible, do not update */
1290 if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
1291 goto out; /* error already logged */
1292 /* key state might have been updated */
1293 sshkey_free(id->key);
1295 free(id->sk_provider);
1296 free_dest_constraints(id->dest_constraints,
1297 id->ndest_constraints);
1301 id->comment = comment;
1303 id->confirm = confirm;
1304 id->sk_provider = sk_provider;
1305 id->dest_constraints = dest_constraints;
1306 id->ndest_constraints = ndest_constraints;
1308 if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
1309 SSH_FP_DEFAULT)) == NULL)
1310 fatal_f("sshkey_fingerprint failed");
1311 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1312 "(provider: %s) (destination constraints: %zu)",
1313 sshkey_ssh_name(k), fp, comment, seconds, confirm,
1314 sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
1320 dest_constraints = NULL;
1321 ndest_constraints = 0;
1327 free_dest_constraints(dest_constraints, ndest_constraints);
1328 send_status(e, success);
1331 /* XXX todo: encrypt sensitive data with passphrase */
1333 process_lock_agent(SocketEntry *e, int lock)
1335 int r, success = 0, delay;
1337 u_char passwdhash[LOCK_SIZE];
1338 static u_int fail_count = 0;
1341 debug2_f("entering");
1343 * This is deliberately fatal: the user has requested that we lock,
1344 * but we can't parse their request properly. The only safe thing to
1347 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
1348 fatal_fr(r, "parse");
1350 debug("empty password not supported");
1351 } else if (locked && !lock) {
1352 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1353 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
1354 fatal("bcrypt_pbkdf");
1355 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
1356 debug("agent unlocked");
1359 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
1362 /* delay in 0.1s increments up to 10s */
1363 if (fail_count < 100)
1365 delay = 100000 * fail_count;
1366 debug("unlock failed, delaying %0.1lf seconds",
1367 (double)delay/1000000);
1370 explicit_bzero(passwdhash, sizeof(passwdhash));
1371 } else if (!locked && lock) {
1372 debug("agent locked");
1374 arc4random_buf(lock_salt, sizeof(lock_salt));
1375 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
1376 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
1377 fatal("bcrypt_pbkdf");
1380 freezero(passwd, pwlen);
1381 send_status(e, success);
1385 no_identities(SocketEntry *e)
1390 if ((msg = sshbuf_new()) == NULL)
1391 fatal_f("sshbuf_new failed");
1392 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
1393 (r = sshbuf_put_u32(msg, 0)) != 0 ||
1394 (r = sshbuf_put_stringb(e->output, msg)) != 0)
1395 fatal_fr(r, "compose");
1399 #ifdef ENABLE_PKCS11
1401 process_add_smartcard_key(SocketEntry *e)
1403 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1404 char **comments = NULL;
1405 int r, i, count = 0, success = 0, confirm = 0;
1408 struct sshkey **keys = NULL, *k;
1410 struct dest_constraint *dest_constraints = NULL;
1411 size_t ndest_constraints = 0;
1413 debug2_f("entering");
1414 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1415 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1416 error_fr(r, "parse");
1419 if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
1420 NULL, &dest_constraints, &ndest_constraints) != 0) {
1421 error_f("failed to parse constraints");
1424 if (realpath(provider, canonical_provider) == NULL) {
1425 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1426 provider, strerror(errno));
1429 if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
1430 verbose("refusing PKCS#11 add of \"%.100s\": "
1431 "provider not allowed", canonical_provider);
1434 debug_f("add %.100s", canonical_provider);
1435 if (lifetime && !death)
1436 death = monotime() + lifetime;
1438 count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
1439 for (i = 0; i < count; i++) {
1441 if (lookup_identity(k) == NULL) {
1442 id = xcalloc(1, sizeof(Identity));
1444 keys[i] = NULL; /* transferred */
1445 id->provider = xstrdup(canonical_provider);
1446 if (*comments[i] != '\0') {
1447 id->comment = comments[i];
1448 comments[i] = NULL; /* transferred */
1450 id->comment = xstrdup(canonical_provider);
1453 id->confirm = confirm;
1454 id->dest_constraints = dest_constraints;
1455 id->ndest_constraints = ndest_constraints;
1456 dest_constraints = NULL; /* transferred */
1457 ndest_constraints = 0;
1458 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
1462 /* XXX update constraints for existing keys */
1463 sshkey_free(keys[i]);
1471 free_dest_constraints(dest_constraints, ndest_constraints);
1472 send_status(e, success);
1476 process_remove_smartcard_key(SocketEntry *e)
1478 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
1482 debug2_f("entering");
1483 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
1484 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
1485 error_fr(r, "parse");
1490 if (realpath(provider, canonical_provider) == NULL) {
1491 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1492 provider, strerror(errno));
1496 debug_f("remove %.100s", canonical_provider);
1497 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
1498 nxt = TAILQ_NEXT(id, next);
1499 /* Skip file--based keys */
1500 if (id->provider == NULL)
1502 if (!strcmp(canonical_provider, id->provider)) {
1503 TAILQ_REMOVE(&idtab->idlist, id, next);
1508 if (pkcs11_del_provider(canonical_provider) == 0)
1511 error_f("pkcs11_del_provider failed");
1514 send_status(e, success);
1516 #endif /* ENABLE_PKCS11 */
1519 process_ext_session_bind(SocketEntry *e)
1521 int r, sid_match, key_match;
1522 struct sshkey *key = NULL;
1523 struct sshbuf *sid = NULL, *sig = NULL;
1528 debug2_f("entering");
1529 if ((r = sshkey_froms(e->request, &key)) != 0 ||
1530 (r = sshbuf_froms(e->request, &sid)) != 0 ||
1531 (r = sshbuf_froms(e->request, &sig)) != 0 ||
1532 (r = sshbuf_get_u8(e->request, &fwd)) != 0) {
1533 error_fr(r, "parse");
1536 if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
1537 SSH_FP_DEFAULT)) == NULL)
1538 fatal_f("fingerprint failed");
1539 /* check signature with hostkey on session ID */
1540 if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
1541 sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
1542 error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
1545 /* check whether sid/key already recorded */
1546 for (i = 0; i < e->nsession_ids; i++) {
1547 if (!e->session_ids[i].forwarded) {
1548 error_f("attempt to bind session ID to socket "
1549 "previously bound for authentication attempt");
1553 sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
1554 key_match = sshkey_equal(key, e->session_ids[i].key);
1555 if (sid_match && key_match) {
1556 debug_f("session ID already recorded for %s %s",
1557 sshkey_type(key), fp);
1560 } else if (sid_match) {
1561 error_f("session ID recorded against different key "
1562 "for %s %s", sshkey_type(key), fp);
1567 * new sid with previously-seen key can happen, e.g. multiple
1568 * connections to the same host.
1571 /* record new key/sid */
1572 if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
1573 error_f("too many session IDs recorded");
1576 e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
1577 e->nsession_ids + 1, sizeof(*e->session_ids));
1578 i = e->nsession_ids++;
1579 debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
1580 AGENT_MAX_SESSION_IDS);
1581 e->session_ids[i].key = key;
1582 e->session_ids[i].forwarded = fwd != 0;
1583 key = NULL; /* transferred */
1584 /* can't transfer sid; it's refcounted and scoped to request's life */
1585 if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
1586 fatal_f("sshbuf_new");
1587 if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
1588 fatal_fr(r, "sshbuf_putb session ID");
1595 return r == 0 ? 1 : 0;
1599 process_extension(SocketEntry *e)
1604 debug2_f("entering");
1605 if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
1606 error_fr(r, "parse");
1609 if (strcmp(name, "session-bind@openssh.com") == 0)
1610 success = process_ext_session_bind(e);
1612 debug_f("unsupported extension \"%s\"", name);
1615 send_status(e, success);
1618 * dispatch incoming message.
1619 * returns 1 on success, 0 for incomplete messages or -1 on error.
1622 process_message(u_int socknum)
1630 if (socknum >= sockets_alloc)
1631 fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
1632 e = &sockets[socknum];
1634 if (sshbuf_len(e->input) < 5)
1635 return 0; /* Incomplete message header. */
1636 cp = sshbuf_ptr(e->input);
1637 msg_len = PEEK_U32(cp);
1638 if (msg_len > AGENT_MAX_LEN) {
1639 debug_f("socket %u (fd=%d) message too long %u > %u",
1640 socknum, e->fd, msg_len, AGENT_MAX_LEN);
1643 if (sshbuf_len(e->input) < msg_len + 4)
1644 return 0; /* Incomplete message body. */
1646 /* move the current input to e->request */
1647 sshbuf_reset(e->request);
1648 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
1649 (r = sshbuf_get_u8(e->request, &type)) != 0) {
1650 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
1651 r == SSH_ERR_STRING_TOO_LARGE) {
1652 error_fr(r, "parse");
1655 fatal_fr(r, "parse");
1658 debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
1660 /* check whether agent is locked */
1661 if (locked && type != SSH_AGENTC_UNLOCK) {
1662 sshbuf_reset(e->request);
1664 case SSH2_AGENTC_REQUEST_IDENTITIES:
1665 /* send empty lists */
1669 /* send a fail message for all other request types */
1676 case SSH_AGENTC_LOCK:
1677 case SSH_AGENTC_UNLOCK:
1678 process_lock_agent(e, type == SSH_AGENTC_LOCK);
1680 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
1681 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
1684 case SSH2_AGENTC_SIGN_REQUEST:
1685 process_sign_request2(e);
1687 case SSH2_AGENTC_REQUEST_IDENTITIES:
1688 process_request_identities(e);
1690 case SSH2_AGENTC_ADD_IDENTITY:
1691 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
1692 process_add_identity(e);
1694 case SSH2_AGENTC_REMOVE_IDENTITY:
1695 process_remove_identity(e);
1697 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
1698 process_remove_all_identities(e);
1700 #ifdef ENABLE_PKCS11
1701 case SSH_AGENTC_ADD_SMARTCARD_KEY:
1702 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
1703 process_add_smartcard_key(e);
1705 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
1706 process_remove_smartcard_key(e);
1708 #endif /* ENABLE_PKCS11 */
1709 case SSH_AGENTC_EXTENSION:
1710 process_extension(e);
1713 /* Unknown message. Respond with failure. */
1714 error("Unknown message %d", type);
1715 sshbuf_reset(e->request);
1723 new_socket(sock_type type, int fd)
1725 u_int i, old_alloc, new_alloc;
1727 debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
1728 (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
1729 if (type == AUTH_CONNECTION) {
1730 debug("xcount %d -> %d", xcount, xcount + 1);
1738 for (i = 0; i < sockets_alloc; i++)
1739 if (sockets[i].type == AUTH_UNUSED) {
1741 if ((sockets[i].input = sshbuf_new()) == NULL ||
1742 (sockets[i].output = sshbuf_new()) == NULL ||
1743 (sockets[i].request = sshbuf_new()) == NULL)
1744 fatal_f("sshbuf_new failed");
1745 sockets[i].type = type;
1748 old_alloc = sockets_alloc;
1749 new_alloc = sockets_alloc + 10;
1750 sockets = xrecallocarray(sockets, old_alloc, new_alloc,
1751 sizeof(sockets[0]));
1752 for (i = old_alloc; i < new_alloc; i++)
1753 sockets[i].type = AUTH_UNUSED;
1754 sockets_alloc = new_alloc;
1755 sockets[old_alloc].fd = fd;
1756 if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
1757 (sockets[old_alloc].output = sshbuf_new()) == NULL ||
1758 (sockets[old_alloc].request = sshbuf_new()) == NULL)
1759 fatal_f("sshbuf_new failed");
1760 sockets[old_alloc].type = type;
1764 handle_socket_read(u_int socknum)
1766 struct sockaddr_un sunaddr;
1772 slen = sizeof(sunaddr);
1773 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
1775 error("accept from AUTH_SOCKET: %s", strerror(errno));
1778 if (getpeereid(fd, &euid, &egid) == -1) {
1779 error("getpeereid %d failed: %s", fd, strerror(errno));
1783 if ((euid != 0) && (getuid() != euid)) {
1784 error("uid mismatch: peer euid %u != uid %u",
1785 (u_int) euid, (u_int) getuid());
1789 new_socket(AUTH_CONNECTION, fd);
1794 handle_conn_read(u_int socknum)
1796 char buf[AGENT_RBUF_LEN];
1800 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
1802 if (errno == EAGAIN || errno == EINTR)
1804 error_f("read error on socket %u (fd %d): %s",
1805 socknum, sockets[socknum].fd, strerror(errno));
1809 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
1810 fatal_fr(r, "compose");
1811 explicit_bzero(buf, sizeof(buf));
1813 if ((r = process_message(socknum)) == -1)
1822 handle_conn_write(u_int socknum)
1827 if (sshbuf_len(sockets[socknum].output) == 0)
1828 return 0; /* shouldn't happen */
1829 if ((len = write(sockets[socknum].fd,
1830 sshbuf_ptr(sockets[socknum].output),
1831 sshbuf_len(sockets[socknum].output))) <= 0) {
1833 if (errno == EAGAIN || errno == EINTR)
1835 error_f("read error on socket %u (fd %d): %s",
1836 socknum, sockets[socknum].fd, strerror(errno));
1840 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
1841 fatal_fr(r, "consume");
1846 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
1849 u_int socknum, activefds = npfd;
1851 for (i = 0; i < npfd; i++) {
1852 if (pfd[i].revents == 0)
1854 /* Find sockets entry */
1855 for (socknum = 0; socknum < sockets_alloc; socknum++) {
1856 if (sockets[socknum].type != AUTH_SOCKET &&
1857 sockets[socknum].type != AUTH_CONNECTION)
1859 if (pfd[i].fd == sockets[socknum].fd)
1862 if (socknum >= sockets_alloc) {
1863 error_f("no socket for fd %d", pfd[i].fd);
1866 /* Process events */
1867 switch (sockets[socknum].type) {
1869 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
1871 if (npfd > maxfds) {
1872 debug3("out of fds (active %u >= limit %u); "
1873 "skipping accept", activefds, maxfds);
1876 if (handle_socket_read(socknum) == 0)
1879 case AUTH_CONNECTION:
1880 if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
1881 handle_conn_read(socknum) != 0)
1883 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
1884 handle_conn_write(socknum) != 0) {
1887 fatal("activefds == 0 at close_sock");
1888 close_socket(&sockets[socknum]);
1900 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
1902 struct pollfd *pfd = *pfdp;
1903 size_t i, j, npfd = 0;
1907 /* Count active sockets */
1908 for (i = 0; i < sockets_alloc; i++) {
1909 switch (sockets[i].type) {
1911 case AUTH_CONNECTION:
1917 fatal("Unknown socket type %d", sockets[i].type);
1921 if (npfd != *npfdp &&
1922 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
1923 fatal_f("recallocarray failed");
1927 for (i = j = 0; i < sockets_alloc; i++) {
1928 switch (sockets[i].type) {
1930 if (npfd > maxfds) {
1931 debug3("out of fds (active %zu >= limit %u); "
1932 "skipping arming listener", npfd, maxfds);
1935 pfd[j].fd = sockets[i].fd;
1937 pfd[j].events = POLLIN;
1940 case AUTH_CONNECTION:
1941 pfd[j].fd = sockets[i].fd;
1944 * Only prepare to read if we can handle a full-size
1945 * input read buffer and enqueue a max size reply..
1947 if ((r = sshbuf_check_reserve(sockets[i].input,
1948 AGENT_RBUF_LEN)) == 0 &&
1949 (r = sshbuf_check_reserve(sockets[i].output,
1950 AGENT_MAX_LEN)) == 0)
1951 pfd[j].events = POLLIN;
1952 else if (r != SSH_ERR_NO_BUFFER_SPACE)
1953 fatal_fr(r, "reserve");
1954 if (sshbuf_len(sockets[i].output) > 0)
1955 pfd[j].events |= POLLOUT;
1962 deadline = reaper();
1963 if (parent_alive_interval != 0)
1964 deadline = (deadline == 0) ? parent_alive_interval :
1965 MINIMUM(deadline, parent_alive_interval);
1966 if (deadline == 0) {
1967 *timeoutp = -1; /* INFTIM */
1969 if (deadline > INT_MAX / 1000)
1970 *timeoutp = INT_MAX / 1000;
1972 *timeoutp = deadline * 1000;
1978 cleanup_socket(void)
1980 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1984 unlink(socket_name);
1998 cleanup_handler(int sig)
2001 #ifdef ENABLE_PKCS11
2008 check_parent_exists(void)
2011 * If our parent has exited then getppid() will return (pid_t)1,
2012 * so testing for that should be safe.
2014 if (parent_pid != -1 && getppid() != parent_pid) {
2015 /* printf("Parent has died - Authentication agent exiting.\n"); */
2025 "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
2026 " [-P allowed_providers] [-t life]\n"
2027 " ssh-agent [-a bind_address] [-E fingerprint_hash] [-P allowed_providers]\n"
2028 " [-t life] command [arg ...]\n"
2029 " ssh-agent [-c | -s] -k\n");
2034 main(int ac, char **av)
2036 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
2037 int sock, ch, result, saved_errno;
2038 char *shell, *format, *pidstr, *agentsocket = NULL;
2039 #ifdef HAVE_SETRLIMIT
2043 extern char *optarg;
2045 char pidstrbuf[1 + 3 * sizeof pid];
2048 int timeout = -1; /* INFTIM */
2049 struct pollfd *pfd = NULL;
2053 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2061 platform_disable_tracing(0); /* strict=no */
2063 #ifdef RLIMIT_NOFILE
2064 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
2065 fatal("%s: getrlimit: %s", __progname, strerror(errno));
2068 __progname = ssh_get_progname(av[0]);
2071 while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:x")) != -1) {
2074 fingerprint_hash = ssh_digest_alg_by_name(optarg);
2075 if (fingerprint_hash == -1)
2076 fatal("Invalid hash algorithm \"%s\"", optarg);
2087 if (strcmp(optarg, "no-restrict-websafe") == 0)
2088 restrict_websafe = 0;
2090 fatal("Unknown -O option");
2093 if (allowed_providers != NULL)
2094 fatal("-P option already specified");
2095 allowed_providers = xstrdup(optarg);
2103 if (d_flag || D_flag)
2108 if (d_flag || D_flag)
2113 agentsocket = optarg;
2116 if ((lifetime = convtime(optarg)) == -1) {
2117 fprintf(stderr, "Invalid lifetime\n");
2131 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
2134 if (allowed_providers == NULL)
2135 allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
2137 if (ac == 0 && !c_flag && !s_flag) {
2138 shell = getenv("SHELL");
2139 if (shell != NULL && (len = strlen(shell)) > 2 &&
2140 strncmp(shell + len - 3, "csh", 3) == 0)
2144 const char *errstr = NULL;
2146 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
2147 if (pidstr == NULL) {
2148 fprintf(stderr, "%s not set, cannot kill agent\n",
2149 SSH_AGENTPID_ENV_NAME);
2152 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
2155 "%s=\"%s\", which is not a good PID: %s\n",
2156 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
2159 if (kill(pid, SIGTERM) == -1) {
2163 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
2164 printf(format, SSH_AUTHSOCKET_ENV_NAME);
2165 printf(format, SSH_AGENTPID_ENV_NAME);
2166 printf("echo Agent pid %ld killed;\n", (long)pid);
2171 * Minimum file descriptors:
2172 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2173 * a few spare for libc / stack protectors / sanitisers, etc.
2175 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2176 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
2177 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2178 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
2179 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
2181 parent_pid = getpid();
2183 if (agentsocket == NULL) {
2184 /* Create private directory for agent socket */
2185 mktemp_proto(socket_dir, sizeof(socket_dir));
2186 if (mkdtemp(socket_dir) == NULL) {
2187 perror("mkdtemp: private socket dir");
2190 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
2193 /* Try to use specified agent socket */
2194 socket_dir[0] = '\0';
2195 strlcpy(socket_name, agentsocket, sizeof socket_name);
2199 * Create socket early so it will exist before command gets run from
2202 prev_mask = umask(0177);
2203 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
2205 /* XXX - unix_listener() calls error() not perror() */
2206 *socket_name = '\0'; /* Don't unlink any existing file */
2212 * Fork, and have the parent execute the command, if any, or present
2213 * the socket data. The child continues as the authentication agent.
2215 if (D_flag || d_flag) {
2216 log_init(__progname,
2217 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
2218 SYSLOG_FACILITY_AUTH, 1);
2219 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2220 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2221 SSH_AUTHSOCKET_ENV_NAME);
2222 printf("echo Agent pid %ld;\n", (long)parent_pid);
2231 if (pid != 0) { /* Parent - execute the given command. */
2233 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
2235 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2236 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
2237 SSH_AUTHSOCKET_ENV_NAME);
2238 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
2239 SSH_AGENTPID_ENV_NAME);
2240 printf("echo Agent pid %ld;\n", (long)pid);
2243 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
2244 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
2253 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
2255 if (setsid() == -1) {
2256 error("setsid: %s", strerror(errno));
2261 if (stdfd_devnull(1, 1, 1) == -1)
2262 error_f("stdfd_devnull failed");
2264 #ifdef HAVE_SETRLIMIT
2265 /* deny core dumps, since memory contains unencrypted private keys */
2266 rlim.rlim_cur = rlim.rlim_max = 0;
2267 if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
2268 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
2275 cleanup_pid = getpid();
2277 #ifdef ENABLE_PKCS11
2280 new_socket(AUTH_SOCKET, sock);
2282 parent_alive_interval = 10;
2284 ssh_signal(SIGPIPE, SIG_IGN);
2285 ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
2286 ssh_signal(SIGHUP, cleanup_handler);
2287 ssh_signal(SIGTERM, cleanup_handler);
2289 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
2290 fatal("%s: pledge: %s", __progname, strerror(errno));
2291 platform_pledge_agent();
2294 prepare_poll(&pfd, &npfd, &timeout, maxfds);
2295 result = poll(pfd, npfd, timeout);
2296 saved_errno = errno;
2297 if (parent_alive_interval != 0)
2298 check_parent_exists();
2299 (void) reaper(); /* remove expired keys */
2301 if (saved_errno == EINTR)
2303 fatal("poll: %s", strerror(saved_errno));
2304 } else if (result > 0)
2305 after_poll(pfd, npfd, maxfds);