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