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