1 /* $OpenBSD: ssh-agent.c,v 1.231 2018/05/11 03:38:51 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/param.h>
42 #include <sys/resource.h>
44 #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"
91 #include "ssh-pkcs11.h"
94 #ifndef DEFAULT_PKCS11_WHITELIST
95 # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
98 /* Maximum accepted message length */
99 #define AGENT_MAX_LEN (256*1024)
110 struct sshbuf *input;
111 struct sshbuf *output;
112 struct sshbuf *request;
115 u_int sockets_alloc = 0;
116 SocketEntry *sockets = NULL;
118 typedef struct identity {
119 TAILQ_ENTRY(identity) next;
129 TAILQ_HEAD(idqueue, identity) idlist;
132 /* private key table */
133 struct idtable *idtab;
137 /* pid of shell == parent of agent */
138 pid_t parent_pid = -1;
139 time_t parent_alive_interval = 0;
141 /* pid of process for which cleanup_socket is applicable */
142 pid_t cleanup_pid = 0;
144 /* pathname and directory for AUTH_SOCKET */
145 char socket_name[PATH_MAX];
146 char socket_dir[PATH_MAX];
148 /* PKCS#11 path whitelist */
149 static char *pkcs11_whitelist;
153 #define LOCK_SALT_SIZE 16
154 #define LOCK_ROUNDS 1
156 u_char lock_pwhash[LOCK_SIZE];
157 u_char lock_salt[LOCK_SALT_SIZE];
159 extern char *__progname;
161 /* Default lifetime in seconds (0 == forever) */
162 static long lifetime = 0;
164 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
167 * Client connection count; incremented in new_socket() and decremented in
168 * close_socket(). When it reaches 0, ssh-agent will exit. Since it is
169 * normally initialized to 1, it will never reach 0. However, if the -x
170 * option is specified, it is initialized to 0 in main(); in that case,
171 * ssh-agent will exit as soon as it has had at least one client but no
174 static int xcount = 1;
177 close_socket(SocketEntry *e)
181 if (e->type == AUTH_CONNECTION) {
182 debug("xcount %d -> %d", xcount, xcount - 1);
188 e->type = AUTH_UNUSED;
189 sshbuf_free(e->input);
190 sshbuf_free(e->output);
191 sshbuf_free(e->request);
199 idtab = xcalloc(1, sizeof(*idtab));
200 TAILQ_INIT(&idtab->idlist);
205 free_identity(Identity *id)
207 sshkey_free(id->key);
213 /* return matching private key for given public key */
215 lookup_identity(struct sshkey *key)
219 TAILQ_FOREACH(id, &idtab->idlist, next) {
220 if (sshkey_equal(key, id->key))
226 /* Check confirmation of keysign request */
228 confirm_key(Identity *id)
233 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
235 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
244 send_status(SocketEntry *e, int success)
248 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
249 (r = sshbuf_put_u8(e->output, success ?
250 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
251 fatal("%s: buffer error: %s", __func__, ssh_err(r));
254 /* send list of supported public keys to 'client' */
256 process_request_identities(SocketEntry *e)
262 if ((msg = sshbuf_new()) == NULL)
263 fatal("%s: sshbuf_new failed", __func__);
264 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
265 (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
266 fatal("%s: buffer error: %s", __func__, ssh_err(r));
267 TAILQ_FOREACH(id, &idtab->idlist, next) {
268 if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO))
270 (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
271 error("%s: put key/comment: %s", __func__,
276 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
277 fatal("%s: buffer error: %s", __func__, ssh_err(r));
283 agent_decode_alg(struct sshkey *key, u_int flags)
285 if (key->type == KEY_RSA) {
286 if (flags & SSH_AGENT_RSA_SHA2_256)
287 return "rsa-sha2-256";
288 else if (flags & SSH_AGENT_RSA_SHA2_512)
289 return "rsa-sha2-512";
296 process_sign_request2(SocketEntry *e)
299 u_char *signature = NULL;
300 size_t dlen, slen = 0;
301 u_int compat = 0, flags;
304 struct sshkey *key = NULL;
307 if ((msg = sshbuf_new()) == NULL)
308 fatal("%s: sshbuf_new failed", __func__);
309 if ((r = sshkey_froms(e->request, &key)) != 0 ||
310 (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
311 (r = sshbuf_get_u32(e->request, &flags)) != 0) {
312 error("%s: couldn't parse request: %s", __func__, ssh_err(r));
316 if ((id = lookup_identity(key)) == NULL) {
317 verbose("%s: %s key not found", __func__, sshkey_type(key));
320 if (id->confirm && confirm_key(id) != 0) {
321 verbose("%s: user refused key", __func__);
324 if ((r = sshkey_sign(id->key, &signature, &slen,
325 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
326 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
334 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
335 (r = sshbuf_put_string(msg, signature, slen)) != 0)
336 fatal("%s: buffer error: %s", __func__, ssh_err(r));
337 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
338 fatal("%s: buffer error: %s", __func__, ssh_err(r));
340 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
341 fatal("%s: buffer error: %s", __func__, ssh_err(r));
349 process_remove_identity(SocketEntry *e)
352 struct sshkey *key = NULL;
355 if ((r = sshkey_froms(e->request, &key)) != 0) {
356 error("%s: get key: %s", __func__, ssh_err(r));
359 if ((id = lookup_identity(key)) == NULL) {
360 debug("%s: key not found", __func__);
363 /* We have this key, free it. */
364 if (idtab->nentries < 1)
365 fatal("%s: internal error: nentries %d",
366 __func__, idtab->nentries);
367 TAILQ_REMOVE(&idtab->idlist, id, next);
373 send_status(e, success);
377 process_remove_all_identities(SocketEntry *e)
381 /* Loop over all identities and clear the keys. */
382 for (id = TAILQ_FIRST(&idtab->idlist); id;
383 id = TAILQ_FIRST(&idtab->idlist)) {
384 TAILQ_REMOVE(&idtab->idlist, id, next);
388 /* Mark that there are no identities. */
395 /* removes expired keys and returns number of seconds until the next expiry */
399 time_t deadline = 0, now = monotime();
402 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
403 nxt = TAILQ_NEXT(id, next);
406 if (now >= id->death) {
407 debug("expiring key '%s'", id->comment);
408 TAILQ_REMOVE(&idtab->idlist, id, next);
412 deadline = (deadline == 0) ? id->death :
413 MINIMUM(deadline, id->death);
415 if (deadline == 0 || deadline <= now)
418 return (deadline - now);
422 process_add_identity(SocketEntry *e)
425 int success = 0, confirm = 0;
426 u_int seconds, maxsign;
427 char *comment = NULL;
429 struct sshkey *k = NULL;
431 int r = SSH_ERR_INTERNAL_ERROR;
433 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
435 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
436 error("%s: decode private key: %s", __func__, ssh_err(r));
440 while (sshbuf_len(e->request)) {
441 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
442 error("%s: buffer error: %s", __func__, ssh_err(r));
446 case SSH_AGENT_CONSTRAIN_LIFETIME:
447 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
448 error("%s: bad lifetime constraint: %s",
449 __func__, ssh_err(r));
452 death = monotime() + seconds;
454 case SSH_AGENT_CONSTRAIN_CONFIRM:
457 case SSH_AGENT_CONSTRAIN_MAXSIGN:
458 if ((r = sshbuf_get_u32(e->request, &maxsign)) != 0) {
459 error("%s: bad maxsign constraint: %s",
460 __func__, ssh_err(r));
463 if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
464 error("%s: cannot enable maxsign: %s",
465 __func__, ssh_err(r));
470 error("%s: Unknown constraint %d", __func__, ctype);
472 sshbuf_reset(e->request);
480 if (lifetime && !death)
481 death = monotime() + lifetime;
482 if ((id = lookup_identity(k)) == NULL) {
483 id = xcalloc(1, sizeof(Identity));
484 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
485 /* Increment the number of identities. */
488 /* key state might have been updated */
489 sshkey_free(id->key);
493 id->comment = comment;
495 id->confirm = confirm;
497 send_status(e, success);
500 /* XXX todo: encrypt sensitive data with passphrase */
502 process_lock_agent(SocketEntry *e, int lock)
504 int r, success = 0, delay;
506 u_char passwdhash[LOCK_SIZE];
507 static u_int fail_count = 0;
511 * This is deliberately fatal: the user has requested that we lock,
512 * but we can't parse their request properly. The only safe thing to
515 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
516 fatal("%s: buffer error: %s", __func__, ssh_err(r));
518 debug("empty password not supported");
519 } else if (locked && !lock) {
520 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
521 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
522 fatal("bcrypt_pbkdf");
523 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
524 debug("agent unlocked");
527 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
530 /* delay in 0.1s increments up to 10s */
531 if (fail_count < 100)
533 delay = 100000 * fail_count;
534 debug("unlock failed, delaying %0.1lf seconds",
535 (double)delay/1000000);
538 explicit_bzero(passwdhash, sizeof(passwdhash));
539 } else if (!locked && lock) {
540 debug("agent locked");
542 arc4random_buf(lock_salt, sizeof(lock_salt));
543 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
544 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
545 fatal("bcrypt_pbkdf");
548 explicit_bzero(passwd, pwlen);
550 send_status(e, success);
554 no_identities(SocketEntry *e)
559 if ((msg = sshbuf_new()) == NULL)
560 fatal("%s: sshbuf_new failed", __func__);
561 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
562 (r = sshbuf_put_u32(msg, 0)) != 0 ||
563 (r = sshbuf_put_stringb(e->output, msg)) != 0)
564 fatal("%s: buffer error: %s", __func__, ssh_err(r));
570 process_add_smartcard_key(SocketEntry *e)
572 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
573 int r, i, count = 0, success = 0, confirm = 0;
577 struct sshkey **keys = NULL, *k;
580 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
581 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
582 error("%s: buffer error: %s", __func__, ssh_err(r));
586 while (sshbuf_len(e->request)) {
587 if ((r = sshbuf_get_u8(e->request, &type)) != 0) {
588 error("%s: buffer error: %s", __func__, ssh_err(r));
592 case SSH_AGENT_CONSTRAIN_LIFETIME:
593 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
594 error("%s: buffer error: %s",
595 __func__, ssh_err(r));
598 death = monotime() + seconds;
600 case SSH_AGENT_CONSTRAIN_CONFIRM:
604 error("%s: Unknown constraint type %d", __func__, type);
608 if (realpath(provider, canonical_provider) == NULL) {
609 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
610 provider, strerror(errno));
613 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
614 verbose("refusing PKCS#11 add of \"%.100s\": "
615 "provider not whitelisted", canonical_provider);
618 debug("%s: add %.100s", __func__, canonical_provider);
619 if (lifetime && !death)
620 death = monotime() + lifetime;
622 count = pkcs11_add_provider(canonical_provider, pin, &keys);
623 for (i = 0; i < count; i++) {
625 if (lookup_identity(k) == NULL) {
626 id = xcalloc(1, sizeof(Identity));
628 id->provider = xstrdup(canonical_provider);
629 id->comment = xstrdup(canonical_provider); /* XXX */
631 id->confirm = confirm;
632 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
644 send_status(e, success);
648 process_remove_smartcard_key(SocketEntry *e)
650 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
654 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
655 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
656 error("%s: buffer error: %s", __func__, ssh_err(r));
661 if (realpath(provider, canonical_provider) == NULL) {
662 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
663 provider, strerror(errno));
667 debug("%s: remove %.100s", __func__, canonical_provider);
668 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
669 nxt = TAILQ_NEXT(id, next);
670 /* Skip file--based keys */
671 if (id->provider == NULL)
673 if (!strcmp(canonical_provider, id->provider)) {
674 TAILQ_REMOVE(&idtab->idlist, id, next);
679 if (pkcs11_del_provider(canonical_provider) == 0)
682 error("%s: pkcs11_del_provider failed", __func__);
685 send_status(e, success);
687 #endif /* ENABLE_PKCS11 */
689 /* dispatch incoming messages */
692 process_message(u_int socknum)
700 if (socknum >= sockets_alloc) {
701 fatal("%s: socket number %u >= allocated %u",
702 __func__, socknum, sockets_alloc);
704 e = &sockets[socknum];
706 if (sshbuf_len(e->input) < 5)
707 return 0; /* Incomplete message header. */
708 cp = sshbuf_ptr(e->input);
709 msg_len = PEEK_U32(cp);
710 if (msg_len > AGENT_MAX_LEN) {
711 debug("%s: socket %u (fd=%d) message too long %u > %u",
712 __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
715 if (sshbuf_len(e->input) < msg_len + 4)
716 return 0; /* Incomplete message body. */
718 /* move the current input to e->request */
719 sshbuf_reset(e->request);
720 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
721 (r = sshbuf_get_u8(e->request, &type)) != 0) {
722 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
723 r == SSH_ERR_STRING_TOO_LARGE) {
724 debug("%s: buffer error: %s", __func__, ssh_err(r));
727 fatal("%s: buffer error: %s", __func__, ssh_err(r));
730 debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
732 /* check whether agent is locked */
733 if (locked && type != SSH_AGENTC_UNLOCK) {
734 sshbuf_reset(e->request);
736 case SSH2_AGENTC_REQUEST_IDENTITIES:
737 /* send empty lists */
741 /* send a fail message for all other request types */
748 case SSH_AGENTC_LOCK:
749 case SSH_AGENTC_UNLOCK:
750 process_lock_agent(e, type == SSH_AGENTC_LOCK);
752 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
753 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
756 case SSH2_AGENTC_SIGN_REQUEST:
757 process_sign_request2(e);
759 case SSH2_AGENTC_REQUEST_IDENTITIES:
760 process_request_identities(e);
762 case SSH2_AGENTC_ADD_IDENTITY:
763 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
764 process_add_identity(e);
766 case SSH2_AGENTC_REMOVE_IDENTITY:
767 process_remove_identity(e);
769 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
770 process_remove_all_identities(e);
773 case SSH_AGENTC_ADD_SMARTCARD_KEY:
774 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
775 process_add_smartcard_key(e);
777 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
778 process_remove_smartcard_key(e);
780 #endif /* ENABLE_PKCS11 */
782 /* Unknown message. Respond with failure. */
783 error("Unknown message %d", type);
784 sshbuf_reset(e->request);
792 new_socket(sock_type type, int fd)
794 u_int i, old_alloc, new_alloc;
796 if (type == AUTH_CONNECTION) {
797 debug("xcount %d -> %d", xcount, xcount + 1);
805 for (i = 0; i < sockets_alloc; i++)
806 if (sockets[i].type == AUTH_UNUSED) {
808 if ((sockets[i].input = sshbuf_new()) == NULL)
809 fatal("%s: sshbuf_new failed", __func__);
810 if ((sockets[i].output = sshbuf_new()) == NULL)
811 fatal("%s: sshbuf_new failed", __func__);
812 if ((sockets[i].request = sshbuf_new()) == NULL)
813 fatal("%s: sshbuf_new failed", __func__);
814 sockets[i].type = type;
817 old_alloc = sockets_alloc;
818 new_alloc = sockets_alloc + 10;
819 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
820 for (i = old_alloc; i < new_alloc; i++)
821 sockets[i].type = AUTH_UNUSED;
822 sockets_alloc = new_alloc;
823 sockets[old_alloc].fd = fd;
824 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
825 fatal("%s: sshbuf_new failed", __func__);
826 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
827 fatal("%s: sshbuf_new failed", __func__);
828 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
829 fatal("%s: sshbuf_new failed", __func__);
830 sockets[old_alloc].type = type;
834 handle_socket_read(u_int socknum)
836 struct sockaddr_un sunaddr;
842 slen = sizeof(sunaddr);
843 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
845 error("accept from AUTH_SOCKET: %s", strerror(errno));
848 if (getpeereid(fd, &euid, &egid) < 0) {
849 error("getpeereid %d failed: %s", fd, strerror(errno));
853 if ((euid != 0) && (getuid() != euid)) {
854 error("uid mismatch: peer euid %u != uid %u",
855 (u_int) euid, (u_int) getuid());
859 new_socket(AUTH_CONNECTION, fd);
864 handle_conn_read(u_int socknum)
870 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
872 if (errno == EAGAIN || errno == EINTR)
874 error("%s: read error on socket %u (fd %d): %s",
875 __func__, socknum, sockets[socknum].fd,
880 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
881 fatal("%s: buffer error: %s", __func__, ssh_err(r));
882 explicit_bzero(buf, sizeof(buf));
883 process_message(socknum);
888 handle_conn_write(u_int socknum)
893 if (sshbuf_len(sockets[socknum].output) == 0)
894 return 0; /* shouldn't happen */
895 if ((len = write(sockets[socknum].fd,
896 sshbuf_ptr(sockets[socknum].output),
897 sshbuf_len(sockets[socknum].output))) <= 0) {
899 if (errno == EAGAIN || errno == EINTR)
901 error("%s: read error on socket %u (fd %d): %s",
902 __func__, socknum, sockets[socknum].fd,
907 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
908 fatal("%s: buffer error: %s", __func__, ssh_err(r));
913 after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
916 u_int socknum, activefds = npfd;
918 for (i = 0; i < npfd; i++) {
919 if (pfd[i].revents == 0)
921 /* Find sockets entry */
922 for (socknum = 0; socknum < sockets_alloc; socknum++) {
923 if (sockets[socknum].type != AUTH_SOCKET &&
924 sockets[socknum].type != AUTH_CONNECTION)
926 if (pfd[i].fd == sockets[socknum].fd)
929 if (socknum >= sockets_alloc) {
930 error("%s: no socket for fd %d", __func__, pfd[i].fd);
934 switch (sockets[socknum].type) {
936 if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
939 debug3("out of fds (active %u >= limit %u); "
940 "skipping accept", activefds, maxfds);
943 if (handle_socket_read(socknum) == 0)
946 case AUTH_CONNECTION:
947 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
948 handle_conn_read(socknum) != 0) {
951 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
952 handle_conn_write(socknum) != 0) {
955 fatal("activefds == 0 at close_sock");
956 close_socket(&sockets[socknum]);
968 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
970 struct pollfd *pfd = *pfdp;
971 size_t i, j, npfd = 0;
974 /* Count active sockets */
975 for (i = 0; i < sockets_alloc; i++) {
976 switch (sockets[i].type) {
978 case AUTH_CONNECTION:
984 fatal("Unknown socket type %d", sockets[i].type);
988 if (npfd != *npfdp &&
989 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
990 fatal("%s: recallocarray failed", __func__);
994 for (i = j = 0; i < sockets_alloc; i++) {
995 switch (sockets[i].type) {
998 debug3("out of fds (active %zu >= limit %u); "
999 "skipping arming listener", npfd, maxfds);
1002 pfd[j].fd = sockets[i].fd;
1004 pfd[j].events = POLLIN;
1007 case AUTH_CONNECTION:
1008 pfd[j].fd = sockets[i].fd;
1010 /* XXX backoff when input buffer full */
1011 pfd[j].events = POLLIN;
1012 if (sshbuf_len(sockets[i].output) > 0)
1013 pfd[j].events |= POLLOUT;
1020 deadline = reaper();
1021 if (parent_alive_interval != 0)
1022 deadline = (deadline == 0) ? parent_alive_interval :
1023 MINIMUM(deadline, parent_alive_interval);
1024 if (deadline == 0) {
1025 *timeoutp = -1; /* INFTIM */
1027 if (deadline > INT_MAX / 1000)
1028 *timeoutp = INT_MAX / 1000;
1030 *timeoutp = deadline * 1000;
1036 cleanup_socket(void)
1038 if (cleanup_pid != 0 && getpid() != cleanup_pid)
1040 debug("%s: cleanup", __func__);
1042 unlink(socket_name);
1056 cleanup_handler(int sig)
1059 #ifdef ENABLE_PKCS11
1066 check_parent_exists(void)
1069 * If our parent has exited then getppid() will return (pid_t)1,
1070 * so testing for that should be safe.
1072 if (parent_pid != -1 && getppid() != parent_pid) {
1073 /* printf("Parent has died - Authentication agent exiting.\n"); */
1083 "usage: ssh-agent [-c | -s] [-Ddx] [-a bind_address] [-E fingerprint_hash]\n"
1084 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1085 " ssh-agent [-c | -s] -k\n");
1090 main(int ac, char **av)
1092 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1093 int sock, fd, ch, result, saved_errno;
1094 char *shell, *format, *pidstr, *agentsocket = NULL;
1095 #ifdef HAVE_SETRLIMIT
1099 extern char *optarg;
1101 char pidstrbuf[1 + 3 * sizeof pid];
1104 int timeout = -1; /* INFTIM */
1105 struct pollfd *pfd = NULL;
1109 ssh_malloc_init(); /* must be called before any mallocs */
1110 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1118 platform_disable_tracing(0); /* strict=no */
1120 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
1121 fatal("%s: getrlimit: %s", __progname, strerror(errno));
1124 OpenSSL_add_all_algorithms();
1127 __progname = ssh_get_progname(av[0]);
1130 while ((ch = getopt(ac, av, "cDdksE:a:P:t:x")) != -1) {
1133 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1134 if (fingerprint_hash == -1)
1135 fatal("Invalid hash algorithm \"%s\"", optarg);
1146 if (pkcs11_whitelist != NULL)
1147 fatal("-P option already specified");
1148 pkcs11_whitelist = xstrdup(optarg);
1156 if (d_flag || D_flag)
1161 if (d_flag || D_flag)
1166 agentsocket = optarg;
1169 if ((lifetime = convtime(optarg)) == -1) {
1170 fprintf(stderr, "Invalid lifetime\n");
1184 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1187 if (pkcs11_whitelist == NULL)
1188 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1190 if (ac == 0 && !c_flag && !s_flag) {
1191 shell = getenv("SHELL");
1192 if (shell != NULL && (len = strlen(shell)) > 2 &&
1193 strncmp(shell + len - 3, "csh", 3) == 0)
1197 const char *errstr = NULL;
1199 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1200 if (pidstr == NULL) {
1201 fprintf(stderr, "%s not set, cannot kill agent\n",
1202 SSH_AGENTPID_ENV_NAME);
1205 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1208 "%s=\"%s\", which is not a good PID: %s\n",
1209 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1212 if (kill(pid, SIGTERM) == -1) {
1216 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1217 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1218 printf(format, SSH_AGENTPID_ENV_NAME);
1219 printf("echo Agent pid %ld killed;\n", (long)pid);
1224 * Minimum file descriptors:
1225 * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
1226 * a few spare for libc / stack protectors / sanitisers, etc.
1228 #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
1229 if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
1230 fatal("%s: file descriptior rlimit %lld too low (minimum %u)",
1231 __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
1232 maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
1234 parent_pid = getpid();
1236 if (agentsocket == NULL) {
1237 /* Create private directory for agent socket */
1238 mktemp_proto(socket_dir, sizeof(socket_dir));
1239 if (mkdtemp(socket_dir) == NULL) {
1240 perror("mkdtemp: private socket dir");
1243 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1246 /* Try to use specified agent socket */
1247 socket_dir[0] = '\0';
1248 strlcpy(socket_name, agentsocket, sizeof socket_name);
1252 * Create socket early so it will exist before command gets run from
1255 prev_mask = umask(0177);
1256 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1258 /* XXX - unix_listener() calls error() not perror() */
1259 *socket_name = '\0'; /* Don't unlink any existing file */
1265 * Fork, and have the parent execute the command, if any, or present
1266 * the socket data. The child continues as the authentication agent.
1268 if (D_flag || d_flag) {
1269 log_init(__progname,
1270 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1271 SYSLOG_FACILITY_AUTH, 1);
1272 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1273 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1274 SSH_AUTHSOCKET_ENV_NAME);
1275 printf("echo Agent pid %ld;\n", (long)parent_pid);
1284 if (pid != 0) { /* Parent - execute the given command. */
1286 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1288 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1289 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1290 SSH_AUTHSOCKET_ENV_NAME);
1291 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1292 SSH_AGENTPID_ENV_NAME);
1293 printf("echo Agent pid %ld;\n", (long)pid);
1296 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1297 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1306 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1308 if (setsid() == -1) {
1309 error("setsid: %s", strerror(errno));
1314 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1315 /* XXX might close listen socket */
1316 (void)dup2(fd, STDIN_FILENO);
1317 (void)dup2(fd, STDOUT_FILENO);
1318 (void)dup2(fd, STDERR_FILENO);
1323 #ifdef HAVE_SETRLIMIT
1324 /* deny core dumps, since memory contains unencrypted private keys */
1325 rlim.rlim_cur = rlim.rlim_max = 0;
1326 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1327 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1334 cleanup_pid = getpid();
1336 #ifdef ENABLE_PKCS11
1339 new_socket(AUTH_SOCKET, sock);
1341 parent_alive_interval = 10;
1343 signal(SIGPIPE, SIG_IGN);
1344 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1345 signal(SIGHUP, cleanup_handler);
1346 signal(SIGTERM, cleanup_handler);
1348 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1349 fatal("%s: pledge: %s", __progname, strerror(errno));
1350 platform_pledge_agent();
1353 prepare_poll(&pfd, &npfd, &timeout, maxfds);
1354 result = poll(pfd, npfd, timeout);
1355 saved_errno = errno;
1356 if (parent_alive_interval != 0)
1357 check_parent_exists();
1358 (void) reaper(); /* remove expired keys */
1360 if (saved_errno == EINTR)
1362 fatal("poll: %s", strerror(saved_errno));
1363 } else if (result > 0)
1364 after_poll(pfd, npfd, maxfds);