No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / external / bsd / openssh / dist / sshconnect2.c
blobb146f9f116acc6ee28f2545c2785cbc97c53e472
1 /* $NetBSD: sshconnect2.c,v 1.1.1.2 2009/12/27 01:07:15 christos Exp $ */
2 /* $OpenBSD: sshconnect2.c,v 1.171 2009/03/05 07:18:19 djm Exp $ */
3 /*
4 * Copyright (c) 2000 Markus Friedl. All rights reserved.
5 * Copyright (c) 2008 Damien Miller. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "includes.h"
29 __RCSID("$NetBSD: sshconnect2.c,v 1.3 2009/06/09 13:32:46 stacktic Exp $");
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/wait.h>
33 #include <sys/queue.h>
34 #include <sys/stat.h>
36 #include <errno.h>
37 #include <netdb.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <signal.h>
41 #include <pwd.h>
42 #include <unistd.h>
43 #include <vis.h>
45 #ifdef KRB5
46 #include <krb5.h>
47 #endif
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;
83 extern Kex *xxx_kex;
85 /* tty_flag is set in ssh.c. use this in ssh_userauth2 */
86 /* if it is set then prevent the switch to the null cipher */
88 extern int tty_flag;
91 * SSH2 key exchange
94 u_char *session_id2 = NULL;
95 u_int session_id2_len = 0;
97 char *xxx_host;
98 struct sockaddr *xxx_hostaddr;
100 Kex *xxx_kex = NULL;
102 static int
103 verify_host_key_callback(Key *hostkey)
105 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
106 fatal("Host key verification failed.");
107 return 0;
110 void
111 ssh_kex2(char *host, struct sockaddr *hostaddr)
113 Kex *kex;
115 xxx_host = host;
116 xxx_hostaddr = hostaddr;
118 if (options.ciphers == (char *)-1) {
119 logit("No valid ciphers for protocol version 2 given, using defaults.");
120 options.ciphers = NULL;
122 if (options.ciphers != NULL) {
123 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
124 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
126 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
127 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
128 myproposal[PROPOSAL_ENC_ALGS_STOC] =
129 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
130 if (options.compression) {
131 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
132 myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib@openssh.com,zlib,none";
133 } else {
134 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
135 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com,zlib";
137 if (options.macs != NULL) {
138 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
139 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
141 if (options.hostkeyalgorithms != NULL)
142 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
143 options.hostkeyalgorithms;
145 if (options.rekey_limit)
146 packet_set_rekey_limit((u_int32_t)options.rekey_limit);
148 /* start key exchange */
149 kex = kex_setup(myproposal);
150 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
151 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
152 kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
153 kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
154 kex->client_version_string=client_version_string;
155 kex->server_version_string=server_version_string;
156 kex->verify_host_key=&verify_host_key_callback;
158 xxx_kex = kex;
160 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
162 session_id2 = kex->session_id;
163 session_id2_len = kex->session_id_len;
165 #ifdef DEBUG_KEXDH
166 /* send 1st encrypted/maced/compressed message */
167 packet_start(SSH2_MSG_IGNORE);
168 packet_put_cstring("markus");
169 packet_send();
170 packet_write_wait();
171 #endif
175 * Authenticate user
178 typedef struct Authctxt Authctxt;
179 typedef struct Authmethod Authmethod;
180 typedef struct identity Identity;
181 typedef struct idlist Idlist;
183 struct identity {
184 TAILQ_ENTRY(identity) next;
185 AuthenticationConnection *ac; /* set if agent supports key */
186 Key *key; /* public/private key */
187 char *filename; /* comment for agent-only keys */
188 int tried;
189 int isprivate; /* key points to the private key */
191 TAILQ_HEAD(idlist, identity);
193 struct Authctxt {
194 const char *server_user;
195 const char *local_user;
196 const char *host;
197 const char *service;
198 Authmethod *method;
199 sig_atomic_t success;
200 char *authlist;
201 /* pubkey */
202 Idlist keys;
203 AuthenticationConnection *agent;
204 /* hostbased */
205 Sensitive *sensitive;
206 /* kbd-interactive */
207 int info_req_seen;
208 /* generic */
209 void *methoddata;
211 struct Authmethod {
212 char *name; /* string to compare against server's list */
213 int (*userauth)(Authctxt *authctxt);
214 void (*cleanup)(Authctxt *authctxt);
215 int *enabled; /* flag in option struct that enables method */
216 int *batch_flag; /* flag in option struct that disables method */
219 void input_userauth_success(int, u_int32_t, void *);
220 void input_userauth_failure(int, u_int32_t, void *);
221 void input_userauth_banner(int, u_int32_t, void *);
222 void input_userauth_error(int, u_int32_t, void *);
223 void input_userauth_info_req(int, u_int32_t, void *);
224 void input_userauth_pk_ok(int, u_int32_t, void *);
225 void input_userauth_passwd_changereq(int, u_int32_t, void *);
226 void input_userauth_jpake_server_step1(int, u_int32_t, void *);
227 void input_userauth_jpake_server_step2(int, u_int32_t, void *);
228 void input_userauth_jpake_server_confirm(int, u_int32_t, void *);
230 int userauth_none(Authctxt *);
231 int userauth_pubkey(Authctxt *);
232 int userauth_passwd(Authctxt *);
233 int userauth_kbdint(Authctxt *);
234 int userauth_hostbased(Authctxt *);
235 int userauth_kerberos(Authctxt *);
236 int userauth_jpake(Authctxt *);
238 void userauth_jpake_cleanup(Authctxt *);
240 #ifdef GSSAPI
241 int userauth_gssapi(Authctxt *authctxt);
242 void input_gssapi_response(int type, u_int32_t, void *);
243 void input_gssapi_token(int type, u_int32_t, void *);
244 void input_gssapi_hash(int type, u_int32_t, void *);
245 void input_gssapi_error(int, u_int32_t, void *);
246 void input_gssapi_errtok(int, u_int32_t, void *);
247 #endif
249 void userauth(Authctxt *, char *);
251 static int sign_and_send_pubkey(Authctxt *, Identity *);
252 static void pubkey_prepare(Authctxt *);
253 static void pubkey_cleanup(Authctxt *);
254 static Key *load_identity_file(char *);
256 static Authmethod *authmethod_get(char *authlist);
257 static Authmethod *authmethod_lookup(const char *name);
258 static char *authmethods_get(void);
260 Authmethod authmethods[] = {
261 #ifdef GSSAPI
262 {"gssapi-with-mic",
263 userauth_gssapi,
264 NULL,
265 &options.gss_authentication,
266 NULL},
267 #endif
268 {"hostbased",
269 userauth_hostbased,
270 NULL,
271 &options.hostbased_authentication,
272 NULL},
273 #if KRB5
274 {"kerberos-2@ssh.com",
275 userauth_kerberos,
276 NULL,
277 &options.kerberos_authentication,
278 NULL},
279 #endif
280 {"publickey",
281 userauth_pubkey,
282 NULL,
283 &options.pubkey_authentication,
284 NULL},
285 #ifdef JPAKE
286 {"jpake-01@openssh.com",
287 userauth_jpake,
288 userauth_jpake_cleanup,
289 &options.zero_knowledge_password_authentication,
290 &options.batch_mode},
291 #endif
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}
310 void
311 ssh_userauth2(const char *local_user, const char *server_user, char *host,
312 Sensitive *sensitive)
314 Authctxt authctxt;
315 int type;
317 if (options.challenge_response_authentication)
318 options.kbd_interactive_authentication = 1;
320 packet_start(SSH2_MSG_SERVICE_REQUEST);
321 packet_put_cstring("ssh-userauth");
322 packet_send();
323 debug("SSH2_MSG_SERVICE_REQUEST sent");
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");
335 packet_check_eom();
336 debug("SSH2_MSG_SERVICE_ACCEPT received");
338 if (options.preferred_authentications == NULL)
339 options.preferred_authentications = authmethods_get();
341 /* setup authentication context */
342 memset(&authctxt, 0, sizeof(authctxt));
343 pubkey_prepare(&authctxt);
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");
357 /* initial userauth request */
358 userauth_none(&authctxt);
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 */
366 pubkey_cleanup(&authctxt);
367 dispatch_range(SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
369 /* if the user wants to use the none cipher do it */
370 /* post authentication and only if the right conditions are met */
371 /* both of the NONE commands must be true and there must be no */
372 /* tty allocated */
373 if ((options.none_switch == 1) && (options.none_enabled == 1))
375 if (!tty_flag) /* no null on tty sessions */
377 debug("Requesting none rekeying...");
378 myproposal[PROPOSAL_ENC_ALGS_STOC] = "none";
379 myproposal[PROPOSAL_ENC_ALGS_CTOS] = "none";
380 kex_prop2buf(&xxx_kex->my,myproposal);
381 packet_request_rekeying();
382 fprintf(stderr, "WARNING: ENABLED NONE CIPHER\n");
384 else
386 /* requested NONE cipher when in a tty */
387 debug("Cannot switch to NONE cipher with tty allocated");
388 fprintf(stderr, "NONE cipher switch disabled when a TTY is allocated\n");
391 debug("Authentication succeeded (%s).", authctxt.method->name);
394 void
395 userauth(Authctxt *authctxt, char *authlist)
397 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
398 authctxt->method->cleanup(authctxt);
400 if (authctxt->methoddata) {
401 xfree(authctxt->methoddata);
402 authctxt->methoddata = NULL;
404 if (authlist == NULL) {
405 authlist = authctxt->authlist;
406 } else {
407 if (authctxt->authlist)
408 xfree(authctxt->authlist);
409 authctxt->authlist = authlist;
411 for (;;) {
412 Authmethod *method = authmethod_get(authlist);
413 if (method == NULL)
414 fatal("Permission denied (%s).", authlist);
415 authctxt->method = method;
417 /* reset the per method handler */
418 dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
419 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
421 /* and try new method */
422 if (method->userauth(authctxt) != 0) {
423 debug2("we sent a %s packet, wait for reply", method->name);
424 break;
425 } else {
426 debug2("we did not send a packet, disable method");
427 method->enabled = NULL;
432 /* ARGSUSED */
433 void
434 input_userauth_error(int type, u_int32_t seq, void *ctxt)
436 fatal("input_userauth_error: bad message during authentication: "
437 "type %d", type);
440 /* ARGSUSED */
441 void
442 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
444 char *msg, *raw, *lang;
445 u_int len;
447 debug3("input_userauth_banner");
448 raw = packet_get_string(&len);
449 lang = packet_get_string(NULL);
450 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) {
451 if (len > 65536)
452 len = 65536;
453 msg = xmalloc(len * 4 + 1); /* max expansion from strnvis() */
454 strvisx(msg, raw, len, VIS_SAFE|VIS_OCTAL);
455 fprintf(stderr, "%s", msg);
456 xfree(msg);
458 xfree(raw);
459 xfree(lang);
462 /* ARGSUSED */
463 void
464 input_userauth_success(int type, u_int32_t seq, void *ctxt)
466 Authctxt *authctxt = ctxt;
467 if (authctxt == NULL)
468 fatal("input_userauth_success: no authentication context");
469 if (authctxt->authlist) {
470 xfree(authctxt->authlist);
471 authctxt->authlist = NULL;
473 if (authctxt->methoddata) {
474 xfree(authctxt->methoddata);
475 authctxt->methoddata = NULL;
477 authctxt->success = 1; /* break out */
480 /* ARGSUSED */
481 void
482 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
484 Authctxt *authctxt = ctxt;
485 char *authlist = NULL;
486 int partial;
488 if (authctxt == NULL)
489 fatal("input_userauth_failure: no authentication context");
491 authlist = packet_get_string(NULL);
492 partial = packet_get_char();
493 packet_check_eom();
495 if (partial != 0)
496 logit("Authenticated with partial success.");
497 debug("Authentications that can continue: %s", authlist);
499 userauth(authctxt, authlist);
502 /* ARGSUSED */
503 void
504 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
506 Authctxt *authctxt = ctxt;
507 Key *key = NULL;
508 Identity *id = NULL;
509 Buffer b;
510 int pktype, sent = 0;
511 u_int alen, blen;
512 char *pkalg, *fp;
513 u_char *pkblob;
515 if (authctxt == NULL)
516 fatal("input_userauth_pk_ok: no authentication context");
517 if (datafellows & SSH_BUG_PKOK) {
518 /* this is similar to SSH_BUG_PKAUTH */
519 debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
520 pkblob = packet_get_string(&blen);
521 buffer_init(&b);
522 buffer_append(&b, pkblob, blen);
523 pkalg = buffer_get_string(&b, &alen);
524 buffer_free(&b);
525 } else {
526 pkalg = packet_get_string(&alen);
527 pkblob = packet_get_string(&blen);
529 packet_check_eom();
531 debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
533 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
534 debug("unknown pkalg %s", pkalg);
535 goto done;
537 if ((key = key_from_blob(pkblob, blen)) == NULL) {
538 debug("no key from blob. pkalg %s", pkalg);
539 goto done;
541 if (key->type != pktype) {
542 error("input_userauth_pk_ok: type mismatch "
543 "for decoded key (received %d, expected %d)",
544 key->type, pktype);
545 goto done;
547 fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
548 debug2("input_userauth_pk_ok: fp %s", fp);
549 xfree(fp);
552 * search keys in the reverse order, because last candidate has been
553 * moved to the end of the queue. this also avoids confusion by
554 * duplicate keys
556 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
557 if (key_equal(key, id->key)) {
558 sent = sign_and_send_pubkey(authctxt, id);
559 break;
562 done:
563 if (key != NULL)
564 key_free(key);
565 xfree(pkalg);
566 xfree(pkblob);
568 /* try another method if we did not send a packet */
569 if (sent == 0)
570 userauth(authctxt, NULL);
573 #ifdef GSSAPI
575 userauth_gssapi(Authctxt *authctxt)
577 Gssctxt *gssctxt = NULL;
578 static gss_OID_set gss_supported = NULL;
579 static u_int mech = 0;
580 OM_uint32 min;
581 int ok = 0;
583 /* Try one GSSAPI method at a time, rather than sending them all at
584 * once. */
586 if (gss_supported == NULL)
587 gss_indicate_mechs(&min, &gss_supported);
589 /* Check to see if the mechanism is usable before we offer it */
590 while (mech < gss_supported->count && !ok) {
591 /* My DER encoding requires length<128 */
592 if (gss_supported->elements[mech].length < 128 &&
593 ssh_gssapi_check_mechanism(&gssctxt,
594 &gss_supported->elements[mech], authctxt->host)) {
595 ok = 1; /* Mechanism works */
596 } else {
597 mech++;
601 if (!ok) {
602 ssh_gssapi_delete_ctx(&gssctxt);
603 return 0;
606 authctxt->methoddata=(void *)gssctxt;
608 packet_start(SSH2_MSG_USERAUTH_REQUEST);
609 packet_put_cstring(authctxt->server_user);
610 packet_put_cstring(authctxt->service);
611 packet_put_cstring(authctxt->method->name);
613 packet_put_int(1);
615 packet_put_int((gss_supported->elements[mech].length) + 2);
616 packet_put_char(SSH_GSS_OIDTYPE);
617 packet_put_char(gss_supported->elements[mech].length);
618 packet_put_raw(gss_supported->elements[mech].elements,
619 gss_supported->elements[mech].length);
621 packet_send();
623 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
624 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
625 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
626 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
628 mech++; /* Move along to next candidate */
630 return 1;
633 static OM_uint32
634 process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
636 Authctxt *authctxt = ctxt;
637 Gssctxt *gssctxt = authctxt->methoddata;
638 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
639 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
640 gss_buffer_desc gssbuf;
641 OM_uint32 status, ms, flags;
642 Buffer b;
644 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
645 recv_tok, &send_tok, &flags);
647 if (send_tok.length > 0) {
648 if (GSS_ERROR(status))
649 packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
650 else
651 packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
653 packet_put_string(send_tok.value, send_tok.length);
654 packet_send();
655 gss_release_buffer(&ms, &send_tok);
658 if (status == GSS_S_COMPLETE) {
659 /* send either complete or MIC, depending on mechanism */
660 if (!(flags & GSS_C_INTEG_FLAG)) {
661 packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
662 packet_send();
663 } else {
664 ssh_gssapi_buildmic(&b, authctxt->server_user,
665 authctxt->service, "gssapi-with-mic");
667 gssbuf.value = buffer_ptr(&b);
668 gssbuf.length = buffer_len(&b);
670 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
672 if (!GSS_ERROR(status)) {
673 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
674 packet_put_string(mic.value, mic.length);
676 packet_send();
679 buffer_free(&b);
680 gss_release_buffer(&ms, &mic);
684 return status;
687 /* ARGSUSED */
688 void
689 input_gssapi_response(int type, u_int32_t plen, void *ctxt)
691 Authctxt *authctxt = ctxt;
692 Gssctxt *gssctxt;
693 int oidlen;
694 char *oidv;
696 if (authctxt == NULL)
697 fatal("input_gssapi_response: no authentication context");
698 gssctxt = authctxt->methoddata;
700 /* Setup our OID */
701 oidv = packet_get_string(&oidlen);
703 if (oidlen <= 2 ||
704 oidv[0] != SSH_GSS_OIDTYPE ||
705 oidv[1] != oidlen - 2) {
706 xfree(oidv);
707 debug("Badly encoded mechanism OID received");
708 userauth(authctxt, NULL);
709 return;
712 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
713 fatal("Server returned different OID than expected");
715 packet_check_eom();
717 xfree(oidv);
719 if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
720 /* Start again with next method on list */
721 debug("Trying to start again");
722 userauth(authctxt, NULL);
723 return;
727 /* ARGSUSED */
728 void
729 input_gssapi_token(int type, u_int32_t plen, void *ctxt)
731 Authctxt *authctxt = ctxt;
732 gss_buffer_desc recv_tok;
733 OM_uint32 status;
734 u_int slen;
736 if (authctxt == NULL)
737 fatal("input_gssapi_response: no authentication context");
739 recv_tok.value = packet_get_string(&slen);
740 recv_tok.length = slen; /* safe typecast */
742 packet_check_eom();
744 status = process_gssapi_token(ctxt, &recv_tok);
746 xfree(recv_tok.value);
748 if (GSS_ERROR(status)) {
749 /* Start again with the next method in the list */
750 userauth(authctxt, NULL);
751 return;
755 /* ARGSUSED */
756 void
757 input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
759 Authctxt *authctxt = ctxt;
760 Gssctxt *gssctxt;
761 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
762 gss_buffer_desc recv_tok;
763 OM_uint32 status, ms;
764 u_int len;
766 if (authctxt == NULL)
767 fatal("input_gssapi_response: no authentication context");
768 gssctxt = authctxt->methoddata;
770 recv_tok.value = packet_get_string(&len);
771 recv_tok.length = len;
773 packet_check_eom();
775 /* Stick it into GSSAPI and see what it says */
776 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
777 &recv_tok, &send_tok, NULL);
779 xfree(recv_tok.value);
780 gss_release_buffer(&ms, &send_tok);
782 /* Server will be returning a failed packet after this one */
785 /* ARGSUSED */
786 void
787 input_gssapi_error(int type, u_int32_t plen, void *ctxt)
789 OM_uint32 maj, min;
790 char *msg;
791 char *lang;
793 maj=packet_get_int();
794 min=packet_get_int();
795 msg=packet_get_string(NULL);
796 lang=packet_get_string(NULL);
798 packet_check_eom();
800 debug("Server GSSAPI Error:\n%s", msg);
801 xfree(msg);
802 xfree(lang);
804 #endif /* GSSAPI */
807 userauth_none(Authctxt *authctxt)
809 /* initial userauth request */
810 packet_start(SSH2_MSG_USERAUTH_REQUEST);
811 packet_put_cstring(authctxt->server_user);
812 packet_put_cstring(authctxt->service);
813 packet_put_cstring(authctxt->method->name);
814 packet_send();
815 return 1;
819 userauth_passwd(Authctxt *authctxt)
821 static int attempt = 0;
822 char prompt[150];
823 char *password;
825 if (attempt++ >= options.number_of_password_prompts)
826 return 0;
828 if (attempt != 1)
829 error("Permission denied, please try again.");
831 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
832 authctxt->server_user, authctxt->host);
833 password = read_passphrase(prompt, 0);
834 packet_start(SSH2_MSG_USERAUTH_REQUEST);
835 packet_put_cstring(authctxt->server_user);
836 packet_put_cstring(authctxt->service);
837 packet_put_cstring(authctxt->method->name);
838 packet_put_char(0);
839 packet_put_cstring(password);
840 memset(password, 0, strlen(password));
841 xfree(password);
842 packet_add_padding(64);
843 packet_send();
845 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
846 &input_userauth_passwd_changereq);
848 return 1;
852 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
854 /* ARGSUSED */
855 void
856 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
858 Authctxt *authctxt = ctxt;
859 char *info, *lang, *password = NULL, *retype = NULL;
860 char prompt[150];
862 debug2("input_userauth_passwd_changereq");
864 if (authctxt == NULL)
865 fatal("input_userauth_passwd_changereq: "
866 "no authentication context");
868 info = packet_get_string(NULL);
869 lang = packet_get_string(NULL);
870 if (strlen(info) > 0)
871 logit("%s", info);
872 xfree(info);
873 xfree(lang);
874 packet_start(SSH2_MSG_USERAUTH_REQUEST);
875 packet_put_cstring(authctxt->server_user);
876 packet_put_cstring(authctxt->service);
877 packet_put_cstring(authctxt->method->name);
878 packet_put_char(1); /* additional info */
879 snprintf(prompt, sizeof(prompt),
880 "Enter %.30s@%.128s's old password: ",
881 authctxt->server_user, authctxt->host);
882 password = read_passphrase(prompt, 0);
883 packet_put_cstring(password);
884 memset(password, 0, strlen(password));
885 xfree(password);
886 password = NULL;
887 while (password == NULL) {
888 snprintf(prompt, sizeof(prompt),
889 "Enter %.30s@%.128s's new password: ",
890 authctxt->server_user, authctxt->host);
891 password = read_passphrase(prompt, RP_ALLOW_EOF);
892 if (password == NULL) {
893 /* bail out */
894 return;
896 snprintf(prompt, sizeof(prompt),
897 "Retype %.30s@%.128s's new password: ",
898 authctxt->server_user, authctxt->host);
899 retype = read_passphrase(prompt, 0);
900 if (strcmp(password, retype) != 0) {
901 memset(password, 0, strlen(password));
902 xfree(password);
903 logit("Mismatch; try again, EOF to quit.");
904 password = NULL;
906 memset(retype, 0, strlen(retype));
907 xfree(retype);
909 packet_put_cstring(password);
910 memset(password, 0, strlen(password));
911 xfree(password);
912 packet_add_padding(64);
913 packet_send();
915 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
916 &input_userauth_passwd_changereq);
919 #ifdef JPAKE
920 static char *
921 pw_encrypt(const char *password, const char *crypt_scheme, const char *salt)
923 /* OpenBSD crypt(3) handles all of these */
924 if (strcmp(crypt_scheme, "crypt") == 0 ||
925 strcmp(crypt_scheme, "bcrypt") == 0 ||
926 strcmp(crypt_scheme, "md5crypt") == 0 ||
927 strcmp(crypt_scheme, "crypt-extended") == 0)
928 return xstrdup(crypt(password, salt));
929 error("%s: unsupported password encryption scheme \"%.100s\"",
930 __func__, crypt_scheme);
931 return NULL;
934 static BIGNUM *
935 jpake_password_to_secret(Authctxt *authctxt, const char *crypt_scheme,
936 const char *salt)
938 char prompt[256], *password, *crypted;
939 u_char *secret;
940 u_int secret_len;
941 BIGNUM *ret;
943 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password (JPAKE): ",
944 authctxt->server_user, authctxt->host);
945 password = read_passphrase(prompt, 0);
947 if ((crypted = pw_encrypt(password, crypt_scheme, salt)) == NULL) {
948 logit("Disabling %s authentication", authctxt->method->name);
949 authctxt->method->enabled = NULL;
950 /* Continue with an empty password to fail gracefully */
951 crypted = xstrdup("");
954 #ifdef JPAKE_DEBUG
955 debug3("%s: salt = %s", __func__, salt);
956 debug3("%s: scheme = %s", __func__, crypt_scheme);
957 debug3("%s: crypted = %s", __func__, crypted);
958 #endif
960 if (hash_buffer(crypted, strlen(crypted), EVP_sha256(),
961 &secret, &secret_len) != 0)
962 fatal("%s: hash_buffer", __func__);
964 bzero(password, strlen(password));
965 bzero(crypted, strlen(crypted));
966 xfree(password);
967 xfree(crypted);
969 if ((ret = BN_bin2bn(secret, secret_len, NULL)) == NULL)
970 fatal("%s: BN_bin2bn (secret)", __func__);
971 bzero(secret, secret_len);
972 xfree(secret);
974 return ret;
977 /* ARGSUSED */
978 void
979 input_userauth_jpake_server_step1(int type, u_int32_t seq, void *ctxt)
981 Authctxt *authctxt = ctxt;
982 struct jpake_ctx *pctx = authctxt->methoddata;
983 u_char *x3_proof, *x4_proof, *x2_s_proof;
984 u_int x3_proof_len, x4_proof_len, x2_s_proof_len;
985 char *crypt_scheme, *salt;
987 /* Disable this message */
988 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1, NULL);
990 if ((pctx->g_x3 = BN_new()) == NULL ||
991 (pctx->g_x4 = BN_new()) == NULL)
992 fatal("%s: BN_new", __func__);
994 /* Fetch step 1 values */
995 crypt_scheme = packet_get_string(NULL);
996 salt = packet_get_string(NULL);
997 pctx->server_id = packet_get_string(&pctx->server_id_len);
998 packet_get_bignum2(pctx->g_x3);
999 packet_get_bignum2(pctx->g_x4);
1000 x3_proof = packet_get_string(&x3_proof_len);
1001 x4_proof = packet_get_string(&x4_proof_len);
1002 packet_check_eom();
1004 JPAKE_DEBUG_CTX((pctx, "step 1 received in %s", __func__));
1006 /* Obtain password and derive secret */
1007 pctx->s = jpake_password_to_secret(authctxt, crypt_scheme, salt);
1008 bzero(crypt_scheme, strlen(crypt_scheme));
1009 bzero(salt, strlen(salt));
1010 xfree(crypt_scheme);
1011 xfree(salt);
1012 JPAKE_DEBUG_BN((pctx->s, "%s: s = ", __func__));
1014 /* Calculate step 2 values */
1015 jpake_step2(pctx->grp, pctx->s, pctx->g_x1,
1016 pctx->g_x3, pctx->g_x4, pctx->x2,
1017 pctx->server_id, pctx->server_id_len,
1018 pctx->client_id, pctx->client_id_len,
1019 x3_proof, x3_proof_len,
1020 x4_proof, x4_proof_len,
1021 &pctx->a,
1022 &x2_s_proof, &x2_s_proof_len);
1024 bzero(x3_proof, x3_proof_len);
1025 bzero(x4_proof, x4_proof_len);
1026 xfree(x3_proof);
1027 xfree(x4_proof);
1029 JPAKE_DEBUG_CTX((pctx, "step 2 sending in %s", __func__));
1031 /* Send values for step 2 */
1032 packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP2);
1033 packet_put_bignum2(pctx->a);
1034 packet_put_string(x2_s_proof, x2_s_proof_len);
1035 packet_send();
1037 bzero(x2_s_proof, x2_s_proof_len);
1038 xfree(x2_s_proof);
1040 /* Expect step 2 packet from peer */
1041 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2,
1042 input_userauth_jpake_server_step2);
1045 /* ARGSUSED */
1046 void
1047 input_userauth_jpake_server_step2(int type, u_int32_t seq, void *ctxt)
1049 Authctxt *authctxt = ctxt;
1050 struct jpake_ctx *pctx = authctxt->methoddata;
1051 u_char *x4_s_proof;
1052 u_int x4_s_proof_len;
1054 /* Disable this message */
1055 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP2, NULL);
1057 if ((pctx->b = BN_new()) == NULL)
1058 fatal("%s: BN_new", __func__);
1060 /* Fetch step 2 values */
1061 packet_get_bignum2(pctx->b);
1062 x4_s_proof = packet_get_string(&x4_s_proof_len);
1063 packet_check_eom();
1065 JPAKE_DEBUG_CTX((pctx, "step 2 received in %s", __func__));
1067 /* Derive shared key and calculate confirmation hash */
1068 jpake_key_confirm(pctx->grp, pctx->s, pctx->b,
1069 pctx->x2, pctx->g_x1, pctx->g_x2, pctx->g_x3, pctx->g_x4,
1070 pctx->client_id, pctx->client_id_len,
1071 pctx->server_id, pctx->server_id_len,
1072 session_id2, session_id2_len,
1073 x4_s_proof, x4_s_proof_len,
1074 &pctx->k,
1075 &pctx->h_k_cid_sessid, &pctx->h_k_cid_sessid_len);
1077 bzero(x4_s_proof, x4_s_proof_len);
1078 xfree(x4_s_proof);
1080 JPAKE_DEBUG_CTX((pctx, "confirm sending in %s", __func__));
1082 /* Send key confirmation proof */
1083 packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_CONFIRM);
1084 packet_put_string(pctx->h_k_cid_sessid, pctx->h_k_cid_sessid_len);
1085 packet_send();
1087 /* Expect confirmation from peer */
1088 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM,
1089 input_userauth_jpake_server_confirm);
1092 /* ARGSUSED */
1093 void
1094 input_userauth_jpake_server_confirm(int type, u_int32_t seq, void *ctxt)
1096 Authctxt *authctxt = ctxt;
1097 struct jpake_ctx *pctx = authctxt->methoddata;
1099 /* Disable this message */
1100 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_CONFIRM, NULL);
1102 pctx->h_k_sid_sessid = packet_get_string(&pctx->h_k_sid_sessid_len);
1103 packet_check_eom();
1105 JPAKE_DEBUG_CTX((pctx, "confirm received in %s", __func__));
1107 /* Verify expected confirmation hash */
1108 if (jpake_check_confirm(pctx->k,
1109 pctx->server_id, pctx->server_id_len,
1110 session_id2, session_id2_len,
1111 pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len) == 1)
1112 debug("%s: %s success", __func__, authctxt->method->name);
1113 else {
1114 debug("%s: confirmation mismatch", __func__);
1115 /* XXX stash this so if auth succeeds then we can warn/kill */
1118 userauth_jpake_cleanup(authctxt);
1120 #endif /* JPAKE */
1122 static int
1123 identity_sign(Identity *id, u_char **sigp, u_int *lenp,
1124 u_char *data, u_int datalen)
1126 Key *prv;
1127 int ret;
1129 /* the agent supports this key */
1130 if (id->ac)
1131 return (ssh_agent_sign(id->ac, id->key, sigp, lenp,
1132 data, datalen));
1134 * we have already loaded the private key or
1135 * the private key is stored in external hardware
1137 if (id->isprivate || (id->key->flags & KEY_FLAG_EXT))
1138 return (key_sign(id->key, sigp, lenp, data, datalen));
1139 /* load the private key from the file */
1140 if ((prv = load_identity_file(id->filename)) == NULL)
1141 return (-1);
1142 ret = key_sign(prv, sigp, lenp, data, datalen);
1143 key_free(prv);
1144 return (ret);
1147 static int
1148 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1150 Buffer b;
1151 u_char *blob, *signature;
1152 u_int bloblen, slen;
1153 u_int skip = 0;
1154 int ret = -1;
1155 int have_sig = 1;
1157 debug3("sign_and_send_pubkey");
1159 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1160 /* we cannot handle this key */
1161 debug3("sign_and_send_pubkey: cannot handle key");
1162 return 0;
1164 /* data to be signed */
1165 buffer_init(&b);
1166 if (datafellows & SSH_OLD_SESSIONID) {
1167 buffer_append(&b, session_id2, session_id2_len);
1168 skip = session_id2_len;
1169 } else {
1170 buffer_put_string(&b, session_id2, session_id2_len);
1171 skip = buffer_len(&b);
1173 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1174 buffer_put_cstring(&b, authctxt->server_user);
1175 buffer_put_cstring(&b,
1176 datafellows & SSH_BUG_PKSERVICE ?
1177 "ssh-userauth" :
1178 authctxt->service);
1179 if (datafellows & SSH_BUG_PKAUTH) {
1180 buffer_put_char(&b, have_sig);
1181 } else {
1182 buffer_put_cstring(&b, authctxt->method->name);
1183 buffer_put_char(&b, have_sig);
1184 buffer_put_cstring(&b, key_ssh_name(id->key));
1186 buffer_put_string(&b, blob, bloblen);
1188 /* generate signature */
1189 ret = identity_sign(id, &signature, &slen,
1190 buffer_ptr(&b), buffer_len(&b));
1191 if (ret == -1) {
1192 xfree(blob);
1193 buffer_free(&b);
1194 return 0;
1196 #ifdef DEBUG_PK
1197 buffer_dump(&b);
1198 #endif
1199 if (datafellows & SSH_BUG_PKSERVICE) {
1200 buffer_clear(&b);
1201 buffer_append(&b, session_id2, session_id2_len);
1202 skip = session_id2_len;
1203 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1204 buffer_put_cstring(&b, authctxt->server_user);
1205 buffer_put_cstring(&b, authctxt->service);
1206 buffer_put_cstring(&b, authctxt->method->name);
1207 buffer_put_char(&b, have_sig);
1208 if (!(datafellows & SSH_BUG_PKAUTH))
1209 buffer_put_cstring(&b, key_ssh_name(id->key));
1210 buffer_put_string(&b, blob, bloblen);
1212 xfree(blob);
1214 /* append signature */
1215 buffer_put_string(&b, signature, slen);
1216 xfree(signature);
1218 /* skip session id and packet type */
1219 if (buffer_len(&b) < skip + 1)
1220 fatal("userauth_pubkey: internal error");
1221 buffer_consume(&b, skip + 1);
1223 /* put remaining data from buffer into packet */
1224 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1225 packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1226 buffer_free(&b);
1227 packet_send();
1229 return 1;
1232 static int
1233 send_pubkey_test(Authctxt *authctxt, Identity *id)
1235 u_char *blob;
1236 u_int bloblen, have_sig = 0;
1238 debug3("send_pubkey_test");
1240 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1241 /* we cannot handle this key */
1242 debug3("send_pubkey_test: cannot handle key");
1243 return 0;
1245 /* register callback for USERAUTH_PK_OK message */
1246 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1248 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1249 packet_put_cstring(authctxt->server_user);
1250 packet_put_cstring(authctxt->service);
1251 packet_put_cstring(authctxt->method->name);
1252 packet_put_char(have_sig);
1253 if (!(datafellows & SSH_BUG_PKAUTH))
1254 packet_put_cstring(key_ssh_name(id->key));
1255 packet_put_string(blob, bloblen);
1256 xfree(blob);
1257 packet_send();
1258 return 1;
1261 static Key *
1262 load_identity_file(char *filename)
1264 Key *private;
1265 char prompt[300], *passphrase;
1266 int perm_ok, quit, i;
1267 struct stat st;
1269 if (stat(filename, &st) < 0) {
1270 debug3("no such identity: %s", filename);
1271 return NULL;
1273 private = key_load_private_type(KEY_UNSPEC, filename, "", NULL, &perm_ok);
1274 if (!perm_ok)
1275 return NULL;
1276 if (private == NULL) {
1277 if (options.batch_mode)
1278 return NULL;
1279 snprintf(prompt, sizeof prompt,
1280 "Enter passphrase for key '%.100s': ", filename);
1281 for (i = 0; i < options.number_of_password_prompts; i++) {
1282 passphrase = read_passphrase(prompt, 0);
1283 if (strcmp(passphrase, "") != 0) {
1284 private = key_load_private_type(KEY_UNSPEC,
1285 filename, passphrase, NULL, NULL);
1286 quit = 0;
1287 } else {
1288 debug2("no passphrase given, try next key");
1289 quit = 1;
1291 memset(passphrase, 0, strlen(passphrase));
1292 xfree(passphrase);
1293 if (private != NULL || quit)
1294 break;
1295 debug2("bad passphrase given, try again...");
1298 return private;
1302 * try keys in the following order:
1303 * 1. agent keys that are found in the config file
1304 * 2. other agent keys
1305 * 3. keys that are only listed in the config file
1307 static void
1308 pubkey_prepare(Authctxt *authctxt)
1310 Identity *id;
1311 Idlist agent, files, *preferred;
1312 Key *key;
1313 AuthenticationConnection *ac;
1314 char *comment;
1315 int i, found;
1317 TAILQ_INIT(&agent); /* keys from the agent */
1318 TAILQ_INIT(&files); /* keys from the config file */
1319 preferred = &authctxt->keys;
1320 TAILQ_INIT(preferred); /* preferred order of keys */
1322 /* list of keys stored in the filesystem */
1323 for (i = 0; i < options.num_identity_files; i++) {
1324 key = options.identity_keys[i];
1325 if (key && key->type == KEY_RSA1)
1326 continue;
1327 options.identity_keys[i] = NULL;
1328 id = xcalloc(1, sizeof(*id));
1329 id->key = key;
1330 id->filename = xstrdup(options.identity_files[i]);
1331 TAILQ_INSERT_TAIL(&files, id, next);
1333 /* list of keys supported by the agent */
1334 if ((ac = ssh_get_authentication_connection())) {
1335 for (key = ssh_get_first_identity(ac, &comment, 2);
1336 key != NULL;
1337 key = ssh_get_next_identity(ac, &comment, 2)) {
1338 found = 0;
1339 TAILQ_FOREACH(id, &files, next) {
1340 /* agent keys from the config file are preferred */
1341 if (key_equal(key, id->key)) {
1342 key_free(key);
1343 xfree(comment);
1344 TAILQ_REMOVE(&files, id, next);
1345 TAILQ_INSERT_TAIL(preferred, id, next);
1346 id->ac = ac;
1347 found = 1;
1348 break;
1351 if (!found && !options.identities_only) {
1352 id = xcalloc(1, sizeof(*id));
1353 id->key = key;
1354 id->filename = comment;
1355 id->ac = ac;
1356 TAILQ_INSERT_TAIL(&agent, id, next);
1359 /* append remaining agent keys */
1360 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1361 TAILQ_REMOVE(&agent, id, next);
1362 TAILQ_INSERT_TAIL(preferred, id, next);
1364 authctxt->agent = ac;
1366 /* append remaining keys from the config file */
1367 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1368 TAILQ_REMOVE(&files, id, next);
1369 TAILQ_INSERT_TAIL(preferred, id, next);
1371 TAILQ_FOREACH(id, preferred, next) {
1372 debug2("key: %s (%p)", id->filename, id->key);
1376 static void
1377 pubkey_cleanup(Authctxt *authctxt)
1379 Identity *id;
1381 if (authctxt->agent != NULL)
1382 ssh_close_authentication_connection(authctxt->agent);
1383 for (id = TAILQ_FIRST(&authctxt->keys); id;
1384 id = TAILQ_FIRST(&authctxt->keys)) {
1385 TAILQ_REMOVE(&authctxt->keys, id, next);
1386 if (id->key)
1387 key_free(id->key);
1388 if (id->filename)
1389 xfree(id->filename);
1390 xfree(id);
1395 userauth_pubkey(Authctxt *authctxt)
1397 Identity *id;
1398 int sent = 0;
1400 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1401 if (id->tried++)
1402 return (0);
1403 /* move key to the end of the queue */
1404 TAILQ_REMOVE(&authctxt->keys, id, next);
1405 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1407 * send a test message if we have the public key. for
1408 * encrypted keys we cannot do this and have to load the
1409 * private key instead
1411 if (id->key && id->key->type != KEY_RSA1) {
1412 debug("Offering public key: %s", id->filename);
1413 sent = send_pubkey_test(authctxt, id);
1414 } else if (id->key == NULL) {
1415 debug("Trying private key: %s", id->filename);
1416 id->key = load_identity_file(id->filename);
1417 if (id->key != NULL) {
1418 id->isprivate = 1;
1419 sent = sign_and_send_pubkey(authctxt, id);
1420 key_free(id->key);
1421 id->key = NULL;
1424 if (sent)
1425 return (sent);
1427 return (0);
1431 * Send userauth request message specifying keyboard-interactive method.
1434 userauth_kbdint(Authctxt *authctxt)
1436 static int attempt = 0;
1438 if (attempt++ >= options.number_of_password_prompts)
1439 return 0;
1440 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1441 if (attempt > 1 && !authctxt->info_req_seen) {
1442 debug3("userauth_kbdint: disable: no info_req_seen");
1443 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1444 return 0;
1447 debug2("userauth_kbdint");
1448 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1449 packet_put_cstring(authctxt->server_user);
1450 packet_put_cstring(authctxt->service);
1451 packet_put_cstring(authctxt->method->name);
1452 packet_put_cstring(""); /* lang */
1453 packet_put_cstring(options.kbd_interactive_devices ?
1454 options.kbd_interactive_devices : "");
1455 packet_send();
1457 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1458 return 1;
1462 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1464 void
1465 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1467 Authctxt *authctxt = ctxt;
1468 char *name, *inst, *lang, *prompt, *response;
1469 u_int num_prompts, i;
1470 int echo = 0;
1472 debug2("input_userauth_info_req");
1474 if (authctxt == NULL)
1475 fatal("input_userauth_info_req: no authentication context");
1477 authctxt->info_req_seen = 1;
1479 name = packet_get_string(NULL);
1480 inst = packet_get_string(NULL);
1481 lang = packet_get_string(NULL);
1482 if (strlen(name) > 0)
1483 logit("%s", name);
1484 if (strlen(inst) > 0)
1485 logit("%s", inst);
1486 xfree(name);
1487 xfree(inst);
1488 xfree(lang);
1490 num_prompts = packet_get_int();
1492 * Begin to build info response packet based on prompts requested.
1493 * We commit to providing the correct number of responses, so if
1494 * further on we run into a problem that prevents this, we have to
1495 * be sure and clean this up and send a correct error response.
1497 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1498 packet_put_int(num_prompts);
1500 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1501 for (i = 0; i < num_prompts; i++) {
1502 prompt = packet_get_string(NULL);
1503 echo = packet_get_char();
1505 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1507 packet_put_cstring(response);
1508 memset(response, 0, strlen(response));
1509 xfree(response);
1510 xfree(prompt);
1512 packet_check_eom(); /* done with parsing incoming message. */
1514 packet_add_padding(64);
1515 packet_send();
1518 static int
1519 ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1520 u_char *data, u_int datalen)
1522 Buffer b;
1523 struct stat st;
1524 pid_t pid;
1525 int to[2], from[2], status, version = 2;
1527 debug2("ssh_keysign called");
1529 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1530 error("ssh_keysign: no installed: %s", strerror(errno));
1531 return -1;
1533 if (fflush(stdout) != 0)
1534 error("ssh_keysign: fflush: %s", strerror(errno));
1535 if (pipe(to) < 0) {
1536 error("ssh_keysign: pipe: %s", strerror(errno));
1537 return -1;
1539 if (pipe(from) < 0) {
1540 error("ssh_keysign: pipe: %s", strerror(errno));
1541 return -1;
1543 if ((pid = fork()) < 0) {
1544 error("ssh_keysign: fork: %s", strerror(errno));
1545 return -1;
1547 if (pid == 0) {
1548 permanently_drop_suid(getuid());
1549 close(from[0]);
1550 if (dup2(from[1], STDOUT_FILENO) < 0)
1551 fatal("ssh_keysign: dup2: %s", strerror(errno));
1552 close(to[1]);
1553 if (dup2(to[0], STDIN_FILENO) < 0)
1554 fatal("ssh_keysign: dup2: %s", strerror(errno));
1555 close(from[1]);
1556 close(to[0]);
1557 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1558 fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1559 strerror(errno));
1561 close(from[1]);
1562 close(to[0]);
1564 buffer_init(&b);
1565 buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1566 buffer_put_string(&b, data, datalen);
1567 if (ssh_msg_send(to[1], version, &b) == -1)
1568 fatal("ssh_keysign: couldn't send request");
1570 if (ssh_msg_recv(from[0], &b) < 0) {
1571 error("ssh_keysign: no reply");
1572 buffer_free(&b);
1573 return -1;
1575 close(from[0]);
1576 close(to[1]);
1578 while (waitpid(pid, &status, 0) < 0)
1579 if (errno != EINTR)
1580 break;
1582 if (buffer_get_char(&b) != version) {
1583 error("ssh_keysign: bad version");
1584 buffer_free(&b);
1585 return -1;
1587 *sigp = buffer_get_string(&b, lenp);
1588 buffer_free(&b);
1590 return 0;
1594 userauth_hostbased(Authctxt *authctxt)
1596 Key *private = NULL;
1597 Sensitive *sensitive = authctxt->sensitive;
1598 Buffer b;
1599 u_char *signature, *blob;
1600 char *chost, *pkalg, *p, myname[NI_MAXHOST];
1601 const char *service;
1602 u_int blen, slen;
1603 int ok, i, len, found = 0;
1605 /* check for a useful key */
1606 for (i = 0; i < sensitive->nkeys; i++) {
1607 private = sensitive->keys[i];
1608 if (private && private->type != KEY_RSA1) {
1609 found = 1;
1610 /* we take and free the key */
1611 sensitive->keys[i] = NULL;
1612 break;
1615 if (!found) {
1616 debug("No more client hostkeys for hostbased authentication.");
1617 return 0;
1619 if (key_to_blob(private, &blob, &blen) == 0) {
1620 key_free(private);
1621 return 0;
1623 /* figure out a name for the client host */
1624 p = NULL;
1625 if (packet_connection_is_on_socket())
1626 p = get_local_name(packet_get_connection_in());
1627 if (p == NULL) {
1628 if (gethostname(myname, sizeof(myname)) == -1) {
1629 verbose("userauth_hostbased: gethostname: %s",
1630 strerror(errno));
1631 } else
1632 p = xstrdup(myname);
1634 if (p == NULL) {
1635 error("userauth_hostbased: cannot get local ipaddr/name");
1636 key_free(private);
1637 xfree(blob);
1638 return 0;
1640 len = strlen(p) + 2;
1641 xasprintf(&chost, "%s.", p);
1642 debug2("userauth_hostbased: chost %s", chost);
1643 xfree(p);
1645 service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1646 authctxt->service;
1647 pkalg = xstrdup(key_ssh_name(private));
1648 buffer_init(&b);
1649 /* construct data */
1650 buffer_put_string(&b, session_id2, session_id2_len);
1651 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1652 buffer_put_cstring(&b, authctxt->server_user);
1653 buffer_put_cstring(&b, service);
1654 buffer_put_cstring(&b, authctxt->method->name);
1655 buffer_put_cstring(&b, pkalg);
1656 buffer_put_string(&b, blob, blen);
1657 buffer_put_cstring(&b, chost);
1658 buffer_put_cstring(&b, authctxt->local_user);
1659 #ifdef DEBUG_PK
1660 buffer_dump(&b);
1661 #endif
1662 if (sensitive->external_keysign)
1663 ok = ssh_keysign(private, &signature, &slen,
1664 buffer_ptr(&b), buffer_len(&b));
1665 else
1666 ok = key_sign(private, &signature, &slen,
1667 buffer_ptr(&b), buffer_len(&b));
1668 key_free(private);
1669 buffer_free(&b);
1670 if (ok != 0) {
1671 error("key_sign failed");
1672 xfree(chost);
1673 xfree(pkalg);
1674 xfree(blob);
1675 return 0;
1677 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1678 packet_put_cstring(authctxt->server_user);
1679 packet_put_cstring(authctxt->service);
1680 packet_put_cstring(authctxt->method->name);
1681 packet_put_cstring(pkalg);
1682 packet_put_string(blob, blen);
1683 packet_put_cstring(chost);
1684 packet_put_cstring(authctxt->local_user);
1685 packet_put_string(signature, slen);
1686 memset(signature, 's', slen);
1687 xfree(signature);
1688 xfree(chost);
1689 xfree(pkalg);
1690 xfree(blob);
1692 packet_send();
1693 return 1;
1696 #ifdef JPAKE
1698 userauth_jpake(Authctxt *authctxt)
1700 struct jpake_ctx *pctx;
1701 u_char *x1_proof, *x2_proof;
1702 u_int x1_proof_len, x2_proof_len;
1703 static int attempt = 0; /* XXX share with userauth_password's? */
1705 if (attempt++ >= options.number_of_password_prompts)
1706 return 0;
1707 if (attempt != 1)
1708 error("Permission denied, please try again.");
1710 if (authctxt->methoddata != NULL)
1711 fatal("%s: authctxt->methoddata already set (%p)",
1712 __func__, authctxt->methoddata);
1714 authctxt->methoddata = pctx = jpake_new();
1717 * Send request immediately, to get the protocol going while
1718 * we do the initial computations.
1720 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1721 packet_put_cstring(authctxt->server_user);
1722 packet_put_cstring(authctxt->service);
1723 packet_put_cstring(authctxt->method->name);
1724 packet_send();
1725 packet_write_wait();
1727 jpake_step1(pctx->grp,
1728 &pctx->client_id, &pctx->client_id_len,
1729 &pctx->x1, &pctx->x2, &pctx->g_x1, &pctx->g_x2,
1730 &x1_proof, &x1_proof_len,
1731 &x2_proof, &x2_proof_len);
1733 JPAKE_DEBUG_CTX((pctx, "step 1 sending in %s", __func__));
1735 packet_start(SSH2_MSG_USERAUTH_JPAKE_CLIENT_STEP1);
1736 packet_put_string(pctx->client_id, pctx->client_id_len);
1737 packet_put_bignum2(pctx->g_x1);
1738 packet_put_bignum2(pctx->g_x2);
1739 packet_put_string(x1_proof, x1_proof_len);
1740 packet_put_string(x2_proof, x2_proof_len);
1741 packet_send();
1743 bzero(x1_proof, x1_proof_len);
1744 bzero(x2_proof, x2_proof_len);
1745 xfree(x1_proof);
1746 xfree(x2_proof);
1748 /* Expect step 1 packet from peer */
1749 dispatch_set(SSH2_MSG_USERAUTH_JPAKE_SERVER_STEP1,
1750 input_userauth_jpake_server_step1);
1752 return 1;
1755 void
1756 userauth_jpake_cleanup(Authctxt *authctxt)
1758 debug3("%s: clean up", __func__);
1759 if (authctxt->methoddata != NULL) {
1760 jpake_free(authctxt->methoddata);
1761 authctxt->methoddata = NULL;
1764 #endif /* JPAKE */
1766 #if KRB5
1767 static int
1768 ssh_krb5_helper(krb5_data *ap)
1770 krb5_context xcontext = NULL; /* XXX share with ssh1 */
1771 krb5_auth_context xauth_context = NULL;
1773 krb5_context *context;
1774 krb5_auth_context *auth_context;
1775 krb5_error_code problem;
1776 const char *tkfile;
1777 struct stat buf;
1778 krb5_ccache ccache = NULL;
1779 const char *remotehost;
1780 int ret;
1782 memset(ap, 0, sizeof(*ap));
1784 context = &xcontext;
1785 auth_context = &xauth_context;
1787 problem = krb5_init_context(context);
1788 if (problem) {
1789 debug("Kerberos v5: krb5_init_context failed");
1790 ret = 0;
1791 goto out;
1794 tkfile = krb5_cc_default_name(*context);
1795 if (strncmp(tkfile, "FILE:", 5) == 0)
1796 tkfile += 5;
1798 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
1799 debug("Kerberos v5: could not get default ccache (permission denied).");
1800 ret = 0;
1801 goto out;
1804 problem = krb5_cc_default(*context, &ccache);
1805 if (problem) {
1806 debug("Kerberos v5: krb5_cc_default failed: %s",
1807 krb5_get_err_text(*context, problem));
1808 ret = 0;
1809 goto out;
1812 remotehost = get_canonical_hostname(1);
1814 problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
1815 "host", remotehost, NULL, ccache, ap);
1816 if (problem) {
1817 debug("Kerberos v5: krb5_mk_req failed: %s",
1818 krb5_get_err_text(*context, problem));
1819 ret = 0;
1820 goto out;
1822 ret = 1;
1824 out:
1825 if (ccache != NULL)
1826 krb5_cc_close(*context, ccache);
1827 if (*auth_context)
1828 krb5_auth_con_free(*context, *auth_context);
1829 if (*context)
1830 krb5_free_context(*context);
1831 return (ret);
1835 userauth_kerberos(Authctxt *authctxt)
1837 krb5_data ap;
1839 if (ssh_krb5_helper(&ap) == 0)
1840 return (0);
1842 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1843 packet_put_cstring(authctxt->server_user);
1844 packet_put_cstring(authctxt->service);
1845 packet_put_cstring(authctxt->method->name);
1846 packet_put_string(ap.data, ap.length);
1847 packet_send();
1849 krb5_data_free(&ap);
1850 return (1);
1852 #endif
1854 /* find auth method */
1857 * given auth method name, if configurable options permit this method fill
1858 * in auth_ident field and return true, otherwise return false.
1860 static int
1861 authmethod_is_enabled(Authmethod *method)
1863 if (method == NULL)
1864 return 0;
1865 /* return false if options indicate this method is disabled */
1866 if (method->enabled == NULL || *method->enabled == 0)
1867 return 0;
1868 /* return false if batch mode is enabled but method needs interactive mode */
1869 if (method->batch_flag != NULL && *method->batch_flag != 0)
1870 return 0;
1871 return 1;
1874 static Authmethod *
1875 authmethod_lookup(const char *name)
1877 Authmethod *method = NULL;
1878 if (name != NULL)
1879 for (method = authmethods; method->name != NULL; method++)
1880 if (strcmp(name, method->name) == 0)
1881 return method;
1882 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1883 return NULL;
1886 /* XXX internal state */
1887 static Authmethod *current = NULL;
1888 static char *supported = NULL;
1889 static char *preferred = NULL;
1892 * Given the authentication method list sent by the server, return the
1893 * next method we should try. If the server initially sends a nil list,
1894 * use a built-in default list.
1896 static Authmethod *
1897 authmethod_get(char *authlist)
1899 char *name = NULL;
1900 u_int next;
1902 /* Use a suitable default if we're passed a nil list. */
1903 if (authlist == NULL || strlen(authlist) == 0)
1904 authlist = options.preferred_authentications;
1906 if (supported == NULL || strcmp(authlist, supported) != 0) {
1907 debug3("start over, passed a different list %s", authlist);
1908 if (supported != NULL)
1909 xfree(supported);
1910 supported = xstrdup(authlist);
1911 preferred = options.preferred_authentications;
1912 debug3("preferred %s", preferred);
1913 current = NULL;
1914 } else if (current != NULL && authmethod_is_enabled(current))
1915 return current;
1917 for (;;) {
1918 if ((name = match_list(preferred, supported, &next)) == NULL) {
1919 debug("No more authentication methods to try.");
1920 current = NULL;
1921 return NULL;
1923 preferred += next;
1924 debug3("authmethod_lookup %s", name);
1925 debug3("remaining preferred: %s", preferred);
1926 if ((current = authmethod_lookup(name)) != NULL &&
1927 authmethod_is_enabled(current)) {
1928 debug3("authmethod_is_enabled %s", name);
1929 debug("Next authentication method: %s", name);
1930 return current;
1935 static char *
1936 authmethods_get(void)
1938 Authmethod *method = NULL;
1939 Buffer b;
1940 char *list;
1942 buffer_init(&b);
1943 for (method = authmethods; method->name != NULL; method++) {
1944 if (authmethod_is_enabled(method)) {
1945 if (buffer_len(&b) > 0)
1946 buffer_append(&b, ",", 1);
1947 buffer_append(&b, method->name, strlen(method->name));
1950 buffer_append(&b, "\0", 1);
1951 list = xstrdup(buffer_ptr(&b));
1952 buffer_free(&b);
1953 return list;