xref: /freebsd/crypto/openssh/authfd.c (revision 2574974648c68c738aec3ff96644d888d7913a37)
1 /* $OpenBSD: authfd.c,v 1.141 2026/03/05 05:44:15 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Functions for connecting the local authentication agent.
7  *
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".
13  *
14  * SSH2 implementation,
15  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include "includes.h"
39 
40 #include <sys/types.h>
41 #include <sys/un.h>
42 #include <sys/socket.h>
43 
44 #include <fcntl.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <stdarg.h>
48 #include <unistd.h>
49 #include <errno.h>
50 
51 #include "ssh.h"
52 #include "sshbuf.h"
53 #include "sshkey.h"
54 #include "authfd.h"
55 #include "log.h"
56 #include "misc.h"
57 #include "atomicio.h"
58 #include "ssherr.h"
59 #include "xmalloc.h"
60 
61 #define MAX_AGENT_IDENTITIES	2048		/* Max keys in agent reply */
62 #define MAX_AGENT_REPLY_LEN	(256 * 1024)	/* Max bytes in agent reply */
63 
64 /* macro to check for "agent failure" message */
65 #define agent_failed(x) \
66     ((x == SSH_AGENT_FAILURE) || \
67     (x == SSH_AGENT_EXTENSION_FAILURE) || \
68     (x == SSH_COM_AGENT2_FAILURE) || \
69     (x == SSH2_AGENT_FAILURE))
70 
71 /* Convert success/failure response from agent to a err.h status */
72 static int
decode_reply(u_char type)73 decode_reply(u_char type)
74 {
75 	if (agent_failed(type))
76 		return SSH_ERR_AGENT_FAILURE;
77 	else if (type == SSH_AGENT_SUCCESS)
78 		return 0;
79 	else
80 		return SSH_ERR_INVALID_FORMAT;
81 }
82 
83 /*
84  * Opens an authentication socket at the provided path and stores the file
85  * descriptor in fdp. Returns 0 on success and an error on failure.
86  */
87 int
ssh_get_authentication_socket_path(const char * authsocket,int * fdp)88 ssh_get_authentication_socket_path(const char *authsocket, int *fdp)
89 {
90 	int sock, oerrno;
91 	struct sockaddr_un sunaddr;
92 
93 	debug3_f("path '%s'", authsocket);
94 	memset(&sunaddr, 0, sizeof(sunaddr));
95 	sunaddr.sun_family = AF_UNIX;
96 	strlcpy(sunaddr.sun_path, authsocket, sizeof(sunaddr.sun_path));
97 
98 	if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
99 		return SSH_ERR_SYSTEM_ERROR;
100 
101 	/* close on exec */
102 	if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1 ||
103 	    connect(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
104 		oerrno = errno;
105 		close(sock);
106 		errno = oerrno;
107 		return SSH_ERR_SYSTEM_ERROR;
108 	}
109 	if (fdp != NULL)
110 		*fdp = sock;
111 	else
112 		close(sock);
113 	return 0;
114 }
115 
116 /*
117  * Opens the default authentication socket and stores the file descriptor in
118  * fdp. Returns 0 on success and an error on failure.
119  */
120 int
ssh_get_authentication_socket(int * fdp)121 ssh_get_authentication_socket(int *fdp)
122 {
123 	const char *authsocket;
124 
125 	if (fdp != NULL)
126 		*fdp = -1;
127 
128 	authsocket = getenv(SSH_AUTHSOCKET_ENV_NAME);
129 	if (authsocket == NULL || *authsocket == '\0')
130 		return SSH_ERR_AGENT_NOT_PRESENT;
131 
132 	return ssh_get_authentication_socket_path(authsocket, fdp);
133 }
134 
135 /* Communicate with agent: send request and read reply */
136 static int
ssh_request_reply(int sock,struct sshbuf * request,struct sshbuf * reply)137 ssh_request_reply(int sock, struct sshbuf *request, struct sshbuf *reply)
138 {
139 	int r;
140 	size_t l, len;
141 	char buf[1024];
142 
143 	/* Get the length of the message, and format it in the buffer. */
144 	len = sshbuf_len(request);
145 	POKE_U32(buf, len);
146 
147 	/* Send the length and then the packet to the agent. */
148 	if (atomicio(vwrite, sock, buf, 4) != 4 ||
149 	    atomicio(vwrite, sock, sshbuf_mutable_ptr(request),
150 	    sshbuf_len(request)) != sshbuf_len(request))
151 		return SSH_ERR_AGENT_COMMUNICATION;
152 	/*
153 	 * Wait for response from the agent.  First read the length of the
154 	 * response packet.
155 	 */
156 	if (atomicio(read, sock, buf, 4) != 4)
157 	    return SSH_ERR_AGENT_COMMUNICATION;
158 
159 	/* Extract the length, and check it for sanity. */
160 	len = PEEK_U32(buf);
161 	if (len > MAX_AGENT_REPLY_LEN)
162 		return SSH_ERR_INVALID_FORMAT;
163 
164 	/* Read the rest of the response in to the buffer. */
165 	sshbuf_reset(reply);
166 	while (len > 0) {
167 		l = len;
168 		if (l > sizeof(buf))
169 			l = sizeof(buf);
170 		if (atomicio(read, sock, buf, l) != l)
171 			return SSH_ERR_AGENT_COMMUNICATION;
172 		if ((r = sshbuf_put(reply, buf, l)) != 0)
173 			return r;
174 		len -= l;
175 	}
176 	return 0;
177 }
178 
179 /* Communicate with agent: sent request, read and decode status reply */
180 static int
ssh_request_reply_decode(int sock,struct sshbuf * request)181 ssh_request_reply_decode(int sock, struct sshbuf *request)
182 {
183 	struct sshbuf *reply;
184 	int r;
185 	u_char type;
186 
187 	if ((reply = sshbuf_new()) == NULL)
188 		return SSH_ERR_ALLOC_FAIL;
189 	if ((r = ssh_request_reply(sock, request, reply)) != 0 ||
190 	    (r = sshbuf_get_u8(reply, &type)) != 0 ||
191 	    (r = decode_reply(type)) != 0)
192 		goto out;
193 	/* success */
194 	r = 0;
195  out:
196 	sshbuf_free(reply);
197 	return r;
198 }
199 
200 /*
201  * Closes the agent socket if it should be closed (depends on how it was
202  * obtained).  The argument must have been returned by
203  * ssh_get_authentication_socket().
204  */
205 void
ssh_close_authentication_socket(int sock)206 ssh_close_authentication_socket(int sock)
207 {
208 	if (getenv(SSH_AUTHSOCKET_ENV_NAME))
209 		close(sock);
210 }
211 
212 /* Lock/unlock agent */
213 int
ssh_lock_agent(int sock,int lock,const char * password)214 ssh_lock_agent(int sock, int lock, const char *password)
215 {
216 	int r;
217 	u_char type = lock ? SSH_AGENTC_LOCK : SSH_AGENTC_UNLOCK;
218 	struct sshbuf *msg;
219 
220 	if ((msg = sshbuf_new()) == NULL)
221 		return SSH_ERR_ALLOC_FAIL;
222 	if ((r = sshbuf_put_u8(msg, type)) != 0 ||
223 	    (r = sshbuf_put_cstring(msg, password)) != 0 ||
224 	    (r = ssh_request_reply_decode(sock, msg)) != 0)
225 		goto out;
226 	/* success */
227 	r = 0;
228  out:
229 	sshbuf_free(msg);
230 	return r;
231 }
232 
233 
234 static int
deserialise_identity2(struct sshbuf * ids,struct sshkey ** keyp,char ** commentp)235 deserialise_identity2(struct sshbuf *ids, struct sshkey **keyp, char **commentp)
236 {
237 	int r;
238 	char *comment = NULL;
239 	const u_char *blob;
240 	size_t blen;
241 
242 	if ((r = sshbuf_get_string_direct(ids, &blob, &blen)) != 0 ||
243 	    (r = sshbuf_get_cstring(ids, &comment, NULL)) != 0)
244 		goto out;
245 	if ((r = sshkey_from_blob(blob, blen, keyp)) != 0)
246 		goto out;
247 	if (commentp != NULL) {
248 		*commentp = comment;
249 		comment = NULL;
250 	}
251 	r = 0;
252  out:
253 	free(comment);
254 	return r;
255 }
256 
257 /*
258  * Fetch list of identities held by the agent.
259  */
260 int
ssh_fetch_identitylist(int sock,struct ssh_identitylist ** idlp)261 ssh_fetch_identitylist(int sock, struct ssh_identitylist **idlp)
262 {
263 	u_char type;
264 	uint32_t num, i;
265 	struct sshbuf *msg;
266 	struct ssh_identitylist *idl = NULL;
267 	int r;
268 
269 	/*
270 	 * Send a message to the agent requesting for a list of the
271 	 * identities it can represent.
272 	 */
273 	if ((msg = sshbuf_new()) == NULL)
274 		return SSH_ERR_ALLOC_FAIL;
275 	if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_REQUEST_IDENTITIES)) != 0)
276 		goto out;
277 
278 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
279 		goto out;
280 
281 	/* Get message type, and verify that we got a proper answer. */
282 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
283 		goto out;
284 	if (agent_failed(type)) {
285 		r = SSH_ERR_AGENT_FAILURE;
286 		goto out;
287 	} else if (type != SSH2_AGENT_IDENTITIES_ANSWER) {
288 		r = SSH_ERR_INVALID_FORMAT;
289 		goto out;
290 	}
291 
292 	/* Get the number of entries in the response and check it for sanity. */
293 	if ((r = sshbuf_get_u32(msg, &num)) != 0)
294 		goto out;
295 	if (num > MAX_AGENT_IDENTITIES) {
296 		r = SSH_ERR_INVALID_FORMAT;
297 		goto out;
298 	}
299 	if (num == 0) {
300 		r = SSH_ERR_AGENT_NO_IDENTITIES;
301 		goto out;
302 	}
303 
304 	/* Deserialise the response into a list of keys/comments */
305 	if ((idl = calloc(1, sizeof(*idl))) == NULL ||
306 	    (idl->keys = calloc(num, sizeof(*idl->keys))) == NULL ||
307 	    (idl->comments = calloc(num, sizeof(*idl->comments))) == NULL) {
308 		r = SSH_ERR_ALLOC_FAIL;
309 		goto out;
310 	}
311 	for (i = 0; i < num;) {
312 		if ((r = deserialise_identity2(msg, &(idl->keys[i]),
313 		    &(idl->comments[i]))) != 0) {
314 			if (r == SSH_ERR_KEY_TYPE_UNKNOWN) {
315 				/* Gracefully skip unknown key types */
316 				num--;
317 				continue;
318 			} else
319 				goto out;
320 		}
321 		i++;
322 	}
323 	idl->nkeys = num;
324 	*idlp = idl;
325 	idl = NULL;
326 	r = 0;
327  out:
328 	sshbuf_free(msg);
329 	if (idl != NULL)
330 		ssh_free_identitylist(idl);
331 	return r;
332 }
333 
334 void
ssh_free_identitylist(struct ssh_identitylist * idl)335 ssh_free_identitylist(struct ssh_identitylist *idl)
336 {
337 	size_t i;
338 
339 	if (idl == NULL)
340 		return;
341 	for (i = 0; i < idl->nkeys; i++) {
342 		if (idl->keys != NULL)
343 			sshkey_free(idl->keys[i]);
344 		if (idl->comments != NULL)
345 			free(idl->comments[i]);
346 	}
347 	free(idl->keys);
348 	free(idl->comments);
349 	free(idl);
350 }
351 
352 /*
353  * Check if the ssh agent has a given key.
354  * Returns 0 if found, or a negative SSH_ERR_* error code on failure.
355  */
356 int
ssh_agent_has_key(int sock,const struct sshkey * key)357 ssh_agent_has_key(int sock, const struct sshkey *key)
358 {
359 	int r, ret = SSH_ERR_KEY_NOT_FOUND;
360 	size_t i;
361 	struct ssh_identitylist *idlist = NULL;
362 
363 	if ((r = ssh_fetch_identitylist(sock, &idlist)) != 0) {
364 		return r;
365 	}
366 
367 	for (i = 0; i < idlist->nkeys; i++) {
368 		if (sshkey_equal_public(idlist->keys[i], key)) {
369 			ret = 0;
370 			break;
371 		}
372 	}
373 
374 	ssh_free_identitylist(idlist);
375 	return ret;
376 }
377 
378 /*
379  * Sends a challenge (typically from a server via ssh(1)) to the agent,
380  * and waits for a response from the agent.
381  * Returns true (non-zero) if the agent gave the correct answer, zero
382  * otherwise.
383  */
384 
385 
386 /* encode signature algorithm in flag bits, so we can keep the msg format */
387 static u_int
agent_encode_alg(const struct sshkey * key,const char * alg)388 agent_encode_alg(const struct sshkey *key, const char *alg)
389 {
390 	if (alg != NULL && sshkey_type_plain(key->type) == KEY_RSA) {
391 		if (strcmp(alg, "rsa-sha2-256") == 0 ||
392 		    strcmp(alg, "rsa-sha2-256-cert-v01@openssh.com") == 0)
393 			return SSH_AGENT_RSA_SHA2_256;
394 		if (strcmp(alg, "rsa-sha2-512") == 0 ||
395 		    strcmp(alg, "rsa-sha2-512-cert-v01@openssh.com") == 0)
396 			return SSH_AGENT_RSA_SHA2_512;
397 	}
398 	return 0;
399 }
400 
401 /* ask agent to sign data, returns err.h code on error, 0 on success */
402 int
ssh_agent_sign(int sock,const struct sshkey * key,u_char ** sigp,size_t * lenp,const u_char * data,size_t datalen,const char * alg,u_int compat)403 ssh_agent_sign(int sock, const struct sshkey *key,
404     u_char **sigp, size_t *lenp,
405     const u_char *data, size_t datalen, const char *alg, u_int compat)
406 {
407 	struct sshbuf *msg;
408 	u_char *sig = NULL, type = 0;
409 	size_t len = 0;
410 	u_int flags = 0;
411 	int r = SSH_ERR_INTERNAL_ERROR;
412 
413 	*sigp = NULL;
414 	*lenp = 0;
415 
416 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
417 		return SSH_ERR_INVALID_ARGUMENT;
418 	if ((msg = sshbuf_new()) == NULL)
419 		return SSH_ERR_ALLOC_FAIL;
420 	flags |= agent_encode_alg(key, alg);
421 	if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_SIGN_REQUEST)) != 0 ||
422 	    (r = sshkey_puts(key, msg)) != 0 ||
423 	    (r = sshbuf_put_string(msg, data, datalen)) != 0 ||
424 	    (r = sshbuf_put_u32(msg, flags)) != 0)
425 		goto out;
426 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
427 		goto out;
428 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
429 		goto out;
430 	if (agent_failed(type)) {
431 		r = SSH_ERR_AGENT_FAILURE;
432 		goto out;
433 	} else if (type != SSH2_AGENT_SIGN_RESPONSE) {
434 		r = SSH_ERR_INVALID_FORMAT;
435 		goto out;
436 	}
437 	if ((r = sshbuf_get_string(msg, &sig, &len)) != 0)
438 		goto out;
439 	/*
440 	 * Check what we actually got back from the agent, in case it returned
441 	 * an incorrect RSA signature algorithm (e.g. "ssh-rsa" (RSA/SHA1) vs.
442 	 * "rsa-sha2-256").
443 	 * We don't do this for FIDO signatures as webauthn vs plain are just
444 	 * different signature formats and not entirely different algorithms.
445 	 */
446 	if (!sshkey_is_sk(key) &&
447 	    (r = sshkey_check_sigtype(sig, len, alg)) != 0)
448 		goto out;
449 	/* success */
450 	*sigp = sig;
451 	*lenp = len;
452 	sig = NULL;
453 	len = 0;
454 	r = 0;
455  out:
456 	freezero(sig, len);
457 	sshbuf_free(msg);
458 	return r;
459 }
460 
461 /* Encode key for a message to the agent. */
462 
463 static int
encode_dest_constraint_hop(struct sshbuf * m,const struct dest_constraint_hop * dch)464 encode_dest_constraint_hop(struct sshbuf *m,
465     const struct dest_constraint_hop *dch)
466 {
467 	struct sshbuf *b;
468 	u_int i;
469 	int r;
470 
471 	if ((b = sshbuf_new()) == NULL)
472 		return SSH_ERR_ALLOC_FAIL;
473 	if ((r = sshbuf_put_cstring(b, dch->user)) != 0 ||
474 	    (r = sshbuf_put_cstring(b, dch->hostname)) != 0 ||
475 	    (r = sshbuf_put_string(b, NULL, 0)) != 0) /* reserved */
476 		goto out;
477 	for (i = 0; i < dch->nkeys; i++) {
478 		if ((r = sshkey_puts(dch->keys[i], b)) != 0 ||
479 		    (r = sshbuf_put_u8(b, dch->key_is_ca[i] != 0)) != 0)
480 			goto out;
481 	}
482 	if ((r = sshbuf_put_stringb(m, b)) != 0)
483 		goto out;
484 	/* success */
485 	r = 0;
486  out:
487 	sshbuf_free(b);
488 	return r;
489 }
490 
491 static int
encode_dest_constraint(struct sshbuf * m,const struct dest_constraint * dc)492 encode_dest_constraint(struct sshbuf *m, const struct dest_constraint *dc)
493 {
494 	struct sshbuf *b;
495 	int r;
496 
497 	if ((b = sshbuf_new()) == NULL)
498 		return SSH_ERR_ALLOC_FAIL;
499 	if ((r = encode_dest_constraint_hop(b, &dc->from)) != 0 ||
500 	    (r = encode_dest_constraint_hop(b, &dc->to)) != 0 ||
501 	    (r = sshbuf_put_string(b, NULL, 0)) != 0) /* reserved */
502 		goto out;
503 	if ((r = sshbuf_put_stringb(m, b)) != 0)
504 		goto out;
505 	/* success */
506 	r = 0;
507  out:
508 	sshbuf_free(b);
509 	return r;
510 }
511 
512 static int
encode_constraints(struct sshbuf * m,u_int life,u_int confirm,const char * provider,struct dest_constraint ** dest_constraints,size_t ndest_constraints,int cert_only,struct sshkey ** certs,size_t ncerts)513 encode_constraints(struct sshbuf *m, u_int life, u_int confirm,
514     const char *provider,
515     struct dest_constraint **dest_constraints, size_t ndest_constraints,
516     int cert_only, struct sshkey **certs, size_t ncerts)
517 {
518 	int r;
519 	struct sshbuf *b = NULL;
520 	size_t i;
521 
522 	if (life != 0) {
523 		if ((r = sshbuf_put_u8(m, SSH_AGENT_CONSTRAIN_LIFETIME)) != 0 ||
524 		    (r = sshbuf_put_u32(m, life)) != 0)
525 			goto out;
526 	}
527 	if (confirm != 0) {
528 		if ((r = sshbuf_put_u8(m, SSH_AGENT_CONSTRAIN_CONFIRM)) != 0)
529 			goto out;
530 	}
531 	if (provider != NULL) {
532 		if ((r = sshbuf_put_u8(m,
533 		    SSH_AGENT_CONSTRAIN_EXTENSION)) != 0 ||
534 		    (r = sshbuf_put_cstring(m,
535 		    "sk-provider@openssh.com")) != 0 ||
536 		    (r = sshbuf_put_cstring(m, provider)) != 0)
537 			goto out;
538 	}
539 	if (dest_constraints != NULL && ndest_constraints > 0) {
540 		if ((b = sshbuf_new()) == NULL) {
541 			r = SSH_ERR_ALLOC_FAIL;
542 			goto out;
543 		}
544 		for (i = 0; i < ndest_constraints; i++) {
545 			if ((r = encode_dest_constraint(b,
546 			    dest_constraints[i])) != 0)
547 				goto out;
548 		}
549 		if ((r = sshbuf_put_u8(m,
550 		    SSH_AGENT_CONSTRAIN_EXTENSION)) != 0 ||
551 		    (r = sshbuf_put_cstring(m,
552 		    "restrict-destination-v00@openssh.com")) != 0 ||
553 		    (r = sshbuf_put_stringb(m, b)) != 0)
554 			goto out;
555 		sshbuf_free(b);
556 		b = NULL;
557 	}
558 	if (ncerts != 0) {
559 		if ((b = sshbuf_new()) == NULL) {
560 			r = SSH_ERR_ALLOC_FAIL;
561 			goto out;
562 		}
563 		for (i = 0; i < ncerts; i++) {
564 			if ((r = sshkey_puts(certs[i], b)) != 0)
565 				goto out;
566 		}
567 		if ((r = sshbuf_put_u8(m,
568 		    SSH_AGENT_CONSTRAIN_EXTENSION)) != 0 ||
569 		    (r = sshbuf_put_cstring(m,
570 		    "associated-certs-v00@openssh.com")) != 0 ||
571 		    (r = sshbuf_put_u8(m, cert_only != 0)) != 0 ||
572 		    (r = sshbuf_put_stringb(m, b)) != 0)
573 			goto out;
574 		sshbuf_free(b);
575 		b = NULL;
576 	}
577 	r = 0;
578  out:
579 	sshbuf_free(b);
580 	return r;
581 }
582 
583 /*
584  * Adds an identity to the authentication server.
585  * This call is intended only for use by ssh-add(1) and like applications.
586  */
587 int
ssh_add_identity_constrained(int sock,struct sshkey * key,const char * comment,u_int life,u_int confirm,const char * provider,struct dest_constraint ** dest_constraints,size_t ndest_constraints)588 ssh_add_identity_constrained(int sock, struct sshkey *key,
589     const char *comment, u_int life, u_int confirm,
590     const char *provider, struct dest_constraint **dest_constraints,
591     size_t ndest_constraints)
592 {
593 	struct sshbuf *msg;
594 	int r, constrained = (life || confirm || provider || dest_constraints);
595 	u_char type;
596 
597 	if ((msg = sshbuf_new()) == NULL)
598 		return SSH_ERR_ALLOC_FAIL;
599 
600 	switch (key->type) {
601 #ifdef WITH_OPENSSL
602 	case KEY_RSA:
603 	case KEY_RSA_CERT:
604 	case KEY_ECDSA:
605 	case KEY_ECDSA_CERT:
606 	case KEY_ECDSA_SK:
607 	case KEY_ECDSA_SK_CERT:
608 #endif
609 	case KEY_ED25519:
610 	case KEY_ED25519_CERT:
611 	case KEY_ED25519_SK:
612 	case KEY_ED25519_SK_CERT:
613 		type = constrained ?
614 		    SSH2_AGENTC_ADD_ID_CONSTRAINED :
615 		    SSH2_AGENTC_ADD_IDENTITY;
616 		if ((r = sshbuf_put_u8(msg, type)) != 0 ||
617 		    (r = sshkey_private_serialize(key, msg)) != 0 ||
618 		    (r = sshbuf_put_cstring(msg, comment)) != 0)
619 			goto out;
620 		break;
621 	default:
622 		r = SSH_ERR_INVALID_ARGUMENT;
623 		goto out;
624 	}
625 	if (constrained &&
626 	    (r = encode_constraints(msg, life, confirm, provider,
627 	    dest_constraints, ndest_constraints, 0, NULL, 0)) != 0)
628 		goto out;
629 	if ((r = ssh_request_reply_decode(sock, msg)) != 0)
630 		goto out;
631 	/* success */
632 	r = 0;
633  out:
634 	sshbuf_free(msg);
635 	return r;
636 }
637 
638 /*
639  * Removes an identity from the authentication server.
640  * This call is intended only for use by ssh-add(1) and like applications.
641  */
642 int
ssh_remove_identity(int sock,const struct sshkey * key)643 ssh_remove_identity(int sock, const struct sshkey *key)
644 {
645 	struct sshbuf *msg;
646 	int r;
647 	u_char *blob = NULL;
648 	size_t blen;
649 
650 	if ((msg = sshbuf_new()) == NULL)
651 		return SSH_ERR_ALLOC_FAIL;
652 
653 	if (key->type != KEY_UNSPEC) {
654 		if ((r = sshkey_to_blob(key, &blob, &blen)) != 0)
655 			goto out;
656 		if ((r = sshbuf_put_u8(msg,
657 		    SSH2_AGENTC_REMOVE_IDENTITY)) != 0 ||
658 		    (r = sshbuf_put_string(msg, blob, blen)) != 0)
659 			goto out;
660 	} else {
661 		r = SSH_ERR_INVALID_ARGUMENT;
662 		goto out;
663 	}
664 	if ((r = ssh_request_reply_decode(sock, msg)) != 0)
665 		goto out;
666 	/* success */
667 	r = 0;
668  out:
669 	if (blob != NULL)
670 		freezero(blob, blen);
671 	sshbuf_free(msg);
672 	return r;
673 }
674 
675 /*
676  * Add/remove an token-based identity from the authentication server.
677  * This call is intended only for use by ssh-add(1) and like applications.
678  */
679 int
ssh_update_card(int sock,int add,const char * reader_id,const char * pin,u_int life,u_int confirm,struct dest_constraint ** dest_constraints,size_t ndest_constraints,int cert_only,struct sshkey ** certs,size_t ncerts)680 ssh_update_card(int sock, int add, const char *reader_id, const char *pin,
681     u_int life, u_int confirm,
682     struct dest_constraint **dest_constraints, size_t ndest_constraints,
683     int cert_only, struct sshkey **certs, size_t ncerts)
684 {
685 	struct sshbuf *msg;
686 	int r, constrained = (life || confirm || dest_constraints || certs);
687 	u_char type;
688 
689 	if (add) {
690 		type = constrained ?
691 		    SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED :
692 		    SSH_AGENTC_ADD_SMARTCARD_KEY;
693 	} else
694 		type = SSH_AGENTC_REMOVE_SMARTCARD_KEY;
695 
696 	if ((msg = sshbuf_new()) == NULL)
697 		return SSH_ERR_ALLOC_FAIL;
698 	if ((r = sshbuf_put_u8(msg, type)) != 0 ||
699 	    (r = sshbuf_put_cstring(msg, reader_id)) != 0 ||
700 	    (r = sshbuf_put_cstring(msg, pin)) != 0)
701 		goto out;
702 	if (constrained &&
703 	    (r = encode_constraints(msg, life, confirm, NULL,
704 	    dest_constraints, ndest_constraints,
705 	    cert_only, certs, ncerts)) != 0)
706 		goto out;
707 	if ((r = ssh_request_reply_decode(sock, msg)) != 0)
708 		goto out;
709 	/* success */
710 	r = 0;
711  out:
712 	sshbuf_free(msg);
713 	return r;
714 }
715 
716 /*
717  * Removes all identities from the agent.
718  * This call is intended only for use by ssh-add(1) and like applications.
719  *
720  * This supports the SSH protocol 1 message to because, when clearing all
721  * keys from an agent, we generally want to clear both protocol v1 and v2
722  * keys.
723  */
724 int
ssh_remove_all_identities(int sock,int version)725 ssh_remove_all_identities(int sock, int version)
726 {
727 	struct sshbuf *msg;
728 	u_char type = (version == 1) ?
729 	    SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES :
730 	    SSH2_AGENTC_REMOVE_ALL_IDENTITIES;
731 	int r;
732 
733 	if ((msg = sshbuf_new()) == NULL)
734 		return SSH_ERR_ALLOC_FAIL;
735 	if ((r = sshbuf_put_u8(msg, type)) != 0)
736 		goto out;
737 	if ((r = ssh_request_reply_decode(sock, msg)) != 0)
738 		goto out;
739 	/* success */
740 	r = 0;
741  out:
742 	sshbuf_free(msg);
743 	return r;
744 }
745 
746 /* Binds a session ID to a hostkey via the initial KEX signature. */
747 int
ssh_agent_bind_hostkey(int sock,const struct sshkey * key,const struct sshbuf * session_id,const struct sshbuf * signature,int forwarding)748 ssh_agent_bind_hostkey(int sock, const struct sshkey *key,
749     const struct sshbuf *session_id, const struct sshbuf *signature,
750     int forwarding)
751 {
752 	struct sshbuf *msg;
753 	int r;
754 
755 	if (key == NULL || session_id == NULL || signature == NULL)
756 		return SSH_ERR_INVALID_ARGUMENT;
757 	if ((msg = sshbuf_new()) == NULL)
758 		return SSH_ERR_ALLOC_FAIL;
759 	if ((r = sshbuf_put_u8(msg, SSH_AGENTC_EXTENSION)) != 0 ||
760 	    (r = sshbuf_put_cstring(msg, "session-bind@openssh.com")) != 0 ||
761 	    (r = sshkey_puts(key, msg)) != 0 ||
762 	    (r = sshbuf_put_stringb(msg, session_id)) != 0 ||
763 	    (r = sshbuf_put_stringb(msg, signature)) != 0 ||
764 	    (r = sshbuf_put_u8(msg, forwarding ? 1 : 0)) != 0)
765 		goto out;
766 	if ((r = ssh_request_reply_decode(sock, msg)) != 0)
767 		goto out;
768 	/* success */
769 	r = 0;
770  out:
771 	sshbuf_free(msg);
772 	return r;
773 }
774 
775 /* Queries supported extension request types */
776 int
ssh_agent_query_extensions(int sock,char *** exts)777 ssh_agent_query_extensions(int sock, char ***exts)
778 {
779 	struct sshbuf *msg;
780 	int r;
781 	u_char type;
782 	char *cp = NULL, **ret = NULL;
783 	size_t i = 0;
784 
785 	*exts = NULL;
786 	if ((msg = sshbuf_new()) == NULL)
787 		return SSH_ERR_ALLOC_FAIL;
788 	if ((r = sshbuf_put_u8(msg, SSH_AGENTC_EXTENSION)) != 0 ||
789 	    (r = sshbuf_put_cstring(msg, "query")) != 0)
790 		goto out;
791 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
792 		goto out;
793 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
794 		goto out;
795 	if (agent_failed(type)) {
796 		r = SSH_ERR_AGENT_FAILURE;
797 		goto out;
798 	}
799 	/* Reply should start with "query" */
800 	if (type != SSH_AGENT_EXTENSION_RESPONSE ||
801 	   (r = sshbuf_get_cstring(msg, &cp, NULL)) != 0 ||
802 	   strcmp(cp, "query") != 0) {
803 		r = SSH_ERR_INVALID_FORMAT;
804 		goto out;
805 	}
806 	ret = calloc(1, sizeof(*ret));
807 	while (sshbuf_len(msg)) {
808 		ret = xrecallocarray(ret, i + 1, i + 2, sizeof(*ret));
809 		if ((r = sshbuf_get_cstring(msg, ret + i, NULL)) != 0) {
810 			r = SSH_ERR_INVALID_FORMAT;
811 			goto out;
812 		}
813 		i++;
814 	}
815 	/* success */
816 	r = 0;
817 	*exts = ret;
818 	ret = NULL; /* transferred */
819  out:
820 	free(cp);
821 	stringlist_free(ret);
822 	sshbuf_free(msg);
823 	return r;
824 }
825