xref: /freebsd/crypto/openssh/sshconnect2.c (revision ee2ea5ceafed78a5bd9810beb9e3ca927180c226)
1 /*
2  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24 
25 #include "includes.h"
26 RCSID("$OpenBSD: sshconnect2.c,v 1.97 2002/02/25 16:33:27 markus Exp $");
27 RCSID("$FreeBSD$");
28 
29 #include "ssh.h"
30 #include "ssh2.h"
31 #include "xmalloc.h"
32 #include "buffer.h"
33 #include "packet.h"
34 #include "compat.h"
35 #include "bufaux.h"
36 #include "cipher.h"
37 #include "kex.h"
38 #include "myproposal.h"
39 #include "sshconnect.h"
40 #include "authfile.h"
41 #include "dh.h"
42 #include "authfd.h"
43 #include "log.h"
44 #include "readconf.h"
45 #include "readpass.h"
46 #include "match.h"
47 #include "dispatch.h"
48 #include "canohost.h"
49 
50 /* import */
51 extern char *client_version_string;
52 extern char *server_version_string;
53 extern Options options;
54 
55 /*
56  * SSH2 key exchange
57  */
58 
59 u_char *session_id2 = NULL;
60 int session_id2_len = 0;
61 
62 char *xxx_host;
63 struct sockaddr *xxx_hostaddr;
64 
65 Kex *xxx_kex = NULL;
66 
67 static int
68 verify_host_key_callback(Key *hostkey)
69 {
70 	if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
71 		fatal("Host key verification failed.");
72 	return 0;
73 }
74 
75 void
76 ssh_kex2(char *host, struct sockaddr *hostaddr)
77 {
78 	Kex *kex;
79 
80 	xxx_host = host;
81 	xxx_hostaddr = hostaddr;
82 
83 	if (options.ciphers == (char *)-1) {
84 		log("No valid ciphers for protocol version 2 given, using defaults.");
85 		options.ciphers = NULL;
86 	}
87 	if (options.ciphers != NULL) {
88 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
89 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
90 	}
91 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
92 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
93 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
94 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
95 	if (options.compression) {
96 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
97 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib";
98 	} else {
99 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
100 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
101 	}
102 	if (options.macs != NULL) {
103 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
104 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
105 	}
106 	if (options.hostkeyalgorithms != NULL)
107 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
108 		    options.hostkeyalgorithms;
109 
110 	/* start key exchange */
111 	kex = kex_setup(myproposal);
112 	kex->client_version_string=client_version_string;
113 	kex->server_version_string=server_version_string;
114 	kex->verify_host_key=&verify_host_key_callback;
115 
116 	xxx_kex = kex;
117 
118 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
119 
120 	session_id2 = kex->session_id;
121 	session_id2_len = kex->session_id_len;
122 
123 #ifdef DEBUG_KEXDH
124 	/* send 1st encrypted/maced/compressed message */
125 	packet_start(SSH2_MSG_IGNORE);
126 	packet_put_cstring("markus");
127 	packet_send();
128 	packet_write_wait();
129 #endif
130 	debug("done: ssh_kex2.");
131 }
132 
133 /*
134  * Authenticate user
135  */
136 
137 typedef struct Authctxt Authctxt;
138 typedef struct Authmethod Authmethod;
139 
140 typedef int sign_cb_fn(
141     Authctxt *authctxt, Key *key,
142     u_char **sigp, u_int *lenp, u_char *data, u_int datalen);
143 
144 struct Authctxt {
145 	const char *server_user;
146 	const char *local_user;
147 	const char *host;
148 	const char *service;
149 	Authmethod *method;
150 	int success;
151 	char *authlist;
152 	/* pubkey */
153 	Key *last_key;
154 	sign_cb_fn *last_key_sign;
155 	int last_key_hint;
156 	AuthenticationConnection *agent;
157 	/* hostbased */
158 	Key **keys;
159 	int nkeys;
160 	/* kbd-interactive */
161 	int info_req_seen;
162 };
163 struct Authmethod {
164 	char	*name;		/* string to compare against server's list */
165 	int	(*userauth)(Authctxt *authctxt);
166 	int	*enabled;	/* flag in option struct that enables method */
167 	int	*batch_flag;	/* flag in option struct that disables method */
168 };
169 
170 void	input_userauth_success(int, u_int32_t, void *);
171 void	input_userauth_failure(int, u_int32_t, void *);
172 void	input_userauth_banner(int, u_int32_t, void *);
173 void	input_userauth_error(int, u_int32_t, void *);
174 void	input_userauth_info_req(int, u_int32_t, void *);
175 void	input_userauth_pk_ok(int, u_int32_t, void *);
176 
177 int	userauth_none(Authctxt *);
178 int	userauth_pubkey(Authctxt *);
179 int	userauth_passwd(Authctxt *);
180 int	userauth_kbdint(Authctxt *);
181 int	userauth_hostbased(Authctxt *);
182 
183 void	userauth(Authctxt *, char *);
184 
185 static int sign_and_send_pubkey(Authctxt *, Key *, sign_cb_fn *);
186 static void clear_auth_state(Authctxt *);
187 
188 static Authmethod *authmethod_get(char *authlist);
189 static Authmethod *authmethod_lookup(const char *name);
190 static char *authmethods_get(void);
191 
192 Authmethod authmethods[] = {
193 	{"hostbased",
194 		userauth_hostbased,
195 		&options.hostbased_authentication,
196 		NULL},
197 	{"publickey",
198 		userauth_pubkey,
199 		&options.pubkey_authentication,
200 		NULL},
201 	{"keyboard-interactive",
202 		userauth_kbdint,
203 		&options.kbd_interactive_authentication,
204 		&options.batch_mode},
205 	{"password",
206 		userauth_passwd,
207 		&options.password_authentication,
208 		&options.batch_mode},
209 	{"none",
210 		userauth_none,
211 		NULL,
212 		NULL},
213 	{NULL, NULL, NULL, NULL}
214 };
215 
216 void
217 ssh_userauth2(const char *local_user, const char *server_user, char *host,
218     Key **keys, int nkeys)
219 {
220 	Authctxt authctxt;
221 	int type;
222 
223 	if (options.challenge_response_authentication)
224 		options.kbd_interactive_authentication = 1;
225 
226 	debug("send SSH2_MSG_SERVICE_REQUEST");
227 	packet_start(SSH2_MSG_SERVICE_REQUEST);
228 	packet_put_cstring("ssh-userauth");
229 	packet_send();
230 	packet_write_wait();
231 	type = packet_read();
232 	if (type != SSH2_MSG_SERVICE_ACCEPT) {
233 		fatal("denied SSH2_MSG_SERVICE_ACCEPT: %d", type);
234 	}
235 	if (packet_remaining() > 0) {
236 		char *reply = packet_get_string(NULL);
237 		debug("service_accept: %s", reply);
238 		xfree(reply);
239 	} else {
240 		debug("buggy server: service_accept w/o service");
241 	}
242 	packet_check_eom();
243 	debug("got SSH2_MSG_SERVICE_ACCEPT");
244 
245 	if (options.preferred_authentications == NULL)
246 		options.preferred_authentications = authmethods_get();
247 
248 	/* setup authentication context */
249 	memset(&authctxt, 0, sizeof(authctxt));
250 	authctxt.agent = ssh_get_authentication_connection();
251 	authctxt.server_user = server_user;
252 	authctxt.local_user = local_user;
253 	authctxt.host = host;
254 	authctxt.service = "ssh-connection";		/* service name */
255 	authctxt.success = 0;
256 	authctxt.method = authmethod_lookup("none");
257 	authctxt.authlist = NULL;
258 	authctxt.keys = keys;
259 	authctxt.nkeys = nkeys;
260 	authctxt.info_req_seen = 0;
261 	if (authctxt.method == NULL)
262 		fatal("ssh_userauth2: internal error: cannot send userauth none request");
263 
264 	/* initial userauth request */
265 	userauth_none(&authctxt);
266 
267 	dispatch_init(&input_userauth_error);
268 	dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
269 	dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
270 	dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
271 	dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt);	/* loop until success */
272 
273 	if (authctxt.agent != NULL)
274 		ssh_close_authentication_connection(authctxt.agent);
275 
276 	debug("ssh-userauth2 successful: method %s", authctxt.method->name);
277 }
278 void
279 userauth(Authctxt *authctxt, char *authlist)
280 {
281 	if (authlist == NULL) {
282 		authlist = authctxt->authlist;
283 	} else {
284 		if (authctxt->authlist)
285 			xfree(authctxt->authlist);
286 		authctxt->authlist = authlist;
287 	}
288 	for (;;) {
289 		Authmethod *method = authmethod_get(authlist);
290 		if (method == NULL)
291 			fatal("Permission denied (%s).", authlist);
292 		authctxt->method = method;
293 		if (method->userauth(authctxt) != 0) {
294 			debug2("we sent a %s packet, wait for reply", method->name);
295 			break;
296 		} else {
297 			debug2("we did not send a packet, disable method");
298 			method->enabled = NULL;
299 		}
300 	}
301 }
302 void
303 input_userauth_error(int type, u_int32_t seq, void *ctxt)
304 {
305 	fatal("input_userauth_error: bad message during authentication: "
306 	   "type %d", type);
307 }
308 void
309 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
310 {
311 	char *msg, *lang;
312 	debug3("input_userauth_banner");
313 	msg = packet_get_string(NULL);
314 	lang = packet_get_string(NULL);
315 	fprintf(stderr, "%s", msg);
316 	xfree(msg);
317 	xfree(lang);
318 }
319 void
320 input_userauth_success(int type, u_int32_t seq, void *ctxt)
321 {
322 	Authctxt *authctxt = ctxt;
323 	if (authctxt == NULL)
324 		fatal("input_userauth_success: no authentication context");
325 	if (authctxt->authlist)
326 		xfree(authctxt->authlist);
327 	clear_auth_state(authctxt);
328 	authctxt->success = 1;			/* break out */
329 }
330 void
331 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
332 {
333 	Authctxt *authctxt = ctxt;
334 	char *authlist = NULL;
335 	int partial;
336 
337 	if (authctxt == NULL)
338 		fatal("input_userauth_failure: no authentication context");
339 
340 	authlist = packet_get_string(NULL);
341 	partial = packet_get_char();
342 	packet_check_eom();
343 
344 	if (partial != 0)
345 		log("Authenticated with partial success.");
346 	debug("authentications that can continue: %s", authlist);
347 
348 	clear_auth_state(authctxt);
349 	userauth(authctxt, authlist);
350 }
351 void
352 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
353 {
354 	Authctxt *authctxt = ctxt;
355 	Key *key = NULL;
356 	Buffer b;
357 	int pktype, sent = 0;
358 	u_int alen, blen;
359 	char *pkalg, *fp;
360 	u_char *pkblob;
361 
362 	if (authctxt == NULL)
363 		fatal("input_userauth_pk_ok: no authentication context");
364 	if (datafellows & SSH_BUG_PKOK) {
365 		/* this is similar to SSH_BUG_PKAUTH */
366 		debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
367 		pkblob = packet_get_string(&blen);
368 		buffer_init(&b);
369 		buffer_append(&b, pkblob, blen);
370 		pkalg = buffer_get_string(&b, &alen);
371 		buffer_free(&b);
372 	} else {
373 		pkalg = packet_get_string(&alen);
374 		pkblob = packet_get_string(&blen);
375 	}
376 	packet_check_eom();
377 
378 	debug("input_userauth_pk_ok: pkalg %s blen %d lastkey %p hint %d",
379 	    pkalg, blen, authctxt->last_key, authctxt->last_key_hint);
380 
381 	do {
382 		if (authctxt->last_key == NULL ||
383 		    authctxt->last_key_sign == NULL) {
384 			debug("no last key or no sign cb");
385 			break;
386 		}
387 		if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
388 			debug("unknown pkalg %s", pkalg);
389 			break;
390 		}
391 		if ((key = key_from_blob(pkblob, blen)) == NULL) {
392 			debug("no key from blob. pkalg %s", pkalg);
393 			break;
394 		}
395 		if (key->type != pktype) {
396 			error("input_userauth_pk_ok: type mismatch "
397 			    "for decoded key (received %d, expected %d)",
398 			     key->type, pktype);
399 			break;
400 		}
401 		fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
402 		debug2("input_userauth_pk_ok: fp %s", fp);
403 		xfree(fp);
404 		if (!key_equal(key, authctxt->last_key)) {
405 			debug("key != last_key");
406 			break;
407 		}
408 		sent = sign_and_send_pubkey(authctxt, key,
409 		   authctxt->last_key_sign);
410 	} while (0);
411 
412 	if (key != NULL)
413 		key_free(key);
414 	xfree(pkalg);
415 	xfree(pkblob);
416 
417 	/* unregister */
418 	clear_auth_state(authctxt);
419 	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, NULL);
420 
421 	/* try another method if we did not send a packet*/
422 	if (sent == 0)
423 		userauth(authctxt, NULL);
424 
425 }
426 
427 int
428 userauth_none(Authctxt *authctxt)
429 {
430 	/* initial userauth request */
431 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
432 	packet_put_cstring(authctxt->server_user);
433 	packet_put_cstring(authctxt->service);
434 	packet_put_cstring(authctxt->method->name);
435 	packet_send();
436 	return 1;
437 }
438 
439 int
440 userauth_passwd(Authctxt *authctxt)
441 {
442 	static int attempt = 0;
443 	char prompt[80];
444 	char *password;
445 
446 	if (attempt++ >= options.number_of_password_prompts)
447 		return 0;
448 
449 	if (attempt != 1)
450 		error("Permission denied, please try again.");
451 
452 	snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
453 	    authctxt->server_user, authctxt->host);
454 	password = read_passphrase(prompt, 0);
455 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
456 	packet_put_cstring(authctxt->server_user);
457 	packet_put_cstring(authctxt->service);
458 	packet_put_cstring(authctxt->method->name);
459 	packet_put_char(0);
460 	packet_put_cstring(password);
461 	memset(password, 0, strlen(password));
462 	xfree(password);
463 	packet_add_padding(64);
464 	packet_send();
465 	return 1;
466 }
467 
468 static void
469 clear_auth_state(Authctxt *authctxt)
470 {
471 	/* XXX clear authentication state */
472 	if (authctxt->last_key != NULL && authctxt->last_key_hint == -1) {
473 		debug3("clear_auth_state: key_free %p", authctxt->last_key);
474 		key_free(authctxt->last_key);
475 	}
476 	authctxt->last_key = NULL;
477 	authctxt->last_key_hint = -2;
478 	authctxt->last_key_sign = NULL;
479 }
480 
481 static int
482 sign_and_send_pubkey(Authctxt *authctxt, Key *k, sign_cb_fn *sign_callback)
483 {
484 	Buffer b;
485 	u_char *blob, *signature;
486 	u_int bloblen, slen;
487 	int skip = 0;
488 	int ret = -1;
489 	int have_sig = 1;
490 
491 	debug3("sign_and_send_pubkey");
492 
493 	if (key_to_blob(k, &blob, &bloblen) == 0) {
494 		/* we cannot handle this key */
495 		debug3("sign_and_send_pubkey: cannot handle key");
496 		return 0;
497 	}
498 	/* data to be signed */
499 	buffer_init(&b);
500 	if (datafellows & SSH_OLD_SESSIONID) {
501 		buffer_append(&b, session_id2, session_id2_len);
502 		skip = session_id2_len;
503 	} else {
504 		buffer_put_string(&b, session_id2, session_id2_len);
505 		skip = buffer_len(&b);
506 	}
507 	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
508 	buffer_put_cstring(&b, authctxt->server_user);
509 	buffer_put_cstring(&b,
510 	    datafellows & SSH_BUG_PKSERVICE ?
511 	    "ssh-userauth" :
512 	    authctxt->service);
513 	if (datafellows & SSH_BUG_PKAUTH) {
514 		buffer_put_char(&b, have_sig);
515 	} else {
516 		buffer_put_cstring(&b, authctxt->method->name);
517 		buffer_put_char(&b, have_sig);
518 		buffer_put_cstring(&b, key_ssh_name(k));
519 	}
520 	buffer_put_string(&b, blob, bloblen);
521 
522 	/* generate signature */
523 	ret = (*sign_callback)(authctxt, k, &signature, &slen,
524 	    buffer_ptr(&b), buffer_len(&b));
525 	if (ret == -1) {
526 		xfree(blob);
527 		buffer_free(&b);
528 		return 0;
529 	}
530 #ifdef DEBUG_PK
531 	buffer_dump(&b);
532 #endif
533 	if (datafellows & SSH_BUG_PKSERVICE) {
534 		buffer_clear(&b);
535 		buffer_append(&b, session_id2, session_id2_len);
536 		skip = session_id2_len;
537 		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
538 		buffer_put_cstring(&b, authctxt->server_user);
539 		buffer_put_cstring(&b, authctxt->service);
540 		buffer_put_cstring(&b, authctxt->method->name);
541 		buffer_put_char(&b, have_sig);
542 		if (!(datafellows & SSH_BUG_PKAUTH))
543 			buffer_put_cstring(&b, key_ssh_name(k));
544 		buffer_put_string(&b, blob, bloblen);
545 	}
546 	xfree(blob);
547 
548 	/* append signature */
549 	buffer_put_string(&b, signature, slen);
550 	xfree(signature);
551 
552 	/* skip session id and packet type */
553 	if (buffer_len(&b) < skip + 1)
554 		fatal("userauth_pubkey: internal error");
555 	buffer_consume(&b, skip + 1);
556 
557 	/* put remaining data from buffer into packet */
558 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
559 	packet_put_raw(buffer_ptr(&b), buffer_len(&b));
560 	buffer_free(&b);
561 	packet_send();
562 
563 	return 1;
564 }
565 
566 static int
567 send_pubkey_test(Authctxt *authctxt, Key *k, sign_cb_fn *sign_callback,
568     int hint)
569 {
570 	u_char *blob;
571 	u_int bloblen, have_sig = 0;
572 
573 	debug3("send_pubkey_test");
574 
575 	if (key_to_blob(k, &blob, &bloblen) == 0) {
576 		/* we cannot handle this key */
577 		debug3("send_pubkey_test: cannot handle key");
578 		return 0;
579 	}
580 	/* register callback for USERAUTH_PK_OK message */
581 	authctxt->last_key_sign = sign_callback;
582 	authctxt->last_key_hint = hint;
583 	authctxt->last_key = k;
584 	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
585 
586 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
587 	packet_put_cstring(authctxt->server_user);
588 	packet_put_cstring(authctxt->service);
589 	packet_put_cstring(authctxt->method->name);
590 	packet_put_char(have_sig);
591 	if (!(datafellows & SSH_BUG_PKAUTH))
592 		packet_put_cstring(key_ssh_name(k));
593 	packet_put_string(blob, bloblen);
594 	xfree(blob);
595 	packet_send();
596 	return 1;
597 }
598 
599 static Key *
600 load_identity_file(char *filename)
601 {
602 	Key *private;
603 	char prompt[300], *passphrase;
604 	int quit, i;
605 	struct stat st;
606 
607 	if (stat(filename, &st) < 0) {
608 		debug3("no such identity: %s", filename);
609 		return NULL;
610 	}
611 	private = key_load_private_type(KEY_UNSPEC, filename, "", NULL);
612 	if (private == NULL) {
613 		if (options.batch_mode)
614 			return NULL;
615 		snprintf(prompt, sizeof prompt,
616 		    "Enter passphrase for key '%.100s': ", filename);
617 		for (i = 0; i < options.number_of_password_prompts; i++) {
618 			passphrase = read_passphrase(prompt, 0);
619 			if (strcmp(passphrase, "") != 0) {
620 				private = key_load_private_type(KEY_UNSPEC, filename,
621 				    passphrase, NULL);
622 				quit = 0;
623 			} else {
624 				debug2("no passphrase given, try next key");
625 				quit = 1;
626 			}
627 			memset(passphrase, 0, strlen(passphrase));
628 			xfree(passphrase);
629 			if (private != NULL || quit)
630 				break;
631 			debug2("bad passphrase given, try again...");
632 		}
633 	}
634 	return private;
635 }
636 
637 static int
638 identity_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
639     u_char *data, u_int datalen)
640 {
641 	Key *private;
642 	int idx, ret;
643 
644 	idx = authctxt->last_key_hint;
645 	if (idx < 0)
646 		return -1;
647 
648 	/* private key is stored in external hardware */
649 	if (options.identity_keys[idx]->flags & KEY_FLAG_EXT)
650 		return key_sign(options.identity_keys[idx], sigp, lenp, data, datalen);
651 
652 	private = load_identity_file(options.identity_files[idx]);
653 	if (private == NULL)
654 		return -1;
655 	ret = key_sign(private, sigp, lenp, data, datalen);
656 	key_free(private);
657 	return ret;
658 }
659 
660 static int
661 agent_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
662     u_char *data, u_int datalen)
663 {
664 	return ssh_agent_sign(authctxt->agent, key, sigp, lenp, data, datalen);
665 }
666 
667 static int
668 key_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
669     u_char *data, u_int datalen)
670 {
671 	return key_sign(key, sigp, lenp, data, datalen);
672 }
673 
674 static int
675 userauth_pubkey_agent(Authctxt *authctxt)
676 {
677 	static int called = 0;
678 	int ret = 0;
679 	char *comment;
680 	Key *k;
681 
682 	if (called == 0) {
683 		if (ssh_get_num_identities(authctxt->agent, 2) == 0)
684 			debug2("userauth_pubkey_agent: no keys at all");
685 		called = 1;
686 	}
687 	k = ssh_get_next_identity(authctxt->agent, &comment, 2);
688 	if (k == NULL) {
689 		debug2("userauth_pubkey_agent: no more keys");
690 	} else {
691 		debug("userauth_pubkey_agent: testing agent key %s", comment);
692 		xfree(comment);
693 		ret = send_pubkey_test(authctxt, k, agent_sign_cb, -1);
694 		if (ret == 0)
695 			key_free(k);
696 	}
697 	if (ret == 0)
698 		debug2("userauth_pubkey_agent: no message sent");
699 	return ret;
700 }
701 
702 int
703 userauth_pubkey(Authctxt *authctxt)
704 {
705 	static int idx = 0;
706 	int sent = 0;
707 	Key *key;
708 	char *filename;
709 
710 	if (authctxt->agent != NULL) {
711 		do {
712 			sent = userauth_pubkey_agent(authctxt);
713 		} while (!sent && authctxt->agent->howmany > 0);
714 	}
715 	while (!sent && idx < options.num_identity_files) {
716 		key = options.identity_keys[idx];
717 		filename = options.identity_files[idx];
718 		if (key == NULL) {
719 			debug("try privkey: %s", filename);
720 			key = load_identity_file(filename);
721 			if (key != NULL) {
722 				sent = sign_and_send_pubkey(authctxt, key,
723 				    key_sign_cb);
724 				key_free(key);
725 			}
726 		} else if (key->type != KEY_RSA1) {
727 			debug("try pubkey: %s", filename);
728 			sent = send_pubkey_test(authctxt, key,
729 			    identity_sign_cb, idx);
730 		}
731 		idx++;
732 	}
733 	return sent;
734 }
735 
736 /*
737  * Send userauth request message specifying keyboard-interactive method.
738  */
739 int
740 userauth_kbdint(Authctxt *authctxt)
741 {
742 	static int attempt = 0;
743 
744 	if (attempt++ >= options.number_of_password_prompts)
745 		return 0;
746 	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
747 	if (attempt > 1 && !authctxt->info_req_seen) {
748 		debug3("userauth_kbdint: disable: no info_req_seen");
749 		dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
750 		return 0;
751 	}
752 
753 	debug2("userauth_kbdint");
754 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
755 	packet_put_cstring(authctxt->server_user);
756 	packet_put_cstring(authctxt->service);
757 	packet_put_cstring(authctxt->method->name);
758 	packet_put_cstring("");					/* lang */
759 	packet_put_cstring(options.kbd_interactive_devices ?
760 	    options.kbd_interactive_devices : "");
761 	packet_send();
762 
763 	dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
764 	return 1;
765 }
766 
767 /*
768  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
769  */
770 void
771 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
772 {
773 	Authctxt *authctxt = ctxt;
774 	char *name, *inst, *lang, *prompt, *response;
775 	u_int num_prompts, i;
776 	int echo = 0;
777 
778 	debug2("input_userauth_info_req");
779 
780 	if (authctxt == NULL)
781 		fatal("input_userauth_info_req: no authentication context");
782 
783 	authctxt->info_req_seen = 1;
784 
785 	name = packet_get_string(NULL);
786 	inst = packet_get_string(NULL);
787 	lang = packet_get_string(NULL);
788 	if (strlen(name) > 0)
789 		log("%s", name);
790 	if (strlen(inst) > 0)
791 		log("%s", inst);
792 	xfree(name);
793 	xfree(inst);
794 	xfree(lang);
795 
796 	num_prompts = packet_get_int();
797 	/*
798 	 * Begin to build info response packet based on prompts requested.
799 	 * We commit to providing the correct number of responses, so if
800 	 * further on we run into a problem that prevents this, we have to
801 	 * be sure and clean this up and send a correct error response.
802 	 */
803 	packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
804 	packet_put_int(num_prompts);
805 
806 	debug2("input_userauth_info_req: num_prompts %d", num_prompts);
807 	for (i = 0; i < num_prompts; i++) {
808 		prompt = packet_get_string(NULL);
809 		echo = packet_get_char();
810 
811 		response = read_passphrase(prompt, echo ? RP_ECHO : 0);
812 
813 		packet_put_cstring(response);
814 		memset(response, 0, strlen(response));
815 		xfree(response);
816 		xfree(prompt);
817 	}
818 	packet_check_eom(); /* done with parsing incoming message. */
819 
820 	packet_add_padding(64);
821 	packet_send();
822 }
823 
824 /*
825  * this will be move to an external program (ssh-keysign) ASAP. ssh-keysign
826  * will be setuid-root and the sbit can be removed from /usr/bin/ssh.
827  */
828 int
829 userauth_hostbased(Authctxt *authctxt)
830 {
831 	Key *private = NULL;
832 	Buffer b;
833 	u_char *signature, *blob;
834 	char *chost, *pkalg, *p;
835 	const char *service;
836 	u_int blen, slen;
837 	int ok, i, len, found = 0;
838 
839 	/* check for a useful key */
840 	for (i = 0; i < authctxt->nkeys; i++) {
841 		private = authctxt->keys[i];
842 		if (private && private->type != KEY_RSA1) {
843 			found = 1;
844 			/* we take and free the key */
845 			authctxt->keys[i] = NULL;
846 			break;
847 		}
848 	}
849 	if (!found) {
850 		debug("userauth_hostbased: no more client hostkeys");
851 		return 0;
852 	}
853 	if (key_to_blob(private, &blob, &blen) == 0) {
854 		key_free(private);
855 		return 0;
856 	}
857 	/* figure out a name for the client host */
858 	p = get_local_name(packet_get_connection_in());
859 	if (p == NULL) {
860 		error("userauth_hostbased: cannot get local ipaddr/name");
861 		key_free(private);
862 		return 0;
863 	}
864 	len = strlen(p) + 2;
865 	chost = xmalloc(len);
866 	strlcpy(chost, p, len);
867 	strlcat(chost, ".", len);
868 	debug2("userauth_hostbased: chost %s", chost);
869 
870 	service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
871 	    authctxt->service;
872 	pkalg = xstrdup(key_ssh_name(private));
873 	buffer_init(&b);
874 	/* construct data */
875 	buffer_put_string(&b, session_id2, session_id2_len);
876 	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
877 	buffer_put_cstring(&b, authctxt->server_user);
878 	buffer_put_cstring(&b, service);
879 	buffer_put_cstring(&b, authctxt->method->name);
880 	buffer_put_cstring(&b, pkalg);
881 	buffer_put_string(&b, blob, blen);
882 	buffer_put_cstring(&b, chost);
883 	buffer_put_cstring(&b, authctxt->local_user);
884 #ifdef DEBUG_PK
885 	buffer_dump(&b);
886 #endif
887 	ok = key_sign(private, &signature, &slen, buffer_ptr(&b), buffer_len(&b));
888 	key_free(private);
889 	buffer_free(&b);
890 	if (ok != 0) {
891 		error("key_sign failed");
892 		xfree(chost);
893 		xfree(pkalg);
894 		return 0;
895 	}
896 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
897 	packet_put_cstring(authctxt->server_user);
898 	packet_put_cstring(authctxt->service);
899 	packet_put_cstring(authctxt->method->name);
900 	packet_put_cstring(pkalg);
901 	packet_put_string(blob, blen);
902 	packet_put_cstring(chost);
903 	packet_put_cstring(authctxt->local_user);
904 	packet_put_string(signature, slen);
905 	memset(signature, 's', slen);
906 	xfree(signature);
907 	xfree(chost);
908 	xfree(pkalg);
909 
910 	packet_send();
911 	return 1;
912 }
913 
914 /* find auth method */
915 
916 /*
917  * given auth method name, if configurable options permit this method fill
918  * in auth_ident field and return true, otherwise return false.
919  */
920 static int
921 authmethod_is_enabled(Authmethod *method)
922 {
923 	if (method == NULL)
924 		return 0;
925 	/* return false if options indicate this method is disabled */
926 	if  (method->enabled == NULL || *method->enabled == 0)
927 		return 0;
928 	/* return false if batch mode is enabled but method needs interactive mode */
929 	if  (method->batch_flag != NULL && *method->batch_flag != 0)
930 		return 0;
931 	return 1;
932 }
933 
934 static Authmethod *
935 authmethod_lookup(const char *name)
936 {
937 	Authmethod *method = NULL;
938 	if (name != NULL)
939 		for (method = authmethods; method->name != NULL; method++)
940 			if (strcmp(name, method->name) == 0)
941 				return method;
942 	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
943 	return NULL;
944 }
945 
946 /* XXX internal state */
947 static Authmethod *current = NULL;
948 static char *supported = NULL;
949 static char *preferred = NULL;
950 /*
951  * Given the authentication method list sent by the server, return the
952  * next method we should try.  If the server initially sends a nil list,
953  * use a built-in default list.
954  */
955 static Authmethod *
956 authmethod_get(char *authlist)
957 {
958 
959 	char *name = NULL;
960 	u_int next;
961 
962 	/* Use a suitable default if we're passed a nil list.  */
963 	if (authlist == NULL || strlen(authlist) == 0)
964 		authlist = options.preferred_authentications;
965 
966 	if (supported == NULL || strcmp(authlist, supported) != 0) {
967 		debug3("start over, passed a different list %s", authlist);
968 		if (supported != NULL)
969 			xfree(supported);
970 		supported = xstrdup(authlist);
971 		preferred = options.preferred_authentications;
972 		debug3("preferred %s", preferred);
973 		current = NULL;
974 	} else if (current != NULL && authmethod_is_enabled(current))
975 		return current;
976 
977 	for (;;) {
978 		if ((name = match_list(preferred, supported, &next)) == NULL) {
979 			debug("no more auth methods to try");
980 			current = NULL;
981 			return NULL;
982 		}
983 		preferred += next;
984 		debug3("authmethod_lookup %s", name);
985 		debug3("remaining preferred: %s", preferred);
986 		if ((current = authmethod_lookup(name)) != NULL &&
987 		    authmethod_is_enabled(current)) {
988 			debug3("authmethod_is_enabled %s", name);
989 			debug("next auth method to try is %s", name);
990 			return current;
991 		}
992 	}
993 }
994 
995 static char *
996 authmethods_get(void)
997 {
998 	Authmethod *method = NULL;
999 	Buffer b;
1000 	char *list;
1001 
1002 	buffer_init(&b);
1003 	for (method = authmethods; method->name != NULL; method++) {
1004 		if (authmethod_is_enabled(method)) {
1005 			if (buffer_len(&b) > 0)
1006 				buffer_append(&b, ",", 1);
1007 			buffer_append(&b, method->name, strlen(method->name));
1008 		}
1009 	}
1010 	buffer_append(&b, "\0", 1);
1011 	list = xstrdup(buffer_ptr(&b));
1012 	buffer_free(&b);
1013 	return list;
1014 }
1015