xref: /openbsd/usr.bin/ssh/authfd.c (revision d493747f)
1 /* $OpenBSD: authfd.c,v 1.120 2019/11/13 04:47:52 deraadt 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 
39 #include <sys/types.h>
40 #include <sys/un.h>
41 #include <sys/socket.h>
42 
43 #include <fcntl.h>
44 #include <stdlib.h>
45 #include <signal.h>
46 #include <string.h>
47 #include <stdarg.h>
48 #include <unistd.h>
49 #include <errno.h>
50 
51 #include "xmalloc.h"
52 #include "ssh.h"
53 #include "sshbuf.h"
54 #include "sshkey.h"
55 #include "authfd.h"
56 #include "cipher.h"
57 #include "compat.h"
58 #include "log.h"
59 #include "atomicio.h"
60 #include "misc.h"
61 #include "ssherr.h"
62 
63 #define MAX_AGENT_IDENTITIES	2048		/* Max keys in agent reply */
64 #define MAX_AGENT_REPLY_LEN	(256 * 1024) 	/* Max bytes in agent reply */
65 
66 /* macro to check for "agent failure" message */
67 #define agent_failed(x) \
68     ((x == SSH_AGENT_FAILURE) || \
69     (x == SSH_COM_AGENT2_FAILURE) || \
70     (x == SSH2_AGENT_FAILURE))
71 
72 /* Convert success/failure response from agent to a err.h status */
73 static int
74 decode_reply(u_char type)
75 {
76 	if (agent_failed(type))
77 		return SSH_ERR_AGENT_FAILURE;
78 	else if (type == SSH_AGENT_SUCCESS)
79 		return 0;
80 	else
81 		return SSH_ERR_INVALID_FORMAT;
82 }
83 
84 /* Returns the number of the authentication fd, or -1 if there is none. */
85 int
86 ssh_get_authentication_socket(int *fdp)
87 {
88 	const char *authsocket;
89 	int sock, oerrno;
90 	struct sockaddr_un sunaddr;
91 
92 	if (fdp != NULL)
93 		*fdp = -1;
94 
95 	authsocket = getenv(SSH_AUTHSOCKET_ENV_NAME);
96 	if (authsocket == NULL || *authsocket == '\0')
97 		return SSH_ERR_AGENT_NOT_PRESENT;
98 
99 	memset(&sunaddr, 0, sizeof(sunaddr));
100 	sunaddr.sun_family = AF_UNIX;
101 	strlcpy(sunaddr.sun_path, authsocket, sizeof(sunaddr.sun_path));
102 
103 	if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
104 		return SSH_ERR_SYSTEM_ERROR;
105 
106 	/* close on exec */
107 	if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1 ||
108 	    connect(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
109 		oerrno = errno;
110 		close(sock);
111 		errno = oerrno;
112 		return SSH_ERR_SYSTEM_ERROR;
113 	}
114 	if (fdp != NULL)
115 		*fdp = sock;
116 	else
117 		close(sock);
118 	return 0;
119 }
120 
121 /* Communicate with agent: send request and read reply */
122 static int
123 ssh_request_reply(int sock, struct sshbuf *request, struct sshbuf *reply)
124 {
125 	int r;
126 	size_t l, len;
127 	char buf[1024];
128 
129 	/* Get the length of the message, and format it in the buffer. */
130 	len = sshbuf_len(request);
131 	POKE_U32(buf, len);
132 
133 	/* Send the length and then the packet to the agent. */
134 	if (atomicio(vwrite, sock, buf, 4) != 4 ||
135 	    atomicio(vwrite, sock, sshbuf_mutable_ptr(request),
136 	    sshbuf_len(request)) != sshbuf_len(request))
137 		return SSH_ERR_AGENT_COMMUNICATION;
138 	/*
139 	 * Wait for response from the agent.  First read the length of the
140 	 * response packet.
141 	 */
142 	if (atomicio(read, sock, buf, 4) != 4)
143 	    return SSH_ERR_AGENT_COMMUNICATION;
144 
145 	/* Extract the length, and check it for sanity. */
146 	len = PEEK_U32(buf);
147 	if (len > MAX_AGENT_REPLY_LEN)
148 		return SSH_ERR_INVALID_FORMAT;
149 
150 	/* Read the rest of the response in to the buffer. */
151 	sshbuf_reset(reply);
152 	while (len > 0) {
153 		l = len;
154 		if (l > sizeof(buf))
155 			l = sizeof(buf);
156 		if (atomicio(read, sock, buf, l) != l)
157 			return SSH_ERR_AGENT_COMMUNICATION;
158 		if ((r = sshbuf_put(reply, buf, l)) != 0)
159 			return r;
160 		len -= l;
161 	}
162 	return 0;
163 }
164 
165 /*
166  * Closes the agent socket if it should be closed (depends on how it was
167  * obtained).  The argument must have been returned by
168  * ssh_get_authentication_socket().
169  */
170 void
171 ssh_close_authentication_socket(int sock)
172 {
173 	if (getenv(SSH_AUTHSOCKET_ENV_NAME))
174 		close(sock);
175 }
176 
177 /* Lock/unlock agent */
178 int
179 ssh_lock_agent(int sock, int lock, const char *password)
180 {
181 	int r;
182 	u_char type = lock ? SSH_AGENTC_LOCK : SSH_AGENTC_UNLOCK;
183 	struct sshbuf *msg;
184 
185 	if ((msg = sshbuf_new()) == NULL)
186 		return SSH_ERR_ALLOC_FAIL;
187 	if ((r = sshbuf_put_u8(msg, type)) != 0 ||
188 	    (r = sshbuf_put_cstring(msg, password)) != 0)
189 		goto out;
190 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
191 		goto out;
192 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
193 		goto out;
194 	r = decode_reply(type);
195  out:
196 	sshbuf_free(msg);
197 	return r;
198 }
199 
200 
201 static int
202 deserialise_identity2(struct sshbuf *ids, struct sshkey **keyp, char **commentp)
203 {
204 	int r;
205 	char *comment = NULL;
206 	const u_char *blob;
207 	size_t blen;
208 
209 	if ((r = sshbuf_get_string_direct(ids, &blob, &blen)) != 0 ||
210 	    (r = sshbuf_get_cstring(ids, &comment, NULL)) != 0)
211 		goto out;
212 	if ((r = sshkey_from_blob(blob, blen, keyp)) != 0)
213 		goto out;
214 	if (commentp != NULL) {
215 		*commentp = comment;
216 		comment = NULL;
217 	}
218 	r = 0;
219  out:
220 	free(comment);
221 	return r;
222 }
223 
224 /*
225  * Fetch list of identities held by the agent.
226  */
227 int
228 ssh_fetch_identitylist(int sock, struct ssh_identitylist **idlp)
229 {
230 	u_char type;
231 	u_int32_t num, i;
232 	struct sshbuf *msg;
233 	struct ssh_identitylist *idl = NULL;
234 	int r;
235 
236 	/*
237 	 * Send a message to the agent requesting for a list of the
238 	 * identities it can represent.
239 	 */
240 	if ((msg = sshbuf_new()) == NULL)
241 		return SSH_ERR_ALLOC_FAIL;
242 	if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_REQUEST_IDENTITIES)) != 0)
243 		goto out;
244 
245 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
246 		goto out;
247 
248 	/* Get message type, and verify that we got a proper answer. */
249 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
250 		goto out;
251 	if (agent_failed(type)) {
252 		r = SSH_ERR_AGENT_FAILURE;
253 		goto out;
254 	} else if (type != SSH2_AGENT_IDENTITIES_ANSWER) {
255 		r = SSH_ERR_INVALID_FORMAT;
256 		goto out;
257 	}
258 
259 	/* Get the number of entries in the response and check it for sanity. */
260 	if ((r = sshbuf_get_u32(msg, &num)) != 0)
261 		goto out;
262 	if (num > MAX_AGENT_IDENTITIES) {
263 		r = SSH_ERR_INVALID_FORMAT;
264 		goto out;
265 	}
266 	if (num == 0) {
267 		r = SSH_ERR_AGENT_NO_IDENTITIES;
268 		goto out;
269 	}
270 
271 	/* Deserialise the response into a list of keys/comments */
272 	if ((idl = calloc(1, sizeof(*idl))) == NULL ||
273 	    (idl->keys = calloc(num, sizeof(*idl->keys))) == NULL ||
274 	    (idl->comments = calloc(num, sizeof(*idl->comments))) == NULL) {
275 		r = SSH_ERR_ALLOC_FAIL;
276 		goto out;
277 	}
278 	for (i = 0; i < num;) {
279 		if ((r = deserialise_identity2(msg, &(idl->keys[i]),
280 		    &(idl->comments[i]))) != 0) {
281 			if (r == SSH_ERR_KEY_TYPE_UNKNOWN) {
282 				/* Gracefully skip unknown key types */
283 				num--;
284 				continue;
285 			} else
286 				goto out;
287 		}
288 		i++;
289 	}
290 	idl->nkeys = num;
291 	*idlp = idl;
292 	idl = NULL;
293 	r = 0;
294  out:
295 	sshbuf_free(msg);
296 	if (idl != NULL)
297 		ssh_free_identitylist(idl);
298 	return r;
299 }
300 
301 void
302 ssh_free_identitylist(struct ssh_identitylist *idl)
303 {
304 	size_t i;
305 
306 	if (idl == NULL)
307 		return;
308 	for (i = 0; i < idl->nkeys; i++) {
309 		if (idl->keys != NULL)
310 			sshkey_free(idl->keys[i]);
311 		if (idl->comments != NULL)
312 			free(idl->comments[i]);
313 	}
314 	free(idl->keys);
315 	free(idl->comments);
316 	free(idl);
317 }
318 
319 /*
320  * Check if the ssh agent has a given key.
321  * Returns 0 if found, or a negative SSH_ERR_* error code on failure.
322  */
323 int
324 ssh_agent_has_key(int sock, struct sshkey *key)
325 {
326 	int r, ret = SSH_ERR_KEY_NOT_FOUND;
327 	size_t i;
328 	struct ssh_identitylist *idlist = NULL;
329 
330 	if ((r = ssh_fetch_identitylist(sock, &idlist)) < 0) {
331 		return r;
332 	}
333 
334 	for (i = 0; i < idlist->nkeys; i++) {
335 		if (sshkey_equal_public(idlist->keys[i], key)) {
336 			ret = 0;
337 			break;
338 		}
339 	}
340 
341 	ssh_free_identitylist(idlist);
342 	return ret;
343 }
344 
345 /*
346  * Sends a challenge (typically from a server via ssh(1)) to the agent,
347  * and waits for a response from the agent.
348  * Returns true (non-zero) if the agent gave the correct answer, zero
349  * otherwise.
350  */
351 
352 
353 /* encode signature algorithm in flag bits, so we can keep the msg format */
354 static u_int
355 agent_encode_alg(const struct sshkey *key, const char *alg)
356 {
357 	if (alg != NULL && sshkey_type_plain(key->type) == KEY_RSA) {
358 		if (strcmp(alg, "rsa-sha2-256") == 0 ||
359 		    strcmp(alg, "rsa-sha2-256-cert-v01@openssh.com") == 0)
360 			return SSH_AGENT_RSA_SHA2_256;
361 		if (strcmp(alg, "rsa-sha2-512") == 0 ||
362 		    strcmp(alg, "rsa-sha2-512-cert-v01@openssh.com") == 0)
363 			return SSH_AGENT_RSA_SHA2_512;
364 	}
365 	return 0;
366 }
367 
368 /* ask agent to sign data, returns err.h code on error, 0 on success */
369 int
370 ssh_agent_sign(int sock, const struct sshkey *key,
371     u_char **sigp, size_t *lenp,
372     const u_char *data, size_t datalen, const char *alg, u_int compat)
373 {
374 	struct sshbuf *msg;
375 	u_char *sig = NULL, type = 0;
376 	size_t len = 0;
377 	u_int flags = 0;
378 	int r = SSH_ERR_INTERNAL_ERROR;
379 
380 	*sigp = NULL;
381 	*lenp = 0;
382 
383 	if (datalen > SSH_KEY_MAX_SIGN_DATA_SIZE)
384 		return SSH_ERR_INVALID_ARGUMENT;
385 	if ((msg = sshbuf_new()) == NULL)
386 		return SSH_ERR_ALLOC_FAIL;
387 	flags |= agent_encode_alg(key, alg);
388 	if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_SIGN_REQUEST)) != 0 ||
389 	    (r = sshkey_puts(key, msg)) != 0 ||
390 	    (r = sshbuf_put_string(msg, data, datalen)) != 0 ||
391 	    (r = sshbuf_put_u32(msg, flags)) != 0)
392 		goto out;
393 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
394 		goto out;
395 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
396 		goto out;
397 	if (agent_failed(type)) {
398 		r = SSH_ERR_AGENT_FAILURE;
399 		goto out;
400 	} else if (type != SSH2_AGENT_SIGN_RESPONSE) {
401 		r = SSH_ERR_INVALID_FORMAT;
402 		goto out;
403 	}
404 	if ((r = sshbuf_get_string(msg, &sig, &len)) != 0)
405 		goto out;
406 	/* Check what we actually got back from the agent. */
407 	if ((r = sshkey_check_sigtype(sig, len, alg)) != 0)
408 		goto out;
409 	/* success */
410 	*sigp = sig;
411 	*lenp = len;
412 	sig = NULL;
413 	len = 0;
414 	r = 0;
415  out:
416 	freezero(sig, len);
417 	sshbuf_free(msg);
418 	return r;
419 }
420 
421 /* Encode key for a message to the agent. */
422 
423 
424 static int
425 encode_constraints(struct sshbuf *m, u_int life, u_int confirm, u_int maxsign,
426     const char *provider)
427 {
428 	int r;
429 
430 	if (life != 0) {
431 		if ((r = sshbuf_put_u8(m, SSH_AGENT_CONSTRAIN_LIFETIME)) != 0 ||
432 		    (r = sshbuf_put_u32(m, life)) != 0)
433 			goto out;
434 	}
435 	if (confirm != 0) {
436 		if ((r = sshbuf_put_u8(m, SSH_AGENT_CONSTRAIN_CONFIRM)) != 0)
437 			goto out;
438 	}
439 	if (maxsign != 0) {
440 		if ((r = sshbuf_put_u8(m, SSH_AGENT_CONSTRAIN_MAXSIGN)) != 0 ||
441 		    (r = sshbuf_put_u32(m, maxsign)) != 0)
442 			goto out;
443 	}
444 	if (provider != NULL) {
445 		if ((r = sshbuf_put_u8(m,
446 		    SSH_AGENT_CONSTRAIN_EXTENSION)) != 0 ||
447 		    (r = sshbuf_put_cstring(m,
448 		    "sk-provider@openssh.com")) != 0 ||
449 		    (r = sshbuf_put_cstring(m, provider)) != 0)
450 			goto out;
451 	}
452 	r = 0;
453  out:
454 	return r;
455 }
456 
457 /*
458  * Adds an identity to the authentication server.
459  * This call is intended only for use by ssh-add(1) and like applications.
460  */
461 int
462 ssh_add_identity_constrained(int sock, struct sshkey *key,
463     const char *comment, u_int life, u_int confirm, u_int maxsign,
464     const char *provider)
465 {
466 	struct sshbuf *msg;
467 	int r, constrained = (life || confirm || maxsign || provider);
468 	u_char type;
469 
470 	if ((msg = sshbuf_new()) == NULL)
471 		return SSH_ERR_ALLOC_FAIL;
472 
473 	switch (key->type) {
474 #ifdef WITH_OPENSSL
475 	case KEY_RSA:
476 	case KEY_RSA_CERT:
477 	case KEY_DSA:
478 	case KEY_DSA_CERT:
479 	case KEY_ECDSA:
480 	case KEY_ECDSA_CERT:
481 	case KEY_ECDSA_SK:
482 	case KEY_ECDSA_SK_CERT:
483 #endif
484 	case KEY_ED25519:
485 	case KEY_ED25519_CERT:
486 	case KEY_ED25519_SK:
487 	case KEY_ED25519_SK_CERT:
488 	case KEY_XMSS:
489 	case KEY_XMSS_CERT:
490 		type = constrained ?
491 		    SSH2_AGENTC_ADD_ID_CONSTRAINED :
492 		    SSH2_AGENTC_ADD_IDENTITY;
493 		if ((r = sshbuf_put_u8(msg, type)) != 0 ||
494 		    (r = sshkey_private_serialize_maxsign(key, msg, maxsign,
495 		    NULL)) != 0 ||
496 		    (r = sshbuf_put_cstring(msg, comment)) != 0)
497 			goto out;
498 		break;
499 	default:
500 		r = SSH_ERR_INVALID_ARGUMENT;
501 		goto out;
502 	}
503 	if (constrained &&
504 	    (r = encode_constraints(msg, life, confirm, maxsign,
505 	    provider)) != 0)
506 		goto out;
507 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
508 		goto out;
509 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
510 		goto out;
511 	r = decode_reply(type);
512  out:
513 	sshbuf_free(msg);
514 	return r;
515 }
516 
517 /*
518  * Removes an identity from the authentication server.
519  * This call is intended only for use by ssh-add(1) and like applications.
520  */
521 int
522 ssh_remove_identity(int sock, struct sshkey *key)
523 {
524 	struct sshbuf *msg;
525 	int r;
526 	u_char type, *blob = NULL;
527 	size_t blen;
528 
529 	if ((msg = sshbuf_new()) == NULL)
530 		return SSH_ERR_ALLOC_FAIL;
531 
532 	if (key->type != KEY_UNSPEC) {
533 		if ((r = sshkey_to_blob(key, &blob, &blen)) != 0)
534 			goto out;
535 		if ((r = sshbuf_put_u8(msg,
536 		    SSH2_AGENTC_REMOVE_IDENTITY)) != 0 ||
537 		    (r = sshbuf_put_string(msg, blob, blen)) != 0)
538 			goto out;
539 	} else {
540 		r = SSH_ERR_INVALID_ARGUMENT;
541 		goto out;
542 	}
543 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
544 		goto out;
545 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
546 		goto out;
547 	r = decode_reply(type);
548  out:
549 	if (blob != NULL) {
550 		explicit_bzero(blob, blen);
551 		free(blob);
552 	}
553 	sshbuf_free(msg);
554 	return r;
555 }
556 
557 /*
558  * Add/remove an token-based identity from the authentication server.
559  * This call is intended only for use by ssh-add(1) and like applications.
560  */
561 int
562 ssh_update_card(int sock, int add, const char *reader_id, const char *pin,
563     u_int life, u_int confirm)
564 {
565 	struct sshbuf *msg;
566 	int r, constrained = (life || confirm);
567 	u_char type;
568 
569 	if (add) {
570 		type = constrained ?
571 		    SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED :
572 		    SSH_AGENTC_ADD_SMARTCARD_KEY;
573 	} else
574 		type = SSH_AGENTC_REMOVE_SMARTCARD_KEY;
575 
576 	if ((msg = sshbuf_new()) == NULL)
577 		return SSH_ERR_ALLOC_FAIL;
578 	if ((r = sshbuf_put_u8(msg, type)) != 0 ||
579 	    (r = sshbuf_put_cstring(msg, reader_id)) != 0 ||
580 	    (r = sshbuf_put_cstring(msg, pin)) != 0)
581 		goto out;
582 	if (constrained &&
583 	    (r = encode_constraints(msg, life, confirm, 0, NULL)) != 0)
584 		goto out;
585 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
586 		goto out;
587 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
588 		goto out;
589 	r = decode_reply(type);
590  out:
591 	sshbuf_free(msg);
592 	return r;
593 }
594 
595 /*
596  * Removes all identities from the agent.
597  * This call is intended only for use by ssh-add(1) and like applications.
598  *
599  * This supports the SSH protocol 1 message to because, when clearing all
600  * keys from an agent, we generally want to clear both protocol v1 and v2
601  * keys.
602  */
603 int
604 ssh_remove_all_identities(int sock, int version)
605 {
606 	struct sshbuf *msg;
607 	u_char type = (version == 1) ?
608 	    SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES :
609 	    SSH2_AGENTC_REMOVE_ALL_IDENTITIES;
610 	int r;
611 
612 	if ((msg = sshbuf_new()) == NULL)
613 		return SSH_ERR_ALLOC_FAIL;
614 	if ((r = sshbuf_put_u8(msg, type)) != 0)
615 		goto out;
616 	if ((r = ssh_request_reply(sock, msg, msg)) != 0)
617 		goto out;
618 	if ((r = sshbuf_get_u8(msg, &type)) != 0)
619 		goto out;
620 	r = decode_reply(type);
621  out:
622 	sshbuf_free(msg);
623 	return r;
624 }
625