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