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