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