]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/sshconnect2.c
Implement "strict key exchange" in ssh and sshd.
[FreeBSD/FreeBSD.git] / crypto / openssh / sshconnect2.c
1 /* $OpenBSD: sshconnect2.c,v 1.367 2023/08/01 08:15:04 dtucker 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 <fcntl.h>
36 #include <limits.h>
37 #include <netdb.h>
38 #include <pwd.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <unistd.h>
44 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
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 "sshbuf.h"
54 #include "packet.h"
55 #include "compat.h"
56 #include "cipher.h"
57 #include "sshkey.h"
58 #include "kex.h"
59 #include "sshconnect.h"
60 #include "authfile.h"
61 #include "dh.h"
62 #include "authfd.h"
63 #include "log.h"
64 #include "misc.h"
65 #include "readconf.h"
66 #include "match.h"
67 #include "dispatch.h"
68 #include "canohost.h"
69 #include "msg.h"
70 #include "pathnames.h"
71 #include "uidswap.h"
72 #include "hostfile.h"
73 #include "ssherr.h"
74 #include "utf8.h"
75 #include "ssh-sk.h"
76 #include "sk-api.h"
77
78 #ifdef GSSAPI
79 #include "ssh-gss.h"
80 #endif
81
82 /* import */
83 extern char *client_version_string;
84 extern char *server_version_string;
85 extern Options options;
86
87 /*
88  * SSH2 key exchange
89  */
90
91 static char *xxx_host;
92 static struct sockaddr *xxx_hostaddr;
93 static const struct ssh_conn_info *xxx_conn_info;
94
95 static int
96 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh)
97 {
98         int r;
99
100         if ((r = sshkey_check_rsa_length(hostkey,
101             options.required_rsa_size)) != 0)
102                 fatal_r(r, "Bad server host key");
103         if (verify_host_key(xxx_host, xxx_hostaddr, hostkey,
104             xxx_conn_info) == -1)
105                 fatal("Host key verification failed.");
106         return 0;
107 }
108
109 /* Returns the first item from a comma-separated algorithm list */
110 static char *
111 first_alg(const char *algs)
112 {
113         char *ret, *cp;
114
115         ret = xstrdup(algs);
116         if ((cp = strchr(ret, ',')) != NULL)
117                 *cp = '\0';
118         return ret;
119 }
120
121 static char *
122 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port,
123     const struct ssh_conn_info *cinfo)
124 {
125         char *oavail = NULL, *avail = NULL, *first = NULL, *last = NULL;
126         char *alg = NULL, *hostname = NULL, *ret = NULL, *best = NULL;
127         size_t maxlen;
128         struct hostkeys *hostkeys = NULL;
129         int ktype;
130         u_int i;
131
132         /* Find all hostkeys for this hostname */
133         get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
134         hostkeys = init_hostkeys();
135         for (i = 0; i < options.num_user_hostfiles; i++)
136                 load_hostkeys(hostkeys, hostname, options.user_hostfiles[i], 0);
137         for (i = 0; i < options.num_system_hostfiles; i++) {
138                 load_hostkeys(hostkeys, hostname,
139                     options.system_hostfiles[i], 0);
140         }
141         if (options.known_hosts_command != NULL) {
142                 load_hostkeys_command(hostkeys, options.known_hosts_command,
143                     "ORDER", cinfo, NULL, host);
144         }
145         /*
146          * If a plain public key exists that matches the type of the best
147          * preference HostkeyAlgorithms, then use the whole list as is.
148          * Note that we ignore whether the best preference algorithm is a
149          * certificate type, as sshconnect.c will downgrade certs to
150          * plain keys if necessary.
151          */
152         best = first_alg(options.hostkeyalgorithms);
153         if (lookup_key_in_hostkeys_by_type(hostkeys,
154             sshkey_type_plain(sshkey_type_from_name(best)),
155             sshkey_ecdsa_nid_from_name(best), NULL)) {
156                 debug3_f("have matching best-preference key type %s, "
157                     "using HostkeyAlgorithms verbatim", best);
158                 ret = xstrdup(options.hostkeyalgorithms);
159                 goto out;
160         }
161
162         /*
163          * Otherwise, prefer the host key algorithms that match known keys
164          * while keeping the ordering of HostkeyAlgorithms as much as possible.
165          */
166         oavail = avail = xstrdup(options.hostkeyalgorithms);
167         maxlen = strlen(avail) + 1;
168         first = xmalloc(maxlen);
169         last = xmalloc(maxlen);
170         *first = *last = '\0';
171
172 #define ALG_APPEND(to, from) \
173         do { \
174                 if (*to != '\0') \
175                         strlcat(to, ",", maxlen); \
176                 strlcat(to, from, maxlen); \
177         } while (0)
178
179         while ((alg = strsep(&avail, ",")) && *alg != '\0') {
180                 if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
181                         fatal_f("unknown alg %s", alg);
182                 /*
183                  * If we have a @cert-authority marker in known_hosts then
184                  * prefer all certificate algorithms.
185                  */
186                 if (sshkey_type_is_cert(ktype) &&
187                     lookup_marker_in_hostkeys(hostkeys, MRK_CA)) {
188                         ALG_APPEND(first, alg);
189                         continue;
190                 }
191                 /* If the key appears in known_hosts then prefer it */
192                 if (lookup_key_in_hostkeys_by_type(hostkeys,
193                     sshkey_type_plain(ktype),
194                     sshkey_ecdsa_nid_from_name(alg), NULL)) {
195                         ALG_APPEND(first, alg);
196                         continue;
197                 }
198                 /* Otherwise, put it last */
199                 ALG_APPEND(last, alg);
200         }
201 #undef ALG_APPEND
202         xasprintf(&ret, "%s%s%s", first,
203             (*first == '\0' || *last == '\0') ? "" : ",", last);
204         if (*first != '\0')
205                 debug3_f("prefer hostkeyalgs: %s", first);
206         else
207                 debug3_f("no algorithms matched; accept original");
208  out:
209         free(best);
210         free(first);
211         free(last);
212         free(hostname);
213         free(oavail);
214         free_hostkeys(hostkeys);
215
216         return ret;
217 }
218
219 void
220 ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port,
221     const struct ssh_conn_info *cinfo)
222 {
223         char *myproposal[PROPOSAL_MAX];
224         char *s, *all_key, *hkalgs = NULL;
225         int r, use_known_hosts_order = 0;
226
227         xxx_host = host;
228         xxx_hostaddr = hostaddr;
229         xxx_conn_info = cinfo;
230
231         if (options.rekey_limit || options.rekey_interval)
232                 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
233                     options.rekey_interval);
234
235         /*
236          * If the user has not specified HostkeyAlgorithms, or has only
237          * appended or removed algorithms from that list then prefer algorithms
238          * that are in the list that are supported by known_hosts keys.
239          */
240         if (options.hostkeyalgorithms == NULL ||
241             options.hostkeyalgorithms[0] == '-' ||
242             options.hostkeyalgorithms[0] == '+')
243                 use_known_hosts_order = 1;
244
245         /* Expand or fill in HostkeyAlgorithms */
246         all_key = sshkey_alg_list(0, 0, 1, ',');
247         if ((r = kex_assemble_names(&options.hostkeyalgorithms,
248             kex_default_pk_alg(), all_key)) != 0)
249                 fatal_fr(r, "kex_assemble_namelist");
250         free(all_key);
251
252         if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
253                 fatal_f("kex_names_cat");
254
255         if (use_known_hosts_order)
256                 hkalgs = order_hostkeyalgs(host, hostaddr, port, cinfo);
257
258         kex_proposal_populate_entries(ssh, myproposal, s, options.ciphers,
259             options.macs, compression_alg_list(options.compression),
260             hkalgs ? hkalgs : options.hostkeyalgorithms);
261
262         free(hkalgs);
263
264         /* start key exchange */
265         if ((r = kex_setup(ssh, myproposal)) != 0)
266                 fatal_r(r, "kex_setup");
267 #ifdef WITH_OPENSSL
268         ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
269         ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
270         ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
271         ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
272         ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
273         ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
274         ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
275 # ifdef OPENSSL_HAS_ECC
276         ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
277 # endif
278 #endif
279         ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
280         ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
281         ssh->kex->verify_host_key=&verify_host_key_callback;
282
283         ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done);
284
285         /* remove ext-info from the KEX proposals for rekeying */
286         free(myproposal[PROPOSAL_KEX_ALGS]);
287         myproposal[PROPOSAL_KEX_ALGS] =
288             compat_kex_proposal(ssh, options.kex_algorithms);
289         if ((r = kex_prop2buf(ssh->kex->my, myproposal)) != 0)
290                 fatal_r(r, "kex_prop2buf");
291
292 #ifdef DEBUG_KEXDH
293         /* send 1st encrypted/maced/compressed message */
294         if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
295             (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
296             (r = sshpkt_send(ssh)) != 0 ||
297             (r = ssh_packet_write_wait(ssh)) != 0)
298                 fatal_fr(r, "send packet");
299 #endif
300         kex_proposal_free_entries(myproposal);
301 }
302
303 /*
304  * Authenticate user
305  */
306
307 typedef struct cauthctxt Authctxt;
308 typedef struct cauthmethod Authmethod;
309 typedef struct identity Identity;
310 typedef struct idlist Idlist;
311
312 struct identity {
313         TAILQ_ENTRY(identity) next;
314         int     agent_fd;               /* >=0 if agent supports key */
315         struct sshkey   *key;           /* public/private key */
316         char    *filename;              /* comment for agent-only keys */
317         int     tried;
318         int     isprivate;              /* key points to the private key */
319         int     userprovided;
320 };
321 TAILQ_HEAD(idlist, identity);
322
323 struct cauthctxt {
324         const char *server_user;
325         const char *local_user;
326         const char *host;
327         const char *service;
328         struct cauthmethod *method;
329         sig_atomic_t success;
330         char *authlist;
331 #ifdef GSSAPI
332         /* gssapi */
333         gss_OID_set gss_supported_mechs;
334         u_int mech_tried;
335 #endif
336         /* pubkey */
337         struct idlist keys;
338         int agent_fd;
339         /* hostbased */
340         Sensitive *sensitive;
341         char *oktypes, *ktypes;
342         const char *active_ktype;
343         /* kbd-interactive */
344         int info_req_seen;
345         int attempt_kbdint;
346         /* password */
347         int attempt_passwd;
348         /* generic */
349         void *methoddata;
350 };
351
352 struct cauthmethod {
353         char    *name;          /* string to compare against server's list */
354         int     (*userauth)(struct ssh *ssh);
355         void    (*cleanup)(struct ssh *ssh);
356         int     *enabled;       /* flag in option struct that enables method */
357         int     *batch_flag;    /* flag in option struct that disables method */
358 };
359
360 static int input_userauth_service_accept(int, u_int32_t, struct ssh *);
361 static int input_userauth_success(int, u_int32_t, struct ssh *);
362 static int input_userauth_failure(int, u_int32_t, struct ssh *);
363 static int input_userauth_banner(int, u_int32_t, struct ssh *);
364 static int input_userauth_error(int, u_int32_t, struct ssh *);
365 static int input_userauth_info_req(int, u_int32_t, struct ssh *);
366 static int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
367 static int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
368
369 static int userauth_none(struct ssh *);
370 static int userauth_pubkey(struct ssh *);
371 static int userauth_passwd(struct ssh *);
372 static int userauth_kbdint(struct ssh *);
373 static int userauth_hostbased(struct ssh *);
374
375 #ifdef GSSAPI
376 static int userauth_gssapi(struct ssh *);
377 static void userauth_gssapi_cleanup(struct ssh *);
378 static int input_gssapi_response(int type, u_int32_t, struct ssh *);
379 static int input_gssapi_token(int type, u_int32_t, struct ssh *);
380 static int input_gssapi_error(int, u_int32_t, struct ssh *);
381 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
382 #endif
383
384 void    userauth(struct ssh *, char *);
385
386 static void pubkey_cleanup(struct ssh *);
387 static int sign_and_send_pubkey(struct ssh *ssh, Identity *);
388 static void pubkey_prepare(struct ssh *, Authctxt *);
389 static void pubkey_reset(Authctxt *);
390 static struct sshkey *load_identity_file(Identity *);
391
392 static Authmethod *authmethod_get(char *authlist);
393 static Authmethod *authmethod_lookup(const char *name);
394 static char *authmethods_get(void);
395
396 Authmethod authmethods[] = {
397 #ifdef GSSAPI
398         {"gssapi-with-mic",
399                 userauth_gssapi,
400                 userauth_gssapi_cleanup,
401                 &options.gss_authentication,
402                 NULL},
403 #endif
404         {"hostbased",
405                 userauth_hostbased,
406                 NULL,
407                 &options.hostbased_authentication,
408                 NULL},
409         {"publickey",
410                 userauth_pubkey,
411                 NULL,
412                 &options.pubkey_authentication,
413                 NULL},
414         {"keyboard-interactive",
415                 userauth_kbdint,
416                 NULL,
417                 &options.kbd_interactive_authentication,
418                 &options.batch_mode},
419         {"password",
420                 userauth_passwd,
421                 NULL,
422                 &options.password_authentication,
423                 &options.batch_mode},
424         {"none",
425                 userauth_none,
426                 NULL,
427                 NULL,
428                 NULL},
429         {NULL, NULL, NULL, NULL, NULL}
430 };
431
432 void
433 ssh_userauth2(struct ssh *ssh, const char *local_user,
434     const char *server_user, char *host, Sensitive *sensitive)
435 {
436         Authctxt authctxt;
437         int r;
438
439         if (options.preferred_authentications == NULL)
440                 options.preferred_authentications = authmethods_get();
441
442         /* setup authentication context */
443         memset(&authctxt, 0, sizeof(authctxt));
444         authctxt.server_user = server_user;
445         authctxt.local_user = local_user;
446         authctxt.host = host;
447         authctxt.service = "ssh-connection";            /* service name */
448         authctxt.success = 0;
449         authctxt.method = authmethod_lookup("none");
450         authctxt.authlist = NULL;
451         authctxt.methoddata = NULL;
452         authctxt.sensitive = sensitive;
453         authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
454         authctxt.info_req_seen = 0;
455         authctxt.attempt_kbdint = 0;
456         authctxt.attempt_passwd = 0;
457 #if GSSAPI
458         authctxt.gss_supported_mechs = NULL;
459         authctxt.mech_tried = 0;
460 #endif
461         authctxt.agent_fd = -1;
462         pubkey_prepare(ssh, &authctxt);
463         if (authctxt.method == NULL) {
464                 fatal_f("internal error: cannot send userauth none request");
465         }
466
467         if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
468             (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
469             (r = sshpkt_send(ssh)) != 0)
470                 fatal_fr(r, "send packet");
471
472         ssh->authctxt = &authctxt;
473         ssh_dispatch_init(ssh, &input_userauth_error);
474         ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, kex_input_ext_info);
475         ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
476         ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success); /* loop until success */
477         pubkey_cleanup(ssh);
478         ssh->authctxt = NULL;
479
480         ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
481
482         if (!authctxt.success)
483                 fatal("Authentication failed.");
484         if (ssh_packet_connection_is_on_socket(ssh)) {
485                 verbose("Authenticated to %s ([%s]:%d) using \"%s\".", host,
486                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
487                     authctxt.method->name);
488         } else {
489                 verbose("Authenticated to %s (via proxy) using \"%s\".", host,
490                     authctxt.method->name);
491         }
492 }
493
494 static int
495 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
496 {
497         int r;
498
499         if (ssh_packet_remaining(ssh) > 0) {
500                 char *reply;
501
502                 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
503                         goto out;
504                 debug2("service_accept: %s", reply);
505                 free(reply);
506         } else {
507                 debug2("buggy server: service_accept w/o service");
508         }
509         if ((r = sshpkt_get_end(ssh)) != 0)
510                 goto out;
511         debug("SSH2_MSG_SERVICE_ACCEPT received");
512
513         /* initial userauth request */
514         userauth_none(ssh);
515
516         ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
517         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
518         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
519         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
520         r = 0;
521  out:
522         return r;
523 }
524
525 void
526 userauth(struct ssh *ssh, char *authlist)
527 {
528         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
529
530         if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
531                 authctxt->method->cleanup(ssh);
532
533         free(authctxt->methoddata);
534         authctxt->methoddata = NULL;
535         if (authlist == NULL) {
536                 authlist = authctxt->authlist;
537         } else {
538                 free(authctxt->authlist);
539                 authctxt->authlist = authlist;
540         }
541         for (;;) {
542                 Authmethod *method = authmethod_get(authlist);
543                 if (method == NULL)
544                         fatal("%s@%s: Permission denied (%s).",
545                             authctxt->server_user, authctxt->host, authlist);
546                 authctxt->method = method;
547
548                 /* reset the per method handler */
549                 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN,
550                     SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
551
552                 /* and try new method */
553                 if (method->userauth(ssh) != 0) {
554                         debug2("we sent a %s packet, wait for reply", method->name);
555                         break;
556                 } else {
557                         debug2("we did not send a packet, disable method");
558                         method->enabled = NULL;
559                 }
560         }
561 }
562
563 static int
564 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
565 {
566         fatal_f("bad message during authentication: type %d", type);
567         return 0;
568 }
569
570 static int
571 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
572 {
573         char *msg = NULL;
574         size_t len;
575         int r;
576
577         debug3_f("entering");
578         if ((r = sshpkt_get_cstring(ssh, &msg, &len)) != 0 ||
579             (r = sshpkt_get_cstring(ssh, NULL, NULL)) != 0)
580                 goto out;
581         if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
582                 fmprintf(stderr, "%s", msg);
583         r = 0;
584  out:
585         free(msg);
586         return r;
587 }
588
589 static int
590 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
591 {
592         Authctxt *authctxt = ssh->authctxt;
593
594         if (authctxt == NULL)
595                 fatal_f("no authentication context");
596         free(authctxt->authlist);
597         authctxt->authlist = NULL;
598         if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
599                 authctxt->method->cleanup(ssh);
600         free(authctxt->methoddata);
601         authctxt->methoddata = NULL;
602         authctxt->success = 1;                  /* break out */
603         ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, dispatch_protocol_error);
604         return 0;
605 }
606
607 #if 0
608 static int
609 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
610 {
611         Authctxt *authctxt = ssh->authctxt;
612
613         if (authctxt == NULL)
614                 fatal_f("no authentication context");
615
616         fatal("Unexpected authentication success during %s.",
617             authctxt->method->name);
618         return 0;
619 }
620 #endif
621
622 static int
623 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
624 {
625         Authctxt *authctxt = ssh->authctxt;
626         char *authlist = NULL;
627         u_char partial;
628
629         if (authctxt == NULL)
630                 fatal("input_userauth_failure: no authentication context");
631
632         if (sshpkt_get_cstring(ssh, &authlist, NULL) != 0 ||
633             sshpkt_get_u8(ssh, &partial) != 0 ||
634             sshpkt_get_end(ssh) != 0)
635                 goto out;
636
637         if (partial != 0) {
638                 verbose("Authenticated using \"%s\" with partial success.",
639                     authctxt->method->name);
640                 /* reset state */
641                 pubkey_reset(authctxt);
642         }
643         debug("Authentications that can continue: %s", authlist);
644
645         userauth(ssh, authlist);
646         authlist = NULL;
647  out:
648         free(authlist);
649         return 0;
650 }
651
652 /*
653  * Format an identity for logging including filename, key type, fingerprint
654  * and location (agent, etc.). Caller must free.
655  */
656 static char *
657 format_identity(Identity *id)
658 {
659         char *fp = NULL, *ret = NULL;
660         const char *note = "";
661
662         if (id->key != NULL) {
663                 fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
664                     SSH_FP_DEFAULT);
665         }
666         if (id->key) {
667                 if ((id->key->flags & SSHKEY_FLAG_EXT) != 0)
668                         note = " token";
669                 else if (sshkey_is_sk(id->key))
670                         note = " authenticator";
671         }
672         xasprintf(&ret, "%s %s%s%s%s%s%s",
673             id->filename,
674             id->key ? sshkey_type(id->key) : "", id->key ? " " : "",
675             fp ? fp : "",
676             id->userprovided ? " explicit" : "", note,
677             id->agent_fd != -1 ? " agent" : "");
678         free(fp);
679         return ret;
680 }
681
682 static int
683 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
684 {
685         Authctxt *authctxt = ssh->authctxt;
686         struct sshkey *key = NULL;
687         Identity *id = NULL;
688         int pktype, found = 0, sent = 0;
689         size_t blen;
690         char *pkalg = NULL, *fp = NULL, *ident = NULL;
691         u_char *pkblob = NULL;
692         int r;
693
694         if (authctxt == NULL)
695                 fatal("input_userauth_pk_ok: no authentication context");
696
697         if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
698             (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
699             (r = sshpkt_get_end(ssh)) != 0)
700                 goto done;
701
702         if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) {
703                 debug_f("server sent unknown pkalg %s", pkalg);
704                 goto done;
705         }
706         if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
707                 debug_r(r, "no key from blob. pkalg %s", pkalg);
708                 goto done;
709         }
710         if (key->type != pktype) {
711                 error("input_userauth_pk_ok: type mismatch "
712                     "for decoded key (received %d, expected %d)",
713                     key->type, pktype);
714                 goto done;
715         }
716
717         /*
718          * search keys in the reverse order, because last candidate has been
719          * moved to the end of the queue.  this also avoids confusion by
720          * duplicate keys
721          */
722         TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
723                 if (sshkey_equal(key, id->key)) {
724                         found = 1;
725                         break;
726                 }
727         }
728         if (!found || id == NULL) {
729                 fp = sshkey_fingerprint(key, options.fingerprint_hash,
730                     SSH_FP_DEFAULT);
731                 error_f("server replied with unknown key: %s %s",
732                     sshkey_type(key), fp == NULL ? "<ERROR>" : fp);
733                 goto done;
734         }
735         ident = format_identity(id);
736         debug("Server accepts key: %s", ident);
737         sent = sign_and_send_pubkey(ssh, id);
738         r = 0;
739  done:
740         sshkey_free(key);
741         free(ident);
742         free(fp);
743         free(pkalg);
744         free(pkblob);
745
746         /* try another method if we did not send a packet */
747         if (r == 0 && sent == 0)
748                 userauth(ssh, NULL);
749         return r;
750 }
751
752 #ifdef GSSAPI
753 static int
754 userauth_gssapi(struct ssh *ssh)
755 {
756         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
757         Gssctxt *gssctxt = NULL;
758         OM_uint32 min;
759         int r, ok = 0;
760         gss_OID mech = NULL;
761
762         /* Try one GSSAPI method at a time, rather than sending them all at
763          * once. */
764
765         if (authctxt->gss_supported_mechs == NULL)
766                 gss_indicate_mechs(&min, &authctxt->gss_supported_mechs);
767
768         /* Check to see whether the mechanism is usable before we offer it */
769         while (authctxt->mech_tried < authctxt->gss_supported_mechs->count &&
770             !ok) {
771                 mech = &authctxt->gss_supported_mechs->
772                     elements[authctxt->mech_tried];
773                 /* My DER encoding requires length<128 */
774                 if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt,
775                     mech, authctxt->host)) {
776                         ok = 1; /* Mechanism works */
777                 } else {
778                         authctxt->mech_tried++;
779                 }
780         }
781
782         if (!ok || mech == NULL)
783                 return 0;
784
785         authctxt->methoddata=(void *)gssctxt;
786
787         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
788             (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
789             (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
790             (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
791             (r = sshpkt_put_u32(ssh, 1)) != 0 ||
792             (r = sshpkt_put_u32(ssh, (mech->length) + 2)) != 0 ||
793             (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 ||
794             (r = sshpkt_put_u8(ssh, mech->length)) != 0 ||
795             (r = sshpkt_put(ssh, mech->elements, mech->length)) != 0 ||
796             (r = sshpkt_send(ssh)) != 0)
797                 fatal_fr(r, "send packet");
798
799         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
800         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
801         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
802         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
803
804         authctxt->mech_tried++; /* Move along to next candidate */
805
806         return 1;
807 }
808
809 static void
810 userauth_gssapi_cleanup(struct ssh *ssh)
811 {
812         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
813         Gssctxt *gssctxt = (Gssctxt *)authctxt->methoddata;
814
815         ssh_gssapi_delete_ctx(&gssctxt);
816         authctxt->methoddata = NULL;
817
818         free(authctxt->gss_supported_mechs);
819         authctxt->gss_supported_mechs = NULL;
820 }
821
822 static OM_uint32
823 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
824 {
825         Authctxt *authctxt = ssh->authctxt;
826         Gssctxt *gssctxt = authctxt->methoddata;
827         gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
828         gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
829         gss_buffer_desc gssbuf;
830         OM_uint32 status, ms, flags;
831         int r;
832
833         status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
834             recv_tok, &send_tok, &flags);
835
836         if (send_tok.length > 0) {
837                 u_char type = GSS_ERROR(status) ?
838                     SSH2_MSG_USERAUTH_GSSAPI_ERRTOK :
839                     SSH2_MSG_USERAUTH_GSSAPI_TOKEN;
840
841                 if ((r = sshpkt_start(ssh, type)) != 0 ||
842                     (r = sshpkt_put_string(ssh, send_tok.value,
843                     send_tok.length)) != 0 ||
844                     (r = sshpkt_send(ssh)) != 0)
845                         fatal_fr(r, "send %u packet", type);
846
847                 gss_release_buffer(&ms, &send_tok);
848         }
849
850         if (status == GSS_S_COMPLETE) {
851                 /* send either complete or MIC, depending on mechanism */
852                 if (!(flags & GSS_C_INTEG_FLAG)) {
853                         if ((r = sshpkt_start(ssh,
854                             SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 ||
855                             (r = sshpkt_send(ssh)) != 0)
856                                 fatal_fr(r, "send completion");
857                 } else {
858                         struct sshbuf *b;
859
860                         if ((b = sshbuf_new()) == NULL)
861                                 fatal_f("sshbuf_new failed");
862                         ssh_gssapi_buildmic(b, authctxt->server_user,
863                             authctxt->service, "gssapi-with-mic",
864                             ssh->kex->session_id);
865
866                         if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
867                                 fatal_f("sshbuf_mutable_ptr failed");
868                         gssbuf.length = sshbuf_len(b);
869
870                         status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
871
872                         if (!GSS_ERROR(status)) {
873                                 if ((r = sshpkt_start(ssh,
874                                     SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 ||
875                                     (r = sshpkt_put_string(ssh, mic.value,
876                                     mic.length)) != 0 ||
877                                     (r = sshpkt_send(ssh)) != 0)
878                                         fatal_fr(r, "send MIC");
879                         }
880
881                         sshbuf_free(b);
882                         gss_release_buffer(&ms, &mic);
883                 }
884         }
885
886         return status;
887 }
888
889 static int
890 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
891 {
892         Authctxt *authctxt = ssh->authctxt;
893         Gssctxt *gssctxt;
894         size_t oidlen;
895         u_char *oidv = NULL;
896         int r;
897
898         if (authctxt == NULL)
899                 fatal("input_gssapi_response: no authentication context");
900         gssctxt = authctxt->methoddata;
901
902         /* Setup our OID */
903         if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0)
904                 goto done;
905
906         if (oidlen <= 2 ||
907             oidv[0] != SSH_GSS_OIDTYPE ||
908             oidv[1] != oidlen - 2) {
909                 debug("Badly encoded mechanism OID received");
910                 userauth(ssh, NULL);
911                 goto ok;
912         }
913
914         if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
915                 fatal("Server returned different OID than expected");
916
917         if ((r = sshpkt_get_end(ssh)) != 0)
918                 goto done;
919
920         if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
921                 /* Start again with next method on list */
922                 debug("Trying to start again");
923                 userauth(ssh, NULL);
924                 goto ok;
925         }
926  ok:
927         r = 0;
928  done:
929         free(oidv);
930         return r;
931 }
932
933 static int
934 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
935 {
936         Authctxt *authctxt = ssh->authctxt;
937         gss_buffer_desc recv_tok;
938         u_char *p = NULL;
939         size_t len;
940         OM_uint32 status;
941         int r;
942
943         if (authctxt == NULL)
944                 fatal("input_gssapi_response: no authentication context");
945
946         if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
947             (r = sshpkt_get_end(ssh)) != 0)
948                 goto out;
949
950         recv_tok.value = p;
951         recv_tok.length = len;
952         status = process_gssapi_token(ssh, &recv_tok);
953
954         /* Start again with the next method in the list */
955         if (GSS_ERROR(status)) {
956                 userauth(ssh, NULL);
957                 /* ok */
958         }
959         r = 0;
960  out:
961         free(p);
962         return r;
963 }
964
965 static int
966 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
967 {
968         Authctxt *authctxt = ssh->authctxt;
969         Gssctxt *gssctxt;
970         gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
971         gss_buffer_desc recv_tok;
972         OM_uint32 ms;
973         u_char *p = NULL;
974         size_t len;
975         int r;
976
977         if (authctxt == NULL)
978                 fatal("input_gssapi_response: no authentication context");
979         gssctxt = authctxt->methoddata;
980
981         if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
982             (r = sshpkt_get_end(ssh)) != 0) {
983                 free(p);
984                 return r;
985         }
986
987         /* Stick it into GSSAPI and see what it says */
988         recv_tok.value = p;
989         recv_tok.length = len;
990         (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
991             &recv_tok, &send_tok, NULL);
992         free(p);
993         gss_release_buffer(&ms, &send_tok);
994
995         /* Server will be returning a failed packet after this one */
996         return 0;
997 }
998
999 static int
1000 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
1001 {
1002         char *msg = NULL;
1003         char *lang = NULL;
1004         int r;
1005
1006         if ((r = sshpkt_get_u32(ssh, NULL)) != 0 ||     /* maj */
1007             (r = sshpkt_get_u32(ssh, NULL)) != 0 ||     /* min */
1008             (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
1009             (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1010                 goto out;
1011         r = sshpkt_get_end(ssh);
1012         debug("Server GSSAPI Error:\n%s", msg);
1013  out:
1014         free(msg);
1015         free(lang);
1016         return r;
1017 }
1018 #endif /* GSSAPI */
1019
1020 static int
1021 userauth_none(struct ssh *ssh)
1022 {
1023         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1024         int r;
1025
1026         /* initial userauth request */
1027         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1028             (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1029             (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1030             (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1031             (r = sshpkt_send(ssh)) != 0)
1032                 fatal_fr(r, "send packet");
1033         return 1;
1034 }
1035
1036 static int
1037 userauth_passwd(struct ssh *ssh)
1038 {
1039         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1040         char *password, *prompt = NULL;
1041         const char *host = options.host_key_alias ?  options.host_key_alias :
1042             authctxt->host;
1043         int r;
1044
1045         if (authctxt->attempt_passwd++ >= options.number_of_password_prompts)
1046                 return 0;
1047
1048         if (authctxt->attempt_passwd != 1)
1049                 error("Permission denied, please try again.");
1050
1051         xasprintf(&prompt, "%s@%s's password: ", authctxt->server_user, host);
1052         password = read_passphrase(prompt, 0);
1053         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1054             (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1055             (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1056             (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1057             (r = sshpkt_put_u8(ssh, 0)) != 0 ||
1058             (r = sshpkt_put_cstring(ssh, password)) != 0 ||
1059             (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1060             (r = sshpkt_send(ssh)) != 0)
1061                 fatal_fr(r, "send packet");
1062
1063         free(prompt);
1064         if (password != NULL)
1065                 freezero(password, strlen(password));
1066
1067         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1068             &input_userauth_passwd_changereq);
1069
1070         return 1;
1071 }
1072
1073 /*
1074  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
1075  */
1076 static int
1077 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
1078 {
1079         Authctxt *authctxt = ssh->authctxt;
1080         char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL;
1081         char prompt[256];
1082         const char *host;
1083         int r;
1084
1085         debug2("input_userauth_passwd_changereq");
1086
1087         if (authctxt == NULL)
1088                 fatal("input_userauth_passwd_changereq: "
1089                     "no authentication context");
1090         host = options.host_key_alias ? options.host_key_alias : authctxt->host;
1091
1092         if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 ||
1093             (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1094                 goto out;
1095         if (strlen(info) > 0)
1096                 logit("%s", info);
1097         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1098             (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1099             (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1100             (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1101             (r = sshpkt_put_u8(ssh, 1)) != 0)   /* additional info */
1102                 goto out;
1103
1104         snprintf(prompt, sizeof(prompt),
1105             "Enter %.30s@%.128s's old password: ",
1106             authctxt->server_user, host);
1107         password = read_passphrase(prompt, 0);
1108         if ((r = sshpkt_put_cstring(ssh, password)) != 0)
1109                 goto out;
1110
1111         freezero(password, strlen(password));
1112         password = NULL;
1113         while (password == NULL) {
1114                 snprintf(prompt, sizeof(prompt),
1115                     "Enter %.30s@%.128s's new password: ",
1116                     authctxt->server_user, host);
1117                 password = read_passphrase(prompt, RP_ALLOW_EOF);
1118                 if (password == NULL) {
1119                         /* bail out */
1120                         r = 0;
1121                         goto out;
1122                 }
1123                 snprintf(prompt, sizeof(prompt),
1124                     "Retype %.30s@%.128s's new password: ",
1125                     authctxt->server_user, host);
1126                 retype = read_passphrase(prompt, 0);
1127                 if (strcmp(password, retype) != 0) {
1128                         freezero(password, strlen(password));
1129                         logit("Mismatch; try again, EOF to quit.");
1130                         password = NULL;
1131                 }
1132                 freezero(retype, strlen(retype));
1133         }
1134         if ((r = sshpkt_put_cstring(ssh, password)) != 0 ||
1135             (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1136             (r = sshpkt_send(ssh)) != 0)
1137                 goto out;
1138
1139         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1140             &input_userauth_passwd_changereq);
1141         r = 0;
1142  out:
1143         if (password)
1144                 freezero(password, strlen(password));
1145         free(info);
1146         free(lang);
1147         return r;
1148 }
1149
1150 /*
1151  * Select an algorithm for publickey signatures.
1152  * Returns algorithm (caller must free) or NULL if no mutual algorithm found.
1153  *
1154  * Call with ssh==NULL to ignore server-sig-algs extension list and
1155  * only attempt with the key's base signature type.
1156  */
1157 static char *
1158 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key)
1159 {
1160         char *allowed, *oallowed, *cp, *tmp, *alg = NULL;
1161         const char *server_sig_algs;
1162
1163         /*
1164          * The signature algorithm will only differ from the key algorithm
1165          * for RSA keys/certs and when the server advertises support for
1166          * newer (SHA2) algorithms.
1167          */
1168         if (ssh == NULL || ssh->kex->server_sig_algs == NULL ||
1169             (key->type != KEY_RSA && key->type != KEY_RSA_CERT) ||
1170             (key->type == KEY_RSA_CERT && (ssh->compat & SSH_BUG_SIGTYPE))) {
1171                 /* Filter base key signature alg against our configuration */
1172                 return match_list(sshkey_ssh_name(key),
1173                     options.pubkey_accepted_algos, NULL);
1174         }
1175
1176         /*
1177          * Workaround OpenSSH 7.4 bug: this version supports RSA/SHA-2 but
1178          * fails to advertise it via SSH2_MSG_EXT_INFO.
1179          */
1180         server_sig_algs = ssh->kex->server_sig_algs;
1181         if (key->type == KEY_RSA && (ssh->compat & SSH_BUG_SIGTYPE74))
1182                 server_sig_algs = "rsa-sha2-256,rsa-sha2-512";
1183
1184         /*
1185          * For RSA keys/certs, since these might have a different sig type:
1186          * find the first entry in PubkeyAcceptedAlgorithms of the right type
1187          * that also appears in the supported signature algorithms list from
1188          * the server.
1189          */
1190         oallowed = allowed = xstrdup(options.pubkey_accepted_algos);
1191         while ((cp = strsep(&allowed, ",")) != NULL) {
1192                 if (sshkey_type_from_name(cp) != key->type)
1193                         continue;
1194                 tmp = match_list(sshkey_sigalg_by_name(cp),
1195                     server_sig_algs, NULL);
1196                 if (tmp != NULL)
1197                         alg = xstrdup(cp);
1198                 free(tmp);
1199                 if (alg != NULL)
1200                         break;
1201         }
1202         free(oallowed);
1203         return alg;
1204 }
1205
1206 static int
1207 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1208     const u_char *data, size_t datalen, u_int compat, const char *alg)
1209 {
1210         struct sshkey *sign_key = NULL, *prv = NULL;
1211         int is_agent = 0, retried = 0, r = SSH_ERR_INTERNAL_ERROR;
1212         struct notifier_ctx *notifier = NULL;
1213         char *fp = NULL, *pin = NULL, *prompt = NULL;
1214
1215         *sigp = NULL;
1216         *lenp = 0;
1217
1218         /* The agent supports this key. */
1219         if (id->key != NULL && id->agent_fd != -1) {
1220                 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1221                     data, datalen, alg, compat);
1222         }
1223
1224         /*
1225          * We have already loaded the private key or the private key is
1226          * stored in external hardware.
1227          */
1228         if (id->key != NULL &&
1229             (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) {
1230                 sign_key = id->key;
1231                 is_agent = 1;
1232         } else {
1233                 /* Load the private key from the file. */
1234                 if ((prv = load_identity_file(id)) == NULL)
1235                         return SSH_ERR_KEY_NOT_FOUND;
1236                 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1237                         error_f("private key %s contents do not match public",
1238                             id->filename);
1239                         r = SSH_ERR_KEY_NOT_FOUND;
1240                         goto out;
1241                 }
1242                 sign_key = prv;
1243         }
1244  retry_pin:
1245         /* Prompt for touch for non-agent FIDO keys that request UP */
1246         if (!is_agent && sshkey_is_sk(sign_key) &&
1247             (sign_key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1248                 /* XXX should batch mode just skip these? */
1249                 if ((fp = sshkey_fingerprint(sign_key,
1250                     options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1251                         fatal_f("fingerprint failed");
1252                 notifier = notify_start(options.batch_mode,
1253                     "Confirm user presence for key %s %s",
1254                     sshkey_type(sign_key), fp);
1255                 free(fp);
1256         }
1257         if ((r = sshkey_sign(sign_key, sigp, lenp, data, datalen,
1258             alg, options.sk_provider, pin, compat)) != 0) {
1259                 debug_fr(r, "sshkey_sign");
1260                 if (!retried && pin == NULL && !is_agent &&
1261                     sshkey_is_sk(sign_key) &&
1262                     r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1263                         notify_complete(notifier, NULL);
1264                         notifier = NULL;
1265                         xasprintf(&prompt, "Enter PIN for %s key %s: ",
1266                             sshkey_type(sign_key), id->filename);
1267                         pin = read_passphrase(prompt, 0);
1268                         retried = 1;
1269                         goto retry_pin;
1270                 }
1271                 goto out;
1272         }
1273
1274         /*
1275          * PKCS#11 tokens may not support all signature algorithms,
1276          * so check what we get back.
1277          */
1278         if ((r = sshkey_check_sigtype(*sigp, *lenp, alg)) != 0) {
1279                 debug_fr(r, "sshkey_check_sigtype");
1280                 goto out;
1281         }
1282         /* success */
1283         r = 0;
1284  out:
1285         free(prompt);
1286         if (pin != NULL)
1287                 freezero(pin, strlen(pin));
1288         notify_complete(notifier, r == 0 ? "User presence confirmed" : NULL);
1289         sshkey_free(prv);
1290         return r;
1291 }
1292
1293 static int
1294 id_filename_matches(Identity *id, Identity *private_id)
1295 {
1296         static const char * const suffixes[] = { ".pub", "-cert.pub", NULL };
1297         size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1298         size_t i, slen;
1299
1300         if (strcmp(id->filename, private_id->filename) == 0)
1301                 return 1;
1302         for (i = 0; suffixes[i]; i++) {
1303                 slen = strlen(suffixes[i]);
1304                 if (len > slen && plen == len - slen &&
1305                     strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1306                     memcmp(id->filename, private_id->filename, plen) == 0)
1307                         return 1;
1308         }
1309         return 0;
1310 }
1311
1312 static int
1313 sign_and_send_pubkey(struct ssh *ssh, Identity *id)
1314 {
1315         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1316         struct sshbuf *b = NULL;
1317         Identity *private_id, *sign_id = NULL;
1318         u_char *signature = NULL;
1319         size_t slen = 0, skip = 0;
1320         int r, fallback_sigtype, sent = 0;
1321         char *alg = NULL, *fp = NULL;
1322         const char *loc = "", *method = "publickey";
1323         int hostbound = 0;
1324
1325         /* prefer host-bound pubkey signatures if supported by server */
1326         if ((ssh->kex->flags & KEX_HAS_PUBKEY_HOSTBOUND) != 0 &&
1327             (options.pubkey_authentication & SSH_PUBKEY_AUTH_HBOUND) != 0) {
1328                 hostbound = 1;
1329                 method = "publickey-hostbound-v00@openssh.com";
1330         }
1331
1332         if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1333             SSH_FP_DEFAULT)) == NULL)
1334                 return 0;
1335
1336         debug3_f("using %s with %s %s", method, sshkey_type(id->key), fp);
1337
1338         /*
1339          * If the key is an certificate, try to find a matching private key
1340          * and use it to complete the signature.
1341          * If no such private key exists, fall back to trying the certificate
1342          * key itself in case it has a private half already loaded.
1343          * This will try to set sign_id to the private key that will perform
1344          * the signature.
1345          */
1346         if (sshkey_is_cert(id->key)) {
1347                 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1348                         if (sshkey_equal_public(id->key, private_id->key) &&
1349                             id->key->type != private_id->key->type) {
1350                                 sign_id = private_id;
1351                                 break;
1352                         }
1353                 }
1354                 /*
1355                  * Exact key matches are preferred, but also allow
1356                  * filename matches for non-PKCS#11/agent keys that
1357                  * didn't load public keys. This supports the case
1358                  * of keeping just a private key file and public
1359                  * certificate on disk.
1360                  */
1361                 if (sign_id == NULL &&
1362                     !id->isprivate && id->agent_fd == -1 &&
1363                     (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1364                         TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1365                                 if (private_id->key == NULL &&
1366                                     id_filename_matches(id, private_id)) {
1367                                         sign_id = private_id;
1368                                         break;
1369                                 }
1370                         }
1371                 }
1372                 if (sign_id != NULL) {
1373                         debug2_f("using private key \"%s\"%s for "
1374                             "certificate", sign_id->filename,
1375                             sign_id->agent_fd != -1 ? " from agent" : "");
1376                 } else {
1377                         debug_f("no separate private key for certificate "
1378                             "\"%s\"", id->filename);
1379                 }
1380         }
1381
1382         /*
1383          * If the above didn't select another identity to do the signing
1384          * then default to the one we started with.
1385          */
1386         if (sign_id == NULL)
1387                 sign_id = id;
1388
1389         /* assemble and sign data */
1390         for (fallback_sigtype = 0; fallback_sigtype <= 1; fallback_sigtype++) {
1391                 free(alg);
1392                 slen = 0;
1393                 signature = NULL;
1394                 if ((alg = key_sig_algorithm(fallback_sigtype ? NULL : ssh,
1395                     id->key)) == NULL) {
1396                         error_f("no mutual signature supported");
1397                         goto out;
1398                 }
1399                 debug3_f("signing using %s %s", alg, fp);
1400
1401                 sshbuf_free(b);
1402                 if ((b = sshbuf_new()) == NULL)
1403                         fatal_f("sshbuf_new failed");
1404                 if (ssh->compat & SSH_OLD_SESSIONID) {
1405                         if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
1406                                 fatal_fr(r, "sshbuf_putb");
1407                 } else {
1408                         if ((r = sshbuf_put_stringb(b,
1409                             ssh->kex->session_id)) != 0)
1410                                 fatal_fr(r, "sshbuf_put_stringb");
1411                 }
1412                 skip = sshbuf_len(b);
1413                 if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1414                     (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1415                     (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1416                     (r = sshbuf_put_cstring(b, method)) != 0 ||
1417                     (r = sshbuf_put_u8(b, 1)) != 0 ||
1418                     (r = sshbuf_put_cstring(b, alg)) != 0 ||
1419                     (r = sshkey_puts(id->key, b)) != 0) {
1420                         fatal_fr(r, "assemble signed data");
1421                 }
1422                 if (hostbound) {
1423                         if (ssh->kex->initial_hostkey == NULL) {
1424                                 fatal_f("internal error: initial hostkey "
1425                                     "not recorded");
1426                         }
1427                         if ((r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0)
1428                                 fatal_fr(r, "assemble %s hostkey", method);
1429                 }
1430                 /* generate signature */
1431                 r = identity_sign(sign_id, &signature, &slen,
1432                     sshbuf_ptr(b), sshbuf_len(b), ssh->compat, alg);
1433                 if (r == 0)
1434                         break;
1435                 else if (r == SSH_ERR_KEY_NOT_FOUND)
1436                         goto out; /* soft failure */
1437                 else if (r == SSH_ERR_SIGN_ALG_UNSUPPORTED &&
1438                     !fallback_sigtype) {
1439                         if (sign_id->agent_fd != -1)
1440                                 loc = "agent ";
1441                         else if ((sign_id->key->flags & SSHKEY_FLAG_EXT) != 0)
1442                                 loc = "token ";
1443                         logit("%skey %s %s returned incorrect signature type",
1444                             loc, sshkey_type(id->key), fp);
1445                         continue;
1446                 }
1447                 error_fr(r, "signing failed for %s \"%s\"%s",
1448                     sshkey_type(sign_id->key), sign_id->filename,
1449                     id->agent_fd != -1 ? " from agent" : "");
1450                 goto out;
1451         }
1452         if (slen == 0 || signature == NULL) /* shouldn't happen */
1453                 fatal_f("no signature");
1454
1455         /* append signature */
1456         if ((r = sshbuf_put_string(b, signature, slen)) != 0)
1457                 fatal_fr(r, "append signature");
1458
1459 #ifdef DEBUG_PK
1460         sshbuf_dump(b, stderr);
1461 #endif
1462         /* skip session id and packet type */
1463         if ((r = sshbuf_consume(b, skip + 1)) != 0)
1464                 fatal_fr(r, "consume");
1465
1466         /* put remaining data from buffer into packet */
1467         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1468             (r = sshpkt_putb(ssh, b)) != 0 ||
1469             (r = sshpkt_send(ssh)) != 0)
1470                 fatal_fr(r, "enqueue request");
1471
1472         /* success */
1473         sent = 1;
1474
1475  out:
1476         free(fp);
1477         free(alg);
1478         sshbuf_free(b);
1479         freezero(signature, slen);
1480         return sent;
1481 }
1482
1483 static int
1484 send_pubkey_test(struct ssh *ssh, Identity *id)
1485 {
1486         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1487         u_char *blob = NULL;
1488         char *alg = NULL;
1489         size_t bloblen;
1490         u_int have_sig = 0;
1491         int sent = 0, r;
1492
1493         if ((alg = key_sig_algorithm(ssh, id->key)) == NULL) {
1494                 debug_f("no mutual signature algorithm");
1495                 goto out;
1496         }
1497
1498         if ((r = sshkey_to_blob(id->key, &blob, &bloblen)) != 0) {
1499                 /* we cannot handle this key */
1500                 debug3_f("cannot handle key");
1501                 goto out;
1502         }
1503         /* register callback for USERAUTH_PK_OK message */
1504         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1505
1506         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1507             (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1508             (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1509             (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1510             (r = sshpkt_put_u8(ssh, have_sig)) != 0 ||
1511             (r = sshpkt_put_cstring(ssh, alg)) != 0 ||
1512             (r = sshpkt_put_string(ssh, blob, bloblen)) != 0 ||
1513             (r = sshpkt_send(ssh)) != 0)
1514                 fatal_fr(r, "send packet");
1515         sent = 1;
1516
1517  out:
1518         free(alg);
1519         free(blob);
1520         return sent;
1521 }
1522
1523 static struct sshkey *
1524 load_identity_file(Identity *id)
1525 {
1526         struct sshkey *private = NULL;
1527         char prompt[300], *passphrase, *comment;
1528         int r, quit = 0, i;
1529         struct stat st;
1530
1531         if (stat(id->filename, &st) == -1) {
1532                 do_log2(id->userprovided ?
1533                     SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_DEBUG3,
1534                     "no such identity: %s: %s", id->filename, strerror(errno));
1535                 return NULL;
1536         }
1537         snprintf(prompt, sizeof prompt,
1538             "Enter passphrase for key '%.100s': ", id->filename);
1539         for (i = 0; i <= options.number_of_password_prompts; i++) {
1540                 if (i == 0)
1541                         passphrase = "";
1542                 else {
1543                         passphrase = read_passphrase(prompt, 0);
1544                         if (*passphrase == '\0') {
1545                                 debug2("no passphrase given, try next key");
1546                                 free(passphrase);
1547                                 break;
1548                         }
1549                 }
1550                 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1551                     passphrase, &private, &comment))) {
1552                 case 0:
1553                         break;
1554                 case SSH_ERR_KEY_WRONG_PASSPHRASE:
1555                         if (options.batch_mode) {
1556                                 quit = 1;
1557                                 break;
1558                         }
1559                         if (i != 0)
1560                                 debug2("bad passphrase given, try again...");
1561                         break;
1562                 case SSH_ERR_SYSTEM_ERROR:
1563                         if (errno == ENOENT) {
1564                                 debug2_r(r, "Load key \"%s\"", id->filename);
1565                                 quit = 1;
1566                                 break;
1567                         }
1568                         /* FALLTHROUGH */
1569                 default:
1570                         error_r(r, "Load key \"%s\"", id->filename);
1571                         quit = 1;
1572                         break;
1573                 }
1574                 if (private != NULL && sshkey_is_sk(private) &&
1575                     options.sk_provider == NULL) {
1576                         debug("key \"%s\" is an authenticator-hosted key, "
1577                             "but no provider specified", id->filename);
1578                         sshkey_free(private);
1579                         private = NULL;
1580                         quit = 1;
1581                 }
1582                 if (!quit && (r = sshkey_check_rsa_length(private,
1583                     options.required_rsa_size)) != 0) {
1584                         debug_fr(r, "Skipping key %s", id->filename);
1585                         sshkey_free(private);
1586                         private = NULL;
1587                         quit = 1;
1588                 }
1589                 if (!quit && private != NULL && id->agent_fd == -1 &&
1590                     !(id->key && id->isprivate))
1591                         maybe_add_key_to_agent(id->filename, private, comment,
1592                             passphrase);
1593                 if (i > 0)
1594                         freezero(passphrase, strlen(passphrase));
1595                 free(comment);
1596                 if (private != NULL || quit)
1597                         break;
1598         }
1599         return private;
1600 }
1601
1602 static int
1603 key_type_allowed_by_config(struct sshkey *key)
1604 {
1605         if (match_pattern_list(sshkey_ssh_name(key),
1606             options.pubkey_accepted_algos, 0) == 1)
1607                 return 1;
1608
1609         /* RSA keys/certs might be allowed by alternate signature types */
1610         switch (key->type) {
1611         case KEY_RSA:
1612                 if (match_pattern_list("rsa-sha2-512",
1613                     options.pubkey_accepted_algos, 0) == 1)
1614                         return 1;
1615                 if (match_pattern_list("rsa-sha2-256",
1616                     options.pubkey_accepted_algos, 0) == 1)
1617                         return 1;
1618                 break;
1619         case KEY_RSA_CERT:
1620                 if (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
1621                     options.pubkey_accepted_algos, 0) == 1)
1622                         return 1;
1623                 if (match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
1624                     options.pubkey_accepted_algos, 0) == 1)
1625                         return 1;
1626                 break;
1627         }
1628         return 0;
1629 }
1630
1631 /* obtain a list of keys from the agent */
1632 static int
1633 get_agent_identities(struct ssh *ssh, int *agent_fdp,
1634     struct ssh_identitylist **idlistp)
1635 {
1636         int r, agent_fd;
1637         struct ssh_identitylist *idlist;
1638
1639         if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1640                 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1641                         debug_fr(r, "ssh_get_authentication_socket");
1642                 return r;
1643         }
1644         if ((r = ssh_agent_bind_hostkey(agent_fd, ssh->kex->initial_hostkey,
1645             ssh->kex->session_id, ssh->kex->initial_sig, 0)) == 0)
1646                 debug_f("bound agent to hostkey");
1647         else
1648                 debug2_fr(r, "ssh_agent_bind_hostkey");
1649
1650         if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1651                 debug_fr(r, "ssh_fetch_identitylist");
1652                 close(agent_fd);
1653                 return r;
1654         }
1655         /* success */
1656         *agent_fdp = agent_fd;
1657         *idlistp = idlist;
1658         debug_f("agent returned %zu keys", idlist->nkeys);
1659         return 0;
1660 }
1661
1662 /*
1663  * try keys in the following order:
1664  *      1. certificates listed in the config file
1665  *      2. other input certificates
1666  *      3. agent keys that are found in the config file
1667  *      4. other agent keys
1668  *      5. keys that are only listed in the config file
1669  */
1670 static void
1671 pubkey_prepare(struct ssh *ssh, Authctxt *authctxt)
1672 {
1673         struct identity *id, *id2, *tmp;
1674         struct idlist agent, files, *preferred;
1675         struct sshkey *key;
1676         int agent_fd = -1, i, r, found;
1677         size_t j;
1678         struct ssh_identitylist *idlist;
1679         char *ident;
1680
1681         TAILQ_INIT(&agent);     /* keys from the agent */
1682         TAILQ_INIT(&files);     /* keys from the config file */
1683         preferred = &authctxt->keys;
1684         TAILQ_INIT(preferred);  /* preferred order of keys */
1685
1686         /* list of keys stored in the filesystem and PKCS#11 */
1687         for (i = 0; i < options.num_identity_files; i++) {
1688                 key = options.identity_keys[i];
1689                 if (key && key->cert &&
1690                     key->cert->type != SSH2_CERT_TYPE_USER) {
1691                         debug_f("ignoring certificate %s: not a user "
1692                             "certificate", options.identity_files[i]);
1693                         continue;
1694                 }
1695                 if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1696                         debug_f("ignoring authenticator-hosted key %s as no "
1697                             "SecurityKeyProvider has been specified",
1698                             options.identity_files[i]);
1699                         continue;
1700                 }
1701                 options.identity_keys[i] = NULL;
1702                 id = xcalloc(1, sizeof(*id));
1703                 id->agent_fd = -1;
1704                 id->key = key;
1705                 id->filename = xstrdup(options.identity_files[i]);
1706                 id->userprovided = options.identity_file_userprovided[i];
1707                 TAILQ_INSERT_TAIL(&files, id, next);
1708         }
1709         /* list of certificates specified by user */
1710         for (i = 0; i < options.num_certificate_files; i++) {
1711                 key = options.certificates[i];
1712                 if (!sshkey_is_cert(key) || key->cert == NULL ||
1713                     key->cert->type != SSH2_CERT_TYPE_USER) {
1714                         debug_f("ignoring certificate %s: not a user "
1715                             "certificate", options.identity_files[i]);
1716                         continue;
1717                 }
1718                 if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1719                         debug_f("ignoring authenticator-hosted key "
1720                             "certificate %s as no "
1721                             "SecurityKeyProvider has been specified",
1722                             options.identity_files[i]);
1723                         continue;
1724                 }
1725                 id = xcalloc(1, sizeof(*id));
1726                 id->agent_fd = -1;
1727                 id->key = key;
1728                 id->filename = xstrdup(options.certificate_files[i]);
1729                 id->userprovided = options.certificate_file_userprovided[i];
1730                 TAILQ_INSERT_TAIL(preferred, id, next);
1731         }
1732         /* list of keys supported by the agent */
1733         if ((r = get_agent_identities(ssh, &agent_fd, &idlist)) == 0) {
1734                 for (j = 0; j < idlist->nkeys; j++) {
1735                         if ((r = sshkey_check_rsa_length(idlist->keys[j],
1736                             options.required_rsa_size)) != 0) {
1737                                 debug_fr(r, "ignoring %s agent key",
1738                                     sshkey_ssh_name(idlist->keys[j]));
1739                                 continue;
1740                         }
1741                         found = 0;
1742                         TAILQ_FOREACH(id, &files, next) {
1743                                 /*
1744                                  * agent keys from the config file are
1745                                  * preferred
1746                                  */
1747                                 if (sshkey_equal(idlist->keys[j], id->key)) {
1748                                         TAILQ_REMOVE(&files, id, next);
1749                                         TAILQ_INSERT_TAIL(preferred, id, next);
1750                                         id->agent_fd = agent_fd;
1751                                         found = 1;
1752                                         break;
1753                                 }
1754                         }
1755                         if (!found && !options.identities_only) {
1756                                 id = xcalloc(1, sizeof(*id));
1757                                 /* XXX "steals" key/comment from idlist */
1758                                 id->key = idlist->keys[j];
1759                                 id->filename = idlist->comments[j];
1760                                 idlist->keys[j] = NULL;
1761                                 idlist->comments[j] = NULL;
1762                                 id->agent_fd = agent_fd;
1763                                 TAILQ_INSERT_TAIL(&agent, id, next);
1764                         }
1765                 }
1766                 ssh_free_identitylist(idlist);
1767                 /* append remaining agent keys */
1768                 TAILQ_CONCAT(preferred, &agent, next);
1769                 authctxt->agent_fd = agent_fd;
1770         }
1771         /* Prefer PKCS11 keys that are explicitly listed */
1772         TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1773                 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1774                         continue;
1775                 found = 0;
1776                 TAILQ_FOREACH(id2, &files, next) {
1777                         if (id2->key == NULL ||
1778                             (id2->key->flags & SSHKEY_FLAG_EXT) != 0)
1779                                 continue;
1780                         if (sshkey_equal(id->key, id2->key)) {
1781                                 TAILQ_REMOVE(&files, id, next);
1782                                 TAILQ_INSERT_TAIL(preferred, id, next);
1783                                 found = 1;
1784                                 break;
1785                         }
1786                 }
1787                 /* If IdentitiesOnly set and key not found then don't use it */
1788                 if (!found && options.identities_only) {
1789                         TAILQ_REMOVE(&files, id, next);
1790                         freezero(id, sizeof(*id));
1791                 }
1792         }
1793         /* append remaining keys from the config file */
1794         TAILQ_CONCAT(preferred, &files, next);
1795         /* finally, filter by PubkeyAcceptedAlgorithms */
1796         TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1797                 if (id->key != NULL && !key_type_allowed_by_config(id->key)) {
1798                         debug("Skipping %s key %s - "
1799                             "corresponding algo not in PubkeyAcceptedAlgorithms",
1800                             sshkey_ssh_name(id->key), id->filename);
1801                         TAILQ_REMOVE(preferred, id, next);
1802                         sshkey_free(id->key);
1803                         free(id->filename);
1804                         memset(id, 0, sizeof(*id));
1805                         continue;
1806                 }
1807         }
1808         /* List the keys we plan on using */
1809         TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1810                 ident = format_identity(id);
1811                 debug("Will attempt key: %s", ident);
1812                 free(ident);
1813         }
1814         debug2_f("done");
1815 }
1816
1817 static void
1818 pubkey_cleanup(struct ssh *ssh)
1819 {
1820         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1821         Identity *id;
1822
1823         if (authctxt->agent_fd != -1) {
1824                 ssh_close_authentication_socket(authctxt->agent_fd);
1825                 authctxt->agent_fd = -1;
1826         }
1827         for (id = TAILQ_FIRST(&authctxt->keys); id;
1828             id = TAILQ_FIRST(&authctxt->keys)) {
1829                 TAILQ_REMOVE(&authctxt->keys, id, next);
1830                 sshkey_free(id->key);
1831                 free(id->filename);
1832                 free(id);
1833         }
1834 }
1835
1836 static void
1837 pubkey_reset(Authctxt *authctxt)
1838 {
1839         Identity *id;
1840
1841         TAILQ_FOREACH(id, &authctxt->keys, next)
1842                 id->tried = 0;
1843 }
1844
1845 static int
1846 userauth_pubkey(struct ssh *ssh)
1847 {
1848         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1849         Identity *id;
1850         int sent = 0;
1851         char *ident;
1852
1853         while ((id = TAILQ_FIRST(&authctxt->keys))) {
1854                 if (id->tried++)
1855                         return (0);
1856                 /* move key to the end of the queue */
1857                 TAILQ_REMOVE(&authctxt->keys, id, next);
1858                 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1859                 /*
1860                  * send a test message if we have the public key. for
1861                  * encrypted keys we cannot do this and have to load the
1862                  * private key instead
1863                  */
1864                 if (id->key != NULL) {
1865                         ident = format_identity(id);
1866                         debug("Offering public key: %s", ident);
1867                         free(ident);
1868                         sent = send_pubkey_test(ssh, id);
1869                 } else {
1870                         debug("Trying private key: %s", id->filename);
1871                         id->key = load_identity_file(id);
1872                         if (id->key != NULL) {
1873                                 if (id->key != NULL) {
1874                                         id->isprivate = 1;
1875                                         sent = sign_and_send_pubkey(ssh, id);
1876                                 }
1877                                 sshkey_free(id->key);
1878                                 id->key = NULL;
1879                                 id->isprivate = 0;
1880                         }
1881                 }
1882                 if (sent)
1883                         return (sent);
1884         }
1885         return (0);
1886 }
1887
1888 /*
1889  * Send userauth request message specifying keyboard-interactive method.
1890  */
1891 static int
1892 userauth_kbdint(struct ssh *ssh)
1893 {
1894         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1895         int r;
1896
1897         if (authctxt->attempt_kbdint++ >= options.number_of_password_prompts)
1898                 return 0;
1899         /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1900         if (authctxt->attempt_kbdint > 1 && !authctxt->info_req_seen) {
1901                 debug3("userauth_kbdint: disable: no info_req_seen");
1902                 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1903                 return 0;
1904         }
1905
1906         debug2("userauth_kbdint");
1907         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1908             (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1909             (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1910             (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1911             (r = sshpkt_put_cstring(ssh, "")) != 0 ||           /* lang */
1912             (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ?
1913             options.kbd_interactive_devices : "")) != 0 ||
1914             (r = sshpkt_send(ssh)) != 0)
1915                 fatal_fr(r, "send packet");
1916
1917         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1918         return 1;
1919 }
1920
1921 /*
1922  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1923  */
1924 static int
1925 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1926 {
1927         Authctxt *authctxt = ssh->authctxt;
1928         char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL;
1929         char *display_prompt = NULL, *response = NULL;
1930         u_char echo = 0;
1931         u_int num_prompts, i;
1932         int r;
1933
1934         debug2_f("entering");
1935
1936         if (authctxt == NULL)
1937                 fatal_f("no authentication context");
1938
1939         authctxt->info_req_seen = 1;
1940
1941         if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1942             (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 ||
1943             (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1944                 goto out;
1945         if (strlen(name) > 0)
1946                 logit("%s", name);
1947         if (strlen(inst) > 0)
1948                 logit("%s", inst);
1949
1950         if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0)
1951                 goto out;
1952         /*
1953          * Begin to build info response packet based on prompts requested.
1954          * We commit to providing the correct number of responses, so if
1955          * further on we run into a problem that prevents this, we have to
1956          * be sure and clean this up and send a correct error response.
1957          */
1958         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 ||
1959             (r = sshpkt_put_u32(ssh, num_prompts)) != 0)
1960                 goto out;
1961
1962         debug2_f("num_prompts %d", num_prompts);
1963         for (i = 0; i < num_prompts; i++) {
1964                 if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 ||
1965                     (r = sshpkt_get_u8(ssh, &echo)) != 0)
1966                         goto out;
1967                 if (asmprintf(&display_prompt, INT_MAX, NULL, "(%s@%s) %s",
1968                     authctxt->server_user, options.host_key_alias ?
1969                     options.host_key_alias : authctxt->host, prompt) == -1)
1970                         fatal_f("asmprintf failed");
1971                 response = read_passphrase(display_prompt, echo ? RP_ECHO : 0);
1972                 if ((r = sshpkt_put_cstring(ssh, response)) != 0)
1973                         goto out;
1974                 freezero(response, strlen(response));
1975                 free(prompt);
1976                 free(display_prompt);
1977                 display_prompt = response = prompt = NULL;
1978         }
1979         /* done with parsing incoming message. */
1980         if ((r = sshpkt_get_end(ssh)) != 0 ||
1981             (r = sshpkt_add_padding(ssh, 64)) != 0)
1982                 goto out;
1983         r = sshpkt_send(ssh);
1984  out:
1985         if (response)
1986                 freezero(response, strlen(response));
1987         free(prompt);
1988         free(display_prompt);
1989         free(name);
1990         free(inst);
1991         free(lang);
1992         return r;
1993 }
1994
1995 static int
1996 ssh_keysign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
1997     const u_char *data, size_t datalen)
1998 {
1999         struct sshbuf *b;
2000         struct stat st;
2001         pid_t pid;
2002         int r, to[2], from[2], status;
2003         int sock = ssh_packet_get_connection_in(ssh);
2004         u_char rversion = 0, version = 2;
2005         void (*osigchld)(int);
2006
2007         *sigp = NULL;
2008         *lenp = 0;
2009
2010         if (stat(_PATH_SSH_KEY_SIGN, &st) == -1) {
2011                 error_f("not installed: %s", strerror(errno));
2012                 return -1;
2013         }
2014         if (fflush(stdout) != 0) {
2015                 error_f("fflush: %s", strerror(errno));
2016                 return -1;
2017         }
2018         if (pipe(to) == -1) {
2019                 error_f("pipe: %s", strerror(errno));
2020                 return -1;
2021         }
2022         if (pipe(from) == -1) {
2023                 error_f("pipe: %s", strerror(errno));
2024                 return -1;
2025         }
2026         if ((pid = fork()) == -1) {
2027                 error_f("fork: %s", strerror(errno));
2028                 return -1;
2029         }
2030         osigchld = ssh_signal(SIGCHLD, SIG_DFL);
2031         if (pid == 0) {
2032                 close(from[0]);
2033                 if (dup2(from[1], STDOUT_FILENO) == -1)
2034                         fatal_f("dup2: %s", strerror(errno));
2035                 close(to[1]);
2036                 if (dup2(to[0], STDIN_FILENO) == -1)
2037                         fatal_f("dup2: %s", strerror(errno));
2038                 close(from[1]);
2039                 close(to[0]);
2040
2041                 if (dup2(sock, STDERR_FILENO + 1) == -1)
2042                         fatal_f("dup2: %s", strerror(errno));
2043                 sock = STDERR_FILENO + 1;
2044                 if (fcntl(sock, F_SETFD, 0) == -1) /* keep the socket on exec */
2045                         debug3_f("fcntl F_SETFD: %s", strerror(errno));
2046                 closefrom(sock + 1);
2047
2048                 debug3_f("[child] pid=%ld, exec %s",
2049                     (long)getpid(), _PATH_SSH_KEY_SIGN);
2050                 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
2051                 fatal_f("exec(%s): %s", _PATH_SSH_KEY_SIGN,
2052                     strerror(errno));
2053         }
2054         close(from[1]);
2055         close(to[0]);
2056         sock = STDERR_FILENO + 1;
2057
2058         if ((b = sshbuf_new()) == NULL)
2059                 fatal_f("sshbuf_new failed");
2060         /* send # of sock, data to be signed */
2061         if ((r = sshbuf_put_u32(b, sock)) != 0 ||
2062             (r = sshbuf_put_string(b, data, datalen)) != 0)
2063                 fatal_fr(r, "buffer error");
2064         if (ssh_msg_send(to[1], version, b) == -1)
2065                 fatal_f("couldn't send request");
2066         sshbuf_reset(b);
2067         r = ssh_msg_recv(from[0], b);
2068         close(from[0]);
2069         close(to[1]);
2070         if (r < 0) {
2071                 error_f("no reply");
2072                 goto fail;
2073         }
2074
2075         errno = 0;
2076         while (waitpid(pid, &status, 0) == -1) {
2077                 if (errno != EINTR) {
2078                         error_f("waitpid %ld: %s", (long)pid, strerror(errno));
2079                         goto fail;
2080                 }
2081         }
2082         if (!WIFEXITED(status)) {
2083                 error_f("exited abnormally");
2084                 goto fail;
2085         }
2086         if (WEXITSTATUS(status) != 0) {
2087                 error_f("exited with status %d", WEXITSTATUS(status));
2088                 goto fail;
2089         }
2090         if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
2091                 error_fr(r, "buffer error");
2092                 goto fail;
2093         }
2094         if (rversion != version) {
2095                 error_f("bad version");
2096                 goto fail;
2097         }
2098         if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
2099                 error_fr(r, "buffer error");
2100  fail:
2101                 ssh_signal(SIGCHLD, osigchld);
2102                 sshbuf_free(b);
2103                 return -1;
2104         }
2105         ssh_signal(SIGCHLD, osigchld);
2106         sshbuf_free(b);
2107
2108         return 0;
2109 }
2110
2111 static int
2112 userauth_hostbased(struct ssh *ssh)
2113 {
2114         Authctxt *authctxt = (Authctxt *)ssh->authctxt;
2115         struct sshkey *private = NULL;
2116         struct sshbuf *b = NULL;
2117         u_char *sig = NULL, *keyblob = NULL;
2118         char *fp = NULL, *chost = NULL, *lname = NULL;
2119         size_t siglen = 0, keylen = 0;
2120         int i, r, success = 0;
2121
2122         if (authctxt->ktypes == NULL) {
2123                 authctxt->oktypes = xstrdup(options.hostbased_accepted_algos);
2124                 authctxt->ktypes = authctxt->oktypes;
2125         }
2126
2127         /*
2128          * Work through each listed type pattern in HostbasedAcceptedAlgorithms,
2129          * trying each hostkey that matches the type in turn.
2130          */
2131         for (;;) {
2132                 if (authctxt->active_ktype == NULL)
2133                         authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
2134                 if (authctxt->active_ktype == NULL ||
2135                     *authctxt->active_ktype == '\0')
2136                         break;
2137                 debug3_f("trying key type %s", authctxt->active_ktype);
2138
2139                 /* check for a useful key */
2140                 private = NULL;
2141                 for (i = 0; i < authctxt->sensitive->nkeys; i++) {
2142                         if (authctxt->sensitive->keys[i] == NULL ||
2143                             authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
2144                                 continue;
2145                         if (!sshkey_match_keyname_to_sigalgs(
2146                             sshkey_ssh_name(authctxt->sensitive->keys[i]),
2147                             authctxt->active_ktype))
2148                                 continue;
2149                         /* we take and free the key */
2150                         private = authctxt->sensitive->keys[i];
2151                         authctxt->sensitive->keys[i] = NULL;
2152                         break;
2153                 }
2154                 /* Found one */
2155                 if (private != NULL)
2156                         break;
2157                 /* No more keys of this type; advance */
2158                 authctxt->active_ktype = NULL;
2159         }
2160         if (private == NULL) {
2161                 free(authctxt->oktypes);
2162                 authctxt->oktypes = authctxt->ktypes = NULL;
2163                 authctxt->active_ktype = NULL;
2164                 debug("No more client hostkeys for hostbased authentication.");
2165                 goto out;
2166         }
2167
2168         if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
2169             SSH_FP_DEFAULT)) == NULL) {
2170                 error_f("sshkey_fingerprint failed");
2171                 goto out;
2172         }
2173         debug_f("trying hostkey %s %s using sigalg %s",
2174             sshkey_ssh_name(private), fp, authctxt->active_ktype);
2175
2176         /* figure out a name for the client host */
2177         lname = get_local_name(ssh_packet_get_connection_in(ssh));
2178         if (lname == NULL) {
2179                 error_f("cannot get local ipaddr/name");
2180                 goto out;
2181         }
2182
2183         /* XXX sshbuf_put_stringf? */
2184         xasprintf(&chost, "%s.", lname);
2185         debug2_f("chost %s", chost);
2186
2187         /* construct data */
2188         if ((b = sshbuf_new()) == NULL) {
2189                 error_f("sshbuf_new failed");
2190                 goto out;
2191         }
2192         if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
2193                 error_fr(r, "sshkey_to_blob");
2194                 goto out;
2195         }
2196         if ((r = sshbuf_put_stringb(b, ssh->kex->session_id)) != 0 ||
2197             (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2198             (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
2199             (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
2200             (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
2201             (r = sshbuf_put_cstring(b, authctxt->active_ktype)) != 0 ||
2202             (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
2203             (r = sshbuf_put_cstring(b, chost)) != 0 ||
2204             (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
2205                 error_fr(r, "buffer error");
2206                 goto out;
2207         }
2208
2209 #ifdef DEBUG_PK
2210         sshbuf_dump(b, stderr);
2211 #endif
2212         if ((r = ssh_keysign(ssh, private, &sig, &siglen,
2213             sshbuf_ptr(b), sshbuf_len(b))) != 0) {
2214                 error("sign using hostkey %s %s failed",
2215                     sshkey_ssh_name(private), fp);
2216                 goto out;
2217         }
2218         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2219             (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
2220             (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
2221             (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
2222             (r = sshpkt_put_cstring(ssh, authctxt->active_ktype)) != 0 ||
2223             (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
2224             (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
2225             (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
2226             (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
2227             (r = sshpkt_send(ssh)) != 0) {
2228                 error_fr(r, "packet error");
2229                 goto out;
2230         }
2231         success = 1;
2232
2233  out:
2234         if (sig != NULL)
2235                 freezero(sig, siglen);
2236         free(keyblob);
2237         free(lname);
2238         free(fp);
2239         free(chost);
2240         sshkey_free(private);
2241         sshbuf_free(b);
2242
2243         return success;
2244 }
2245
2246 /* find auth method */
2247
2248 /*
2249  * given auth method name, if configurable options permit this method fill
2250  * in auth_ident field and return true, otherwise return false.
2251  */
2252 static int
2253 authmethod_is_enabled(Authmethod *method)
2254 {
2255         if (method == NULL)
2256                 return 0;
2257         /* return false if options indicate this method is disabled */
2258         if  (method->enabled == NULL || *method->enabled == 0)
2259                 return 0;
2260         /* return false if batch mode is enabled but method needs interactive mode */
2261         if  (method->batch_flag != NULL && *method->batch_flag != 0)
2262                 return 0;
2263         return 1;
2264 }
2265
2266 static Authmethod *
2267 authmethod_lookup(const char *name)
2268 {
2269         Authmethod *method = NULL;
2270         if (name != NULL)
2271                 for (method = authmethods; method->name != NULL; method++)
2272                         if (strcmp(name, method->name) == 0)
2273                                 return method;
2274         debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
2275         return NULL;
2276 }
2277
2278 /* XXX internal state */
2279 static Authmethod *current = NULL;
2280 static char *supported = NULL;
2281 static char *preferred = NULL;
2282
2283 /*
2284  * Given the authentication method list sent by the server, return the
2285  * next method we should try.  If the server initially sends a nil list,
2286  * use a built-in default list.
2287  */
2288 static Authmethod *
2289 authmethod_get(char *authlist)
2290 {
2291         char *name = NULL;
2292         u_int next;
2293
2294         /* Use a suitable default if we're passed a nil list.  */
2295         if (authlist == NULL || strlen(authlist) == 0)
2296                 authlist = options.preferred_authentications;
2297
2298         if (supported == NULL || strcmp(authlist, supported) != 0) {
2299                 debug3("start over, passed a different list %s", authlist);
2300                 free(supported);
2301                 supported = xstrdup(authlist);
2302                 preferred = options.preferred_authentications;
2303                 debug3("preferred %s", preferred);
2304                 current = NULL;
2305         } else if (current != NULL && authmethod_is_enabled(current))
2306                 return current;
2307
2308         for (;;) {
2309                 if ((name = match_list(preferred, supported, &next)) == NULL) {
2310                         debug("No more authentication methods to try.");
2311                         current = NULL;
2312                         return NULL;
2313                 }
2314                 preferred += next;
2315                 debug3("authmethod_lookup %s", name);
2316                 debug3("remaining preferred: %s", preferred);
2317                 if ((current = authmethod_lookup(name)) != NULL &&
2318                     authmethod_is_enabled(current)) {
2319                         debug3("authmethod_is_enabled %s", name);
2320                         debug("Next authentication method: %s", name);
2321                         free(name);
2322                         return current;
2323                 }
2324                 free(name);
2325         }
2326 }
2327
2328 static char *
2329 authmethods_get(void)
2330 {
2331         Authmethod *method = NULL;
2332         struct sshbuf *b;
2333         char *list;
2334         int r;
2335
2336         if ((b = sshbuf_new()) == NULL)
2337                 fatal_f("sshbuf_new failed");
2338         for (method = authmethods; method->name != NULL; method++) {
2339                 if (authmethod_is_enabled(method)) {
2340                         if ((r = sshbuf_putf(b, "%s%s",
2341                             sshbuf_len(b) ? "," : "", method->name)) != 0)
2342                                 fatal_fr(r, "buffer error");
2343                 }
2344         }
2345         if ((list = sshbuf_dup_string(b)) == NULL)
2346                 fatal_f("sshbuf_dup_string failed");
2347         sshbuf_free(b);
2348         return list;
2349 }