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