1/* $OpenBSD: authfd.c,v 1.86 2011/07/06 18:09:21 tedu 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 <openssl/evp.h>
45
46#include <openssl/crypto.h>
47#include <fcntl.h>
48#include <stdlib.h>
49#include <signal.h>
50#include <stdarg.h>
51#include <string.h>
52#include <unistd.h>
53
54#include "xmalloc.h"
55#include "ssh.h"
56#include "rsa.h"
57#include "buffer.h"
58#include "key.h"
59#include "authfd.h"
60#include "cipher.h"
61#include "kex.h"
62#include "compat.h"
63#include "log.h"
64#include "atomicio.h"
65#include "misc.h"
66
67static int agent_present = 0;
68
69/* helper */
70int	decode_reply(int type);
71
72/* macro to check for "agent failure" message */
73#define agent_failed(x) \
74    ((x == SSH_AGENT_FAILURE) || (x == SSH_COM_AGENT2_FAILURE) || \
75    (x == SSH2_AGENT_FAILURE))
76
77int
78ssh_agent_present(void)
79{
80	int authfd;
81
82	if (agent_present)
83		return 1;
84	if ((authfd = ssh_get_authentication_socket()) == -1)
85		return 0;
86	else {
87		ssh_close_authentication_socket(authfd);
88		return 1;
89	}
90}
91
92/* Returns the number of the authentication fd, or -1 if there is none. */
93
94int
95ssh_get_authentication_socket(void)
96{
97	const char *authsocket;
98	int sock;
99	struct sockaddr_un sunaddr;
100
101	authsocket = getenv(SSH_AUTHSOCKET_ENV_NAME);
102	if (!authsocket)
103		return -1;
104
105	bzero(&sunaddr, sizeof(sunaddr));
106	sunaddr.sun_family = AF_UNIX;
107	strlcpy(sunaddr.sun_path, authsocket, sizeof(sunaddr.sun_path));
108
109	sock = socket(AF_UNIX, SOCK_STREAM, 0);
110	if (sock < 0)
111		return -1;
112
113	/* close on exec */
114	if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
115		close(sock);
116		return -1;
117	}
118	if (connect(sock, (struct sockaddr *)&sunaddr, sizeof sunaddr) < 0) {
119		close(sock);
120		return -1;
121	}
122	agent_present = 1;
123	return sock;
124}
125
126static int
127ssh_request_reply(AuthenticationConnection *auth, Buffer *request, Buffer *reply)
128{
129	u_int l, len;
130	char buf[1024];
131
132	/* Get the length of the message, and format it in the buffer. */
133	len = buffer_len(request);
134	put_u32(buf, len);
135
136	/* Send the length and then the packet to the agent. */
137	if (atomicio(vwrite, auth->fd, buf, 4) != 4 ||
138	    atomicio(vwrite, auth->fd, buffer_ptr(request),
139	    buffer_len(request)) != buffer_len(request)) {
140		error("Error writing to authentication socket.");
141		return 0;
142	}
143	/*
144	 * Wait for response from the agent.  First read the length of the
145	 * response packet.
146	 */
147	if (atomicio(read, auth->fd, buf, 4) != 4) {
148	    error("Error reading response length from authentication socket.");
149	    return 0;
150	}
151
152	/* Extract the length, and check it for sanity. */
153	len = get_u32(buf);
154	if (len > 256 * 1024)
155		fatal("Authentication response too long: %u", len);
156
157	/* Read the rest of the response in to the buffer. */
158	buffer_clear(reply);
159	while (len > 0) {
160		l = len;
161		if (l > sizeof(buf))
162			l = sizeof(buf);
163		if (atomicio(read, auth->fd, buf, l) != l) {
164			error("Error reading response from authentication socket.");
165			return 0;
166		}
167		buffer_append(reply, buf, l);
168		len -= l;
169	}
170	return 1;
171}
172
173/*
174 * Closes the agent socket if it should be closed (depends on how it was
175 * obtained).  The argument must have been returned by
176 * ssh_get_authentication_socket().
177 */
178
179void
180ssh_close_authentication_socket(int sock)
181{
182	if (getenv(SSH_AUTHSOCKET_ENV_NAME))
183		close(sock);
184}
185
186/*
187 * Opens and connects a private socket for communication with the
188 * authentication agent.  Returns the file descriptor (which must be
189 * shut down and closed by the caller when no longer needed).
190 * Returns NULL if an error occurred and the connection could not be
191 * opened.
192 */
193
194AuthenticationConnection *
195ssh_get_authentication_connection(void)
196{
197	AuthenticationConnection *auth;
198	int sock;
199
200	sock = ssh_get_authentication_socket();
201
202	/*
203	 * Fail if we couldn't obtain a connection.  This happens if we
204	 * exited due to a timeout.
205	 */
206	if (sock < 0)
207		return NULL;
208
209	auth = xmalloc(sizeof(*auth));
210	auth->fd = sock;
211	buffer_init(&auth->identities);
212	auth->howmany = 0;
213
214	return auth;
215}
216
217/*
218 * Closes the connection to the authentication agent and frees any associated
219 * memory.
220 */
221
222void
223ssh_close_authentication_connection(AuthenticationConnection *auth)
224{
225	buffer_free(&auth->identities);
226	close(auth->fd);
227	xfree(auth);
228}
229
230/* Lock/unlock agent */
231int
232ssh_lock_agent(AuthenticationConnection *auth, int lock, const char *password)
233{
234	int type;
235	Buffer msg;
236
237	buffer_init(&msg);
238	buffer_put_char(&msg, lock ? SSH_AGENTC_LOCK : SSH_AGENTC_UNLOCK);
239	buffer_put_cstring(&msg, password);
240
241	if (ssh_request_reply(auth, &msg, &msg) == 0) {
242		buffer_free(&msg);
243		return 0;
244	}
245	type = buffer_get_char(&msg);
246	buffer_free(&msg);
247	return decode_reply(type);
248}
249
250/*
251 * Returns the first authentication identity held by the agent.
252 */
253
254int
255ssh_get_num_identities(AuthenticationConnection *auth, int version)
256{
257	int type, code1 = 0, code2 = 0;
258	Buffer request;
259
260	switch (version) {
261	case 1:
262		code1 = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
263		code2 = SSH_AGENT_RSA_IDENTITIES_ANSWER;
264		break;
265	case 2:
266		code1 = SSH2_AGENTC_REQUEST_IDENTITIES;
267		code2 = SSH2_AGENT_IDENTITIES_ANSWER;
268		break;
269	default:
270		return 0;
271	}
272
273	/*
274	 * Send a message to the agent requesting for a list of the
275	 * identities it can represent.
276	 */
277	buffer_init(&request);
278	buffer_put_char(&request, code1);
279
280	buffer_clear(&auth->identities);
281	if (ssh_request_reply(auth, &request, &auth->identities) == 0) {
282		buffer_free(&request);
283		return 0;
284	}
285	buffer_free(&request);
286
287	/* Get message type, and verify that we got a proper answer. */
288	type = buffer_get_char(&auth->identities);
289	if (agent_failed(type)) {
290		return 0;
291	} else if (type != code2) {
292		fatal("Bad authentication reply message type: %d", type);
293	}
294
295	/* Get the number of entries in the response and check it for sanity. */
296	auth->howmany = buffer_get_int(&auth->identities);
297	if ((u_int)auth->howmany > 1024)
298		fatal("Too many identities in authentication reply: %d",
299		    auth->howmany);
300
301	return auth->howmany;
302}
303
304Key *
305ssh_get_first_identity(AuthenticationConnection *auth, char **comment, int version)
306{
307	/* get number of identities and return the first entry (if any). */
308	if (ssh_get_num_identities(auth, version) > 0)
309		return ssh_get_next_identity(auth, comment, version);
310	return NULL;
311}
312
313Key *
314ssh_get_next_identity(AuthenticationConnection *auth, char **comment, int version)
315{
316	int keybits;
317	u_int bits;
318	u_char *blob;
319	u_int blen;
320	Key *key = NULL;
321
322	/* Return failure if no more entries. */
323	if (auth->howmany <= 0)
324		return NULL;
325
326	/*
327	 * Get the next entry from the packet.  These will abort with a fatal
328	 * error if the packet is too short or contains corrupt data.
329	 */
330	switch (version) {
331	case 1:
332		key = key_new(KEY_RSA1);
333		bits = buffer_get_int(&auth->identities);
334		buffer_get_bignum(&auth->identities, key->rsa->e);
335		buffer_get_bignum(&auth->identities, key->rsa->n);
336		*comment = buffer_get_string(&auth->identities, NULL);
337		keybits = BN_num_bits(key->rsa->n);
338		if (keybits < 0 || bits != (u_int)keybits)
339			logit("Warning: identity keysize mismatch: actual %d, announced %u",
340			    BN_num_bits(key->rsa->n), bits);
341		break;
342	case 2:
343		blob = buffer_get_string(&auth->identities, &blen);
344		*comment = buffer_get_string(&auth->identities, NULL);
345		key = key_from_blob(blob, blen);
346		xfree(blob);
347		break;
348	default:
349		return NULL;
350	}
351	/* Decrement the number of remaining entries. */
352	auth->howmany--;
353	return key;
354}
355
356/*
357 * Generates a random challenge, sends it to the agent, and waits for
358 * response from the agent.  Returns true (non-zero) if the agent gave the
359 * correct answer, zero otherwise.  Response type selects the style of
360 * response desired, with 0 corresponding to protocol version 1.0 (no longer
361 * supported) and 1 corresponding to protocol version 1.1.
362 */
363
364int
365ssh_decrypt_challenge(AuthenticationConnection *auth,
366    Key* key, BIGNUM *challenge,
367    u_char session_id[16],
368    u_int response_type,
369    u_char response[16])
370{
371	Buffer buffer;
372	int success = 0;
373	int i;
374	int type;
375
376	if (key->type != KEY_RSA1)
377		return 0;
378	if (response_type == 0) {
379		logit("Compatibility with ssh protocol version 1.0 no longer supported.");
380		return 0;
381	}
382	buffer_init(&buffer);
383	buffer_put_char(&buffer, SSH_AGENTC_RSA_CHALLENGE);
384	buffer_put_int(&buffer, BN_num_bits(key->rsa->n));
385	buffer_put_bignum(&buffer, key->rsa->e);
386	buffer_put_bignum(&buffer, key->rsa->n);
387	buffer_put_bignum(&buffer, challenge);
388	buffer_append(&buffer, session_id, 16);
389	buffer_put_int(&buffer, response_type);
390
391	if (ssh_request_reply(auth, &buffer, &buffer) == 0) {
392		buffer_free(&buffer);
393		return 0;
394	}
395	type = buffer_get_char(&buffer);
396
397	if (agent_failed(type)) {
398		logit("Agent admitted failure to authenticate using the key.");
399	} else if (type != SSH_AGENT_RSA_RESPONSE) {
400		fatal("Bad authentication response: %d", type);
401	} else {
402		success = 1;
403		/*
404		 * Get the response from the packet.  This will abort with a
405		 * fatal error if the packet is corrupt.
406		 */
407		for (i = 0; i < 16; i++)
408			response[i] = (u_char)buffer_get_char(&buffer);
409	}
410	buffer_free(&buffer);
411	return success;
412}
413
414/* ask agent to sign data, returns -1 on error, 0 on success */
415int
416ssh_agent_sign(AuthenticationConnection *auth,
417    Key *key,
418    u_char **sigp, u_int *lenp,
419    u_char *data, u_int datalen)
420{
421	extern int datafellows;
422	Buffer msg;
423	u_char *blob;
424	u_int blen;
425	int type, flags = 0;
426	int ret = -1;
427
428	if (key_to_blob(key, &blob, &blen) == 0)
429		return -1;
430
431	if (datafellows & SSH_BUG_SIGBLOB)
432		flags = SSH_AGENT_OLD_SIGNATURE;
433
434	buffer_init(&msg);
435	buffer_put_char(&msg, SSH2_AGENTC_SIGN_REQUEST);
436	buffer_put_string(&msg, blob, blen);
437	buffer_put_string(&msg, data, datalen);
438	buffer_put_int(&msg, flags);
439	xfree(blob);
440
441	if (ssh_request_reply(auth, &msg, &msg) == 0) {
442		buffer_free(&msg);
443		return -1;
444	}
445	type = buffer_get_char(&msg);
446	if (agent_failed(type)) {
447		logit("Agent admitted failure to sign using the key.");
448	} else if (type != SSH2_AGENT_SIGN_RESPONSE) {
449		fatal("Bad authentication response: %d", type);
450	} else {
451		ret = 0;
452		*sigp = buffer_get_string(&msg, lenp);
453	}
454	buffer_free(&msg);
455	return ret;
456}
457
458/* Encode key for a message to the agent. */
459
460static void
461ssh_encode_identity_rsa1(Buffer *b, RSA *key, const char *comment)
462{
463	buffer_put_int(b, BN_num_bits(key->n));
464	buffer_put_bignum(b, key->n);
465	buffer_put_bignum(b, key->e);
466	buffer_put_bignum(b, key->d);
467	/* To keep within the protocol: p < q for ssh. in SSL p > q */
468	buffer_put_bignum(b, key->iqmp);	/* ssh key->u */
469	buffer_put_bignum(b, key->q);	/* ssh key->p, SSL key->q */
470	buffer_put_bignum(b, key->p);	/* ssh key->q, SSL key->p */
471	buffer_put_cstring(b, comment);
472}
473
474static void
475ssh_encode_identity_ssh2(Buffer *b, Key *key, const char *comment)
476{
477	buffer_put_cstring(b, key_ssh_name(key));
478	switch (key->type) {
479	case KEY_RSA:
480		buffer_put_bignum2(b, key->rsa->n);
481		buffer_put_bignum2(b, key->rsa->e);
482		buffer_put_bignum2(b, key->rsa->d);
483		buffer_put_bignum2(b, key->rsa->iqmp);
484		buffer_put_bignum2(b, key->rsa->p);
485		buffer_put_bignum2(b, key->rsa->q);
486		break;
487	case KEY_RSA_CERT_V00:
488	case KEY_RSA_CERT:
489		if (key->cert == NULL || buffer_len(&key->cert->certblob) == 0)
490			fatal("%s: no cert/certblob", __func__);
491		buffer_put_string(b, buffer_ptr(&key->cert->certblob),
492		    buffer_len(&key->cert->certblob));
493		buffer_put_bignum2(b, key->rsa->d);
494		buffer_put_bignum2(b, key->rsa->iqmp);
495		buffer_put_bignum2(b, key->rsa->p);
496		buffer_put_bignum2(b, key->rsa->q);
497		break;
498	case KEY_DSA:
499		buffer_put_bignum2(b, key->dsa->p);
500		buffer_put_bignum2(b, key->dsa->q);
501		buffer_put_bignum2(b, key->dsa->g);
502		buffer_put_bignum2(b, key->dsa->pub_key);
503		buffer_put_bignum2(b, key->dsa->priv_key);
504		break;
505	case KEY_DSA_CERT_V00:
506	case KEY_DSA_CERT:
507		if (key->cert == NULL || buffer_len(&key->cert->certblob) == 0)
508			fatal("%s: no cert/certblob", __func__);
509		buffer_put_string(b, buffer_ptr(&key->cert->certblob),
510		    buffer_len(&key->cert->certblob));
511		buffer_put_bignum2(b, key->dsa->priv_key);
512		break;
513#ifdef OPENSSL_HAS_ECC
514	case KEY_ECDSA:
515		buffer_put_cstring(b, key_curve_nid_to_name(key->ecdsa_nid));
516		buffer_put_ecpoint(b, EC_KEY_get0_group(key->ecdsa),
517		    EC_KEY_get0_public_key(key->ecdsa));
518		buffer_put_bignum2(b, EC_KEY_get0_private_key(key->ecdsa));
519		break;
520	case KEY_ECDSA_CERT:
521		if (key->cert == NULL || buffer_len(&key->cert->certblob) == 0)
522			fatal("%s: no cert/certblob", __func__);
523		buffer_put_string(b, buffer_ptr(&key->cert->certblob),
524		    buffer_len(&key->cert->certblob));
525		buffer_put_bignum2(b, EC_KEY_get0_private_key(key->ecdsa));
526		break;
527#endif
528	}
529	buffer_put_cstring(b, comment);
530}
531
532/*
533 * Adds an identity to the authentication server.  This call is not meant to
534 * be used by normal applications.
535 */
536
537int
538ssh_add_identity_constrained(AuthenticationConnection *auth, Key *key,
539    const char *comment, u_int life, u_int confirm)
540{
541	Buffer msg;
542	int type, constrained = (life || confirm);
543
544	buffer_init(&msg);
545
546	switch (key->type) {
547	case KEY_RSA1:
548		type = constrained ?
549		    SSH_AGENTC_ADD_RSA_ID_CONSTRAINED :
550		    SSH_AGENTC_ADD_RSA_IDENTITY;
551		buffer_put_char(&msg, type);
552		ssh_encode_identity_rsa1(&msg, key->rsa, comment);
553		break;
554	case KEY_RSA:
555	case KEY_RSA_CERT:
556	case KEY_RSA_CERT_V00:
557	case KEY_DSA:
558	case KEY_DSA_CERT:
559	case KEY_DSA_CERT_V00:
560	case KEY_ECDSA:
561	case KEY_ECDSA_CERT:
562		type = constrained ?
563		    SSH2_AGENTC_ADD_ID_CONSTRAINED :
564		    SSH2_AGENTC_ADD_IDENTITY;
565		buffer_put_char(&msg, type);
566		ssh_encode_identity_ssh2(&msg, key, comment);
567		break;
568	default:
569		buffer_free(&msg);
570		return 0;
571	}
572	if (constrained) {
573		if (life != 0) {
574			buffer_put_char(&msg, SSH_AGENT_CONSTRAIN_LIFETIME);
575			buffer_put_int(&msg, life);
576		}
577		if (confirm != 0)
578			buffer_put_char(&msg, SSH_AGENT_CONSTRAIN_CONFIRM);
579	}
580	if (ssh_request_reply(auth, &msg, &msg) == 0) {
581		buffer_free(&msg);
582		return 0;
583	}
584	type = buffer_get_char(&msg);
585	buffer_free(&msg);
586	return decode_reply(type);
587}
588
589/*
590 * Removes an identity from the authentication server.  This call is not
591 * meant to be used by normal applications.
592 */
593
594int
595ssh_remove_identity(AuthenticationConnection *auth, Key *key)
596{
597	Buffer msg;
598	int type;
599	u_char *blob;
600	u_int blen;
601
602	buffer_init(&msg);
603
604	if (key->type == KEY_RSA1) {
605		buffer_put_char(&msg, SSH_AGENTC_REMOVE_RSA_IDENTITY);
606		buffer_put_int(&msg, BN_num_bits(key->rsa->n));
607		buffer_put_bignum(&msg, key->rsa->e);
608		buffer_put_bignum(&msg, key->rsa->n);
609	} else if (key_type_plain(key->type) == KEY_DSA ||
610	    key_type_plain(key->type) == KEY_RSA ||
611	    key_type_plain(key->type) == KEY_ECDSA) {
612		key_to_blob(key, &blob, &blen);
613		buffer_put_char(&msg, SSH2_AGENTC_REMOVE_IDENTITY);
614		buffer_put_string(&msg, blob, blen);
615		xfree(blob);
616	} else {
617		buffer_free(&msg);
618		return 0;
619	}
620	if (ssh_request_reply(auth, &msg, &msg) == 0) {
621		buffer_free(&msg);
622		return 0;
623	}
624	type = buffer_get_char(&msg);
625	buffer_free(&msg);
626	return decode_reply(type);
627}
628
629int
630ssh_update_card(AuthenticationConnection *auth, int add,
631    const char *reader_id, const char *pin, u_int life, u_int confirm)
632{
633	Buffer msg;
634	int type, constrained = (life || confirm);
635
636	if (add) {
637		type = constrained ?
638		    SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED :
639		    SSH_AGENTC_ADD_SMARTCARD_KEY;
640	} else
641		type = SSH_AGENTC_REMOVE_SMARTCARD_KEY;
642
643	buffer_init(&msg);
644	buffer_put_char(&msg, type);
645	buffer_put_cstring(&msg, reader_id);
646	buffer_put_cstring(&msg, pin);
647
648	if (constrained) {
649		if (life != 0) {
650			buffer_put_char(&msg, SSH_AGENT_CONSTRAIN_LIFETIME);
651			buffer_put_int(&msg, life);
652		}
653		if (confirm != 0)
654			buffer_put_char(&msg, SSH_AGENT_CONSTRAIN_CONFIRM);
655	}
656
657	if (ssh_request_reply(auth, &msg, &msg) == 0) {
658		buffer_free(&msg);
659		return 0;
660	}
661	type = buffer_get_char(&msg);
662	buffer_free(&msg);
663	return decode_reply(type);
664}
665
666/*
667 * Removes all identities from the agent.  This call is not meant to be used
668 * by normal applications.
669 */
670
671int
672ssh_remove_all_identities(AuthenticationConnection *auth, int version)
673{
674	Buffer msg;
675	int type;
676	int code = (version==1) ?
677		SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES :
678		SSH2_AGENTC_REMOVE_ALL_IDENTITIES;
679
680	buffer_init(&msg);
681	buffer_put_char(&msg, code);
682
683	if (ssh_request_reply(auth, &msg, &msg) == 0) {
684		buffer_free(&msg);
685		return 0;
686	}
687	type = buffer_get_char(&msg);
688	buffer_free(&msg);
689	return decode_reply(type);
690}
691
692int
693decode_reply(int type)
694{
695	switch (type) {
696	case SSH_AGENT_FAILURE:
697	case SSH_COM_AGENT2_FAILURE:
698	case SSH2_AGENT_FAILURE:
699		logit("SSH_AGENT_FAILURE");
700		return 0;
701	case SSH_AGENT_SUCCESS:
702		return 1;
703	default:
704		fatal("Bad response from authentication agent: %d", type);
705	}
706	/* NOTREACHED */
707	return 0;
708}
709