xref: /titanic_50/usr/src/cmd/ssh/ssh/sshconnect2.c (revision b9aa66a73c9016cf5c71fe80efe90ce9f2ca5c73)
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  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
26  * Use is subject to license terms.
27  */
28 
29 #include "includes.h"
30 RCSID("$OpenBSD: sshconnect2.c,v 1.107 2002/07/01 19:48:46 markus Exp $");
31 
32 #include "ssh.h"
33 #include "ssh2.h"
34 #include "xmalloc.h"
35 #include "buffer.h"
36 #include "packet.h"
37 #include "compat.h"
38 #include "bufaux.h"
39 #include "cipher.h"
40 #include "kex.h"
41 #include "myproposal.h"
42 #include "sshconnect.h"
43 #include "authfile.h"
44 #include "dh.h"
45 #include "authfd.h"
46 #include "log.h"
47 #include "readconf.h"
48 #include "readpass.h"
49 #include "match.h"
50 #include "dispatch.h"
51 #include "canohost.h"
52 #include "msg.h"
53 #include "pathnames.h"
54 #include "g11n.h"
55 
56 #ifdef GSSAPI
57 #include "ssh-gss.h"
58 extern Gssctxt *xxx_gssctxt;
59 #endif /* GSSAPI */
60 
61 /* import */
62 extern char *client_version_string;
63 extern char *server_version_string;
64 extern Options options;
65 extern Buffer command;
66 
67 /*
68  * SSH2 key exchange
69  */
70 
71 u_char *session_id2 = NULL;
72 int session_id2_len = 0;
73 
74 char *xxx_host;
75 struct sockaddr *xxx_hostaddr;
76 
77 Kex *xxx_kex = NULL;
78 
79 static int
verify_host_key_callback(Key * hostkey)80 verify_host_key_callback(Key *hostkey)
81 {
82 	if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
83 		fatal("Host key verification failed.");
84 	return 0;
85 }
86 
87 static int
accept_host_key_callback(Key * hostkey)88 accept_host_key_callback(Key *hostkey)
89 {
90 	if (accept_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
91 		log("GSS-API authenticated host key addition to "
92 			"known_hosts file failed");
93 	return 0;
94 }
95 
96 void
ssh_kex2(char * host,struct sockaddr * hostaddr)97 ssh_kex2(char *host, struct sockaddr *hostaddr)
98 {
99 	Kex *kex;
100 	Kex_hook_func kex_hook = NULL;
101 	static char **myproposal;
102 
103 	myproposal = my_clnt_proposal;
104 
105 	xxx_host = host;
106 	xxx_hostaddr = hostaddr;
107 
108 #ifdef GSSAPI
109 	/* Add the GSSAPI mechanisms currently supported on this client to
110 	 * the key exchange algorithm proposal */
111 	if (options.gss_keyex)
112 		kex_hook = ssh_gssapi_client_kex_hook;
113 #endif /* GSSAPI */
114 	if (options.ciphers == (char *)-1) {
115 		log("No valid ciphers for protocol version 2 given, using defaults.");
116 		options.ciphers = NULL;
117 	}
118 	if (options.ciphers != NULL) {
119 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
120 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
121 	}
122 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
123 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
124 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
125 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
126 	if (options.compression) {
127 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
128 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib,none";
129 	} else {
130 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
131 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib";
132 	}
133 	if (options.macs != NULL) {
134 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
135 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
136 	}
137 	if (options.hostkeyalgorithms != NULL)
138 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
139 		    options.hostkeyalgorithms;
140 
141 	if (options.rekey_limit)
142 		packet_set_rekey_limit((u_int32_t)options.rekey_limit);
143 
144 	if (datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS) {
145 		char *locale = setlocale(LC_ALL, "");
146 
147 		/* Solaris 9 SSHD expects a locale, not a langtag list */
148 		myproposal[PROPOSAL_LANG_CTOS] = "";
149 		if (locale != NULL && *locale != '\0' &&
150 		    strcmp(locale, "C") != 0)
151 			myproposal[PROPOSAL_LANG_CTOS] = locale;
152 	} else {
153 		myproposal[PROPOSAL_LANG_CTOS] = g11n_getlangs();
154 	}
155 
156 	/* Same languages proposal for both directions */
157 	if (myproposal[PROPOSAL_LANG_CTOS] == NULL) {
158 		myproposal[PROPOSAL_LANG_CTOS] = "";
159 		myproposal[PROPOSAL_LANG_STOC] = "";
160 	} else {
161 		myproposal[PROPOSAL_LANG_STOC] =
162 			myproposal[PROPOSAL_LANG_CTOS];
163 	}
164 
165         /* start key exchange */
166         kex = kex_setup(host, myproposal, kex_hook);
167 	kex_start(kex);
168         kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
169         kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
170 #ifdef GSSAPI
171 	kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_client;
172 	kex->options.gss_deleg_creds = options.gss_deleg_creds;
173 #endif /* GSSAPI */
174         kex->client_version_string=client_version_string;
175         kex->server_version_string=server_version_string;
176         kex->verify_host_key=&verify_host_key_callback;
177         kex->accept_host_key=&accept_host_key_callback;
178 
179 	xxx_kex = kex;
180 
181 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
182 
183 	session_id2 = kex->session_id;
184 	session_id2_len = kex->session_id_len;
185 
186 #ifdef DEBUG_KEXDH
187 	/* send 1st encrypted/maced/compressed message */
188 	packet_start(SSH2_MSG_IGNORE);
189 	packet_put_cstring("markus");
190 	packet_send();
191 	packet_write_wait();
192 #endif
193 	debug("done: ssh_kex2.");
194 }
195 
196 /*
197  * Authenticate user
198  */
199 
200 typedef struct Authctxt Authctxt;
201 typedef struct Authmethod Authmethod;
202 
203 typedef int sign_cb_fn(
204     Authctxt *authctxt, Key *key,
205     u_char **sigp, u_int *lenp, u_char *data, u_int datalen);
206 
207 struct Authctxt {
208 	const char *server_user;
209 	const char *local_user;
210 	const char *host;
211 	const char *service;
212 	Authmethod *method;
213 	int success;
214 	char *authlist;
215 	/* pubkey */
216 	Key *last_key;
217 	sign_cb_fn *last_key_sign;
218 	int last_key_hint;
219 	AuthenticationConnection *agent;
220 	/* hostbased */
221 	Sensitive *sensitive;
222 	/* kbd-interactive */
223 	int info_req_seen;
224 	/* generic */
225 	void *methoddata;
226 };
227 struct Authmethod {
228 	char	*name;		/* string to compare against server's list */
229 	int	(*userauth)(Authctxt *authctxt);
230 	void	(*cleanup)(Authctxt *authctxt);
231 	int	*enabled;	/* flag in option struct that enables method */
232 	int	*batch_flag;	/* flag in option struct that disables method */
233 };
234 
235 void	input_userauth_success(int, u_int32_t, void *);
236 void	input_userauth_failure(int, u_int32_t, void *);
237 void	input_userauth_banner(int, u_int32_t, void *);
238 void	input_userauth_error(int, u_int32_t, void *);
239 void	input_userauth_info_req(int, u_int32_t, void *);
240 void	input_userauth_pk_ok(int, u_int32_t, void *);
241 void	input_userauth_passwd_changereq(int, u_int32_t, void *);
242 
243 int	userauth_none(Authctxt *);
244 int	userauth_pubkey(Authctxt *);
245 int	userauth_passwd(Authctxt *);
246 int	userauth_kbdint(Authctxt *);
247 int	userauth_hostbased(Authctxt *);
248 
249 #ifdef GSSAPI
250 static	int	userauth_gssapi_keyex(Authctxt *authctxt);
251 static	int	userauth_gssapi(Authctxt *authctxt);
252 static	void	userauth_gssapi_cleanup(Authctxt *authctxt);
253 static	void	input_gssapi_response(int type, u_int32_t, void *);
254 static	void	input_gssapi_token(int type, u_int32_t, void *);
255 static	void	input_gssapi_hash(int type, u_int32_t, void *);
256 static	void	input_gssapi_error(int, u_int32_t, void *);
257 static	void	input_gssapi_errtok(int, u_int32_t, void *);
258 #endif /* GSSAPI */
259 
260 void	userauth(Authctxt *, char *);
261 
262 static int sign_and_send_pubkey(Authctxt *, Key *, sign_cb_fn *);
263 static void clear_auth_state(Authctxt *);
264 
265 static Authmethod *authmethod_get(char *authlist);
266 static Authmethod *authmethod_lookup(const char *name);
267 static char *authmethods_get(void);
268 
269 Authmethod authmethods[] = {
270 #ifdef GSSAPI
271 	{"gssapi-keyex",
272 		userauth_gssapi_keyex,
273 		userauth_gssapi_cleanup,
274 		&options.gss_keyex,
275 		NULL},
276 	{"gssapi-with-mic",
277 		userauth_gssapi,
278 		userauth_gssapi_cleanup,
279 		&options.gss_authentication,
280 		NULL},
281 #endif /* GSSAPI */
282 	{"hostbased",
283 		userauth_hostbased,
284 		NULL,
285 		&options.hostbased_authentication,
286 		NULL},
287 	{"publickey",
288 		userauth_pubkey,
289 		NULL,
290 		&options.pubkey_authentication,
291 		NULL},
292 	{"keyboard-interactive",
293 		userauth_kbdint,
294 		NULL,
295 		&options.kbd_interactive_authentication,
296 		&options.batch_mode},
297 	{"password",
298 		userauth_passwd,
299 		NULL,
300 		&options.password_authentication,
301 		&options.batch_mode},
302 	{"none",
303 		userauth_none,
304 		NULL,
305 		NULL,
306 		NULL},
307 	{NULL, NULL, NULL, NULL, NULL}
308 };
309 
310 void
ssh_userauth2(const char * local_user,const char * server_user,char * host,Sensitive * sensitive)311 ssh_userauth2(const char *local_user, const char *server_user, char *host,
312     Sensitive *sensitive)
313 {
314 	Authctxt authctxt;
315 	int type;
316 
317 	if (options.challenge_response_authentication)
318 		options.kbd_interactive_authentication = 1;
319 
320 	packet_start(SSH2_MSG_SERVICE_REQUEST);
321 	packet_put_cstring("ssh-userauth");
322 	packet_send();
323 	debug("send SSH2_MSG_SERVICE_REQUEST");
324 	packet_write_wait();
325 	type = packet_read();
326 	if (type != SSH2_MSG_SERVICE_ACCEPT)
327 		fatal("Server denied authentication request: %d", type);
328 	if (packet_remaining() > 0) {
329 		char *reply = packet_get_string(NULL);
330 		debug2("service_accept: %s", reply);
331 		xfree(reply);
332 	} else {
333 		debug2("buggy server: service_accept w/o service");
334 	}
335 	packet_check_eom();
336 	debug("got SSH2_MSG_SERVICE_ACCEPT");
337 
338 	if (options.preferred_authentications == NULL)
339 		options.preferred_authentications = authmethods_get();
340 
341 	/* setup authentication context */
342 	memset(&authctxt, 0, sizeof(authctxt));
343 	authctxt.agent = ssh_get_authentication_connection();
344 	authctxt.server_user = server_user;
345 	authctxt.local_user = local_user;
346 	authctxt.host = host;
347 	authctxt.service = "ssh-connection";		/* service name */
348 	authctxt.success = 0;
349 	authctxt.method = authmethod_lookup("none");
350 	authctxt.authlist = NULL;
351 	authctxt.methoddata = NULL;
352 	authctxt.sensitive = sensitive;
353 	authctxt.info_req_seen = 0;
354 	if (authctxt.method == NULL)
355 		fatal("ssh_userauth2: internal error: cannot send userauth none request");
356 
357 	/* initial userauth request */
358 	userauth_none(&authctxt);
359 
360 	dispatch_init(&input_userauth_error);
361 	dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
362 	dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
363 	dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
364 	dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt);	/* loop until success */
365 
366 	if (authctxt.agent != NULL)
367 		ssh_close_authentication_connection(authctxt.agent);
368 
369 	debug("Authentication succeeded (%s)", authctxt.method->name);
370 }
371 void
userauth(Authctxt * authctxt,char * authlist)372 userauth(Authctxt *authctxt, char *authlist)
373 {
374 	if (authctxt->method != NULL &&
375 	    authctxt->method->cleanup != NULL)
376 		authctxt->method->cleanup(authctxt);
377 
378 	if (authlist == NULL) {
379 		authlist = authctxt->authlist;
380 	} else {
381 		if (authctxt->authlist)
382 			xfree(authctxt->authlist);
383 		authctxt->authlist = authlist;
384 	}
385 	for (;;) {
386 		Authmethod *method = authmethod_get(authlist);
387 		if (method == NULL)
388 			fatal("Permission denied (%s).", authlist);
389 		authctxt->method = method;
390 		if (method->userauth(authctxt) != 0) {
391 			debug2("we sent a %s packet, wait for reply", method->name);
392 			break;
393 		} else {
394 			debug2("we did not send a packet, disable method");
395 			method->enabled = NULL;
396 		}
397 	}
398 }
399 
400 void
input_userauth_error(int type,u_int32_t seq,void * ctxt)401 input_userauth_error(int type, u_int32_t seq, void *ctxt)
402 {
403 	fatal("input_userauth_error: bad message during authentication: "
404 	   "type %d", type);
405 }
406 
407 void
input_userauth_banner(int type,u_int32_t seq,void * ctxt)408 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
409 {
410 	char *msg, *lang;
411 
412 	debug3("input_userauth_banner");
413 	msg = packet_get_utf8_string(NULL);
414 	lang = packet_get_string(NULL);
415 	/*
416 	 * Banner is a warning message according to RFC 4252. So, never print
417 	 * a banner in error log level or lower. If the log level is higher,
418 	 * use DisableBanner option to decide whether to display it or not.
419 	 */
420 	if (options.log_level > SYSLOG_LEVEL_ERROR) {
421 		if (options.disable_banner == 0 ||
422 		    (options.disable_banner == SSH_NO_BANNER_IN_EXEC_MODE &&
423 		    buffer_len(&command) == 0)) {
424 			msg = g11n_filter_string(msg);
425 			(void) fprintf(stderr, "%s", msg);
426 		}
427 	}
428 	xfree(msg);
429 	xfree(lang);
430 }
431 
432 void
input_userauth_success(int type,u_int32_t seq,void * ctxt)433 input_userauth_success(int type, u_int32_t seq, void *ctxt)
434 {
435 	Authctxt *authctxt = ctxt;
436 	if (authctxt == NULL)
437 		fatal("input_userauth_success: no authentication context");
438 	if (authctxt->authlist)
439 		xfree(authctxt->authlist);
440 	if (authctxt->method != NULL &&
441 	    authctxt->method->cleanup != NULL)
442 		authctxt->method->cleanup(authctxt);
443 	clear_auth_state(authctxt);
444 	authctxt->success = 1;			/* break out */
445 }
446 
447 void
input_userauth_failure(int type,u_int32_t seq,void * ctxt)448 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
449 {
450 	Authctxt *authctxt = ctxt;
451 	char *authlist = NULL;
452 	int partial;
453 
454 	if (authctxt == NULL)
455 		fatal("input_userauth_failure: no authentication context");
456 
457 	authlist = packet_get_string(NULL);
458 	partial = packet_get_char();
459 	packet_check_eom();
460 
461 	if (partial != 0)
462 		log("Authenticated with partial success.");
463 	debug("Authentications that can continue: %s", authlist);
464 
465 	clear_auth_state(authctxt);
466 	userauth(authctxt, authlist);
467 }
468 void
input_userauth_pk_ok(int type,u_int32_t seq,void * ctxt)469 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
470 {
471 	Authctxt *authctxt = ctxt;
472 	Key *key = NULL;
473 	Buffer b;
474 	int pktype, sent = 0;
475 	u_int alen, blen;
476 	char *pkalg, *fp;
477 	u_char *pkblob;
478 
479 	if (authctxt == NULL)
480 		fatal("input_userauth_pk_ok: no authentication context");
481 	if (datafellows & SSH_BUG_PKOK) {
482 		/* this is similar to SSH_BUG_PKAUTH */
483 		debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
484 		pkblob = packet_get_string(&blen);
485 		buffer_init(&b);
486 		buffer_append(&b, pkblob, blen);
487 		pkalg = buffer_get_string(&b, &alen);
488 		buffer_free(&b);
489 	} else {
490 		pkalg = packet_get_string(&alen);
491 		pkblob = packet_get_string(&blen);
492 	}
493 	packet_check_eom();
494 
495 	debug("Server accepts key: pkalg %s blen %u lastkey %p hint %d",
496 	    pkalg, blen, authctxt->last_key, authctxt->last_key_hint);
497 
498 	do {
499 		if (authctxt->last_key == NULL ||
500 		    authctxt->last_key_sign == NULL) {
501 			debug("no last key or no sign cb");
502 			break;
503 		}
504 		if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
505 			debug("unknown pkalg %s", pkalg);
506 			break;
507 		}
508 		if ((key = key_from_blob(pkblob, blen)) == NULL) {
509 			debug("no key from blob. pkalg %s", pkalg);
510 			break;
511 		}
512 		if (key->type != pktype) {
513 			error("input_userauth_pk_ok: type mismatch "
514 			    "for decoded key (received %d, expected %d)",
515 			    key->type, pktype);
516 			break;
517 		}
518 		fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
519 		debug2("input_userauth_pk_ok: fp %s", fp);
520 		xfree(fp);
521 		if (!key_equal(key, authctxt->last_key)) {
522 			debug("key != last_key");
523 			break;
524 		}
525 		sent = sign_and_send_pubkey(authctxt, key,
526 		   authctxt->last_key_sign);
527 	} while (0);
528 
529 	if (key != NULL)
530 		key_free(key);
531 	xfree(pkalg);
532 	xfree(pkblob);
533 
534 	/* unregister */
535 	clear_auth_state(authctxt);
536 	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, NULL);
537 
538 	/* try another method if we did not send a packet */
539 	if (sent == 0)
540 		userauth(authctxt, NULL);
541 
542 }
543 
544 #ifdef GSSAPI
545 int
userauth_gssapi(Authctxt * authctxt)546 userauth_gssapi(Authctxt *authctxt)
547 {
548 	Gssctxt *gssctxt = NULL;
549 	static int initialized = 0;
550 	static int mech_idx = 0;
551 	static gss_OID_set supported = GSS_C_NULL_OID_SET;
552 	gss_OID mech = GSS_C_NULL_OID;
553 
554 	/* Things work better if we send one mechanism at a time, rather
555 	 * than them all at once. This means that if we fail at some point
556 	 * in the middle of a negotiation, we can come back and try something
557 	 * different. */
558 
559 	if (datafellows & SSH_OLD_GSSAPI) return 0;
560 
561 	/* Before we offer a mechanism, check that we can support it. Don't
562 	 * bother trying to get credentials - as the standard fallback will
563 	 * deal with that kind of failure.
564 	 */
565 
566 	if (!initialized) {
567 		initialized = 1;
568 		ssh_gssapi_client_mechs(authctxt->host, &supported);
569 		if (supported == GSS_C_NULL_OID_SET || supported->count == 0)
570 			return (0);
571 	} else if (supported != GSS_C_NULL_OID_SET) {
572 		/* Try next mech, if any */
573 		mech_idx++;
574 
575 		if (mech_idx >= supported->count)
576 			return (0);
577 	} else {
578 		return (0);
579 	}
580 
581 	mech = &supported->elements[mech_idx];
582 
583 	ssh_gssapi_build_ctx(&gssctxt, 1, mech);
584 	authctxt->methoddata=(void *)gssctxt;
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 
591 	packet_put_int(1);
592 
593 	/* The newest gsskeyex draft stipulates that OIDs should
594 	 * be DER encoded, so we need to add the object type and
595 	 * length information back on */
596 	if (datafellows & SSH_BUG_GSSAPI_BER) {
597 		packet_put_string(mech->elements, mech->length);
598 	} else {
599 		packet_put_int((mech->length)+2);
600 		packet_put_char(0x06);
601 		packet_put_char(mech->length);
602 		packet_put_raw(mech->elements, mech->length);
603 	}
604 
605         packet_send();
606         packet_write_wait();
607 
608         dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,&input_gssapi_response);
609 
610         return 1;
611 }
612 
613 void
input_gssapi_response(int type,u_int32_t plen,void * ctxt)614 input_gssapi_response(int type, u_int32_t plen, void *ctxt)
615 {
616 	Authctxt *authctxt = ctxt;
617 	Gssctxt *gssctxt;
618 	OM_uint32 status,ms;
619 	u_int oidlen;
620 	char *oidv;
621 	gss_buffer_desc send_tok;
622 
623 	if (authctxt == NULL)
624 		fatal("input_gssapi_response: no authentication context");
625 	gssctxt = authctxt->methoddata;
626 
627 	/* Setup our OID */
628 	oidv=packet_get_string(&oidlen);
629 
630 	if (datafellows & SSH_BUG_GSSAPI_BER) {
631 		if (!ssh_gssapi_check_mech_oid(gssctxt,oidv,oidlen)) {
632 			gss_OID oid;
633 
634 			oid = ssh_gssapi_make_oid(oidlen, oidv);
635 			debug("Server returned different OID (%s) than expected (%s)",
636 				ssh_gssapi_oid_to_str(oid),
637 				ssh_gssapi_oid_to_str(gssctxt->desired_mech));
638 			ssh_gssapi_release_oid(&oid);
639 			clear_auth_state(authctxt);
640 			userauth(authctxt,NULL);
641 			return;
642 		}
643 	} else {
644 		if(oidv[0]!=0x06 || oidv[1]!=oidlen-2) {
645 			debug("Badly encoded mechanism OID received");
646 			clear_auth_state(authctxt);
647 			userauth(authctxt,NULL);
648 			return;
649 		}
650 		if (!ssh_gssapi_check_mech_oid(gssctxt,oidv+2,oidlen-2)) {
651 			gss_OID oid;
652 
653 			oid = ssh_gssapi_make_oid(oidlen-2, oidv+2);
654 			debug("Server returned different OID (%s) than expected (%s)",
655 				ssh_gssapi_oid_to_str(oid),
656 				ssh_gssapi_oid_to_str(gssctxt->desired_mech));
657 			clear_auth_state(authctxt);
658 			userauth(authctxt,NULL);
659 			return;
660 		}
661 	}
662 
663 	packet_check_eom();
664 
665         dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,&input_gssapi_token);
666 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR,&input_gssapi_error);
667 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,&input_gssapi_errtok);
668 
669 	status = ssh_gssapi_init_ctx(gssctxt, authctxt->host,
670 					options.gss_deleg_creds,
671 					GSS_C_NO_BUFFER, &send_tok);
672 	if (GSS_ERROR(status)) {
673 		if (send_tok.length>0) {
674 			packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
675 			packet_put_string(send_tok.value,send_tok.length);
676 			packet_send();
677 			packet_write_wait();
678 		}
679 		/* Start again with next method on list */
680 		debug("Trying to start again");
681 		clear_auth_state(authctxt);
682 		userauth(authctxt,NULL);
683 		return;
684 	}
685 
686 	/* We must have data to send */
687 	packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
688 	packet_put_string(send_tok.value,send_tok.length);
689 	packet_send();
690 	packet_write_wait();
691 	gss_release_buffer(&ms, &send_tok);
692 }
693 
694 void
input_gssapi_token(int type,u_int32_t plen,void * ctxt)695 input_gssapi_token(int type, u_int32_t plen, void *ctxt)
696 {
697 	Authctxt *authctxt = ctxt;
698 	Gssctxt *gssctxt;
699 	gss_buffer_desc send_tok, recv_tok, g_mic_data;
700 	Buffer mic_data;
701 	OM_uint32 status;
702 	u_int slen;
703 
704 	if (authctxt == NULL || authctxt->method == NULL)
705 		fatal("input_gssapi_response: no authentication context");
706 	gssctxt = authctxt->methoddata;
707 
708 	recv_tok.value=packet_get_string(&slen);
709 	recv_tok.length=slen;	/* safe typecast */
710 
711 	status=ssh_gssapi_init_ctx(gssctxt, authctxt->host,
712 					options.gss_deleg_creds,
713 					&recv_tok, &send_tok);
714 
715 	packet_check_eom();
716 
717 	if (GSS_ERROR(status)) {
718 		if (send_tok.length>0) {
719 			packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
720 			packet_put_string(send_tok.value,send_tok.length);
721 			packet_send();
722 			packet_write_wait();
723 		}
724 		/* Start again with the next method in the list */
725 		clear_auth_state(authctxt);
726 		userauth(authctxt,NULL);
727 		return;
728 	}
729 
730 	if (send_tok.length>0) {
731 		packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
732 		packet_put_string(send_tok.value,send_tok.length);
733 		packet_send();
734 		packet_write_wait();
735 	}
736 
737 	if (status != GSS_S_COMPLETE)
738 		return;
739 
740 	/* Make data buffer to MIC */
741 	buffer_init(&mic_data);
742 	buffer_put_string(&mic_data, session_id2, session_id2_len);
743 	buffer_put_char(&mic_data, SSH2_MSG_USERAUTH_REQUEST);
744 	buffer_put_cstring(&mic_data, authctxt->server_user);
745 	buffer_put_cstring(&mic_data, authctxt->service);
746 	buffer_put_cstring(&mic_data, authctxt->method->name);
747 
748 	/* Make MIC */
749 	g_mic_data.value  = buffer_ptr(&mic_data);
750 	g_mic_data.length = buffer_len(&mic_data);
751 
752 	status = ssh_gssapi_get_mic(gssctxt, &g_mic_data, &send_tok);
753 	buffer_clear(&mic_data);
754 
755 	if (GSS_ERROR(status) || send_tok.length == 0) {
756 		/*
757 		 * Oops, now what?  There's no error token...
758 		 * Next userauth
759 		 */
760 		debug("GSS_GetMIC() failed! - "
761 		      "Abandoning GSSAPI userauth");
762 		clear_auth_state(authctxt);
763 		userauth(authctxt,NULL);
764 		return;
765 	}
766 	packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
767 	packet_put_string(send_tok.value,send_tok.length);
768 	packet_send();
769 	packet_write_wait();
770 }
771 
772 void
input_gssapi_errtok(int type,u_int32_t plen,void * ctxt)773 input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
774 {
775 	OM_uint32 min_status;
776 	Authctxt *authctxt = ctxt;
777 	Gssctxt *gssctxt;
778 	gss_buffer_desc send_tok, recv_tok;
779 
780 	if (authctxt == NULL)
781 		fatal("input_gssapi_response: no authentication context");
782 	gssctxt = authctxt->methoddata;
783 
784 	recv_tok.value=packet_get_string(&recv_tok.length);
785 
786 	/* Stick it into GSSAPI and see what it says */
787 	(void) ssh_gssapi_init_ctx(gssctxt, authctxt->host,
788 					options.gss_deleg_creds,
789 					&recv_tok, &send_tok);
790 
791 	xfree(recv_tok.value);
792 	(void) gss_release_buffer(&min_status, &send_tok);
793 
794 	debug("Server sent a GSS-API error token during GSS userauth -- %s",
795 		ssh_gssapi_last_error(gssctxt, NULL, NULL));
796 
797 	packet_check_eom();
798 
799 	/* We can't send a packet to the server */
800 
801 	/* The draft says that we should wait for the server to fail
802 	 * before starting the next authentication. So, we clear the
803 	 * state, but don't do anything else
804 	 */
805 	clear_auth_state(authctxt);
806 	return;
807 }
808 
809 void
input_gssapi_error(int type,u_int32_t plen,void * ctxt)810 input_gssapi_error(int type, u_int32_t plen, void *ctxt)
811 {
812 	OM_uint32 maj,min;
813 	char *msg;
814 	char *lang;
815 
816 	maj = packet_get_int();
817 	min = packet_get_int();
818 	msg = packet_get_string(NULL);
819 	lang = packet_get_string(NULL);
820 
821 	packet_check_eom();
822 
823 	fprintf(stderr, "Server GSSAPI Error:\n%s (%d, %d)\n", msg, maj, min);
824 	xfree(msg);
825 	xfree(lang);
826 }
827 
828 int
userauth_gssapi_keyex(Authctxt * authctxt)829 userauth_gssapi_keyex(Authctxt *authctxt)
830 {
831 	Gssctxt *gssctxt;
832 	gss_buffer_desc send_tok;
833 	OM_uint32 status;
834         static int attempt = 0;
835 
836 	if (authctxt == NULL || authctxt->method == NULL)
837 		fatal("input_gssapi_response: no authentication context");
838 
839 	if (xxx_gssctxt == NULL || xxx_gssctxt->context == GSS_C_NO_CONTEXT)
840 		return 0;
841 
842 	if (strcmp(authctxt->method->name, "gssapi-keyex") == 0)
843 		authctxt->methoddata = gssctxt = xxx_gssctxt;
844 
845         if (attempt++ >= 1)
846         	return 0;
847 
848 	if (strcmp(authctxt->method->name, "gssapi-keyex") == 0) {
849 		gss_buffer_desc g_mic_data;
850 		Buffer mic_data;
851 
852 		debug2("Authenticating with GSS-API context from key exchange (w/ MIC)");
853 
854 		/* Make data buffer to MIC */
855 		buffer_init(&mic_data);
856 		buffer_put_string(&mic_data, session_id2, session_id2_len);
857 		buffer_put_char(&mic_data, SSH2_MSG_USERAUTH_REQUEST);
858 		buffer_put_cstring(&mic_data, authctxt->server_user);
859 		buffer_put_cstring(&mic_data, authctxt->service);
860 		buffer_put_cstring(&mic_data, authctxt->method->name);
861 
862 		/* Make MIC */
863 		g_mic_data.value  = buffer_ptr(&mic_data);
864 		g_mic_data.length = buffer_len(&mic_data);
865 		status = ssh_gssapi_get_mic(gssctxt, &g_mic_data, &send_tok);
866 		buffer_clear(&mic_data);
867 
868 		if (GSS_ERROR(status) || send_tok.length == 0) {
869 			/*
870 			 * Oops, now what?  There's no error token...
871 			 * Next userauth
872 			 */
873 			debug("GSS_GetMIC() failed! - "
874 			      "Abandoning GSSAPI userauth");
875 			clear_auth_state(authctxt);
876 			userauth(authctxt,NULL);
877 			return 0;
878 		}
879 		packet_start(SSH2_MSG_USERAUTH_REQUEST);
880 		packet_put_cstring(authctxt->server_user);
881 		packet_put_cstring(authctxt->service);
882 		packet_put_cstring(authctxt->method->name);
883 		packet_put_string(send_tok.value,send_tok.length); /* MIC */
884 		packet_send();
885 		packet_write_wait();
886 		(void) gss_release_buffer(&status, &send_tok);
887 	} else if (strcmp(authctxt->method->name, "external-keyx") == 0) {
888 		debug2("Authentication with deprecated \"external-keyx\""
889 			" method not supported");
890 		return 0;
891 	}
892         return 1;
893 }
894 
895 static
896 void
userauth_gssapi_cleanup(Authctxt * authctxt)897 userauth_gssapi_cleanup(Authctxt *authctxt)
898 {
899 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,NULL);
900 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,NULL);
901 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR,NULL);
902 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,NULL);
903 
904 	if (authctxt == NULL ||
905 	    authctxt->method == NULL ||
906 	    authctxt->methoddata == NULL)
907 		return;
908 
909 	if (strncmp(authctxt->method->name, "gssapi", strlen("gssapi")) == 0) {
910 		ssh_gssapi_delete_ctx((Gssctxt **)&authctxt->methoddata);
911 	}
912 }
913 #endif /* GSSAPI */
914 
915 int
userauth_none(Authctxt * authctxt)916 userauth_none(Authctxt *authctxt)
917 {
918 	/* initial userauth request */
919 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
920 	packet_put_cstring(authctxt->server_user);
921 	packet_put_cstring(authctxt->service);
922 	packet_put_cstring(authctxt->method->name);
923 	packet_send();
924 	return 1;
925 
926 }
927 
928 int
userauth_passwd(Authctxt * authctxt)929 userauth_passwd(Authctxt *authctxt)
930 {
931 	static int attempt = 0;
932 	char prompt[150];
933 	char *password;
934 
935 	if (attempt++ >= options.number_of_password_prompts)
936 		return 0;
937 
938 	if (attempt != 1)
939 		error("Permission denied, please try again.");
940 
941 	snprintf(prompt, sizeof(prompt), gettext("%.30s@%.128s's password: "),
942 	    authctxt->server_user, authctxt->host);
943 	password = read_passphrase(prompt, 0);
944 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
945 	packet_put_cstring(authctxt->server_user);
946 	packet_put_cstring(authctxt->service);
947 	packet_put_cstring(authctxt->method->name);
948 	packet_put_char(0);
949 	packet_put_cstring(password);
950 	memset(password, 0, strlen(password));
951 	xfree(password);
952 	packet_add_padding(64);
953 	packet_send();
954 
955 	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
956 	    &input_userauth_passwd_changereq);
957 
958 	return 1;
959 }
960 /*
961  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
962  */
963 void
input_userauth_passwd_changereq(int type,u_int32_t seqnr,void * ctxt)964 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
965 {
966 	Authctxt *authctxt = ctxt;
967 	char *info, *lang, *password = NULL, *retype = NULL;
968 	char prompt[150];
969 
970 	debug2("input_userauth_passwd_changereq");
971 
972 	if (authctxt == NULL)
973 		fatal("input_userauth_passwd_changereq: "
974 		    "no authentication context");
975 
976 	info = packet_get_utf8_string(NULL);
977 	if (strlen(info) != 0) {
978 		info = g11n_filter_string(info);
979 		log("%s", info);
980 	}
981 	xfree(info);
982 	lang = packet_get_string(NULL);
983 	xfree(lang);
984 
985 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
986 	packet_put_cstring(authctxt->server_user);
987 	packet_put_cstring(authctxt->service);
988 	packet_put_cstring(authctxt->method->name);
989 	packet_put_char(1);			/* additional info */
990 	snprintf(prompt, sizeof(prompt),
991 	    gettext("Enter %.30s@%.128s's old password: "),
992 	    authctxt->server_user, authctxt->host);
993 	password = read_passphrase(prompt, 0);
994 	packet_put_cstring(password);
995 	memset(password, 0, strlen(password));
996 	xfree(password);
997 	password = NULL;
998 	while (password == NULL) {
999 		snprintf(prompt, sizeof(prompt),
1000 		    gettext("Enter %.30s@%.128s's new password: "),
1001 		    authctxt->server_user, authctxt->host);
1002 		password = read_passphrase(prompt, RP_ALLOW_EOF);
1003 		if (password == NULL) {
1004 			/* bail out */
1005 			return;
1006 		}
1007 		snprintf(prompt, sizeof(prompt),
1008 		    gettext("Retype %.30s@%.128s's new password: "),
1009 		    authctxt->server_user, authctxt->host);
1010 		retype = read_passphrase(prompt, 0);
1011 		if (strcmp(password, retype) != 0) {
1012 			memset(password, 0, strlen(password));
1013 			xfree(password);
1014 			log("Mismatch; try again, EOF to quit.");
1015 			password = NULL;
1016 		}
1017 		memset(retype, 0, strlen(retype));
1018 		xfree(retype);
1019 	}
1020 	packet_put_cstring(password);
1021 	memset(password, 0, strlen(password));
1022 	xfree(password);
1023 	packet_add_padding(64);
1024 	packet_send();
1025 
1026 	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1027 	    &input_userauth_passwd_changereq);
1028 }
1029 
1030 static void
clear_auth_state(Authctxt * authctxt)1031 clear_auth_state(Authctxt *authctxt)
1032 {
1033 	/* XXX clear authentication state */
1034 	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, NULL);
1035 #ifdef GSSAPI
1036 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,NULL);
1037 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,NULL);
1038 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR,NULL);
1039 #endif /* GSSAPI */
1040 
1041 	if (authctxt->last_key != NULL && authctxt->last_key_hint == -1) {
1042 		debug3("clear_auth_state: key_free %p", authctxt->last_key);
1043 		key_free(authctxt->last_key);
1044 	}
1045 	authctxt->last_key = NULL;
1046 	authctxt->last_key_hint = -2;
1047 	authctxt->last_key_sign = NULL;
1048 }
1049 
1050 static int
sign_and_send_pubkey(Authctxt * authctxt,Key * k,sign_cb_fn * sign_callback)1051 sign_and_send_pubkey(Authctxt *authctxt, Key *k, sign_cb_fn *sign_callback)
1052 {
1053 	Buffer b;
1054 	u_char *blob, *signature;
1055 	u_int bloblen, slen;
1056 	int skip = 0;
1057 	int ret = -1;
1058 	int have_sig = 1;
1059 
1060 	debug3("sign_and_send_pubkey");
1061 
1062 	if (key_to_blob(k, &blob, &bloblen) == 0) {
1063 		/* we cannot handle this key */
1064 		debug3("sign_and_send_pubkey: cannot handle key");
1065 		return 0;
1066 	}
1067 	/* data to be signed */
1068 	buffer_init(&b);
1069 	if (datafellows & SSH_OLD_SESSIONID) {
1070 		buffer_append(&b, session_id2, session_id2_len);
1071 		skip = session_id2_len;
1072 	} else {
1073 		buffer_put_string(&b, session_id2, session_id2_len);
1074 		skip = buffer_len(&b);
1075 	}
1076 	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1077 	buffer_put_cstring(&b, authctxt->server_user);
1078 	buffer_put_cstring(&b,
1079 	    datafellows & SSH_BUG_PKSERVICE ?
1080 	    "ssh-userauth" :
1081 	    authctxt->service);
1082 	if (datafellows & SSH_BUG_PKAUTH) {
1083 		buffer_put_char(&b, have_sig);
1084 	} else {
1085 		buffer_put_cstring(&b, authctxt->method->name);
1086 		buffer_put_char(&b, have_sig);
1087 		buffer_put_cstring(&b, key_ssh_name(k));
1088 	}
1089 	buffer_put_string(&b, blob, bloblen);
1090 
1091 	/* generate signature */
1092 	ret = (*sign_callback)(authctxt, k, &signature, &slen,
1093 	    buffer_ptr(&b), buffer_len(&b));
1094 	if (ret == -1) {
1095 		xfree(blob);
1096 		buffer_free(&b);
1097 		return 0;
1098 	}
1099 #ifdef DEBUG_PK
1100 	buffer_dump(&b);
1101 #endif
1102 	if (datafellows & SSH_BUG_PKSERVICE) {
1103 		buffer_clear(&b);
1104 		buffer_append(&b, session_id2, session_id2_len);
1105 		skip = session_id2_len;
1106 		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1107 		buffer_put_cstring(&b, authctxt->server_user);
1108 		buffer_put_cstring(&b, authctxt->service);
1109 		buffer_put_cstring(&b, authctxt->method->name);
1110 		buffer_put_char(&b, have_sig);
1111 		if (!(datafellows & SSH_BUG_PKAUTH))
1112 			buffer_put_cstring(&b, key_ssh_name(k));
1113 		buffer_put_string(&b, blob, bloblen);
1114 	}
1115 	xfree(blob);
1116 
1117 	/* append signature */
1118 	buffer_put_string(&b, signature, slen);
1119 	xfree(signature);
1120 
1121 	/* skip session id and packet type */
1122 	if (buffer_len(&b) < skip + 1)
1123 		fatal("userauth_pubkey: internal error");
1124 	buffer_consume(&b, skip + 1);
1125 
1126 	/* put remaining data from buffer into packet */
1127 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1128 	packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1129 	buffer_free(&b);
1130 	packet_send();
1131 
1132 	return 1;
1133 }
1134 
1135 static int
send_pubkey_test(Authctxt * authctxt,Key * k,sign_cb_fn * sign_callback,int hint)1136 send_pubkey_test(Authctxt *authctxt, Key *k, sign_cb_fn *sign_callback,
1137     int hint)
1138 {
1139 	u_char *blob;
1140 	u_int bloblen, have_sig = 0;
1141 
1142 	debug3("send_pubkey_test");
1143 
1144 	if (key_to_blob(k, &blob, &bloblen) == 0) {
1145 		/* we cannot handle this key */
1146 		debug3("send_pubkey_test: cannot handle key");
1147 		return 0;
1148 	}
1149 	/* register callback for USERAUTH_PK_OK message */
1150 	authctxt->last_key_sign = sign_callback;
1151 	authctxt->last_key_hint = hint;
1152 	authctxt->last_key = k;
1153 	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1154 
1155 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1156 	packet_put_cstring(authctxt->server_user);
1157 	packet_put_cstring(authctxt->service);
1158 	packet_put_cstring(authctxt->method->name);
1159 	packet_put_char(have_sig);
1160 	if (!(datafellows & SSH_BUG_PKAUTH))
1161 		packet_put_cstring(key_ssh_name(k));
1162 	packet_put_string(blob, bloblen);
1163 	xfree(blob);
1164 	packet_send();
1165 	return 1;
1166 }
1167 
1168 static Key *
load_identity_file(char * filename)1169 load_identity_file(char *filename)
1170 {
1171 	Key *private;
1172 	char prompt[300], *passphrase;
1173 	int quit, i;
1174 	struct stat st;
1175 
1176 	if (stat(filename, &st) < 0) {
1177 		debug3("no such identity: %s", filename);
1178 		return NULL;
1179 	}
1180 	private = key_load_private_type(KEY_UNSPEC, filename, "", NULL);
1181 	if (private == NULL) {
1182 		if (options.batch_mode)
1183 			return NULL;
1184 		snprintf(prompt, sizeof prompt,
1185 		    gettext("Enter passphrase for key '%.100s': "), filename);
1186 		for (i = 0; i < options.number_of_password_prompts; i++) {
1187 			passphrase = read_passphrase(prompt, 0);
1188 			if (strcmp(passphrase, "") != 0) {
1189 				private = key_load_private_type(KEY_UNSPEC, filename,
1190 				    passphrase, NULL);
1191 				quit = 0;
1192 			} else {
1193 				debug2("no passphrase given, try next key");
1194 				quit = 1;
1195 			}
1196 			memset(passphrase, 0, strlen(passphrase));
1197 			xfree(passphrase);
1198 			if (private != NULL || quit)
1199 				break;
1200 			debug2("bad passphrase given, try again...");
1201 		}
1202 	}
1203 	return private;
1204 }
1205 
1206 static int
identity_sign_cb(Authctxt * authctxt,Key * key,u_char ** sigp,u_int * lenp,u_char * data,u_int datalen)1207 identity_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
1208     u_char *data, u_int datalen)
1209 {
1210 	Key *private;
1211 	int idx, ret;
1212 
1213 	idx = authctxt->last_key_hint;
1214 	if (idx < 0)
1215 		return -1;
1216 
1217 	/* private key is stored in external hardware */
1218 	if (options.identity_keys[idx]->flags & KEY_FLAG_EXT)
1219 		return key_sign(options.identity_keys[idx], sigp, lenp, data, datalen);
1220 
1221 	private = load_identity_file(options.identity_files[idx]);
1222 	if (private == NULL)
1223 		return -1;
1224 	ret = key_sign(private, sigp, lenp, data, datalen);
1225 	key_free(private);
1226 	return ret;
1227 }
1228 
1229 static int
agent_sign_cb(Authctxt * authctxt,Key * key,u_char ** sigp,u_int * lenp,u_char * data,u_int datalen)1230 agent_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
1231     u_char *data, u_int datalen)
1232 {
1233 	return ssh_agent_sign(authctxt->agent, key, sigp, lenp, data, datalen);
1234 }
1235 
1236 static int
key_sign_cb(Authctxt * authctxt,Key * key,u_char ** sigp,u_int * lenp,u_char * data,u_int datalen)1237 key_sign_cb(Authctxt *authctxt, Key *key, u_char **sigp, u_int *lenp,
1238     u_char *data, u_int datalen)
1239 {
1240 	return key_sign(key, sigp, lenp, data, datalen);
1241 }
1242 
1243 static int
userauth_pubkey_agent(Authctxt * authctxt)1244 userauth_pubkey_agent(Authctxt *authctxt)
1245 {
1246 	static int called = 0;
1247 	int ret = 0;
1248 	char *comment;
1249 	Key *k;
1250 
1251 	if (called == 0) {
1252 		if (ssh_get_num_identities(authctxt->agent, 2) == 0)
1253 			debug2("userauth_pubkey_agent: no keys at all");
1254 		called = 1;
1255 	}
1256 	k = ssh_get_next_identity(authctxt->agent, &comment, 2);
1257 	if (k == NULL) {
1258 		debug2("userauth_pubkey_agent: no more keys");
1259 	} else {
1260 		debug("Offering agent key: %s", comment);
1261 		xfree(comment);
1262 		ret = send_pubkey_test(authctxt, k, agent_sign_cb, -1);
1263 		if (ret == 0)
1264 			key_free(k);
1265 	}
1266 	if (ret == 0)
1267 		debug2("userauth_pubkey_agent: no message sent");
1268 	return ret;
1269 }
1270 
1271 int
userauth_pubkey(Authctxt * authctxt)1272 userauth_pubkey(Authctxt *authctxt)
1273 {
1274 	static int idx = 0;
1275 	int sent = 0;
1276 	Key *key;
1277 	char *filename;
1278 
1279 	if (authctxt->agent != NULL) {
1280 		do {
1281 			sent = userauth_pubkey_agent(authctxt);
1282 		} while (!sent && authctxt->agent->howmany > 0);
1283 	}
1284 	while (!sent && idx < options.num_identity_files) {
1285 		key = options.identity_keys[idx];
1286 		filename = options.identity_files[idx];
1287 		if (key == NULL) {
1288 			debug("Trying private key: %s", filename);
1289 			key = load_identity_file(filename);
1290 			if (key != NULL) {
1291 				sent = sign_and_send_pubkey(authctxt, key,
1292 				    key_sign_cb);
1293 				key_free(key);
1294 			}
1295 		} else if (key->type != KEY_RSA1) {
1296 			debug("Trying public key: %s", filename);
1297 			sent = send_pubkey_test(authctxt, key,
1298 			    identity_sign_cb, idx);
1299 		}
1300 		idx++;
1301 	}
1302 	return sent;
1303 }
1304 
1305 /*
1306  * Send userauth request message specifying keyboard-interactive method.
1307  */
1308 int
userauth_kbdint(Authctxt * authctxt)1309 userauth_kbdint(Authctxt *authctxt)
1310 {
1311 	static int attempt = 0;
1312 
1313 	if (attempt++ >= options.number_of_password_prompts)
1314 		return 0;
1315 	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1316 	if (attempt > 1 && !authctxt->info_req_seen) {
1317 		debug3("userauth_kbdint: disable: no info_req_seen");
1318 		dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1319 		return 0;
1320 	}
1321 
1322 	debug2("userauth_kbdint");
1323 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1324 	packet_put_cstring(authctxt->server_user);
1325 	packet_put_cstring(authctxt->service);
1326 	packet_put_cstring(authctxt->method->name);
1327 	packet_put_cstring("");					/* lang */
1328 	packet_put_cstring(options.kbd_interactive_devices ?
1329 	    options.kbd_interactive_devices : "");
1330 	packet_send();
1331 
1332 	dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1333 	return 1;
1334 }
1335 
1336 /*
1337  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1338  */
1339 void
input_userauth_info_req(int type,u_int32_t seq,void * ctxt)1340 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1341 {
1342 	Authctxt *authctxt = ctxt;
1343 	char *name, *inst, *lang, *prompt, *response;
1344 	u_int num_prompts, i;
1345 	int echo = 0;
1346 
1347 	debug2("input_userauth_info_req");
1348 
1349 	if (authctxt == NULL)
1350 		fatal("input_userauth_info_req: no authentication context");
1351 
1352 	authctxt->info_req_seen = 1;
1353 
1354 	/*
1355 	 * We assume that ASCII is used for user name although it is defined
1356 	 * by the protocol to use UTF-8 encoding. Therefore, we don't perform
1357 	 * code conversion from UTF-8 to native codeset for the user name
1358 	 * string.
1359 	 */
1360 	name = packet_get_string(NULL);
1361 	inst = packet_get_utf8_string(NULL);
1362 	lang = packet_get_string(NULL);
1363 	if (strlen(name) != 0) {
1364 		name = g11n_filter_string(name);
1365 		log("%s", name);
1366 	}
1367 	if (strlen(inst) != 0) {
1368 		inst = g11n_filter_string(inst);
1369 		log("%s", inst);
1370 	}
1371 	xfree(name);
1372 	xfree(inst);
1373 	xfree(lang);
1374 
1375 	num_prompts = packet_get_int();
1376 	/*
1377 	 * Begin to build info response packet based on prompts requested.
1378 	 * We commit to providing the correct number of responses, so if
1379 	 * further on we run into a problem that prevents this, we have to
1380 	 * be sure and clean this up and send a correct error response.
1381 	 */
1382 	packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1383 	packet_put_int(num_prompts);
1384 
1385 	debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1386 	for (i = 0; i < num_prompts; i++) {
1387 		prompt = packet_get_utf8_string(NULL);
1388 		echo = packet_get_char();
1389 
1390 		prompt = g11n_filter_string(prompt);
1391 		response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1392 
1393 		/*
1394 	 	 * We assume that ASCII is used for password as well. We
1395 		 * don't perform code conversion from native codeset to
1396 		 * UTF-8 for the password string.
1397 		 */
1398 		packet_put_cstring(response);
1399 		memset(response, 0, strlen(response));
1400 		xfree(response);
1401 		xfree(prompt);
1402 	}
1403 	packet_check_eom(); /* done with parsing incoming message. */
1404 
1405 	packet_add_padding(64);
1406 	packet_send();
1407 }
1408 
1409 static int
ssh_keysign(Key * key,u_char ** sigp,u_int * lenp,u_char * data,u_int datalen)1410 ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1411     u_char *data, u_int datalen)
1412 {
1413 	Buffer b;
1414 	struct stat st;
1415 	pid_t pid;
1416 	int to[2], from[2], status, version = 2;
1417 
1418 	debug2("ssh_keysign called");
1419 
1420 	if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1421 		error("ssh_keysign: no installed: %s", strerror(errno));
1422 		return -1;
1423 	}
1424 	if (fflush(stdout) != 0)
1425 		error("ssh_keysign: fflush: %s", strerror(errno));
1426 	if (pipe(to) < 0) {
1427 		error("ssh_keysign: pipe: %s", strerror(errno));
1428 		return -1;
1429 	}
1430 	if (pipe(from) < 0) {
1431 		error("ssh_keysign: pipe: %s", strerror(errno));
1432 		return -1;
1433 	}
1434 	if ((pid = fork()) < 0) {
1435 		error("ssh_keysign: fork: %s", strerror(errno));
1436 		return -1;
1437 	}
1438 	if (pid == 0) {
1439 		seteuid(getuid());
1440 		setuid(getuid());
1441 		close(from[0]);
1442 		if (dup2(from[1], STDOUT_FILENO) < 0)
1443 			fatal("ssh_keysign: dup2: %s", strerror(errno));
1444 		close(to[1]);
1445 		if (dup2(to[0], STDIN_FILENO) < 0)
1446 			fatal("ssh_keysign: dup2: %s", strerror(errno));
1447 		close(from[1]);
1448 		close(to[0]);
1449 		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1450 		fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1451 		    strerror(errno));
1452 	}
1453 	close(from[1]);
1454 	close(to[0]);
1455 
1456 	buffer_init(&b);
1457 	buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1458 	buffer_put_string(&b, data, datalen);
1459 	ssh_msg_send(to[1], version, &b);
1460 
1461 	if (ssh_msg_recv(from[0], &b) < 0) {
1462 		error("ssh_keysign: no reply");
1463 		buffer_clear(&b);
1464 		return -1;
1465 	}
1466 	close(from[0]);
1467 	close(to[1]);
1468 
1469 	while (waitpid(pid, &status, 0) < 0)
1470 		if (errno != EINTR)
1471 			break;
1472 
1473 	if (buffer_get_char(&b) != version) {
1474 		error("ssh_keysign: bad version");
1475 		buffer_clear(&b);
1476 		return -1;
1477 	}
1478 	*sigp = buffer_get_string(&b, lenp);
1479 	buffer_clear(&b);
1480 
1481 	return 0;
1482 }
1483 
1484 int
userauth_hostbased(Authctxt * authctxt)1485 userauth_hostbased(Authctxt *authctxt)
1486 {
1487 	Key *private = NULL;
1488 	Sensitive *sensitive = authctxt->sensitive;
1489 	Buffer b;
1490 	u_char *signature, *blob;
1491 	char *chost, *pkalg, *p;
1492 	const char *service;
1493 	u_int blen, slen;
1494 	int ok, i, len, found = 0;
1495 	static int last_hostkey = -1;
1496 
1497 	/* check for a useful key */
1498 	for (i = 0; i < sensitive->nkeys; i++) {
1499 		private = sensitive->keys[i];
1500 		if (private && private->type != KEY_RSA1 && i > last_hostkey) {
1501 			found = 1;
1502 			last_hostkey = i;
1503 			/* we take and free the key */
1504 			sensitive->keys[i] = NULL;
1505 			break;
1506 		}
1507 	}
1508 	if (!found) {
1509 		debug("No more client hostkeys for hostbased authentication");
1510 		return 0;
1511 	}
1512 	if (key_to_blob(private, &blob, &blen) == 0) {
1513 		key_free(private);
1514 		return 0;
1515 	}
1516 	/* figure out a name for the client host */
1517 	p = get_local_name(packet_get_connection_in());
1518 	if (p == NULL) {
1519 		error("userauth_hostbased: cannot get local ipaddr/name");
1520 		key_free(private);
1521 		return 0;
1522 	}
1523 
1524 	service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1525 	    authctxt->service;
1526 	pkalg = xstrdup(key_ssh_name(private));
1527 
1528 	len = strlen(p) + 2;
1529 	chost = xmalloc(len);
1530 	strlcpy(chost, p, len);
1531 	strlcat(chost, ".", len);
1532 	xfree(p);
1533 	debug2("userauth_hostbased: chost %s, pkalg %s", chost, pkalg);
1534 
1535 	buffer_init(&b);
1536 	/* construct data */
1537 	buffer_put_string(&b, session_id2, session_id2_len);
1538 	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1539 	buffer_put_cstring(&b, authctxt->server_user);
1540 	buffer_put_cstring(&b, service);
1541 	buffer_put_cstring(&b, authctxt->method->name);
1542 	buffer_put_cstring(&b, pkalg);
1543 	buffer_put_string(&b, blob, blen);
1544 	buffer_put_cstring(&b, chost);
1545 	buffer_put_cstring(&b, authctxt->local_user);
1546 #ifdef DEBUG_PK
1547 	buffer_dump(&b);
1548 #endif
1549 	if (sensitive->external_keysign)
1550 		ok = ssh_keysign(private, &signature, &slen,
1551 		    buffer_ptr(&b), buffer_len(&b));
1552 	else
1553 		ok = key_sign(private, &signature, &slen,
1554 		    buffer_ptr(&b), buffer_len(&b));
1555 	key_free(private);
1556 	buffer_free(&b);
1557 	if (ok != 0) {
1558 		error("key_sign failed");
1559 		xfree(chost);
1560 		xfree(pkalg);
1561 		return 0;
1562 	}
1563 	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1564 	packet_put_cstring(authctxt->server_user);
1565 	packet_put_cstring(authctxt->service);
1566 	packet_put_cstring(authctxt->method->name);
1567 	packet_put_cstring(pkalg);
1568 	packet_put_string(blob, blen);
1569 	packet_put_cstring(chost);
1570 	packet_put_cstring(authctxt->local_user);
1571 	packet_put_string(signature, slen);
1572 	memset(signature, 's', slen);
1573 	xfree(signature);
1574 	xfree(chost);
1575 	xfree(pkalg);
1576 
1577 	packet_send();
1578 	return 1;
1579 }
1580 
1581 /* find auth method */
1582 
1583 /*
1584  * given auth method name, if configurable options permit this method fill
1585  * in auth_ident field and return true, otherwise return false.
1586  */
1587 static int
authmethod_is_enabled(Authmethod * method)1588 authmethod_is_enabled(Authmethod *method)
1589 {
1590 	if (method == NULL)
1591 		return 0;
1592 	/* return false if options indicate this method is disabled */
1593 	if  (method->enabled == NULL || *method->enabled == 0)
1594 		return 0;
1595 	/* return false if batch mode is enabled but method needs interactive mode */
1596 	if  (method->batch_flag != NULL && *method->batch_flag != 0)
1597 		return 0;
1598 	return 1;
1599 }
1600 
1601 static Authmethod *
authmethod_lookup(const char * name)1602 authmethod_lookup(const char *name)
1603 {
1604 	Authmethod *method = NULL;
1605 	if (name != NULL) {
1606 		for (method = authmethods; method->name != NULL; method++) {
1607 			if (strcmp(name, method->name) == 0)
1608 				return method;
1609 		}
1610 	}
1611 	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1612 	return NULL;
1613 }
1614 
1615 /* XXX internal state */
1616 static Authmethod *current = NULL;
1617 static char *supported = NULL;
1618 static char *preferred = NULL;
1619 
1620 /*
1621  * Given the authentication method list sent by the server, return the
1622  * next method we should try.  If the server initially sends a nil list,
1623  * use a built-in default list.
1624  */
1625 static Authmethod *
authmethod_get(char * authlist)1626 authmethod_get(char *authlist)
1627 {
1628 	char *name = NULL;
1629 	u_int next;
1630 
1631 	/* Use a suitable default if we're passed a nil list.  */
1632 	if (authlist == NULL || strlen(authlist) == 0)
1633 		authlist = options.preferred_authentications;
1634 
1635 	if (supported == NULL || strcmp(authlist, supported) != 0) {
1636 		debug3("start over, passed a different list %s", authlist);
1637 		if (supported != NULL)
1638 			xfree(supported);
1639 		supported = xstrdup(authlist);
1640 		preferred = options.preferred_authentications;
1641 		debug3("preferred %s", preferred);
1642 		current = NULL;
1643 	} else if (current != NULL && authmethod_is_enabled(current))
1644 		return current;
1645 
1646 	for (;;) {
1647 		if ((name = match_list(preferred, supported, &next)) == NULL) {
1648 			debug("No more authentication methods to try.");
1649 			current = NULL;
1650 			return NULL;
1651 		}
1652 		preferred += next;
1653 		debug3("authmethod_lookup %s", name);
1654 		debug3("remaining preferred: %s", preferred);
1655 		if ((current = authmethod_lookup(name)) != NULL &&
1656 		    authmethod_is_enabled(current)) {
1657 			debug3("authmethod_is_enabled %s", name);
1658 			debug("Next authentication method: %s", name);
1659 			xfree(name);
1660 			return current;
1661 		}
1662 		xfree(name);
1663 	}
1664 }
1665 
1666 static char *
authmethods_get(void)1667 authmethods_get(void)
1668 {
1669 	Authmethod *method = NULL;
1670 	Buffer b;
1671 	char *list;
1672 
1673 	buffer_init(&b);
1674 	for (method = authmethods; method->name != NULL; method++) {
1675 		if (authmethod_is_enabled(method)) {
1676 			if (buffer_len(&b) > 0)
1677 				buffer_append(&b, ",", 1);
1678 			buffer_append(&b, method->name, strlen(method->name));
1679 		}
1680 	}
1681 	buffer_append(&b, "\0", 1);
1682 	list = xstrdup(buffer_ptr(&b));
1683 	buffer_free(&b);
1684 	return list;
1685 }
1686