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