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