1 /* $OpenBSD: sshconnect2.c,v 1.303 2019/02/12 23:53:10 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"
81 extern char *client_version_string;
82 extern char *server_version_string;
83 extern Options options;
89 u_char *session_id2 = NULL;
90 u_int session_id2_len = 0;
93 struct sockaddr *xxx_hostaddr;
96 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh)
98 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
99 fatal("Host key verification failed.");
104 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
106 char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
108 struct hostkeys *hostkeys;
112 /* Find all hostkeys for this hostname */
113 get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
114 hostkeys = init_hostkeys();
115 for (i = 0; i < options.num_user_hostfiles; i++)
116 load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]);
117 for (i = 0; i < options.num_system_hostfiles; i++)
118 load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]);
120 oavail = avail = xstrdup(KEX_DEFAULT_PK_ALG);
121 maxlen = strlen(avail) + 1;
122 first = xmalloc(maxlen);
123 last = xmalloc(maxlen);
124 *first = *last = '\0';
126 #define ALG_APPEND(to, from) \
129 strlcat(to, ",", maxlen); \
130 strlcat(to, from, maxlen); \
133 while ((alg = strsep(&avail, ",")) && *alg != '\0') {
134 if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
135 fatal("%s: unknown alg %s", __func__, alg);
136 if (lookup_key_in_hostkeys_by_type(hostkeys,
137 sshkey_type_plain(ktype), NULL))
138 ALG_APPEND(first, alg);
140 ALG_APPEND(last, alg);
143 xasprintf(&ret, "%s%s%s", first,
144 (*first == '\0' || *last == '\0') ? "" : ",", last);
146 debug3("%s: prefer hostkeyalgs: %s", __func__, first);
152 free_hostkeys(hostkeys);
158 ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port)
160 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
165 xxx_hostaddr = hostaddr;
167 if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
168 fatal("%s: kex_names_cat", __func__);
169 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
170 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
171 compat_cipher_proposal(options.ciphers);
172 myproposal[PROPOSAL_ENC_ALGS_STOC] =
173 compat_cipher_proposal(options.ciphers);
174 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
175 myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ?
176 "zlib@openssh.com,zlib,none" : "none,zlib@openssh.com,zlib";
177 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
178 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
179 if (options.hostkeyalgorithms != NULL) {
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__);
185 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
186 compat_pkalg_proposal(options.hostkeyalgorithms);
188 /* Enforce default */
189 options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG);
190 /* Prefer algorithms that we already have keys for */
191 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
192 compat_pkalg_proposal(
193 order_hostkeyalgs(host, hostaddr, port));
196 if (options.rekey_limit || options.rekey_interval)
197 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
198 options.rekey_interval);
200 /* start key exchange */
201 if ((r = kex_setup(ssh, myproposal)) != 0)
202 fatal("kex_setup: %s", ssh_err(r));
204 ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
205 ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
206 ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
207 ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
208 ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
209 ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
210 ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
211 # ifdef OPENSSL_HAS_ECC
212 ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
215 ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
216 ssh->kex->kex[KEX_KEM_SNTRUP4591761X25519_SHA512] = kex_gen_client;
217 ssh->kex->verify_host_key=&verify_host_key_callback;
219 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done);
221 /* remove ext-info from the KEX proposals for rekeying */
222 myproposal[PROPOSAL_KEX_ALGS] =
223 compat_kex_proposal(options.kex_algorithms);
224 if ((r = kex_prop2buf(ssh->kex->my, myproposal)) != 0)
225 fatal("kex_prop2buf: %s", ssh_err(r));
227 session_id2 = ssh->kex->session_id;
228 session_id2_len = ssh->kex->session_id_len;
231 /* send 1st encrypted/maced/compressed message */
232 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
233 (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
234 (r = sshpkt_send(ssh)) != 0 ||
235 (r = ssh_packet_write_wait(ssh)) != 0)
236 fatal("%s: %s", __func__, ssh_err(r));
244 typedef struct cauthctxt Authctxt;
245 typedef struct cauthmethod Authmethod;
246 typedef struct identity Identity;
247 typedef struct idlist Idlist;
250 TAILQ_ENTRY(identity) next;
251 int agent_fd; /* >=0 if agent supports key */
252 struct sshkey *key; /* public/private key */
253 char *filename; /* comment for agent-only keys */
255 int isprivate; /* key points to the private key */
258 TAILQ_HEAD(idlist, identity);
261 const char *server_user;
262 const char *local_user;
265 struct cauthmethod *method;
266 sig_atomic_t success;
270 gss_OID_set gss_supported_mechs;
277 Sensitive *sensitive;
278 char *oktypes, *ktypes;
279 const char *active_ktype;
280 /* kbd-interactive */
290 char *name; /* string to compare against server's list */
291 int (*userauth)(struct ssh *ssh);
292 void (*cleanup)(struct ssh *ssh);
293 int *enabled; /* flag in option struct that enables method */
294 int *batch_flag; /* flag in option struct that disables method */
297 static int input_userauth_service_accept(int, u_int32_t, struct ssh *);
298 static int input_userauth_ext_info(int, u_int32_t, struct ssh *);
299 static int input_userauth_success(int, u_int32_t, struct ssh *);
300 static int input_userauth_failure(int, u_int32_t, struct ssh *);
301 static int input_userauth_banner(int, u_int32_t, struct ssh *);
302 static int input_userauth_error(int, u_int32_t, struct ssh *);
303 static int input_userauth_info_req(int, u_int32_t, struct ssh *);
304 static int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
305 static int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
307 static int userauth_none(struct ssh *);
308 static int userauth_pubkey(struct ssh *);
309 static int userauth_passwd(struct ssh *);
310 static int userauth_kbdint(struct ssh *);
311 static int userauth_hostbased(struct ssh *);
314 static int userauth_gssapi(struct ssh *);
315 static void userauth_gssapi_cleanup(struct ssh *);
316 static int input_gssapi_response(int type, u_int32_t, struct ssh *);
317 static int input_gssapi_token(int type, u_int32_t, struct ssh *);
318 static int input_gssapi_error(int, u_int32_t, struct ssh *);
319 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
322 void userauth(struct ssh *, char *);
324 static void pubkey_cleanup(struct ssh *);
325 static int sign_and_send_pubkey(struct ssh *ssh, Identity *);
326 static void pubkey_prepare(Authctxt *);
327 static void pubkey_reset(Authctxt *);
328 static struct sshkey *load_identity_file(Identity *);
330 static Authmethod *authmethod_get(char *authlist);
331 static Authmethod *authmethod_lookup(const char *name);
332 static char *authmethods_get(void);
334 Authmethod authmethods[] = {
338 userauth_gssapi_cleanup,
339 &options.gss_authentication,
345 &options.hostbased_authentication,
350 &options.pubkey_authentication,
352 {"keyboard-interactive",
355 &options.kbd_interactive_authentication,
356 &options.batch_mode},
360 &options.password_authentication,
361 &options.batch_mode},
367 {NULL, NULL, NULL, NULL, NULL}
371 ssh_userauth2(struct ssh *ssh, const char *local_user,
372 const char *server_user, char *host, Sensitive *sensitive)
377 if (options.challenge_response_authentication)
378 options.kbd_interactive_authentication = 1;
379 if (options.preferred_authentications == NULL)
380 options.preferred_authentications = authmethods_get();
382 /* setup authentication context */
383 memset(&authctxt, 0, sizeof(authctxt));
384 authctxt.server_user = server_user;
385 authctxt.local_user = local_user;
386 authctxt.host = host;
387 authctxt.service = "ssh-connection"; /* service name */
388 authctxt.success = 0;
389 authctxt.method = authmethod_lookup("none");
390 authctxt.authlist = NULL;
391 authctxt.methoddata = NULL;
392 authctxt.sensitive = sensitive;
393 authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
394 authctxt.info_req_seen = 0;
395 authctxt.attempt_kbdint = 0;
396 authctxt.attempt_passwd = 0;
398 authctxt.gss_supported_mechs = NULL;
399 authctxt.mech_tried = 0;
401 authctxt.agent_fd = -1;
402 pubkey_prepare(&authctxt);
403 if (authctxt.method == NULL) {
404 fatal("%s: internal error: cannot send userauth none request",
408 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
409 (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
410 (r = sshpkt_send(ssh)) != 0)
411 fatal("%s: %s", __func__, ssh_err(r));
413 ssh->authctxt = &authctxt;
414 ssh_dispatch_init(ssh, &input_userauth_error);
415 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
416 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
417 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success); /* loop until success */
419 ssh->authctxt = NULL;
421 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
423 if (!authctxt.success)
424 fatal("Authentication failed.");
425 debug("Authentication succeeded (%s).", authctxt.method->name);
430 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
434 if (ssh_packet_remaining(ssh) > 0) {
437 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
439 debug2("service_accept: %s", reply);
442 debug2("buggy server: service_accept w/o service");
444 if ((r = sshpkt_get_end(ssh)) != 0)
446 debug("SSH2_MSG_SERVICE_ACCEPT received");
448 /* initial userauth request */
451 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
452 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
453 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
454 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
462 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh)
464 return kex_input_ext_info(type, seqnr, ssh);
468 userauth(struct ssh *ssh, char *authlist)
470 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
472 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
473 authctxt->method->cleanup(ssh);
475 free(authctxt->methoddata);
476 authctxt->methoddata = NULL;
477 if (authlist == NULL) {
478 authlist = authctxt->authlist;
480 free(authctxt->authlist);
481 authctxt->authlist = authlist;
484 Authmethod *method = authmethod_get(authlist);
486 fatal("%s@%s: Permission denied (%s).",
487 authctxt->server_user, authctxt->host, authlist);
488 authctxt->method = method;
490 /* reset the per method handler */
491 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN,
492 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
494 /* and try new method */
495 if (method->userauth(ssh) != 0) {
496 debug2("we sent a %s packet, wait for reply", method->name);
499 debug2("we did not send a packet, disable method");
500 method->enabled = NULL;
507 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
509 fatal("%s: bad message during authentication: type %d", __func__, type);
515 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
521 debug3("%s", __func__);
522 if ((r = sshpkt_get_cstring(ssh, &msg, &len)) != 0 ||
523 (r = sshpkt_get_cstring(ssh, NULL, NULL)) != 0)
525 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
526 fmprintf(stderr, "%s", msg);
535 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
537 Authctxt *authctxt = ssh->authctxt;
539 if (authctxt == NULL)
540 fatal("%s: no authentication context", __func__);
541 free(authctxt->authlist);
542 authctxt->authlist = NULL;
543 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
544 authctxt->method->cleanup(ssh);
545 free(authctxt->methoddata);
546 authctxt->methoddata = NULL;
547 authctxt->success = 1; /* break out */
553 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
555 Authctxt *authctxt = ssh->authctxt;
557 if (authctxt == NULL)
558 fatal("%s: no authentication context", __func__);
560 fatal("Unexpected authentication success during %s.",
561 authctxt->method->name);
568 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
570 Authctxt *authctxt = ssh->authctxt;
571 char *authlist = NULL;
575 if (authctxt == NULL)
576 fatal("input_userauth_failure: no authentication context");
578 if ((r = sshpkt_get_cstring(ssh, &authlist, NULL)) != 0 ||
579 (r = sshpkt_get_u8(ssh, &partial)) != 0 ||
580 (r = sshpkt_get_end(ssh)) != 0)
584 verbose("Authenticated with partial success.");
586 pubkey_reset(authctxt);
588 debug("Authentications that can continue: %s", authlist);
590 userauth(ssh, authlist);
598 * Format an identity for logging including filename, key type, fingerprint
599 * and location (agent, etc.). Caller must free.
602 format_identity(Identity *id)
604 char *fp = NULL, *ret = NULL;
606 if (id->key != NULL) {
607 fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
610 xasprintf(&ret, "%s %s%s%s%s%s%s",
612 id->key ? sshkey_type(id->key) : "", id->key ? " " : "",
614 id->userprovided ? " explicit" : "",
615 (id->key && (id->key->flags & SSHKEY_FLAG_EXT)) ? " token" : "",
616 id->agent_fd != -1 ? " agent" : "");
623 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
625 Authctxt *authctxt = ssh->authctxt;
626 struct sshkey *key = NULL;
628 int pktype, found = 0, sent = 0;
630 char *pkalg = NULL, *fp = NULL, *ident = NULL;
631 u_char *pkblob = NULL;
634 if (authctxt == NULL)
635 fatal("input_userauth_pk_ok: no authentication context");
637 if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
638 (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
639 (r = sshpkt_get_end(ssh)) != 0)
642 if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) {
643 debug("%s: server sent unknown pkalg %s", __func__, pkalg);
646 if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
647 debug("no key from blob. pkalg %s: %s", pkalg, ssh_err(r));
650 if (key->type != pktype) {
651 error("input_userauth_pk_ok: type mismatch "
652 "for decoded key (received %d, expected %d)",
658 * search keys in the reverse order, because last candidate has been
659 * moved to the end of the queue. this also avoids confusion by
662 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
663 if (sshkey_equal(key, id->key)) {
668 if (!found || id == NULL) {
669 fp = sshkey_fingerprint(key, options.fingerprint_hash,
671 error("%s: server replied with unknown key: %s %s", __func__,
672 sshkey_type(key), fp == NULL ? "<ERROR>" : fp);
675 ident = format_identity(id);
676 debug("Server accepts key: %s", ident);
677 sent = sign_and_send_pubkey(ssh, id);
686 /* try another method if we did not send a packet */
687 if (r == 0 && sent == 0)
694 userauth_gssapi(struct ssh *ssh)
696 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
697 Gssctxt *gssctxt = NULL;
702 /* Try one GSSAPI method at a time, rather than sending them all at
705 if (authctxt->gss_supported_mechs == NULL)
706 gss_indicate_mechs(&min, &authctxt->gss_supported_mechs);
708 /* Check to see whether the mechanism is usable before we offer it */
709 while (authctxt->mech_tried < authctxt->gss_supported_mechs->count &&
711 mech = &authctxt->gss_supported_mechs->
712 elements[authctxt->mech_tried];
713 /* My DER encoding requires length<128 */
714 if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt,
715 mech, authctxt->host)) {
716 ok = 1; /* Mechanism works */
718 authctxt->mech_tried++;
722 if (!ok || mech == NULL)
725 authctxt->methoddata=(void *)gssctxt;
727 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
728 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
729 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
730 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
731 (r = sshpkt_put_u32(ssh, 1)) != 0 ||
732 (r = sshpkt_put_u32(ssh, (mech->length) + 2)) != 0 ||
733 (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 ||
734 (r = sshpkt_put_u8(ssh, mech->length)) != 0 ||
735 (r = sshpkt_put(ssh, mech->elements, mech->length)) != 0 ||
736 (r = sshpkt_send(ssh)) != 0)
737 fatal("%s: %s", __func__, ssh_err(r));
739 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
740 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
741 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
742 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
744 authctxt->mech_tried++; /* Move along to next candidate */
750 userauth_gssapi_cleanup(struct ssh *ssh)
752 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
753 Gssctxt *gssctxt = (Gssctxt *)authctxt->methoddata;
755 ssh_gssapi_delete_ctx(&gssctxt);
756 authctxt->methoddata = NULL;
758 free(authctxt->gss_supported_mechs);
759 authctxt->gss_supported_mechs = NULL;
763 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
765 Authctxt *authctxt = ssh->authctxt;
766 Gssctxt *gssctxt = authctxt->methoddata;
767 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
768 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
769 gss_buffer_desc gssbuf;
770 OM_uint32 status, ms, flags;
773 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
774 recv_tok, &send_tok, &flags);
776 if (send_tok.length > 0) {
777 u_char type = GSS_ERROR(status) ?
778 SSH2_MSG_USERAUTH_GSSAPI_ERRTOK :
779 SSH2_MSG_USERAUTH_GSSAPI_TOKEN;
781 if ((r = sshpkt_start(ssh, type)) != 0 ||
782 (r = sshpkt_put_string(ssh, send_tok.value,
783 send_tok.length)) != 0 ||
784 (r = sshpkt_send(ssh)) != 0)
785 fatal("%s: %s", __func__, ssh_err(r));
787 gss_release_buffer(&ms, &send_tok);
790 if (status == GSS_S_COMPLETE) {
791 /* send either complete or MIC, depending on mechanism */
792 if (!(flags & GSS_C_INTEG_FLAG)) {
793 if ((r = sshpkt_start(ssh,
794 SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 ||
795 (r = sshpkt_send(ssh)) != 0)
796 fatal("%s: %s", __func__, ssh_err(r));
800 if ((b = sshbuf_new()) == NULL)
801 fatal("%s: sshbuf_new failed", __func__);
802 ssh_gssapi_buildmic(b, authctxt->server_user,
803 authctxt->service, "gssapi-with-mic");
805 if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
806 fatal("%s: sshbuf_mutable_ptr failed", __func__);
807 gssbuf.length = sshbuf_len(b);
809 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
811 if (!GSS_ERROR(status)) {
812 if ((r = sshpkt_start(ssh,
813 SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 ||
814 (r = sshpkt_put_string(ssh, mic.value,
816 (r = sshpkt_send(ssh)) != 0)
817 fatal("%s: %s", __func__, ssh_err(r));
821 gss_release_buffer(&ms, &mic);
830 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
832 Authctxt *authctxt = ssh->authctxt;
838 if (authctxt == NULL)
839 fatal("input_gssapi_response: no authentication context");
840 gssctxt = authctxt->methoddata;
843 if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0)
847 oidv[0] != SSH_GSS_OIDTYPE ||
848 oidv[1] != oidlen - 2) {
849 debug("Badly encoded mechanism OID received");
854 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
855 fatal("Server returned different OID than expected");
857 if ((r = sshpkt_get_end(ssh)) != 0)
860 if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
861 /* Start again with next method on list */
862 debug("Trying to start again");
875 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
877 Authctxt *authctxt = ssh->authctxt;
878 gss_buffer_desc recv_tok;
884 if (authctxt == NULL)
885 fatal("input_gssapi_response: no authentication context");
887 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
888 (r = sshpkt_get_end(ssh)) != 0)
892 recv_tok.length = len;
893 status = process_gssapi_token(ssh, &recv_tok);
895 /* Start again with the next method in the list */
896 if (GSS_ERROR(status)) {
908 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
910 Authctxt *authctxt = ssh->authctxt;
912 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
913 gss_buffer_desc recv_tok;
919 if (authctxt == NULL)
920 fatal("input_gssapi_response: no authentication context");
921 gssctxt = authctxt->methoddata;
923 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
924 (r = sshpkt_get_end(ssh)) != 0) {
929 /* Stick it into GSSAPI and see what it says */
931 recv_tok.length = len;
932 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
933 &recv_tok, &send_tok, NULL);
935 gss_release_buffer(&ms, &send_tok);
937 /* Server will be returning a failed packet after this one */
943 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
949 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* maj */
950 (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* min */
951 (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
952 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
954 r = sshpkt_get_end(ssh);
955 debug("Server GSSAPI Error:\n%s", msg);
964 userauth_none(struct ssh *ssh)
966 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
969 /* initial userauth request */
970 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
971 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
972 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
973 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
974 (r = sshpkt_send(ssh)) != 0)
975 fatal("%s: %s", __func__, ssh_err(r));
980 userauth_passwd(struct ssh *ssh)
982 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
983 char *password, *prompt = NULL;
984 const char *host = options.host_key_alias ? options.host_key_alias :
988 if (authctxt->attempt_passwd++ >= options.number_of_password_prompts)
991 if (authctxt->attempt_passwd != 1)
992 error("Permission denied, please try again.");
994 xasprintf(&prompt, "%s@%s's password: ", authctxt->server_user, host);
995 password = read_passphrase(prompt, 0);
996 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
997 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
998 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
999 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1000 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
1001 (r = sshpkt_put_cstring(ssh, password)) != 0 ||
1002 (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1003 (r = sshpkt_send(ssh)) != 0)
1004 fatal("%s: %s", __func__, ssh_err(r));
1007 if (password != NULL)
1008 freezero(password, strlen(password));
1010 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1011 &input_userauth_passwd_changereq);
1017 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
1021 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
1023 Authctxt *authctxt = ssh->authctxt;
1024 char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL;
1029 debug2("input_userauth_passwd_changereq");
1031 if (authctxt == NULL)
1032 fatal("input_userauth_passwd_changereq: "
1033 "no authentication context");
1034 host = options.host_key_alias ? options.host_key_alias : authctxt->host;
1036 if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 ||
1037 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1039 if (strlen(info) > 0)
1041 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1042 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1043 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1044 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1045 (r = sshpkt_put_u8(ssh, 1)) != 0) /* additional info */
1048 snprintf(prompt, sizeof(prompt),
1049 "Enter %.30s@%.128s's old password: ",
1050 authctxt->server_user, host);
1051 password = read_passphrase(prompt, 0);
1052 if ((r = sshpkt_put_cstring(ssh, password)) != 0)
1055 freezero(password, strlen(password));
1057 while (password == NULL) {
1058 snprintf(prompt, sizeof(prompt),
1059 "Enter %.30s@%.128s's new password: ",
1060 authctxt->server_user, host);
1061 password = read_passphrase(prompt, RP_ALLOW_EOF);
1062 if (password == NULL) {
1067 snprintf(prompt, sizeof(prompt),
1068 "Retype %.30s@%.128s's new password: ",
1069 authctxt->server_user, host);
1070 retype = read_passphrase(prompt, 0);
1071 if (strcmp(password, retype) != 0) {
1072 freezero(password, strlen(password));
1073 logit("Mismatch; try again, EOF to quit.");
1076 freezero(retype, strlen(retype));
1078 if ((r = sshpkt_put_cstring(ssh, password)) != 0 ||
1079 (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1080 (r = sshpkt_send(ssh)) != 0)
1083 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1084 &input_userauth_passwd_changereq);
1088 freezero(password, strlen(password));
1095 * Select an algorithm for publickey signatures.
1096 * Returns algorithm (caller must free) or NULL if no mutual algorithm found.
1098 * Call with ssh==NULL to ignore server-sig-algs extension list and
1099 * only attempt with the key's base signature type.
1102 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key)
1104 char *allowed, *oallowed, *cp, *tmp, *alg = NULL;
1107 * The signature algorithm will only differ from the key algorithm
1108 * for RSA keys/certs and when the server advertises support for
1109 * newer (SHA2) algorithms.
1111 if (ssh == NULL || ssh->kex->server_sig_algs == NULL ||
1112 (key->type != KEY_RSA && key->type != KEY_RSA_CERT) ||
1113 (key->type == KEY_RSA_CERT && (datafellows & SSH_BUG_SIGTYPE))) {
1114 /* Filter base key signature alg against our configuration */
1115 return match_list(sshkey_ssh_name(key),
1116 options.pubkey_key_types, NULL);
1120 * For RSA keys/certs, since these might have a different sig type:
1121 * find the first entry in PubkeyAcceptedKeyTypes of the right type
1122 * that also appears in the supported signature algorithms list from
1125 oallowed = allowed = xstrdup(options.pubkey_key_types);
1126 while ((cp = strsep(&allowed, ",")) != NULL) {
1127 if (sshkey_type_from_name(cp) != key->type)
1129 tmp = match_list(sshkey_sigalg_by_name(cp), ssh->kex->server_sig_algs, NULL);
1141 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1142 const u_char *data, size_t datalen, u_int compat, const char *alg)
1147 /* The agent supports this key. */
1148 if (id->key != NULL && id->agent_fd != -1) {
1149 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1150 data, datalen, alg, compat);
1154 * We have already loaded the private key or the private key is
1155 * stored in external hardware.
1157 if (id->key != NULL &&
1158 (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) {
1159 if ((r = sshkey_sign(id->key, sigp, lenp, data, datalen,
1163 * PKCS#11 tokens may not support all signature algorithms,
1164 * so check what we get back.
1166 if ((r = sshkey_check_sigtype(*sigp, *lenp, alg)) != 0)
1171 /* Load the private key from the file. */
1172 if ((prv = load_identity_file(id)) == NULL)
1173 return SSH_ERR_KEY_NOT_FOUND;
1174 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1175 error("%s: private key %s contents do not match public",
1176 __func__, id->filename);
1177 return SSH_ERR_KEY_NOT_FOUND;
1179 r = sshkey_sign(prv, sigp, lenp, data, datalen, alg, compat);
1185 id_filename_matches(Identity *id, Identity *private_id)
1187 const char *suffixes[] = { ".pub", "-cert.pub", NULL };
1188 size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1191 if (strcmp(id->filename, private_id->filename) == 0)
1193 for (i = 0; suffixes[i]; i++) {
1194 slen = strlen(suffixes[i]);
1195 if (len > slen && plen == len - slen &&
1196 strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1197 memcmp(id->filename, private_id->filename, plen) == 0)
1204 sign_and_send_pubkey(struct ssh *ssh, Identity *id)
1206 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1207 struct sshbuf *b = NULL;
1208 Identity *private_id, *sign_id = NULL;
1209 u_char *signature = NULL;
1210 size_t slen = 0, skip = 0;
1211 int r, fallback_sigtype, sent = 0;
1212 char *alg = NULL, *fp = NULL;
1213 const char *loc = "";
1215 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1216 SSH_FP_DEFAULT)) == NULL)
1219 debug3("%s: %s %s", __func__, sshkey_type(id->key), fp);
1222 * If the key is an certificate, try to find a matching private key
1223 * and use it to complete the signature.
1224 * If no such private key exists, fall back to trying the certificate
1225 * key itself in case it has a private half already loaded.
1226 * This will try to set sign_id to the private key that will perform
1229 if (sshkey_is_cert(id->key)) {
1230 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1231 if (sshkey_equal_public(id->key, private_id->key) &&
1232 id->key->type != private_id->key->type) {
1233 sign_id = private_id;
1238 * Exact key matches are preferred, but also allow
1239 * filename matches for non-PKCS#11/agent keys that
1240 * didn't load public keys. This supports the case
1241 * of keeping just a private key file and public
1242 * certificate on disk.
1244 if (sign_id == NULL &&
1245 !id->isprivate && id->agent_fd == -1 &&
1246 (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1247 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1248 if (private_id->key == NULL &&
1249 id_filename_matches(id, private_id)) {
1250 sign_id = private_id;
1255 if (sign_id != NULL) {
1256 debug2("%s: using private key \"%s\"%s for "
1257 "certificate", __func__, id->filename,
1258 id->agent_fd != -1 ? " from agent" : "");
1260 debug("%s: no separate private key for certificate "
1261 "\"%s\"", __func__, id->filename);
1266 * If the above didn't select another identity to do the signing
1267 * then default to the one we started with.
1269 if (sign_id == NULL)
1272 /* assemble and sign data */
1273 for (fallback_sigtype = 0; fallback_sigtype <= 1; fallback_sigtype++) {
1277 if ((alg = key_sig_algorithm(fallback_sigtype ? NULL : ssh,
1278 id->key)) == NULL) {
1279 error("%s: no mutual signature supported", __func__);
1282 debug3("%s: signing using %s", __func__, alg);
1285 if ((b = sshbuf_new()) == NULL)
1286 fatal("%s: sshbuf_new failed", __func__);
1287 if (datafellows & SSH_OLD_SESSIONID) {
1288 if ((r = sshbuf_put(b, session_id2,
1289 session_id2_len)) != 0) {
1290 fatal("%s: sshbuf_put: %s",
1291 __func__, ssh_err(r));
1294 if ((r = sshbuf_put_string(b, session_id2,
1295 session_id2_len)) != 0) {
1296 fatal("%s: sshbuf_put_string: %s",
1297 __func__, ssh_err(r));
1300 skip = sshbuf_len(b);
1301 if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1302 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1303 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1304 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
1305 (r = sshbuf_put_u8(b, 1)) != 0 ||
1306 (r = sshbuf_put_cstring(b, alg)) != 0 ||
1307 (r = sshkey_puts(id->key, b)) != 0) {
1308 fatal("%s: assemble signed data: %s",
1309 __func__, ssh_err(r));
1312 /* generate signature */
1313 r = identity_sign(sign_id, &signature, &slen,
1314 sshbuf_ptr(b), sshbuf_len(b), datafellows, alg);
1317 else if (r == SSH_ERR_KEY_NOT_FOUND)
1318 goto out; /* soft failure */
1319 else if (r == SSH_ERR_SIGN_ALG_UNSUPPORTED &&
1320 !fallback_sigtype) {
1321 if (sign_id->agent_fd != -1)
1323 else if ((sign_id->key->flags & SSHKEY_FLAG_EXT) != 0)
1325 logit("%skey %s %s returned incorrect signature type",
1326 loc, sshkey_type(id->key), fp);
1329 error("%s: signing failed: %s", __func__, ssh_err(r));
1332 if (slen == 0 || signature == NULL) /* shouldn't happen */
1333 fatal("%s: no signature", __func__);
1335 /* append signature */
1336 if ((r = sshbuf_put_string(b, signature, slen)) != 0)
1337 fatal("%s: append signature: %s", __func__, ssh_err(r));
1340 sshbuf_dump(b, stderr);
1342 /* skip session id and packet type */
1343 if ((r = sshbuf_consume(b, skip + 1)) != 0)
1344 fatal("%s: consume: %s", __func__, ssh_err(r));
1346 /* put remaining data from buffer into packet */
1347 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1348 (r = sshpkt_putb(ssh, b)) != 0 ||
1349 (r = sshpkt_send(ssh)) != 0)
1350 fatal("%s: enqueue request: %s", __func__, ssh_err(r));
1359 freezero(signature, slen);
1364 send_pubkey_test(struct ssh *ssh, Identity *id)
1366 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1367 u_char *blob = NULL;
1373 if ((alg = key_sig_algorithm(ssh, id->key)) == NULL) {
1374 debug("%s: no mutual signature algorithm", __func__);
1378 if ((r = sshkey_to_blob(id->key, &blob, &bloblen)) != 0) {
1379 /* we cannot handle this key */
1380 debug3("%s: cannot handle key", __func__);
1383 /* register callback for USERAUTH_PK_OK message */
1384 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1386 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1387 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1388 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1389 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1390 (r = sshpkt_put_u8(ssh, have_sig)) != 0 ||
1391 (r = sshpkt_put_cstring(ssh, alg)) != 0 ||
1392 (r = sshpkt_put_string(ssh, blob, bloblen)) != 0 ||
1393 (r = sshpkt_send(ssh)) != 0)
1394 fatal("%s: %s", __func__, ssh_err(r));
1403 static struct sshkey *
1404 load_identity_file(Identity *id)
1406 struct sshkey *private = NULL;
1407 char prompt[300], *passphrase, *comment;
1408 int r, perm_ok = 0, quit = 0, i;
1411 if (stat(id->filename, &st) < 0) {
1412 (id->userprovided ? logit : debug3)("no such identity: %s: %s",
1413 id->filename, strerror(errno));
1416 snprintf(prompt, sizeof prompt,
1417 "Enter passphrase for key '%.100s': ", id->filename);
1418 for (i = 0; i <= options.number_of_password_prompts; i++) {
1422 passphrase = read_passphrase(prompt, 0);
1423 if (*passphrase == '\0') {
1424 debug2("no passphrase given, try next key");
1429 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1430 passphrase, &private, &comment, &perm_ok))) {
1433 case SSH_ERR_KEY_WRONG_PASSPHRASE:
1434 if (options.batch_mode) {
1439 debug2("bad passphrase given, try again...");
1441 case SSH_ERR_SYSTEM_ERROR:
1442 if (errno == ENOENT) {
1443 debug2("Load key \"%s\": %s",
1444 id->filename, ssh_err(r));
1450 error("Load key \"%s\": %s", id->filename, ssh_err(r));
1454 if (!quit && private != NULL && id->agent_fd == -1 &&
1455 !(id->key && id->isprivate))
1456 maybe_add_key_to_agent(id->filename, private, comment,
1459 freezero(passphrase, strlen(passphrase));
1461 if (private != NULL || quit)
1468 key_type_allowed_by_config(struct sshkey *key)
1470 if (match_pattern_list(sshkey_ssh_name(key),
1471 options.pubkey_key_types, 0) == 1)
1474 /* RSA keys/certs might be allowed by alternate signature types */
1475 switch (key->type) {
1477 if (match_pattern_list("rsa-sha2-512",
1478 options.pubkey_key_types, 0) == 1)
1480 if (match_pattern_list("rsa-sha2-256",
1481 options.pubkey_key_types, 0) == 1)
1485 if (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
1486 options.pubkey_key_types, 0) == 1)
1488 if (match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
1489 options.pubkey_key_types, 0) == 1)
1498 * try keys in the following order:
1499 * 1. certificates listed in the config file
1500 * 2. other input certificates
1501 * 3. agent keys that are found in the config file
1502 * 4. other agent keys
1503 * 5. keys that are only listed in the config file
1506 pubkey_prepare(Authctxt *authctxt)
1508 struct identity *id, *id2, *tmp;
1509 struct idlist agent, files, *preferred;
1511 int agent_fd = -1, i, r, found;
1513 struct ssh_identitylist *idlist;
1516 TAILQ_INIT(&agent); /* keys from the agent */
1517 TAILQ_INIT(&files); /* keys from the config file */
1518 preferred = &authctxt->keys;
1519 TAILQ_INIT(preferred); /* preferred order of keys */
1521 /* list of keys stored in the filesystem and PKCS#11 */
1522 for (i = 0; i < options.num_identity_files; i++) {
1523 key = options.identity_keys[i];
1524 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1526 options.identity_keys[i] = NULL;
1527 id = xcalloc(1, sizeof(*id));
1530 id->filename = xstrdup(options.identity_files[i]);
1531 id->userprovided = options.identity_file_userprovided[i];
1532 TAILQ_INSERT_TAIL(&files, id, next);
1534 /* list of certificates specified by user */
1535 for (i = 0; i < options.num_certificate_files; i++) {
1536 key = options.certificates[i];
1537 if (!sshkey_is_cert(key) || key->cert == NULL ||
1538 key->cert->type != SSH2_CERT_TYPE_USER)
1540 id = xcalloc(1, sizeof(*id));
1543 id->filename = xstrdup(options.certificate_files[i]);
1544 id->userprovided = options.certificate_file_userprovided[i];
1545 TAILQ_INSERT_TAIL(preferred, id, next);
1547 /* list of keys supported by the agent */
1548 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1549 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1550 debug("%s: ssh_get_authentication_socket: %s",
1551 __func__, ssh_err(r));
1552 } else if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1553 if (r != SSH_ERR_AGENT_NO_IDENTITIES)
1554 debug("%s: ssh_fetch_identitylist: %s",
1555 __func__, ssh_err(r));
1558 for (j = 0; j < idlist->nkeys; j++) {
1560 TAILQ_FOREACH(id, &files, next) {
1562 * agent keys from the config file are
1565 if (sshkey_equal(idlist->keys[j], id->key)) {
1566 TAILQ_REMOVE(&files, id, next);
1567 TAILQ_INSERT_TAIL(preferred, id, next);
1568 id->agent_fd = agent_fd;
1573 if (!found && !options.identities_only) {
1574 id = xcalloc(1, sizeof(*id));
1575 /* XXX "steals" key/comment from idlist */
1576 id->key = idlist->keys[j];
1577 id->filename = idlist->comments[j];
1578 idlist->keys[j] = NULL;
1579 idlist->comments[j] = NULL;
1580 id->agent_fd = agent_fd;
1581 TAILQ_INSERT_TAIL(&agent, id, next);
1584 ssh_free_identitylist(idlist);
1585 /* append remaining agent keys */
1586 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1587 TAILQ_REMOVE(&agent, id, next);
1588 TAILQ_INSERT_TAIL(preferred, id, next);
1590 authctxt->agent_fd = agent_fd;
1592 /* Prefer PKCS11 keys that are explicitly listed */
1593 TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1594 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1597 TAILQ_FOREACH(id2, &files, next) {
1598 if (id2->key == NULL ||
1599 (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
1601 if (sshkey_equal(id->key, id2->key)) {
1602 TAILQ_REMOVE(&files, id, next);
1603 TAILQ_INSERT_TAIL(preferred, id, next);
1608 /* If IdentitiesOnly set and key not found then don't use it */
1609 if (!found && options.identities_only) {
1610 TAILQ_REMOVE(&files, id, next);
1611 freezero(id, sizeof(*id));
1614 /* append remaining keys from the config file */
1615 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1616 TAILQ_REMOVE(&files, id, next);
1617 TAILQ_INSERT_TAIL(preferred, id, next);
1619 /* finally, filter by PubkeyAcceptedKeyTypes */
1620 TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1621 if (id->key != NULL && !key_type_allowed_by_config(id->key)) {
1622 debug("Skipping %s key %s - "
1623 "not in PubkeyAcceptedKeyTypes",
1624 sshkey_ssh_name(id->key), id->filename);
1625 TAILQ_REMOVE(preferred, id, next);
1626 sshkey_free(id->key);
1628 memset(id, 0, sizeof(*id));
1632 /* List the keys we plan on using */
1633 TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1634 ident = format_identity(id);
1635 debug("Will attempt key: %s", ident);
1638 debug2("%s: done", __func__);
1642 pubkey_cleanup(struct ssh *ssh)
1644 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1647 if (authctxt->agent_fd != -1) {
1648 ssh_close_authentication_socket(authctxt->agent_fd);
1649 authctxt->agent_fd = -1;
1651 for (id = TAILQ_FIRST(&authctxt->keys); id;
1652 id = TAILQ_FIRST(&authctxt->keys)) {
1653 TAILQ_REMOVE(&authctxt->keys, id, next);
1654 sshkey_free(id->key);
1661 pubkey_reset(Authctxt *authctxt)
1665 TAILQ_FOREACH(id, &authctxt->keys, next)
1670 try_identity(Identity *id)
1674 if (sshkey_type_plain(id->key->type) == KEY_RSA &&
1675 (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1676 debug("Skipped %s key %s for RSA/MD5 server",
1677 sshkey_type(id->key), id->filename);
1684 userauth_pubkey(struct ssh *ssh)
1686 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1691 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1694 /* move key to the end of the queue */
1695 TAILQ_REMOVE(&authctxt->keys, id, next);
1696 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1698 * send a test message if we have the public key. for
1699 * encrypted keys we cannot do this and have to load the
1700 * private key instead
1702 if (id->key != NULL) {
1703 if (try_identity(id)) {
1704 ident = format_identity(id);
1705 debug("Offering public key: %s", ident);
1707 sent = send_pubkey_test(ssh, id);
1710 debug("Trying private key: %s", id->filename);
1711 id->key = load_identity_file(id);
1712 if (id->key != NULL) {
1713 if (try_identity(id)) {
1715 sent = sign_and_send_pubkey(ssh, id);
1717 sshkey_free(id->key);
1729 * Send userauth request message specifying keyboard-interactive method.
1732 userauth_kbdint(struct ssh *ssh)
1734 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1737 if (authctxt->attempt_kbdint++ >= options.number_of_password_prompts)
1739 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1740 if (authctxt->attempt_kbdint > 1 && !authctxt->info_req_seen) {
1741 debug3("userauth_kbdint: disable: no info_req_seen");
1742 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1746 debug2("userauth_kbdint");
1747 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1748 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1749 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1750 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1751 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* lang */
1752 (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ?
1753 options.kbd_interactive_devices : "")) != 0 ||
1754 (r = sshpkt_send(ssh)) != 0)
1755 fatal("%s: %s", __func__, ssh_err(r));
1757 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1762 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1765 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1767 Authctxt *authctxt = ssh->authctxt;
1768 char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL;
1769 char *response = NULL;
1771 u_int num_prompts, i;
1774 debug2("input_userauth_info_req");
1776 if (authctxt == NULL)
1777 fatal("input_userauth_info_req: no authentication context");
1779 authctxt->info_req_seen = 1;
1781 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1782 (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 ||
1783 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1785 if (strlen(name) > 0)
1787 if (strlen(inst) > 0)
1790 if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0)
1793 * Begin to build info response packet based on prompts requested.
1794 * We commit to providing the correct number of responses, so if
1795 * further on we run into a problem that prevents this, we have to
1796 * be sure and clean this up and send a correct error response.
1798 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 ||
1799 (r = sshpkt_put_u32(ssh, num_prompts)) != 0)
1802 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1803 for (i = 0; i < num_prompts; i++) {
1804 if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 ||
1805 (r = sshpkt_get_u8(ssh, &echo)) != 0)
1807 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1808 if ((r = sshpkt_put_cstring(ssh, response)) != 0)
1810 freezero(response, strlen(response));
1812 response = prompt = NULL;
1814 /* done with parsing incoming message. */
1815 if ((r = sshpkt_get_end(ssh)) != 0 ||
1816 (r = sshpkt_add_padding(ssh, 64)) != 0)
1818 r = sshpkt_send(ssh);
1821 freezero(response, strlen(response));
1830 ssh_keysign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
1831 const u_char *data, size_t datalen)
1836 int i, r, to[2], from[2], status;
1837 int sock = ssh_packet_get_connection_in(ssh);
1838 u_char rversion = 0, version = 2;
1839 void (*osigchld)(int);
1844 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1845 error("%s: not installed: %s", __func__, strerror(errno));
1848 if (fflush(stdout) != 0) {
1849 error("%s: fflush: %s", __func__, strerror(errno));
1853 error("%s: pipe: %s", __func__, strerror(errno));
1856 if (pipe(from) < 0) {
1857 error("%s: pipe: %s", __func__, strerror(errno));
1860 if ((pid = fork()) < 0) {
1861 error("%s: fork: %s", __func__, strerror(errno));
1864 osigchld = signal(SIGCHLD, SIG_DFL);
1866 /* keep the socket on exec */
1867 fcntl(sock, F_SETFD, 0);
1869 if (dup2(from[1], STDOUT_FILENO) < 0)
1870 fatal("%s: dup2: %s", __func__, strerror(errno));
1872 if (dup2(to[0], STDIN_FILENO) < 0)
1873 fatal("%s: dup2: %s", __func__, strerror(errno));
1876 /* Close everything but stdio and the socket */
1877 for (i = STDERR_FILENO + 1; i < sock; i++)
1879 closefrom(sock + 1);
1880 debug3("%s: [child] pid=%ld, exec %s",
1881 __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
1882 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
1883 fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
1889 if ((b = sshbuf_new()) == NULL)
1890 fatal("%s: sshbuf_new failed", __func__);
1891 /* send # of sock, data to be signed */
1892 if ((r = sshbuf_put_u32(b, sock)) != 0 ||
1893 (r = sshbuf_put_string(b, data, datalen)) != 0)
1894 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1895 if (ssh_msg_send(to[1], version, b) == -1)
1896 fatal("%s: couldn't send request", __func__);
1898 r = ssh_msg_recv(from[0], b);
1902 error("%s: no reply", __func__);
1907 while (waitpid(pid, &status, 0) < 0) {
1908 if (errno != EINTR) {
1909 error("%s: waitpid %ld: %s",
1910 __func__, (long)pid, strerror(errno));
1914 if (!WIFEXITED(status)) {
1915 error("%s: exited abnormally", __func__);
1918 if (WEXITSTATUS(status) != 0) {
1919 error("%s: exited with status %d",
1920 __func__, WEXITSTATUS(status));
1923 if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
1924 error("%s: buffer error: %s", __func__, ssh_err(r));
1927 if (rversion != version) {
1928 error("%s: bad version", __func__);
1931 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
1932 error("%s: buffer error: %s", __func__, ssh_err(r));
1934 signal(SIGCHLD, osigchld);
1938 signal(SIGCHLD, osigchld);
1945 userauth_hostbased(struct ssh *ssh)
1947 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1948 struct sshkey *private = NULL;
1949 struct sshbuf *b = NULL;
1950 u_char *sig = NULL, *keyblob = NULL;
1951 char *fp = NULL, *chost = NULL, *lname = NULL;
1952 size_t siglen = 0, keylen = 0;
1953 int i, r, success = 0;
1955 if (authctxt->ktypes == NULL) {
1956 authctxt->oktypes = xstrdup(options.hostbased_key_types);
1957 authctxt->ktypes = authctxt->oktypes;
1961 * Work through each listed type pattern in HostbasedKeyTypes,
1962 * trying each hostkey that matches the type in turn.
1965 if (authctxt->active_ktype == NULL)
1966 authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
1967 if (authctxt->active_ktype == NULL ||
1968 *authctxt->active_ktype == '\0')
1970 debug3("%s: trying key type %s", __func__,
1971 authctxt->active_ktype);
1973 /* check for a useful key */
1975 for (i = 0; i < authctxt->sensitive->nkeys; i++) {
1976 if (authctxt->sensitive->keys[i] == NULL ||
1977 authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
1979 if (match_pattern_list(
1980 sshkey_ssh_name(authctxt->sensitive->keys[i]),
1981 authctxt->active_ktype, 0) != 1)
1983 /* we take and free the key */
1984 private = authctxt->sensitive->keys[i];
1985 authctxt->sensitive->keys[i] = NULL;
1989 if (private != NULL)
1991 /* No more keys of this type; advance */
1992 authctxt->active_ktype = NULL;
1994 if (private == NULL) {
1995 free(authctxt->oktypes);
1996 authctxt->oktypes = authctxt->ktypes = NULL;
1997 authctxt->active_ktype = NULL;
1998 debug("No more client hostkeys for hostbased authentication.");
2002 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
2003 SSH_FP_DEFAULT)) == NULL) {
2004 error("%s: sshkey_fingerprint failed", __func__);
2007 debug("%s: trying hostkey %s %s",
2008 __func__, sshkey_ssh_name(private), fp);
2010 /* figure out a name for the client host */
2011 lname = get_local_name(ssh_packet_get_connection_in(ssh));
2012 if (lname == NULL) {
2013 error("%s: cannot get local ipaddr/name", __func__);
2017 /* XXX sshbuf_put_stringf? */
2018 xasprintf(&chost, "%s.", lname);
2019 debug2("%s: chost %s", __func__, chost);
2021 /* construct data */
2022 if ((b = sshbuf_new()) == NULL) {
2023 error("%s: sshbuf_new failed", __func__);
2026 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
2027 error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
2030 if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
2031 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2032 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
2033 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
2034 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
2035 (r = sshbuf_put_cstring(b, sshkey_ssh_name(private))) != 0 ||
2036 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
2037 (r = sshbuf_put_cstring(b, chost)) != 0 ||
2038 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
2039 error("%s: buffer error: %s", __func__, ssh_err(r));
2044 sshbuf_dump(b, stderr);
2046 if ((r = ssh_keysign(ssh, private, &sig, &siglen,
2047 sshbuf_ptr(b), sshbuf_len(b))) != 0) {
2048 error("sign using hostkey %s %s failed",
2049 sshkey_ssh_name(private), fp);
2052 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2053 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
2054 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
2055 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
2056 (r = sshpkt_put_cstring(ssh, sshkey_ssh_name(private))) != 0 ||
2057 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
2058 (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
2059 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
2060 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
2061 (r = sshpkt_send(ssh)) != 0) {
2062 error("%s: packet error: %s", __func__, ssh_err(r));
2069 freezero(sig, siglen);
2074 sshkey_free(private);
2080 /* find auth method */
2083 * given auth method name, if configurable options permit this method fill
2084 * in auth_ident field and return true, otherwise return false.
2087 authmethod_is_enabled(Authmethod *method)
2091 /* return false if options indicate this method is disabled */
2092 if (method->enabled == NULL || *method->enabled == 0)
2094 /* return false if batch mode is enabled but method needs interactive mode */
2095 if (method->batch_flag != NULL && *method->batch_flag != 0)
2101 authmethod_lookup(const char *name)
2103 Authmethod *method = NULL;
2105 for (method = authmethods; method->name != NULL; method++)
2106 if (strcmp(name, method->name) == 0)
2108 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
2112 /* XXX internal state */
2113 static Authmethod *current = NULL;
2114 static char *supported = NULL;
2115 static char *preferred = NULL;
2118 * Given the authentication method list sent by the server, return the
2119 * next method we should try. If the server initially sends a nil list,
2120 * use a built-in default list.
2123 authmethod_get(char *authlist)
2128 /* Use a suitable default if we're passed a nil list. */
2129 if (authlist == NULL || strlen(authlist) == 0)
2130 authlist = options.preferred_authentications;
2132 if (supported == NULL || strcmp(authlist, supported) != 0) {
2133 debug3("start over, passed a different list %s", authlist);
2135 supported = xstrdup(authlist);
2136 preferred = options.preferred_authentications;
2137 debug3("preferred %s", preferred);
2139 } else if (current != NULL && authmethod_is_enabled(current))
2143 if ((name = match_list(preferred, supported, &next)) == NULL) {
2144 debug("No more authentication methods to try.");
2149 debug3("authmethod_lookup %s", name);
2150 debug3("remaining preferred: %s", preferred);
2151 if ((current = authmethod_lookup(name)) != NULL &&
2152 authmethod_is_enabled(current)) {
2153 debug3("authmethod_is_enabled %s", name);
2154 debug("Next authentication method: %s", name);
2163 authmethods_get(void)
2165 Authmethod *method = NULL;
2170 if ((b = sshbuf_new()) == NULL)
2171 fatal("%s: sshbuf_new failed", __func__);
2172 for (method = authmethods; method->name != NULL; method++) {
2173 if (authmethod_is_enabled(method)) {
2174 if ((r = sshbuf_putf(b, "%s%s",
2175 sshbuf_len(b) ? "," : "", method->name)) != 0)
2176 fatal("%s: buffer error: %s",
2177 __func__, ssh_err(r));
2180 if ((list = sshbuf_dup_string(b)) == NULL)
2181 fatal("%s: sshbuf_dup_string failed", __func__);