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