- (dtucker) Bug #1840: fix warning when configuring --with-ssl-engine, patch
[openssh-git.git] / sshconnect2.c
blob6fe356ccaa9eaf3e3ce0eb790076d764ed2e15df
1 /* $OpenBSD: sshconnect2.c,v 1.185 2010/09/22 05:01:29 djm Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2008 Damien Miller. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "includes.h"
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <netdb.h>
37 #include <pwd.h>
38 #include <signal.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <unistd.h>
43 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H)
44 #include <vis.h>
45 #endif
47 #include "openbsd-compat/sys-queue.h"
49 #include "xmalloc.h"
50 #include "ssh.h"
51 #include "ssh2.h"
52 #include "buffer.h"
53 #include "packet.h"
54 #include "compat.h"
55 #include "cipher.h"
56 #include "key.h"
57 #include "kex.h"
58 #include "myproposal.h"
59 #include "sshconnect.h"
60 #include "authfile.h"
61 #include "dh.h"
62 #include "authfd.h"
63 #include "log.h"
64 #include "readconf.h"
65 #include "misc.h"
66 #include "match.h"
67 #include "dispatch.h"
68 #include "canohost.h"
69 #include "msg.h"
70 #include "pathnames.h"
71 #include "uidswap.h"
72 #include "schnorr.h"
73 #include "jpake.h"
75 #ifdef GSSAPI
76 #include "ssh-gss.h"
77 #endif
79 /* import */
80 extern char *client_version_string;
81 extern char *server_version_string;
82 extern Options options;
85 * SSH2 key exchange
88 u_char *session_id2 = NULL;
89 u_int session_id2_len = 0;
91 char *xxx_host;
92 struct sockaddr *xxx_hostaddr;
94 Kex *xxx_kex = NULL;
96 static int
97 verify_host_key_callback(Key *hostkey)
99 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
100 fatal("Host key verification failed.");
101 return 0;
104 void
105 ssh_kex2(char *host, struct sockaddr *hostaddr)
107 Kex *kex;
109 xxx_host = host;
110 xxx_hostaddr = hostaddr;
112 if (options.ciphers == (char *)-1) {
113 logit("No valid ciphers for protocol version 2 given, using defaults.");
114 options.ciphers = NULL;
116 if (options.ciphers != NULL) {
117 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
118 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
120 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
121 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
122 myproposal[PROPOSAL_ENC_ALGS_STOC] =
123 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
124 if (options.compression) {
125 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
126 myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib@openssh.com,zlib,none";
127 } else {
128 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
129 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com,zlib";
131 if (options.macs != NULL) {
132 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
133 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
135 if (options.hostkeyalgorithms != NULL)
136 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
137 options.hostkeyalgorithms;
138 if (options.kex_algorithms != NULL)
139 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
141 if (options.rekey_limit)
142 packet_set_rekey_limit((u_int32_t)options.rekey_limit);
144 /* start key exchange */
145 kex = kex_setup(myproposal);
146 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
147 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
148 kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
149 kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
150 kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
151 kex->client_version_string=client_version_string;
152 kex->server_version_string=server_version_string;
153 kex->verify_host_key=&verify_host_key_callback;
155 xxx_kex = kex;
157 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
159 if (options.use_roaming && !kex->roaming) {
160 debug("Roaming not allowed by server");
161 options.use_roaming = 0;
164 session_id2 = kex->session_id;
165 session_id2_len = kex->session_id_len;
167 #ifdef DEBUG_KEXDH
168 /* send 1st encrypted/maced/compressed message */
169 packet_start(SSH2_MSG_IGNORE);
170 packet_put_cstring("markus");
171 packet_send();
172 packet_write_wait();
173 #endif
177 * Authenticate user
180 typedef struct Authctxt Authctxt;
181 typedef struct Authmethod Authmethod;
182 typedef struct identity Identity;
183 typedef struct idlist Idlist;
185 struct identity {
186 TAILQ_ENTRY(identity) next;
187 AuthenticationConnection *ac; /* set if agent supports key */
188 Key *key; /* public/private key */
189 char *filename; /* comment for agent-only keys */
190 int tried;
191 int isprivate; /* key points to the private key */
193 TAILQ_HEAD(idlist, identity);
195 struct Authctxt {
196 const char *server_user;
197 const char *local_user;
198 const char *host;
199 const char *service;
200 Authmethod *method;
201 sig_atomic_t success;
202 char *authlist;
203 /* pubkey */
204 Idlist keys;
205 AuthenticationConnection *agent;
206 /* hostbased */
207 Sensitive *sensitive;
208 /* kbd-interactive */
209 int info_req_seen;
210 /* generic */
211 void *methoddata;
213 struct Authmethod {
214 char *name; /* string to compare against server's list */
215 int (*userauth)(Authctxt *authctxt);
216 void (*cleanup)(Authctxt *authctxt);
217 int *enabled; /* flag in option struct that enables method */
218 int *batch_flag; /* flag in option struct that disables method */
221 void input_userauth_success(int, u_int32_t, void *);
222 void input_userauth_success_unexpected(int, u_int32_t, void *);
223 void input_userauth_failure(int, u_int32_t, void *);
224 void input_userauth_banner(int, u_int32_t, void *);
225 void input_userauth_error(int, u_int32_t, void *);
226 void input_userauth_info_req(int, u_int32_t, void *);
227 void input_userauth_pk_ok(int, u_int32_t, void *);
228 void input_userauth_passwd_changereq(int, u_int32_t, void *);
229 void input_userauth_jpake_server_step1(int, u_int32_t, void *);
230 void input_userauth_jpake_server_step2(int, u_int32_t, void *);
231 void input_userauth_jpake_server_confirm(int, u_int32_t, void *);
233 int userauth_none(Authctxt *);
234 int userauth_pubkey(Authctxt *);
235 int userauth_passwd(Authctxt *);
236 int userauth_kbdint(Authctxt *);
237 int userauth_hostbased(Authctxt *);
238 int userauth_jpake(Authctxt *);
240 void userauth_jpake_cleanup(Authctxt *);
242 #ifdef GSSAPI
243 int userauth_gssapi(Authctxt *authctxt);
244 void input_gssapi_response(int type, u_int32_t, void *);
245 void input_gssapi_token(int type, u_int32_t, void *);
246 void input_gssapi_hash(int type, u_int32_t, void *);
247 void input_gssapi_error(int, u_int32_t, void *);
248 void input_gssapi_errtok(int, u_int32_t, void *);
249 #endif
251 void userauth(Authctxt *, char *);
253 static int sign_and_send_pubkey(Authctxt *, Identity *);
254 static void pubkey_prepare(Authctxt *);
255 static void pubkey_cleanup(Authctxt *);
256 static Key *load_identity_file(char *);
258 static Authmethod *authmethod_get(char *authlist);
259 static Authmethod *authmethod_lookup(const char *name);
260 static char *authmethods_get(void);
262 Authmethod authmethods[] = {
263 #ifdef GSSAPI
264 {"gssapi-with-mic",
265 userauth_gssapi,
266 NULL,
267 &options.gss_authentication,
268 NULL},
269 #endif
270 {"hostbased",
271 userauth_hostbased,
272 NULL,
273 &options.hostbased_authentication,
274 NULL},
275 {"publickey",
276 userauth_pubkey,
277 NULL,
278 &options.pubkey_authentication,
279 NULL},
280 #ifdef JPAKE
281 {"jpake-01@openssh.com",
282 userauth_jpake,
283 userauth_jpake_cleanup,
284 &options.zero_knowledge_password_authentication,
285 &options.batch_mode},
286 #endif
287 {"keyboard-interactive",
288 userauth_kbdint,
289 NULL,
290 &options.kbd_interactive_authentication,
291 &options.batch_mode},
292 {"password",
293 userauth_passwd,
294 NULL,
295 &options.password_authentication,
296 &options.batch_mode},
297 {"none",
298 userauth_none,
299 NULL,
300 NULL,
301 NULL},
302 {NULL, NULL, NULL, NULL, NULL}
305 void
306 ssh_userauth2(const char *local_user, const char *server_user, char *host,
307 Sensitive *sensitive)
309 Authctxt authctxt;
310 int type;
312 if (options.challenge_response_authentication)
313 options.kbd_interactive_authentication = 1;
315 packet_start(SSH2_MSG_SERVICE_REQUEST);
316 packet_put_cstring("ssh-userauth");
317 packet_send();
318 debug("SSH2_MSG_SERVICE_REQUEST sent");
319 packet_write_wait();
320 type = packet_read();
321 if (type != SSH2_MSG_SERVICE_ACCEPT)
322 fatal("Server denied authentication request: %d", type);
323 if (packet_remaining() > 0) {
324 char *reply = packet_get_string(NULL);
325 debug2("service_accept: %s", reply);
326 xfree(reply);
327 } else {
328 debug2("buggy server: service_accept w/o service");
330 packet_check_eom();
331 debug("SSH2_MSG_SERVICE_ACCEPT received");
333 if (options.preferred_authentications == NULL)
334 options.preferred_authentications = authmethods_get();
336 /* setup authentication context */
337 memset(&authctxt, 0, sizeof(authctxt));
338 pubkey_prepare(&authctxt);
339 authctxt.server_user = server_user;
340 authctxt.local_user = local_user;
341 authctxt.host = host;
342 authctxt.service = "ssh-connection"; /* service name */
343 authctxt.success = 0;
344 authctxt.method = authmethod_lookup("none");
345 authctxt.authlist = NULL;
346 authctxt.methoddata = NULL;
347 authctxt.sensitive = sensitive;
348 authctxt.info_req_seen = 0;
349 if (authctxt.method == NULL)
350 fatal("ssh_userauth2: internal error: cannot send userauth none request");
352 /* initial userauth request */
353 userauth_none(&authctxt);
355 dispatch_init(&input_userauth_error);
356 dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
357 dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
358 dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
359 dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt); /* loop until success */
361 pubkey_cleanup(&authctxt);
362 dispatch_range(SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
364 debug("Authentication succeeded (%s).", authctxt.method->name);
367 void
368 userauth(Authctxt *authctxt, char *authlist)
370 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
371 authctxt->method->cleanup(authctxt);
373 if (authctxt->methoddata) {
374 xfree(authctxt->methoddata);
375 authctxt->methoddata = NULL;
377 if (authlist == NULL) {
378 authlist = authctxt->authlist;
379 } else {
380 if (authctxt->authlist)
381 xfree(authctxt->authlist);
382 authctxt->authlist = authlist;
384 for (;;) {
385 Authmethod *method = authmethod_get(authlist);
386 if (method == NULL)
387 fatal("Permission denied (%s).", authlist);
388 authctxt->method = method;
390 /* reset the per method handler */
391 dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
392 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
394 /* and try new method */
395 if (method->userauth(authctxt) != 0) {
396 debug2("we sent a %s packet, wait for reply", method->name);
397 break;
398 } else {
399 debug2("we did not send a packet, disable method");
400 method->enabled = NULL;
405 /* ARGSUSED */
406 void
407 input_userauth_error(int type, u_int32_t seq, void *ctxt)
409 fatal("input_userauth_error: bad message during authentication: "
410 "type %d", type);
413 /* ARGSUSED */
414 void
415 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
417 char *msg, *raw, *lang;
418 u_int len;
420 debug3("input_userauth_banner");
421 raw = packet_get_string(&len);
422 lang = packet_get_string(NULL);
423 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) {
424 if (len > 65536)
425 len = 65536;
426 msg = xmalloc(len * 4 + 1); /* max expansion from strnvis() */
427 strnvis(msg, raw, len * 4 + 1, VIS_SAFE|VIS_OCTAL|VIS_NOSLASH);
428 fprintf(stderr, "%s", msg);
429 xfree(msg);
431 xfree(raw);
432 xfree(lang);
435 /* ARGSUSED */
436 void
437 input_userauth_success(int type, u_int32_t seq, void *ctxt)
439 Authctxt *authctxt = ctxt;
441 if (authctxt == NULL)
442 fatal("input_userauth_success: no authentication context");
443 if (authctxt->authlist) {
444 xfree(authctxt->authlist);
445 authctxt->authlist = NULL;
447 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
448 authctxt->method->cleanup(authctxt);
449 if (authctxt->methoddata) {
450 xfree(authctxt->methoddata);
451 authctxt->methoddata = NULL;
453 authctxt->success = 1; /* break out */
456 void
457 input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt)
459 Authctxt *authctxt = ctxt;
461 if (authctxt == NULL)
462 fatal("%s: no authentication context", __func__);
464 fatal("Unexpected authentication success during %s.",
465 authctxt->method->name);
468 /* ARGSUSED */
469 void
470 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
472 Authctxt *authctxt = ctxt;
473 char *authlist = NULL;
474 int partial;
476 if (authctxt == NULL)
477 fatal("input_userauth_failure: no authentication context");
479 authlist = packet_get_string(NULL);
480 partial = packet_get_char();
481 packet_check_eom();
483 if (partial != 0)
484 logit("Authenticated with partial success.");
485 debug("Authentications that can continue: %s", authlist);
487 userauth(authctxt, authlist);
490 /* ARGSUSED */
491 void
492 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
494 Authctxt *authctxt = ctxt;
495 Key *key = NULL;
496 Identity *id = NULL;
497 Buffer b;
498 int pktype, sent = 0;
499 u_int alen, blen;
500 char *pkalg, *fp;
501 u_char *pkblob;
503 if (authctxt == NULL)
504 fatal("input_userauth_pk_ok: no authentication context");
505 if (datafellows & SSH_BUG_PKOK) {
506 /* this is similar to SSH_BUG_PKAUTH */
507 debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
508 pkblob = packet_get_string(&blen);
509 buffer_init(&b);
510 buffer_append(&b, pkblob, blen);
511 pkalg = buffer_get_string(&b, &alen);
512 buffer_free(&b);
513 } else {
514 pkalg = packet_get_string(&alen);
515 pkblob = packet_get_string(&blen);
517 packet_check_eom();
519 debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
521 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
522 debug("unknown pkalg %s", pkalg);
523 goto done;
525 if ((key = key_from_blob(pkblob, blen)) == NULL) {
526 debug("no key from blob. pkalg %s", pkalg);
527 goto done;
529 if (key->type != pktype) {
530 error("input_userauth_pk_ok: type mismatch "
531 "for decoded key (received %d, expected %d)",
532 key->type, pktype);
533 goto done;
535 fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
536 debug2("input_userauth_pk_ok: fp %s", fp);
537 xfree(fp);
540 * search keys in the reverse order, because last candidate has been
541 * moved to the end of the queue. this also avoids confusion by
542 * duplicate keys
544 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
545 if (key_equal(key, id->key)) {
546 sent = sign_and_send_pubkey(authctxt, id);
547 break;
550 done:
551 if (key != NULL)
552 key_free(key);
553 xfree(pkalg);
554 xfree(pkblob);
556 /* try another method if we did not send a packet */
557 if (sent == 0)
558 userauth(authctxt, NULL);
561 #ifdef GSSAPI
563 userauth_gssapi(Authctxt *authctxt)
565 Gssctxt *gssctxt = NULL;
566 static gss_OID_set gss_supported = NULL;
567 static u_int mech = 0;
568 OM_uint32 min;
569 int ok = 0;
571 /* Try one GSSAPI method at a time, rather than sending them all at
572 * once. */
574 if (gss_supported == NULL)
575 gss_indicate_mechs(&min, &gss_supported);
577 /* Check to see if the mechanism is usable before we offer it */
578 while (mech < gss_supported->count && !ok) {
579 /* My DER encoding requires length<128 */
580 if (gss_supported->elements[mech].length < 128 &&
581 ssh_gssapi_check_mechanism(&gssctxt,
582 &gss_supported->elements[mech], authctxt->host)) {
583 ok = 1; /* Mechanism works */
584 } else {
585 mech++;
589 if (!ok)
590 return 0;
592 authctxt->methoddata=(void *)gssctxt;
594 packet_start(SSH2_MSG_USERAUTH_REQUEST);
595 packet_put_cstring(authctxt->server_user);
596 packet_put_cstring(authctxt->service);
597 packet_put_cstring(authctxt->method->name);
599 packet_put_int(1);
601 packet_put_int((gss_supported->elements[mech].length) + 2);
602 packet_put_char(SSH_GSS_OIDTYPE);
603 packet_put_char(gss_supported->elements[mech].length);
604 packet_put_raw(gss_supported->elements[mech].elements,
605 gss_supported->elements[mech].length);
607 packet_send();
609 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
610 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
611 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
612 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
614 mech++; /* Move along to next candidate */
616 return 1;
619 static OM_uint32
620 process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
622 Authctxt *authctxt = ctxt;
623 Gssctxt *gssctxt = authctxt->methoddata;
624 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
625 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
626 gss_buffer_desc gssbuf;
627 OM_uint32 status, ms, flags;
628 Buffer b;
630 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
631 recv_tok, &send_tok, &flags);
633 if (send_tok.length > 0) {
634 if (GSS_ERROR(status))
635 packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
636 else
637 packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
639 packet_put_string(send_tok.value, send_tok.length);
640 packet_send();
641 gss_release_buffer(&ms, &send_tok);
644 if (status == GSS_S_COMPLETE) {
645 /* send either complete or MIC, depending on mechanism */
646 if (!(flags & GSS_C_INTEG_FLAG)) {
647 packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
648 packet_send();
649 } else {
650 ssh_gssapi_buildmic(&b, authctxt->server_user,
651 authctxt->service, "gssapi-with-mic");
653 gssbuf.value = buffer_ptr(&b);
654 gssbuf.length = buffer_len(&b);
656 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
658 if (!GSS_ERROR(status)) {
659 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
660 packet_put_string(mic.value, mic.length);
662 packet_send();
665 buffer_free(&b);
666 gss_release_buffer(&ms, &mic);
670 return status;
673 /* ARGSUSED */
674 void
675 input_gssapi_response(int type, u_int32_t plen, void *ctxt)
677 Authctxt *authctxt = ctxt;
678 Gssctxt *gssctxt;
679 int oidlen;
680 char *oidv;
682 if (authctxt == NULL)
683 fatal("input_gssapi_response: no authentication context");
684 gssctxt = authctxt->methoddata;
686 /* Setup our OID */
687 oidv = packet_get_string(&oidlen);
689 if (oidlen <= 2 ||
690 oidv[0] != SSH_GSS_OIDTYPE ||
691 oidv[1] != oidlen - 2) {
692 xfree(oidv);
693 debug("Badly encoded mechanism OID received");
694 userauth(authctxt, NULL);
695 return;
698 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
699 fatal("Server returned different OID than expected");
701 packet_check_eom();
703 xfree(oidv);
705 if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
706 /* Start again with next method on list */
707 debug("Trying to start again");
708 userauth(authctxt, NULL);
709 return;
713 /* ARGSUSED */
714 void
715 input_gssapi_token(int type, u_int32_t plen, void *ctxt)
717 Authctxt *authctxt = ctxt;
718 gss_buffer_desc recv_tok;
719 OM_uint32 status;
720 u_int slen;
722 if (authctxt == NULL)
723 fatal("input_gssapi_response: no authentication context");
725 recv_tok.value = packet_get_string(&slen);
726 recv_tok.length = slen; /* safe typecast */
728 packet_check_eom();
730 status = process_gssapi_token(ctxt, &recv_tok);
732 xfree(recv_tok.value);
734 if (GSS_ERROR(status)) {
735 /* Start again with the next method in the list */
736 userauth(authctxt, NULL);
737 return;
741 /* ARGSUSED */
742 void
743 input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
745 Authctxt *authctxt = ctxt;
746 Gssctxt *gssctxt;
747 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
748 gss_buffer_desc recv_tok;
749 OM_uint32 status, ms;
750 u_int len;
752 if (authctxt == NULL)
753 fatal("input_gssapi_response: no authentication context");
754 gssctxt = authctxt->methoddata;
756 recv_tok.value = packet_get_string(&len);
757 recv_tok.length = len;
759 packet_check_eom();
761 /* Stick it into GSSAPI and see what it says */
762 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
763 &recv_tok, &send_tok, NULL);
765 xfree(recv_tok.value);
766 gss_release_buffer(&ms, &send_tok);
768 /* Server will be returning a failed packet after this one */
771 /* ARGSUSED */
772 void
773 input_gssapi_error(int type, u_int32_t plen, void *ctxt)
775 OM_uint32 maj, min;
776 char *msg;
777 char *lang;
779 maj=packet_get_int();
780 min=packet_get_int();
781 msg=packet_get_string(NULL);
782 lang=packet_get_string(NULL);
784 packet_check_eom();
786 debug("Server GSSAPI Error:\n%s", msg);
787 xfree(msg);
788 xfree(lang);
790 #endif /* GSSAPI */
793 userauth_none(Authctxt *authctxt)
795 /* initial userauth request */
796 packet_start(SSH2_MSG_USERAUTH_REQUEST);
797 packet_put_cstring(authctxt->server_user);
798 packet_put_cstring(authctxt->service);
799 packet_put_cstring(authctxt->method->name);
800 packet_send();
801 return 1;
805 userauth_passwd(Authctxt *authctxt)
807 static int attempt = 0;
808 char prompt[150];
809 char *password;
810 const char *host = options.host_key_alias ? options.host_key_alias :
811 authctxt->host;
813 if (attempt++ >= options.number_of_password_prompts)
814 return 0;
816 if (attempt != 1)
817 error("Permission denied, please try again.");
819 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
820 authctxt->server_user, host);
821 password = read_passphrase(prompt, 0);
822 packet_start(SSH2_MSG_USERAUTH_REQUEST);
823 packet_put_cstring(authctxt->server_user);
824 packet_put_cstring(authctxt->service);
825 packet_put_cstring(authctxt->method->name);
826 packet_put_char(0);
827 packet_put_cstring(password);
828 memset(password, 0, strlen(password));
829 xfree(password);
830 packet_add_padding(64);
831 packet_send();
833 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
834 &input_userauth_passwd_changereq);
836 return 1;
840 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
842 /* ARGSUSED */
843 void
844 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
846 Authctxt *authctxt = ctxt;
847 char *info, *lang, *password = NULL, *retype = NULL;
848 char prompt[150];
849 const char *host = options.host_key_alias ? options.host_key_alias :
850 authctxt->host;
852 debug2("input_userauth_passwd_changereq");
854 if (authctxt == NULL)
855 fatal("input_userauth_passwd_changereq: "
856 "no authentication context");
858 info = packet_get_string(NULL);
859 lang = packet_get_string(NULL);
860 if (strlen(info) > 0)
861 logit("%s", info);
862 xfree(info);
863 xfree(lang);
864 packet_start(SSH2_MSG_USERAUTH_REQUEST);
865 packet_put_cstring(authctxt->server_user);
866 packet_put_cstring(authctxt->service);
867 packet_put_cstring(authctxt->method->name);
868 packet_put_char(1); /* additional info */
869 snprintf(prompt, sizeof(prompt),
870 "Enter %.30s@%.128s's old password: ",
871 authctxt->server_user, host);
872 password = read_passphrase(prompt, 0);
873 packet_put_cstring(password);
874 memset(password, 0, strlen(password));
875 xfree(password);
876 password = NULL;
877 while (password == NULL) {
878 snprintf(prompt, sizeof(prompt),
879 "Enter %.30s@%.128s's new password: ",
880 authctxt->server_user, host);
881 password = read_passphrase(prompt, RP_ALLOW_EOF);
882 if (password == NULL) {
883 /* bail out */
884 return;
886 snprintf(prompt, sizeof(prompt),
887 "Retype %.30s@%.128s's new password: ",
888 authctxt->server_user, host);
889 retype = read_passphrase(prompt, 0);
890 if (strcmp(password, retype) != 0) {
891 memset(password, 0, strlen(password));
892 xfree(password);
893 logit("Mismatch; try again, EOF to quit.");
894 password = NULL;
896 memset(retype, 0, strlen(retype));
897 xfree(retype);
899 packet_put_cstring(password);
900 memset(password, 0, strlen(password));
901 xfree(password);
902 packet_add_padding(64);
903 packet_send();
905 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
906 &input_userauth_passwd_changereq);
909 #ifdef JPAKE
910 static char *
911 pw_encrypt(const char *password, const char *crypt_scheme, const char *salt)
913 /* OpenBSD crypt(3) handles all of these */
914 if (strcmp(crypt_scheme, "crypt") == 0 ||
915 strcmp(crypt_scheme, "bcrypt") == 0 ||
916 strcmp(crypt_scheme, "md5crypt") == 0 ||
917 strcmp(crypt_scheme, "crypt-extended") == 0)
918 return xstrdup(crypt(password, salt));
919 error("%s: unsupported password encryption scheme \"%.100s\"",
920 __func__, crypt_scheme);
921 return NULL;
924 static BIGNUM *
925 jpake_password_to_secret(Authctxt *authctxt, const char *crypt_scheme,
926 const char *salt)
928 char prompt[256], *password, *crypted;
929 u_char *secret;
930 u_int secret_len;
931 BIGNUM *ret;
933 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password (JPAKE): ",
934 authctxt->server_user, authctxt->host);
935 password = read_passphrase(prompt, 0);
937 if ((crypted = pw_encrypt(password, crypt_scheme, salt)) == NULL) {
938 logit("Disabling %s authentication", authctxt->method->name);
939 authctxt->method->enabled = NULL;
940 /* Continue with an empty password to fail gracefully */
941 crypted = xstrdup("");
944 #ifdef JPAKE_DEBUG
945 debug3("%s: salt = %s", __func__, salt);
946 debug3("%s: scheme = %s", __func__, crypt_scheme);
947 debug3("%s: crypted = %s", __func__, crypted);
948 #endif
950 if (hash_buffer(crypted, strlen(crypted), EVP_sha256(),
951 &secret, &secret_len) != 0)
952 fatal("%s: hash_buffer", __func__);
954 bzero(password, strlen(password));
955 bzero(crypted, strlen(crypted));
956 xfree(password);
957 xfree(crypted);
959 if ((ret = BN_bin2bn(secret, secret_len, NULL)) == NULL)
960 fatal("%s: BN_bin2bn (secret)", __func__);
961 bzero(secret, secret_len);
962 xfree(secret);
964 return ret;
967 /* ARGSUSED */
968 void
969 input_userauth_jpake_server_step1(int type, u_int32_t seq, void *ctxt)
971 Authctxt *authctxt = ctxt;
972 struct jpake_ctx *pctx = authctxt->methoddata;
973 u_char *x3_proof, *x4_proof, *x2_s_proof;
974 u_int x3_proof_len, x4_proof_len, x2_s_proof_len;
975 char *crypt_scheme, *salt;
977 /* Disable this message */
978 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1, NULL);
980 if ((pctx->g_x3 = BN_new()) == NULL ||
981 (pctx->g_x4 = BN_new()) == NULL)
982 fatal("%s: BN_new", __func__);
984 /* Fetch step 1 values */
985 crypt_scheme = packet_get_string(NULL);
986 salt = packet_get_string(NULL);
987 pctx->server_id = packet_get_string(&pctx->server_id_len);
988 packet_get_bignum2(pctx->g_x3);
989 packet_get_bignum2(pctx->g_x4);
990 x3_proof = packet_get_string(&x3_proof_len);
991 x4_proof = packet_get_string(&x4_proof_len);
992 packet_check_eom();
994 JPAKE_DEBUG_CTX((pctx, "step 1 received in %s", __func__));
996 /* Obtain password and derive secret */
997 pctx->s = jpake_password_to_secret(authctxt, crypt_scheme, salt);
998 bzero(crypt_scheme, strlen(crypt_scheme));
999 bzero(salt, strlen(salt));
1000 xfree(crypt_scheme);
1001 xfree(salt);
1002 JPAKE_DEBUG_BN((pctx->s, "%s: s = ", __func__));
1004 /* Calculate step 2 values */
1005 jpake_step2(pctx->grp, pctx->s, pctx->g_x1,
1006 pctx->g_x3, pctx->g_x4, pctx->x2,
1007 pctx->server_id, pctx->server_id_len,
1008 pctx->client_id, pctx->client_id_len,
1009 x3_proof, x3_proof_len,
1010 x4_proof, x4_proof_len,
1011 &pctx->a,
1012 &x2_s_proof, &x2_s_proof_len);
1014 bzero(x3_proof, x3_proof_len);
1015 bzero(x4_proof, x4_proof_len);
1016 xfree(x3_proof);
1017 xfree(x4_proof);
1019 JPAKE_DEBUG_CTX((pctx, "step 2 sending in %s", __func__));
1021 /* Send values for step 2 */
1022 packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP2);
1023 packet_put_bignum2(pctx->a);
1024 packet_put_string(x2_s_proof, x2_s_proof_len);
1025 packet_send();
1027 bzero(x2_s_proof, x2_s_proof_len);
1028 xfree(x2_s_proof);
1030 /* Expect step 2 packet from peer */
1031 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2,
1032 input_userauth_jpake_server_step2);
1035 /* ARGSUSED */
1036 void
1037 input_userauth_jpake_server_step2(int type, u_int32_t seq, void *ctxt)
1039 Authctxt *authctxt = ctxt;
1040 struct jpake_ctx *pctx = authctxt->methoddata;
1041 u_char *x4_s_proof;
1042 u_int x4_s_proof_len;
1044 /* Disable this message */
1045 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2, NULL);
1047 if ((pctx->b = BN_new()) == NULL)
1048 fatal("%s: BN_new", __func__);
1050 /* Fetch step 2 values */
1051 packet_get_bignum2(pctx->b);
1052 x4_s_proof = packet_get_string(&x4_s_proof_len);
1053 packet_check_eom();
1055 JPAKE_DEBUG_CTX((pctx, "step 2 received in %s", __func__));
1057 /* Derive shared key and calculate confirmation hash */
1058 jpake_key_confirm(pctx->grp, pctx->s, pctx->b,
1059 pctx->x2, pctx->g_x1, pctx->g_x2, pctx->g_x3, pctx->g_x4,
1060 pctx->client_id, pctx->client_id_len,
1061 pctx->server_id, pctx->server_id_len,
1062 session_id2, session_id2_len,
1063 x4_s_proof, x4_s_proof_len,
1064 &pctx->k,
1065 &pctx->h_k_cid_sessid, &pctx->h_k_cid_sessid_len);
1067 bzero(x4_s_proof, x4_s_proof_len);
1068 xfree(x4_s_proof);
1070 JPAKE_DEBUG_CTX((pctx, "confirm sending in %s", __func__));
1072 /* Send key confirmation proof */
1073 packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_CONFIRM);
1074 packet_put_string(pctx->h_k_cid_sessid, pctx->h_k_cid_sessid_len);
1075 packet_send();
1077 /* Expect confirmation from peer */
1078 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM,
1079 input_userauth_jpake_server_confirm);
1082 /* ARGSUSED */
1083 void
1084 input_userauth_jpake_server_confirm(int type, u_int32_t seq, void *ctxt)
1086 Authctxt *authctxt = ctxt;
1087 struct jpake_ctx *pctx = authctxt->methoddata;
1089 /* Disable this message */
1090 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM, NULL);
1092 pctx->h_k_sid_sessid = packet_get_string(&pctx->h_k_sid_sessid_len);
1093 packet_check_eom();
1095 JPAKE_DEBUG_CTX((pctx, "confirm received in %s", __func__));
1097 /* Verify expected confirmation hash */
1098 if (jpake_check_confirm(pctx->k,
1099 pctx->server_id, pctx->server_id_len,
1100 session_id2, session_id2_len,
1101 pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len) == 1)
1102 debug("%s: %s success", __func__, authctxt->method->name);
1103 else {
1104 debug("%s: confirmation mismatch", __func__);
1105 /* XXX stash this so if auth succeeds then we can warn/kill */
1108 userauth_jpake_cleanup(authctxt);
1110 #endif /* JPAKE */
1112 static int
1113 identity_sign(Identity *id, u_char **sigp, u_int *lenp,
1114 u_char *data, u_int datalen)
1116 Key *prv;
1117 int ret;
1119 /* the agent supports this key */
1120 if (id->ac)
1121 return (ssh_agent_sign(id->ac, id->key, sigp, lenp,
1122 data, datalen));
1124 * we have already loaded the private key or
1125 * the private key is stored in external hardware
1127 if (id->isprivate || (id->key->flags & KEY_FLAG_EXT))
1128 return (key_sign(id->key, sigp, lenp, data, datalen));
1129 /* load the private key from the file */
1130 if ((prv = load_identity_file(id->filename)) == NULL)
1131 return (-1);
1132 ret = key_sign(prv, sigp, lenp, data, datalen);
1133 key_free(prv);
1134 return (ret);
1137 static int
1138 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1140 Buffer b;
1141 u_char *blob, *signature;
1142 u_int bloblen, slen;
1143 u_int skip = 0;
1144 int ret = -1;
1145 int have_sig = 1;
1146 char *fp;
1148 fp = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
1149 debug3("sign_and_send_pubkey: %s %s", key_type(id->key), fp);
1150 xfree(fp);
1152 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1153 /* we cannot handle this key */
1154 debug3("sign_and_send_pubkey: cannot handle key");
1155 return 0;
1157 /* data to be signed */
1158 buffer_init(&b);
1159 if (datafellows & SSH_OLD_SESSIONID) {
1160 buffer_append(&b, session_id2, session_id2_len);
1161 skip = session_id2_len;
1162 } else {
1163 buffer_put_string(&b, session_id2, session_id2_len);
1164 skip = buffer_len(&b);
1166 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1167 buffer_put_cstring(&b, authctxt->server_user);
1168 buffer_put_cstring(&b,
1169 datafellows & SSH_BUG_PKSERVICE ?
1170 "ssh-userauth" :
1171 authctxt->service);
1172 if (datafellows & SSH_BUG_PKAUTH) {
1173 buffer_put_char(&b, have_sig);
1174 } else {
1175 buffer_put_cstring(&b, authctxt->method->name);
1176 buffer_put_char(&b, have_sig);
1177 buffer_put_cstring(&b, key_ssh_name(id->key));
1179 buffer_put_string(&b, blob, bloblen);
1181 /* generate signature */
1182 ret = identity_sign(id, &signature, &slen,
1183 buffer_ptr(&b), buffer_len(&b));
1184 if (ret == -1) {
1185 xfree(blob);
1186 buffer_free(&b);
1187 return 0;
1189 #ifdef DEBUG_PK
1190 buffer_dump(&b);
1191 #endif
1192 if (datafellows & SSH_BUG_PKSERVICE) {
1193 buffer_clear(&b);
1194 buffer_append(&b, session_id2, session_id2_len);
1195 skip = session_id2_len;
1196 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1197 buffer_put_cstring(&b, authctxt->server_user);
1198 buffer_put_cstring(&b, authctxt->service);
1199 buffer_put_cstring(&b, authctxt->method->name);
1200 buffer_put_char(&b, have_sig);
1201 if (!(datafellows & SSH_BUG_PKAUTH))
1202 buffer_put_cstring(&b, key_ssh_name(id->key));
1203 buffer_put_string(&b, blob, bloblen);
1205 xfree(blob);
1207 /* append signature */
1208 buffer_put_string(&b, signature, slen);
1209 xfree(signature);
1211 /* skip session id and packet type */
1212 if (buffer_len(&b) < skip + 1)
1213 fatal("userauth_pubkey: internal error");
1214 buffer_consume(&b, skip + 1);
1216 /* put remaining data from buffer into packet */
1217 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1218 packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1219 buffer_free(&b);
1220 packet_send();
1222 return 1;
1225 static int
1226 send_pubkey_test(Authctxt *authctxt, Identity *id)
1228 u_char *blob;
1229 u_int bloblen, have_sig = 0;
1231 debug3("send_pubkey_test");
1233 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1234 /* we cannot handle this key */
1235 debug3("send_pubkey_test: cannot handle key");
1236 return 0;
1238 /* register callback for USERAUTH_PK_OK message */
1239 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1241 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1242 packet_put_cstring(authctxt->server_user);
1243 packet_put_cstring(authctxt->service);
1244 packet_put_cstring(authctxt->method->name);
1245 packet_put_char(have_sig);
1246 if (!(datafellows & SSH_BUG_PKAUTH))
1247 packet_put_cstring(key_ssh_name(id->key));
1248 packet_put_string(blob, bloblen);
1249 xfree(blob);
1250 packet_send();
1251 return 1;
1254 static Key *
1255 load_identity_file(char *filename)
1257 Key *private;
1258 char prompt[300], *passphrase;
1259 int perm_ok = 0, quit, i;
1260 struct stat st;
1262 if (stat(filename, &st) < 0) {
1263 debug3("no such identity: %s", filename);
1264 return NULL;
1266 private = key_load_private_type(KEY_UNSPEC, filename, "", NULL, &perm_ok);
1267 if (!perm_ok)
1268 return NULL;
1269 if (private == NULL) {
1270 if (options.batch_mode)
1271 return NULL;
1272 snprintf(prompt, sizeof prompt,
1273 "Enter passphrase for key '%.100s': ", filename);
1274 for (i = 0; i < options.number_of_password_prompts; i++) {
1275 passphrase = read_passphrase(prompt, 0);
1276 if (strcmp(passphrase, "") != 0) {
1277 private = key_load_private_type(KEY_UNSPEC,
1278 filename, passphrase, NULL, NULL);
1279 quit = 0;
1280 } else {
1281 debug2("no passphrase given, try next key");
1282 quit = 1;
1284 memset(passphrase, 0, strlen(passphrase));
1285 xfree(passphrase);
1286 if (private != NULL || quit)
1287 break;
1288 debug2("bad passphrase given, try again...");
1291 return private;
1295 * try keys in the following order:
1296 * 1. agent keys that are found in the config file
1297 * 2. other agent keys
1298 * 3. keys that are only listed in the config file
1300 static void
1301 pubkey_prepare(Authctxt *authctxt)
1303 Identity *id;
1304 Idlist agent, files, *preferred;
1305 Key *key;
1306 AuthenticationConnection *ac;
1307 char *comment;
1308 int i, found;
1310 TAILQ_INIT(&agent); /* keys from the agent */
1311 TAILQ_INIT(&files); /* keys from the config file */
1312 preferred = &authctxt->keys;
1313 TAILQ_INIT(preferred); /* preferred order of keys */
1315 /* list of keys stored in the filesystem */
1316 for (i = 0; i < options.num_identity_files; i++) {
1317 key = options.identity_keys[i];
1318 if (key && key->type == KEY_RSA1)
1319 continue;
1320 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1321 continue;
1322 options.identity_keys[i] = NULL;
1323 id = xcalloc(1, sizeof(*id));
1324 id->key = key;
1325 id->filename = xstrdup(options.identity_files[i]);
1326 TAILQ_INSERT_TAIL(&files, id, next);
1328 /* list of keys supported by the agent */
1329 if ((ac = ssh_get_authentication_connection())) {
1330 for (key = ssh_get_first_identity(ac, &comment, 2);
1331 key != NULL;
1332 key = ssh_get_next_identity(ac, &comment, 2)) {
1333 found = 0;
1334 TAILQ_FOREACH(id, &files, next) {
1335 /* agent keys from the config file are preferred */
1336 if (key_equal(key, id->key)) {
1337 key_free(key);
1338 xfree(comment);
1339 TAILQ_REMOVE(&files, id, next);
1340 TAILQ_INSERT_TAIL(preferred, id, next);
1341 id->ac = ac;
1342 found = 1;
1343 break;
1346 if (!found && !options.identities_only) {
1347 id = xcalloc(1, sizeof(*id));
1348 id->key = key;
1349 id->filename = comment;
1350 id->ac = ac;
1351 TAILQ_INSERT_TAIL(&agent, id, next);
1354 /* append remaining agent keys */
1355 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1356 TAILQ_REMOVE(&agent, id, next);
1357 TAILQ_INSERT_TAIL(preferred, id, next);
1359 authctxt->agent = ac;
1361 /* append remaining keys from the config file */
1362 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1363 TAILQ_REMOVE(&files, id, next);
1364 TAILQ_INSERT_TAIL(preferred, id, next);
1366 TAILQ_FOREACH(id, preferred, next) {
1367 debug2("key: %s (%p)", id->filename, id->key);
1371 static void
1372 pubkey_cleanup(Authctxt *authctxt)
1374 Identity *id;
1376 if (authctxt->agent != NULL)
1377 ssh_close_authentication_connection(authctxt->agent);
1378 for (id = TAILQ_FIRST(&authctxt->keys); id;
1379 id = TAILQ_FIRST(&authctxt->keys)) {
1380 TAILQ_REMOVE(&authctxt->keys, id, next);
1381 if (id->key)
1382 key_free(id->key);
1383 if (id->filename)
1384 xfree(id->filename);
1385 xfree(id);
1390 userauth_pubkey(Authctxt *authctxt)
1392 Identity *id;
1393 int sent = 0;
1395 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1396 if (id->tried++)
1397 return (0);
1398 /* move key to the end of the queue */
1399 TAILQ_REMOVE(&authctxt->keys, id, next);
1400 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1402 * send a test message if we have the public key. for
1403 * encrypted keys we cannot do this and have to load the
1404 * private key instead
1406 if (id->key && id->key->type != KEY_RSA1) {
1407 debug("Offering %s public key: %s", key_type(id->key),
1408 id->filename);
1409 sent = send_pubkey_test(authctxt, id);
1410 } else if (id->key == NULL) {
1411 debug("Trying private key: %s", id->filename);
1412 id->key = load_identity_file(id->filename);
1413 if (id->key != NULL) {
1414 id->isprivate = 1;
1415 sent = sign_and_send_pubkey(authctxt, id);
1416 key_free(id->key);
1417 id->key = NULL;
1420 if (sent)
1421 return (sent);
1423 return (0);
1427 * Send userauth request message specifying keyboard-interactive method.
1430 userauth_kbdint(Authctxt *authctxt)
1432 static int attempt = 0;
1434 if (attempt++ >= options.number_of_password_prompts)
1435 return 0;
1436 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1437 if (attempt > 1 && !authctxt->info_req_seen) {
1438 debug3("userauth_kbdint: disable: no info_req_seen");
1439 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1440 return 0;
1443 debug2("userauth_kbdint");
1444 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1445 packet_put_cstring(authctxt->server_user);
1446 packet_put_cstring(authctxt->service);
1447 packet_put_cstring(authctxt->method->name);
1448 packet_put_cstring(""); /* lang */
1449 packet_put_cstring(options.kbd_interactive_devices ?
1450 options.kbd_interactive_devices : "");
1451 packet_send();
1453 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1454 return 1;
1458 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1460 void
1461 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1463 Authctxt *authctxt = ctxt;
1464 char *name, *inst, *lang, *prompt, *response;
1465 u_int num_prompts, i;
1466 int echo = 0;
1468 debug2("input_userauth_info_req");
1470 if (authctxt == NULL)
1471 fatal("input_userauth_info_req: no authentication context");
1473 authctxt->info_req_seen = 1;
1475 name = packet_get_string(NULL);
1476 inst = packet_get_string(NULL);
1477 lang = packet_get_string(NULL);
1478 if (strlen(name) > 0)
1479 logit("%s", name);
1480 if (strlen(inst) > 0)
1481 logit("%s", inst);
1482 xfree(name);
1483 xfree(inst);
1484 xfree(lang);
1486 num_prompts = packet_get_int();
1488 * Begin to build info response packet based on prompts requested.
1489 * We commit to providing the correct number of responses, so if
1490 * further on we run into a problem that prevents this, we have to
1491 * be sure and clean this up and send a correct error response.
1493 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1494 packet_put_int(num_prompts);
1496 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1497 for (i = 0; i < num_prompts; i++) {
1498 prompt = packet_get_string(NULL);
1499 echo = packet_get_char();
1501 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1503 packet_put_cstring(response);
1504 memset(response, 0, strlen(response));
1505 xfree(response);
1506 xfree(prompt);
1508 packet_check_eom(); /* done with parsing incoming message. */
1510 packet_add_padding(64);
1511 packet_send();
1514 static int
1515 ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1516 u_char *data, u_int datalen)
1518 Buffer b;
1519 struct stat st;
1520 pid_t pid;
1521 int to[2], from[2], status, version = 2;
1523 debug2("ssh_keysign called");
1525 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1526 error("ssh_keysign: not installed: %s", strerror(errno));
1527 return -1;
1529 if (fflush(stdout) != 0)
1530 error("ssh_keysign: fflush: %s", strerror(errno));
1531 if (pipe(to) < 0) {
1532 error("ssh_keysign: pipe: %s", strerror(errno));
1533 return -1;
1535 if (pipe(from) < 0) {
1536 error("ssh_keysign: pipe: %s", strerror(errno));
1537 return -1;
1539 if ((pid = fork()) < 0) {
1540 error("ssh_keysign: fork: %s", strerror(errno));
1541 return -1;
1543 if (pid == 0) {
1544 /* keep the socket on exec */
1545 fcntl(packet_get_connection_in(), F_SETFD, 0);
1546 permanently_drop_suid(getuid());
1547 close(from[0]);
1548 if (dup2(from[1], STDOUT_FILENO) < 0)
1549 fatal("ssh_keysign: dup2: %s", strerror(errno));
1550 close(to[1]);
1551 if (dup2(to[0], STDIN_FILENO) < 0)
1552 fatal("ssh_keysign: dup2: %s", strerror(errno));
1553 close(from[1]);
1554 close(to[0]);
1555 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1556 fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1557 strerror(errno));
1559 close(from[1]);
1560 close(to[0]);
1562 buffer_init(&b);
1563 buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1564 buffer_put_string(&b, data, datalen);
1565 if (ssh_msg_send(to[1], version, &b) == -1)
1566 fatal("ssh_keysign: couldn't send request");
1568 if (ssh_msg_recv(from[0], &b) < 0) {
1569 error("ssh_keysign: no reply");
1570 buffer_free(&b);
1571 return -1;
1573 close(from[0]);
1574 close(to[1]);
1576 while (waitpid(pid, &status, 0) < 0)
1577 if (errno != EINTR)
1578 break;
1580 if (buffer_get_char(&b) != version) {
1581 error("ssh_keysign: bad version");
1582 buffer_free(&b);
1583 return -1;
1585 *sigp = buffer_get_string(&b, lenp);
1586 buffer_free(&b);
1588 return 0;
1592 userauth_hostbased(Authctxt *authctxt)
1594 Key *private = NULL;
1595 Sensitive *sensitive = authctxt->sensitive;
1596 Buffer b;
1597 u_char *signature, *blob;
1598 char *chost, *pkalg, *p;
1599 const char *service;
1600 u_int blen, slen;
1601 int ok, i, found = 0;
1603 /* check for a useful key */
1604 for (i = 0; i < sensitive->nkeys; i++) {
1605 private = sensitive->keys[i];
1606 if (private && private->type != KEY_RSA1) {
1607 found = 1;
1608 /* we take and free the key */
1609 sensitive->keys[i] = NULL;
1610 break;
1613 if (!found) {
1614 debug("No more client hostkeys for hostbased authentication.");
1615 return 0;
1617 if (key_to_blob(private, &blob, &blen) == 0) {
1618 key_free(private);
1619 return 0;
1621 /* figure out a name for the client host */
1622 p = get_local_name(packet_get_connection_in());
1623 if (p == NULL) {
1624 error("userauth_hostbased: cannot get local ipaddr/name");
1625 key_free(private);
1626 xfree(blob);
1627 return 0;
1629 xasprintf(&chost, "%s.", p);
1630 debug2("userauth_hostbased: chost %s", chost);
1631 xfree(p);
1633 service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1634 authctxt->service;
1635 pkalg = xstrdup(key_ssh_name(private));
1636 buffer_init(&b);
1637 /* construct data */
1638 buffer_put_string(&b, session_id2, session_id2_len);
1639 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1640 buffer_put_cstring(&b, authctxt->server_user);
1641 buffer_put_cstring(&b, service);
1642 buffer_put_cstring(&b, authctxt->method->name);
1643 buffer_put_cstring(&b, pkalg);
1644 buffer_put_string(&b, blob, blen);
1645 buffer_put_cstring(&b, chost);
1646 buffer_put_cstring(&b, authctxt->local_user);
1647 #ifdef DEBUG_PK
1648 buffer_dump(&b);
1649 #endif
1650 if (sensitive->external_keysign)
1651 ok = ssh_keysign(private, &signature, &slen,
1652 buffer_ptr(&b), buffer_len(&b));
1653 else
1654 ok = key_sign(private, &signature, &slen,
1655 buffer_ptr(&b), buffer_len(&b));
1656 key_free(private);
1657 buffer_free(&b);
1658 if (ok != 0) {
1659 error("key_sign failed");
1660 xfree(chost);
1661 xfree(pkalg);
1662 xfree(blob);
1663 return 0;
1665 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1666 packet_put_cstring(authctxt->server_user);
1667 packet_put_cstring(authctxt->service);
1668 packet_put_cstring(authctxt->method->name);
1669 packet_put_cstring(pkalg);
1670 packet_put_string(blob, blen);
1671 packet_put_cstring(chost);
1672 packet_put_cstring(authctxt->local_user);
1673 packet_put_string(signature, slen);
1674 memset(signature, 's', slen);
1675 xfree(signature);
1676 xfree(chost);
1677 xfree(pkalg);
1678 xfree(blob);
1680 packet_send();
1681 return 1;
1684 #ifdef JPAKE
1686 userauth_jpake(Authctxt *authctxt)
1688 struct jpake_ctx *pctx;
1689 u_char *x1_proof, *x2_proof;
1690 u_int x1_proof_len, x2_proof_len;
1691 static int attempt = 0; /* XXX share with userauth_password's? */
1693 if (attempt++ >= options.number_of_password_prompts)
1694 return 0;
1695 if (attempt != 1)
1696 error("Permission denied, please try again.");
1698 if (authctxt->methoddata != NULL)
1699 fatal("%s: authctxt->methoddata already set (%p)",
1700 __func__, authctxt->methoddata);
1702 authctxt->methoddata = pctx = jpake_new();
1705 * Send request immediately, to get the protocol going while
1706 * we do the initial computations.
1708 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1709 packet_put_cstring(authctxt->server_user);
1710 packet_put_cstring(authctxt->service);
1711 packet_put_cstring(authctxt->method->name);
1712 packet_send();
1713 packet_write_wait();
1715 jpake_step1(pctx->grp,
1716 &pctx->client_id, &pctx->client_id_len,
1717 &pctx->x1, &pctx->x2, &pctx->g_x1, &pctx->g_x2,
1718 &x1_proof, &x1_proof_len,
1719 &x2_proof, &x2_proof_len);
1721 JPAKE_DEBUG_CTX((pctx, "step 1 sending in %s", __func__));
1723 packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP1);
1724 packet_put_string(pctx->client_id, pctx->client_id_len);
1725 packet_put_bignum2(pctx->g_x1);
1726 packet_put_bignum2(pctx->g_x2);
1727 packet_put_string(x1_proof, x1_proof_len);
1728 packet_put_string(x2_proof, x2_proof_len);
1729 packet_send();
1731 bzero(x1_proof, x1_proof_len);
1732 bzero(x2_proof, x2_proof_len);
1733 xfree(x1_proof);
1734 xfree(x2_proof);
1736 /* Expect step 1 packet from peer */
1737 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1,
1738 input_userauth_jpake_server_step1);
1739 dispatch_set(SSH2_MSG_USERAUTH_SUCCESS,
1740 &input_userauth_success_unexpected);
1742 return 1;
1745 void
1746 userauth_jpake_cleanup(Authctxt *authctxt)
1748 debug3("%s: clean up", __func__);
1749 if (authctxt->methoddata != NULL) {
1750 jpake_free(authctxt->methoddata);
1751 authctxt->methoddata = NULL;
1753 dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
1755 #endif /* JPAKE */
1757 /* find auth method */
1760 * given auth method name, if configurable options permit this method fill
1761 * in auth_ident field and return true, otherwise return false.
1763 static int
1764 authmethod_is_enabled(Authmethod *method)
1766 if (method == NULL)
1767 return 0;
1768 /* return false if options indicate this method is disabled */
1769 if (method->enabled == NULL || *method->enabled == 0)
1770 return 0;
1771 /* return false if batch mode is enabled but method needs interactive mode */
1772 if (method->batch_flag != NULL && *method->batch_flag != 0)
1773 return 0;
1774 return 1;
1777 static Authmethod *
1778 authmethod_lookup(const char *name)
1780 Authmethod *method = NULL;
1781 if (name != NULL)
1782 for (method = authmethods; method->name != NULL; method++)
1783 if (strcmp(name, method->name) == 0)
1784 return method;
1785 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1786 return NULL;
1789 /* XXX internal state */
1790 static Authmethod *current = NULL;
1791 static char *supported = NULL;
1792 static char *preferred = NULL;
1795 * Given the authentication method list sent by the server, return the
1796 * next method we should try. If the server initially sends a nil list,
1797 * use a built-in default list.
1799 static Authmethod *
1800 authmethod_get(char *authlist)
1802 char *name = NULL;
1803 u_int next;
1805 /* Use a suitable default if we're passed a nil list. */
1806 if (authlist == NULL || strlen(authlist) == 0)
1807 authlist = options.preferred_authentications;
1809 if (supported == NULL || strcmp(authlist, supported) != 0) {
1810 debug3("start over, passed a different list %s", authlist);
1811 if (supported != NULL)
1812 xfree(supported);
1813 supported = xstrdup(authlist);
1814 preferred = options.preferred_authentications;
1815 debug3("preferred %s", preferred);
1816 current = NULL;
1817 } else if (current != NULL && authmethod_is_enabled(current))
1818 return current;
1820 for (;;) {
1821 if ((name = match_list(preferred, supported, &next)) == NULL) {
1822 debug("No more authentication methods to try.");
1823 current = NULL;
1824 return NULL;
1826 preferred += next;
1827 debug3("authmethod_lookup %s", name);
1828 debug3("remaining preferred: %s", preferred);
1829 if ((current = authmethod_lookup(name)) != NULL &&
1830 authmethod_is_enabled(current)) {
1831 debug3("authmethod_is_enabled %s", name);
1832 debug("Next authentication method: %s", name);
1833 return current;
1838 static char *
1839 authmethods_get(void)
1841 Authmethod *method = NULL;
1842 Buffer b;
1843 char *list;
1845 buffer_init(&b);
1846 for (method = authmethods; method->name != NULL; method++) {
1847 if (authmethod_is_enabled(method)) {
1848 if (buffer_len(&b) > 0)
1849 buffer_append(&b, ",", 1);
1850 buffer_append(&b, method->name, strlen(method->name));
1853 buffer_append(&b, "\0", 1);
1854 list = xstrdup(buffer_ptr(&b));
1855 buffer_free(&b);
1856 return list;