1 /* $OpenBSD: sshconnect2.c,v 1.321 2020/04/17 03:38:47 djm Exp $ */
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2008 Damien Miller. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
29 #include <sys/types.h>
30 #include <sys/socket.h>
43 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
47 #include "openbsd-compat/sys-queue.h"
58 #include "myproposal.h"
59 #include "sshconnect.h"
70 #include "pathnames.h"
83 extern char *client_version_string;
84 extern char *server_version_string;
85 extern Options options;
91 u_char *session_id2 = NULL;
92 u_int session_id2_len = 0;
95 struct sockaddr *xxx_hostaddr;
98 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh)
100 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
101 fatal("Host key verification failed.");
106 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
108 char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
110 struct hostkeys *hostkeys;
114 /* Find all hostkeys for this hostname */
115 get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
116 hostkeys = init_hostkeys();
117 for (i = 0; i < options.num_user_hostfiles; i++)
118 load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]);
119 for (i = 0; i < options.num_system_hostfiles; i++)
120 load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]);
122 oavail = avail = xstrdup(options.hostkeyalgorithms);
123 maxlen = strlen(avail) + 1;
124 first = xmalloc(maxlen);
125 last = xmalloc(maxlen);
126 *first = *last = '\0';
128 #define ALG_APPEND(to, from) \
131 strlcat(to, ",", maxlen); \
132 strlcat(to, from, maxlen); \
135 while ((alg = strsep(&avail, ",")) && *alg != '\0') {
136 if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
137 fatal("%s: unknown alg %s", __func__, alg);
138 if (lookup_key_in_hostkeys_by_type(hostkeys,
139 sshkey_type_plain(ktype), NULL))
140 ALG_APPEND(first, alg);
142 ALG_APPEND(last, alg);
145 xasprintf(&ret, "%s%s%s", first,
146 (*first == '\0' || *last == '\0') ? "" : ",", last);
148 debug3("%s: prefer hostkeyalgs: %s", __func__, first);
154 free_hostkeys(hostkeys);
160 ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port)
162 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
164 int r, use_known_hosts_order = 0;
167 xxx_hostaddr = hostaddr;
170 * If the user has not specified HostkeyAlgorithms, or has only
171 * appended or removed algorithms from that list then prefer algorithms
172 * that are in the list that are supported by known_hosts keys.
174 if (options.hostkeyalgorithms == NULL ||
175 options.hostkeyalgorithms[0] == '-' ||
176 options.hostkeyalgorithms[0] == '+')
177 use_known_hosts_order = 1;
179 /* Expand or fill in HostkeyAlgorithms */
180 all_key = sshkey_alg_list(0, 0, 1, ',');
181 if (kex_assemble_names(&options.hostkeyalgorithms,
182 kex_default_pk_alg(), all_key) != 0)
183 fatal("%s: kex_assemble_namelist", __func__);
186 if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
187 fatal("%s: kex_names_cat", __func__);
188 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
189 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
190 compat_cipher_proposal(options.ciphers);
191 myproposal[PROPOSAL_ENC_ALGS_STOC] =
192 compat_cipher_proposal(options.ciphers);
193 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
194 myproposal[PROPOSAL_COMP_ALGS_STOC] =
195 (char *)compression_alg_list(options.compression);
196 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
197 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
198 if (use_known_hosts_order) {
199 /* Query known_hosts and prefer algorithms that appear there */
200 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
201 compat_pkalg_proposal(
202 order_hostkeyalgs(host, hostaddr, port));
204 /* Use specified HostkeyAlgorithms exactly */
205 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
206 compat_pkalg_proposal(options.hostkeyalgorithms);
209 if (options.rekey_limit || options.rekey_interval)
210 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
211 options.rekey_interval);
213 /* start key exchange */
214 if ((r = kex_setup(ssh, myproposal)) != 0)
215 fatal("kex_setup: %s", ssh_err(r));
217 ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
218 ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
219 ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
220 ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
221 ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
222 ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
223 ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
224 # ifdef OPENSSL_HAS_ECC
225 ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
228 ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
229 ssh->kex->kex[KEX_KEM_SNTRUP4591761X25519_SHA512] = kex_gen_client;
230 ssh->kex->verify_host_key=&verify_host_key_callback;
232 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done);
234 /* remove ext-info from the KEX proposals for rekeying */
235 myproposal[PROPOSAL_KEX_ALGS] =
236 compat_kex_proposal(options.kex_algorithms);
237 if ((r = kex_prop2buf(ssh->kex->my, myproposal)) != 0)
238 fatal("kex_prop2buf: %s", ssh_err(r));
240 session_id2 = ssh->kex->session_id;
241 session_id2_len = ssh->kex->session_id_len;
244 /* send 1st encrypted/maced/compressed message */
245 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
246 (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
247 (r = sshpkt_send(ssh)) != 0 ||
248 (r = ssh_packet_write_wait(ssh)) != 0)
249 fatal("%s: %s", __func__, ssh_err(r));
257 typedef struct cauthctxt Authctxt;
258 typedef struct cauthmethod Authmethod;
259 typedef struct identity Identity;
260 typedef struct idlist Idlist;
263 TAILQ_ENTRY(identity) next;
264 int agent_fd; /* >=0 if agent supports key */
265 struct sshkey *key; /* public/private key */
266 char *filename; /* comment for agent-only keys */
268 int isprivate; /* key points to the private key */
271 TAILQ_HEAD(idlist, identity);
274 const char *server_user;
275 const char *local_user;
278 struct cauthmethod *method;
279 sig_atomic_t success;
283 gss_OID_set gss_supported_mechs;
290 Sensitive *sensitive;
291 char *oktypes, *ktypes;
292 const char *active_ktype;
293 /* kbd-interactive */
303 char *name; /* string to compare against server's list */
304 int (*userauth)(struct ssh *ssh);
305 void (*cleanup)(struct ssh *ssh);
306 int *enabled; /* flag in option struct that enables method */
307 int *batch_flag; /* flag in option struct that disables method */
310 static int input_userauth_service_accept(int, u_int32_t, struct ssh *);
311 static int input_userauth_ext_info(int, u_int32_t, struct ssh *);
312 static int input_userauth_success(int, u_int32_t, struct ssh *);
313 static int input_userauth_failure(int, u_int32_t, struct ssh *);
314 static int input_userauth_banner(int, u_int32_t, struct ssh *);
315 static int input_userauth_error(int, u_int32_t, struct ssh *);
316 static int input_userauth_info_req(int, u_int32_t, struct ssh *);
317 static int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
318 static int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
320 static int userauth_none(struct ssh *);
321 static int userauth_pubkey(struct ssh *);
322 static int userauth_passwd(struct ssh *);
323 static int userauth_kbdint(struct ssh *);
324 static int userauth_hostbased(struct ssh *);
327 static int userauth_gssapi(struct ssh *);
328 static void userauth_gssapi_cleanup(struct ssh *);
329 static int input_gssapi_response(int type, u_int32_t, struct ssh *);
330 static int input_gssapi_token(int type, u_int32_t, struct ssh *);
331 static int input_gssapi_error(int, u_int32_t, struct ssh *);
332 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
335 void userauth(struct ssh *, char *);
337 static void pubkey_cleanup(struct ssh *);
338 static int sign_and_send_pubkey(struct ssh *ssh, Identity *);
339 static void pubkey_prepare(Authctxt *);
340 static void pubkey_reset(Authctxt *);
341 static struct sshkey *load_identity_file(Identity *);
343 static Authmethod *authmethod_get(char *authlist);
344 static Authmethod *authmethod_lookup(const char *name);
345 static char *authmethods_get(void);
347 Authmethod authmethods[] = {
351 userauth_gssapi_cleanup,
352 &options.gss_authentication,
358 &options.hostbased_authentication,
363 &options.pubkey_authentication,
365 {"keyboard-interactive",
368 &options.kbd_interactive_authentication,
369 &options.batch_mode},
373 &options.password_authentication,
374 &options.batch_mode},
380 {NULL, NULL, NULL, NULL, NULL}
384 ssh_userauth2(struct ssh *ssh, const char *local_user,
385 const char *server_user, char *host, Sensitive *sensitive)
390 if (options.challenge_response_authentication)
391 options.kbd_interactive_authentication = 1;
392 if (options.preferred_authentications == NULL)
393 options.preferred_authentications = authmethods_get();
395 /* setup authentication context */
396 memset(&authctxt, 0, sizeof(authctxt));
397 authctxt.server_user = server_user;
398 authctxt.local_user = local_user;
399 authctxt.host = host;
400 authctxt.service = "ssh-connection"; /* service name */
401 authctxt.success = 0;
402 authctxt.method = authmethod_lookup("none");
403 authctxt.authlist = NULL;
404 authctxt.methoddata = NULL;
405 authctxt.sensitive = sensitive;
406 authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
407 authctxt.info_req_seen = 0;
408 authctxt.attempt_kbdint = 0;
409 authctxt.attempt_passwd = 0;
411 authctxt.gss_supported_mechs = NULL;
412 authctxt.mech_tried = 0;
414 authctxt.agent_fd = -1;
415 pubkey_prepare(&authctxt);
416 if (authctxt.method == NULL) {
417 fatal("%s: internal error: cannot send userauth none request",
421 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
422 (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
423 (r = sshpkt_send(ssh)) != 0)
424 fatal("%s: %s", __func__, ssh_err(r));
426 ssh->authctxt = &authctxt;
427 ssh_dispatch_init(ssh, &input_userauth_error);
428 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
429 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
430 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success); /* loop until success */
432 ssh->authctxt = NULL;
434 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
436 if (!authctxt.success)
437 fatal("Authentication failed.");
438 debug("Authentication succeeded (%s).", authctxt.method->name);
443 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
447 if (ssh_packet_remaining(ssh) > 0) {
450 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
452 debug2("service_accept: %s", reply);
455 debug2("buggy server: service_accept w/o service");
457 if ((r = sshpkt_get_end(ssh)) != 0)
459 debug("SSH2_MSG_SERVICE_ACCEPT received");
461 /* initial userauth request */
464 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
465 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
466 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
467 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
475 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh)
477 return kex_input_ext_info(type, seqnr, ssh);
481 userauth(struct ssh *ssh, char *authlist)
483 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
485 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
486 authctxt->method->cleanup(ssh);
488 free(authctxt->methoddata);
489 authctxt->methoddata = NULL;
490 if (authlist == NULL) {
491 authlist = authctxt->authlist;
493 free(authctxt->authlist);
494 authctxt->authlist = authlist;
497 Authmethod *method = authmethod_get(authlist);
499 fatal("%s@%s: Permission denied (%s).",
500 authctxt->server_user, authctxt->host, authlist);
501 authctxt->method = method;
503 /* reset the per method handler */
504 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN,
505 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
507 /* and try new method */
508 if (method->userauth(ssh) != 0) {
509 debug2("we sent a %s packet, wait for reply", method->name);
512 debug2("we did not send a packet, disable method");
513 method->enabled = NULL;
520 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
522 fatal("%s: bad message during authentication: type %d", __func__, type);
528 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
534 debug3("%s", __func__);
535 if ((r = sshpkt_get_cstring(ssh, &msg, &len)) != 0 ||
536 (r = sshpkt_get_cstring(ssh, NULL, NULL)) != 0)
538 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
539 fmprintf(stderr, "%s", msg);
548 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
550 Authctxt *authctxt = ssh->authctxt;
552 if (authctxt == NULL)
553 fatal("%s: no authentication context", __func__);
554 free(authctxt->authlist);
555 authctxt->authlist = NULL;
556 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
557 authctxt->method->cleanup(ssh);
558 free(authctxt->methoddata);
559 authctxt->methoddata = NULL;
560 authctxt->success = 1; /* break out */
566 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
568 Authctxt *authctxt = ssh->authctxt;
570 if (authctxt == NULL)
571 fatal("%s: no authentication context", __func__);
573 fatal("Unexpected authentication success during %s.",
574 authctxt->method->name);
581 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
583 Authctxt *authctxt = ssh->authctxt;
584 char *authlist = NULL;
587 if (authctxt == NULL)
588 fatal("input_userauth_failure: no authentication context");
590 if (sshpkt_get_cstring(ssh, &authlist, NULL) != 0 ||
591 sshpkt_get_u8(ssh, &partial) != 0 ||
592 sshpkt_get_end(ssh) != 0)
596 verbose("Authenticated with partial success.");
598 pubkey_reset(authctxt);
600 debug("Authentications that can continue: %s", authlist);
602 userauth(ssh, authlist);
610 * Format an identity for logging including filename, key type, fingerprint
611 * and location (agent, etc.). Caller must free.
614 format_identity(Identity *id)
616 char *fp = NULL, *ret = NULL;
617 const char *note = "";
619 if (id->key != NULL) {
620 fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
624 if ((id->key->flags & SSHKEY_FLAG_EXT) != 0)
626 else if (sshkey_is_sk(id->key))
627 note = " authenticator";
629 xasprintf(&ret, "%s %s%s%s%s%s%s",
631 id->key ? sshkey_type(id->key) : "", id->key ? " " : "",
633 id->userprovided ? " explicit" : "", note,
634 id->agent_fd != -1 ? " agent" : "");
641 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
643 Authctxt *authctxt = ssh->authctxt;
644 struct sshkey *key = NULL;
646 int pktype, found = 0, sent = 0;
648 char *pkalg = NULL, *fp = NULL, *ident = NULL;
649 u_char *pkblob = NULL;
652 if (authctxt == NULL)
653 fatal("input_userauth_pk_ok: no authentication context");
655 if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
656 (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
657 (r = sshpkt_get_end(ssh)) != 0)
660 if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) {
661 debug("%s: server sent unknown pkalg %s", __func__, pkalg);
664 if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
665 debug("no key from blob. pkalg %s: %s", pkalg, ssh_err(r));
668 if (key->type != pktype) {
669 error("input_userauth_pk_ok: type mismatch "
670 "for decoded key (received %d, expected %d)",
676 * search keys in the reverse order, because last candidate has been
677 * moved to the end of the queue. this also avoids confusion by
680 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
681 if (sshkey_equal(key, id->key)) {
686 if (!found || id == NULL) {
687 fp = sshkey_fingerprint(key, options.fingerprint_hash,
689 error("%s: server replied with unknown key: %s %s", __func__,
690 sshkey_type(key), fp == NULL ? "<ERROR>" : fp);
693 ident = format_identity(id);
694 debug("Server accepts key: %s", ident);
695 sent = sign_and_send_pubkey(ssh, id);
704 /* try another method if we did not send a packet */
705 if (r == 0 && sent == 0)
712 userauth_gssapi(struct ssh *ssh)
714 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
715 Gssctxt *gssctxt = NULL;
720 /* Try one GSSAPI method at a time, rather than sending them all at
723 if (authctxt->gss_supported_mechs == NULL)
724 gss_indicate_mechs(&min, &authctxt->gss_supported_mechs);
726 /* Check to see whether the mechanism is usable before we offer it */
727 while (authctxt->mech_tried < authctxt->gss_supported_mechs->count &&
729 mech = &authctxt->gss_supported_mechs->
730 elements[authctxt->mech_tried];
731 /* My DER encoding requires length<128 */
732 if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt,
733 mech, authctxt->host)) {
734 ok = 1; /* Mechanism works */
736 authctxt->mech_tried++;
740 if (!ok || mech == NULL)
743 authctxt->methoddata=(void *)gssctxt;
745 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
746 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
747 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
748 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
749 (r = sshpkt_put_u32(ssh, 1)) != 0 ||
750 (r = sshpkt_put_u32(ssh, (mech->length) + 2)) != 0 ||
751 (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 ||
752 (r = sshpkt_put_u8(ssh, mech->length)) != 0 ||
753 (r = sshpkt_put(ssh, mech->elements, mech->length)) != 0 ||
754 (r = sshpkt_send(ssh)) != 0)
755 fatal("%s: %s", __func__, ssh_err(r));
757 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
758 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
759 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
760 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
762 authctxt->mech_tried++; /* Move along to next candidate */
768 userauth_gssapi_cleanup(struct ssh *ssh)
770 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
771 Gssctxt *gssctxt = (Gssctxt *)authctxt->methoddata;
773 ssh_gssapi_delete_ctx(&gssctxt);
774 authctxt->methoddata = NULL;
776 free(authctxt->gss_supported_mechs);
777 authctxt->gss_supported_mechs = NULL;
781 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
783 Authctxt *authctxt = ssh->authctxt;
784 Gssctxt *gssctxt = authctxt->methoddata;
785 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
786 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
787 gss_buffer_desc gssbuf;
788 OM_uint32 status, ms, flags;
791 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
792 recv_tok, &send_tok, &flags);
794 if (send_tok.length > 0) {
795 u_char type = GSS_ERROR(status) ?
796 SSH2_MSG_USERAUTH_GSSAPI_ERRTOK :
797 SSH2_MSG_USERAUTH_GSSAPI_TOKEN;
799 if ((r = sshpkt_start(ssh, type)) != 0 ||
800 (r = sshpkt_put_string(ssh, send_tok.value,
801 send_tok.length)) != 0 ||
802 (r = sshpkt_send(ssh)) != 0)
803 fatal("%s: %s", __func__, ssh_err(r));
805 gss_release_buffer(&ms, &send_tok);
808 if (status == GSS_S_COMPLETE) {
809 /* send either complete or MIC, depending on mechanism */
810 if (!(flags & GSS_C_INTEG_FLAG)) {
811 if ((r = sshpkt_start(ssh,
812 SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 ||
813 (r = sshpkt_send(ssh)) != 0)
814 fatal("%s: %s", __func__, ssh_err(r));
818 if ((b = sshbuf_new()) == NULL)
819 fatal("%s: sshbuf_new failed", __func__);
820 ssh_gssapi_buildmic(b, authctxt->server_user,
821 authctxt->service, "gssapi-with-mic");
823 if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
824 fatal("%s: sshbuf_mutable_ptr failed", __func__);
825 gssbuf.length = sshbuf_len(b);
827 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
829 if (!GSS_ERROR(status)) {
830 if ((r = sshpkt_start(ssh,
831 SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 ||
832 (r = sshpkt_put_string(ssh, mic.value,
834 (r = sshpkt_send(ssh)) != 0)
835 fatal("%s: %s", __func__, ssh_err(r));
839 gss_release_buffer(&ms, &mic);
848 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
850 Authctxt *authctxt = ssh->authctxt;
856 if (authctxt == NULL)
857 fatal("input_gssapi_response: no authentication context");
858 gssctxt = authctxt->methoddata;
861 if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0)
865 oidv[0] != SSH_GSS_OIDTYPE ||
866 oidv[1] != oidlen - 2) {
867 debug("Badly encoded mechanism OID received");
872 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
873 fatal("Server returned different OID than expected");
875 if ((r = sshpkt_get_end(ssh)) != 0)
878 if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
879 /* Start again with next method on list */
880 debug("Trying to start again");
893 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
895 Authctxt *authctxt = ssh->authctxt;
896 gss_buffer_desc recv_tok;
902 if (authctxt == NULL)
903 fatal("input_gssapi_response: no authentication context");
905 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
906 (r = sshpkt_get_end(ssh)) != 0)
910 recv_tok.length = len;
911 status = process_gssapi_token(ssh, &recv_tok);
913 /* Start again with the next method in the list */
914 if (GSS_ERROR(status)) {
926 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
928 Authctxt *authctxt = ssh->authctxt;
930 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
931 gss_buffer_desc recv_tok;
937 if (authctxt == NULL)
938 fatal("input_gssapi_response: no authentication context");
939 gssctxt = authctxt->methoddata;
941 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
942 (r = sshpkt_get_end(ssh)) != 0) {
947 /* Stick it into GSSAPI and see what it says */
949 recv_tok.length = len;
950 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
951 &recv_tok, &send_tok, NULL);
953 gss_release_buffer(&ms, &send_tok);
955 /* Server will be returning a failed packet after this one */
961 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
967 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* maj */
968 (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* min */
969 (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
970 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
972 r = sshpkt_get_end(ssh);
973 debug("Server GSSAPI Error:\n%s", msg);
982 userauth_none(struct ssh *ssh)
984 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
987 /* initial userauth request */
988 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
989 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
990 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
991 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
992 (r = sshpkt_send(ssh)) != 0)
993 fatal("%s: %s", __func__, ssh_err(r));
998 userauth_passwd(struct ssh *ssh)
1000 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1001 char *password, *prompt = NULL;
1002 const char *host = options.host_key_alias ? options.host_key_alias :
1006 if (authctxt->attempt_passwd++ >= options.number_of_password_prompts)
1009 if (authctxt->attempt_passwd != 1)
1010 error("Permission denied, please try again.");
1012 xasprintf(&prompt, "%s@%s's password: ", authctxt->server_user, host);
1013 password = read_passphrase(prompt, 0);
1014 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1015 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1016 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1017 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1018 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
1019 (r = sshpkt_put_cstring(ssh, password)) != 0 ||
1020 (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1021 (r = sshpkt_send(ssh)) != 0)
1022 fatal("%s: %s", __func__, ssh_err(r));
1025 if (password != NULL)
1026 freezero(password, strlen(password));
1028 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1029 &input_userauth_passwd_changereq);
1035 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
1039 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
1041 Authctxt *authctxt = ssh->authctxt;
1042 char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL;
1047 debug2("input_userauth_passwd_changereq");
1049 if (authctxt == NULL)
1050 fatal("input_userauth_passwd_changereq: "
1051 "no authentication context");
1052 host = options.host_key_alias ? options.host_key_alias : authctxt->host;
1054 if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 ||
1055 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1057 if (strlen(info) > 0)
1059 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1060 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1061 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1062 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1063 (r = sshpkt_put_u8(ssh, 1)) != 0) /* additional info */
1066 snprintf(prompt, sizeof(prompt),
1067 "Enter %.30s@%.128s's old password: ",
1068 authctxt->server_user, host);
1069 password = read_passphrase(prompt, 0);
1070 if ((r = sshpkt_put_cstring(ssh, password)) != 0)
1073 freezero(password, strlen(password));
1075 while (password == NULL) {
1076 snprintf(prompt, sizeof(prompt),
1077 "Enter %.30s@%.128s's new password: ",
1078 authctxt->server_user, host);
1079 password = read_passphrase(prompt, RP_ALLOW_EOF);
1080 if (password == NULL) {
1085 snprintf(prompt, sizeof(prompt),
1086 "Retype %.30s@%.128s's new password: ",
1087 authctxt->server_user, host);
1088 retype = read_passphrase(prompt, 0);
1089 if (strcmp(password, retype) != 0) {
1090 freezero(password, strlen(password));
1091 logit("Mismatch; try again, EOF to quit.");
1094 freezero(retype, strlen(retype));
1096 if ((r = sshpkt_put_cstring(ssh, password)) != 0 ||
1097 (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1098 (r = sshpkt_send(ssh)) != 0)
1101 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1102 &input_userauth_passwd_changereq);
1106 freezero(password, strlen(password));
1113 * Select an algorithm for publickey signatures.
1114 * Returns algorithm (caller must free) or NULL if no mutual algorithm found.
1116 * Call with ssh==NULL to ignore server-sig-algs extension list and
1117 * only attempt with the key's base signature type.
1120 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key)
1122 char *allowed, *oallowed, *cp, *tmp, *alg = NULL;
1125 * The signature algorithm will only differ from the key algorithm
1126 * for RSA keys/certs and when the server advertises support for
1127 * newer (SHA2) algorithms.
1129 if (ssh == NULL || ssh->kex->server_sig_algs == NULL ||
1130 (key->type != KEY_RSA && key->type != KEY_RSA_CERT) ||
1131 (key->type == KEY_RSA_CERT && (datafellows & SSH_BUG_SIGTYPE))) {
1132 /* Filter base key signature alg against our configuration */
1133 return match_list(sshkey_ssh_name(key),
1134 options.pubkey_key_types, NULL);
1138 * For RSA keys/certs, since these might have a different sig type:
1139 * find the first entry in PubkeyAcceptedKeyTypes of the right type
1140 * that also appears in the supported signature algorithms list from
1143 oallowed = allowed = xstrdup(options.pubkey_key_types);
1144 while ((cp = strsep(&allowed, ",")) != NULL) {
1145 if (sshkey_type_from_name(cp) != key->type)
1147 tmp = match_list(sshkey_sigalg_by_name(cp), ssh->kex->server_sig_algs, NULL);
1159 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1160 const u_char *data, size_t datalen, u_int compat, const char *alg)
1162 struct sshkey *sign_key = NULL, *prv = NULL;
1163 int r = SSH_ERR_INTERNAL_ERROR;
1164 struct notifier_ctx *notifier = NULL;
1170 /* The agent supports this key. */
1171 if (id->key != NULL && id->agent_fd != -1) {
1172 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1173 data, datalen, alg, compat);
1177 * We have already loaded the private key or the private key is
1178 * stored in external hardware.
1180 if (id->key != NULL &&
1181 (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) {
1184 /* Load the private key from the file. */
1185 if ((prv = load_identity_file(id)) == NULL)
1186 return SSH_ERR_KEY_NOT_FOUND;
1187 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1188 error("%s: private key %s contents do not match public",
1189 __func__, id->filename);
1190 r = SSH_ERR_KEY_NOT_FOUND;
1194 if (sshkey_is_sk(sign_key) &&
1195 (sign_key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1196 /* XXX match batch mode should just skip these keys? */
1197 if ((fp = sshkey_fingerprint(sign_key,
1198 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1199 fatal("%s: sshkey_fingerprint", __func__);
1200 notifier = notify_start(options.batch_mode,
1201 "Confirm user presence for key %s %s",
1202 sshkey_type(sign_key), fp);
1206 if ((r = sshkey_sign(sign_key, sigp, lenp, data, datalen,
1207 alg, options.sk_provider, compat)) != 0) {
1208 debug("%s: sshkey_sign: %s", __func__, ssh_err(r));
1212 * PKCS#11 tokens may not support all signature algorithms,
1213 * so check what we get back.
1215 if ((r = sshkey_check_sigtype(*sigp, *lenp, alg)) != 0) {
1216 debug("%s: sshkey_check_sigtype: %s", __func__, ssh_err(r));
1222 notify_complete(notifier);
1228 id_filename_matches(Identity *id, Identity *private_id)
1230 const char *suffixes[] = { ".pub", "-cert.pub", NULL };
1231 size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1234 if (strcmp(id->filename, private_id->filename) == 0)
1236 for (i = 0; suffixes[i]; i++) {
1237 slen = strlen(suffixes[i]);
1238 if (len > slen && plen == len - slen &&
1239 strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1240 memcmp(id->filename, private_id->filename, plen) == 0)
1247 sign_and_send_pubkey(struct ssh *ssh, Identity *id)
1249 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1250 struct sshbuf *b = NULL;
1251 Identity *private_id, *sign_id = NULL;
1252 u_char *signature = NULL;
1253 size_t slen = 0, skip = 0;
1254 int r, fallback_sigtype, sent = 0;
1255 char *alg = NULL, *fp = NULL;
1256 const char *loc = "";
1258 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1259 SSH_FP_DEFAULT)) == NULL)
1262 debug3("%s: %s %s", __func__, sshkey_type(id->key), fp);
1265 * If the key is an certificate, try to find a matching private key
1266 * and use it to complete the signature.
1267 * If no such private key exists, fall back to trying the certificate
1268 * key itself in case it has a private half already loaded.
1269 * This will try to set sign_id to the private key that will perform
1272 if (sshkey_is_cert(id->key)) {
1273 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1274 if (sshkey_equal_public(id->key, private_id->key) &&
1275 id->key->type != private_id->key->type) {
1276 sign_id = private_id;
1281 * Exact key matches are preferred, but also allow
1282 * filename matches for non-PKCS#11/agent keys that
1283 * didn't load public keys. This supports the case
1284 * of keeping just a private key file and public
1285 * certificate on disk.
1287 if (sign_id == NULL &&
1288 !id->isprivate && id->agent_fd == -1 &&
1289 (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1290 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1291 if (private_id->key == NULL &&
1292 id_filename_matches(id, private_id)) {
1293 sign_id = private_id;
1298 if (sign_id != NULL) {
1299 debug2("%s: using private key \"%s\"%s for "
1300 "certificate", __func__, id->filename,
1301 id->agent_fd != -1 ? " from agent" : "");
1303 debug("%s: no separate private key for certificate "
1304 "\"%s\"", __func__, id->filename);
1309 * If the above didn't select another identity to do the signing
1310 * then default to the one we started with.
1312 if (sign_id == NULL)
1315 /* assemble and sign data */
1316 for (fallback_sigtype = 0; fallback_sigtype <= 1; fallback_sigtype++) {
1320 if ((alg = key_sig_algorithm(fallback_sigtype ? NULL : ssh,
1321 id->key)) == NULL) {
1322 error("%s: no mutual signature supported", __func__);
1325 debug3("%s: signing using %s %s", __func__, alg, fp);
1328 if ((b = sshbuf_new()) == NULL)
1329 fatal("%s: sshbuf_new failed", __func__);
1330 if (datafellows & SSH_OLD_SESSIONID) {
1331 if ((r = sshbuf_put(b, session_id2,
1332 session_id2_len)) != 0) {
1333 fatal("%s: sshbuf_put: %s",
1334 __func__, ssh_err(r));
1337 if ((r = sshbuf_put_string(b, session_id2,
1338 session_id2_len)) != 0) {
1339 fatal("%s: sshbuf_put_string: %s",
1340 __func__, ssh_err(r));
1343 skip = sshbuf_len(b);
1344 if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1345 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1346 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1347 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
1348 (r = sshbuf_put_u8(b, 1)) != 0 ||
1349 (r = sshbuf_put_cstring(b, alg)) != 0 ||
1350 (r = sshkey_puts(id->key, b)) != 0) {
1351 fatal("%s: assemble signed data: %s",
1352 __func__, ssh_err(r));
1355 /* generate signature */
1356 r = identity_sign(sign_id, &signature, &slen,
1357 sshbuf_ptr(b), sshbuf_len(b), datafellows, alg);
1360 else if (r == SSH_ERR_KEY_NOT_FOUND)
1361 goto out; /* soft failure */
1362 else if (r == SSH_ERR_SIGN_ALG_UNSUPPORTED &&
1363 !fallback_sigtype) {
1364 if (sign_id->agent_fd != -1)
1366 else if ((sign_id->key->flags & SSHKEY_FLAG_EXT) != 0)
1368 logit("%skey %s %s returned incorrect signature type",
1369 loc, sshkey_type(id->key), fp);
1372 error("%s: signing failed for %s \"%s\"%s: %s", __func__,
1373 sshkey_type(sign_id->key), sign_id->filename,
1374 id->agent_fd != -1 ? " from agent" : "", ssh_err(r));
1377 if (slen == 0 || signature == NULL) /* shouldn't happen */
1378 fatal("%s: no signature", __func__);
1380 /* append signature */
1381 if ((r = sshbuf_put_string(b, signature, slen)) != 0)
1382 fatal("%s: append signature: %s", __func__, ssh_err(r));
1385 sshbuf_dump(b, stderr);
1387 /* skip session id and packet type */
1388 if ((r = sshbuf_consume(b, skip + 1)) != 0)
1389 fatal("%s: consume: %s", __func__, ssh_err(r));
1391 /* put remaining data from buffer into packet */
1392 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1393 (r = sshpkt_putb(ssh, b)) != 0 ||
1394 (r = sshpkt_send(ssh)) != 0)
1395 fatal("%s: enqueue request: %s", __func__, ssh_err(r));
1404 freezero(signature, slen);
1409 send_pubkey_test(struct ssh *ssh, Identity *id)
1411 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1412 u_char *blob = NULL;
1418 if ((alg = key_sig_algorithm(ssh, id->key)) == NULL) {
1419 debug("%s: no mutual signature algorithm", __func__);
1423 if ((r = sshkey_to_blob(id->key, &blob, &bloblen)) != 0) {
1424 /* we cannot handle this key */
1425 debug3("%s: cannot handle key", __func__);
1428 /* register callback for USERAUTH_PK_OK message */
1429 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1431 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1432 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1433 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1434 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1435 (r = sshpkt_put_u8(ssh, have_sig)) != 0 ||
1436 (r = sshpkt_put_cstring(ssh, alg)) != 0 ||
1437 (r = sshpkt_put_string(ssh, blob, bloblen)) != 0 ||
1438 (r = sshpkt_send(ssh)) != 0)
1439 fatal("%s: %s", __func__, ssh_err(r));
1448 static struct sshkey *
1449 load_identity_file(Identity *id)
1451 struct sshkey *private = NULL;
1452 char prompt[300], *passphrase, *comment;
1456 if (stat(id->filename, &st) == -1) {
1457 (id->userprovided ? logit : debug3)("no such identity: %s: %s",
1458 id->filename, strerror(errno));
1461 snprintf(prompt, sizeof prompt,
1462 "Enter passphrase for key '%.100s': ", id->filename);
1463 for (i = 0; i <= options.number_of_password_prompts; i++) {
1467 passphrase = read_passphrase(prompt, 0);
1468 if (*passphrase == '\0') {
1469 debug2("no passphrase given, try next key");
1474 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1475 passphrase, &private, &comment))) {
1478 case SSH_ERR_KEY_WRONG_PASSPHRASE:
1479 if (options.batch_mode) {
1484 debug2("bad passphrase given, try again...");
1486 case SSH_ERR_SYSTEM_ERROR:
1487 if (errno == ENOENT) {
1488 debug2("Load key \"%s\": %s",
1489 id->filename, ssh_err(r));
1495 error("Load key \"%s\": %s", id->filename, ssh_err(r));
1499 if (private != NULL && sshkey_is_sk(private) &&
1500 options.sk_provider == NULL) {
1501 debug("key \"%s\" is an authenticator-hosted key, "
1502 "but no provider specified", id->filename);
1503 sshkey_free(private);
1507 if (!quit && private != NULL && id->agent_fd == -1 &&
1508 !(id->key && id->isprivate))
1509 maybe_add_key_to_agent(id->filename, private, comment,
1512 freezero(passphrase, strlen(passphrase));
1514 if (private != NULL || quit)
1521 key_type_allowed_by_config(struct sshkey *key)
1523 if (match_pattern_list(sshkey_ssh_name(key),
1524 options.pubkey_key_types, 0) == 1)
1527 /* RSA keys/certs might be allowed by alternate signature types */
1528 switch (key->type) {
1530 if (match_pattern_list("rsa-sha2-512",
1531 options.pubkey_key_types, 0) == 1)
1533 if (match_pattern_list("rsa-sha2-256",
1534 options.pubkey_key_types, 0) == 1)
1538 if (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
1539 options.pubkey_key_types, 0) == 1)
1541 if (match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
1542 options.pubkey_key_types, 0) == 1)
1551 * try keys in the following order:
1552 * 1. certificates listed in the config file
1553 * 2. other input certificates
1554 * 3. agent keys that are found in the config file
1555 * 4. other agent keys
1556 * 5. keys that are only listed in the config file
1559 pubkey_prepare(Authctxt *authctxt)
1561 struct identity *id, *id2, *tmp;
1562 struct idlist agent, files, *preferred;
1564 int agent_fd = -1, i, r, found;
1566 struct ssh_identitylist *idlist;
1569 TAILQ_INIT(&agent); /* keys from the agent */
1570 TAILQ_INIT(&files); /* keys from the config file */
1571 preferred = &authctxt->keys;
1572 TAILQ_INIT(preferred); /* preferred order of keys */
1574 /* list of keys stored in the filesystem and PKCS#11 */
1575 for (i = 0; i < options.num_identity_files; i++) {
1576 key = options.identity_keys[i];
1577 if (key && key->cert &&
1578 key->cert->type != SSH2_CERT_TYPE_USER) {
1579 debug("%s: ignoring certificate %s: not a user "
1580 "certificate", __func__,
1581 options.identity_files[i]);
1584 if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1585 debug("%s: ignoring authenticator-hosted key %s as no "
1586 "SecurityKeyProvider has been specified",
1587 __func__, options.identity_files[i]);
1590 options.identity_keys[i] = NULL;
1591 id = xcalloc(1, sizeof(*id));
1594 id->filename = xstrdup(options.identity_files[i]);
1595 id->userprovided = options.identity_file_userprovided[i];
1596 TAILQ_INSERT_TAIL(&files, id, next);
1598 /* list of certificates specified by user */
1599 for (i = 0; i < options.num_certificate_files; i++) {
1600 key = options.certificates[i];
1601 if (!sshkey_is_cert(key) || key->cert == NULL ||
1602 key->cert->type != SSH2_CERT_TYPE_USER) {
1603 debug("%s: ignoring certificate %s: not a user "
1604 "certificate", __func__,
1605 options.identity_files[i]);
1608 if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1609 debug("%s: ignoring authenticator-hosted key "
1610 "certificate %s as no "
1611 "SecurityKeyProvider has been specified",
1612 __func__, options.identity_files[i]);
1615 id = xcalloc(1, sizeof(*id));
1618 id->filename = xstrdup(options.certificate_files[i]);
1619 id->userprovided = options.certificate_file_userprovided[i];
1620 TAILQ_INSERT_TAIL(preferred, id, next);
1622 /* list of keys supported by the agent */
1623 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1624 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1625 debug("%s: ssh_get_authentication_socket: %s",
1626 __func__, ssh_err(r));
1627 } else if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1628 if (r != SSH_ERR_AGENT_NO_IDENTITIES)
1629 debug("%s: ssh_fetch_identitylist: %s",
1630 __func__, ssh_err(r));
1633 for (j = 0; j < idlist->nkeys; j++) {
1635 TAILQ_FOREACH(id, &files, next) {
1637 * agent keys from the config file are
1640 if (sshkey_equal(idlist->keys[j], id->key)) {
1641 TAILQ_REMOVE(&files, id, next);
1642 TAILQ_INSERT_TAIL(preferred, id, next);
1643 id->agent_fd = agent_fd;
1648 if (!found && !options.identities_only) {
1649 id = xcalloc(1, sizeof(*id));
1650 /* XXX "steals" key/comment from idlist */
1651 id->key = idlist->keys[j];
1652 id->filename = idlist->comments[j];
1653 idlist->keys[j] = NULL;
1654 idlist->comments[j] = NULL;
1655 id->agent_fd = agent_fd;
1656 TAILQ_INSERT_TAIL(&agent, id, next);
1659 ssh_free_identitylist(idlist);
1660 /* append remaining agent keys */
1661 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1662 TAILQ_REMOVE(&agent, id, next);
1663 TAILQ_INSERT_TAIL(preferred, id, next);
1665 authctxt->agent_fd = agent_fd;
1667 /* Prefer PKCS11 keys that are explicitly listed */
1668 TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1669 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1672 TAILQ_FOREACH(id2, &files, next) {
1673 if (id2->key == NULL ||
1674 (id2->key->flags & SSHKEY_FLAG_EXT) != 0)
1676 if (sshkey_equal(id->key, id2->key)) {
1677 TAILQ_REMOVE(&files, id, next);
1678 TAILQ_INSERT_TAIL(preferred, id, next);
1683 /* If IdentitiesOnly set and key not found then don't use it */
1684 if (!found && options.identities_only) {
1685 TAILQ_REMOVE(&files, id, next);
1686 freezero(id, sizeof(*id));
1689 /* append remaining keys from the config file */
1690 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1691 TAILQ_REMOVE(&files, id, next);
1692 TAILQ_INSERT_TAIL(preferred, id, next);
1694 /* finally, filter by PubkeyAcceptedKeyTypes */
1695 TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1696 if (id->key != NULL && !key_type_allowed_by_config(id->key)) {
1697 debug("Skipping %s key %s - "
1698 "not in PubkeyAcceptedKeyTypes",
1699 sshkey_ssh_name(id->key), id->filename);
1700 TAILQ_REMOVE(preferred, id, next);
1701 sshkey_free(id->key);
1703 memset(id, 0, sizeof(*id));
1707 /* List the keys we plan on using */
1708 TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1709 ident = format_identity(id);
1710 debug("Will attempt key: %s", ident);
1713 debug2("%s: done", __func__);
1717 pubkey_cleanup(struct ssh *ssh)
1719 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1722 if (authctxt->agent_fd != -1) {
1723 ssh_close_authentication_socket(authctxt->agent_fd);
1724 authctxt->agent_fd = -1;
1726 for (id = TAILQ_FIRST(&authctxt->keys); id;
1727 id = TAILQ_FIRST(&authctxt->keys)) {
1728 TAILQ_REMOVE(&authctxt->keys, id, next);
1729 sshkey_free(id->key);
1736 pubkey_reset(Authctxt *authctxt)
1740 TAILQ_FOREACH(id, &authctxt->keys, next)
1745 try_identity(Identity *id)
1749 if (sshkey_type_plain(id->key->type) == KEY_RSA &&
1750 (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1751 debug("Skipped %s key %s for RSA/MD5 server",
1752 sshkey_type(id->key), id->filename);
1759 userauth_pubkey(struct ssh *ssh)
1761 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1766 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1769 /* move key to the end of the queue */
1770 TAILQ_REMOVE(&authctxt->keys, id, next);
1771 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1773 * send a test message if we have the public key. for
1774 * encrypted keys we cannot do this and have to load the
1775 * private key instead
1777 if (id->key != NULL) {
1778 if (try_identity(id)) {
1779 ident = format_identity(id);
1780 debug("Offering public key: %s", ident);
1782 sent = send_pubkey_test(ssh, id);
1785 debug("Trying private key: %s", id->filename);
1786 id->key = load_identity_file(id);
1787 if (id->key != NULL) {
1788 if (try_identity(id)) {
1790 sent = sign_and_send_pubkey(ssh, id);
1792 sshkey_free(id->key);
1804 * Send userauth request message specifying keyboard-interactive method.
1807 userauth_kbdint(struct ssh *ssh)
1809 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1812 if (authctxt->attempt_kbdint++ >= options.number_of_password_prompts)
1814 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1815 if (authctxt->attempt_kbdint > 1 && !authctxt->info_req_seen) {
1816 debug3("userauth_kbdint: disable: no info_req_seen");
1817 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1821 debug2("userauth_kbdint");
1822 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1823 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1824 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1825 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1826 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* lang */
1827 (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ?
1828 options.kbd_interactive_devices : "")) != 0 ||
1829 (r = sshpkt_send(ssh)) != 0)
1830 fatal("%s: %s", __func__, ssh_err(r));
1832 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1837 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1840 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1842 Authctxt *authctxt = ssh->authctxt;
1843 char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL;
1844 char *response = NULL;
1846 u_int num_prompts, i;
1849 debug2("input_userauth_info_req");
1851 if (authctxt == NULL)
1852 fatal("input_userauth_info_req: no authentication context");
1854 authctxt->info_req_seen = 1;
1856 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1857 (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 ||
1858 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1860 if (strlen(name) > 0)
1862 if (strlen(inst) > 0)
1865 if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0)
1868 * Begin to build info response packet based on prompts requested.
1869 * We commit to providing the correct number of responses, so if
1870 * further on we run into a problem that prevents this, we have to
1871 * be sure and clean this up and send a correct error response.
1873 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 ||
1874 (r = sshpkt_put_u32(ssh, num_prompts)) != 0)
1877 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1878 for (i = 0; i < num_prompts; i++) {
1879 if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 ||
1880 (r = sshpkt_get_u8(ssh, &echo)) != 0)
1882 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1883 if ((r = sshpkt_put_cstring(ssh, response)) != 0)
1885 freezero(response, strlen(response));
1887 response = prompt = NULL;
1889 /* done with parsing incoming message. */
1890 if ((r = sshpkt_get_end(ssh)) != 0 ||
1891 (r = sshpkt_add_padding(ssh, 64)) != 0)
1893 r = sshpkt_send(ssh);
1896 freezero(response, strlen(response));
1905 ssh_keysign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
1906 const u_char *data, size_t datalen)
1911 int r, to[2], from[2], status;
1912 int sock = ssh_packet_get_connection_in(ssh);
1913 u_char rversion = 0, version = 2;
1914 void (*osigchld)(int);
1919 if (stat(_PATH_SSH_KEY_SIGN, &st) == -1) {
1920 error("%s: not installed: %s", __func__, strerror(errno));
1923 if (fflush(stdout) != 0) {
1924 error("%s: fflush: %s", __func__, strerror(errno));
1927 if (pipe(to) == -1) {
1928 error("%s: pipe: %s", __func__, strerror(errno));
1931 if (pipe(from) == -1) {
1932 error("%s: pipe: %s", __func__, strerror(errno));
1935 if ((pid = fork()) == -1) {
1936 error("%s: fork: %s", __func__, strerror(errno));
1939 osigchld = ssh_signal(SIGCHLD, SIG_DFL);
1942 if (dup2(from[1], STDOUT_FILENO) == -1)
1943 fatal("%s: dup2: %s", __func__, strerror(errno));
1945 if (dup2(to[0], STDIN_FILENO) == -1)
1946 fatal("%s: dup2: %s", __func__, strerror(errno));
1950 if (dup2(sock, STDERR_FILENO + 1) == -1)
1951 fatal("%s: dup2: %s", __func__, strerror(errno));
1952 sock = STDERR_FILENO + 1;
1953 fcntl(sock, F_SETFD, 0); /* keep the socket on exec */
1954 closefrom(sock + 1);
1956 debug3("%s: [child] pid=%ld, exec %s",
1957 __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
1958 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
1959 fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
1964 sock = STDERR_FILENO + 1;
1966 if ((b = sshbuf_new()) == NULL)
1967 fatal("%s: sshbuf_new failed", __func__);
1968 /* send # of sock, data to be signed */
1969 if ((r = sshbuf_put_u32(b, sock)) != 0 ||
1970 (r = sshbuf_put_string(b, data, datalen)) != 0)
1971 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1972 if (ssh_msg_send(to[1], version, b) == -1)
1973 fatal("%s: couldn't send request", __func__);
1975 r = ssh_msg_recv(from[0], b);
1979 error("%s: no reply", __func__);
1984 while (waitpid(pid, &status, 0) == -1) {
1985 if (errno != EINTR) {
1986 error("%s: waitpid %ld: %s",
1987 __func__, (long)pid, strerror(errno));
1991 if (!WIFEXITED(status)) {
1992 error("%s: exited abnormally", __func__);
1995 if (WEXITSTATUS(status) != 0) {
1996 error("%s: exited with status %d",
1997 __func__, WEXITSTATUS(status));
2000 if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
2001 error("%s: buffer error: %s", __func__, ssh_err(r));
2004 if (rversion != version) {
2005 error("%s: bad version", __func__);
2008 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
2009 error("%s: buffer error: %s", __func__, ssh_err(r));
2011 ssh_signal(SIGCHLD, osigchld);
2015 ssh_signal(SIGCHLD, osigchld);
2022 userauth_hostbased(struct ssh *ssh)
2024 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
2025 struct sshkey *private = NULL;
2026 struct sshbuf *b = NULL;
2027 u_char *sig = NULL, *keyblob = NULL;
2028 char *fp = NULL, *chost = NULL, *lname = NULL;
2029 size_t siglen = 0, keylen = 0;
2030 int i, r, success = 0;
2032 if (authctxt->ktypes == NULL) {
2033 authctxt->oktypes = xstrdup(options.hostbased_key_types);
2034 authctxt->ktypes = authctxt->oktypes;
2038 * Work through each listed type pattern in HostbasedKeyTypes,
2039 * trying each hostkey that matches the type in turn.
2042 if (authctxt->active_ktype == NULL)
2043 authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
2044 if (authctxt->active_ktype == NULL ||
2045 *authctxt->active_ktype == '\0')
2047 debug3("%s: trying key type %s", __func__,
2048 authctxt->active_ktype);
2050 /* check for a useful key */
2052 for (i = 0; i < authctxt->sensitive->nkeys; i++) {
2053 if (authctxt->sensitive->keys[i] == NULL ||
2054 authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
2056 if (match_pattern_list(
2057 sshkey_ssh_name(authctxt->sensitive->keys[i]),
2058 authctxt->active_ktype, 0) != 1)
2060 /* we take and free the key */
2061 private = authctxt->sensitive->keys[i];
2062 authctxt->sensitive->keys[i] = NULL;
2066 if (private != NULL)
2068 /* No more keys of this type; advance */
2069 authctxt->active_ktype = NULL;
2071 if (private == NULL) {
2072 free(authctxt->oktypes);
2073 authctxt->oktypes = authctxt->ktypes = NULL;
2074 authctxt->active_ktype = NULL;
2075 debug("No more client hostkeys for hostbased authentication.");
2079 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
2080 SSH_FP_DEFAULT)) == NULL) {
2081 error("%s: sshkey_fingerprint failed", __func__);
2084 debug("%s: trying hostkey %s %s",
2085 __func__, sshkey_ssh_name(private), fp);
2087 /* figure out a name for the client host */
2088 lname = get_local_name(ssh_packet_get_connection_in(ssh));
2089 if (lname == NULL) {
2090 error("%s: cannot get local ipaddr/name", __func__);
2094 /* XXX sshbuf_put_stringf? */
2095 xasprintf(&chost, "%s.", lname);
2096 debug2("%s: chost %s", __func__, chost);
2098 /* construct data */
2099 if ((b = sshbuf_new()) == NULL) {
2100 error("%s: sshbuf_new failed", __func__);
2103 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
2104 error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
2107 if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
2108 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2109 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
2110 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
2111 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
2112 (r = sshbuf_put_cstring(b, sshkey_ssh_name(private))) != 0 ||
2113 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
2114 (r = sshbuf_put_cstring(b, chost)) != 0 ||
2115 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
2116 error("%s: buffer error: %s", __func__, ssh_err(r));
2121 sshbuf_dump(b, stderr);
2123 if ((r = ssh_keysign(ssh, private, &sig, &siglen,
2124 sshbuf_ptr(b), sshbuf_len(b))) != 0) {
2125 error("sign using hostkey %s %s failed",
2126 sshkey_ssh_name(private), fp);
2129 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2130 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
2131 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
2132 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
2133 (r = sshpkt_put_cstring(ssh, sshkey_ssh_name(private))) != 0 ||
2134 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
2135 (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
2136 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
2137 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
2138 (r = sshpkt_send(ssh)) != 0) {
2139 error("%s: packet error: %s", __func__, ssh_err(r));
2146 freezero(sig, siglen);
2151 sshkey_free(private);
2157 /* find auth method */
2160 * given auth method name, if configurable options permit this method fill
2161 * in auth_ident field and return true, otherwise return false.
2164 authmethod_is_enabled(Authmethod *method)
2168 /* return false if options indicate this method is disabled */
2169 if (method->enabled == NULL || *method->enabled == 0)
2171 /* return false if batch mode is enabled but method needs interactive mode */
2172 if (method->batch_flag != NULL && *method->batch_flag != 0)
2178 authmethod_lookup(const char *name)
2180 Authmethod *method = NULL;
2182 for (method = authmethods; method->name != NULL; method++)
2183 if (strcmp(name, method->name) == 0)
2185 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
2189 /* XXX internal state */
2190 static Authmethod *current = NULL;
2191 static char *supported = NULL;
2192 static char *preferred = NULL;
2195 * Given the authentication method list sent by the server, return the
2196 * next method we should try. If the server initially sends a nil list,
2197 * use a built-in default list.
2200 authmethod_get(char *authlist)
2205 /* Use a suitable default if we're passed a nil list. */
2206 if (authlist == NULL || strlen(authlist) == 0)
2207 authlist = options.preferred_authentications;
2209 if (supported == NULL || strcmp(authlist, supported) != 0) {
2210 debug3("start over, passed a different list %s", authlist);
2212 supported = xstrdup(authlist);
2213 preferred = options.preferred_authentications;
2214 debug3("preferred %s", preferred);
2216 } else if (current != NULL && authmethod_is_enabled(current))
2220 if ((name = match_list(preferred, supported, &next)) == NULL) {
2221 debug("No more authentication methods to try.");
2226 debug3("authmethod_lookup %s", name);
2227 debug3("remaining preferred: %s", preferred);
2228 if ((current = authmethod_lookup(name)) != NULL &&
2229 authmethod_is_enabled(current)) {
2230 debug3("authmethod_is_enabled %s", name);
2231 debug("Next authentication method: %s", name);
2240 authmethods_get(void)
2242 Authmethod *method = NULL;
2247 if ((b = sshbuf_new()) == NULL)
2248 fatal("%s: sshbuf_new failed", __func__);
2249 for (method = authmethods; method->name != NULL; method++) {
2250 if (authmethod_is_enabled(method)) {
2251 if ((r = sshbuf_putf(b, "%s%s",
2252 sshbuf_len(b) ? "," : "", method->name)) != 0)
2253 fatal("%s: buffer error: %s",
2254 __func__, ssh_err(r));
2257 if ((list = sshbuf_dup_string(b)) == NULL)
2258 fatal("%s: sshbuf_dup_string failed", __func__);