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