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