1 /* $OpenBSD: ssh-agent.c,v 1.306 2024/03/09 05:12:13 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 sig_atomic_t signalled
= 0;
167 /* pid of process for which cleanup_socket is applicable */
168 pid_t cleanup_pid
= 0;
170 /* pathname and directory for AUTH_SOCKET */
171 char socket_name
[PATH_MAX
];
172 char socket_dir
[PATH_MAX
];
174 /* Pattern-list of allowed PKCS#11/Security key paths */
175 static char *allowed_providers
;
178 * Allows PKCS11 providers or SK keys that use non-internal providers to
179 * be added over a remote connection (identified by session-bind@openssh.com).
181 static int remote_add_provider
;
185 #define LOCK_SALT_SIZE 16
186 #define LOCK_ROUNDS 1
188 u_char lock_pwhash
[LOCK_SIZE
];
189 u_char lock_salt
[LOCK_SALT_SIZE
];
191 extern char *__progname
;
193 /* Default lifetime in seconds (0 == forever) */
194 static int lifetime
= 0;
196 static int fingerprint_hash
= SSH_FP_HASH_DEFAULT
;
198 /* Refuse signing of non-SSH messages for web-origin FIDO keys */
199 static int restrict_websafe
= 1;
202 close_socket(SocketEntry
*e
)
207 sshbuf_free(e
->input
);
208 sshbuf_free(e
->output
);
209 sshbuf_free(e
->request
);
210 for (i
= 0; i
< e
->nsession_ids
; i
++) {
211 sshkey_free(e
->session_ids
[i
].key
);
212 sshbuf_free(e
->session_ids
[i
].sid
);
214 free(e
->session_ids
);
215 memset(e
, '\0', sizeof(*e
));
217 e
->type
= AUTH_UNUSED
;
223 idtab
= xcalloc(1, sizeof(*idtab
));
224 TAILQ_INIT(&idtab
->idlist
);
229 free_dest_constraint_hop(struct dest_constraint_hop
*dch
)
237 for (i
= 0; i
< dch
->nkeys
; i
++)
238 sshkey_free(dch
->keys
[i
]);
240 free(dch
->key_is_ca
);
244 free_dest_constraints(struct dest_constraint
*dcs
, size_t ndcs
)
248 for (i
= 0; i
< ndcs
; i
++) {
249 free_dest_constraint_hop(&dcs
[i
].from
);
250 free_dest_constraint_hop(&dcs
[i
].to
);
257 dup_dest_constraint_hop(const struct dest_constraint_hop
*dch
,
258 struct dest_constraint_hop
*out
)
263 out
->user
= dch
->user
== NULL
? NULL
: xstrdup(dch
->user
);
264 out
->hostname
= dch
->hostname
== NULL
? NULL
: xstrdup(dch
->hostname
);
265 out
->is_ca
= dch
->is_ca
;
266 out
->nkeys
= dch
->nkeys
;
267 out
->keys
= out
->nkeys
== 0 ? NULL
:
268 xcalloc(out
->nkeys
, sizeof(*out
->keys
));
269 out
->key_is_ca
= out
->nkeys
== 0 ? NULL
:
270 xcalloc(out
->nkeys
, sizeof(*out
->key_is_ca
));
271 for (i
= 0; i
< dch
->nkeys
; i
++) {
272 if (dch
->keys
[i
] != NULL
&&
273 (r
= sshkey_from_private(dch
->keys
[i
],
274 &(out
->keys
[i
]))) != 0)
275 fatal_fr(r
, "copy key");
276 out
->key_is_ca
[i
] = dch
->key_is_ca
[i
];
280 static struct dest_constraint
*
281 dup_dest_constraints(const struct dest_constraint
*dcs
, size_t ndcs
)
284 struct dest_constraint
*ret
;
288 ret
= xcalloc(ndcs
, sizeof(*ret
));
289 for (i
= 0; i
< ndcs
; i
++) {
290 dup_dest_constraint_hop(&dcs
[i
].from
, &ret
[i
].from
);
291 dup_dest_constraint_hop(&dcs
[i
].to
, &ret
[i
].to
);
295 #endif /* ENABLE_PKCS11 */
297 #ifdef DEBUG_CONSTRAINTS
299 dump_dest_constraint_hop(const struct dest_constraint_hop
*dch
)
304 debug_f("user %s hostname %s is_ca %d nkeys %u",
305 dch
->user
== NULL
? "(null)" : dch
->user
,
306 dch
->hostname
== NULL
? "(null)" : dch
->hostname
,
307 dch
->is_ca
, dch
->nkeys
);
308 for (i
= 0; i
< dch
->nkeys
; i
++) {
310 if (dch
->keys
[i
] != NULL
&&
311 (fp
= sshkey_fingerprint(dch
->keys
[i
],
312 SSH_FP_HASH_DEFAULT
, SSH_FP_DEFAULT
)) == NULL
)
313 fatal_f("fingerprint failed");
314 debug_f("key %u/%u: %s%s%s key_is_ca %d", i
, dch
->nkeys
,
315 dch
->keys
[i
] == NULL
? "" : sshkey_ssh_name(dch
->keys
[i
]),
316 dch
->keys
[i
] == NULL
? "" : " ",
317 dch
->keys
[i
] == NULL
? "none" : fp
,
322 #endif /* DEBUG_CONSTRAINTS */
325 dump_dest_constraints(const char *context
,
326 const struct dest_constraint
*dcs
, size_t ndcs
)
328 #ifdef DEBUG_CONSTRAINTS
331 debug_f("%s: %zu constraints", context
, ndcs
);
332 for (i
= 0; i
< ndcs
; i
++) {
333 debug_f("constraint %zu / %zu: from: ", i
, ndcs
);
334 dump_dest_constraint_hop(&dcs
[i
].from
);
335 debug_f("constraint %zu / %zu: to: ", i
, ndcs
);
336 dump_dest_constraint_hop(&dcs
[i
].to
);
338 debug_f("done for %s", context
);
339 #endif /* DEBUG_CONSTRAINTS */
343 free_identity(Identity
*id
)
345 sshkey_free(id
->key
);
348 free(id
->sk_provider
);
349 free_dest_constraints(id
->dest_constraints
, id
->ndest_constraints
);
354 * Match 'key' against the key/CA list in a destination constraint hop
355 * Returns 0 on success or -1 otherwise.
358 match_key_hop(const char *tag
, const struct sshkey
*key
,
359 const struct dest_constraint_hop
*dch
)
361 const char *reason
= NULL
;
362 const char *hostname
= dch
->hostname
? dch
->hostname
: "(ORIGIN)";
369 if ((fp
= sshkey_fingerprint(key
, SSH_FP_HASH_DEFAULT
,
370 SSH_FP_DEFAULT
)) == NULL
)
371 fatal_f("fingerprint failed");
372 debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
373 tag
, hostname
, sshkey_type(key
), fp
, dch
->nkeys
);
375 for (i
= 0; i
< dch
->nkeys
; i
++) {
376 if (dch
->keys
[i
] == NULL
)
379 if ((fp
= sshkey_fingerprint(dch
->keys
[i
], SSH_FP_HASH_DEFAULT
,
380 SSH_FP_DEFAULT
)) == NULL
)
381 fatal_f("fingerprint failed");
382 debug3_f("%s: key %u: %s%s %s", tag
, i
,
383 dch
->key_is_ca
[i
] ? "CA " : "",
384 sshkey_type(dch
->keys
[i
]), fp
);
386 if (!sshkey_is_cert(key
)) {
388 if (dch
->key_is_ca
[i
] ||
389 !sshkey_equal(key
, dch
->keys
[i
]))
394 if (!dch
->key_is_ca
[i
])
396 if (key
->cert
== NULL
|| key
->cert
->signature_key
== NULL
)
397 return -1; /* shouldn't happen */
398 if (!sshkey_equal(key
->cert
->signature_key
, dch
->keys
[i
]))
400 if (sshkey_cert_check_host(key
, hostname
, 1,
401 SSH_ALLOWED_CA_SIGALGS
, &reason
) != 0) {
402 debug_f("cert %s / hostname %s rejected: %s",
403 key
->cert
->key_id
, hostname
, reason
);
411 /* Check destination constraints on an identity against the hostkey/user */
413 permitted_by_dest_constraints(const struct sshkey
*fromkey
,
414 const struct sshkey
*tokey
, Identity
*id
, const char *user
,
415 const char **hostnamep
)
418 struct dest_constraint
*d
;
420 if (hostnamep
!= NULL
)
422 for (i
= 0; i
< id
->ndest_constraints
; i
++) {
423 d
= id
->dest_constraints
+ i
;
424 /* XXX remove logspam */
425 debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
426 i
, d
->from
.user
? d
->from
.user
: "",
427 d
->from
.user
? "@" : "",
428 d
->from
.hostname
? d
->from
.hostname
: "(ORIGIN)",
430 d
->to
.user
? d
->to
.user
: "", d
->to
.user
? "@" : "",
431 d
->to
.hostname
? d
->to
.hostname
: "(ANY)", d
->to
.nkeys
);
433 /* Match 'from' key */
434 if (fromkey
== NULL
) {
435 /* We are matching the first hop */
436 if (d
->from
.hostname
!= NULL
|| d
->from
.nkeys
!= 0)
438 } else if (match_key_hop("from", fromkey
, &d
->from
) != 0)
442 if (tokey
!= NULL
&& match_key_hop("to", tokey
, &d
->to
) != 0)
445 /* Match user if specified */
446 if (d
->to
.user
!= NULL
&& user
!= NULL
&&
447 !match_pattern(user
, d
->to
.user
))
450 /* successfully matched this constraint */
451 if (hostnamep
!= NULL
)
452 *hostnamep
= d
->to
.hostname
;
453 debug2_f("allowed for hostname %s",
454 d
->to
.hostname
== NULL
? "*" : d
->to
.hostname
);
458 debug2_f("%s identity \"%s\" not permitted for this destination",
459 sshkey_type(id
->key
), id
->comment
);
464 * Check whether hostkeys on a SocketEntry and the optionally specified user
465 * are permitted by the destination constraints on the Identity.
466 * Returns 0 on success or -1 otherwise.
469 identity_permitted(Identity
*id
, SocketEntry
*e
, char *user
,
470 const char **forward_hostnamep
, const char **last_hostnamep
)
474 struct hostkey_sid
*hks
;
475 const struct sshkey
*fromkey
= NULL
;
476 const char *test_user
;
479 /* XXX remove logspam */
480 debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
481 "%zu constraints", sshkey_type(id
->key
), id
->comment
,
482 e
->nsession_ids
, id
->ndest_constraints
);
483 if (id
->ndest_constraints
== 0)
484 return 0; /* unconstrained */
485 if (e
->session_bind_attempted
&& e
->nsession_ids
== 0) {
486 error_f("previous session bind failed on socket");
489 if (e
->nsession_ids
== 0)
490 return 0; /* local use */
492 * Walk through the hops recorded by session_id and try to find a
493 * constraint that satisfies each.
495 for (i
= 0; i
< e
->nsession_ids
; i
++) {
496 hks
= e
->session_ids
+ i
;
497 if (hks
->key
== NULL
)
498 fatal_f("internal error: no bound key");
499 /* XXX remove logspam */
501 if (fromkey
!= NULL
&&
502 (fp1
= sshkey_fingerprint(fromkey
, SSH_FP_HASH_DEFAULT
,
503 SSH_FP_DEFAULT
)) == NULL
)
504 fatal_f("fingerprint failed");
505 if ((fp2
= sshkey_fingerprint(hks
->key
, SSH_FP_HASH_DEFAULT
,
506 SSH_FP_DEFAULT
)) == NULL
)
507 fatal_f("fingerprint failed");
508 debug3_f("socketentry fd=%d, entry %zu %s, "
509 "from hostkey %s %s to user %s hostkey %s %s",
510 e
->fd
, i
, hks
->forwarded
? "FORWARD" : "AUTH",
511 fromkey
? sshkey_type(fromkey
) : "(ORIGIN)",
512 fromkey
? fp1
: "", user
? user
: "(ANY)",
513 sshkey_type(hks
->key
), fp2
);
517 * Record the hostnames for the initial forwarding and
518 * the final destination.
521 if (i
== e
->nsession_ids
- 1)
524 hp
= forward_hostnamep
;
525 /* Special handling for final recorded binding */
527 if (i
== e
->nsession_ids
- 1) {
528 /* Can only check user at final hop */
531 * user is only presented for signature requests.
532 * If this is the case, make sure last binding is not
535 if (hks
->forwarded
&& user
!= NULL
) {
536 error_f("tried to sign on forwarding hop");
539 } else if (!hks
->forwarded
) {
540 error_f("tried to forward though signing bind");
543 if (permitted_by_dest_constraints(fromkey
, hks
->key
, id
,
549 * Another special case: if the last bound session ID was for a
550 * forwarding, and this function is not being called to check a sign
551 * request (i.e. no 'user' supplied), then only permit the key if
552 * there is a permission that would allow it to be used at another
553 * destination. This hides keys that are allowed to be used to
554 * authenticate *to* a host but not permitted for *use* beyond it.
556 hks
= &e
->session_ids
[e
->nsession_ids
- 1];
557 if (hks
->forwarded
&& user
== NULL
&&
558 permitted_by_dest_constraints(hks
->key
, NULL
, id
,
560 debug3_f("key permitted at host but not after");
569 socket_is_remote(SocketEntry
*e
)
571 return e
->session_bind_attempted
|| (e
->nsession_ids
!= 0);
574 /* return matching private key for given public key */
576 lookup_identity(struct sshkey
*key
)
580 TAILQ_FOREACH(id
, &idtab
->idlist
, next
) {
581 if (sshkey_equal(key
, id
->key
))
587 /* Check confirmation of keysign request */
589 confirm_key(Identity
*id
, const char *extra
)
594 p
= sshkey_fingerprint(id
->key
, fingerprint_hash
, SSH_FP_DEFAULT
);
596 ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
598 extra
== NULL
? "" : "\n", extra
== NULL
? "" : extra
))
606 send_status(SocketEntry
*e
, int success
)
610 if ((r
= sshbuf_put_u32(e
->output
, 1)) != 0 ||
611 (r
= sshbuf_put_u8(e
->output
, success
?
612 SSH_AGENT_SUCCESS
: SSH_AGENT_FAILURE
)) != 0)
613 fatal_fr(r
, "compose");
616 /* send list of supported public keys to 'client' */
618 process_request_identities(SocketEntry
*e
)
621 struct sshbuf
*msg
, *keys
;
623 u_int i
= 0, nentries
= 0;
626 debug2_f("entering");
628 if ((msg
= sshbuf_new()) == NULL
|| (keys
= sshbuf_new()) == NULL
)
629 fatal_f("sshbuf_new failed");
630 TAILQ_FOREACH(id
, &idtab
->idlist
, next
) {
631 if ((fp
= sshkey_fingerprint(id
->key
, SSH_FP_HASH_DEFAULT
,
632 SSH_FP_DEFAULT
)) == NULL
)
633 fatal_f("fingerprint failed");
634 debug_f("key %u / %u: %s %s", i
++, idtab
->nentries
,
635 sshkey_ssh_name(id
->key
), fp
);
636 dump_dest_constraints(__func__
,
637 id
->dest_constraints
, id
->ndest_constraints
);
639 /* identity not visible, don't include in response */
640 if (identity_permitted(id
, e
, NULL
, NULL
, NULL
) != 0)
642 if ((r
= sshkey_puts_opts(id
->key
, keys
,
643 SSHKEY_SERIALIZE_INFO
)) != 0 ||
644 (r
= sshbuf_put_cstring(keys
, id
->comment
)) != 0) {
645 error_fr(r
, "compose key/comment");
650 debug2_f("replying with %u allowed of %u available keys",
651 nentries
, idtab
->nentries
);
652 if ((r
= sshbuf_put_u8(msg
, SSH2_AGENT_IDENTITIES_ANSWER
)) != 0 ||
653 (r
= sshbuf_put_u32(msg
, nentries
)) != 0 ||
654 (r
= sshbuf_putb(msg
, keys
)) != 0)
655 fatal_fr(r
, "compose");
656 if ((r
= sshbuf_put_stringb(e
->output
, msg
)) != 0)
657 fatal_fr(r
, "enqueue");
664 agent_decode_alg(struct sshkey
*key
, u_int flags
)
666 if (key
->type
== KEY_RSA
) {
667 if (flags
& SSH_AGENT_RSA_SHA2_256
)
668 return "rsa-sha2-256";
669 else if (flags
& SSH_AGENT_RSA_SHA2_512
)
670 return "rsa-sha2-512";
671 } else if (key
->type
== KEY_RSA_CERT
) {
672 if (flags
& SSH_AGENT_RSA_SHA2_256
)
673 return "rsa-sha2-256-cert-v01@openssh.com";
674 else if (flags
& SSH_AGENT_RSA_SHA2_512
)
675 return "rsa-sha2-512-cert-v01@openssh.com";
681 * Attempt to parse the contents of a buffer as a SSH publickey userauth
682 * request, checking its contents for consistency and matching the embedded
683 * key against the one that is being used for signing.
684 * Note: does not modify msg buffer.
685 * Optionally extract the username, session ID and/or hostkey from the request.
688 parse_userauth_request(struct sshbuf
*msg
, const struct sshkey
*expected_key
,
689 char **userp
, struct sshbuf
**sess_idp
, struct sshkey
**hostkeyp
)
691 struct sshbuf
*b
= NULL
, *sess_id
= NULL
;
692 char *user
= NULL
, *service
= NULL
, *method
= NULL
, *pkalg
= NULL
;
694 u_char t
, sig_follows
;
695 struct sshkey
*mkey
= NULL
, *hostkey
= NULL
;
699 if (sess_idp
!= NULL
)
701 if (hostkeyp
!= NULL
)
703 if ((b
= sshbuf_fromb(msg
)) == NULL
)
704 fatal_f("sshbuf_fromb");
706 /* SSH userauth request */
707 if ((r
= sshbuf_froms(b
, &sess_id
)) != 0)
709 if (sshbuf_len(sess_id
) == 0) {
710 r
= SSH_ERR_INVALID_FORMAT
;
713 if ((r
= sshbuf_get_u8(b
, &t
)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
714 (r
= sshbuf_get_cstring(b
, &user
, NULL
)) != 0 || /* server user */
715 (r
= sshbuf_get_cstring(b
, &service
, NULL
)) != 0 || /* service */
716 (r
= sshbuf_get_cstring(b
, &method
, NULL
)) != 0 || /* method */
717 (r
= sshbuf_get_u8(b
, &sig_follows
)) != 0 || /* sig-follows */
718 (r
= sshbuf_get_cstring(b
, &pkalg
, NULL
)) != 0 || /* alg */
719 (r
= sshkey_froms(b
, &mkey
)) != 0) /* key */
721 if (t
!= SSH2_MSG_USERAUTH_REQUEST
||
723 strcmp(service
, "ssh-connection") != 0 ||
724 !sshkey_equal(expected_key
, mkey
) ||
725 sshkey_type_from_name(pkalg
) != expected_key
->type
) {
726 r
= SSH_ERR_INVALID_FORMAT
;
729 if (strcmp(method
, "publickey-hostbound-v00@openssh.com") == 0) {
730 if ((r
= sshkey_froms(b
, &hostkey
)) != 0)
732 } else if (strcmp(method
, "publickey") != 0) {
733 r
= SSH_ERR_INVALID_FORMAT
;
736 if (sshbuf_len(b
) != 0) {
737 r
= SSH_ERR_INVALID_FORMAT
;
742 debug3_f("well formed userauth");
747 if (sess_idp
!= NULL
) {
751 if (hostkeyp
!= NULL
) {
757 sshbuf_free(sess_id
);
763 sshkey_free(hostkey
);
768 * Attempt to parse the contents of a buffer as a SSHSIG signature request.
769 * Note: does not modify buffer.
772 parse_sshsig_request(struct sshbuf
*msg
)
777 if ((b
= sshbuf_fromb(msg
)) == NULL
)
778 fatal_f("sshbuf_fromb");
780 if ((r
= sshbuf_cmp(b
, 0, "SSHSIG", 6)) != 0 ||
781 (r
= sshbuf_consume(b
, 6)) != 0 ||
782 (r
= sshbuf_get_cstring(b
, NULL
, NULL
)) != 0 || /* namespace */
783 (r
= sshbuf_get_string_direct(b
, NULL
, NULL
)) != 0 || /* reserved */
784 (r
= sshbuf_get_cstring(b
, NULL
, NULL
)) != 0 || /* hashalg */
785 (r
= sshbuf_get_string_direct(b
, NULL
, NULL
)) != 0) /* H(msg) */
787 if (sshbuf_len(b
) != 0) {
788 r
= SSH_ERR_INVALID_FORMAT
;
799 * This function inspects a message to be signed by a FIDO key that has a
800 * web-like application string (i.e. one that does not begin with "ssh:".
801 * It checks that the message is one of those expected for SSH operations
802 * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
806 check_websafe_message_contents(struct sshkey
*key
, struct sshbuf
*data
)
808 if (parse_userauth_request(data
, key
, NULL
, NULL
, NULL
) == 0) {
809 debug_f("signed data matches public key userauth request");
812 if (parse_sshsig_request(data
) == 0) {
813 debug_f("signed data matches SSHSIG signature request");
817 /* XXX check CA signature operation */
819 error("web-origin key attempting to sign non-SSH message");
824 buf_equal(const struct sshbuf
*a
, const struct sshbuf
*b
)
826 if (sshbuf_ptr(a
) == NULL
|| sshbuf_ptr(b
) == NULL
)
827 return SSH_ERR_INVALID_ARGUMENT
;
828 if (sshbuf_len(a
) != sshbuf_len(b
))
829 return SSH_ERR_INVALID_FORMAT
;
830 if (timingsafe_bcmp(sshbuf_ptr(a
), sshbuf_ptr(b
), sshbuf_len(a
)) != 0)
831 return SSH_ERR_INVALID_FORMAT
;
837 process_sign_request2(SocketEntry
*e
)
839 u_char
*signature
= NULL
;
841 u_int compat
= 0, flags
;
842 int r
, ok
= -1, retried
= 0;
843 char *fp
= NULL
, *pin
= NULL
, *prompt
= NULL
;
844 char *user
= NULL
, *sig_dest
= NULL
;
845 const char *fwd_host
= NULL
, *dest_host
= NULL
;
846 struct sshbuf
*msg
= NULL
, *data
= NULL
, *sid
= NULL
;
847 struct sshkey
*key
= NULL
, *hostkey
= NULL
;
849 struct notifier_ctx
*notifier
= NULL
;
853 if ((msg
= sshbuf_new()) == NULL
|| (data
= sshbuf_new()) == NULL
)
854 fatal_f("sshbuf_new failed");
855 if ((r
= sshkey_froms(e
->request
, &key
)) != 0 ||
856 (r
= sshbuf_get_stringb(e
->request
, data
)) != 0 ||
857 (r
= sshbuf_get_u32(e
->request
, &flags
)) != 0) {
858 error_fr(r
, "parse");
862 if ((id
= lookup_identity(key
)) == NULL
) {
863 verbose_f("%s key not found", sshkey_type(key
));
866 if ((fp
= sshkey_fingerprint(key
, SSH_FP_HASH_DEFAULT
,
867 SSH_FP_DEFAULT
)) == NULL
)
868 fatal_f("fingerprint failed");
870 if (id
->ndest_constraints
!= 0) {
871 if (e
->nsession_ids
== 0) {
872 logit_f("refusing use of destination-constrained key "
873 "to sign on unbound connection");
876 if (parse_userauth_request(data
, key
, &user
, &sid
,
878 logit_f("refusing use of destination-constrained key "
879 "to sign an unidentified signature");
883 debug_f("user=%s", user
);
884 if (identity_permitted(id
, e
, user
, &fwd_host
, &dest_host
) != 0)
886 /* XXX display fwd_host/dest_host in askpass UI */
888 * Ensure that the session ID is the most recent one
889 * registered on the socket - it should have been bound by
890 * ssh immediately before userauth.
893 e
->session_ids
[e
->nsession_ids
- 1].sid
) != 0) {
894 error_f("unexpected session ID (%zu listed) on "
895 "signature request for target user %s with "
896 "key %s %s", e
->nsession_ids
, user
,
897 sshkey_type(id
->key
), fp
);
901 * Ensure that the hostkey embedded in the signature matches
902 * the one most recently bound to the socket. An exception is
903 * made for the initial forwarding hop.
905 if (e
->nsession_ids
> 1 && hostkey
== NULL
) {
906 error_f("refusing use of destination-constrained key: "
907 "no hostkey recorded in signature for forwarded "
911 if (hostkey
!= NULL
&& !sshkey_equal(hostkey
,
912 e
->session_ids
[e
->nsession_ids
- 1].key
)) {
913 error_f("refusing use of destination-constrained key: "
914 "mismatch between hostkey in request and most "
915 "recently bound session");
918 xasprintf(&sig_dest
, "public key authentication request for "
919 "user \"%s\" to listed host", user
);
921 if (id
->confirm
&& confirm_key(id
, sig_dest
) != 0) {
922 verbose_f("user refused key");
925 if (sshkey_is_sk(id
->key
)) {
926 if (restrict_websafe
&&
927 strncmp(id
->key
->sk_application
, "ssh:", 4) != 0 &&
928 !check_websafe_message_contents(key
, data
)) {
929 /* error already logged */
932 if (id
->key
->sk_flags
& SSH_SK_USER_PRESENCE_REQD
) {
933 notifier
= notify_start(0,
934 "Confirm user presence for key %s %s%s%s",
935 sshkey_type(id
->key
), fp
,
936 sig_dest
== NULL
? "" : "\n",
937 sig_dest
== NULL
? "" : sig_dest
);
941 if ((r
= sshkey_sign(id
->key
, &signature
, &slen
,
942 sshbuf_ptr(data
), sshbuf_len(data
), agent_decode_alg(key
, flags
),
943 id
->sk_provider
, pin
, compat
)) != 0) {
944 debug_fr(r
, "sshkey_sign");
945 if (pin
== NULL
&& !retried
&& sshkey_is_sk(id
->key
) &&
946 r
== SSH_ERR_KEY_WRONG_PASSPHRASE
) {
947 notify_complete(notifier
, NULL
);
949 /* XXX include sig_dest */
950 xasprintf(&prompt
, "Enter PIN%sfor %s key %s: ",
951 (id
->key
->sk_flags
& SSH_SK_USER_PRESENCE_REQD
) ?
952 " and confirm user presence " : " ",
953 sshkey_type(id
->key
), fp
);
954 pin
= read_passphrase(prompt
, RP_USE_ASKPASS
);
958 error_fr(r
, "sshkey_sign");
963 debug_f("good signature");
965 notify_complete(notifier
, "User presence confirmed");
968 if ((r
= sshbuf_put_u8(msg
, SSH2_AGENT_SIGN_RESPONSE
)) != 0 ||
969 (r
= sshbuf_put_string(msg
, signature
, slen
)) != 0)
970 fatal_fr(r
, "compose");
971 } else if ((r
= sshbuf_put_u8(msg
, SSH_AGENT_FAILURE
)) != 0)
972 fatal_fr(r
, "compose failure");
974 if ((r
= sshbuf_put_stringb(e
->output
, msg
)) != 0)
975 fatal_fr(r
, "enqueue");
981 sshkey_free(hostkey
);
988 freezero(pin
, strlen(pin
));
993 process_remove_identity(SocketEntry
*e
)
996 struct sshkey
*key
= NULL
;
999 debug2_f("entering");
1000 if ((r
= sshkey_froms(e
->request
, &key
)) != 0) {
1001 error_fr(r
, "parse key");
1004 if ((id
= lookup_identity(key
)) == NULL
) {
1005 debug_f("key not found");
1008 /* identity not visible, cannot be removed */
1009 if (identity_permitted(id
, e
, NULL
, NULL
, NULL
) != 0)
1010 goto done
; /* error already logged */
1011 /* We have this key, free it. */
1012 if (idtab
->nentries
< 1)
1013 fatal_f("internal error: nentries %d", idtab
->nentries
);
1014 TAILQ_REMOVE(&idtab
->idlist
, id
, next
);
1020 send_status(e
, success
);
1024 process_remove_all_identities(SocketEntry
*e
)
1028 debug2_f("entering");
1029 /* Loop over all identities and clear the keys. */
1030 for (id
= TAILQ_FIRST(&idtab
->idlist
); id
;
1031 id
= TAILQ_FIRST(&idtab
->idlist
)) {
1032 TAILQ_REMOVE(&idtab
->idlist
, id
, next
);
1036 /* Mark that there are no identities. */
1037 idtab
->nentries
= 0;
1043 /* removes expired keys and returns number of seconds until the next expiry */
1047 time_t deadline
= 0, now
= monotime();
1050 for (id
= TAILQ_FIRST(&idtab
->idlist
); id
; id
= nxt
) {
1051 nxt
= TAILQ_NEXT(id
, next
);
1054 if (now
>= id
->death
) {
1055 debug("expiring key '%s'", id
->comment
);
1056 TAILQ_REMOVE(&idtab
->idlist
, id
, next
);
1060 deadline
= (deadline
== 0) ? id
->death
:
1061 MINIMUM(deadline
, id
->death
);
1063 if (deadline
== 0 || deadline
<= now
)
1066 return (deadline
- now
);
1070 parse_dest_constraint_hop(struct sshbuf
*b
, struct dest_constraint_hop
*dch
)
1075 struct sshkey
*k
= NULL
;
1078 memset(dch
, '\0', sizeof(*dch
));
1079 if ((r
= sshbuf_get_cstring(b
, &dch
->user
, NULL
)) != 0 ||
1080 (r
= sshbuf_get_cstring(b
, &dch
->hostname
, NULL
)) != 0 ||
1081 (r
= sshbuf_get_string_direct(b
, NULL
, &elen
)) != 0) {
1082 error_fr(r
, "parse");
1086 error_f("unsupported extensions (len %zu)", elen
);
1087 r
= SSH_ERR_FEATURE_UNSUPPORTED
;
1090 if (*dch
->hostname
== '\0') {
1091 free(dch
->hostname
);
1092 dch
->hostname
= NULL
;
1094 if (*dch
->user
== '\0') {
1098 while (sshbuf_len(b
) != 0) {
1099 dch
->keys
= xrecallocarray(dch
->keys
, dch
->nkeys
,
1100 dch
->nkeys
+ 1, sizeof(*dch
->keys
));
1101 dch
->key_is_ca
= xrecallocarray(dch
->key_is_ca
, dch
->nkeys
,
1102 dch
->nkeys
+ 1, sizeof(*dch
->key_is_ca
));
1103 if ((r
= sshkey_froms(b
, &k
)) != 0 ||
1104 (r
= sshbuf_get_u8(b
, &key_is_ca
)) != 0)
1106 if ((fp
= sshkey_fingerprint(k
, SSH_FP_HASH_DEFAULT
,
1107 SSH_FP_DEFAULT
)) == NULL
)
1108 fatal_f("fingerprint failed");
1109 debug3_f("%s%s%s: adding %skey %s %s",
1110 dch
->user
== NULL
? "" : dch
->user
,
1111 dch
->user
== NULL
? "" : "@",
1112 dch
->hostname
, key_is_ca
? "CA " : "", sshkey_type(k
), fp
);
1114 dch
->keys
[dch
->nkeys
] = k
;
1115 dch
->key_is_ca
[dch
->nkeys
] = key_is_ca
!= 0;
1117 k
= NULL
; /* transferred */
1127 parse_dest_constraint(struct sshbuf
*m
, struct dest_constraint
*dc
)
1129 struct sshbuf
*b
= NULL
, *frombuf
= NULL
, *tobuf
= NULL
;
1133 debug3_f("entering");
1135 memset(dc
, '\0', sizeof(*dc
));
1136 if ((r
= sshbuf_froms(m
, &b
)) != 0 ||
1137 (r
= sshbuf_froms(b
, &frombuf
)) != 0 ||
1138 (r
= sshbuf_froms(b
, &tobuf
)) != 0 ||
1139 (r
= sshbuf_get_string_direct(b
, NULL
, &elen
)) != 0) {
1140 error_fr(r
, "parse");
1143 if ((r
= parse_dest_constraint_hop(frombuf
, &dc
->from
)) != 0 ||
1144 (r
= parse_dest_constraint_hop(tobuf
, &dc
->to
)) != 0)
1145 goto out
; /* already logged */
1147 error_f("unsupported extensions (len %zu)", elen
);
1148 r
= SSH_ERR_FEATURE_UNSUPPORTED
;
1151 debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
1152 dc
->from
.hostname
? dc
->from
.hostname
: "(ORIGIN)", dc
->from
.nkeys
,
1153 dc
->to
.user
? dc
->to
.user
: "", dc
->to
.user
? "@" : "",
1154 dc
->to
.hostname
? dc
->to
.hostname
: "(ANY)", dc
->to
.nkeys
);
1155 /* check consistency */
1156 if ((dc
->from
.hostname
== NULL
) != (dc
->from
.nkeys
== 0) ||
1157 dc
->from
.user
!= NULL
) {
1158 error_f("inconsistent \"from\" specification");
1159 r
= SSH_ERR_INVALID_FORMAT
;
1162 if (dc
->to
.hostname
== NULL
|| dc
->to
.nkeys
== 0) {
1163 error_f("incomplete \"to\" specification");
1164 r
= SSH_ERR_INVALID_FORMAT
;
1171 sshbuf_free(frombuf
);
1177 parse_key_constraint_extension(struct sshbuf
*m
, char **sk_providerp
,
1178 struct dest_constraint
**dcsp
, size_t *ndcsp
, int *cert_onlyp
,
1179 struct sshkey
***certs
, size_t *ncerts
)
1181 char *ext_name
= NULL
;
1183 struct sshbuf
*b
= NULL
;
1187 if ((r
= sshbuf_get_cstring(m
, &ext_name
, NULL
)) != 0) {
1188 error_fr(r
, "parse constraint extension");
1191 debug_f("constraint ext %s", ext_name
);
1192 if (strcmp(ext_name
, "sk-provider@openssh.com") == 0) {
1193 if (sk_providerp
== NULL
) {
1194 error_f("%s not valid here", ext_name
);
1195 r
= SSH_ERR_INVALID_FORMAT
;
1198 if (*sk_providerp
!= NULL
) {
1199 error_f("%s already set", ext_name
);
1200 r
= SSH_ERR_INVALID_FORMAT
;
1203 if ((r
= sshbuf_get_cstring(m
, sk_providerp
, NULL
)) != 0) {
1204 error_fr(r
, "parse %s", ext_name
);
1207 } else if (strcmp(ext_name
,
1208 "restrict-destination-v00@openssh.com") == 0) {
1209 if (*dcsp
!= NULL
) {
1210 error_f("%s already set", ext_name
);
1213 if ((r
= sshbuf_froms(m
, &b
)) != 0) {
1214 error_fr(r
, "parse %s outer", ext_name
);
1217 while (sshbuf_len(b
) != 0) {
1218 if (*ndcsp
>= AGENT_MAX_DEST_CONSTRAINTS
) {
1219 error_f("too many %s constraints", ext_name
);
1222 *dcsp
= xrecallocarray(*dcsp
, *ndcsp
, *ndcsp
+ 1,
1224 if ((r
= parse_dest_constraint(b
,
1225 *dcsp
+ (*ndcsp
)++)) != 0)
1226 goto out
; /* error already logged */
1228 } else if (strcmp(ext_name
,
1229 "associated-certs-v00@openssh.com") == 0) {
1230 if (certs
== NULL
|| ncerts
== NULL
|| cert_onlyp
== NULL
) {
1231 error_f("%s not valid here", ext_name
);
1232 r
= SSH_ERR_INVALID_FORMAT
;
1235 if (*certs
!= NULL
) {
1236 error_f("%s already set", ext_name
);
1239 if ((r
= sshbuf_get_u8(m
, &v
)) != 0 ||
1240 (r
= sshbuf_froms(m
, &b
)) != 0) {
1241 error_fr(r
, "parse %s", ext_name
);
1244 *cert_onlyp
= v
!= 0;
1245 while (sshbuf_len(b
) != 0) {
1246 if (*ncerts
>= AGENT_MAX_EXT_CERTS
) {
1247 error_f("too many %s constraints", ext_name
);
1250 *certs
= xrecallocarray(*certs
, *ncerts
, *ncerts
+ 1,
1252 if ((r
= sshkey_froms(b
, &k
)) != 0) {
1253 error_fr(r
, "parse key");
1256 (*certs
)[(*ncerts
)++] = k
;
1259 error_f("unsupported constraint \"%s\"", ext_name
);
1260 r
= SSH_ERR_FEATURE_UNSUPPORTED
;
1272 parse_key_constraints(struct sshbuf
*m
, struct sshkey
*k
, time_t *deathp
,
1273 u_int
*secondsp
, int *confirmp
, char **sk_providerp
,
1274 struct dest_constraint
**dcsp
, size_t *ndcsp
,
1275 int *cert_onlyp
, size_t *ncerts
, struct sshkey
***certs
)
1279 u_int seconds
, maxsign
= 0;
1281 while (sshbuf_len(m
)) {
1282 if ((r
= sshbuf_get_u8(m
, &ctype
)) != 0) {
1283 error_fr(r
, "parse constraint type");
1287 case SSH_AGENT_CONSTRAIN_LIFETIME
:
1289 error_f("lifetime already set");
1290 r
= SSH_ERR_INVALID_FORMAT
;
1293 if ((r
= sshbuf_get_u32(m
, &seconds
)) != 0) {
1294 error_fr(r
, "parse lifetime constraint");
1297 *deathp
= monotime() + seconds
;
1298 *secondsp
= seconds
;
1300 case SSH_AGENT_CONSTRAIN_CONFIRM
:
1301 if (*confirmp
!= 0) {
1302 error_f("confirm already set");
1303 r
= SSH_ERR_INVALID_FORMAT
;
1308 case SSH_AGENT_CONSTRAIN_MAXSIGN
:
1310 error_f("maxsign not valid here");
1311 r
= SSH_ERR_INVALID_FORMAT
;
1315 error_f("maxsign already set");
1316 r
= SSH_ERR_INVALID_FORMAT
;
1319 if ((r
= sshbuf_get_u32(m
, &maxsign
)) != 0) {
1320 error_fr(r
, "parse maxsign constraint");
1323 if ((r
= sshkey_enable_maxsign(k
, maxsign
)) != 0) {
1324 error_fr(r
, "enable maxsign");
1328 case SSH_AGENT_CONSTRAIN_EXTENSION
:
1329 if ((r
= parse_key_constraint_extension(m
,
1330 sk_providerp
, dcsp
, ndcsp
,
1331 cert_onlyp
, certs
, ncerts
)) != 0)
1332 goto out
; /* error already logged */
1335 error_f("Unknown constraint %d", ctype
);
1336 r
= SSH_ERR_FEATURE_UNSUPPORTED
;
1347 process_add_identity(SocketEntry
*e
)
1350 int success
= 0, confirm
= 0;
1351 char *fp
, *comment
= NULL
, *sk_provider
= NULL
;
1352 char canonical_provider
[PATH_MAX
];
1355 struct dest_constraint
*dest_constraints
= NULL
;
1356 size_t ndest_constraints
= 0;
1357 struct sshkey
*k
= NULL
;
1358 int r
= SSH_ERR_INTERNAL_ERROR
;
1360 debug2_f("entering");
1361 if ((r
= sshkey_private_deserialize(e
->request
, &k
)) != 0 ||
1363 (r
= sshbuf_get_cstring(e
->request
, &comment
, NULL
)) != 0) {
1364 error_fr(r
, "parse");
1367 if (parse_key_constraints(e
->request
, k
, &death
, &seconds
, &confirm
,
1368 &sk_provider
, &dest_constraints
, &ndest_constraints
,
1369 NULL
, NULL
, NULL
) != 0) {
1370 error_f("failed to parse constraints");
1371 sshbuf_reset(e
->request
);
1374 dump_dest_constraints(__func__
, dest_constraints
, ndest_constraints
);
1376 if (sk_provider
!= NULL
) {
1377 if (!sshkey_is_sk(k
)) {
1378 error("Cannot add provider: %s is not an "
1379 "authenticator-hosted key", sshkey_type(k
));
1382 if (strcasecmp(sk_provider
, "internal") == 0) {
1383 debug_f("internal provider");
1385 if (socket_is_remote(e
) && !remote_add_provider
) {
1386 verbose("failed add of SK provider \"%.100s\": "
1387 "remote addition of providers is disabled",
1391 if (realpath(sk_provider
, canonical_provider
) == NULL
) {
1392 verbose("failed provider \"%.100s\": "
1393 "realpath: %s", sk_provider
,
1398 sk_provider
= xstrdup(canonical_provider
);
1399 if (match_pattern_list(sk_provider
,
1400 allowed_providers
, 0) != 1) {
1401 error("Refusing add key: "
1402 "provider %s not allowed", sk_provider
);
1407 if ((r
= sshkey_shield_private(k
)) != 0) {
1408 error_fr(r
, "shield private");
1411 if (lifetime
&& !death
)
1412 death
= monotime() + lifetime
;
1413 if ((id
= lookup_identity(k
)) == NULL
) {
1414 id
= xcalloc(1, sizeof(Identity
));
1415 TAILQ_INSERT_TAIL(&idtab
->idlist
, id
, next
);
1416 /* Increment the number of identities. */
1419 /* identity not visible, do not update */
1420 if (identity_permitted(id
, e
, NULL
, NULL
, NULL
) != 0)
1421 goto out
; /* error already logged */
1422 /* key state might have been updated */
1423 sshkey_free(id
->key
);
1425 free(id
->sk_provider
);
1426 free_dest_constraints(id
->dest_constraints
,
1427 id
->ndest_constraints
);
1431 id
->comment
= comment
;
1433 id
->confirm
= confirm
;
1434 id
->sk_provider
= sk_provider
;
1435 id
->dest_constraints
= dest_constraints
;
1436 id
->ndest_constraints
= ndest_constraints
;
1438 if ((fp
= sshkey_fingerprint(k
, SSH_FP_HASH_DEFAULT
,
1439 SSH_FP_DEFAULT
)) == NULL
)
1440 fatal_f("sshkey_fingerprint failed");
1441 debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
1442 "(provider: %s) (destination constraints: %zu)",
1443 sshkey_ssh_name(k
), fp
, comment
, seconds
, confirm
,
1444 sk_provider
== NULL
? "none" : sk_provider
, ndest_constraints
);
1450 dest_constraints
= NULL
;
1451 ndest_constraints
= 0;
1457 free_dest_constraints(dest_constraints
, ndest_constraints
);
1458 send_status(e
, success
);
1461 /* XXX todo: encrypt sensitive data with passphrase */
1463 process_lock_agent(SocketEntry
*e
, int lock
)
1465 int r
, success
= 0, delay
;
1467 u_char passwdhash
[LOCK_SIZE
];
1468 static u_int fail_count
= 0;
1471 debug2_f("entering");
1473 * This is deliberately fatal: the user has requested that we lock,
1474 * but we can't parse their request properly. The only safe thing to
1477 if ((r
= sshbuf_get_cstring(e
->request
, &passwd
, &pwlen
)) != 0)
1478 fatal_fr(r
, "parse");
1480 debug("empty password not supported");
1481 } else if (locked
&& !lock
) {
1482 if (bcrypt_pbkdf(passwd
, pwlen
, lock_salt
, sizeof(lock_salt
),
1483 passwdhash
, sizeof(passwdhash
), LOCK_ROUNDS
) < 0)
1484 fatal("bcrypt_pbkdf");
1485 if (timingsafe_bcmp(passwdhash
, lock_pwhash
, LOCK_SIZE
) == 0) {
1486 debug("agent unlocked");
1489 explicit_bzero(lock_pwhash
, sizeof(lock_pwhash
));
1492 /* delay in 0.1s increments up to 10s */
1493 if (fail_count
< 100)
1495 delay
= 100000 * fail_count
;
1496 debug("unlock failed, delaying %0.1lf seconds",
1497 (double)delay
/1000000);
1500 explicit_bzero(passwdhash
, sizeof(passwdhash
));
1501 } else if (!locked
&& lock
) {
1502 debug("agent locked");
1504 arc4random_buf(lock_salt
, sizeof(lock_salt
));
1505 if (bcrypt_pbkdf(passwd
, pwlen
, lock_salt
, sizeof(lock_salt
),
1506 lock_pwhash
, sizeof(lock_pwhash
), LOCK_ROUNDS
) < 0)
1507 fatal("bcrypt_pbkdf");
1510 freezero(passwd
, pwlen
);
1511 send_status(e
, success
);
1515 no_identities(SocketEntry
*e
)
1520 if ((msg
= sshbuf_new()) == NULL
)
1521 fatal_f("sshbuf_new failed");
1522 if ((r
= sshbuf_put_u8(msg
, SSH2_AGENT_IDENTITIES_ANSWER
)) != 0 ||
1523 (r
= sshbuf_put_u32(msg
, 0)) != 0 ||
1524 (r
= sshbuf_put_stringb(e
->output
, msg
)) != 0)
1525 fatal_fr(r
, "compose");
1529 #ifdef ENABLE_PKCS11
1530 /* Add an identity to idlist; takes ownership of 'key' and 'comment' */
1532 add_p11_identity(struct sshkey
*key
, char *comment
, const char *provider
,
1533 time_t death
, u_int confirm
, struct dest_constraint
*dest_constraints
,
1534 size_t ndest_constraints
)
1538 if (lookup_identity(key
) != NULL
) {
1543 id
= xcalloc(1, sizeof(Identity
));
1545 id
->comment
= comment
;
1546 id
->provider
= xstrdup(provider
);
1548 id
->confirm
= confirm
;
1549 id
->dest_constraints
= dup_dest_constraints(dest_constraints
,
1551 id
->ndest_constraints
= ndest_constraints
;
1552 TAILQ_INSERT_TAIL(&idtab
->idlist
, id
, next
);
1557 process_add_smartcard_key(SocketEntry
*e
)
1559 char *provider
= NULL
, *pin
= NULL
, canonical_provider
[PATH_MAX
];
1560 char **comments
= NULL
;
1561 int r
, i
, count
= 0, success
= 0, confirm
= 0;
1564 struct sshkey
**keys
= NULL
, *k
;
1565 struct dest_constraint
*dest_constraints
= NULL
;
1566 size_t j
, ndest_constraints
= 0, ncerts
= 0;
1567 struct sshkey
**certs
= NULL
;
1570 debug2_f("entering");
1571 if ((r
= sshbuf_get_cstring(e
->request
, &provider
, NULL
)) != 0 ||
1572 (r
= sshbuf_get_cstring(e
->request
, &pin
, NULL
)) != 0) {
1573 error_fr(r
, "parse");
1576 if (parse_key_constraints(e
->request
, NULL
, &death
, &seconds
, &confirm
,
1577 NULL
, &dest_constraints
, &ndest_constraints
, &cert_only
,
1578 &ncerts
, &certs
) != 0) {
1579 error_f("failed to parse constraints");
1582 dump_dest_constraints(__func__
, dest_constraints
, ndest_constraints
);
1583 if (socket_is_remote(e
) && !remote_add_provider
) {
1584 verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
1585 "providers is disabled", provider
);
1588 if (realpath(provider
, canonical_provider
) == NULL
) {
1589 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1590 provider
, strerror(errno
));
1593 if (match_pattern_list(canonical_provider
, allowed_providers
, 0) != 1) {
1594 verbose("refusing PKCS#11 add of \"%.100s\": "
1595 "provider not allowed", canonical_provider
);
1598 debug_f("add %.100s", canonical_provider
);
1599 if (lifetime
&& !death
)
1600 death
= monotime() + lifetime
;
1602 count
= pkcs11_add_provider(canonical_provider
, pin
, &keys
, &comments
);
1603 for (i
= 0; i
< count
; i
++) {
1604 if (comments
[i
] == NULL
|| comments
[i
][0] == '\0') {
1606 comments
[i
] = xstrdup(canonical_provider
);
1608 for (j
= 0; j
< ncerts
; j
++) {
1609 if (!sshkey_is_cert(certs
[j
]))
1611 if (!sshkey_equal_public(keys
[i
], certs
[j
]))
1613 if (pkcs11_make_cert(keys
[i
], certs
[j
], &k
) != 0)
1615 add_p11_identity(k
, xstrdup(comments
[i
]),
1616 canonical_provider
, death
, confirm
,
1617 dest_constraints
, ndest_constraints
);
1620 if (!cert_only
&& lookup_identity(keys
[i
]) == NULL
) {
1621 add_p11_identity(keys
[i
], comments
[i
],
1622 canonical_provider
, death
, confirm
,
1623 dest_constraints
, ndest_constraints
);
1624 keys
[i
] = NULL
; /* transferred */
1625 comments
[i
] = NULL
; /* transferred */
1628 /* XXX update constraints for existing keys */
1629 sshkey_free(keys
[i
]);
1637 free_dest_constraints(dest_constraints
, ndest_constraints
);
1638 for (j
= 0; j
< ncerts
; j
++)
1639 sshkey_free(certs
[j
]);
1641 send_status(e
, success
);
1645 process_remove_smartcard_key(SocketEntry
*e
)
1647 char *provider
= NULL
, *pin
= NULL
, canonical_provider
[PATH_MAX
];
1651 debug2_f("entering");
1652 if ((r
= sshbuf_get_cstring(e
->request
, &provider
, NULL
)) != 0 ||
1653 (r
= sshbuf_get_cstring(e
->request
, &pin
, NULL
)) != 0) {
1654 error_fr(r
, "parse");
1659 if (realpath(provider
, canonical_provider
) == NULL
) {
1660 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
1661 provider
, strerror(errno
));
1665 debug_f("remove %.100s", canonical_provider
);
1666 for (id
= TAILQ_FIRST(&idtab
->idlist
); id
; id
= nxt
) {
1667 nxt
= TAILQ_NEXT(id
, next
);
1668 /* Skip file--based keys */
1669 if (id
->provider
== NULL
)
1671 if (!strcmp(canonical_provider
, id
->provider
)) {
1672 TAILQ_REMOVE(&idtab
->idlist
, id
, next
);
1677 if (pkcs11_del_provider(canonical_provider
) == 0)
1680 error_f("pkcs11_del_provider failed");
1683 send_status(e
, success
);
1685 #endif /* ENABLE_PKCS11 */
1688 process_ext_session_bind(SocketEntry
*e
)
1690 int r
, sid_match
, key_match
;
1691 struct sshkey
*key
= NULL
;
1692 struct sshbuf
*sid
= NULL
, *sig
= NULL
;
1697 debug2_f("entering");
1698 e
->session_bind_attempted
= 1;
1699 if ((r
= sshkey_froms(e
->request
, &key
)) != 0 ||
1700 (r
= sshbuf_froms(e
->request
, &sid
)) != 0 ||
1701 (r
= sshbuf_froms(e
->request
, &sig
)) != 0 ||
1702 (r
= sshbuf_get_u8(e
->request
, &fwd
)) != 0) {
1703 error_fr(r
, "parse");
1706 if ((fp
= sshkey_fingerprint(key
, SSH_FP_HASH_DEFAULT
,
1707 SSH_FP_DEFAULT
)) == NULL
)
1708 fatal_f("fingerprint failed");
1709 /* check signature with hostkey on session ID */
1710 if ((r
= sshkey_verify(key
, sshbuf_ptr(sig
), sshbuf_len(sig
),
1711 sshbuf_ptr(sid
), sshbuf_len(sid
), NULL
, 0, NULL
)) != 0) {
1712 error_fr(r
, "sshkey_verify for %s %s", sshkey_type(key
), fp
);
1715 /* check whether sid/key already recorded */
1716 for (i
= 0; i
< e
->nsession_ids
; i
++) {
1717 if (!e
->session_ids
[i
].forwarded
) {
1718 error_f("attempt to bind session ID to socket "
1719 "previously bound for authentication attempt");
1723 sid_match
= buf_equal(sid
, e
->session_ids
[i
].sid
) == 0;
1724 key_match
= sshkey_equal(key
, e
->session_ids
[i
].key
);
1725 if (sid_match
&& key_match
) {
1726 debug_f("session ID already recorded for %s %s",
1727 sshkey_type(key
), fp
);
1730 } else if (sid_match
) {
1731 error_f("session ID recorded against different key "
1732 "for %s %s", sshkey_type(key
), fp
);
1737 * new sid with previously-seen key can happen, e.g. multiple
1738 * connections to the same host.
1741 /* record new key/sid */
1742 if (e
->nsession_ids
>= AGENT_MAX_SESSION_IDS
) {
1743 error_f("too many session IDs recorded");
1746 e
->session_ids
= xrecallocarray(e
->session_ids
, e
->nsession_ids
,
1747 e
->nsession_ids
+ 1, sizeof(*e
->session_ids
));
1748 i
= e
->nsession_ids
++;
1749 debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key
), fp
, i
,
1750 AGENT_MAX_SESSION_IDS
);
1751 e
->session_ids
[i
].key
= key
;
1752 e
->session_ids
[i
].forwarded
= fwd
!= 0;
1753 key
= NULL
; /* transferred */
1754 /* can't transfer sid; it's refcounted and scoped to request's life */
1755 if ((e
->session_ids
[i
].sid
= sshbuf_new()) == NULL
)
1756 fatal_f("sshbuf_new");
1757 if ((r
= sshbuf_putb(e
->session_ids
[i
].sid
, sid
)) != 0)
1758 fatal_fr(r
, "sshbuf_putb session ID");
1766 return r
== 0 ? 1 : 0;
1770 process_extension(SocketEntry
*e
)
1775 debug2_f("entering");
1776 if ((r
= sshbuf_get_cstring(e
->request
, &name
, NULL
)) != 0) {
1777 error_fr(r
, "parse");
1780 if (strcmp(name
, "session-bind@openssh.com") == 0)
1781 success
= process_ext_session_bind(e
);
1783 debug_f("unsupported extension \"%s\"", name
);
1786 send_status(e
, success
);
1789 * dispatch incoming message.
1790 * returns 1 on success, 0 for incomplete messages or -1 on error.
1793 process_message(u_int socknum
)
1801 if (socknum
>= sockets_alloc
)
1802 fatal_f("sock %u >= allocated %u", socknum
, sockets_alloc
);
1803 e
= &sockets
[socknum
];
1805 if (sshbuf_len(e
->input
) < 5)
1806 return 0; /* Incomplete message header. */
1807 cp
= sshbuf_ptr(e
->input
);
1808 msg_len
= PEEK_U32(cp
);
1809 if (msg_len
> AGENT_MAX_LEN
) {
1810 debug_f("socket %u (fd=%d) message too long %u > %u",
1811 socknum
, e
->fd
, msg_len
, AGENT_MAX_LEN
);
1814 if (sshbuf_len(e
->input
) < msg_len
+ 4)
1815 return 0; /* Incomplete message body. */
1817 /* move the current input to e->request */
1818 sshbuf_reset(e
->request
);
1819 if ((r
= sshbuf_get_stringb(e
->input
, e
->request
)) != 0 ||
1820 (r
= sshbuf_get_u8(e
->request
, &type
)) != 0) {
1821 if (r
== SSH_ERR_MESSAGE_INCOMPLETE
||
1822 r
== SSH_ERR_STRING_TOO_LARGE
) {
1823 error_fr(r
, "parse");
1826 fatal_fr(r
, "parse");
1829 debug_f("socket %u (fd=%d) type %d", socknum
, e
->fd
, type
);
1831 /* check whether agent is locked */
1832 if (locked
&& type
!= SSH_AGENTC_UNLOCK
) {
1833 sshbuf_reset(e
->request
);
1835 case SSH2_AGENTC_REQUEST_IDENTITIES
:
1836 /* send empty lists */
1840 /* send a fail message for all other request types */
1847 case SSH_AGENTC_LOCK
:
1848 case SSH_AGENTC_UNLOCK
:
1849 process_lock_agent(e
, type
== SSH_AGENTC_LOCK
);
1851 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES
:
1852 process_remove_all_identities(e
); /* safe for !WITH_SSH1 */
1855 case SSH2_AGENTC_SIGN_REQUEST
:
1856 process_sign_request2(e
);
1858 case SSH2_AGENTC_REQUEST_IDENTITIES
:
1859 process_request_identities(e
);
1861 case SSH2_AGENTC_ADD_IDENTITY
:
1862 case SSH2_AGENTC_ADD_ID_CONSTRAINED
:
1863 process_add_identity(e
);
1865 case SSH2_AGENTC_REMOVE_IDENTITY
:
1866 process_remove_identity(e
);
1868 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES
:
1869 process_remove_all_identities(e
);
1871 #ifdef ENABLE_PKCS11
1872 case SSH_AGENTC_ADD_SMARTCARD_KEY
:
1873 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED
:
1874 process_add_smartcard_key(e
);
1876 case SSH_AGENTC_REMOVE_SMARTCARD_KEY
:
1877 process_remove_smartcard_key(e
);
1879 #endif /* ENABLE_PKCS11 */
1880 case SSH_AGENTC_EXTENSION
:
1881 process_extension(e
);
1884 /* Unknown message. Respond with failure. */
1885 error("Unknown message %d", type
);
1886 sshbuf_reset(e
->request
);
1894 new_socket(sock_type type
, int fd
)
1896 u_int i
, old_alloc
, new_alloc
;
1898 debug_f("type = %s", type
== AUTH_CONNECTION
? "CONNECTION" :
1899 (type
== AUTH_SOCKET
? "SOCKET" : "UNKNOWN"));
1905 for (i
= 0; i
< sockets_alloc
; i
++)
1906 if (sockets
[i
].type
== AUTH_UNUSED
) {
1908 if ((sockets
[i
].input
= sshbuf_new()) == NULL
||
1909 (sockets
[i
].output
= sshbuf_new()) == NULL
||
1910 (sockets
[i
].request
= sshbuf_new()) == NULL
)
1911 fatal_f("sshbuf_new failed");
1912 sockets
[i
].type
= type
;
1915 old_alloc
= sockets_alloc
;
1916 new_alloc
= sockets_alloc
+ 10;
1917 sockets
= xrecallocarray(sockets
, old_alloc
, new_alloc
,
1918 sizeof(sockets
[0]));
1919 for (i
= old_alloc
; i
< new_alloc
; i
++)
1920 sockets
[i
].type
= AUTH_UNUSED
;
1921 sockets_alloc
= new_alloc
;
1922 sockets
[old_alloc
].fd
= fd
;
1923 if ((sockets
[old_alloc
].input
= sshbuf_new()) == NULL
||
1924 (sockets
[old_alloc
].output
= sshbuf_new()) == NULL
||
1925 (sockets
[old_alloc
].request
= sshbuf_new()) == NULL
)
1926 fatal_f("sshbuf_new failed");
1927 sockets
[old_alloc
].type
= type
;
1931 handle_socket_read(u_int socknum
)
1933 struct sockaddr_un sunaddr
;
1939 slen
= sizeof(sunaddr
);
1940 fd
= accept(sockets
[socknum
].fd
, (struct sockaddr
*)&sunaddr
, &slen
);
1942 error("accept from AUTH_SOCKET: %s", strerror(errno
));
1945 if (getpeereid(fd
, &euid
, &egid
) == -1) {
1946 error("getpeereid %d failed: %s", fd
, strerror(errno
));
1950 if ((euid
!= 0) && (getuid() != euid
)) {
1951 error("uid mismatch: peer euid %u != uid %u",
1952 (u_int
) euid
, (u_int
) getuid());
1956 new_socket(AUTH_CONNECTION
, fd
);
1961 handle_conn_read(u_int socknum
)
1963 char buf
[AGENT_RBUF_LEN
];
1967 if ((len
= read(sockets
[socknum
].fd
, buf
, sizeof(buf
))) <= 0) {
1969 if (errno
== EAGAIN
|| errno
== EINTR
)
1971 error_f("read error on socket %u (fd %d): %s",
1972 socknum
, sockets
[socknum
].fd
, strerror(errno
));
1976 if ((r
= sshbuf_put(sockets
[socknum
].input
, buf
, len
)) != 0)
1977 fatal_fr(r
, "compose");
1978 explicit_bzero(buf
, sizeof(buf
));
1980 if ((r
= process_message(socknum
)) == -1)
1989 handle_conn_write(u_int socknum
)
1994 if (sshbuf_len(sockets
[socknum
].output
) == 0)
1995 return 0; /* shouldn't happen */
1996 if ((len
= write(sockets
[socknum
].fd
,
1997 sshbuf_ptr(sockets
[socknum
].output
),
1998 sshbuf_len(sockets
[socknum
].output
))) <= 0) {
2000 if (errno
== EAGAIN
|| errno
== EINTR
)
2002 error_f("read error on socket %u (fd %d): %s",
2003 socknum
, sockets
[socknum
].fd
, strerror(errno
));
2007 if ((r
= sshbuf_consume(sockets
[socknum
].output
, len
)) != 0)
2008 fatal_fr(r
, "consume");
2013 after_poll(struct pollfd
*pfd
, size_t npfd
, u_int maxfds
)
2016 u_int socknum
, activefds
= npfd
;
2018 for (i
= 0; i
< npfd
; i
++) {
2019 if (pfd
[i
].revents
== 0)
2021 /* Find sockets entry */
2022 for (socknum
= 0; socknum
< sockets_alloc
; socknum
++) {
2023 if (sockets
[socknum
].type
!= AUTH_SOCKET
&&
2024 sockets
[socknum
].type
!= AUTH_CONNECTION
)
2026 if (pfd
[i
].fd
== sockets
[socknum
].fd
)
2029 if (socknum
>= sockets_alloc
) {
2030 error_f("no socket for fd %d", pfd
[i
].fd
);
2033 /* Process events */
2034 switch (sockets
[socknum
].type
) {
2036 if ((pfd
[i
].revents
& (POLLIN
|POLLERR
)) == 0)
2038 if (npfd
> maxfds
) {
2039 debug3("out of fds (active %u >= limit %u); "
2040 "skipping accept", activefds
, maxfds
);
2043 if (handle_socket_read(socknum
) == 0)
2046 case AUTH_CONNECTION
:
2047 if ((pfd
[i
].revents
& (POLLIN
|POLLHUP
|POLLERR
)) != 0 &&
2048 handle_conn_read(socknum
) != 0)
2050 if ((pfd
[i
].revents
& (POLLOUT
|POLLHUP
)) != 0 &&
2051 handle_conn_write(socknum
) != 0) {
2054 fatal("activefds == 0 at close_sock");
2055 close_socket(&sockets
[socknum
]);
2067 prepare_poll(struct pollfd
**pfdp
, size_t *npfdp
, struct timespec
*timeoutp
, u_int maxfds
)
2069 struct pollfd
*pfd
= *pfdp
;
2070 size_t i
, j
, npfd
= 0;
2074 /* Count active sockets */
2075 for (i
= 0; i
< sockets_alloc
; i
++) {
2076 switch (sockets
[i
].type
) {
2078 case AUTH_CONNECTION
:
2084 fatal("Unknown socket type %d", sockets
[i
].type
);
2088 if (npfd
!= *npfdp
&&
2089 (pfd
= recallocarray(pfd
, *npfdp
, npfd
, sizeof(*pfd
))) == NULL
)
2090 fatal_f("recallocarray failed");
2094 for (i
= j
= 0; i
< sockets_alloc
; i
++) {
2095 switch (sockets
[i
].type
) {
2097 if (npfd
> maxfds
) {
2098 debug3("out of fds (active %zu >= limit %u); "
2099 "skipping arming listener", npfd
, maxfds
);
2102 pfd
[j
].fd
= sockets
[i
].fd
;
2104 pfd
[j
].events
= POLLIN
;
2107 case AUTH_CONNECTION
:
2108 pfd
[j
].fd
= sockets
[i
].fd
;
2111 * Only prepare to read if we can handle a full-size
2112 * input read buffer and enqueue a max size reply..
2114 if ((r
= sshbuf_check_reserve(sockets
[i
].input
,
2115 AGENT_RBUF_LEN
)) == 0 &&
2116 (r
= sshbuf_check_reserve(sockets
[i
].output
,
2117 AGENT_MAX_LEN
)) == 0)
2118 pfd
[j
].events
= POLLIN
;
2119 else if (r
!= SSH_ERR_NO_BUFFER_SPACE
)
2120 fatal_fr(r
, "reserve");
2121 if (sshbuf_len(sockets
[i
].output
) > 0)
2122 pfd
[j
].events
|= POLLOUT
;
2129 deadline
= reaper();
2130 if (parent_alive_interval
!= 0)
2131 deadline
= (deadline
== 0) ? parent_alive_interval
:
2132 MINIMUM(deadline
, parent_alive_interval
);
2134 ptimeout_deadline_sec(timeoutp
, deadline
);
2139 cleanup_socket(void)
2141 if (cleanup_pid
!= 0 && getpid() != cleanup_pid
)
2145 unlink(socket_name
);
2154 #ifdef ENABLE_PKCS11
2161 cleanup_handler(int sig
)
2167 check_parent_exists(void)
2170 * If our parent has exited then getppid() will return (pid_t)1,
2171 * so testing for that should be safe.
2173 if (parent_pid
!= -1 && getppid() != parent_pid
) {
2174 /* printf("Parent has died - Authentication agent exiting.\n"); */
2184 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
2185 " [-O option] [-P allowed_providers] [-t life]\n"
2186 " ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n"
2187 " [-P allowed_providers] [-t life] command [arg ...]\n"
2188 " ssh-agent [-c | -s] -k\n");
2193 main(int ac
, char **av
)
2195 int c_flag
= 0, d_flag
= 0, D_flag
= 0, k_flag
= 0, s_flag
= 0;
2196 int sock
, ch
, result
, saved_errno
;
2197 char *shell
, *format
, *pidstr
, *agentsocket
= NULL
;
2198 #ifdef HAVE_SETRLIMIT
2202 extern char *optarg
;
2204 char pidstrbuf
[1 + 3 * sizeof pid
];
2207 struct timespec timeout
;
2208 struct pollfd
*pfd
= NULL
;
2211 sigset_t nsigset
, osigset
;
2213 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2217 (void)setegid(getgid());
2218 (void)setgid(getgid());
2220 platform_disable_tracing(0); /* strict=no */
2222 #ifdef RLIMIT_NOFILE
2223 if (getrlimit(RLIMIT_NOFILE
, &rlim
) == -1)
2224 fatal("%s: getrlimit: %s", __progname
, strerror(errno
));
2227 __progname
= ssh_get_progname(av
[0]);
2230 while ((ch
= getopt(ac
, av
, "cDdksE:a:O:P:t:")) != -1) {
2233 fingerprint_hash
= ssh_digest_alg_by_name(optarg
);
2234 if (fingerprint_hash
== -1)
2235 fatal("Invalid hash algorithm \"%s\"", optarg
);
2246 if (strcmp(optarg
, "no-restrict-websafe") == 0)
2247 restrict_websafe
= 0;
2248 else if (strcmp(optarg
, "allow-remote-pkcs11") == 0)
2249 remote_add_provider
= 1;
2251 fatal("Unknown -O option");
2254 if (allowed_providers
!= NULL
)
2255 fatal("-P option already specified");
2256 allowed_providers
= xstrdup(optarg
);
2264 if (d_flag
|| D_flag
)
2269 if (d_flag
|| D_flag
)
2274 agentsocket
= optarg
;
2277 if ((lifetime
= convtime(optarg
)) == -1) {
2278 fprintf(stderr
, "Invalid lifetime\n");
2289 if (ac
> 0 && (c_flag
|| k_flag
|| s_flag
|| d_flag
|| D_flag
))
2292 if (allowed_providers
== NULL
)
2293 allowed_providers
= xstrdup(DEFAULT_ALLOWED_PROVIDERS
);
2295 if (ac
== 0 && !c_flag
&& !s_flag
) {
2296 shell
= getenv("SHELL");
2297 if (shell
!= NULL
&& (len
= strlen(shell
)) > 2 &&
2298 strncmp(shell
+ len
- 3, "csh", 3) == 0)
2302 const char *errstr
= NULL
;
2304 pidstr
= getenv(SSH_AGENTPID_ENV_NAME
);
2305 if (pidstr
== NULL
) {
2306 fprintf(stderr
, "%s not set, cannot kill agent\n",
2307 SSH_AGENTPID_ENV_NAME
);
2310 pid
= (int)strtonum(pidstr
, 2, INT_MAX
, &errstr
);
2313 "%s=\"%s\", which is not a good PID: %s\n",
2314 SSH_AGENTPID_ENV_NAME
, pidstr
, errstr
);
2317 if (kill(pid
, SIGTERM
) == -1) {
2321 format
= c_flag
? "unsetenv %s;\n" : "unset %s;\n";
2322 printf(format
, SSH_AUTHSOCKET_ENV_NAME
);
2323 printf(format
, SSH_AGENTPID_ENV_NAME
);
2324 printf("echo Agent pid %ld killed;\n", (long)pid
);
2329 * Minimum file descriptors:
2330 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
2331 * a few spare for libc / stack protectors / sanitisers, etc.
2333 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
2334 if (rlim
.rlim_cur
< SSH_AGENT_MIN_FDS
)
2335 fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
2336 __progname
, (long long)rlim
.rlim_cur
, SSH_AGENT_MIN_FDS
);
2337 maxfds
= rlim
.rlim_cur
- SSH_AGENT_MIN_FDS
;
2339 parent_pid
= getpid();
2341 if (agentsocket
== NULL
) {
2342 /* Create private directory for agent socket */
2343 mktemp_proto(socket_dir
, sizeof(socket_dir
));
2344 if (mkdtemp(socket_dir
) == NULL
) {
2345 perror("mkdtemp: private socket dir");
2348 snprintf(socket_name
, sizeof socket_name
, "%s/agent.%ld", socket_dir
,
2351 /* Try to use specified agent socket */
2352 socket_dir
[0] = '\0';
2353 strlcpy(socket_name
, agentsocket
, sizeof socket_name
);
2357 * Create socket early so it will exist before command gets run from
2360 prev_mask
= umask(0177);
2361 sock
= unix_listener(socket_name
, SSH_LISTEN_BACKLOG
, 0);
2363 /* XXX - unix_listener() calls error() not perror() */
2364 *socket_name
= '\0'; /* Don't unlink any existing file */
2370 * Fork, and have the parent execute the command, if any, or present
2371 * the socket data. The child continues as the authentication agent.
2373 if (D_flag
|| d_flag
) {
2374 log_init(__progname
,
2375 d_flag
? SYSLOG_LEVEL_DEBUG3
: SYSLOG_LEVEL_INFO
,
2376 SYSLOG_FACILITY_AUTH
, 1);
2377 format
= c_flag
? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2378 printf(format
, SSH_AUTHSOCKET_ENV_NAME
, socket_name
,
2379 SSH_AUTHSOCKET_ENV_NAME
);
2380 printf("echo Agent pid %ld;\n", (long)parent_pid
);
2389 if (pid
!= 0) { /* Parent - execute the given command. */
2391 snprintf(pidstrbuf
, sizeof pidstrbuf
, "%ld", (long)pid
);
2393 format
= c_flag
? "setenv %s %s;\n" : "%s=%s; export %s;\n";
2394 printf(format
, SSH_AUTHSOCKET_ENV_NAME
, socket_name
,
2395 SSH_AUTHSOCKET_ENV_NAME
);
2396 printf(format
, SSH_AGENTPID_ENV_NAME
, pidstrbuf
,
2397 SSH_AGENTPID_ENV_NAME
);
2398 printf("echo Agent pid %ld;\n", (long)pid
);
2401 if (setenv(SSH_AUTHSOCKET_ENV_NAME
, socket_name
, 1) == -1 ||
2402 setenv(SSH_AGENTPID_ENV_NAME
, pidstrbuf
, 1) == -1) {
2411 log_init(__progname
, SYSLOG_LEVEL_INFO
, SYSLOG_FACILITY_AUTH
, 0);
2413 if (setsid() == -1) {
2414 error("setsid: %s", strerror(errno
));
2419 if (stdfd_devnull(1, 1, 1) == -1)
2420 error_f("stdfd_devnull failed");
2422 #ifdef HAVE_SETRLIMIT
2423 /* deny core dumps, since memory contains unencrypted private keys */
2424 rlim
.rlim_cur
= rlim
.rlim_max
= 0;
2425 if (setrlimit(RLIMIT_CORE
, &rlim
) == -1) {
2426 error("setrlimit RLIMIT_CORE: %s", strerror(errno
));
2433 cleanup_pid
= getpid();
2435 #ifdef ENABLE_PKCS11
2438 new_socket(AUTH_SOCKET
, sock
);
2440 parent_alive_interval
= 10;
2442 ssh_signal(SIGPIPE
, SIG_IGN
);
2443 ssh_signal(SIGINT
, (d_flag
| D_flag
) ? cleanup_handler
: SIG_IGN
);
2444 ssh_signal(SIGHUP
, cleanup_handler
);
2445 ssh_signal(SIGTERM
, cleanup_handler
);
2447 sigemptyset(&nsigset
);
2448 sigaddset(&nsigset
, SIGINT
);
2449 sigaddset(&nsigset
, SIGHUP
);
2450 sigaddset(&nsigset
, SIGTERM
);
2452 if (pledge("stdio rpath cpath unix id proc exec", NULL
) == -1)
2453 fatal("%s: pledge: %s", __progname
, strerror(errno
));
2454 platform_pledge_agent();
2457 sigprocmask(SIG_BLOCK
, &nsigset
, &osigset
);
2458 if (signalled
!= 0) {
2459 logit("exiting on signal %d", (int)signalled
);
2462 ptimeout_init(&timeout
);
2463 prepare_poll(&pfd
, &npfd
, &timeout
, maxfds
);
2464 result
= ppoll(pfd
, npfd
, ptimeout_get_tsp(&timeout
), &osigset
);
2465 sigprocmask(SIG_SETMASK
, &osigset
, NULL
);
2466 saved_errno
= errno
;
2467 if (parent_alive_interval
!= 0)
2468 check_parent_exists();
2469 (void) reaper(); /* remove expired keys */
2471 if (saved_errno
== EINTR
)
2473 fatal("poll: %s", strerror(saved_errno
));
2474 } else if (result
> 0)
2475 after_poll(pfd
, npfd
, maxfds
);