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