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