1 /* $OpenBSD: sshconnect2.c,v 1.270 2018/03/24 19:28:43 markus 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(char *host, struct sockaddr *hostaddr, u_short port)
160 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
166 xxx_hostaddr = hostaddr;
168 if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
169 fatal("%s: kex_names_cat", __func__);
170 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
171 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
172 compat_cipher_proposal(options.ciphers);
173 myproposal[PROPOSAL_ENC_ALGS_STOC] =
174 compat_cipher_proposal(options.ciphers);
175 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
176 myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ?
177 "zlib@openssh.com,zlib,none" : "none,zlib@openssh.com,zlib";
178 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
179 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
180 if (options.hostkeyalgorithms != NULL) {
181 if (kex_assemble_names(KEX_DEFAULT_PK_ALG,
182 &options.hostkeyalgorithms) != 0)
183 fatal("%s: kex_assemble_namelist", __func__);
184 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
185 compat_pkalg_proposal(options.hostkeyalgorithms);
187 /* Enforce default */
188 options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG);
189 /* Prefer algorithms that we already have keys for */
190 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
191 compat_pkalg_proposal(
192 order_hostkeyalgs(host, hostaddr, port));
195 if (options.rekey_limit || options.rekey_interval)
196 packet_set_rekey_limits(options.rekey_limit,
197 options.rekey_interval);
199 /* start key exchange */
200 if ((r = kex_setup(active_state, myproposal)) != 0)
201 fatal("kex_setup: %s", ssh_err(r));
202 kex = active_state->kex;
204 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
205 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
206 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client;
207 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client;
208 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client;
209 kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
210 kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
211 # ifdef OPENSSL_HAS_ECC
212 kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
215 kex->kex[KEX_C25519_SHA256] = kexc25519_client;
216 kex->client_version_string=client_version_string;
217 kex->server_version_string=server_version_string;
218 kex->verify_host_key=&verify_host_key_callback;
220 ssh_dispatch_run_fatal(active_state, DISPATCH_BLOCK, &kex->done);
222 /* remove ext-info from the KEX proposals for rekeying */
223 myproposal[PROPOSAL_KEX_ALGS] =
224 compat_kex_proposal(options.kex_algorithms);
225 if ((r = kex_prop2buf(kex->my, myproposal)) != 0)
226 fatal("kex_prop2buf: %s", ssh_err(r));
228 session_id2 = kex->session_id;
229 session_id2_len = kex->session_id_len;
232 /* send 1st encrypted/maced/compressed message */
233 packet_start(SSH2_MSG_IGNORE);
234 packet_put_cstring("markus");
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;
273 Sensitive *sensitive;
274 char *oktypes, *ktypes;
275 const char *active_ktype;
276 /* kbd-interactive */
283 char *name; /* string to compare against server's list */
284 int (*userauth)(Authctxt *authctxt);
285 void (*cleanup)(Authctxt *authctxt);
286 int *enabled; /* flag in option struct that enables method */
287 int *batch_flag; /* flag in option struct that disables method */
290 int input_userauth_service_accept(int, u_int32_t, struct ssh *);
291 int input_userauth_ext_info(int, u_int32_t, struct ssh *);
292 int input_userauth_success(int, u_int32_t, struct ssh *);
293 int input_userauth_success_unexpected(int, u_int32_t, struct ssh *);
294 int input_userauth_failure(int, u_int32_t, struct ssh *);
295 int input_userauth_banner(int, u_int32_t, struct ssh *);
296 int input_userauth_error(int, u_int32_t, struct ssh *);
297 int input_userauth_info_req(int, u_int32_t, struct ssh *);
298 int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
299 int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
301 int userauth_none(Authctxt *);
302 int userauth_pubkey(Authctxt *);
303 int userauth_passwd(Authctxt *);
304 int userauth_kbdint(Authctxt *);
305 int userauth_hostbased(Authctxt *);
308 int userauth_gssapi(Authctxt *authctxt);
309 int input_gssapi_response(int type, u_int32_t, struct ssh *);
310 int input_gssapi_token(int type, u_int32_t, struct ssh *);
311 int input_gssapi_hash(int type, u_int32_t, struct ssh *);
312 int input_gssapi_error(int, u_int32_t, struct ssh *);
313 int input_gssapi_errtok(int, u_int32_t, struct ssh *);
316 void userauth(Authctxt *, char *);
318 static int sign_and_send_pubkey(Authctxt *, Identity *);
319 static void pubkey_prepare(Authctxt *);
320 static void pubkey_cleanup(Authctxt *);
321 static void pubkey_reset(Authctxt *);
322 static struct sshkey *load_identity_file(Identity *);
324 static Authmethod *authmethod_get(char *authlist);
325 static Authmethod *authmethod_lookup(const char *name);
326 static char *authmethods_get(void);
328 Authmethod authmethods[] = {
333 &options.gss_authentication,
339 &options.hostbased_authentication,
344 &options.pubkey_authentication,
346 {"keyboard-interactive",
349 &options.kbd_interactive_authentication,
350 &options.batch_mode},
354 &options.password_authentication,
355 &options.batch_mode},
361 {NULL, NULL, NULL, NULL, NULL}
365 ssh_userauth2(const char *local_user, const char *server_user, char *host,
366 Sensitive *sensitive)
368 struct ssh *ssh = active_state;
372 if (options.challenge_response_authentication)
373 options.kbd_interactive_authentication = 1;
374 if (options.preferred_authentications == NULL)
375 options.preferred_authentications = authmethods_get();
377 /* setup authentication context */
378 memset(&authctxt, 0, sizeof(authctxt));
379 pubkey_prepare(&authctxt);
380 authctxt.server_user = server_user;
381 authctxt.local_user = local_user;
382 authctxt.host = host;
383 authctxt.service = "ssh-connection"; /* service name */
384 authctxt.success = 0;
385 authctxt.method = authmethod_lookup("none");
386 authctxt.authlist = NULL;
387 authctxt.methoddata = NULL;
388 authctxt.sensitive = sensitive;
389 authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
390 authctxt.info_req_seen = 0;
391 authctxt.agent_fd = -1;
392 if (authctxt.method == NULL)
393 fatal("ssh_userauth2: internal error: cannot send userauth none request");
395 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
396 (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
397 (r = sshpkt_send(ssh)) != 0)
398 fatal("%s: %s", __func__, ssh_err(r));
400 ssh->authctxt = &authctxt;
401 ssh_dispatch_init(ssh, &input_userauth_error);
402 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
403 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
404 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success); /* loop until success */
405 ssh->authctxt = NULL;
407 pubkey_cleanup(&authctxt);
408 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
410 if (!authctxt.success)
411 fatal("Authentication failed.");
412 debug("Authentication succeeded (%s).", authctxt.method->name);
417 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
419 Authctxt *authctxt = ssh->authctxt;
422 if (ssh_packet_remaining(ssh) > 0) {
425 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
427 debug2("service_accept: %s", reply);
430 debug2("buggy server: service_accept w/o service");
432 if ((r = sshpkt_get_end(ssh)) != 0)
434 debug("SSH2_MSG_SERVICE_ACCEPT received");
436 /* initial userauth request */
437 userauth_none(authctxt);
439 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
440 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
441 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
442 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
450 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh)
452 return kex_input_ext_info(type, seqnr, ssh);
456 userauth(Authctxt *authctxt, char *authlist)
458 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
459 authctxt->method->cleanup(authctxt);
461 free(authctxt->methoddata);
462 authctxt->methoddata = NULL;
463 if (authlist == NULL) {
464 authlist = authctxt->authlist;
466 free(authctxt->authlist);
467 authctxt->authlist = authlist;
470 Authmethod *method = authmethod_get(authlist);
472 fatal("%s@%s: Permission denied (%s).",
473 authctxt->server_user, authctxt->host, authlist);
474 authctxt->method = method;
476 /* reset the per method handler */
477 dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
478 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
480 /* and try new method */
481 if (method->userauth(authctxt) != 0) {
482 debug2("we sent a %s packet, wait for reply", method->name);
485 debug2("we did not send a packet, disable method");
486 method->enabled = NULL;
493 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
495 fatal("input_userauth_error: bad message during authentication: "
502 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
507 debug3("%s", __func__);
508 msg = packet_get_string(&len);
509 lang = packet_get_string(NULL);
510 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
511 fmprintf(stderr, "%s", msg);
519 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
521 Authctxt *authctxt = ssh->authctxt;
523 if (authctxt == NULL)
524 fatal("input_userauth_success: no authentication context");
525 free(authctxt->authlist);
526 authctxt->authlist = NULL;
527 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
528 authctxt->method->cleanup(authctxt);
529 free(authctxt->methoddata);
530 authctxt->methoddata = NULL;
531 authctxt->success = 1; /* break out */
536 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
538 Authctxt *authctxt = ssh->authctxt;
540 if (authctxt == NULL)
541 fatal("%s: no authentication context", __func__);
543 fatal("Unexpected authentication success during %s.",
544 authctxt->method->name);
550 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
552 Authctxt *authctxt = ssh->authctxt;
553 char *authlist = NULL;
556 if (authctxt == NULL)
557 fatal("input_userauth_failure: no authentication context");
559 authlist = packet_get_string(NULL);
560 partial = packet_get_char();
564 verbose("Authenticated with partial success.");
566 pubkey_reset(authctxt);
568 debug("Authentications that can continue: %s", authlist);
570 userauth(authctxt, authlist);
576 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
578 Authctxt *authctxt = ssh->authctxt;
579 struct sshkey *key = NULL;
581 int pktype, sent = 0;
586 if (authctxt == NULL)
587 fatal("input_userauth_pk_ok: no authentication context");
589 pkalg = packet_get_string(&alen);
590 pkblob = packet_get_string(&blen);
593 debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
595 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
596 debug("unknown pkalg %s", pkalg);
599 if ((key = key_from_blob(pkblob, blen)) == NULL) {
600 debug("no key from blob. pkalg %s", pkalg);
603 if (key->type != pktype) {
604 error("input_userauth_pk_ok: type mismatch "
605 "for decoded key (received %d, expected %d)",
609 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
610 SSH_FP_DEFAULT)) == NULL)
612 debug2("input_userauth_pk_ok: fp %s", fp);
616 * search keys in the reverse order, because last candidate has been
617 * moved to the end of the queue. this also avoids confusion by
620 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
621 if (key_equal(key, id->key)) {
622 sent = sign_and_send_pubkey(authctxt, id);
631 /* try another method if we did not send a packet */
633 userauth(authctxt, NULL);
639 userauth_gssapi(Authctxt *authctxt)
641 Gssctxt *gssctxt = NULL;
642 static gss_OID_set gss_supported = NULL;
643 static u_int mech = 0;
647 /* Try one GSSAPI method at a time, rather than sending them all at
650 if (gss_supported == NULL)
651 gss_indicate_mechs(&min, &gss_supported);
653 /* Check to see if the mechanism is usable before we offer it */
654 while (mech < gss_supported->count && !ok) {
655 /* My DER encoding requires length<128 */
656 if (gss_supported->elements[mech].length < 128 &&
657 ssh_gssapi_check_mechanism(&gssctxt,
658 &gss_supported->elements[mech], authctxt->host)) {
659 ok = 1; /* Mechanism works */
668 authctxt->methoddata=(void *)gssctxt;
670 packet_start(SSH2_MSG_USERAUTH_REQUEST);
671 packet_put_cstring(authctxt->server_user);
672 packet_put_cstring(authctxt->service);
673 packet_put_cstring(authctxt->method->name);
677 packet_put_int((gss_supported->elements[mech].length) + 2);
678 packet_put_char(SSH_GSS_OIDTYPE);
679 packet_put_char(gss_supported->elements[mech].length);
680 packet_put_raw(gss_supported->elements[mech].elements,
681 gss_supported->elements[mech].length);
685 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
686 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
687 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
688 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
690 mech++; /* Move along to next candidate */
696 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
698 Authctxt *authctxt = ssh->authctxt;
699 Gssctxt *gssctxt = authctxt->methoddata;
700 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
701 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
702 gss_buffer_desc gssbuf;
703 OM_uint32 status, ms, flags;
706 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
707 recv_tok, &send_tok, &flags);
709 if (send_tok.length > 0) {
710 if (GSS_ERROR(status))
711 packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
713 packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
715 packet_put_string(send_tok.value, send_tok.length);
717 gss_release_buffer(&ms, &send_tok);
720 if (status == GSS_S_COMPLETE) {
721 /* send either complete or MIC, depending on mechanism */
722 if (!(flags & GSS_C_INTEG_FLAG)) {
723 packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
726 ssh_gssapi_buildmic(&b, authctxt->server_user,
727 authctxt->service, "gssapi-with-mic");
729 gssbuf.value = buffer_ptr(&b);
730 gssbuf.length = buffer_len(&b);
732 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
734 if (!GSS_ERROR(status)) {
735 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
736 packet_put_string(mic.value, mic.length);
742 gss_release_buffer(&ms, &mic);
751 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
753 Authctxt *authctxt = ssh->authctxt;
758 if (authctxt == NULL)
759 fatal("input_gssapi_response: no authentication context");
760 gssctxt = authctxt->methoddata;
763 oidv = packet_get_string(&oidlen);
766 oidv[0] != SSH_GSS_OIDTYPE ||
767 oidv[1] != oidlen - 2) {
769 debug("Badly encoded mechanism OID received");
770 userauth(authctxt, NULL);
774 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
775 fatal("Server returned different OID than expected");
781 if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
782 /* Start again with next method on list */
783 debug("Trying to start again");
784 userauth(authctxt, NULL);
792 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
794 Authctxt *authctxt = ssh->authctxt;
795 gss_buffer_desc recv_tok;
799 if (authctxt == NULL)
800 fatal("input_gssapi_response: no authentication context");
802 recv_tok.value = packet_get_string(&slen);
803 recv_tok.length = slen; /* safe typecast */
807 status = process_gssapi_token(ssh, &recv_tok);
809 free(recv_tok.value);
811 if (GSS_ERROR(status)) {
812 /* Start again with the next method in the list */
813 userauth(authctxt, NULL);
821 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
823 Authctxt *authctxt = ssh->authctxt;
825 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
826 gss_buffer_desc recv_tok;
830 if (authctxt == NULL)
831 fatal("input_gssapi_response: no authentication context");
832 gssctxt = authctxt->methoddata;
834 recv_tok.value = packet_get_string(&len);
835 recv_tok.length = len;
839 /* Stick it into GSSAPI and see what it says */
840 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
841 &recv_tok, &send_tok, NULL);
843 free(recv_tok.value);
844 gss_release_buffer(&ms, &send_tok);
846 /* Server will be returning a failed packet after this one */
852 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
857 /* maj */(void)packet_get_int();
858 /* min */(void)packet_get_int();
859 msg=packet_get_string(NULL);
860 lang=packet_get_string(NULL);
864 debug("Server GSSAPI Error:\n%s", msg);
872 userauth_none(Authctxt *authctxt)
874 /* initial userauth request */
875 packet_start(SSH2_MSG_USERAUTH_REQUEST);
876 packet_put_cstring(authctxt->server_user);
877 packet_put_cstring(authctxt->service);
878 packet_put_cstring(authctxt->method->name);
884 userauth_passwd(Authctxt *authctxt)
886 static int attempt = 0;
889 const char *host = options.host_key_alias ? options.host_key_alias :
892 if (attempt++ >= options.number_of_password_prompts)
896 error("Permission denied, please try again.");
898 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
899 authctxt->server_user, host);
900 password = read_passphrase(prompt, 0);
901 packet_start(SSH2_MSG_USERAUTH_REQUEST);
902 packet_put_cstring(authctxt->server_user);
903 packet_put_cstring(authctxt->service);
904 packet_put_cstring(authctxt->method->name);
906 packet_put_cstring(password);
907 explicit_bzero(password, strlen(password));
909 packet_add_padding(64);
912 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
913 &input_userauth_passwd_changereq);
919 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
923 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
925 Authctxt *authctxt = ssh->authctxt;
926 char *info, *lang, *password = NULL, *retype = NULL;
930 debug2("input_userauth_passwd_changereq");
932 if (authctxt == NULL)
933 fatal("input_userauth_passwd_changereq: "
934 "no authentication context");
935 host = options.host_key_alias ? options.host_key_alias : authctxt->host;
937 info = packet_get_string(NULL);
938 lang = packet_get_string(NULL);
939 if (strlen(info) > 0)
943 packet_start(SSH2_MSG_USERAUTH_REQUEST);
944 packet_put_cstring(authctxt->server_user);
945 packet_put_cstring(authctxt->service);
946 packet_put_cstring(authctxt->method->name);
947 packet_put_char(1); /* additional info */
948 snprintf(prompt, sizeof(prompt),
949 "Enter %.30s@%.128s's old password: ",
950 authctxt->server_user, host);
951 password = read_passphrase(prompt, 0);
952 packet_put_cstring(password);
953 explicit_bzero(password, strlen(password));
956 while (password == NULL) {
957 snprintf(prompt, sizeof(prompt),
958 "Enter %.30s@%.128s's new password: ",
959 authctxt->server_user, host);
960 password = read_passphrase(prompt, RP_ALLOW_EOF);
961 if (password == NULL) {
965 snprintf(prompt, sizeof(prompt),
966 "Retype %.30s@%.128s's new password: ",
967 authctxt->server_user, host);
968 retype = read_passphrase(prompt, 0);
969 if (strcmp(password, retype) != 0) {
970 explicit_bzero(password, strlen(password));
972 logit("Mismatch; try again, EOF to quit.");
975 explicit_bzero(retype, strlen(retype));
978 packet_put_cstring(password);
979 explicit_bzero(password, strlen(password));
981 packet_add_padding(64);
984 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
985 &input_userauth_passwd_changereq);
990 key_sign_encode(const struct sshkey *key)
992 struct ssh *ssh = active_state;
994 if (key->type == KEY_RSA) {
995 switch (ssh->kex->rsa_sha2) {
997 return "rsa-sha2-256";
999 return "rsa-sha2-512";
1002 return key_ssh_name(key);
1006 * Some agents will return ssh-rsa signatures when asked to make a
1007 * rsa-sha2-* signature. Check what they actually gave back and warn the
1008 * user if the agent has returned an unexpected type.
1011 check_sigtype(const struct sshkey *key, const u_char *sig, size_t len)
1014 char *sigtype = NULL;
1015 const char *alg = key_sign_encode(key);
1017 if (sshkey_is_cert(key))
1019 if ((r = sshkey_sigtype(sig, len, &sigtype)) != 0)
1021 if (strcmp(sigtype, alg) != 0) {
1022 logit("warning: agent returned different signature type %s "
1023 "(expected %s)", sigtype, alg);
1026 /* Incorrect signature types aren't an error ... yet */
1031 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1032 const u_char *data, size_t datalen, u_int compat)
1037 /* the agent supports this key */
1038 if (id->key != NULL && id->agent_fd != -1) {
1039 if ((r = ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1040 data, datalen, key_sign_encode(id->key), compat)) != 0 ||
1041 (r = check_sigtype(id->key, *sigp, *lenp)) != 0)
1047 * we have already loaded the private key or
1048 * the private key is stored in external hardware
1050 if (id->key != NULL &&
1051 (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT)))
1052 return (sshkey_sign(id->key, sigp, lenp, data, datalen,
1053 key_sign_encode(id->key), compat));
1055 /* load the private key from the file */
1056 if ((prv = load_identity_file(id)) == NULL)
1057 return SSH_ERR_KEY_NOT_FOUND;
1058 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1059 error("%s: private key %s contents do not match public",
1060 __func__, id->filename);
1061 return SSH_ERR_KEY_NOT_FOUND;
1063 r = sshkey_sign(prv, sigp, lenp, data, datalen,
1064 key_sign_encode(prv), compat);
1070 id_filename_matches(Identity *id, Identity *private_id)
1072 const char *suffixes[] = { ".pub", "-cert.pub", NULL };
1073 size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1076 if (strcmp(id->filename, private_id->filename) == 0)
1078 for (i = 0; suffixes[i]; i++) {
1079 slen = strlen(suffixes[i]);
1080 if (len > slen && plen == len - slen &&
1081 strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1082 memcmp(id->filename, private_id->filename, plen) == 0)
1089 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1092 Identity *private_id;
1093 u_char *blob, *signature;
1095 u_int bloblen, skip = 0;
1096 int matched, ret = -1, have_sig = 1;
1099 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1100 SSH_FP_DEFAULT)) == NULL)
1102 debug3("%s: %s %s", __func__, key_type(id->key), fp);
1105 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1106 /* we cannot handle this key */
1107 debug3("sign_and_send_pubkey: cannot handle key");
1110 /* data to be signed */
1112 if (datafellows & SSH_OLD_SESSIONID) {
1113 buffer_append(&b, session_id2, session_id2_len);
1114 skip = session_id2_len;
1116 buffer_put_string(&b, session_id2, session_id2_len);
1117 skip = buffer_len(&b);
1119 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1120 buffer_put_cstring(&b, authctxt->server_user);
1121 buffer_put_cstring(&b, authctxt->service);
1122 buffer_put_cstring(&b, authctxt->method->name);
1123 buffer_put_char(&b, have_sig);
1124 buffer_put_cstring(&b, key_sign_encode(id->key));
1125 buffer_put_string(&b, blob, bloblen);
1128 * If the key is an certificate, try to find a matching private key
1129 * and use it to complete the signature.
1130 * If no such private key exists, fall back to trying the certificate
1131 * key itself in case it has a private half already loaded.
1133 if (key_is_cert(id->key)) {
1135 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1136 if (sshkey_equal_public(id->key, private_id->key) &&
1137 id->key->type != private_id->key->type) {
1144 * Exact key matches are preferred, but also allow
1145 * filename matches for non-PKCS#11/agent keys that
1146 * didn't load public keys. This supports the case
1147 * of keeping just a private key file and public
1148 * certificate on disk.
1150 if (!matched && !id->isprivate && id->agent_fd == -1 &&
1151 (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1152 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1153 if (private_id->key == NULL &&
1154 id_filename_matches(id, private_id)) {
1162 debug2("%s: using private key \"%s\"%s for "
1163 "certificate", __func__, id->filename,
1164 id->agent_fd != -1 ? " from agent" : "");
1166 debug("%s: no separate private key for certificate "
1167 "\"%s\"", __func__, id->filename);
1171 /* generate signature */
1172 ret = identity_sign(id, &signature, &slen,
1173 buffer_ptr(&b), buffer_len(&b), datafellows);
1175 if (ret != SSH_ERR_KEY_NOT_FOUND)
1176 error("%s: signing failed: %s", __func__, ssh_err(ret));
1186 /* append signature */
1187 buffer_put_string(&b, signature, slen);
1190 /* skip session id and packet type */
1191 if (buffer_len(&b) < skip + 1)
1192 fatal("userauth_pubkey: internal error");
1193 buffer_consume(&b, skip + 1);
1195 /* put remaining data from buffer into packet */
1196 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1197 packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1205 send_pubkey_test(Authctxt *authctxt, Identity *id)
1208 u_int bloblen, have_sig = 0;
1210 debug3("send_pubkey_test");
1212 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1213 /* we cannot handle this key */
1214 debug3("send_pubkey_test: cannot handle key");
1217 /* register callback for USERAUTH_PK_OK message */
1218 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1220 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1221 packet_put_cstring(authctxt->server_user);
1222 packet_put_cstring(authctxt->service);
1223 packet_put_cstring(authctxt->method->name);
1224 packet_put_char(have_sig);
1225 packet_put_cstring(key_sign_encode(id->key));
1226 packet_put_string(blob, bloblen);
1232 static struct sshkey *
1233 load_identity_file(Identity *id)
1235 struct sshkey *private = NULL;
1236 char prompt[300], *passphrase, *comment;
1237 int r, perm_ok = 0, quit = 0, i;
1240 if (stat(id->filename, &st) < 0) {
1241 (id->userprovided ? logit : debug3)("no such identity: %s: %s",
1242 id->filename, strerror(errno));
1245 snprintf(prompt, sizeof prompt,
1246 "Enter passphrase for key '%.100s': ", id->filename);
1247 for (i = 0; i <= options.number_of_password_prompts; i++) {
1251 passphrase = read_passphrase(prompt, 0);
1252 if (*passphrase == '\0') {
1253 debug2("no passphrase given, try next key");
1258 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1259 passphrase, &private, &comment, &perm_ok))) {
1262 case SSH_ERR_KEY_WRONG_PASSPHRASE:
1263 if (options.batch_mode) {
1268 debug2("bad passphrase given, try again...");
1270 case SSH_ERR_SYSTEM_ERROR:
1271 if (errno == ENOENT) {
1272 debug2("Load key \"%s\": %s",
1273 id->filename, ssh_err(r));
1279 error("Load key \"%s\": %s", id->filename, ssh_err(r));
1283 if (!quit && private != NULL && id->agent_fd == -1 &&
1284 !(id->key && id->isprivate))
1285 maybe_add_key_to_agent(id->filename, private, comment,
1288 explicit_bzero(passphrase, strlen(passphrase));
1292 if (private != NULL || quit)
1299 * try keys in the following order:
1300 * 1. certificates listed in the config file
1301 * 2. other input certificates
1302 * 3. agent keys that are found in the config file
1303 * 4. other agent keys
1304 * 5. keys that are only listed in the config file
1307 pubkey_prepare(Authctxt *authctxt)
1309 struct identity *id, *id2, *tmp;
1310 struct idlist agent, files, *preferred;
1312 int agent_fd = -1, i, r, found;
1314 struct ssh_identitylist *idlist;
1316 TAILQ_INIT(&agent); /* keys from the agent */
1317 TAILQ_INIT(&files); /* keys from the config file */
1318 preferred = &authctxt->keys;
1319 TAILQ_INIT(preferred); /* preferred order of keys */
1321 /* list of keys stored in the filesystem and PKCS#11 */
1322 for (i = 0; i < options.num_identity_files; i++) {
1323 key = options.identity_keys[i];
1324 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1326 options.identity_keys[i] = NULL;
1327 id = xcalloc(1, sizeof(*id));
1330 id->filename = xstrdup(options.identity_files[i]);
1331 id->userprovided = options.identity_file_userprovided[i];
1332 TAILQ_INSERT_TAIL(&files, id, next);
1334 /* list of certificates specified by user */
1335 for (i = 0; i < options.num_certificate_files; i++) {
1336 key = options.certificates[i];
1337 if (!key_is_cert(key) || key->cert == NULL ||
1338 key->cert->type != SSH2_CERT_TYPE_USER)
1340 id = xcalloc(1, sizeof(*id));
1343 id->filename = xstrdup(options.certificate_files[i]);
1344 id->userprovided = options.certificate_file_userprovided[i];
1345 TAILQ_INSERT_TAIL(preferred, id, next);
1347 /* list of keys supported by the agent */
1348 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1349 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1350 debug("%s: ssh_get_authentication_socket: %s",
1351 __func__, ssh_err(r));
1352 } else if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1353 if (r != SSH_ERR_AGENT_NO_IDENTITIES)
1354 debug("%s: ssh_fetch_identitylist: %s",
1355 __func__, ssh_err(r));
1358 for (j = 0; j < idlist->nkeys; j++) {
1360 TAILQ_FOREACH(id, &files, next) {
1362 * agent keys from the config file are
1365 if (sshkey_equal(idlist->keys[j], id->key)) {
1366 TAILQ_REMOVE(&files, id, next);
1367 TAILQ_INSERT_TAIL(preferred, id, next);
1368 id->agent_fd = agent_fd;
1373 if (!found && !options.identities_only) {
1374 id = xcalloc(1, sizeof(*id));
1375 /* XXX "steals" key/comment from idlist */
1376 id->key = idlist->keys[j];
1377 id->filename = idlist->comments[j];
1378 idlist->keys[j] = NULL;
1379 idlist->comments[j] = NULL;
1380 id->agent_fd = agent_fd;
1381 TAILQ_INSERT_TAIL(&agent, id, next);
1384 ssh_free_identitylist(idlist);
1385 /* append remaining agent keys */
1386 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1387 TAILQ_REMOVE(&agent, id, next);
1388 TAILQ_INSERT_TAIL(preferred, id, next);
1390 authctxt->agent_fd = agent_fd;
1392 /* Prefer PKCS11 keys that are explicitly listed */
1393 TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1394 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1397 TAILQ_FOREACH(id2, &files, next) {
1398 if (id2->key == NULL ||
1399 (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
1401 if (sshkey_equal(id->key, id2->key)) {
1402 TAILQ_REMOVE(&files, id, next);
1403 TAILQ_INSERT_TAIL(preferred, id, next);
1408 /* If IdentitiesOnly set and key not found then don't use it */
1409 if (!found && options.identities_only) {
1410 TAILQ_REMOVE(&files, id, next);
1411 explicit_bzero(id, sizeof(*id));
1415 /* append remaining keys from the config file */
1416 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1417 TAILQ_REMOVE(&files, id, next);
1418 TAILQ_INSERT_TAIL(preferred, id, next);
1420 /* finally, filter by PubkeyAcceptedKeyTypes */
1421 TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1422 if (id->key != NULL &&
1423 match_pattern_list(sshkey_ssh_name(id->key),
1424 options.pubkey_key_types, 0) != 1) {
1425 debug("Skipping %s key %s - "
1426 "not in PubkeyAcceptedKeyTypes",
1427 sshkey_ssh_name(id->key), id->filename);
1428 TAILQ_REMOVE(preferred, id, next);
1429 sshkey_free(id->key);
1431 memset(id, 0, sizeof(*id));
1434 debug2("key: %s (%p)%s%s", id->filename, id->key,
1435 id->userprovided ? ", explicit" : "",
1436 id->agent_fd != -1 ? ", agent" : "");
1441 pubkey_cleanup(Authctxt *authctxt)
1445 if (authctxt->agent_fd != -1)
1446 ssh_close_authentication_socket(authctxt->agent_fd);
1447 for (id = TAILQ_FIRST(&authctxt->keys); id;
1448 id = TAILQ_FIRST(&authctxt->keys)) {
1449 TAILQ_REMOVE(&authctxt->keys, id, next);
1450 sshkey_free(id->key);
1457 pubkey_reset(Authctxt *authctxt)
1461 TAILQ_FOREACH(id, &authctxt->keys, next)
1466 try_identity(Identity *id)
1470 if (key_type_plain(id->key->type) == KEY_RSA &&
1471 (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1472 debug("Skipped %s key %s for RSA/MD5 server",
1473 key_type(id->key), id->filename);
1480 userauth_pubkey(Authctxt *authctxt)
1486 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1489 /* move key to the end of the queue */
1490 TAILQ_REMOVE(&authctxt->keys, id, next);
1491 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1493 * send a test message if we have the public key. for
1494 * encrypted keys we cannot do this and have to load the
1495 * private key instead
1497 if (id->key != NULL) {
1498 if (try_identity(id)) {
1499 if ((fp = sshkey_fingerprint(id->key,
1500 options.fingerprint_hash,
1501 SSH_FP_DEFAULT)) == NULL) {
1502 error("%s: sshkey_fingerprint failed",
1506 debug("Offering public key: %s %s %s",
1507 sshkey_type(id->key), fp, id->filename);
1509 sent = send_pubkey_test(authctxt, id);
1512 debug("Trying private key: %s", id->filename);
1513 id->key = load_identity_file(id);
1514 if (id->key != NULL) {
1515 if (try_identity(id)) {
1517 sent = sign_and_send_pubkey(
1532 * Send userauth request message specifying keyboard-interactive method.
1535 userauth_kbdint(Authctxt *authctxt)
1537 static int attempt = 0;
1539 if (attempt++ >= options.number_of_password_prompts)
1541 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1542 if (attempt > 1 && !authctxt->info_req_seen) {
1543 debug3("userauth_kbdint: disable: no info_req_seen");
1544 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1548 debug2("userauth_kbdint");
1549 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1550 packet_put_cstring(authctxt->server_user);
1551 packet_put_cstring(authctxt->service);
1552 packet_put_cstring(authctxt->method->name);
1553 packet_put_cstring(""); /* lang */
1554 packet_put_cstring(options.kbd_interactive_devices ?
1555 options.kbd_interactive_devices : "");
1558 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1563 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1566 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1568 Authctxt *authctxt = ssh->authctxt;
1569 char *name, *inst, *lang, *prompt, *response;
1570 u_int num_prompts, i;
1573 debug2("input_userauth_info_req");
1575 if (authctxt == NULL)
1576 fatal("input_userauth_info_req: no authentication context");
1578 authctxt->info_req_seen = 1;
1580 name = packet_get_string(NULL);
1581 inst = packet_get_string(NULL);
1582 lang = packet_get_string(NULL);
1583 if (strlen(name) > 0)
1585 if (strlen(inst) > 0)
1591 num_prompts = packet_get_int();
1593 * Begin to build info response packet based on prompts requested.
1594 * We commit to providing the correct number of responses, so if
1595 * further on we run into a problem that prevents this, we have to
1596 * be sure and clean this up and send a correct error response.
1598 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1599 packet_put_int(num_prompts);
1601 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1602 for (i = 0; i < num_prompts; i++) {
1603 prompt = packet_get_string(NULL);
1604 echo = packet_get_char();
1606 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1608 packet_put_cstring(response);
1609 explicit_bzero(response, strlen(response));
1613 packet_check_eom(); /* done with parsing incoming message. */
1615 packet_add_padding(64);
1621 ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp,
1622 const u_char *data, size_t datalen)
1627 int i, r, to[2], from[2], status, sock = packet_get_connection_in();
1628 u_char rversion = 0, version = 2;
1629 void (*osigchld)(int);
1634 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1635 error("%s: not installed: %s", __func__, strerror(errno));
1638 if (fflush(stdout) != 0) {
1639 error("%s: fflush: %s", __func__, strerror(errno));
1643 error("%s: pipe: %s", __func__, strerror(errno));
1646 if (pipe(from) < 0) {
1647 error("%s: pipe: %s", __func__, strerror(errno));
1650 if ((pid = fork()) < 0) {
1651 error("%s: fork: %s", __func__, strerror(errno));
1654 osigchld = signal(SIGCHLD, SIG_DFL);
1656 /* keep the socket on exec */
1657 fcntl(sock, F_SETFD, 0);
1658 permanently_drop_suid(getuid());
1660 if (dup2(from[1], STDOUT_FILENO) < 0)
1661 fatal("%s: dup2: %s", __func__, strerror(errno));
1663 if (dup2(to[0], STDIN_FILENO) < 0)
1664 fatal("%s: dup2: %s", __func__, strerror(errno));
1667 /* Close everything but stdio and the socket */
1668 for (i = STDERR_FILENO + 1; i < sock; i++)
1670 closefrom(sock + 1);
1671 debug3("%s: [child] pid=%ld, exec %s",
1672 __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
1673 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
1674 fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
1680 if ((b = sshbuf_new()) == NULL)
1681 fatal("%s: sshbuf_new failed", __func__);
1682 /* send # of sock, data to be signed */
1683 if ((r = sshbuf_put_u32(b, sock)) != 0 ||
1684 (r = sshbuf_put_string(b, data, datalen)) != 0)
1685 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1686 if (ssh_msg_send(to[1], version, b) == -1)
1687 fatal("%s: couldn't send request", __func__);
1689 r = ssh_msg_recv(from[0], b);
1693 error("%s: no reply", __func__);
1698 while (waitpid(pid, &status, 0) < 0) {
1699 if (errno != EINTR) {
1700 error("%s: waitpid %ld: %s",
1701 __func__, (long)pid, strerror(errno));
1705 if (!WIFEXITED(status)) {
1706 error("%s: exited abnormally", __func__);
1709 if (WEXITSTATUS(status) != 0) {
1710 error("%s: exited with status %d",
1711 __func__, WEXITSTATUS(status));
1714 if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
1715 error("%s: buffer error: %s", __func__, ssh_err(r));
1718 if (rversion != version) {
1719 error("%s: bad version", __func__);
1722 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
1723 error("%s: buffer error: %s", __func__, ssh_err(r));
1725 signal(SIGCHLD, osigchld);
1729 signal(SIGCHLD, osigchld);
1736 userauth_hostbased(Authctxt *authctxt)
1738 struct ssh *ssh = active_state;
1739 struct sshkey *private = NULL;
1740 struct sshbuf *b = NULL;
1741 u_char *sig = NULL, *keyblob = NULL;
1742 char *fp = NULL, *chost = NULL, *lname = NULL;
1743 size_t siglen = 0, keylen = 0;
1744 int i, r, success = 0;
1746 if (authctxt->ktypes == NULL) {
1747 authctxt->oktypes = xstrdup(options.hostbased_key_types);
1748 authctxt->ktypes = authctxt->oktypes;
1752 * Work through each listed type pattern in HostbasedKeyTypes,
1753 * trying each hostkey that matches the type in turn.
1756 if (authctxt->active_ktype == NULL)
1757 authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
1758 if (authctxt->active_ktype == NULL ||
1759 *authctxt->active_ktype == '\0')
1761 debug3("%s: trying key type %s", __func__,
1762 authctxt->active_ktype);
1764 /* check for a useful key */
1766 for (i = 0; i < authctxt->sensitive->nkeys; i++) {
1767 if (authctxt->sensitive->keys[i] == NULL ||
1768 authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
1770 if (match_pattern_list(
1771 sshkey_ssh_name(authctxt->sensitive->keys[i]),
1772 authctxt->active_ktype, 0) != 1)
1774 /* we take and free the key */
1775 private = authctxt->sensitive->keys[i];
1776 authctxt->sensitive->keys[i] = NULL;
1780 if (private != NULL)
1782 /* No more keys of this type; advance */
1783 authctxt->active_ktype = NULL;
1785 if (private == NULL) {
1786 free(authctxt->oktypes);
1787 authctxt->oktypes = authctxt->ktypes = NULL;
1788 authctxt->active_ktype = NULL;
1789 debug("No more client hostkeys for hostbased authentication.");
1793 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
1794 SSH_FP_DEFAULT)) == NULL) {
1795 error("%s: sshkey_fingerprint failed", __func__);
1798 debug("%s: trying hostkey %s %s",
1799 __func__, sshkey_ssh_name(private), fp);
1801 /* figure out a name for the client host */
1802 if ((lname = get_local_name(packet_get_connection_in())) == NULL) {
1803 error("%s: cannot get local ipaddr/name", __func__);
1807 /* XXX sshbuf_put_stringf? */
1808 xasprintf(&chost, "%s.", lname);
1809 debug2("%s: chost %s", __func__, chost);
1811 /* construct data */
1812 if ((b = sshbuf_new()) == NULL) {
1813 error("%s: sshbuf_new failed", __func__);
1816 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
1817 error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
1820 if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
1821 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1822 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1823 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1824 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
1825 (r = sshbuf_put_cstring(b, key_ssh_name(private))) != 0 ||
1826 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
1827 (r = sshbuf_put_cstring(b, chost)) != 0 ||
1828 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
1829 error("%s: buffer error: %s", __func__, ssh_err(r));
1834 sshbuf_dump(b, stderr);
1836 if (authctxt->sensitive->external_keysign)
1837 r = ssh_keysign(private, &sig, &siglen,
1838 sshbuf_ptr(b), sshbuf_len(b));
1839 else if ((r = sshkey_sign(private, &sig, &siglen,
1840 sshbuf_ptr(b), sshbuf_len(b), NULL, datafellows)) != 0)
1841 debug("%s: sshkey_sign: %s", __func__, ssh_err(r));
1843 error("sign using hostkey %s %s failed",
1844 sshkey_ssh_name(private), fp);
1847 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1848 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1849 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1850 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1851 (r = sshpkt_put_cstring(ssh, key_ssh_name(private))) != 0 ||
1852 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
1853 (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
1854 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
1855 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
1856 (r = sshpkt_send(ssh)) != 0) {
1857 error("%s: packet error: %s", __func__, ssh_err(r));
1864 explicit_bzero(sig, siglen);
1871 sshkey_free(private);
1877 /* find auth method */
1880 * given auth method name, if configurable options permit this method fill
1881 * in auth_ident field and return true, otherwise return false.
1884 authmethod_is_enabled(Authmethod *method)
1888 /* return false if options indicate this method is disabled */
1889 if (method->enabled == NULL || *method->enabled == 0)
1891 /* return false if batch mode is enabled but method needs interactive mode */
1892 if (method->batch_flag != NULL && *method->batch_flag != 0)
1898 authmethod_lookup(const char *name)
1900 Authmethod *method = NULL;
1902 for (method = authmethods; method->name != NULL; method++)
1903 if (strcmp(name, method->name) == 0)
1905 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1909 /* XXX internal state */
1910 static Authmethod *current = NULL;
1911 static char *supported = NULL;
1912 static char *preferred = NULL;
1915 * Given the authentication method list sent by the server, return the
1916 * next method we should try. If the server initially sends a nil list,
1917 * use a built-in default list.
1920 authmethod_get(char *authlist)
1925 /* Use a suitable default if we're passed a nil list. */
1926 if (authlist == NULL || strlen(authlist) == 0)
1927 authlist = options.preferred_authentications;
1929 if (supported == NULL || strcmp(authlist, supported) != 0) {
1930 debug3("start over, passed a different list %s", authlist);
1932 supported = xstrdup(authlist);
1933 preferred = options.preferred_authentications;
1934 debug3("preferred %s", preferred);
1936 } else if (current != NULL && authmethod_is_enabled(current))
1940 if ((name = match_list(preferred, supported, &next)) == NULL) {
1941 debug("No more authentication methods to try.");
1946 debug3("authmethod_lookup %s", name);
1947 debug3("remaining preferred: %s", preferred);
1948 if ((current = authmethod_lookup(name)) != NULL &&
1949 authmethod_is_enabled(current)) {
1950 debug3("authmethod_is_enabled %s", name);
1951 debug("Next authentication method: %s", name);
1960 authmethods_get(void)
1962 Authmethod *method = NULL;
1967 for (method = authmethods; method->name != NULL; method++) {
1968 if (authmethod_is_enabled(method)) {
1969 if (buffer_len(&b) > 0)
1970 buffer_append(&b, ",", 1);
1971 buffer_append(&b, method->name, strlen(method->name));
1974 if ((list = sshbuf_dup_string(&b)) == NULL)
1975 fatal("%s: sshbuf_dup_string failed", __func__);