1 /* $OpenBSD: sshconnect2.c,v 1.204 2014/02/02 03:44:32 djm Exp $ */
4 * Copyright (c) 2000 Markus Friedl. All rights reserved.
5 * Copyright (c) 2008 Damien Miller. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include <sys/types.h>
31 #include <sys/socket.h>
44 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
48 #include "openbsd-compat/sys-queue.h"
59 #include "myproposal.h"
60 #include "sshconnect.h"
71 #include "pathnames.h"
80 extern char *client_version_string;
81 extern char *server_version_string;
82 extern Options options;
83 #ifdef NONE_CIPHER_ENABLED
87 * tty_flag is set in ssh.c so we can use it here. If set then prevent
88 * the switch to the null cipher.
98 u_char *session_id2 = NULL;
99 u_int session_id2_len = 0;
102 struct sockaddr *xxx_hostaddr;
107 verify_host_key_callback(Key *hostkey)
109 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
110 fatal("Host key verification failed.");
115 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
117 char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
119 struct hostkeys *hostkeys;
123 /* Find all hostkeys for this hostname */
124 get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
125 hostkeys = init_hostkeys();
126 for (i = 0; i < options.num_user_hostfiles; i++)
127 load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]);
128 for (i = 0; i < options.num_system_hostfiles; i++)
129 load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]);
131 oavail = avail = xstrdup(KEX_DEFAULT_PK_ALG);
132 maxlen = strlen(avail) + 1;
133 first = xmalloc(maxlen);
134 last = xmalloc(maxlen);
135 *first = *last = '\0';
137 #define ALG_APPEND(to, from) \
140 strlcat(to, ",", maxlen); \
141 strlcat(to, from, maxlen); \
144 while ((alg = strsep(&avail, ",")) && *alg != '\0') {
145 if ((ktype = key_type_from_name(alg)) == KEY_UNSPEC)
146 fatal("%s: unknown alg %s", __func__, alg);
147 if (lookup_key_in_hostkeys_by_type(hostkeys,
148 key_type_plain(ktype), NULL))
149 ALG_APPEND(first, alg);
151 ALG_APPEND(last, alg);
154 xasprintf(&ret, "%s%s%s", first, *first == '\0' ? "" : ",", last);
156 debug3("%s: prefer hostkeyalgs: %s", __func__, first);
162 free_hostkeys(hostkeys);
168 ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
173 xxx_hostaddr = hostaddr;
175 if (options.ciphers == (char *)-1) {
176 logit("No valid ciphers for protocol version 2 given, using defaults.");
177 options.ciphers = NULL;
179 if (options.ciphers != NULL) {
180 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
181 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
183 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
184 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
185 myproposal[PROPOSAL_ENC_ALGS_STOC] =
186 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
187 if (options.compression) {
188 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
189 myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib@openssh.com,zlib,none";
191 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
192 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com,zlib";
194 if (options.macs != NULL) {
195 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
196 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
198 if (options.hostkeyalgorithms != NULL)
199 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
200 compat_pkalg_proposal(options.hostkeyalgorithms);
202 /* Prefer algorithms that we already have keys for */
203 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
204 compat_pkalg_proposal(
205 order_hostkeyalgs(host, hostaddr, port));
207 if (options.kex_algorithms != NULL)
208 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
210 if (options.rekey_limit || options.rekey_interval)
211 packet_set_rekey_limits((u_int32_t)options.rekey_limit,
212 (time_t)options.rekey_interval);
214 /* start key exchange */
215 kex = kex_setup(myproposal);
216 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
217 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
218 kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
219 kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
220 kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
221 kex->kex[KEX_C25519_SHA256] = kexc25519_client;
222 kex->client_version_string=client_version_string;
223 kex->server_version_string=server_version_string;
224 kex->verify_host_key=&verify_host_key_callback;
228 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
230 if (options.use_roaming && !kex->roaming) {
231 debug("Roaming not allowed by server");
232 options.use_roaming = 0;
235 session_id2 = kex->session_id;
236 session_id2_len = kex->session_id_len;
239 /* send 1st encrypted/maced/compressed message */
240 packet_start(SSH2_MSG_IGNORE);
241 packet_put_cstring("markus");
251 typedef struct Authctxt Authctxt;
252 typedef struct Authmethod Authmethod;
253 typedef struct identity Identity;
254 typedef struct idlist Idlist;
257 TAILQ_ENTRY(identity) next;
258 AuthenticationConnection *ac; /* set if agent supports key */
259 Key *key; /* public/private key */
260 char *filename; /* comment for agent-only keys */
262 int isprivate; /* key points to the private key */
265 TAILQ_HEAD(idlist, identity);
268 const char *server_user;
269 const char *local_user;
273 sig_atomic_t success;
277 AuthenticationConnection *agent;
279 Sensitive *sensitive;
280 /* kbd-interactive */
286 char *name; /* string to compare against server's list */
287 int (*userauth)(Authctxt *authctxt);
288 void (*cleanup)(Authctxt *authctxt);
289 int *enabled; /* flag in option struct that enables method */
290 int *batch_flag; /* flag in option struct that disables method */
293 void input_userauth_success(int, u_int32_t, void *);
294 void input_userauth_success_unexpected(int, u_int32_t, void *);
295 void input_userauth_failure(int, u_int32_t, void *);
296 void input_userauth_banner(int, u_int32_t, void *);
297 void input_userauth_error(int, u_int32_t, void *);
298 void input_userauth_info_req(int, u_int32_t, void *);
299 void input_userauth_pk_ok(int, u_int32_t, void *);
300 void input_userauth_passwd_changereq(int, u_int32_t, void *);
302 int userauth_none(Authctxt *);
303 int userauth_pubkey(Authctxt *);
304 int userauth_passwd(Authctxt *);
305 int userauth_kbdint(Authctxt *);
306 int userauth_hostbased(Authctxt *);
309 int userauth_gssapi(Authctxt *authctxt);
310 void input_gssapi_response(int type, u_int32_t, void *);
311 void input_gssapi_token(int type, u_int32_t, void *);
312 void input_gssapi_hash(int type, u_int32_t, void *);
313 void input_gssapi_error(int, u_int32_t, void *);
314 void input_gssapi_errtok(int, u_int32_t, void *);
317 void userauth(Authctxt *, char *);
319 static int sign_and_send_pubkey(Authctxt *, Identity *);
320 static void pubkey_prepare(Authctxt *);
321 static void pubkey_cleanup(Authctxt *);
322 static Key *load_identity_file(char *, int);
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)
371 if (options.challenge_response_authentication)
372 options.kbd_interactive_authentication = 1;
374 packet_start(SSH2_MSG_SERVICE_REQUEST);
375 packet_put_cstring("ssh-userauth");
377 debug("SSH2_MSG_SERVICE_REQUEST sent");
379 type = packet_read();
380 if (type != SSH2_MSG_SERVICE_ACCEPT)
381 fatal("Server denied authentication request: %d", type);
382 if (packet_remaining() > 0) {
383 char *reply = packet_get_string(NULL);
384 debug2("service_accept: %s", reply);
387 debug2("buggy server: service_accept w/o service");
390 debug("SSH2_MSG_SERVICE_ACCEPT received");
392 if (options.preferred_authentications == NULL)
393 options.preferred_authentications = authmethods_get();
395 /* setup authentication context */
396 memset(&authctxt, 0, sizeof(authctxt));
397 pubkey_prepare(&authctxt);
398 authctxt.server_user = server_user;
399 authctxt.local_user = local_user;
400 authctxt.host = host;
401 authctxt.service = "ssh-connection"; /* service name */
402 authctxt.success = 0;
403 authctxt.method = authmethod_lookup("none");
404 authctxt.authlist = NULL;
405 authctxt.methoddata = NULL;
406 authctxt.sensitive = sensitive;
407 authctxt.info_req_seen = 0;
408 if (authctxt.method == NULL)
409 fatal("ssh_userauth2: internal error: cannot send userauth none request");
411 /* initial userauth request */
412 userauth_none(&authctxt);
414 dispatch_init(&input_userauth_error);
415 dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
416 dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
417 dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
418 dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt); /* loop until success */
420 pubkey_cleanup(&authctxt);
421 dispatch_range(SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
423 #ifdef NONE_CIPHER_ENABLED
425 * If the user explicitly requests to use the none cipher enable it
426 * post authentication and only if the right conditions are met: both
427 * of the NONE switches must be true and there must be no tty allocated.
429 if (options.none_switch == 1 && options.none_enabled == 1) {
431 debug("Requesting none cipher re-keying...");
432 myproposal[PROPOSAL_ENC_ALGS_STOC] = "none";
433 myproposal[PROPOSAL_ENC_ALGS_CTOS] = "none";
434 kex_prop2buf(&xxx_kex->my, myproposal);
435 packet_request_rekeying();
436 fprintf(stderr, "WARNING: enabled NONE cipher\n");
438 /* Requested NONE cipher on an interactive session. */
439 debug("Cannot switch to NONE cipher with tty "
441 fprintf(stderr, "NONE cipher switch disabled given "
442 "a TTY is allocated\n");
446 debug("Authentication succeeded (%s).", authctxt.method->name);
450 userauth(Authctxt *authctxt, char *authlist)
452 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
453 authctxt->method->cleanup(authctxt);
455 free(authctxt->methoddata);
456 authctxt->methoddata = NULL;
457 if (authlist == NULL) {
458 authlist = authctxt->authlist;
460 free(authctxt->authlist);
461 authctxt->authlist = authlist;
464 Authmethod *method = authmethod_get(authlist);
466 fatal("Permission denied (%s).", authlist);
467 authctxt->method = method;
469 /* reset the per method handler */
470 dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
471 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
473 /* and try new method */
474 if (method->userauth(authctxt) != 0) {
475 debug2("we sent a %s packet, wait for reply", method->name);
478 debug2("we did not send a packet, disable method");
479 method->enabled = NULL;
486 input_userauth_error(int type, u_int32_t seq, void *ctxt)
488 fatal("input_userauth_error: bad message during authentication: "
494 input_userauth_banner(int type, u_int32_t seq, void *ctxt)
496 char *msg, *raw, *lang;
499 debug3("input_userauth_banner");
500 raw = packet_get_string(&len);
501 lang = packet_get_string(NULL);
502 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) {
505 msg = xmalloc(len * 4 + 1); /* max expansion from strnvis() */
506 strnvis(msg, raw, len * 4 + 1, VIS_SAFE|VIS_OCTAL|VIS_NOSLASH);
507 fprintf(stderr, "%s", msg);
516 input_userauth_success(int type, u_int32_t seq, void *ctxt)
518 Authctxt *authctxt = ctxt;
520 if (authctxt == NULL)
521 fatal("input_userauth_success: no authentication context");
522 free(authctxt->authlist);
523 authctxt->authlist = NULL;
524 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
525 authctxt->method->cleanup(authctxt);
526 free(authctxt->methoddata);
527 authctxt->methoddata = NULL;
528 authctxt->success = 1; /* break out */
532 input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt)
534 Authctxt *authctxt = ctxt;
536 if (authctxt == NULL)
537 fatal("%s: no authentication context", __func__);
539 fatal("Unexpected authentication success during %s.",
540 authctxt->method->name);
545 input_userauth_failure(int type, u_int32_t seq, void *ctxt)
547 Authctxt *authctxt = ctxt;
548 char *authlist = NULL;
551 if (authctxt == NULL)
552 fatal("input_userauth_failure: no authentication context");
554 authlist = packet_get_string(NULL);
555 partial = packet_get_char();
559 logit("Authenticated with partial success.");
561 pubkey_cleanup(authctxt);
562 pubkey_prepare(authctxt);
564 debug("Authentications that can continue: %s", authlist);
566 userauth(authctxt, authlist);
571 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
573 Authctxt *authctxt = ctxt;
577 int pktype, sent = 0;
582 if (authctxt == NULL)
583 fatal("input_userauth_pk_ok: no authentication context");
584 if (datafellows & SSH_BUG_PKOK) {
585 /* this is similar to SSH_BUG_PKAUTH */
586 debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
587 pkblob = packet_get_string(&blen);
589 buffer_append(&b, pkblob, blen);
590 pkalg = buffer_get_string(&b, &alen);
593 pkalg = packet_get_string(&alen);
594 pkblob = packet_get_string(&blen);
598 debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
600 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
601 debug("unknown pkalg %s", pkalg);
604 if ((key = key_from_blob(pkblob, blen)) == NULL) {
605 debug("no key from blob. pkalg %s", pkalg);
608 if (key->type != pktype) {
609 error("input_userauth_pk_ok: type mismatch "
610 "for decoded key (received %d, expected %d)",
614 fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
615 debug2("input_userauth_pk_ok: fp %s", fp);
619 * search keys in the reverse order, because last candidate has been
620 * moved to the end of the queue. this also avoids confusion by
623 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
624 if (key_equal(key, id->key)) {
625 sent = sign_and_send_pubkey(authctxt, id);
635 /* try another method if we did not send a packet */
637 userauth(authctxt, NULL);
642 userauth_gssapi(Authctxt *authctxt)
644 Gssctxt *gssctxt = NULL;
645 static gss_OID_set gss_supported = NULL;
646 static u_int mech = 0;
650 /* Try one GSSAPI method at a time, rather than sending them all at
653 if (gss_supported == NULL)
654 gss_indicate_mechs(&min, &gss_supported);
656 /* Check to see if the mechanism is usable before we offer it */
657 while (mech < gss_supported->count && !ok) {
658 /* My DER encoding requires length<128 */
659 if (gss_supported->elements[mech].length < 128 &&
660 ssh_gssapi_check_mechanism(&gssctxt,
661 &gss_supported->elements[mech], authctxt->host)) {
662 ok = 1; /* Mechanism works */
671 authctxt->methoddata=(void *)gssctxt;
673 packet_start(SSH2_MSG_USERAUTH_REQUEST);
674 packet_put_cstring(authctxt->server_user);
675 packet_put_cstring(authctxt->service);
676 packet_put_cstring(authctxt->method->name);
680 packet_put_int((gss_supported->elements[mech].length) + 2);
681 packet_put_char(SSH_GSS_OIDTYPE);
682 packet_put_char(gss_supported->elements[mech].length);
683 packet_put_raw(gss_supported->elements[mech].elements,
684 gss_supported->elements[mech].length);
688 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
689 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
690 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
691 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
693 mech++; /* Move along to next candidate */
699 process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
701 Authctxt *authctxt = ctxt;
702 Gssctxt *gssctxt = authctxt->methoddata;
703 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
704 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
705 gss_buffer_desc gssbuf;
706 OM_uint32 status, ms, flags;
709 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
710 recv_tok, &send_tok, &flags);
712 if (send_tok.length > 0) {
713 if (GSS_ERROR(status))
714 packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
716 packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
718 packet_put_string(send_tok.value, send_tok.length);
720 gss_release_buffer(&ms, &send_tok);
723 if (status == GSS_S_COMPLETE) {
724 /* send either complete or MIC, depending on mechanism */
725 if (!(flags & GSS_C_INTEG_FLAG)) {
726 packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
729 ssh_gssapi_buildmic(&b, authctxt->server_user,
730 authctxt->service, "gssapi-with-mic");
732 gssbuf.value = buffer_ptr(&b);
733 gssbuf.length = buffer_len(&b);
735 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
737 if (!GSS_ERROR(status)) {
738 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
739 packet_put_string(mic.value, mic.length);
745 gss_release_buffer(&ms, &mic);
754 input_gssapi_response(int type, u_int32_t plen, void *ctxt)
756 Authctxt *authctxt = ctxt;
761 if (authctxt == NULL)
762 fatal("input_gssapi_response: no authentication context");
763 gssctxt = authctxt->methoddata;
766 oidv = packet_get_string(&oidlen);
769 oidv[0] != SSH_GSS_OIDTYPE ||
770 oidv[1] != oidlen - 2) {
772 debug("Badly encoded mechanism OID received");
773 userauth(authctxt, NULL);
777 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
778 fatal("Server returned different OID than expected");
784 if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
785 /* Start again with next method on list */
786 debug("Trying to start again");
787 userauth(authctxt, NULL);
794 input_gssapi_token(int type, u_int32_t plen, void *ctxt)
796 Authctxt *authctxt = ctxt;
797 gss_buffer_desc recv_tok;
801 if (authctxt == NULL)
802 fatal("input_gssapi_response: no authentication context");
804 recv_tok.value = packet_get_string(&slen);
805 recv_tok.length = slen; /* safe typecast */
809 status = process_gssapi_token(ctxt, &recv_tok);
811 free(recv_tok.value);
813 if (GSS_ERROR(status)) {
814 /* Start again with the next method in the list */
815 userauth(authctxt, NULL);
822 input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
824 Authctxt *authctxt = ctxt;
826 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
827 gss_buffer_desc recv_tok;
831 if (authctxt == NULL)
832 fatal("input_gssapi_response: no authentication context");
833 gssctxt = authctxt->methoddata;
835 recv_tok.value = packet_get_string(&len);
836 recv_tok.length = len;
840 /* Stick it into GSSAPI and see what it says */
841 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
842 &recv_tok, &send_tok, NULL);
844 free(recv_tok.value);
845 gss_release_buffer(&ms, &send_tok);
847 /* Server will be returning a failed packet after this one */
852 input_gssapi_error(int type, u_int32_t plen, void *ctxt)
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);
871 userauth_none(Authctxt *authctxt)
873 /* initial userauth request */
874 packet_start(SSH2_MSG_USERAUTH_REQUEST);
875 packet_put_cstring(authctxt->server_user);
876 packet_put_cstring(authctxt->service);
877 packet_put_cstring(authctxt->method->name);
883 userauth_passwd(Authctxt *authctxt)
885 static int attempt = 0;
888 const char *host = options.host_key_alias ? options.host_key_alias :
891 if (attempt++ >= options.number_of_password_prompts)
895 error("Permission denied, please try again.");
897 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
898 authctxt->server_user, host);
899 password = read_passphrase(prompt, 0);
900 packet_start(SSH2_MSG_USERAUTH_REQUEST);
901 packet_put_cstring(authctxt->server_user);
902 packet_put_cstring(authctxt->service);
903 packet_put_cstring(authctxt->method->name);
905 packet_put_cstring(password);
906 explicit_bzero(password, strlen(password));
908 packet_add_padding(64);
911 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
912 &input_userauth_passwd_changereq);
918 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
922 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
924 Authctxt *authctxt = ctxt;
925 char *info, *lang, *password = NULL, *retype = NULL;
927 const char *host = options.host_key_alias ? options.host_key_alias :
930 debug2("input_userauth_passwd_changereq");
932 if (authctxt == NULL)
933 fatal("input_userauth_passwd_changereq: "
934 "no authentication context");
936 info = packet_get_string(NULL);
937 lang = packet_get_string(NULL);
938 if (strlen(info) > 0)
942 packet_start(SSH2_MSG_USERAUTH_REQUEST);
943 packet_put_cstring(authctxt->server_user);
944 packet_put_cstring(authctxt->service);
945 packet_put_cstring(authctxt->method->name);
946 packet_put_char(1); /* additional info */
947 snprintf(prompt, sizeof(prompt),
948 "Enter %.30s@%.128s's old password: ",
949 authctxt->server_user, host);
950 password = read_passphrase(prompt, 0);
951 packet_put_cstring(password);
952 explicit_bzero(password, strlen(password));
955 while (password == NULL) {
956 snprintf(prompt, sizeof(prompt),
957 "Enter %.30s@%.128s's new password: ",
958 authctxt->server_user, host);
959 password = read_passphrase(prompt, RP_ALLOW_EOF);
960 if (password == NULL) {
964 snprintf(prompt, sizeof(prompt),
965 "Retype %.30s@%.128s's new password: ",
966 authctxt->server_user, host);
967 retype = read_passphrase(prompt, 0);
968 if (strcmp(password, retype) != 0) {
969 explicit_bzero(password, strlen(password));
971 logit("Mismatch; try again, EOF to quit.");
974 explicit_bzero(retype, strlen(retype));
977 packet_put_cstring(password);
978 explicit_bzero(password, strlen(password));
980 packet_add_padding(64);
983 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
984 &input_userauth_passwd_changereq);
988 identity_sign(Identity *id, u_char **sigp, u_int *lenp,
989 u_char *data, u_int datalen)
994 /* the agent supports this key */
996 return (ssh_agent_sign(id->ac, id->key, sigp, lenp,
999 * we have already loaded the private key or
1000 * the private key is stored in external hardware
1002 if (id->isprivate || (id->key->flags & KEY_FLAG_EXT))
1003 return (key_sign(id->key, sigp, lenp, data, datalen));
1004 /* load the private key from the file */
1005 if ((prv = load_identity_file(id->filename, id->userprovided)) == NULL)
1007 ret = key_sign(prv, sigp, lenp, data, datalen);
1013 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1016 u_char *blob, *signature;
1017 u_int bloblen, slen;
1023 fp = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
1024 debug3("sign_and_send_pubkey: %s %s", key_type(id->key), fp);
1027 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1028 /* we cannot handle this key */
1029 debug3("sign_and_send_pubkey: cannot handle key");
1032 /* data to be signed */
1034 if (datafellows & SSH_OLD_SESSIONID) {
1035 buffer_append(&b, session_id2, session_id2_len);
1036 skip = session_id2_len;
1038 buffer_put_string(&b, session_id2, session_id2_len);
1039 skip = buffer_len(&b);
1041 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1042 buffer_put_cstring(&b, authctxt->server_user);
1043 buffer_put_cstring(&b,
1044 datafellows & SSH_BUG_PKSERVICE ?
1047 if (datafellows & SSH_BUG_PKAUTH) {
1048 buffer_put_char(&b, have_sig);
1050 buffer_put_cstring(&b, authctxt->method->name);
1051 buffer_put_char(&b, have_sig);
1052 buffer_put_cstring(&b, key_ssh_name(id->key));
1054 buffer_put_string(&b, blob, bloblen);
1056 /* generate signature */
1057 ret = identity_sign(id, &signature, &slen,
1058 buffer_ptr(&b), buffer_len(&b));
1067 if (datafellows & SSH_BUG_PKSERVICE) {
1069 buffer_append(&b, session_id2, session_id2_len);
1070 skip = session_id2_len;
1071 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1072 buffer_put_cstring(&b, authctxt->server_user);
1073 buffer_put_cstring(&b, authctxt->service);
1074 buffer_put_cstring(&b, authctxt->method->name);
1075 buffer_put_char(&b, have_sig);
1076 if (!(datafellows & SSH_BUG_PKAUTH))
1077 buffer_put_cstring(&b, key_ssh_name(id->key));
1078 buffer_put_string(&b, blob, bloblen);
1082 /* append signature */
1083 buffer_put_string(&b, signature, slen);
1086 /* skip session id and packet type */
1087 if (buffer_len(&b) < skip + 1)
1088 fatal("userauth_pubkey: internal error");
1089 buffer_consume(&b, skip + 1);
1091 /* put remaining data from buffer into packet */
1092 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1093 packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1101 send_pubkey_test(Authctxt *authctxt, Identity *id)
1104 u_int bloblen, have_sig = 0;
1106 debug3("send_pubkey_test");
1108 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1109 /* we cannot handle this key */
1110 debug3("send_pubkey_test: cannot handle key");
1113 /* register callback for USERAUTH_PK_OK message */
1114 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1116 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1117 packet_put_cstring(authctxt->server_user);
1118 packet_put_cstring(authctxt->service);
1119 packet_put_cstring(authctxt->method->name);
1120 packet_put_char(have_sig);
1121 if (!(datafellows & SSH_BUG_PKAUTH))
1122 packet_put_cstring(key_ssh_name(id->key));
1123 packet_put_string(blob, bloblen);
1130 load_identity_file(char *filename, int userprovided)
1133 char prompt[300], *passphrase;
1134 int perm_ok = 0, quit, i;
1137 if (stat(filename, &st) < 0) {
1138 (userprovided ? logit : debug3)("no such identity: %s: %s",
1139 filename, strerror(errno));
1142 private = key_load_private_type(KEY_UNSPEC, filename, "", NULL, &perm_ok);
1144 if (private != NULL)
1148 if (private == NULL) {
1149 if (options.batch_mode)
1151 snprintf(prompt, sizeof prompt,
1152 "Enter passphrase for key '%.100s': ", filename);
1153 for (i = 0; i < options.number_of_password_prompts; i++) {
1154 passphrase = read_passphrase(prompt, 0);
1155 if (strcmp(passphrase, "") != 0) {
1156 private = key_load_private_type(KEY_UNSPEC,
1157 filename, passphrase, NULL, NULL);
1160 debug2("no passphrase given, try next key");
1163 explicit_bzero(passphrase, strlen(passphrase));
1165 if (private != NULL || quit)
1167 debug2("bad passphrase given, try again...");
1174 * try keys in the following order:
1175 * 1. agent keys that are found in the config file
1176 * 2. other agent keys
1177 * 3. keys that are only listed in the config file
1180 pubkey_prepare(Authctxt *authctxt)
1182 Identity *id, *id2, *tmp;
1183 Idlist agent, files, *preferred;
1185 AuthenticationConnection *ac;
1189 TAILQ_INIT(&agent); /* keys from the agent */
1190 TAILQ_INIT(&files); /* keys from the config file */
1191 preferred = &authctxt->keys;
1192 TAILQ_INIT(preferred); /* preferred order of keys */
1194 /* list of keys stored in the filesystem and PKCS#11 */
1195 for (i = 0; i < options.num_identity_files; i++) {
1196 key = options.identity_keys[i];
1197 if (key && key->type == KEY_RSA1)
1199 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1201 options.identity_keys[i] = NULL;
1202 id = xcalloc(1, sizeof(*id));
1204 id->filename = xstrdup(options.identity_files[i]);
1205 id->userprovided = options.identity_file_userprovided[i];
1206 TAILQ_INSERT_TAIL(&files, id, next);
1208 /* Prefer PKCS11 keys that are explicitly listed */
1209 TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1210 if (id->key == NULL || (id->key->flags & KEY_FLAG_EXT) == 0)
1213 TAILQ_FOREACH(id2, &files, next) {
1214 if (id2->key == NULL ||
1215 (id2->key->flags & KEY_FLAG_EXT) != 0)
1217 if (key_equal(id->key, id2->key)) {
1218 TAILQ_REMOVE(&files, id, next);
1219 TAILQ_INSERT_TAIL(preferred, id, next);
1224 /* If IdentitiesOnly set and key not found then don't use it */
1225 if (!found && options.identities_only) {
1226 TAILQ_REMOVE(&files, id, next);
1227 explicit_bzero(id, sizeof(*id));
1231 /* list of keys supported by the agent */
1232 if ((ac = ssh_get_authentication_connection())) {
1233 for (key = ssh_get_first_identity(ac, &comment, 2);
1235 key = ssh_get_next_identity(ac, &comment, 2)) {
1237 TAILQ_FOREACH(id, &files, next) {
1238 /* agent keys from the config file are preferred */
1239 if (key_equal(key, id->key)) {
1242 TAILQ_REMOVE(&files, id, next);
1243 TAILQ_INSERT_TAIL(preferred, id, next);
1249 if (!found && !options.identities_only) {
1250 id = xcalloc(1, sizeof(*id));
1252 id->filename = comment;
1254 TAILQ_INSERT_TAIL(&agent, id, next);
1257 /* append remaining agent keys */
1258 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1259 TAILQ_REMOVE(&agent, id, next);
1260 TAILQ_INSERT_TAIL(preferred, id, next);
1262 authctxt->agent = ac;
1264 /* append remaining keys from the config file */
1265 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1266 TAILQ_REMOVE(&files, id, next);
1267 TAILQ_INSERT_TAIL(preferred, id, next);
1269 TAILQ_FOREACH(id, preferred, next) {
1270 debug2("key: %s (%p),%s", id->filename, id->key,
1271 id->userprovided ? " explicit" : "");
1276 pubkey_cleanup(Authctxt *authctxt)
1280 if (authctxt->agent != NULL)
1281 ssh_close_authentication_connection(authctxt->agent);
1282 for (id = TAILQ_FIRST(&authctxt->keys); id;
1283 id = TAILQ_FIRST(&authctxt->keys)) {
1284 TAILQ_REMOVE(&authctxt->keys, id, next);
1293 userauth_pubkey(Authctxt *authctxt)
1298 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1301 /* move key to the end of the queue */
1302 TAILQ_REMOVE(&authctxt->keys, id, next);
1303 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1305 * send a test message if we have the public key. for
1306 * encrypted keys we cannot do this and have to load the
1307 * private key instead
1309 if (id->key != NULL) {
1310 if (key_type_plain(id->key->type) == KEY_RSA &&
1311 (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1312 debug("Skipped %s key %s for RSA/MD5 server",
1313 key_type(id->key), id->filename);
1314 } else if (id->key->type != KEY_RSA1) {
1315 debug("Offering %s public key: %s",
1316 key_type(id->key), id->filename);
1317 sent = send_pubkey_test(authctxt, id);
1320 debug("Trying private key: %s", id->filename);
1321 id->key = load_identity_file(id->filename,
1323 if (id->key != NULL) {
1325 if (key_type_plain(id->key->type) == KEY_RSA &&
1326 (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1327 debug("Skipped %s key %s for RSA/MD5 "
1328 "server", key_type(id->key),
1331 sent = sign_and_send_pubkey(
1345 * Send userauth request message specifying keyboard-interactive method.
1348 userauth_kbdint(Authctxt *authctxt)
1350 static int attempt = 0;
1352 if (attempt++ >= options.number_of_password_prompts)
1354 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1355 if (attempt > 1 && !authctxt->info_req_seen) {
1356 debug3("userauth_kbdint: disable: no info_req_seen");
1357 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1361 debug2("userauth_kbdint");
1362 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1363 packet_put_cstring(authctxt->server_user);
1364 packet_put_cstring(authctxt->service);
1365 packet_put_cstring(authctxt->method->name);
1366 packet_put_cstring(""); /* lang */
1367 packet_put_cstring(options.kbd_interactive_devices ?
1368 options.kbd_interactive_devices : "");
1371 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1376 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1379 input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1381 Authctxt *authctxt = ctxt;
1382 char *name, *inst, *lang, *prompt, *response;
1383 u_int num_prompts, i;
1386 debug2("input_userauth_info_req");
1388 if (authctxt == NULL)
1389 fatal("input_userauth_info_req: no authentication context");
1391 authctxt->info_req_seen = 1;
1393 name = packet_get_string(NULL);
1394 inst = packet_get_string(NULL);
1395 lang = packet_get_string(NULL);
1396 if (strlen(name) > 0)
1398 if (strlen(inst) > 0)
1404 num_prompts = packet_get_int();
1406 * Begin to build info response packet based on prompts requested.
1407 * We commit to providing the correct number of responses, so if
1408 * further on we run into a problem that prevents this, we have to
1409 * be sure and clean this up and send a correct error response.
1411 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1412 packet_put_int(num_prompts);
1414 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1415 for (i = 0; i < num_prompts; i++) {
1416 prompt = packet_get_string(NULL);
1417 echo = packet_get_char();
1419 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1421 packet_put_cstring(response);
1422 explicit_bzero(response, strlen(response));
1426 packet_check_eom(); /* done with parsing incoming message. */
1428 packet_add_padding(64);
1433 ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1434 u_char *data, u_int datalen)
1439 int to[2], from[2], status, version = 2;
1441 debug2("ssh_keysign called");
1443 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1444 error("ssh_keysign: not installed: %s", strerror(errno));
1447 if (fflush(stdout) != 0)
1448 error("ssh_keysign: fflush: %s", strerror(errno));
1450 error("ssh_keysign: pipe: %s", strerror(errno));
1453 if (pipe(from) < 0) {
1454 error("ssh_keysign: pipe: %s", strerror(errno));
1457 if ((pid = fork()) < 0) {
1458 error("ssh_keysign: fork: %s", strerror(errno));
1462 /* keep the socket on exec */
1463 fcntl(packet_get_connection_in(), F_SETFD, 0);
1464 permanently_drop_suid(getuid());
1466 if (dup2(from[1], STDOUT_FILENO) < 0)
1467 fatal("ssh_keysign: dup2: %s", strerror(errno));
1469 if (dup2(to[0], STDIN_FILENO) < 0)
1470 fatal("ssh_keysign: dup2: %s", strerror(errno));
1473 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1474 fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1481 buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1482 buffer_put_string(&b, data, datalen);
1483 if (ssh_msg_send(to[1], version, &b) == -1)
1484 fatal("ssh_keysign: couldn't send request");
1486 if (ssh_msg_recv(from[0], &b) < 0) {
1487 error("ssh_keysign: no reply");
1494 while (waitpid(pid, &status, 0) < 0)
1498 if (buffer_get_char(&b) != version) {
1499 error("ssh_keysign: bad version");
1503 *sigp = buffer_get_string(&b, lenp);
1510 userauth_hostbased(Authctxt *authctxt)
1512 Key *private = NULL;
1513 Sensitive *sensitive = authctxt->sensitive;
1515 u_char *signature, *blob;
1516 char *chost, *pkalg, *p;
1517 const char *service;
1519 int ok, i, found = 0;
1521 /* check for a useful key */
1522 for (i = 0; i < sensitive->nkeys; i++) {
1523 private = sensitive->keys[i];
1524 if (private && private->type != KEY_RSA1) {
1526 /* we take and free the key */
1527 sensitive->keys[i] = NULL;
1532 debug("No more client hostkeys for hostbased authentication.");
1535 if (key_to_blob(private, &blob, &blen) == 0) {
1539 /* figure out a name for the client host */
1540 p = get_local_name(packet_get_connection_in());
1542 error("userauth_hostbased: cannot get local ipaddr/name");
1547 xasprintf(&chost, "%s.", p);
1548 debug2("userauth_hostbased: chost %s", chost);
1551 service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1553 pkalg = xstrdup(key_ssh_name(private));
1555 /* construct data */
1556 buffer_put_string(&b, session_id2, session_id2_len);
1557 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1558 buffer_put_cstring(&b, authctxt->server_user);
1559 buffer_put_cstring(&b, service);
1560 buffer_put_cstring(&b, authctxt->method->name);
1561 buffer_put_cstring(&b, pkalg);
1562 buffer_put_string(&b, blob, blen);
1563 buffer_put_cstring(&b, chost);
1564 buffer_put_cstring(&b, authctxt->local_user);
1568 if (sensitive->external_keysign)
1569 ok = ssh_keysign(private, &signature, &slen,
1570 buffer_ptr(&b), buffer_len(&b));
1572 ok = key_sign(private, &signature, &slen,
1573 buffer_ptr(&b), buffer_len(&b));
1577 error("key_sign failed");
1583 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1584 packet_put_cstring(authctxt->server_user);
1585 packet_put_cstring(authctxt->service);
1586 packet_put_cstring(authctxt->method->name);
1587 packet_put_cstring(pkalg);
1588 packet_put_string(blob, blen);
1589 packet_put_cstring(chost);
1590 packet_put_cstring(authctxt->local_user);
1591 packet_put_string(signature, slen);
1592 explicit_bzero(signature, slen);
1602 /* find auth method */
1605 * given auth method name, if configurable options permit this method fill
1606 * in auth_ident field and return true, otherwise return false.
1609 authmethod_is_enabled(Authmethod *method)
1613 /* return false if options indicate this method is disabled */
1614 if (method->enabled == NULL || *method->enabled == 0)
1616 /* return false if batch mode is enabled but method needs interactive mode */
1617 if (method->batch_flag != NULL && *method->batch_flag != 0)
1623 authmethod_lookup(const char *name)
1625 Authmethod *method = NULL;
1627 for (method = authmethods; method->name != NULL; method++)
1628 if (strcmp(name, method->name) == 0)
1630 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1634 /* XXX internal state */
1635 static Authmethod *current = NULL;
1636 static char *supported = NULL;
1637 static char *preferred = NULL;
1640 * Given the authentication method list sent by the server, return the
1641 * next method we should try. If the server initially sends a nil list,
1642 * use a built-in default list.
1645 authmethod_get(char *authlist)
1650 /* Use a suitable default if we're passed a nil list. */
1651 if (authlist == NULL || strlen(authlist) == 0)
1652 authlist = options.preferred_authentications;
1654 if (supported == NULL || strcmp(authlist, supported) != 0) {
1655 debug3("start over, passed a different list %s", authlist);
1657 supported = xstrdup(authlist);
1658 preferred = options.preferred_authentications;
1659 debug3("preferred %s", preferred);
1661 } else if (current != NULL && authmethod_is_enabled(current))
1665 if ((name = match_list(preferred, supported, &next)) == NULL) {
1666 debug("No more authentication methods to try.");
1671 debug3("authmethod_lookup %s", name);
1672 debug3("remaining preferred: %s", preferred);
1673 if ((current = authmethod_lookup(name)) != NULL &&
1674 authmethod_is_enabled(current)) {
1675 debug3("authmethod_is_enabled %s", name);
1676 debug("Next authentication method: %s", name);
1685 authmethods_get(void)
1687 Authmethod *method = NULL;
1692 for (method = authmethods; method->name != NULL; method++) {
1693 if (authmethod_is_enabled(method)) {
1694 if (buffer_len(&b) > 0)
1695 buffer_append(&b, ",", 1);
1696 buffer_append(&b, method->name, strlen(method->name));
1699 buffer_append(&b, "\0", 1);
1700 list = xstrdup(buffer_ptr(&b));