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