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