Index | Thread | Search

From:
Damien Miller <djm@mindrot.org>
Subject:
ssh-add: connect to agent after getopt() done
To:
tech@openbsd.org
Cc:
openssh@openssh.com
Date:
Fri, 26 Jun 2026 11:49:49 +1000

Download raw body.

Thread
Hi,

This is trivial: make ssh-agent finish getopt() processing before it
attempts to connect to the agent. This allows -v to work better.

ok?

diff --git a/authfd.c b/authfd.c
index b442915..274931a 100644
--- a/authfd.c
+++ b/authfd.c
@@ -204,7 +204,7 @@ ssh_request_reply_decode(int sock, struct sshbuf *request)
 void
 ssh_close_authentication_socket(int sock)
 {
-	if (getenv(SSH_AUTHSOCKET_ENV_NAME))
+	if (sock != -1 && getenv(SSH_AUTHSOCKET_ENV_NAME) != NULL)
 		close(sock);
 }
 
diff --git a/ssh-add.c b/ssh-add.c
index 2788f7e..5d3ff4d 100644
--- a/ssh-add.c
+++ b/ssh-add.c
@@ -806,7 +806,7 @@ main(int argc, char **argv)
 {
 	extern char *optarg;
 	extern int optind;
-	int agent_fd;
+	int agent_fd = -1;
 	char *pkcs11provider = NULL, *skprovider = NULL;
 	char **dest_constraint_strings = NULL, **hostkey_files = NULL;
 	int r, i, ch, deleting = 0, ret = 0, key_only = 0, cert_only = 0;
@@ -825,19 +825,6 @@ main(int argc, char **argv)
 
 	setvbuf(stdout, NULL, _IOLBF, 0);
 
-	/* First, get a connection to the authentication agent. */
-	switch (r = ssh_get_authentication_socket(&agent_fd)) {
-	case 0:
-		break;
-	case SSH_ERR_AGENT_NOT_PRESENT:
-		fprintf(stderr, "Could not open a connection to your "
-		    "authentication agent.\n");
-		exit(2);
-	default:
-		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
-		exit(2);
-	}
-
 	skprovider = getenv("SSH_SK_PROVIDER");
 
 	while ((ch = getopt(argc, argv, "vkKlLNCcdDTxXE:e:h:H:M:m:Qqs:S:t:")) != -1) {
@@ -933,7 +920,21 @@ main(int argc, char **argv)
 
 	if ((xflag != 0) + (lflag != 0) + (Dflag != 0) + (Qflag != 0) > 1)
 		fatal("Invalid combination of actions");
-	else if (xflag) {
+
+	/* First, get a connection to the authentication agent. */
+	switch (r = ssh_get_authentication_socket(&agent_fd)) {
+	case 0:
+		break;
+	case SSH_ERR_AGENT_NOT_PRESENT:
+		fprintf(stderr, "Could not open a connection to your "
+		    "authentication agent.\n");
+		exit(2);
+	default:
+		fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
+		exit(2);
+	}
+
+	if (xflag) {
 		if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
 			ret = 1;
 		goto done;