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