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