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