xref: /freebsd/crypto/openssh/authfd.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * Functions for connecting the local authentication agent.
6  *
7  * As far as I am concerned, the code I have written for this software
8  * can be used freely for any purpose.  Any derived versions of this
9  * software must be clearly marked as such, and if the derived work is
10  * incompatible with the protocol description in the RFC file, it must be
11  * called by a name other than "ssh" or "Secure Shell".
12  *
13  * SSH2 implementation,
14  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
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.
24  *
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.
35  */
36 
37 #include "includes.h"
38 RCSID("$OpenBSD: authfd.c,v 1.39 2001/04/05 10:42:48 markus Exp $");
39 RCSID("$FreeBSD$");
40 
41 #include <openssl/evp.h>
42 
43 #include "ssh.h"
44 #include "rsa.h"
45 #include "buffer.h"
46 #include "bufaux.h"
47 #include "xmalloc.h"
48 #include "getput.h"
49 #include "key.h"
50 #include "authfd.h"
51 #include "cipher.h"
52 #include "kex.h"
53 #include "compat.h"
54 #include "log.h"
55 #include "atomicio.h"
56 
57 /* helper */
58 int	decode_reply(int type);
59 
60 /* macro to check for "agent failure" message */
61 #define agent_failed(x) \
62     ((x == SSH_AGENT_FAILURE) || (x == SSH_COM_AGENT2_FAILURE))
63 
64 /* Returns the number of the authentication fd, or -1 if there is none. */
65 
66 int
67 ssh_get_authentication_socket(void)
68 {
69 	const char *authsocket;
70 	int sock, len;
71 	struct sockaddr_un sunaddr;
72 
73 	authsocket = getenv(SSH_AUTHSOCKET_ENV_NAME);
74 	if (!authsocket)
75 		return -1;
76 
77 	sunaddr.sun_family = AF_UNIX;
78 	strlcpy(sunaddr.sun_path, authsocket, sizeof(sunaddr.sun_path));
79 	len = SUN_LEN(&sunaddr)+1;
80 	sunaddr.sun_len = len;
81 
82 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
83 	if (sock < 0)
84 		return -1;
85 
86 	/* close on exec */
87 	if (fcntl(sock, F_SETFD, 1) == -1) {
88 		close(sock);
89 		return -1;
90 	}
91 	if (connect(sock, (struct sockaddr *) & sunaddr, len) < 0) {
92 		close(sock);
93 		return -1;
94 	}
95 	return sock;
96 }
97 
98 int
99 ssh_request_reply(AuthenticationConnection *auth, Buffer *request, Buffer *reply)
100 {
101 	int l, len;
102 	char buf[1024];
103 
104 	/* Get the length of the message, and format it in the buffer. */
105 	len = buffer_len(request);
106 	PUT_32BIT(buf, len);
107 
108 	/* Send the length and then the packet to the agent. */
109 	if (atomicio(write, auth->fd, buf, 4) != 4 ||
110 	    atomicio(write, auth->fd, buffer_ptr(request),
111 	    buffer_len(request)) != buffer_len(request)) {
112 		error("Error writing to authentication socket.");
113 		return 0;
114 	}
115 	/*
116 	 * Wait for response from the agent.  First read the length of the
117 	 * response packet.
118 	 */
119 	len = 4;
120 	while (len > 0) {
121 		l = read(auth->fd, buf + 4 - len, len);
122 		if (l == -1 && (errno == EAGAIN || errno == EINTR))
123 			continue;
124 		if (l <= 0) {
125 			error("Error reading response length from authentication socket.");
126 			return 0;
127 		}
128 		len -= l;
129 	}
130 
131 	/* Extract the length, and check it for sanity. */
132 	len = GET_32BIT(buf);
133 	if (len > 256 * 1024)
134 		fatal("Authentication response too long: %d", len);
135 
136 	/* Read the rest of the response in to the buffer. */
137 	buffer_clear(reply);
138 	while (len > 0) {
139 		l = len;
140 		if (l > sizeof(buf))
141 			l = sizeof(buf);
142 		l = read(auth->fd, buf, l);
143 		if (l == -1 && (errno == EAGAIN || errno == EINTR))
144 			continue;
145 		if (l <= 0) {
146 			error("Error reading response from authentication socket.");
147 			return 0;
148 		}
149 		buffer_append(reply, (char *) buf, l);
150 		len -= l;
151 	}
152 	return 1;
153 }
154 
155 /*
156  * Closes the agent socket if it should be closed (depends on how it was
157  * obtained).  The argument must have been returned by
158  * ssh_get_authentication_socket().
159  */
160 
161 void
162 ssh_close_authentication_socket(int sock)
163 {
164 	if (getenv(SSH_AUTHSOCKET_ENV_NAME))
165 		close(sock);
166 }
167 
168 /*
169  * Opens and connects a private socket for communication with the
170  * authentication agent.  Returns the file descriptor (which must be
171  * shut down and closed by the caller when no longer needed).
172  * Returns NULL if an error occurred and the connection could not be
173  * opened.
174  */
175 
176 AuthenticationConnection *
177 ssh_get_authentication_connection(void)
178 {
179 	AuthenticationConnection *auth;
180 	int sock;
181 
182 	sock = ssh_get_authentication_socket();
183 
184 	/*
185 	 * Fail if we couldn't obtain a connection.  This happens if we
186 	 * exited due to a timeout.
187 	 */
188 	if (sock < 0)
189 		return NULL;
190 
191 	auth = xmalloc(sizeof(*auth));
192 	auth->fd = sock;
193 	buffer_init(&auth->identities);
194 	auth->howmany = 0;
195 
196 	return auth;
197 }
198 
199 /*
200  * Closes the connection to the authentication agent and frees any associated
201  * memory.
202  */
203 
204 void
205 ssh_close_authentication_connection(AuthenticationConnection *auth)
206 {
207 	buffer_free(&auth->identities);
208 	close(auth->fd);
209 	xfree(auth);
210 }
211 
212 /*
213  * Returns the first authentication identity held by the agent.
214  */
215 
216 int
217 ssh_get_num_identities(AuthenticationConnection *auth, int version)
218 {
219 	int type, code1 = 0, code2 = 0;
220 	Buffer request;
221 
222 	switch(version){
223 	case 1:
224 		code1 = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
225 		code2 = SSH_AGENT_RSA_IDENTITIES_ANSWER;
226 		break;
227 	case 2:
228 		code1 = SSH2_AGENTC_REQUEST_IDENTITIES;
229 		code2 = SSH2_AGENT_IDENTITIES_ANSWER;
230 		break;
231 	default:
232 		return 0;
233 	}
234 
235 	/*
236 	 * Send a message to the agent requesting for a list of the
237 	 * identities it can represent.
238 	 */
239 	buffer_init(&request);
240 	buffer_put_char(&request, code1);
241 
242 	buffer_clear(&auth->identities);
243 	if (ssh_request_reply(auth, &request, &auth->identities) == 0) {
244 		buffer_free(&request);
245 		return 0;
246 	}
247 	buffer_free(&request);
248 
249 	/* Get message type, and verify that we got a proper answer. */
250 	type = buffer_get_char(&auth->identities);
251 	if (agent_failed(type)) {
252 		return 0;
253 	} else if (type != code2) {
254 		fatal("Bad authentication reply message type: %d", type);
255 	}
256 
257 	/* Get the number of entries in the response and check it for sanity. */
258 	auth->howmany = buffer_get_int(&auth->identities);
259 	if (auth->howmany > 1024)
260 		fatal("Too many identities in authentication reply: %d",
261 		    auth->howmany);
262 
263 	return auth->howmany;
264 }
265 
266 Key *
267 ssh_get_first_identity(AuthenticationConnection *auth, char **comment, int version)
268 {
269 	/* get number of identities and return the first entry (if any). */
270 	if (ssh_get_num_identities(auth, version) > 0)
271 		return ssh_get_next_identity(auth, comment, version);
272 	return NULL;
273 }
274 
275 Key *
276 ssh_get_next_identity(AuthenticationConnection *auth, char **comment, int version)
277 {
278 	u_int bits;
279 	u_char *blob;
280 	u_int blen;
281 	Key *key = NULL;
282 
283 	/* Return failure if no more entries. */
284 	if (auth->howmany <= 0)
285 		return NULL;
286 
287 	/*
288 	 * Get the next entry from the packet.  These will abort with a fatal
289 	 * error if the packet is too short or contains corrupt data.
290 	 */
291 	switch(version){
292 	case 1:
293 		key = key_new(KEY_RSA1);
294 		bits = buffer_get_int(&auth->identities);
295 		buffer_get_bignum(&auth->identities, key->rsa->e);
296 		buffer_get_bignum(&auth->identities, key->rsa->n);
297 		*comment = buffer_get_string(&auth->identities, NULL);
298 		if (bits != BN_num_bits(key->rsa->n))
299 			log("Warning: identity keysize mismatch: actual %d, announced %u",
300 			    BN_num_bits(key->rsa->n), bits);
301 		break;
302 	case 2:
303 		blob = buffer_get_string(&auth->identities, &blen);
304 		*comment = buffer_get_string(&auth->identities, NULL);
305 		key = key_from_blob(blob, blen);
306 		xfree(blob);
307 		break;
308 	default:
309 		return NULL;
310 		break;
311 	}
312 	/* Decrement the number of remaining entries. */
313 	auth->howmany--;
314 	return key;
315 }
316 
317 /*
318  * Generates a random challenge, sends it to the agent, and waits for
319  * response from the agent.  Returns true (non-zero) if the agent gave the
320  * correct answer, zero otherwise.  Response type selects the style of
321  * response desired, with 0 corresponding to protocol version 1.0 (no longer
322  * supported) and 1 corresponding to protocol version 1.1.
323  */
324 
325 int
326 ssh_decrypt_challenge(AuthenticationConnection *auth,
327     Key* key, BIGNUM *challenge,
328     u_char session_id[16],
329     u_int response_type,
330     u_char response[16])
331 {
332 	Buffer buffer;
333 	int success = 0;
334 	int i;
335 	int type;
336 
337 	if (key->type != KEY_RSA1)
338 		return 0;
339 	if (response_type == 0) {
340 		log("Compatibility with ssh protocol version 1.0 no longer supported.");
341 		return 0;
342 	}
343 	buffer_init(&buffer);
344 	buffer_put_char(&buffer, SSH_AGENTC_RSA_CHALLENGE);
345 	buffer_put_int(&buffer, BN_num_bits(key->rsa->n));
346 	buffer_put_bignum(&buffer, key->rsa->e);
347 	buffer_put_bignum(&buffer, key->rsa->n);
348 	buffer_put_bignum(&buffer, challenge);
349 	buffer_append(&buffer, (char *) session_id, 16);
350 	buffer_put_int(&buffer, response_type);
351 
352 	if (ssh_request_reply(auth, &buffer, &buffer) == 0) {
353 		buffer_free(&buffer);
354 		return 0;
355 	}
356 	type = buffer_get_char(&buffer);
357 
358 	if (agent_failed(type)) {
359 		log("Agent admitted failure to authenticate using the key.");
360 	} else if (type != SSH_AGENT_RSA_RESPONSE) {
361 		fatal("Bad authentication response: %d", type);
362 	} else {
363 		success = 1;
364 		/*
365 		 * Get the response from the packet.  This will abort with a
366 		 * fatal error if the packet is corrupt.
367 		 */
368 		for (i = 0; i < 16; i++)
369 			response[i] = buffer_get_char(&buffer);
370 	}
371 	buffer_free(&buffer);
372 	return success;
373 }
374 
375 /* ask agent to sign data, returns -1 on error, 0 on success */
376 int
377 ssh_agent_sign(AuthenticationConnection *auth,
378     Key *key,
379     u_char **sigp, int *lenp,
380     u_char *data, int datalen)
381 {
382 	extern int datafellows;
383 	Buffer msg;
384 	u_char *blob;
385 	u_int blen;
386 	int type, flags = 0;
387 	int ret = -1;
388 
389 	if (key_to_blob(key, &blob, &blen) == 0)
390 		return -1;
391 
392 	if (datafellows & SSH_BUG_SIGBLOB)
393 		flags = SSH_AGENT_OLD_SIGNATURE;
394 
395 	buffer_init(&msg);
396 	buffer_put_char(&msg, SSH2_AGENTC_SIGN_REQUEST);
397 	buffer_put_string(&msg, blob, blen);
398 	buffer_put_string(&msg, data, datalen);
399 	buffer_put_int(&msg, flags);
400 	xfree(blob);
401 
402 	if (ssh_request_reply(auth, &msg, &msg) == 0) {
403 		buffer_free(&msg);
404 		return -1;
405 	}
406 	type = buffer_get_char(&msg);
407 	if (agent_failed(type)) {
408 		log("Agent admitted failure to sign using the key.");
409 	} else if (type != SSH2_AGENT_SIGN_RESPONSE) {
410 		fatal("Bad authentication response: %d", type);
411 	} else {
412 		ret = 0;
413 		*sigp = buffer_get_string(&msg, lenp);
414 	}
415 	buffer_free(&msg);
416 	return ret;
417 }
418 
419 /* Encode key for a message to the agent. */
420 
421 void
422 ssh_encode_identity_rsa1(Buffer *b, RSA *key, const char *comment)
423 {
424 	buffer_clear(b);
425 	buffer_put_char(b, SSH_AGENTC_ADD_RSA_IDENTITY);
426 	buffer_put_int(b, BN_num_bits(key->n));
427 	buffer_put_bignum(b, key->n);
428 	buffer_put_bignum(b, key->e);
429 	buffer_put_bignum(b, key->d);
430 	/* To keep within the protocol: p < q for ssh. in SSL p > q */
431 	buffer_put_bignum(b, key->iqmp);	/* ssh key->u */
432 	buffer_put_bignum(b, key->q);	/* ssh key->p, SSL key->q */
433 	buffer_put_bignum(b, key->p);	/* ssh key->q, SSL key->p */
434 	buffer_put_string(b, comment, strlen(comment));
435 }
436 
437 void
438 ssh_encode_identity_ssh2(Buffer *b, Key *key, const char *comment)
439 {
440 	buffer_clear(b);
441 	buffer_put_char(b, SSH2_AGENTC_ADD_IDENTITY);
442 	buffer_put_cstring(b, key_ssh_name(key));
443 	switch(key->type){
444 	case KEY_RSA:
445 		buffer_put_bignum2(b, key->rsa->n);
446 		buffer_put_bignum2(b, key->rsa->e);
447 		buffer_put_bignum2(b, key->rsa->d);
448 		buffer_put_bignum2(b, key->rsa->iqmp);
449 		buffer_put_bignum2(b, key->rsa->p);
450 		buffer_put_bignum2(b, key->rsa->q);
451 		break;
452 	case KEY_DSA:
453 		buffer_put_bignum2(b, key->dsa->p);
454 		buffer_put_bignum2(b, key->dsa->q);
455 		buffer_put_bignum2(b, key->dsa->g);
456 		buffer_put_bignum2(b, key->dsa->pub_key);
457 		buffer_put_bignum2(b, key->dsa->priv_key);
458 		break;
459 	}
460 	buffer_put_cstring(b, comment);
461 }
462 
463 /*
464  * Adds an identity to the authentication server.  This call is not meant to
465  * be used by normal applications.
466  */
467 
468 int
469 ssh_add_identity(AuthenticationConnection *auth, Key *key, const char *comment)
470 {
471 	Buffer msg;
472 	int type;
473 
474 	buffer_init(&msg);
475 
476 	switch (key->type) {
477 	case KEY_RSA1:
478 		ssh_encode_identity_rsa1(&msg, key->rsa, comment);
479 		break;
480 	case KEY_RSA:
481 	case KEY_DSA:
482 		ssh_encode_identity_ssh2(&msg, key, comment);
483 		break;
484 	default:
485 		buffer_free(&msg);
486 		return 0;
487 		break;
488 	}
489 	if (ssh_request_reply(auth, &msg, &msg) == 0) {
490 		buffer_free(&msg);
491 		return 0;
492 	}
493 	type = buffer_get_char(&msg);
494 	buffer_free(&msg);
495 	return decode_reply(type);
496 }
497 
498 /*
499  * Removes an identity from the authentication server.  This call is not
500  * meant to be used by normal applications.
501  */
502 
503 int
504 ssh_remove_identity(AuthenticationConnection *auth, Key *key)
505 {
506 	Buffer msg;
507 	int type;
508 	u_char *blob;
509 	u_int blen;
510 
511 	buffer_init(&msg);
512 
513 	if (key->type == KEY_RSA1) {
514 		buffer_put_char(&msg, SSH_AGENTC_REMOVE_RSA_IDENTITY);
515 		buffer_put_int(&msg, BN_num_bits(key->rsa->n));
516 		buffer_put_bignum(&msg, key->rsa->e);
517 		buffer_put_bignum(&msg, key->rsa->n);
518 	} else if (key->type == KEY_DSA || key->type == KEY_RSA) {
519 		key_to_blob(key, &blob, &blen);
520 		buffer_put_char(&msg, SSH2_AGENTC_REMOVE_IDENTITY);
521 		buffer_put_string(&msg, blob, blen);
522 		xfree(blob);
523 	} else {
524 		buffer_free(&msg);
525 		return 0;
526 	}
527 	if (ssh_request_reply(auth, &msg, &msg) == 0) {
528 		buffer_free(&msg);
529 		return 0;
530 	}
531 	type = buffer_get_char(&msg);
532 	buffer_free(&msg);
533 	return decode_reply(type);
534 }
535 
536 /*
537  * Removes all identities from the agent.  This call is not meant to be used
538  * by normal applications.
539  */
540 
541 int
542 ssh_remove_all_identities(AuthenticationConnection *auth, int version)
543 {
544 	Buffer msg;
545 	int type;
546 	int code = (version==1) ?
547 		SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES :
548 		SSH2_AGENTC_REMOVE_ALL_IDENTITIES;
549 
550 	buffer_init(&msg);
551 	buffer_put_char(&msg, code);
552 
553 	if (ssh_request_reply(auth, &msg, &msg) == 0) {
554 		buffer_free(&msg);
555 		return 0;
556 	}
557 	type = buffer_get_char(&msg);
558 	buffer_free(&msg);
559 	return decode_reply(type);
560 }
561 
562 int
563 decode_reply(int type)
564 {
565 	switch (type) {
566 	case SSH_AGENT_FAILURE:
567 	case SSH_COM_AGENT2_FAILURE:
568 		log("SSH_AGENT_FAILURE");
569 		return 0;
570 	case SSH_AGENT_SUCCESS:
571 		return 1;
572 	default:
573 		fatal("Bad response from authentication agent: %d", type);
574 	}
575 	/* NOTREACHED */
576 	return 0;
577 }
578