1 /* $OpenBSD: ssh-agent.c,v 1.224 2017/07/24 04:34:28 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/param.h>
41 #include <sys/resource.h>
43 #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"
90 #include "ssh-pkcs11.h"
93 #ifndef DEFAULT_PKCS11_WHITELIST
94 # define DEFAULT_PKCS11_WHITELIST "/usr/lib*/*,/usr/local/lib*/*"
97 /* Maximum accepted message length */
98 #define AGENT_MAX_LEN (256*1024)
109 struct sshbuf *input;
110 struct sshbuf *output;
111 struct sshbuf *request;
114 u_int sockets_alloc = 0;
115 SocketEntry *sockets = NULL;
117 typedef struct identity {
118 TAILQ_ENTRY(identity) next;
128 TAILQ_HEAD(idqueue, identity) idlist;
131 /* private key table */
132 struct idtable *idtab;
136 /* pid of shell == parent of agent */
137 pid_t parent_pid = -1;
138 time_t parent_alive_interval = 0;
140 /* pid of process for which cleanup_socket is applicable */
141 pid_t cleanup_pid = 0;
143 /* pathname and directory for AUTH_SOCKET */
144 char socket_name[PATH_MAX];
145 char socket_dir[PATH_MAX];
147 /* PKCS#11 path whitelist */
148 static char *pkcs11_whitelist;
152 #define LOCK_SALT_SIZE 16
153 #define LOCK_ROUNDS 1
155 u_char lock_pwhash[LOCK_SIZE];
156 u_char lock_salt[LOCK_SALT_SIZE];
158 extern char *__progname;
160 /* Default lifetime in seconds (0 == forever) */
161 static long lifetime = 0;
163 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
166 close_socket(SocketEntry *e)
170 e->type = AUTH_UNUSED;
171 sshbuf_free(e->input);
172 sshbuf_free(e->output);
173 sshbuf_free(e->request);
179 idtab = xcalloc(1, sizeof(*idtab));
180 TAILQ_INIT(&idtab->idlist);
185 free_identity(Identity *id)
187 sshkey_free(id->key);
193 /* return matching private key for given public key */
195 lookup_identity(struct sshkey *key)
199 TAILQ_FOREACH(id, &idtab->idlist, next) {
200 if (sshkey_equal(key, id->key))
206 /* Check confirmation of keysign request */
208 confirm_key(Identity *id)
213 p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
215 ask_permission("Allow use of key %s?\nKey fingerprint %s.",
224 send_status(SocketEntry *e, int success)
228 if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
229 (r = sshbuf_put_u8(e->output, success ?
230 SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
231 fatal("%s: buffer error: %s", __func__, ssh_err(r));
234 /* send list of supported public keys to 'client' */
236 process_request_identities(SocketEntry *e)
242 if ((msg = sshbuf_new()) == NULL)
243 fatal("%s: sshbuf_new failed", __func__);
244 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
245 (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
246 fatal("%s: buffer error: %s", __func__, ssh_err(r));
247 TAILQ_FOREACH(id, &idtab->idlist, next) {
248 if ((r = sshkey_puts(id->key, msg)) != 0 ||
249 (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
250 error("%s: put key/comment: %s", __func__,
255 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
256 fatal("%s: buffer error: %s", __func__, ssh_err(r));
262 agent_decode_alg(struct sshkey *key, u_int flags)
264 if (key->type == KEY_RSA) {
265 if (flags & SSH_AGENT_RSA_SHA2_256)
266 return "rsa-sha2-256";
267 else if (flags & SSH_AGENT_RSA_SHA2_512)
268 return "rsa-sha2-512";
275 process_sign_request2(SocketEntry *e)
278 u_char *signature = NULL;
279 size_t dlen, slen = 0;
280 u_int compat = 0, flags;
283 struct sshkey *key = NULL;
286 if ((msg = sshbuf_new()) == NULL)
287 fatal("%s: sshbuf_new failed", __func__);
288 if ((r = sshkey_froms(e->request, &key)) != 0 ||
289 (r = sshbuf_get_string_direct(e->request, &data, &dlen)) != 0 ||
290 (r = sshbuf_get_u32(e->request, &flags)) != 0)
291 fatal("%s: buffer error: %s", __func__, ssh_err(r));
292 if (flags & SSH_AGENT_OLD_SIGNATURE)
293 compat = SSH_BUG_SIGBLOB;
294 if ((id = lookup_identity(key)) == NULL) {
295 verbose("%s: %s key not found", __func__, sshkey_type(key));
298 if (id->confirm && confirm_key(id) != 0) {
299 verbose("%s: user refused key", __func__);
302 if ((r = sshkey_sign(id->key, &signature, &slen,
303 data, dlen, agent_decode_alg(key, flags), compat)) != 0) {
304 error("%s: sshkey_sign: %s", __func__, ssh_err(r));
312 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
313 (r = sshbuf_put_string(msg, signature, slen)) != 0)
314 fatal("%s: buffer error: %s", __func__, ssh_err(r));
315 } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
316 fatal("%s: buffer error: %s", __func__, ssh_err(r));
318 if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
319 fatal("%s: buffer error: %s", __func__, ssh_err(r));
327 process_remove_identity(SocketEntry *e)
330 struct sshkey *key = NULL;
333 if ((r = sshkey_froms(e->request, &key)) != 0) {
334 error("%s: get key: %s", __func__, ssh_err(r));
337 if ((id = lookup_identity(key)) == NULL) {
338 debug("%s: key not found", __func__);
341 /* We have this key, free it. */
342 if (idtab->nentries < 1)
343 fatal("%s: internal error: nentries %d",
344 __func__, idtab->nentries);
345 TAILQ_REMOVE(&idtab->idlist, id, next);
351 send_status(e, success);
355 process_remove_all_identities(SocketEntry *e)
359 /* Loop over all identities and clear the keys. */
360 for (id = TAILQ_FIRST(&idtab->idlist); id;
361 id = TAILQ_FIRST(&idtab->idlist)) {
362 TAILQ_REMOVE(&idtab->idlist, id, next);
366 /* Mark that there are no identities. */
373 /* removes expired keys and returns number of seconds until the next expiry */
377 time_t deadline = 0, now = monotime();
380 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
381 nxt = TAILQ_NEXT(id, next);
384 if (now >= id->death) {
385 debug("expiring key '%s'", id->comment);
386 TAILQ_REMOVE(&idtab->idlist, id, next);
390 deadline = (deadline == 0) ? id->death :
391 MINIMUM(deadline, id->death);
393 if (deadline == 0 || deadline <= now)
396 return (deadline - now);
400 process_add_identity(SocketEntry *e)
403 int success = 0, confirm = 0;
405 char *comment = NULL;
407 struct sshkey *k = NULL;
409 int r = SSH_ERR_INTERNAL_ERROR;
411 if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
413 (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
414 error("%s: decode private key: %s", __func__, ssh_err(r));
418 while (sshbuf_len(e->request)) {
419 if ((r = sshbuf_get_u8(e->request, &ctype)) != 0) {
420 error("%s: buffer error: %s", __func__, ssh_err(r));
424 case SSH_AGENT_CONSTRAIN_LIFETIME:
425 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) {
426 error("%s: bad lifetime constraint: %s",
427 __func__, ssh_err(r));
430 death = monotime() + seconds;
432 case SSH_AGENT_CONSTRAIN_CONFIRM:
436 error("%s: Unknown constraint %d", __func__, ctype);
438 sshbuf_reset(e->request);
446 if (lifetime && !death)
447 death = monotime() + lifetime;
448 if ((id = lookup_identity(k)) == NULL) {
449 id = xcalloc(1, sizeof(Identity));
451 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
452 /* Increment the number of identities. */
458 id->comment = comment;
460 id->confirm = confirm;
462 send_status(e, success);
465 /* XXX todo: encrypt sensitive data with passphrase */
467 process_lock_agent(SocketEntry *e, int lock)
469 int r, success = 0, delay;
471 u_char passwdhash[LOCK_SIZE];
472 static u_int fail_count = 0;
475 if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
476 fatal("%s: buffer error: %s", __func__, ssh_err(r));
478 debug("empty password not supported");
479 } else if (locked && !lock) {
480 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
481 passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
482 fatal("bcrypt_pbkdf");
483 if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
484 debug("agent unlocked");
487 explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
490 /* delay in 0.1s increments up to 10s */
491 if (fail_count < 100)
493 delay = 100000 * fail_count;
494 debug("unlock failed, delaying %0.1lf seconds",
495 (double)delay/1000000);
498 explicit_bzero(passwdhash, sizeof(passwdhash));
499 } else if (!locked && lock) {
500 debug("agent locked");
502 arc4random_buf(lock_salt, sizeof(lock_salt));
503 if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
504 lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
505 fatal("bcrypt_pbkdf");
508 explicit_bzero(passwd, pwlen);
510 send_status(e, success);
514 no_identities(SocketEntry *e)
519 if ((msg = sshbuf_new()) == NULL)
520 fatal("%s: sshbuf_new failed", __func__);
521 if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
522 (r = sshbuf_put_u32(msg, 0)) != 0 ||
523 (r = sshbuf_put_stringb(e->output, msg)) != 0)
524 fatal("%s: buffer error: %s", __func__, ssh_err(r));
530 process_add_smartcard_key(SocketEntry *e)
532 char *provider = NULL, *pin, canonical_provider[PATH_MAX];
533 int r, i, count = 0, success = 0, confirm = 0;
537 struct sshkey **keys = NULL, *k;
540 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
541 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
542 fatal("%s: buffer error: %s", __func__, ssh_err(r));
544 while (sshbuf_len(e->request)) {
545 if ((r = sshbuf_get_u8(e->request, &type)) != 0)
546 fatal("%s: buffer error: %s", __func__, ssh_err(r));
548 case SSH_AGENT_CONSTRAIN_LIFETIME:
549 if ((r = sshbuf_get_u32(e->request, &seconds)) != 0)
550 fatal("%s: buffer error: %s",
551 __func__, ssh_err(r));
552 death = monotime() + seconds;
554 case SSH_AGENT_CONSTRAIN_CONFIRM:
558 error("%s: Unknown constraint type %d", __func__, type);
562 if (realpath(provider, canonical_provider) == NULL) {
563 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
564 provider, strerror(errno));
567 if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
568 verbose("refusing PKCS#11 add of \"%.100s\": "
569 "provider not whitelisted", canonical_provider);
572 debug("%s: add %.100s", __func__, canonical_provider);
573 if (lifetime && !death)
574 death = monotime() + lifetime;
576 count = pkcs11_add_provider(canonical_provider, pin, &keys);
577 for (i = 0; i < count; i++) {
579 if (lookup_identity(k) == NULL) {
580 id = xcalloc(1, sizeof(Identity));
582 id->provider = xstrdup(canonical_provider);
583 id->comment = xstrdup(canonical_provider); /* XXX */
585 id->confirm = confirm;
586 TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
598 send_status(e, success);
602 process_remove_smartcard_key(SocketEntry *e)
604 char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
608 if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
609 (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0)
610 fatal("%s: buffer error: %s", __func__, ssh_err(r));
613 if (realpath(provider, canonical_provider) == NULL) {
614 verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
615 provider, strerror(errno));
619 debug("%s: remove %.100s", __func__, canonical_provider);
620 for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
621 nxt = TAILQ_NEXT(id, next);
622 /* Skip file--based keys */
623 if (id->provider == NULL)
625 if (!strcmp(canonical_provider, id->provider)) {
626 TAILQ_REMOVE(&idtab->idlist, id, next);
631 if (pkcs11_del_provider(canonical_provider) == 0)
634 error("%s: pkcs11_del_provider failed", __func__);
637 send_status(e, success);
639 #endif /* ENABLE_PKCS11 */
641 /* dispatch incoming messages */
644 process_message(u_int socknum)
652 if (socknum >= sockets_alloc) {
653 fatal("%s: socket number %u >= allocated %u",
654 __func__, socknum, sockets_alloc);
656 e = &sockets[socknum];
658 if (sshbuf_len(e->input) < 5)
659 return 0; /* Incomplete message header. */
660 cp = sshbuf_ptr(e->input);
661 msg_len = PEEK_U32(cp);
662 if (msg_len > AGENT_MAX_LEN) {
663 debug("%s: socket %u (fd=%d) message too long %u > %u",
664 __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
667 if (sshbuf_len(e->input) < msg_len + 4)
668 return 0; /* Incomplete message body. */
670 /* move the current input to e->request */
671 sshbuf_reset(e->request);
672 if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
673 (r = sshbuf_get_u8(e->request, &type)) != 0) {
674 if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
675 r == SSH_ERR_STRING_TOO_LARGE) {
676 debug("%s: buffer error: %s", __func__, ssh_err(r));
679 fatal("%s: buffer error: %s", __func__, ssh_err(r));
682 debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
684 /* check wheter agent is locked */
685 if (locked && type != SSH_AGENTC_UNLOCK) {
686 sshbuf_reset(e->request);
688 case SSH2_AGENTC_REQUEST_IDENTITIES:
689 /* send empty lists */
693 /* send a fail message for all other request types */
700 case SSH_AGENTC_LOCK:
701 case SSH_AGENTC_UNLOCK:
702 process_lock_agent(e, type == SSH_AGENTC_LOCK);
704 case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
705 process_remove_all_identities(e); /* safe for !WITH_SSH1 */
708 case SSH2_AGENTC_SIGN_REQUEST:
709 process_sign_request2(e);
711 case SSH2_AGENTC_REQUEST_IDENTITIES:
712 process_request_identities(e);
714 case SSH2_AGENTC_ADD_IDENTITY:
715 case SSH2_AGENTC_ADD_ID_CONSTRAINED:
716 process_add_identity(e);
718 case SSH2_AGENTC_REMOVE_IDENTITY:
719 process_remove_identity(e);
721 case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
722 process_remove_all_identities(e);
725 case SSH_AGENTC_ADD_SMARTCARD_KEY:
726 case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
727 process_add_smartcard_key(e);
729 case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
730 process_remove_smartcard_key(e);
732 #endif /* ENABLE_PKCS11 */
734 /* Unknown message. Respond with failure. */
735 error("Unknown message %d", type);
736 sshbuf_reset(e->request);
744 new_socket(sock_type type, int fd)
746 u_int i, old_alloc, new_alloc;
753 for (i = 0; i < sockets_alloc; i++)
754 if (sockets[i].type == AUTH_UNUSED) {
756 if ((sockets[i].input = sshbuf_new()) == NULL)
757 fatal("%s: sshbuf_new failed", __func__);
758 if ((sockets[i].output = sshbuf_new()) == NULL)
759 fatal("%s: sshbuf_new failed", __func__);
760 if ((sockets[i].request = sshbuf_new()) == NULL)
761 fatal("%s: sshbuf_new failed", __func__);
762 sockets[i].type = type;
765 old_alloc = sockets_alloc;
766 new_alloc = sockets_alloc + 10;
767 sockets = xreallocarray(sockets, new_alloc, sizeof(sockets[0]));
768 for (i = old_alloc; i < new_alloc; i++)
769 sockets[i].type = AUTH_UNUSED;
770 sockets_alloc = new_alloc;
771 sockets[old_alloc].fd = fd;
772 if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
773 fatal("%s: sshbuf_new failed", __func__);
774 if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
775 fatal("%s: sshbuf_new failed", __func__);
776 if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
777 fatal("%s: sshbuf_new failed", __func__);
778 sockets[old_alloc].type = type;
782 handle_socket_read(u_int socknum)
784 struct sockaddr_un sunaddr;
790 slen = sizeof(sunaddr);
791 fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
793 error("accept from AUTH_SOCKET: %s", strerror(errno));
796 if (getpeereid(fd, &euid, &egid) < 0) {
797 error("getpeereid %d failed: %s", fd, strerror(errno));
801 if ((euid != 0) && (getuid() != euid)) {
802 error("uid mismatch: peer euid %u != uid %u",
803 (u_int) euid, (u_int) getuid());
807 new_socket(AUTH_CONNECTION, fd);
812 handle_conn_read(u_int socknum)
818 if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
820 if (errno == EAGAIN || errno == EINTR)
822 error("%s: read error on socket %u (fd %d): %s",
823 __func__, socknum, sockets[socknum].fd,
828 if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
829 fatal("%s: buffer error: %s", __func__, ssh_err(r));
830 explicit_bzero(buf, sizeof(buf));
831 process_message(socknum);
836 handle_conn_write(u_int socknum)
841 if (sshbuf_len(sockets[socknum].output) == 0)
842 return 0; /* shouldn't happen */
843 if ((len = write(sockets[socknum].fd,
844 sshbuf_ptr(sockets[socknum].output),
845 sshbuf_len(sockets[socknum].output))) <= 0) {
847 if (errno == EAGAIN || errno == EINTR)
849 error("%s: read error on socket %u (fd %d): %s",
850 __func__, socknum, sockets[socknum].fd,
855 if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
856 fatal("%s: buffer error: %s", __func__, ssh_err(r));
861 after_poll(struct pollfd *pfd, size_t npfd)
866 for (i = 0; i < npfd; i++) {
867 if (pfd[i].revents == 0)
869 /* Find sockets entry */
870 for (socknum = 0; socknum < sockets_alloc; socknum++) {
871 if (sockets[socknum].type != AUTH_SOCKET &&
872 sockets[socknum].type != AUTH_CONNECTION)
874 if (pfd[i].fd == sockets[socknum].fd)
877 if (socknum >= sockets_alloc) {
878 error("%s: no socket for fd %d", __func__, pfd[i].fd);
882 switch (sockets[socknum].type) {
884 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
885 handle_socket_read(socknum) != 0)
886 close_socket(&sockets[socknum]);
888 case AUTH_CONNECTION:
889 if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
890 handle_conn_read(socknum) != 0) {
891 close_socket(&sockets[socknum]);
894 if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
895 handle_conn_write(socknum) != 0)
896 close_socket(&sockets[socknum]);
905 prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp)
907 struct pollfd *pfd = *pfdp;
908 size_t i, j, npfd = 0;
911 /* Count active sockets */
912 for (i = 0; i < sockets_alloc; i++) {
913 switch (sockets[i].type) {
915 case AUTH_CONNECTION:
921 fatal("Unknown socket type %d", sockets[i].type);
925 if (npfd != *npfdp &&
926 (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
927 fatal("%s: recallocarray failed", __func__);
931 for (i = j = 0; i < sockets_alloc; i++) {
932 switch (sockets[i].type) {
934 case AUTH_CONNECTION:
935 pfd[j].fd = sockets[i].fd;
937 /* XXX backoff when input buffer full */
938 pfd[j].events = POLLIN;
939 if (sshbuf_len(sockets[i].output) > 0)
940 pfd[j].events |= POLLOUT;
948 if (parent_alive_interval != 0)
949 deadline = (deadline == 0) ? parent_alive_interval :
950 MINIMUM(deadline, parent_alive_interval);
952 *timeoutp = -1; /* INFTIM */
954 if (deadline > INT_MAX / 1000)
955 *timeoutp = INT_MAX / 1000;
957 *timeoutp = deadline * 1000;
965 if (cleanup_pid != 0 && getpid() != cleanup_pid)
967 debug("%s: cleanup", __func__);
983 cleanup_handler(int sig)
993 check_parent_exists(void)
996 * If our parent has exited then getppid() will return (pid_t)1,
997 * so testing for that should be safe.
999 if (parent_pid != -1 && getppid() != parent_pid) {
1000 /* printf("Parent has died - Authentication agent exiting.\n"); */
1010 "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
1011 " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n"
1012 " ssh-agent [-c | -s] -k\n");
1017 main(int ac, char **av)
1019 int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
1020 int sock, fd, ch, result, saved_errno;
1021 char *shell, *format, *pidstr, *agentsocket = NULL;
1022 #ifdef HAVE_SETRLIMIT
1026 extern char *optarg;
1028 char pidstrbuf[1 + 3 * sizeof pid];
1031 int timeout = -1; /* INFTIM */
1032 struct pollfd *pfd = NULL;
1035 ssh_malloc_init(); /* must be called before any mallocs */
1036 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1043 platform_disable_tracing(0); /* strict=no */
1046 OpenSSL_add_all_algorithms();
1049 __progname = ssh_get_progname(av[0]);
1052 while ((ch = getopt(ac, av, "cDdksE:a:P:t:")) != -1) {
1055 fingerprint_hash = ssh_digest_alg_by_name(optarg);
1056 if (fingerprint_hash == -1)
1057 fatal("Invalid hash algorithm \"%s\"", optarg);
1068 if (pkcs11_whitelist != NULL)
1069 fatal("-P option already specified");
1070 pkcs11_whitelist = xstrdup(optarg);
1078 if (d_flag || D_flag)
1083 if (d_flag || D_flag)
1088 agentsocket = optarg;
1091 if ((lifetime = convtime(optarg)) == -1) {
1092 fprintf(stderr, "Invalid lifetime\n");
1103 if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
1106 if (pkcs11_whitelist == NULL)
1107 pkcs11_whitelist = xstrdup(DEFAULT_PKCS11_WHITELIST);
1109 if (ac == 0 && !c_flag && !s_flag) {
1110 shell = getenv("SHELL");
1111 if (shell != NULL && (len = strlen(shell)) > 2 &&
1112 strncmp(shell + len - 3, "csh", 3) == 0)
1116 const char *errstr = NULL;
1118 pidstr = getenv(SSH_AGENTPID_ENV_NAME);
1119 if (pidstr == NULL) {
1120 fprintf(stderr, "%s not set, cannot kill agent\n",
1121 SSH_AGENTPID_ENV_NAME);
1124 pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
1127 "%s=\"%s\", which is not a good PID: %s\n",
1128 SSH_AGENTPID_ENV_NAME, pidstr, errstr);
1131 if (kill(pid, SIGTERM) == -1) {
1135 format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
1136 printf(format, SSH_AUTHSOCKET_ENV_NAME);
1137 printf(format, SSH_AGENTPID_ENV_NAME);
1138 printf("echo Agent pid %ld killed;\n", (long)pid);
1141 parent_pid = getpid();
1143 if (agentsocket == NULL) {
1144 /* Create private directory for agent socket */
1145 mktemp_proto(socket_dir, sizeof(socket_dir));
1146 if (mkdtemp(socket_dir) == NULL) {
1147 perror("mkdtemp: private socket dir");
1150 snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
1153 /* Try to use specified agent socket */
1154 socket_dir[0] = '\0';
1155 strlcpy(socket_name, agentsocket, sizeof socket_name);
1159 * Create socket early so it will exist before command gets run from
1162 prev_mask = umask(0177);
1163 sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
1165 /* XXX - unix_listener() calls error() not perror() */
1166 *socket_name = '\0'; /* Don't unlink any existing file */
1172 * Fork, and have the parent execute the command, if any, or present
1173 * the socket data. The child continues as the authentication agent.
1175 if (D_flag || d_flag) {
1176 log_init(__progname,
1177 d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
1178 SYSLOG_FACILITY_AUTH, 1);
1179 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1180 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1181 SSH_AUTHSOCKET_ENV_NAME);
1182 printf("echo Agent pid %ld;\n", (long)parent_pid);
1191 if (pid != 0) { /* Parent - execute the given command. */
1193 snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
1195 format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
1196 printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
1197 SSH_AUTHSOCKET_ENV_NAME);
1198 printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
1199 SSH_AGENTPID_ENV_NAME);
1200 printf("echo Agent pid %ld;\n", (long)pid);
1203 if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
1204 setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
1213 log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
1215 if (setsid() == -1) {
1216 error("setsid: %s", strerror(errno));
1221 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1222 /* XXX might close listen socket */
1223 (void)dup2(fd, STDIN_FILENO);
1224 (void)dup2(fd, STDOUT_FILENO);
1225 (void)dup2(fd, STDERR_FILENO);
1230 #ifdef HAVE_SETRLIMIT
1231 /* deny core dumps, since memory contains unencrypted private keys */
1232 rlim.rlim_cur = rlim.rlim_max = 0;
1233 if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
1234 error("setrlimit RLIMIT_CORE: %s", strerror(errno));
1241 cleanup_pid = getpid();
1243 #ifdef ENABLE_PKCS11
1246 new_socket(AUTH_SOCKET, sock);
1248 parent_alive_interval = 10;
1250 signal(SIGPIPE, SIG_IGN);
1251 signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
1252 signal(SIGHUP, cleanup_handler);
1253 signal(SIGTERM, cleanup_handler);
1255 if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
1256 fatal("%s: pledge: %s", __progname, strerror(errno));
1257 platform_pledge_agent();
1260 prepare_poll(&pfd, &npfd, &timeout);
1261 result = poll(pfd, npfd, timeout);
1262 saved_errno = errno;
1263 if (parent_alive_interval != 0)
1264 check_parent_exists();
1265 (void) reaper(); /* remove expired keys */
1267 if (saved_errno == EINTR)
1269 fatal("poll: %s", strerror(saved_errno));
1270 } else if (result > 0)
1271 after_poll(pfd, npfd);