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