drm/radeon: Finish replacing task queues by Linux work queues
[dragonfly.git] / crypto / openssh / sshconnect2.c
blobbe9397e481bd658f4ec55e616d56076864f2d750
1 /* $OpenBSD: sshconnect2.c,v 1.266 2017/08/27 00:38:41 dtucker Exp $ */
2 /*
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
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
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.
27 #include "includes.h"
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <sys/wait.h>
32 #include <sys/stat.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <netdb.h>
37 #include <pwd.h>
38 #include <signal.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <unistd.h>
43 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
44 #include <vis.h>
45 #endif
47 #include "openbsd-compat/sys-queue.h"
49 #include "xmalloc.h"
50 #include "ssh.h"
51 #include "ssh2.h"
52 #include "buffer.h"
53 #include "packet.h"
54 #include "compat.h"
55 #include "cipher.h"
56 #include "key.h"
57 #include "kex.h"
58 #include "myproposal.h"
59 #include "sshconnect.h"
60 #include "authfile.h"
61 #include "dh.h"
62 #include "authfd.h"
63 #include "log.h"
64 #include "misc.h"
65 #include "readconf.h"
66 #include "match.h"
67 #include "dispatch.h"
68 #include "canohost.h"
69 #include "msg.h"
70 #include "pathnames.h"
71 #include "uidswap.h"
72 #include "hostfile.h"
73 #include "ssherr.h"
74 #include "utf8.h"
76 #ifdef GSSAPI
77 #include "ssh-gss.h"
78 #endif
80 /* import */
81 extern char *client_version_string;
82 extern char *server_version_string;
83 extern Options options;
86 * SSH2 key exchange
89 u_char *session_id2 = NULL;
90 u_int session_id2_len = 0;
92 char *xxx_host;
93 struct sockaddr *xxx_hostaddr;
95 static int
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.");
100 return 0;
103 static char *
104 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
106 char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
107 size_t maxlen;
108 struct hostkeys *hostkeys;
109 int ktype;
110 u_int i;
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) \
127 do { \
128 if (*to != '\0') \
129 strlcat(to, ",", maxlen); \
130 strlcat(to, from, maxlen); \
131 } while (0)
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);
139 else
140 ALG_APPEND(last, alg);
142 #undef ALG_APPEND
143 xasprintf(&ret, "%s%s%s", first,
144 (*first == '\0' || *last == '\0') ? "" : ",", last);
145 if (*first != '\0')
146 debug3("%s: prefer hostkeyalgs: %s", __func__, first);
148 free(first);
149 free(last);
150 free(hostname);
151 free(oavail);
152 free_hostkeys(hostkeys);
154 return ret;
157 void
158 ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
160 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
161 char *s;
162 struct kex *kex;
163 int r;
165 xxx_host = host;
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);
186 } else {
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;
203 #ifdef WITH_OPENSSL
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;
213 # endif
214 #endif
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;
231 #ifdef DEBUG_KEXDH
232 /* send 1st encrypted/maced/compressed message */
233 packet_start(SSH2_MSG_IGNORE);
234 packet_put_cstring("markus");
235 packet_send();
236 packet_write_wait();
237 #endif
241 * Authenticate user
244 typedef struct cauthctxt Authctxt;
245 typedef struct cauthmethod Authmethod;
246 typedef struct identity Identity;
247 typedef struct idlist Idlist;
249 struct identity {
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 */
254 int tried;
255 int isprivate; /* key points to the private key */
256 int userprovided;
258 TAILQ_HEAD(idlist, identity);
260 struct cauthctxt {
261 const char *server_user;
262 const char *local_user;
263 const char *host;
264 const char *service;
265 struct cauthmethod *method;
266 sig_atomic_t success;
267 char *authlist;
268 int attempt;
269 /* pubkey */
270 struct idlist keys;
271 int agent_fd;
272 /* hostbased */
273 Sensitive *sensitive;
274 char *oktypes, *ktypes;
275 const char *active_ktype;
276 /* kbd-interactive */
277 int info_req_seen;
278 /* generic */
279 void *methoddata;
282 struct cauthmethod {
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 *);
307 #ifdef GSSAPI
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 *);
314 #endif
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[] = {
329 #ifdef GSSAPI
330 {"gssapi-with-mic",
331 userauth_gssapi,
332 NULL,
333 &options.gss_authentication,
334 NULL},
335 #endif
336 {"hostbased",
337 userauth_hostbased,
338 NULL,
339 &options.hostbased_authentication,
340 NULL},
341 {"publickey",
342 userauth_pubkey,
343 NULL,
344 &options.pubkey_authentication,
345 NULL},
346 {"keyboard-interactive",
347 userauth_kbdint,
348 NULL,
349 &options.kbd_interactive_authentication,
350 &options.batch_mode},
351 {"password",
352 userauth_passwd,
353 NULL,
354 &options.password_authentication,
355 &options.batch_mode},
356 {"none",
357 userauth_none,
358 NULL,
359 NULL,
360 NULL},
361 {NULL, NULL, NULL, NULL, NULL}
364 void
365 ssh_userauth2(const char *local_user, const char *server_user, char *host,
366 Sensitive *sensitive)
368 struct ssh *ssh = active_state;
369 Authctxt authctxt;
370 int r;
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);
415 /* ARGSUSED */
417 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
419 Authctxt *authctxt = ssh->authctxt;
420 int r;
422 if (ssh_packet_remaining(ssh) > 0) {
423 char *reply;
425 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
426 goto out;
427 debug2("service_accept: %s", reply);
428 free(reply);
429 } else {
430 debug2("buggy server: service_accept w/o service");
432 if ((r = sshpkt_get_end(ssh)) != 0)
433 goto out;
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);
443 r = 0;
444 out:
445 return r;
448 /* ARGSUSED */
450 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh)
452 return kex_input_ext_info(type, seqnr, ssh);
455 void
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;
465 } else {
466 free(authctxt->authlist);
467 authctxt->authlist = authlist;
469 for (;;) {
470 Authmethod *method = authmethod_get(authlist);
471 if (method == NULL)
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);
483 break;
484 } else {
485 debug2("we did not send a packet, disable method");
486 method->enabled = NULL;
491 /* ARGSUSED */
493 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
495 fatal("input_userauth_error: bad message during authentication: "
496 "type %d", type);
497 return 0;
500 /* ARGSUSED */
502 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
504 char *msg, *lang;
505 u_int len;
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);
512 free(msg);
513 free(lang);
514 return 0;
517 /* ARGSUSED */
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 */
532 return 0;
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);
545 return 0;
548 /* ARGSUSED */
550 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
552 Authctxt *authctxt = ssh->authctxt;
553 char *authlist = NULL;
554 int partial;
556 if (authctxt == NULL)
557 fatal("input_userauth_failure: no authentication context");
559 authlist = packet_get_string(NULL);
560 partial = packet_get_char();
561 packet_check_eom();
563 if (partial != 0) {
564 verbose("Authenticated with partial success.");
565 /* reset state */
566 pubkey_reset(authctxt);
568 debug("Authentications that can continue: %s", authlist);
570 userauth(authctxt, authlist);
571 return 0;
574 /* ARGSUSED */
576 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
578 Authctxt *authctxt = ssh->authctxt;
579 struct sshkey *key = NULL;
580 Identity *id = NULL;
581 Buffer b;
582 int pktype, sent = 0;
583 u_int alen, blen;
584 char *pkalg, *fp;
585 u_char *pkblob;
587 if (authctxt == NULL)
588 fatal("input_userauth_pk_ok: no authentication context");
589 if (datafellows & SSH_BUG_PKOK) {
590 /* this is similar to SSH_BUG_PKAUTH */
591 debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
592 pkblob = packet_get_string(&blen);
593 buffer_init(&b);
594 buffer_append(&b, pkblob, blen);
595 pkalg = buffer_get_string(&b, &alen);
596 buffer_free(&b);
597 } else {
598 pkalg = packet_get_string(&alen);
599 pkblob = packet_get_string(&blen);
601 packet_check_eom();
603 debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
605 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
606 debug("unknown pkalg %s", pkalg);
607 goto done;
609 if ((key = key_from_blob(pkblob, blen)) == NULL) {
610 debug("no key from blob. pkalg %s", pkalg);
611 goto done;
613 if (key->type != pktype) {
614 error("input_userauth_pk_ok: type mismatch "
615 "for decoded key (received %d, expected %d)",
616 key->type, pktype);
617 goto done;
619 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
620 SSH_FP_DEFAULT)) == NULL)
621 goto done;
622 debug2("input_userauth_pk_ok: fp %s", fp);
623 free(fp);
626 * search keys in the reverse order, because last candidate has been
627 * moved to the end of the queue. this also avoids confusion by
628 * duplicate keys
630 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
631 if (key_equal(key, id->key)) {
632 sent = sign_and_send_pubkey(authctxt, id);
633 break;
636 done:
637 if (key != NULL)
638 key_free(key);
639 free(pkalg);
640 free(pkblob);
642 /* try another method if we did not send a packet */
643 if (sent == 0)
644 userauth(authctxt, NULL);
645 return 0;
648 #ifdef GSSAPI
650 userauth_gssapi(Authctxt *authctxt)
652 Gssctxt *gssctxt = NULL;
653 static gss_OID_set gss_supported = NULL;
654 static u_int mech = 0;
655 OM_uint32 min;
656 int ok = 0;
658 /* Try one GSSAPI method at a time, rather than sending them all at
659 * once. */
661 if (gss_supported == NULL)
662 gss_indicate_mechs(&min, &gss_supported);
664 /* Check to see if the mechanism is usable before we offer it */
665 while (mech < gss_supported->count && !ok) {
666 /* My DER encoding requires length<128 */
667 if (gss_supported->elements[mech].length < 128 &&
668 ssh_gssapi_check_mechanism(&gssctxt,
669 &gss_supported->elements[mech], authctxt->host)) {
670 ok = 1; /* Mechanism works */
671 } else {
672 mech++;
676 if (!ok)
677 return 0;
679 authctxt->methoddata=(void *)gssctxt;
681 packet_start(SSH2_MSG_USERAUTH_REQUEST);
682 packet_put_cstring(authctxt->server_user);
683 packet_put_cstring(authctxt->service);
684 packet_put_cstring(authctxt->method->name);
686 packet_put_int(1);
688 packet_put_int((gss_supported->elements[mech].length) + 2);
689 packet_put_char(SSH_GSS_OIDTYPE);
690 packet_put_char(gss_supported->elements[mech].length);
691 packet_put_raw(gss_supported->elements[mech].elements,
692 gss_supported->elements[mech].length);
694 packet_send();
696 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
697 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
698 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
699 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
701 mech++; /* Move along to next candidate */
703 return 1;
706 static OM_uint32
707 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
709 Authctxt *authctxt = ssh->authctxt;
710 Gssctxt *gssctxt = authctxt->methoddata;
711 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
712 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
713 gss_buffer_desc gssbuf;
714 OM_uint32 status, ms, flags;
715 Buffer b;
717 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
718 recv_tok, &send_tok, &flags);
720 if (send_tok.length > 0) {
721 if (GSS_ERROR(status))
722 packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
723 else
724 packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
726 packet_put_string(send_tok.value, send_tok.length);
727 packet_send();
728 gss_release_buffer(&ms, &send_tok);
731 if (status == GSS_S_COMPLETE) {
732 /* send either complete or MIC, depending on mechanism */
733 if (!(flags & GSS_C_INTEG_FLAG)) {
734 packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
735 packet_send();
736 } else {
737 ssh_gssapi_buildmic(&b, authctxt->server_user,
738 authctxt->service, "gssapi-with-mic");
740 gssbuf.value = buffer_ptr(&b);
741 gssbuf.length = buffer_len(&b);
743 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
745 if (!GSS_ERROR(status)) {
746 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
747 packet_put_string(mic.value, mic.length);
749 packet_send();
752 buffer_free(&b);
753 gss_release_buffer(&ms, &mic);
757 return status;
760 /* ARGSUSED */
762 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
764 Authctxt *authctxt = ssh->authctxt;
765 Gssctxt *gssctxt;
766 int oidlen;
767 char *oidv;
769 if (authctxt == NULL)
770 fatal("input_gssapi_response: no authentication context");
771 gssctxt = authctxt->methoddata;
773 /* Setup our OID */
774 oidv = packet_get_string(&oidlen);
776 if (oidlen <= 2 ||
777 oidv[0] != SSH_GSS_OIDTYPE ||
778 oidv[1] != oidlen - 2) {
779 free(oidv);
780 debug("Badly encoded mechanism OID received");
781 userauth(authctxt, NULL);
782 return 0;
785 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
786 fatal("Server returned different OID than expected");
788 packet_check_eom();
790 free(oidv);
792 if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
793 /* Start again with next method on list */
794 debug("Trying to start again");
795 userauth(authctxt, NULL);
796 return 0;
798 return 0;
801 /* ARGSUSED */
803 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
805 Authctxt *authctxt = ssh->authctxt;
806 gss_buffer_desc recv_tok;
807 OM_uint32 status;
808 u_int slen;
810 if (authctxt == NULL)
811 fatal("input_gssapi_response: no authentication context");
813 recv_tok.value = packet_get_string(&slen);
814 recv_tok.length = slen; /* safe typecast */
816 packet_check_eom();
818 status = process_gssapi_token(ssh, &recv_tok);
820 free(recv_tok.value);
822 if (GSS_ERROR(status)) {
823 /* Start again with the next method in the list */
824 userauth(authctxt, NULL);
825 return 0;
827 return 0;
830 /* ARGSUSED */
832 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
834 Authctxt *authctxt = ssh->authctxt;
835 Gssctxt *gssctxt;
836 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
837 gss_buffer_desc recv_tok;
838 OM_uint32 ms;
839 u_int len;
841 if (authctxt == NULL)
842 fatal("input_gssapi_response: no authentication context");
843 gssctxt = authctxt->methoddata;
845 recv_tok.value = packet_get_string(&len);
846 recv_tok.length = len;
848 packet_check_eom();
850 /* Stick it into GSSAPI and see what it says */
851 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
852 &recv_tok, &send_tok, NULL);
854 free(recv_tok.value);
855 gss_release_buffer(&ms, &send_tok);
857 /* Server will be returning a failed packet after this one */
858 return 0;
861 /* ARGSUSED */
863 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
865 char *msg;
866 char *lang;
868 /* maj */(void)packet_get_int();
869 /* min */(void)packet_get_int();
870 msg=packet_get_string(NULL);
871 lang=packet_get_string(NULL);
873 packet_check_eom();
875 debug("Server GSSAPI Error:\n%s", msg);
876 free(msg);
877 free(lang);
878 return 0;
880 #endif /* GSSAPI */
883 userauth_none(Authctxt *authctxt)
885 /* initial userauth request */
886 packet_start(SSH2_MSG_USERAUTH_REQUEST);
887 packet_put_cstring(authctxt->server_user);
888 packet_put_cstring(authctxt->service);
889 packet_put_cstring(authctxt->method->name);
890 packet_send();
891 return 1;
895 userauth_passwd(Authctxt *authctxt)
897 static int attempt = 0;
898 char prompt[256];
899 char *password;
900 const char *host = options.host_key_alias ? options.host_key_alias :
901 authctxt->host;
903 if (attempt++ >= options.number_of_password_prompts)
904 return 0;
906 if (attempt != 1)
907 error("Permission denied, please try again.");
909 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
910 authctxt->server_user, host);
911 password = read_passphrase(prompt, 0);
912 packet_start(SSH2_MSG_USERAUTH_REQUEST);
913 packet_put_cstring(authctxt->server_user);
914 packet_put_cstring(authctxt->service);
915 packet_put_cstring(authctxt->method->name);
916 packet_put_char(0);
917 packet_put_cstring(password);
918 explicit_bzero(password, strlen(password));
919 free(password);
920 packet_add_padding(64);
921 packet_send();
923 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
924 &input_userauth_passwd_changereq);
926 return 1;
930 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
932 /* ARGSUSED */
934 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
936 Authctxt *authctxt = ssh->authctxt;
937 char *info, *lang, *password = NULL, *retype = NULL;
938 char prompt[256];
939 const char *host;
941 debug2("input_userauth_passwd_changereq");
943 if (authctxt == NULL)
944 fatal("input_userauth_passwd_changereq: "
945 "no authentication context");
946 host = options.host_key_alias ? options.host_key_alias : authctxt->host;
948 info = packet_get_string(NULL);
949 lang = packet_get_string(NULL);
950 if (strlen(info) > 0)
951 logit("%s", info);
952 free(info);
953 free(lang);
954 packet_start(SSH2_MSG_USERAUTH_REQUEST);
955 packet_put_cstring(authctxt->server_user);
956 packet_put_cstring(authctxt->service);
957 packet_put_cstring(authctxt->method->name);
958 packet_put_char(1); /* additional info */
959 snprintf(prompt, sizeof(prompt),
960 "Enter %.30s@%.128s's old password: ",
961 authctxt->server_user, host);
962 password = read_passphrase(prompt, 0);
963 packet_put_cstring(password);
964 explicit_bzero(password, strlen(password));
965 free(password);
966 password = NULL;
967 while (password == NULL) {
968 snprintf(prompt, sizeof(prompt),
969 "Enter %.30s@%.128s's new password: ",
970 authctxt->server_user, host);
971 password = read_passphrase(prompt, RP_ALLOW_EOF);
972 if (password == NULL) {
973 /* bail out */
974 return 0;
976 snprintf(prompt, sizeof(prompt),
977 "Retype %.30s@%.128s's new password: ",
978 authctxt->server_user, host);
979 retype = read_passphrase(prompt, 0);
980 if (strcmp(password, retype) != 0) {
981 explicit_bzero(password, strlen(password));
982 free(password);
983 logit("Mismatch; try again, EOF to quit.");
984 password = NULL;
986 explicit_bzero(retype, strlen(retype));
987 free(retype);
989 packet_put_cstring(password);
990 explicit_bzero(password, strlen(password));
991 free(password);
992 packet_add_padding(64);
993 packet_send();
995 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
996 &input_userauth_passwd_changereq);
997 return 0;
1000 static const char *
1001 key_sign_encode(const struct sshkey *key)
1003 struct ssh *ssh = active_state;
1005 if (key->type == KEY_RSA) {
1006 switch (ssh->kex->rsa_sha2) {
1007 case 256:
1008 return "rsa-sha2-256";
1009 case 512:
1010 return "rsa-sha2-512";
1013 return key_ssh_name(key);
1016 static int
1017 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1018 const u_char *data, size_t datalen, u_int compat)
1020 struct sshkey *prv;
1021 int ret;
1023 /* the agent supports this key */
1024 if (id->key != NULL && id->agent_fd != -1)
1025 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1026 data, datalen, key_sign_encode(id->key), compat);
1029 * we have already loaded the private key or
1030 * the private key is stored in external hardware
1032 if (id->key != NULL &&
1033 (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT)))
1034 return (sshkey_sign(id->key, sigp, lenp, data, datalen,
1035 key_sign_encode(id->key), compat));
1037 /* load the private key from the file */
1038 if ((prv = load_identity_file(id)) == NULL)
1039 return SSH_ERR_KEY_NOT_FOUND;
1040 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1041 error("%s: private key %s contents do not match public",
1042 __func__, id->filename);
1043 return SSH_ERR_KEY_NOT_FOUND;
1045 ret = sshkey_sign(prv, sigp, lenp, data, datalen,
1046 key_sign_encode(prv), compat);
1047 sshkey_free(prv);
1048 return (ret);
1051 static int
1052 id_filename_matches(Identity *id, Identity *private_id)
1054 const char *suffixes[] = { ".pub", "-cert.pub", NULL };
1055 size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1056 size_t i, slen;
1058 if (strcmp(id->filename, private_id->filename) == 0)
1059 return 1;
1060 for (i = 0; suffixes[i]; i++) {
1061 slen = strlen(suffixes[i]);
1062 if (len > slen && plen == len - slen &&
1063 strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1064 memcmp(id->filename, private_id->filename, plen) == 0)
1065 return 1;
1067 return 0;
1070 static int
1071 sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1073 Buffer b;
1074 Identity *private_id;
1075 u_char *blob, *signature;
1076 size_t slen;
1077 u_int bloblen, skip = 0;
1078 int matched, ret = -1, have_sig = 1;
1079 char *fp;
1081 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1082 SSH_FP_DEFAULT)) == NULL)
1083 return 0;
1084 debug3("%s: %s %s", __func__, key_type(id->key), fp);
1085 free(fp);
1087 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1088 /* we cannot handle this key */
1089 debug3("sign_and_send_pubkey: cannot handle key");
1090 return 0;
1092 /* data to be signed */
1093 buffer_init(&b);
1094 if (datafellows & SSH_OLD_SESSIONID) {
1095 buffer_append(&b, session_id2, session_id2_len);
1096 skip = session_id2_len;
1097 } else {
1098 buffer_put_string(&b, session_id2, session_id2_len);
1099 skip = buffer_len(&b);
1101 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1102 buffer_put_cstring(&b, authctxt->server_user);
1103 buffer_put_cstring(&b,
1104 datafellows & SSH_BUG_PKSERVICE ?
1105 "ssh-userauth" :
1106 authctxt->service);
1107 if (datafellows & SSH_BUG_PKAUTH) {
1108 buffer_put_char(&b, have_sig);
1109 } else {
1110 buffer_put_cstring(&b, authctxt->method->name);
1111 buffer_put_char(&b, have_sig);
1112 buffer_put_cstring(&b, key_sign_encode(id->key));
1114 buffer_put_string(&b, blob, bloblen);
1117 * If the key is an certificate, try to find a matching private key
1118 * and use it to complete the signature.
1119 * If no such private key exists, fall back to trying the certificate
1120 * key itself in case it has a private half already loaded.
1122 if (key_is_cert(id->key)) {
1123 matched = 0;
1124 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1125 if (sshkey_equal_public(id->key, private_id->key) &&
1126 id->key->type != private_id->key->type) {
1127 id = private_id;
1128 matched = 1;
1129 break;
1133 * Exact key matches are preferred, but also allow
1134 * filename matches for non-PKCS#11/agent keys that
1135 * didn't load public keys. This supports the case
1136 * of keeping just a private key file and public
1137 * certificate on disk.
1139 if (!matched && !id->isprivate && id->agent_fd == -1 &&
1140 (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1141 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1142 if (private_id->key == NULL &&
1143 id_filename_matches(id, private_id)) {
1144 id = private_id;
1145 matched = 1;
1146 break;
1150 if (matched) {
1151 debug2("%s: using private key \"%s\"%s for "
1152 "certificate", __func__, id->filename,
1153 id->agent_fd != -1 ? " from agent" : "");
1154 } else {
1155 debug("%s: no separate private key for certificate "
1156 "\"%s\"", __func__, id->filename);
1160 /* generate signature */
1161 ret = identity_sign(id, &signature, &slen,
1162 buffer_ptr(&b), buffer_len(&b), datafellows);
1163 if (ret != 0) {
1164 if (ret != SSH_ERR_KEY_NOT_FOUND)
1165 error("%s: signing failed: %s", __func__, ssh_err(ret));
1166 free(blob);
1167 buffer_free(&b);
1168 return 0;
1170 #ifdef DEBUG_PK
1171 buffer_dump(&b);
1172 #endif
1173 if (datafellows & SSH_BUG_PKSERVICE) {
1174 buffer_clear(&b);
1175 buffer_append(&b, session_id2, session_id2_len);
1176 skip = session_id2_len;
1177 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1178 buffer_put_cstring(&b, authctxt->server_user);
1179 buffer_put_cstring(&b, authctxt->service);
1180 buffer_put_cstring(&b, authctxt->method->name);
1181 buffer_put_char(&b, have_sig);
1182 if (!(datafellows & SSH_BUG_PKAUTH))
1183 buffer_put_cstring(&b, key_ssh_name(id->key));
1184 buffer_put_string(&b, blob, bloblen);
1186 free(blob);
1188 /* append signature */
1189 buffer_put_string(&b, signature, slen);
1190 free(signature);
1192 /* skip session id and packet type */
1193 if (buffer_len(&b) < skip + 1)
1194 fatal("userauth_pubkey: internal error");
1195 buffer_consume(&b, skip + 1);
1197 /* put remaining data from buffer into packet */
1198 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1199 packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1200 buffer_free(&b);
1201 packet_send();
1203 return 1;
1206 static int
1207 send_pubkey_test(Authctxt *authctxt, Identity *id)
1209 u_char *blob;
1210 u_int bloblen, have_sig = 0;
1212 debug3("send_pubkey_test");
1214 if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1215 /* we cannot handle this key */
1216 debug3("send_pubkey_test: cannot handle key");
1217 return 0;
1219 /* register callback for USERAUTH_PK_OK message */
1220 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1222 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1223 packet_put_cstring(authctxt->server_user);
1224 packet_put_cstring(authctxt->service);
1225 packet_put_cstring(authctxt->method->name);
1226 packet_put_char(have_sig);
1227 if (!(datafellows & SSH_BUG_PKAUTH))
1228 packet_put_cstring(key_sign_encode(id->key));
1229 packet_put_string(blob, bloblen);
1230 free(blob);
1231 packet_send();
1232 return 1;
1235 static struct sshkey *
1236 load_identity_file(Identity *id)
1238 struct sshkey *private = NULL;
1239 char prompt[300], *passphrase, *comment;
1240 int r, perm_ok = 0, quit = 0, i;
1241 struct stat st;
1243 if (stat(id->filename, &st) < 0) {
1244 (id->userprovided ? logit : debug3)("no such identity: %s: %s",
1245 id->filename, strerror(errno));
1246 return NULL;
1248 snprintf(prompt, sizeof prompt,
1249 "Enter passphrase for key '%.100s': ", id->filename);
1250 for (i = 0; i <= options.number_of_password_prompts; i++) {
1251 if (i == 0)
1252 passphrase = "";
1253 else {
1254 passphrase = read_passphrase(prompt, 0);
1255 if (*passphrase == '\0') {
1256 debug2("no passphrase given, try next key");
1257 free(passphrase);
1258 break;
1261 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1262 passphrase, &private, &comment, &perm_ok))) {
1263 case 0:
1264 break;
1265 case SSH_ERR_KEY_WRONG_PASSPHRASE:
1266 if (options.batch_mode) {
1267 quit = 1;
1268 break;
1270 if (i != 0)
1271 debug2("bad passphrase given, try again...");
1272 break;
1273 case SSH_ERR_SYSTEM_ERROR:
1274 if (errno == ENOENT) {
1275 debug2("Load key \"%s\": %s",
1276 id->filename, ssh_err(r));
1277 quit = 1;
1278 break;
1280 /* FALLTHROUGH */
1281 default:
1282 error("Load key \"%s\": %s", id->filename, ssh_err(r));
1283 quit = 1;
1284 break;
1286 if (!quit && private != NULL && id->agent_fd == -1 &&
1287 !(id->key && id->isprivate))
1288 maybe_add_key_to_agent(id->filename, private, comment,
1289 passphrase);
1290 if (i > 0) {
1291 explicit_bzero(passphrase, strlen(passphrase));
1292 free(passphrase);
1294 free(comment);
1295 if (private != NULL || quit)
1296 break;
1298 return private;
1302 * try keys in the following order:
1303 * 1. certificates listed in the config file
1304 * 2. other input certificates
1305 * 3. agent keys that are found in the config file
1306 * 4. other agent keys
1307 * 5. keys that are only listed in the config file
1309 static void
1310 pubkey_prepare(Authctxt *authctxt)
1312 struct identity *id, *id2, *tmp;
1313 struct idlist agent, files, *preferred;
1314 struct sshkey *key;
1315 int agent_fd = -1, i, r, found;
1316 size_t j;
1317 struct ssh_identitylist *idlist;
1319 TAILQ_INIT(&agent); /* keys from the agent */
1320 TAILQ_INIT(&files); /* keys from the config file */
1321 preferred = &authctxt->keys;
1322 TAILQ_INIT(preferred); /* preferred order of keys */
1324 /* list of keys stored in the filesystem and PKCS#11 */
1325 for (i = 0; i < options.num_identity_files; i++) {
1326 key = options.identity_keys[i];
1327 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1328 continue;
1329 options.identity_keys[i] = NULL;
1330 id = xcalloc(1, sizeof(*id));
1331 id->agent_fd = -1;
1332 id->key = key;
1333 id->filename = xstrdup(options.identity_files[i]);
1334 id->userprovided = options.identity_file_userprovided[i];
1335 TAILQ_INSERT_TAIL(&files, id, next);
1337 /* list of certificates specified by user */
1338 for (i = 0; i < options.num_certificate_files; i++) {
1339 key = options.certificates[i];
1340 if (!key_is_cert(key) || key->cert == NULL ||
1341 key->cert->type != SSH2_CERT_TYPE_USER)
1342 continue;
1343 id = xcalloc(1, sizeof(*id));
1344 id->agent_fd = -1;
1345 id->key = key;
1346 id->filename = xstrdup(options.certificate_files[i]);
1347 id->userprovided = options.certificate_file_userprovided[i];
1348 TAILQ_INSERT_TAIL(preferred, id, next);
1350 /* list of keys supported by the agent */
1351 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1352 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1353 debug("%s: ssh_get_authentication_socket: %s",
1354 __func__, ssh_err(r));
1355 } else if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1356 if (r != SSH_ERR_AGENT_NO_IDENTITIES)
1357 debug("%s: ssh_fetch_identitylist: %s",
1358 __func__, ssh_err(r));
1359 close(agent_fd);
1360 } else {
1361 for (j = 0; j < idlist->nkeys; j++) {
1362 found = 0;
1363 TAILQ_FOREACH(id, &files, next) {
1365 * agent keys from the config file are
1366 * preferred
1368 if (sshkey_equal(idlist->keys[j], id->key)) {
1369 TAILQ_REMOVE(&files, id, next);
1370 TAILQ_INSERT_TAIL(preferred, id, next);
1371 id->agent_fd = agent_fd;
1372 found = 1;
1373 break;
1376 if (!found && !options.identities_only) {
1377 id = xcalloc(1, sizeof(*id));
1378 /* XXX "steals" key/comment from idlist */
1379 id->key = idlist->keys[j];
1380 id->filename = idlist->comments[j];
1381 idlist->keys[j] = NULL;
1382 idlist->comments[j] = NULL;
1383 id->agent_fd = agent_fd;
1384 TAILQ_INSERT_TAIL(&agent, id, next);
1387 ssh_free_identitylist(idlist);
1388 /* append remaining agent keys */
1389 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1390 TAILQ_REMOVE(&agent, id, next);
1391 TAILQ_INSERT_TAIL(preferred, id, next);
1393 authctxt->agent_fd = agent_fd;
1395 /* Prefer PKCS11 keys that are explicitly listed */
1396 TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1397 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1398 continue;
1399 found = 0;
1400 TAILQ_FOREACH(id2, &files, next) {
1401 if (id2->key == NULL ||
1402 (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
1403 continue;
1404 if (sshkey_equal(id->key, id2->key)) {
1405 TAILQ_REMOVE(&files, id, next);
1406 TAILQ_INSERT_TAIL(preferred, id, next);
1407 found = 1;
1408 break;
1411 /* If IdentitiesOnly set and key not found then don't use it */
1412 if (!found && options.identities_only) {
1413 TAILQ_REMOVE(&files, id, next);
1414 explicit_bzero(id, sizeof(*id));
1415 free(id);
1418 /* append remaining keys from the config file */
1419 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1420 TAILQ_REMOVE(&files, id, next);
1421 TAILQ_INSERT_TAIL(preferred, id, next);
1423 /* finally, filter by PubkeyAcceptedKeyTypes */
1424 TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1425 if (id->key != NULL &&
1426 match_pattern_list(sshkey_ssh_name(id->key),
1427 options.pubkey_key_types, 0) != 1) {
1428 debug("Skipping %s key %s - "
1429 "not in PubkeyAcceptedKeyTypes",
1430 sshkey_ssh_name(id->key), id->filename);
1431 TAILQ_REMOVE(preferred, id, next);
1432 sshkey_free(id->key);
1433 free(id->filename);
1434 memset(id, 0, sizeof(*id));
1435 continue;
1437 debug2("key: %s (%p)%s%s", id->filename, id->key,
1438 id->userprovided ? ", explicit" : "",
1439 id->agent_fd != -1 ? ", agent" : "");
1443 static void
1444 pubkey_cleanup(Authctxt *authctxt)
1446 Identity *id;
1448 if (authctxt->agent_fd != -1)
1449 ssh_close_authentication_socket(authctxt->agent_fd);
1450 for (id = TAILQ_FIRST(&authctxt->keys); id;
1451 id = TAILQ_FIRST(&authctxt->keys)) {
1452 TAILQ_REMOVE(&authctxt->keys, id, next);
1453 sshkey_free(id->key);
1454 free(id->filename);
1455 free(id);
1459 static void
1460 pubkey_reset(Authctxt *authctxt)
1462 Identity *id;
1464 TAILQ_FOREACH(id, &authctxt->keys, next)
1465 id->tried = 0;
1468 static int
1469 try_identity(Identity *id)
1471 if (!id->key)
1472 return (0);
1473 if (key_type_plain(id->key->type) == KEY_RSA &&
1474 (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1475 debug("Skipped %s key %s for RSA/MD5 server",
1476 key_type(id->key), id->filename);
1477 return (0);
1479 return 1;
1483 userauth_pubkey(Authctxt *authctxt)
1485 Identity *id;
1486 int sent = 0;
1487 char *fp;
1489 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1490 if (id->tried++)
1491 return (0);
1492 /* move key to the end of the queue */
1493 TAILQ_REMOVE(&authctxt->keys, id, next);
1494 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1496 * send a test message if we have the public key. for
1497 * encrypted keys we cannot do this and have to load the
1498 * private key instead
1500 if (id->key != NULL) {
1501 if (try_identity(id)) {
1502 if ((fp = sshkey_fingerprint(id->key,
1503 options.fingerprint_hash,
1504 SSH_FP_DEFAULT)) == NULL) {
1505 error("%s: sshkey_fingerprint failed",
1506 __func__);
1507 return 0;
1509 debug("Offering public key: %s %s %s",
1510 sshkey_type(id->key), fp, id->filename);
1511 free(fp);
1512 sent = send_pubkey_test(authctxt, id);
1514 } else {
1515 debug("Trying private key: %s", id->filename);
1516 id->key = load_identity_file(id);
1517 if (id->key != NULL) {
1518 if (try_identity(id)) {
1519 id->isprivate = 1;
1520 sent = sign_and_send_pubkey(
1521 authctxt, id);
1523 key_free(id->key);
1524 id->key = NULL;
1525 id->isprivate = 0;
1528 if (sent)
1529 return (sent);
1531 return (0);
1535 * Send userauth request message specifying keyboard-interactive method.
1538 userauth_kbdint(Authctxt *authctxt)
1540 static int attempt = 0;
1542 if (attempt++ >= options.number_of_password_prompts)
1543 return 0;
1544 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1545 if (attempt > 1 && !authctxt->info_req_seen) {
1546 debug3("userauth_kbdint: disable: no info_req_seen");
1547 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1548 return 0;
1551 debug2("userauth_kbdint");
1552 packet_start(SSH2_MSG_USERAUTH_REQUEST);
1553 packet_put_cstring(authctxt->server_user);
1554 packet_put_cstring(authctxt->service);
1555 packet_put_cstring(authctxt->method->name);
1556 packet_put_cstring(""); /* lang */
1557 packet_put_cstring(options.kbd_interactive_devices ?
1558 options.kbd_interactive_devices : "");
1559 packet_send();
1561 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1562 return 1;
1566 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1569 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1571 Authctxt *authctxt = ssh->authctxt;
1572 char *name, *inst, *lang, *prompt, *response;
1573 u_int num_prompts, i;
1574 int echo = 0;
1576 debug2("input_userauth_info_req");
1578 if (authctxt == NULL)
1579 fatal("input_userauth_info_req: no authentication context");
1581 authctxt->info_req_seen = 1;
1583 name = packet_get_string(NULL);
1584 inst = packet_get_string(NULL);
1585 lang = packet_get_string(NULL);
1586 if (strlen(name) > 0)
1587 logit("%s", name);
1588 if (strlen(inst) > 0)
1589 logit("%s", inst);
1590 free(name);
1591 free(inst);
1592 free(lang);
1594 num_prompts = packet_get_int();
1596 * Begin to build info response packet based on prompts requested.
1597 * We commit to providing the correct number of responses, so if
1598 * further on we run into a problem that prevents this, we have to
1599 * be sure and clean this up and send a correct error response.
1601 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1602 packet_put_int(num_prompts);
1604 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1605 for (i = 0; i < num_prompts; i++) {
1606 prompt = packet_get_string(NULL);
1607 echo = packet_get_char();
1609 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1611 packet_put_cstring(response);
1612 explicit_bzero(response, strlen(response));
1613 free(response);
1614 free(prompt);
1616 packet_check_eom(); /* done with parsing incoming message. */
1618 packet_add_padding(64);
1619 packet_send();
1620 return 0;
1623 static int
1624 ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp,
1625 const u_char *data, size_t datalen)
1627 struct sshbuf *b;
1628 struct stat st;
1629 pid_t pid;
1630 int i, r, to[2], from[2], status, sock = packet_get_connection_in();
1631 u_char rversion = 0, version = 2;
1632 void (*osigchld)(int);
1634 *sigp = NULL;
1635 *lenp = 0;
1637 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1638 error("%s: not installed: %s", __func__, strerror(errno));
1639 return -1;
1641 if (fflush(stdout) != 0) {
1642 error("%s: fflush: %s", __func__, strerror(errno));
1643 return -1;
1645 if (pipe(to) < 0) {
1646 error("%s: pipe: %s", __func__, strerror(errno));
1647 return -1;
1649 if (pipe(from) < 0) {
1650 error("%s: pipe: %s", __func__, strerror(errno));
1651 return -1;
1653 if ((pid = fork()) < 0) {
1654 error("%s: fork: %s", __func__, strerror(errno));
1655 return -1;
1657 osigchld = signal(SIGCHLD, SIG_DFL);
1658 if (pid == 0) {
1659 /* keep the socket on exec */
1660 fcntl(sock, F_SETFD, 0);
1661 permanently_drop_suid(getuid());
1662 close(from[0]);
1663 if (dup2(from[1], STDOUT_FILENO) < 0)
1664 fatal("%s: dup2: %s", __func__, strerror(errno));
1665 close(to[1]);
1666 if (dup2(to[0], STDIN_FILENO) < 0)
1667 fatal("%s: dup2: %s", __func__, strerror(errno));
1668 close(from[1]);
1669 close(to[0]);
1670 /* Close everything but stdio and the socket */
1671 for (i = STDERR_FILENO + 1; i < sock; i++)
1672 close(i);
1673 closefrom(sock + 1);
1674 debug3("%s: [child] pid=%ld, exec %s",
1675 __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
1676 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
1677 fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
1678 strerror(errno));
1680 close(from[1]);
1681 close(to[0]);
1683 if ((b = sshbuf_new()) == NULL)
1684 fatal("%s: sshbuf_new failed", __func__);
1685 /* send # of sock, data to be signed */
1686 if ((r = sshbuf_put_u32(b, sock)) != 0 ||
1687 (r = sshbuf_put_string(b, data, datalen)) != 0)
1688 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1689 if (ssh_msg_send(to[1], version, b) == -1)
1690 fatal("%s: couldn't send request", __func__);
1691 sshbuf_reset(b);
1692 r = ssh_msg_recv(from[0], b);
1693 close(from[0]);
1694 close(to[1]);
1695 if (r < 0) {
1696 error("%s: no reply", __func__);
1697 goto fail;
1700 errno = 0;
1701 while (waitpid(pid, &status, 0) < 0) {
1702 if (errno != EINTR) {
1703 error("%s: waitpid %ld: %s",
1704 __func__, (long)pid, strerror(errno));
1705 goto fail;
1708 if (!WIFEXITED(status)) {
1709 error("%s: exited abnormally", __func__);
1710 goto fail;
1712 if (WEXITSTATUS(status) != 0) {
1713 error("%s: exited with status %d",
1714 __func__, WEXITSTATUS(status));
1715 goto fail;
1717 if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
1718 error("%s: buffer error: %s", __func__, ssh_err(r));
1719 goto fail;
1721 if (rversion != version) {
1722 error("%s: bad version", __func__);
1723 goto fail;
1725 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
1726 error("%s: buffer error: %s", __func__, ssh_err(r));
1727 fail:
1728 signal(SIGCHLD, osigchld);
1729 sshbuf_free(b);
1730 return -1;
1732 signal(SIGCHLD, osigchld);
1733 sshbuf_free(b);
1735 return 0;
1739 userauth_hostbased(Authctxt *authctxt)
1741 struct ssh *ssh = active_state;
1742 struct sshkey *private = NULL;
1743 struct sshbuf *b = NULL;
1744 const char *service;
1745 u_char *sig = NULL, *keyblob = NULL;
1746 char *fp = NULL, *chost = NULL, *lname = NULL;
1747 size_t siglen = 0, keylen = 0;
1748 int i, r, success = 0;
1750 if (authctxt->ktypes == NULL) {
1751 authctxt->oktypes = xstrdup(options.hostbased_key_types);
1752 authctxt->ktypes = authctxt->oktypes;
1756 * Work through each listed type pattern in HostbasedKeyTypes,
1757 * trying each hostkey that matches the type in turn.
1759 for (;;) {
1760 if (authctxt->active_ktype == NULL)
1761 authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
1762 if (authctxt->active_ktype == NULL ||
1763 *authctxt->active_ktype == '\0')
1764 break;
1765 debug3("%s: trying key type %s", __func__,
1766 authctxt->active_ktype);
1768 /* check for a useful key */
1769 private = NULL;
1770 for (i = 0; i < authctxt->sensitive->nkeys; i++) {
1771 if (authctxt->sensitive->keys[i] == NULL ||
1772 authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
1773 continue;
1774 if (match_pattern_list(
1775 sshkey_ssh_name(authctxt->sensitive->keys[i]),
1776 authctxt->active_ktype, 0) != 1)
1777 continue;
1778 /* we take and free the key */
1779 private = authctxt->sensitive->keys[i];
1780 authctxt->sensitive->keys[i] = NULL;
1781 break;
1783 /* Found one */
1784 if (private != NULL)
1785 break;
1786 /* No more keys of this type; advance */
1787 authctxt->active_ktype = NULL;
1789 if (private == NULL) {
1790 free(authctxt->oktypes);
1791 authctxt->oktypes = authctxt->ktypes = NULL;
1792 authctxt->active_ktype = NULL;
1793 debug("No more client hostkeys for hostbased authentication.");
1794 goto out;
1797 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
1798 SSH_FP_DEFAULT)) == NULL) {
1799 error("%s: sshkey_fingerprint failed", __func__);
1800 goto out;
1802 debug("%s: trying hostkey %s %s",
1803 __func__, sshkey_ssh_name(private), fp);
1805 /* figure out a name for the client host */
1806 if ((lname = get_local_name(packet_get_connection_in())) == NULL) {
1807 error("%s: cannot get local ipaddr/name", __func__);
1808 goto out;
1811 /* XXX sshbuf_put_stringf? */
1812 xasprintf(&chost, "%s.", lname);
1813 debug2("%s: chost %s", __func__, chost);
1815 service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1816 authctxt->service;
1818 /* construct data */
1819 if ((b = sshbuf_new()) == NULL) {
1820 error("%s: sshbuf_new failed", __func__);
1821 goto out;
1823 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
1824 error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
1825 goto out;
1827 if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
1828 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1829 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1830 (r = sshbuf_put_cstring(b, service)) != 0 ||
1831 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
1832 (r = sshbuf_put_cstring(b, key_ssh_name(private))) != 0 ||
1833 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
1834 (r = sshbuf_put_cstring(b, chost)) != 0 ||
1835 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
1836 error("%s: buffer error: %s", __func__, ssh_err(r));
1837 goto out;
1840 #ifdef DEBUG_PK
1841 sshbuf_dump(b, stderr);
1842 #endif
1843 if (authctxt->sensitive->external_keysign)
1844 r = ssh_keysign(private, &sig, &siglen,
1845 sshbuf_ptr(b), sshbuf_len(b));
1846 else if ((r = sshkey_sign(private, &sig, &siglen,
1847 sshbuf_ptr(b), sshbuf_len(b), NULL, datafellows)) != 0)
1848 debug("%s: sshkey_sign: %s", __func__, ssh_err(r));
1849 if (r != 0) {
1850 error("sign using hostkey %s %s failed",
1851 sshkey_ssh_name(private), fp);
1852 goto out;
1854 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1855 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1856 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1857 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1858 (r = sshpkt_put_cstring(ssh, key_ssh_name(private))) != 0 ||
1859 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
1860 (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
1861 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
1862 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
1863 (r = sshpkt_send(ssh)) != 0) {
1864 error("%s: packet error: %s", __func__, ssh_err(r));
1865 goto out;
1867 success = 1;
1869 out:
1870 if (sig != NULL) {
1871 explicit_bzero(sig, siglen);
1872 free(sig);
1874 free(keyblob);
1875 free(lname);
1876 free(fp);
1877 free(chost);
1878 sshkey_free(private);
1879 sshbuf_free(b);
1881 return success;
1884 /* find auth method */
1887 * given auth method name, if configurable options permit this method fill
1888 * in auth_ident field and return true, otherwise return false.
1890 static int
1891 authmethod_is_enabled(Authmethod *method)
1893 if (method == NULL)
1894 return 0;
1895 /* return false if options indicate this method is disabled */
1896 if (method->enabled == NULL || *method->enabled == 0)
1897 return 0;
1898 /* return false if batch mode is enabled but method needs interactive mode */
1899 if (method->batch_flag != NULL && *method->batch_flag != 0)
1900 return 0;
1901 return 1;
1904 static Authmethod *
1905 authmethod_lookup(const char *name)
1907 Authmethod *method = NULL;
1908 if (name != NULL)
1909 for (method = authmethods; method->name != NULL; method++)
1910 if (strcmp(name, method->name) == 0)
1911 return method;
1912 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1913 return NULL;
1916 /* XXX internal state */
1917 static Authmethod *current = NULL;
1918 static char *supported = NULL;
1919 static char *preferred = NULL;
1922 * Given the authentication method list sent by the server, return the
1923 * next method we should try. If the server initially sends a nil list,
1924 * use a built-in default list.
1926 static Authmethod *
1927 authmethod_get(char *authlist)
1929 char *name = NULL;
1930 u_int next;
1932 /* Use a suitable default if we're passed a nil list. */
1933 if (authlist == NULL || strlen(authlist) == 0)
1934 authlist = options.preferred_authentications;
1936 if (supported == NULL || strcmp(authlist, supported) != 0) {
1937 debug3("start over, passed a different list %s", authlist);
1938 free(supported);
1939 supported = xstrdup(authlist);
1940 preferred = options.preferred_authentications;
1941 debug3("preferred %s", preferred);
1942 current = NULL;
1943 } else if (current != NULL && authmethod_is_enabled(current))
1944 return current;
1946 for (;;) {
1947 if ((name = match_list(preferred, supported, &next)) == NULL) {
1948 debug("No more authentication methods to try.");
1949 current = NULL;
1950 return NULL;
1952 preferred += next;
1953 debug3("authmethod_lookup %s", name);
1954 debug3("remaining preferred: %s", preferred);
1955 if ((current = authmethod_lookup(name)) != NULL &&
1956 authmethod_is_enabled(current)) {
1957 debug3("authmethod_is_enabled %s", name);
1958 debug("Next authentication method: %s", name);
1959 free(name);
1960 return current;
1962 free(name);
1966 static char *
1967 authmethods_get(void)
1969 Authmethod *method = NULL;
1970 Buffer b;
1971 char *list;
1973 buffer_init(&b);
1974 for (method = authmethods; method->name != NULL; method++) {
1975 if (authmethod_is_enabled(method)) {
1976 if (buffer_len(&b) > 0)
1977 buffer_append(&b, ",", 1);
1978 buffer_append(&b, method->name, strlen(method->name));
1981 if ((list = sshbuf_dup_string(&b)) == NULL)
1982 fatal("%s: sshbuf_dup_string failed", __func__);
1983 buffer_free(&b);
1984 return list;