sshconnect2.c revision 1.1.1.19 1 /* $OpenBSD: sshconnect2.c,v 1.284 2018/08/13 02:41:05 djm Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2008 Damien Miller. All rights reserved.
5 *
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.
14 *
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.
25 */
26
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <sys/wait.h>
30 #include <sys/queue.h>
31 #include <sys/stat.h>
32
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <netdb.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <signal.h>
39 #include <pwd.h>
40 #include <unistd.h>
41 #include <vis.h>
42
43 #include "xmalloc.h"
44 #include "ssh.h"
45 #include "ssh2.h"
46 #include "sshbuf.h"
47 #include "packet.h"
48 #include "compat.h"
49 #include "cipher.h"
50 #include "sshkey.h"
51 #include "kex.h"
52 #include "myproposal.h"
53 #include "sshconnect.h"
54 #include "authfile.h"
55 #include "dh.h"
56 #include "authfd.h"
57 #include "log.h"
58 #include "misc.h"
59 #include "readconf.h"
60 #include "match.h"
61 #include "dispatch.h"
62 #include "canohost.h"
63 #include "msg.h"
64 #include "pathnames.h"
65 #include "uidswap.h"
66 #include "hostfile.h"
67 #include "ssherr.h"
68 #include "utf8.h"
69
70 #ifdef GSSAPI
71 #include "ssh-gss.h"
72 #endif
73
74 /* import */
75 extern char *client_version_string;
76 extern char *server_version_string;
77 extern Options options;
78
79 /*
80 * SSH2 key exchange
81 */
82
83 u_char *session_id2 = NULL;
84 u_int session_id2_len = 0;
85
86 char *xxx_host;
87 struct sockaddr *xxx_hostaddr;
88
89 static int
90 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh)
91 {
92 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
93 fatal("Host key verification failed.");
94 return 0;
95 }
96
97 static char *
98 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
99 {
100 char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
101 size_t maxlen;
102 struct hostkeys *hostkeys;
103 int ktype;
104 u_int i;
105
106 /* Find all hostkeys for this hostname */
107 get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
108 hostkeys = init_hostkeys();
109 for (i = 0; i < options.num_user_hostfiles; i++)
110 load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]);
111 for (i = 0; i < options.num_system_hostfiles; i++)
112 load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]);
113
114 oavail = avail = xstrdup(KEX_DEFAULT_PK_ALG);
115 maxlen = strlen(avail) + 1;
116 first = xmalloc(maxlen);
117 last = xmalloc(maxlen);
118 *first = *last = '\0';
119
120 #define ALG_APPEND(to, from) \
121 do { \
122 if (*to != '\0') \
123 strlcat(to, ",", maxlen); \
124 strlcat(to, from, maxlen); \
125 } while (0)
126
127 while ((alg = strsep(&avail, ",")) && *alg != '\0') {
128 if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
129 fatal("%s: unknown alg %s", __func__, alg);
130 if (lookup_key_in_hostkeys_by_type(hostkeys,
131 sshkey_type_plain(ktype), NULL))
132 ALG_APPEND(first, alg);
133 else
134 ALG_APPEND(last, alg);
135 }
136 #undef ALG_APPEND
137 xasprintf(&ret, "%s%s%s", first,
138 (*first == '\0' || *last == '\0') ? "" : ",", last);
139 if (*first != '\0')
140 debug3("%s: prefer hostkeyalgs: %s", __func__, first);
141
142 free(first);
143 free(last);
144 free(hostname);
145 free(oavail);
146 free_hostkeys(hostkeys);
147
148 return ret;
149 }
150
151 void
152 ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
153 {
154 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
155 char *s, *all_key;
156 struct kex *kex;
157 int r;
158
159 xxx_host = host;
160 xxx_hostaddr = hostaddr;
161
162 if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
163 fatal("%s: kex_names_cat", __func__);
164 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
165 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
166 compat_cipher_proposal(options.ciphers);
167 myproposal[PROPOSAL_ENC_ALGS_STOC] =
168 compat_cipher_proposal(options.ciphers);
169 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
170 myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ?
171 "zlib (at) openssh.com,zlib,none" : "none,zlib (at) openssh.com,zlib";
172 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
173 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
174 if (options.hostkeyalgorithms != NULL) {
175 all_key = sshkey_alg_list(0, 0, 1, ',');
176 if (kex_assemble_names(&options.hostkeyalgorithms,
177 KEX_DEFAULT_PK_ALG, all_key) != 0)
178 fatal("%s: kex_assemble_namelist", __func__);
179 free(all_key);
180 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
181 compat_pkalg_proposal(options.hostkeyalgorithms);
182 } else {
183 /* Enforce default */
184 options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG);
185 /* Prefer algorithms that we already have keys for */
186 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
187 compat_pkalg_proposal(
188 order_hostkeyalgs(host, hostaddr, port));
189 }
190
191 if (options.rekey_limit || options.rekey_interval)
192 packet_set_rekey_limits(options.rekey_limit,
193 options.rekey_interval);
194
195 /* start key exchange */
196 if ((r = kex_setup(active_state, myproposal)) != 0)
197 fatal("kex_setup: %s", ssh_err(r));
198 kex = active_state->kex;
199 #ifdef WITH_OPENSSL
200 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
201 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
202 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client;
203 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client;
204 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client;
205 kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
206 kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
207 kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
208 #endif
209 kex->kex[KEX_C25519_SHA256] = kexc25519_client;
210 kex->client_version_string=client_version_string;
211 kex->server_version_string=server_version_string;
212 kex->verify_host_key=&verify_host_key_callback;
213
214 ssh_dispatch_run_fatal(active_state, DISPATCH_BLOCK, &kex->done);
215
216 /* remove ext-info from the KEX proposals for rekeying */
217 myproposal[PROPOSAL_KEX_ALGS] =
218 compat_kex_proposal(options.kex_algorithms);
219 if ((r = kex_prop2buf(kex->my, myproposal)) != 0)
220 fatal("kex_prop2buf: %s", ssh_err(r));
221
222 session_id2 = kex->session_id;
223 session_id2_len = kex->session_id_len;
224
225 #ifdef DEBUG_KEXDH
226 /* send 1st encrypted/maced/compressed message */
227 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
228 (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
229 (r = sshpkt_send(ssh)) != 0 ||
230 (r = ssh_packet_write_wait(ssh)) != 0)
231 fatal("%s: %s", __func__, ssh_err(r));
232 #endif
233 }
234
235 /*
236 * Authenticate user
237 */
238
239 typedef struct cauthctxt Authctxt;
240 typedef struct cauthmethod Authmethod;
241 typedef struct identity Identity;
242 typedef struct idlist Idlist;
243
244 struct identity {
245 TAILQ_ENTRY(identity) next;
246 int agent_fd; /* >=0 if agent supports key */
247 struct sshkey *key; /* public/private key */
248 char *filename; /* comment for agent-only keys */
249 int tried;
250 int isprivate; /* key points to the private key */
251 int userprovided;
252 };
253 TAILQ_HEAD(idlist, identity);
254
255 struct cauthctxt {
256 const char *server_user;
257 const char *local_user;
258 const char *host;
259 const char *service;
260 struct cauthmethod *method;
261 sig_atomic_t success;
262 char *authlist;
263 int attempt;
264 /* pubkey */
265 struct idlist keys;
266 int agent_fd;
267 /* hostbased */
268 Sensitive *sensitive;
269 char *oktypes, *ktypes;
270 const char *active_ktype;
271 /* kbd-interactive */
272 int info_req_seen;
273 /* generic */
274 void *methoddata;
275 };
276
277 struct cauthmethod {
278 char *name; /* string to compare against server's list */
279 int (*userauth)(Authctxt *authctxt);
280 void (*cleanup)(Authctxt *authctxt);
281 int *enabled; /* flag in option struct that enables method */
282 int *batch_flag; /* flag in option struct that disables method */
283 };
284
285 int input_userauth_service_accept(int, u_int32_t, struct ssh *);
286 int input_userauth_ext_info(int, u_int32_t, struct ssh *);
287 int input_userauth_success(int, u_int32_t, struct ssh *);
288 int input_userauth_success_unexpected(int, u_int32_t, struct ssh *);
289 int input_userauth_failure(int, u_int32_t, struct ssh *);
290 int input_userauth_banner(int, u_int32_t, struct ssh *);
291 int input_userauth_error(int, u_int32_t, struct ssh *);
292 int input_userauth_info_req(int, u_int32_t, struct ssh *);
293 int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
294 int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
295
296 int userauth_none(Authctxt *);
297 int userauth_pubkey(Authctxt *);
298 int userauth_passwd(Authctxt *);
299 int userauth_kbdint(Authctxt *);
300 int userauth_hostbased(Authctxt *);
301
302 #ifdef GSSAPI
303 int userauth_gssapi(Authctxt *authctxt);
304 int input_gssapi_response(int type, u_int32_t, struct ssh *);
305 int input_gssapi_token(int type, u_int32_t, struct ssh *);
306 int input_gssapi_hash(int type, u_int32_t, struct ssh *);
307 int input_gssapi_error(int, u_int32_t, struct ssh *);
308 int input_gssapi_errtok(int, u_int32_t, struct ssh *);
309 #endif
310
311 void userauth(Authctxt *, char *);
312
313 static int sign_and_send_pubkey(struct ssh *ssh, Authctxt *, Identity *);
314 static void pubkey_prepare(Authctxt *);
315 static void pubkey_cleanup(Authctxt *);
316 static void pubkey_reset(Authctxt *);
317 static struct sshkey *load_identity_file(Identity *);
318
319 static Authmethod *authmethod_get(char *authlist);
320 static Authmethod *authmethod_lookup(const char *name);
321 static char *authmethods_get(void);
322
323 Authmethod authmethods[] = {
324 #ifdef GSSAPI
325 {"gssapi-with-mic",
326 userauth_gssapi,
327 NULL,
328 &options.gss_authentication,
329 NULL},
330 #endif
331 {"hostbased",
332 userauth_hostbased,
333 NULL,
334 &options.hostbased_authentication,
335 NULL},
336 {"publickey",
337 userauth_pubkey,
338 NULL,
339 &options.pubkey_authentication,
340 NULL},
341 {"keyboard-interactive",
342 userauth_kbdint,
343 NULL,
344 &options.kbd_interactive_authentication,
345 &options.batch_mode},
346 {"password",
347 userauth_passwd,
348 NULL,
349 &options.password_authentication,
350 &options.batch_mode},
351 {"none",
352 userauth_none,
353 NULL,
354 NULL,
355 NULL},
356 {NULL, NULL, NULL, NULL, NULL}
357 };
358
359 void
360 ssh_userauth2(const char *local_user, const char *server_user, char *host,
361 Sensitive *sensitive)
362 {
363 struct ssh *ssh = active_state;
364 Authctxt authctxt;
365 int r;
366
367 if (options.challenge_response_authentication)
368 options.kbd_interactive_authentication = 1;
369 if (options.preferred_authentications == NULL)
370 options.preferred_authentications = authmethods_get();
371
372 /* setup authentication context */
373 memset(&authctxt, 0, sizeof(authctxt));
374 pubkey_prepare(&authctxt);
375 authctxt.server_user = server_user;
376 authctxt.local_user = local_user;
377 authctxt.host = host;
378 authctxt.service = "ssh-connection"; /* service name */
379 authctxt.success = 0;
380 authctxt.method = authmethod_lookup("none");
381 authctxt.authlist = NULL;
382 authctxt.methoddata = NULL;
383 authctxt.sensitive = sensitive;
384 authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
385 authctxt.info_req_seen = 0;
386 authctxt.agent_fd = -1;
387 if (authctxt.method == NULL)
388 fatal("ssh_userauth2: internal error: cannot send userauth none request");
389
390 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
391 (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
392 (r = sshpkt_send(ssh)) != 0)
393 fatal("%s: %s", __func__, ssh_err(r));
394
395 ssh->authctxt = &authctxt;
396 ssh_dispatch_init(ssh, &input_userauth_error);
397 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info);
398 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
399 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success); /* loop until success */
400 ssh->authctxt = NULL;
401
402 pubkey_cleanup(&authctxt);
403 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
404
405 if (!authctxt.success)
406 fatal("Authentication failed.");
407 debug("Authentication succeeded (%s).", authctxt.method->name);
408 }
409
410 /* ARGSUSED */
411 int
412 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
413 {
414 Authctxt *authctxt = ssh->authctxt;
415 int r;
416
417 if (ssh_packet_remaining(ssh) > 0) {
418 char *reply;
419
420 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
421 goto out;
422 debug2("service_accept: %s", reply);
423 free(reply);
424 } else {
425 debug2("buggy server: service_accept w/o service");
426 }
427 if ((r = sshpkt_get_end(ssh)) != 0)
428 goto out;
429 debug("SSH2_MSG_SERVICE_ACCEPT received");
430
431 /* initial userauth request */
432 userauth_none(authctxt);
433
434 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error);
435 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
436 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
437 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
438 r = 0;
439 out:
440 return r;
441 }
442
443 /* ARGSUSED */
444 int
445 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh)
446 {
447 return kex_input_ext_info(type, seqnr, ssh);
448 }
449
450 void
451 userauth(Authctxt *authctxt, char *authlist)
452 {
453 struct ssh *ssh = active_state; /* XXX */
454
455 if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
456 authctxt->method->cleanup(authctxt);
457
458 free(authctxt->methoddata);
459 authctxt->methoddata = NULL;
460 if (authlist == NULL) {
461 authlist = authctxt->authlist;
462 } else {
463 free(authctxt->authlist);
464 authctxt->authlist = authlist;
465 }
466 for (;;) {
467 Authmethod *method = authmethod_get(authlist);
468 if (method == NULL)
469 fatal("%s@%s: Permission denied (%s).",
470 authctxt->server_user, authctxt->host, authlist);
471 authctxt->method = method;
472
473 /* reset the per method handler */
474 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN,
475 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
476
477 /* and try new method */
478 if (method->userauth(authctxt) != 0) {
479 debug2("we sent a %s packet, wait for reply", method->name);
480 break;
481 } else {
482 debug2("we did not send a packet, disable method");
483 method->enabled = NULL;
484 }
485 }
486 }
487
488 /* ARGSUSED */
489 int
490 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
491 {
492 fatal("input_userauth_error: bad message during authentication: "
493 "type %d", type);
494 return 0;
495 }
496
497 /* ARGSUSED */
498 int
499 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
500 {
501 char *msg, *lang;
502 u_int len;
503
504 debug3("%s", __func__);
505 msg = packet_get_string(&len);
506 lang = packet_get_string(NULL);
507 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
508 fmprintf(stderr, "%s", msg);
509 free(msg);
510 free(lang);
511 return 0;
512 }
513
514 /* ARGSUSED */
515 int
516 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
517 {
518 Authctxt *authctxt = ssh->authctxt;
519
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 */
529 return 0;
530 }
531
532 int
533 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
534 {
535 Authctxt *authctxt = ssh->authctxt;
536
537 if (authctxt == NULL)
538 fatal("%s: no authentication context", __func__);
539
540 fatal("Unexpected authentication success during %s.",
541 authctxt->method->name);
542 return 0;
543 }
544
545 /* ARGSUSED */
546 int
547 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
548 {
549 Authctxt *authctxt = ssh->authctxt;
550 char *authlist = NULL;
551 u_char partial;
552 int r;
553
554 if (authctxt == NULL)
555 fatal("input_userauth_failure: no authentication context");
556
557 if ((r = sshpkt_get_cstring(ssh, &authlist, NULL)) != 0 ||
558 (r = sshpkt_get_u8(ssh, &partial)) != 0 ||
559 (r = sshpkt_get_end(ssh)) != 0)
560 goto out;
561
562 if (partial != 0) {
563 verbose("Authenticated with partial success.");
564 /* reset state */
565 pubkey_reset(authctxt);
566 }
567 debug("Authentications that can continue: %s", authlist);
568
569 userauth(authctxt, authlist);
570 authlist = NULL;
571 out:
572 free(authlist);
573 return 0;
574 }
575
576 /* ARGSUSED */
577 int
578 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
579 {
580 Authctxt *authctxt = ssh->authctxt;
581 struct sshkey *key = NULL;
582 Identity *id = NULL;
583 int pktype, sent = 0;
584 size_t blen;
585 char *pkalg = NULL, *fp;
586 u_char *pkblob = NULL;
587 int r;
588
589 if (authctxt == NULL)
590 fatal("input_userauth_pk_ok: no authentication context");
591
592 if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
593 (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
594 (r = sshpkt_get_end(ssh)) != 0)
595 goto done;
596
597 debug("Server accepts key: pkalg %s blen %zu", pkalg, blen);
598
599 if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) {
600 debug("unknown pkalg %s", pkalg);
601 goto done;
602 }
603 if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
604 debug("no key from blob. pkalg %s: %s", pkalg, ssh_err(r));
605 goto done;
606 }
607 if (key->type != pktype) {
608 error("input_userauth_pk_ok: type mismatch "
609 "for decoded key (received %d, expected %d)",
610 key->type, pktype);
611 goto done;
612 }
613 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
614 SSH_FP_DEFAULT)) == NULL)
615 goto done;
616 debug2("input_userauth_pk_ok: fp %s", fp);
617 free(fp);
618
619 /*
620 * search keys in the reverse order, because last candidate has been
621 * moved to the end of the queue. this also avoids confusion by
622 * duplicate keys
623 */
624 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
625 if (sshkey_equal(key, id->key)) {
626 sent = sign_and_send_pubkey(ssh, authctxt, id);
627 break;
628 }
629 }
630 r = 0;
631 done:
632 sshkey_free(key);
633 free(pkalg);
634 free(pkblob);
635
636 /* try another method if we did not send a packet */
637 if (r == 0 && sent == 0)
638 userauth(authctxt, NULL);
639 return r;
640 }
641
642 #ifdef GSSAPI
643 int
644 userauth_gssapi(Authctxt *authctxt)
645 {
646 struct ssh *ssh = active_state; /* XXX */
647 Gssctxt *gssctxt = NULL;
648 static gss_OID_set gss_supported = NULL;
649 static u_int mech = 0;
650 OM_uint32 min;
651 int r, ok = 0;
652
653 /* Try one GSSAPI method at a time, rather than sending them all at
654 * once. */
655
656 if (gss_supported == NULL)
657 gss_indicate_mechs(&min, &gss_supported);
658
659 /* Check to see if the mechanism is usable before we offer it */
660 while (mech < gss_supported->count && !ok) {
661 /* My DER encoding requires length<128 */
662 if (gss_supported->elements[mech].length < 128 &&
663 ssh_gssapi_check_mechanism(&gssctxt,
664 &gss_supported->elements[mech], authctxt->host)) {
665 ok = 1; /* Mechanism works */
666 } else {
667 mech++;
668 }
669 }
670
671 if (!ok)
672 return 0;
673
674 authctxt->methoddata=(void *)gssctxt;
675
676 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
677 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
678 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
679 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
680 (r = sshpkt_put_u32(ssh, 1)) != 0 ||
681 (r = sshpkt_put_u32(ssh,
682 (gss_supported->elements[mech].length) + 2)) != 0 ||
683 (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 ||
684 (r = sshpkt_put_u8(ssh,
685 gss_supported->elements[mech].length)) != 0 ||
686 (r = sshpkt_put(ssh,
687 gss_supported->elements[mech].elements,
688 gss_supported->elements[mech].length)) != 0 ||
689 (r = sshpkt_send(ssh)) != 0)
690 fatal("%s: %s", __func__, ssh_err(r));
691
692 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
693 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
694 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
695 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
696
697 mech++; /* Move along to next candidate */
698
699 return 1;
700 }
701
702 static OM_uint32
703 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
704 {
705 Authctxt *authctxt = ssh->authctxt;
706 Gssctxt *gssctxt = authctxt->methoddata;
707 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
708 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
709 gss_buffer_desc gssbuf;
710 OM_uint32 status, ms, flags;
711 int r;
712
713 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
714 recv_tok, &send_tok, &flags);
715
716 if (send_tok.length > 0) {
717 u_char type = GSS_ERROR(status) ?
718 SSH2_MSG_USERAUTH_GSSAPI_ERRTOK :
719 SSH2_MSG_USERAUTH_GSSAPI_TOKEN;
720
721 if ((r = sshpkt_start(ssh, type)) != 0 ||
722 (r = sshpkt_put_string(ssh, send_tok.value,
723 send_tok.length)) != 0 ||
724 (r = sshpkt_send(ssh)) != 0)
725 fatal("%s: %s", __func__, ssh_err(r));
726
727 gss_release_buffer(&ms, &send_tok);
728 }
729
730 if (status == GSS_S_COMPLETE) {
731 /* send either complete or MIC, depending on mechanism */
732 if (!(flags & GSS_C_INTEG_FLAG)) {
733 if ((r = sshpkt_start(ssh,
734 SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 ||
735 (r = sshpkt_send(ssh)) != 0)
736 fatal("%s: %s", __func__, ssh_err(r));
737 } else {
738 struct sshbuf *b;
739
740 if ((b = sshbuf_new()) == NULL)
741 fatal("%s: sshbuf_new failed", __func__);
742 ssh_gssapi_buildmic(b, authctxt->server_user,
743 authctxt->service, "gssapi-with-mic");
744
745 if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
746 fatal("%s: sshbuf_mutable_ptr failed", __func__);
747 gssbuf.length = sshbuf_len(b);
748
749 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
750
751 if (!GSS_ERROR(status)) {
752 if ((r = sshpkt_start(ssh,
753 SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 ||
754 (r = sshpkt_put_string(ssh, mic.value,
755 mic.length)) != 0 ||
756 (r = sshpkt_send(ssh)) != 0)
757 fatal("%s: %s", __func__, ssh_err(r));
758 }
759
760 sshbuf_free(b);
761 gss_release_buffer(&ms, &mic);
762 }
763 }
764
765 return status;
766 }
767
768 /* ARGSUSED */
769 int
770 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
771 {
772 Authctxt *authctxt = ssh->authctxt;
773 Gssctxt *gssctxt;
774 size_t oidlen;
775 u_char *oidv = NULL;
776 int r;
777
778 if (authctxt == NULL)
779 fatal("input_gssapi_response: no authentication context");
780 gssctxt = authctxt->methoddata;
781
782 /* Setup our OID */
783 if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0)
784 goto done;
785
786 if (oidlen <= 2 ||
787 oidv[0] != SSH_GSS_OIDTYPE ||
788 oidv[1] != oidlen - 2) {
789 debug("Badly encoded mechanism OID received");
790 userauth(authctxt, NULL);
791 goto ok;
792 }
793
794 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
795 fatal("Server returned different OID than expected");
796
797 if ((r = sshpkt_get_end(ssh)) != 0)
798 goto done;
799
800 if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
801 /* Start again with next method on list */
802 debug("Trying to start again");
803 userauth(authctxt, NULL);
804 goto ok;
805 }
806 ok:
807 r = 0;
808 done:
809 free(oidv);
810 return r;
811 }
812
813 /* ARGSUSED */
814 int
815 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
816 {
817 Authctxt *authctxt = ssh->authctxt;
818 gss_buffer_desc recv_tok;
819 u_char *p = NULL;
820 size_t len;
821 OM_uint32 status;
822 int r;
823
824 if (authctxt == NULL)
825 fatal("input_gssapi_response: no authentication context");
826
827 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
828 (r = sshpkt_get_end(ssh)) != 0)
829 goto out;
830
831 recv_tok.value = p;
832 recv_tok.length = len;
833 status = process_gssapi_token(ssh, &recv_tok);
834
835 /* Start again with the next method in the list */
836 if (GSS_ERROR(status)) {
837 userauth(authctxt, NULL);
838 /* ok */
839 }
840 r = 0;
841 out:
842 free(p);
843 return r;
844 }
845
846 /* ARGSUSED */
847 int
848 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
849 {
850 Authctxt *authctxt = ssh->authctxt;
851 Gssctxt *gssctxt;
852 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
853 gss_buffer_desc recv_tok;
854 OM_uint32 ms;
855 u_char *p = NULL;
856 size_t len;
857 int r;
858
859 if (authctxt == NULL)
860 fatal("input_gssapi_response: no authentication context");
861 gssctxt = authctxt->methoddata;
862
863 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
864 (r = sshpkt_get_end(ssh)) != 0) {
865 free(p);
866 return r;
867 }
868
869 /* Stick it into GSSAPI and see what it says */
870 recv_tok.value = p;
871 recv_tok.length = len;
872 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
873 &recv_tok, &send_tok, NULL);
874 free(p);
875 gss_release_buffer(&ms, &send_tok);
876
877 /* Server will be returning a failed packet after this one */
878 return 0;
879 }
880
881 /* ARGSUSED */
882 int
883 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
884 {
885 char *msg = NULL;
886 char *lang = NULL;
887 int r;
888
889 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* maj */
890 (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* min */
891 (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
892 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
893 goto out;
894 r = sshpkt_get_end(ssh);
895 debug("Server GSSAPI Error:\n%s", msg);
896 out:
897 free(msg);
898 free(lang);
899 return r;
900 }
901 #endif /* GSSAPI */
902
903 int
904 userauth_none(Authctxt *authctxt)
905 {
906 struct ssh *ssh = active_state; /* XXX */
907 int r;
908
909 /* initial userauth request */
910 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
911 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
912 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
913 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
914 (r = sshpkt_send(ssh)) != 0)
915 fatal("%s: %s", __func__, ssh_err(r));
916 return 1;
917 }
918
919 int
920 userauth_passwd(Authctxt *authctxt)
921 {
922 struct ssh *ssh = active_state; /* XXX */
923 static int attempt = 0;
924 char prompt[256];
925 char *password;
926 const char *host = options.host_key_alias ? options.host_key_alias :
927 authctxt->host;
928 int r;
929
930 if (attempt++ >= options.number_of_password_prompts)
931 return 0;
932
933 if (attempt != 1)
934 error("Permission denied, please try again.");
935
936 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
937 authctxt->server_user, host);
938 password = read_passphrase(prompt, 0);
939 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
940 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
941 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
942 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
943 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
944 (r = sshpkt_put_cstring(ssh, password)) != 0 ||
945 (r = sshpkt_add_padding(ssh, 64)) != 0 ||
946 (r = sshpkt_send(ssh)) != 0)
947 fatal("%s: %s", __func__, ssh_err(r));
948
949 if (password)
950 freezero(password, strlen(password));
951
952 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
953 &input_userauth_passwd_changereq);
954
955 return 1;
956 }
957
958 /*
959 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
960 */
961 /* ARGSUSED */
962 int
963 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
964 {
965 Authctxt *authctxt = ssh->authctxt;
966 char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL;
967 char prompt[256];
968 const char *host;
969 int r;
970
971 debug2("input_userauth_passwd_changereq");
972
973 if (authctxt == NULL)
974 fatal("input_userauth_passwd_changereq: "
975 "no authentication context");
976 host = options.host_key_alias ? options.host_key_alias : authctxt->host;
977
978 if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 ||
979 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
980 goto out;
981 if (strlen(info) > 0)
982 logit("%s", info);
983 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
984 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
985 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
986 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
987 (r = sshpkt_put_u8(ssh, 1)) != 0) /* additional info */
988 goto out;
989
990 snprintf(prompt, sizeof(prompt),
991 "Enter %.30s@%.128s's old password: ",
992 authctxt->server_user, host);
993 password = read_passphrase(prompt, 0);
994 if ((r = sshpkt_put_cstring(ssh, password)) != 0)
995 goto out;
996
997 freezero(password, strlen(password));
998 password = NULL;
999 while (password == NULL) {
1000 snprintf(prompt, sizeof(prompt),
1001 "Enter %.30s@%.128s's new password: ",
1002 authctxt->server_user, host);
1003 password = read_passphrase(prompt, RP_ALLOW_EOF);
1004 if (password == NULL) {
1005 /* bail out */
1006 r = 0;
1007 goto out;
1008 }
1009 snprintf(prompt, sizeof(prompt),
1010 "Retype %.30s@%.128s's new password: ",
1011 authctxt->server_user, host);
1012 retype = read_passphrase(prompt, 0);
1013 if (strcmp(password, retype) != 0) {
1014 freezero(password, strlen(password));
1015 logit("Mismatch; try again, EOF to quit.");
1016 password = NULL;
1017 }
1018 freezero(retype, strlen(retype));
1019 }
1020 if ((r = sshpkt_put_cstring(ssh, password)) != 0 ||
1021 (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1022 (r = sshpkt_send(ssh)) != 0)
1023 goto out;
1024
1025 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1026 &input_userauth_passwd_changereq);
1027 r = 0;
1028 out:
1029 if (password)
1030 freezero(password, strlen(password));
1031 free(info);
1032 free(lang);
1033 return r;
1034 }
1035
1036 /*
1037 * Select an algorithm for publickey signatures.
1038 * Returns algorithm (caller must free) or NULL if no mutual algorithm found.
1039 *
1040 * Call with ssh==NULL to ignore server-sig-algs extension list and
1041 * only attempt with the key's base signature type.
1042 */
1043 static char *
1044 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key)
1045 {
1046 char *allowed, *oallowed, *cp, *tmp, *alg = NULL;
1047
1048 /*
1049 * The signature algorithm will only differ from the key algorithm
1050 * for RSA keys/certs and when the server advertises support for
1051 * newer (SHA2) algorithms.
1052 */
1053 if (ssh == NULL || ssh->kex->server_sig_algs == NULL ||
1054 (key->type != KEY_RSA && key->type != KEY_RSA_CERT)) {
1055 /* Filter base key signature alg against our configuration */
1056 return match_list(sshkey_ssh_name(key),
1057 options.pubkey_key_types, NULL);
1058 }
1059
1060 /*
1061 * For RSA keys/certs, since these might have a different sig type:
1062 * find the first entry in PubkeyAcceptedKeyTypes of the right type
1063 * that also appears in the supported signature algorithms list from
1064 * the server.
1065 */
1066 oallowed = allowed = xstrdup(options.pubkey_key_types);
1067 while ((cp = strsep(&allowed, ",")) != NULL) {
1068 if (sshkey_type_from_name(cp) != key->type)
1069 continue;
1070 tmp = match_list(sshkey_sigalg_by_name(cp), ssh->kex->server_sig_algs, NULL);
1071 if (tmp != NULL)
1072 alg = xstrdup(cp);
1073 free(tmp);
1074 if (alg != NULL)
1075 break;
1076 }
1077 free(oallowed);
1078 return alg;
1079 }
1080
1081 static int
1082 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1083 const u_char *data, size_t datalen, u_int compat, const char *alg)
1084 {
1085 struct sshkey *prv;
1086 int r;
1087
1088 /* The agent supports this key. */
1089 if (id->key != NULL && id->agent_fd != -1) {
1090 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1091 data, datalen, alg, compat);
1092 }
1093
1094 /*
1095 * We have already loaded the private key or the private key is
1096 * stored in external hardware.
1097 */
1098 if (id->key != NULL &&
1099 (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) {
1100 if ((r = sshkey_sign(id->key, sigp, lenp, data, datalen,
1101 alg, compat)) != 0)
1102 return r;
1103 /*
1104 * PKCS#11 tokens may not support all signature algorithms,
1105 * so check what we get back.
1106 */
1107 if ((r = sshkey_check_sigtype(*sigp, *lenp, alg)) != 0)
1108 return r;
1109 return 0;
1110 }
1111
1112 /* Load the private key from the file. */
1113 if ((prv = load_identity_file(id)) == NULL)
1114 return SSH_ERR_KEY_NOT_FOUND;
1115 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1116 error("%s: private key %s contents do not match public",
1117 __func__, id->filename);
1118 return SSH_ERR_KEY_NOT_FOUND;
1119 }
1120 r = sshkey_sign(prv, sigp, lenp, data, datalen, alg, compat);
1121 sshkey_free(prv);
1122 return r;
1123 }
1124
1125 static int
1126 id_filename_matches(Identity *id, Identity *private_id)
1127 {
1128 const char *suffixes[] = { ".pub", "-cert.pub", NULL };
1129 size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1130 size_t i, slen;
1131
1132 if (strcmp(id->filename, private_id->filename) == 0)
1133 return 1;
1134 for (i = 0; suffixes[i]; i++) {
1135 slen = strlen(suffixes[i]);
1136 if (len > slen && plen == len - slen &&
1137 strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1138 memcmp(id->filename, private_id->filename, plen) == 0)
1139 return 1;
1140 }
1141 return 0;
1142 }
1143
1144 static int
1145 sign_and_send_pubkey(struct ssh *ssh, Authctxt *authctxt, Identity *id)
1146 {
1147 struct sshbuf *b = NULL;
1148 Identity *private_id, *sign_id = NULL;
1149 u_char *signature = NULL;
1150 size_t slen = 0, skip = 0;
1151 int r, fallback_sigtype, sent = 0;
1152 char *alg = NULL, *fp = NULL;
1153 const char *loc = "";
1154
1155 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1156 SSH_FP_DEFAULT)) == NULL)
1157 return 0;
1158
1159 debug3("%s: %s %s", __func__, sshkey_type(id->key), fp);
1160
1161 /*
1162 * If the key is an certificate, try to find a matching private key
1163 * and use it to complete the signature.
1164 * If no such private key exists, fall back to trying the certificate
1165 * key itself in case it has a private half already loaded.
1166 * This will try to set sign_id to the private key that will perform
1167 * the signature.
1168 */
1169 if (sshkey_is_cert(id->key)) {
1170 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1171 if (sshkey_equal_public(id->key, private_id->key) &&
1172 id->key->type != private_id->key->type) {
1173 sign_id = private_id;
1174 break;
1175 }
1176 }
1177 /*
1178 * Exact key matches are preferred, but also allow
1179 * filename matches for non-PKCS#11/agent keys that
1180 * didn't load public keys. This supports the case
1181 * of keeping just a private key file and public
1182 * certificate on disk.
1183 */
1184 if (sign_id == NULL &&
1185 !id->isprivate && id->agent_fd == -1 &&
1186 (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1187 TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1188 if (private_id->key == NULL &&
1189 id_filename_matches(id, private_id)) {
1190 sign_id = private_id;
1191 break;
1192 }
1193 }
1194 }
1195 if (sign_id != NULL) {
1196 debug2("%s: using private key \"%s\"%s for "
1197 "certificate", __func__, id->filename,
1198 id->agent_fd != -1 ? " from agent" : "");
1199 } else {
1200 debug("%s: no separate private key for certificate "
1201 "\"%s\"", __func__, id->filename);
1202 }
1203 }
1204
1205 /*
1206 * If the above didn't select another identity to do the signing
1207 * then default to the one we started with.
1208 */
1209 if (sign_id == NULL)
1210 sign_id = id;
1211
1212 /* assemble and sign data */
1213 for (fallback_sigtype = 0; fallback_sigtype <= 1; fallback_sigtype++) {
1214 free(alg);
1215 slen = 0;
1216 signature = NULL;
1217 if ((alg = key_sig_algorithm(fallback_sigtype ? NULL : ssh,
1218 id->key)) == NULL) {
1219 error("%s: no mutual signature supported", __func__);
1220 goto out;
1221 }
1222 debug3("%s: signing using %s", __func__, alg);
1223
1224 sshbuf_free(b);
1225 if ((b = sshbuf_new()) == NULL)
1226 fatal("%s: sshbuf_new failed", __func__);
1227 if (datafellows & SSH_OLD_SESSIONID) {
1228 if ((r = sshbuf_put(b, session_id2,
1229 session_id2_len)) != 0) {
1230 fatal("%s: sshbuf_put: %s",
1231 __func__, ssh_err(r));
1232 }
1233 } else {
1234 if ((r = sshbuf_put_string(b, session_id2,
1235 session_id2_len)) != 0) {
1236 fatal("%s: sshbuf_put_string: %s",
1237 __func__, ssh_err(r));
1238 }
1239 }
1240 skip = sshbuf_len(b);
1241 if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1242 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1243 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1244 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
1245 (r = sshbuf_put_u8(b, 1)) != 0 ||
1246 (r = sshbuf_put_cstring(b, alg)) != 0 ||
1247 (r = sshkey_puts(id->key, b)) != 0) {
1248 fatal("%s: assemble signed data: %s",
1249 __func__, ssh_err(r));
1250 }
1251
1252 /* generate signature */
1253 r = identity_sign(sign_id, &signature, &slen,
1254 sshbuf_ptr(b), sshbuf_len(b), datafellows, alg);
1255 if (r == 0)
1256 break;
1257 else if (r == SSH_ERR_KEY_NOT_FOUND)
1258 goto out; /* soft failure */
1259 else if (r == SSH_ERR_SIGN_ALG_UNSUPPORTED &&
1260 !fallback_sigtype) {
1261 if (sign_id->agent_fd != -1)
1262 loc = "agent ";
1263 else if ((sign_id->key->flags & SSHKEY_FLAG_EXT) != 0)
1264 loc = "token ";
1265 logit("%skey %s %s returned incorrect signature type",
1266 loc, sshkey_type(id->key), fp);
1267 continue;
1268 }
1269 error("%s: signing failed: %s", __func__, ssh_err(r));
1270 goto out;
1271 }
1272 if (slen == 0 || signature == NULL) /* shouldn't happen */
1273 fatal("%s: no signature", __func__);
1274
1275 /* append signature */
1276 if ((r = sshbuf_put_string(b, signature, slen)) != 0)
1277 fatal("%s: append signature: %s", __func__, ssh_err(r));
1278
1279 #ifdef DEBUG_PK
1280 sshbuf_dump(b, stderr);
1281 #endif
1282 /* skip session id and packet type */
1283 if ((r = sshbuf_consume(b, skip + 1)) != 0)
1284 fatal("%s: consume: %s", __func__, ssh_err(r));
1285
1286 /* put remaining data from buffer into packet */
1287 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1288 (r = sshpkt_putb(ssh, b)) != 0 ||
1289 (r = sshpkt_send(ssh)) != 0)
1290 fatal("%s: enqueue request: %s", __func__, ssh_err(r));
1291
1292 /* success */
1293 sent = 1;
1294
1295 out:
1296 free(fp);
1297 free(alg);
1298 sshbuf_free(b);
1299 freezero(signature, slen);
1300 return sent;
1301 }
1302
1303 static int
1304 send_pubkey_test(struct ssh *ssh, Authctxt *authctxt, Identity *id)
1305 {
1306 u_char *blob = NULL;
1307 char *alg = NULL;
1308 size_t bloblen;
1309 u_int have_sig = 0;
1310 int sent = 0, r;
1311
1312 if ((alg = key_sig_algorithm(ssh, id->key)) == NULL) {
1313 debug("%s: no mutual signature algorithm", __func__);
1314 goto out;
1315 }
1316
1317 if ((r = sshkey_to_blob(id->key, &blob, &bloblen)) != 0) {
1318 /* we cannot handle this key */
1319 debug3("%s: cannot handle key", __func__);
1320 goto out;
1321 }
1322 /* register callback for USERAUTH_PK_OK message */
1323 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1324
1325 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1326 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1327 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1328 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1329 (r = sshpkt_put_u8(ssh, have_sig)) != 0 ||
1330 (r = sshpkt_put_cstring(ssh, alg)) != 0 ||
1331 (r = sshpkt_put_string(ssh, blob, bloblen)) != 0 ||
1332 (r = sshpkt_send(ssh)) != 0)
1333 fatal("%s: %s", __func__, ssh_err(r));
1334 sent = 1;
1335
1336 out:
1337 free(alg);
1338 free(blob);
1339 return sent;
1340 }
1341
1342 static struct sshkey *
1343 load_identity_file(Identity *id)
1344 {
1345 struct sshkey *private = NULL;
1346 char prompt[300], *passphrase, *comment;
1347 int r, perm_ok = 0, quit = 0, i;
1348 struct stat st;
1349
1350 if (stat(id->filename, &st) < 0) {
1351 (id->userprovided ? logit : debug3)("no such identity: %s: %s",
1352 id->filename, strerror(errno));
1353 return NULL;
1354 }
1355 snprintf(prompt, sizeof prompt,
1356 "Enter passphrase for key '%.100s': ", id->filename);
1357 for (i = 0; i <= options.number_of_password_prompts; i++) {
1358 if (i == 0)
1359 passphrase = "";
1360 else {
1361 passphrase = read_passphrase(prompt, 0);
1362 if (*passphrase == '\0') {
1363 debug2("no passphrase given, try next key");
1364 free(passphrase);
1365 break;
1366 }
1367 }
1368 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1369 passphrase, &private, &comment, &perm_ok))) {
1370 case 0:
1371 break;
1372 case SSH_ERR_KEY_WRONG_PASSPHRASE:
1373 if (options.batch_mode) {
1374 quit = 1;
1375 break;
1376 }
1377 if (i != 0)
1378 debug2("bad passphrase given, try again...");
1379 break;
1380 case SSH_ERR_SYSTEM_ERROR:
1381 if (errno == ENOENT) {
1382 debug2("Load key \"%s\": %s",
1383 id->filename, ssh_err(r));
1384 quit = 1;
1385 break;
1386 }
1387 /* FALLTHROUGH */
1388 default:
1389 error("Load key \"%s\": %s", id->filename, ssh_err(r));
1390 quit = 1;
1391 break;
1392 }
1393 if (!quit && private != NULL && id->agent_fd == -1 &&
1394 !(id->key && id->isprivate))
1395 maybe_add_key_to_agent(id->filename, private, comment,
1396 passphrase);
1397 if (i > 0)
1398 freezero(passphrase, strlen(passphrase));
1399 free(comment);
1400 if (private != NULL || quit)
1401 break;
1402 }
1403 return private;
1404 }
1405
1406 static int
1407 key_type_allowed_by_config(struct sshkey *key)
1408 {
1409 if (match_pattern_list(sshkey_ssh_name(key),
1410 options.pubkey_key_types, 0) == 1)
1411 return 1;
1412
1413 /* RSA keys/certs might be allowed by alternate signature types */
1414 switch (key->type) {
1415 case KEY_RSA:
1416 if (match_pattern_list("rsa-sha2-512",
1417 options.pubkey_key_types, 0) == 1)
1418 return 1;
1419 if (match_pattern_list("rsa-sha2-256",
1420 options.pubkey_key_types, 0) == 1)
1421 return 1;
1422 break;
1423 case KEY_RSA_CERT:
1424 if (match_pattern_list("rsa-sha2-512-cert-v01 (at) openssh.com",
1425 options.pubkey_key_types, 0) == 1)
1426 return 1;
1427 if (match_pattern_list("rsa-sha2-256-cert-v01 (at) openssh.com",
1428 options.pubkey_key_types, 0) == 1)
1429 return 1;
1430 break;
1431 }
1432 return 0;
1433 }
1434
1435
1436 /*
1437 * try keys in the following order:
1438 * 1. certificates listed in the config file
1439 * 2. other input certificates
1440 * 3. agent keys that are found in the config file
1441 * 4. other agent keys
1442 * 5. keys that are only listed in the config file
1443 */
1444 static void
1445 pubkey_prepare(Authctxt *authctxt)
1446 {
1447 struct identity *id, *id2, *tmp;
1448 struct idlist agent, files, *preferred;
1449 struct sshkey *key;
1450 int agent_fd = -1, i, r, found;
1451 size_t j;
1452 struct ssh_identitylist *idlist;
1453
1454 TAILQ_INIT(&agent); /* keys from the agent */
1455 TAILQ_INIT(&files); /* keys from the config file */
1456 preferred = &authctxt->keys;
1457 TAILQ_INIT(preferred); /* preferred order of keys */
1458
1459 /* list of keys stored in the filesystem and PKCS#11 */
1460 for (i = 0; i < options.num_identity_files; i++) {
1461 key = options.identity_keys[i];
1462 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1463 continue;
1464 options.identity_keys[i] = NULL;
1465 id = xcalloc(1, sizeof(*id));
1466 id->agent_fd = -1;
1467 id->key = key;
1468 id->filename = xstrdup(options.identity_files[i]);
1469 id->userprovided = options.identity_file_userprovided[i];
1470 TAILQ_INSERT_TAIL(&files, id, next);
1471 }
1472 /* list of certificates specified by user */
1473 for (i = 0; i < options.num_certificate_files; i++) {
1474 key = options.certificates[i];
1475 if (!sshkey_is_cert(key) || key->cert == NULL ||
1476 key->cert->type != SSH2_CERT_TYPE_USER)
1477 continue;
1478 id = xcalloc(1, sizeof(*id));
1479 id->agent_fd = -1;
1480 id->key = key;
1481 id->filename = xstrdup(options.certificate_files[i]);
1482 id->userprovided = options.certificate_file_userprovided[i];
1483 TAILQ_INSERT_TAIL(preferred, id, next);
1484 }
1485 /* list of keys supported by the agent */
1486 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1487 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1488 debug("%s: ssh_get_authentication_socket: %s",
1489 __func__, ssh_err(r));
1490 } else if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1491 if (r != SSH_ERR_AGENT_NO_IDENTITIES)
1492 debug("%s: ssh_fetch_identitylist: %s",
1493 __func__, ssh_err(r));
1494 close(agent_fd);
1495 } else {
1496 for (j = 0; j < idlist->nkeys; j++) {
1497 found = 0;
1498 TAILQ_FOREACH(id, &files, next) {
1499 /*
1500 * agent keys from the config file are
1501 * preferred
1502 */
1503 if (sshkey_equal(idlist->keys[j], id->key)) {
1504 TAILQ_REMOVE(&files, id, next);
1505 TAILQ_INSERT_TAIL(preferred, id, next);
1506 id->agent_fd = agent_fd;
1507 found = 1;
1508 break;
1509 }
1510 }
1511 if (!found && !options.identities_only) {
1512 id = xcalloc(1, sizeof(*id));
1513 /* XXX "steals" key/comment from idlist */
1514 id->key = idlist->keys[j];
1515 id->filename = idlist->comments[j];
1516 idlist->keys[j] = NULL;
1517 idlist->comments[j] = NULL;
1518 id->agent_fd = agent_fd;
1519 TAILQ_INSERT_TAIL(&agent, id, next);
1520 }
1521 }
1522 ssh_free_identitylist(idlist);
1523 /* append remaining agent keys */
1524 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1525 TAILQ_REMOVE(&agent, id, next);
1526 TAILQ_INSERT_TAIL(preferred, id, next);
1527 }
1528 authctxt->agent_fd = agent_fd;
1529 }
1530 /* Prefer PKCS11 keys that are explicitly listed */
1531 TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1532 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1533 continue;
1534 found = 0;
1535 TAILQ_FOREACH(id2, &files, next) {
1536 if (id2->key == NULL ||
1537 (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
1538 continue;
1539 if (sshkey_equal(id->key, id2->key)) {
1540 TAILQ_REMOVE(&files, id, next);
1541 TAILQ_INSERT_TAIL(preferred, id, next);
1542 found = 1;
1543 break;
1544 }
1545 }
1546 /* If IdentitiesOnly set and key not found then don't use it */
1547 if (!found && options.identities_only) {
1548 TAILQ_REMOVE(&files, id, next);
1549 freezero(id, sizeof(*id));
1550 }
1551 }
1552 /* append remaining keys from the config file */
1553 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1554 TAILQ_REMOVE(&files, id, next);
1555 TAILQ_INSERT_TAIL(preferred, id, next);
1556 }
1557 /* finally, filter by PubkeyAcceptedKeyTypes */
1558 TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1559 if (id->key != NULL && !key_type_allowed_by_config(id->key)) {
1560 debug("Skipping %s key %s - "
1561 "not in PubkeyAcceptedKeyTypes",
1562 sshkey_ssh_name(id->key), id->filename);
1563 TAILQ_REMOVE(preferred, id, next);
1564 sshkey_free(id->key);
1565 free(id->filename);
1566 memset(id, 0, sizeof(*id));
1567 continue;
1568 }
1569 debug2("key: %s (%p)%s%s", id->filename, id->key,
1570 id->userprovided ? ", explicit" : "",
1571 id->agent_fd != -1 ? ", agent" : "");
1572 }
1573 }
1574
1575 static void
1576 pubkey_cleanup(Authctxt *authctxt)
1577 {
1578 Identity *id;
1579
1580 if (authctxt->agent_fd != -1)
1581 ssh_close_authentication_socket(authctxt->agent_fd);
1582 for (id = TAILQ_FIRST(&authctxt->keys); id;
1583 id = TAILQ_FIRST(&authctxt->keys)) {
1584 TAILQ_REMOVE(&authctxt->keys, id, next);
1585 sshkey_free(id->key);
1586 free(id->filename);
1587 free(id);
1588 }
1589 }
1590
1591 static void
1592 pubkey_reset(Authctxt *authctxt)
1593 {
1594 Identity *id;
1595
1596 TAILQ_FOREACH(id, &authctxt->keys, next)
1597 id->tried = 0;
1598 }
1599
1600 static int
1601 try_identity(Identity *id)
1602 {
1603 if (!id->key)
1604 return (0);
1605 if (sshkey_type_plain(id->key->type) == KEY_RSA &&
1606 (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1607 debug("Skipped %s key %s for RSA/MD5 server",
1608 sshkey_type(id->key), id->filename);
1609 return (0);
1610 }
1611 return 1;
1612 }
1613
1614 int
1615 userauth_pubkey(Authctxt *authctxt)
1616 {
1617 struct ssh *ssh = active_state; /* XXX */
1618 Identity *id;
1619 int sent = 0;
1620 char *fp;
1621
1622 while ((id = TAILQ_FIRST(&authctxt->keys))) {
1623 if (id->tried++)
1624 return (0);
1625 /* move key to the end of the queue */
1626 TAILQ_REMOVE(&authctxt->keys, id, next);
1627 TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1628 /*
1629 * send a test message if we have the public key. for
1630 * encrypted keys we cannot do this and have to load the
1631 * private key instead
1632 */
1633 if (id->key != NULL) {
1634 if (try_identity(id)) {
1635 if ((fp = sshkey_fingerprint(id->key,
1636 options.fingerprint_hash,
1637 SSH_FP_DEFAULT)) == NULL) {
1638 error("%s: sshkey_fingerprint failed",
1639 __func__);
1640 return 0;
1641 }
1642 debug("Offering public key: %s %s %s",
1643 sshkey_type(id->key), fp, id->filename);
1644 free(fp);
1645 sent = send_pubkey_test(ssh, authctxt, id);
1646 }
1647 } else {
1648 debug("Trying private key: %s", id->filename);
1649 id->key = load_identity_file(id);
1650 if (id->key != NULL) {
1651 if (try_identity(id)) {
1652 id->isprivate = 1;
1653 sent = sign_and_send_pubkey(ssh,
1654 authctxt, id);
1655 }
1656 sshkey_free(id->key);
1657 id->key = NULL;
1658 id->isprivate = 0;
1659 }
1660 }
1661 if (sent)
1662 return (sent);
1663 }
1664 return (0);
1665 }
1666
1667 /*
1668 * Send userauth request message specifying keyboard-interactive method.
1669 */
1670 int
1671 userauth_kbdint(Authctxt *authctxt)
1672 {
1673 struct ssh *ssh = active_state; /* XXX */
1674 static int attempt = 0;
1675 int r;
1676
1677 if (attempt++ >= options.number_of_password_prompts)
1678 return 0;
1679 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1680 if (attempt > 1 && !authctxt->info_req_seen) {
1681 debug3("userauth_kbdint: disable: no info_req_seen");
1682 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1683 return 0;
1684 }
1685
1686 debug2("userauth_kbdint");
1687 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1688 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1689 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1690 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1691 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* lang */
1692 (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ?
1693 options.kbd_interactive_devices : "")) != 0 ||
1694 (r = sshpkt_send(ssh)) != 0)
1695 fatal("%s: %s", __func__, ssh_err(r));
1696
1697 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1698 return 1;
1699 }
1700
1701 /*
1702 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1703 */
1704 int
1705 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1706 {
1707 Authctxt *authctxt = ssh->authctxt;
1708 char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL;
1709 char *response = NULL;
1710 u_char echo = 0;
1711 u_int num_prompts, i;
1712 int r;
1713
1714 debug2("input_userauth_info_req");
1715
1716 if (authctxt == NULL)
1717 fatal("input_userauth_info_req: no authentication context");
1718
1719 authctxt->info_req_seen = 1;
1720
1721 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1722 (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 ||
1723 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1724 goto out;
1725 if (strlen(name) > 0)
1726 logit("%s", name);
1727 if (strlen(inst) > 0)
1728 logit("%s", inst);
1729
1730 if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0)
1731 goto out;
1732 /*
1733 * Begin to build info response packet based on prompts requested.
1734 * We commit to providing the correct number of responses, so if
1735 * further on we run into a problem that prevents this, we have to
1736 * be sure and clean this up and send a correct error response.
1737 */
1738 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 ||
1739 (r = sshpkt_put_u32(ssh, num_prompts)) != 0)
1740 goto out;
1741
1742 debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1743 for (i = 0; i < num_prompts; i++) {
1744 if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 ||
1745 (r = sshpkt_get_u8(ssh, &echo)) != 0)
1746 goto out;
1747 response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1748 if ((r = sshpkt_put_cstring(ssh, response)) != 0)
1749 goto out;
1750 freezero(response, strlen(response));
1751 free(prompt);
1752 response = prompt = NULL;
1753 }
1754 /* done with parsing incoming message. */
1755 if ((r = sshpkt_get_end(ssh)) != 0 ||
1756 (r = sshpkt_add_padding(ssh, 64)) != 0)
1757 goto out;
1758 r = sshpkt_send(ssh);
1759 out:
1760 if (response)
1761 freezero(response, strlen(response));
1762 free(prompt);
1763 free(name);
1764 free(inst);
1765 free(lang);
1766 return r;
1767 }
1768
1769 static int
1770 ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp,
1771 const u_char *data, size_t datalen)
1772 {
1773 struct sshbuf *b;
1774 struct stat st;
1775 pid_t pid;
1776 int i, r, to[2], from[2], status, sock = packet_get_connection_in();
1777 u_char rversion = 0, version = 2;
1778 void (*osigchld)(int);
1779
1780 *sigp = NULL;
1781 *lenp = 0;
1782
1783 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1784 error("%s: not installed: %s", __func__, strerror(errno));
1785 return -1;
1786 }
1787 if (fflush(stdout) != 0) {
1788 error("%s: fflush: %s", __func__, strerror(errno));
1789 return -1;
1790 }
1791 if (pipe(to) < 0) {
1792 error("%s: pipe: %s", __func__, strerror(errno));
1793 return -1;
1794 }
1795 if (pipe(from) < 0) {
1796 error("%s: pipe: %s", __func__, strerror(errno));
1797 return -1;
1798 }
1799 if ((pid = fork()) < 0) {
1800 error("%s: fork: %s", __func__, strerror(errno));
1801 return -1;
1802 }
1803 osigchld = signal(SIGCHLD, SIG_DFL);
1804 if (pid == 0) {
1805 /* keep the socket on exec */
1806 fcntl(sock, F_SETFD, 0);
1807 close(from[0]);
1808 if (dup2(from[1], STDOUT_FILENO) < 0)
1809 fatal("%s: dup2: %s", __func__, strerror(errno));
1810 close(to[1]);
1811 if (dup2(to[0], STDIN_FILENO) < 0)
1812 fatal("%s: dup2: %s", __func__, strerror(errno));
1813 close(from[1]);
1814 close(to[0]);
1815 /* Close everything but stdio and the socket */
1816 for (i = STDERR_FILENO + 1; i < sock; i++)
1817 close(i);
1818 closefrom(sock + 1);
1819 debug3("%s: [child] pid=%ld, exec %s",
1820 __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
1821 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
1822 fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
1823 strerror(errno));
1824 }
1825 close(from[1]);
1826 close(to[0]);
1827
1828 if ((b = sshbuf_new()) == NULL)
1829 fatal("%s: sshbuf_new failed", __func__);
1830 /* send # of sock, data to be signed */
1831 if ((r = sshbuf_put_u32(b, sock)) != 0 ||
1832 (r = sshbuf_put_string(b, data, datalen)) != 0)
1833 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1834 if (ssh_msg_send(to[1], version, b) == -1)
1835 fatal("%s: couldn't send request", __func__);
1836 sshbuf_reset(b);
1837 r = ssh_msg_recv(from[0], b);
1838 close(from[0]);
1839 close(to[1]);
1840 if (r < 0) {
1841 error("%s: no reply", __func__);
1842 goto fail;
1843 }
1844
1845 errno = 0;
1846 while (waitpid(pid, &status, 0) < 0) {
1847 if (errno != EINTR) {
1848 error("%s: waitpid %ld: %s",
1849 __func__, (long)pid, strerror(errno));
1850 goto fail;
1851 }
1852 }
1853 if (!WIFEXITED(status)) {
1854 error("%s: exited abnormally", __func__);
1855 goto fail;
1856 }
1857 if (WEXITSTATUS(status) != 0) {
1858 error("%s: exited with status %d",
1859 __func__, WEXITSTATUS(status));
1860 goto fail;
1861 }
1862 if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
1863 error("%s: buffer error: %s", __func__, ssh_err(r));
1864 goto fail;
1865 }
1866 if (rversion != version) {
1867 error("%s: bad version", __func__);
1868 goto fail;
1869 }
1870 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
1871 error("%s: buffer error: %s", __func__, ssh_err(r));
1872 fail:
1873 signal(SIGCHLD, osigchld);
1874 sshbuf_free(b);
1875 return -1;
1876 }
1877 signal(SIGCHLD, osigchld);
1878 sshbuf_free(b);
1879
1880 return 0;
1881 }
1882
1883 int
1884 userauth_hostbased(Authctxt *authctxt)
1885 {
1886 struct ssh *ssh = active_state; /* XXX */
1887 struct sshkey *private = NULL;
1888 struct sshbuf *b = NULL;
1889 u_char *sig = NULL, *keyblob = NULL;
1890 char *fp = NULL, *chost = NULL, *lname = NULL;
1891 size_t siglen = 0, keylen = 0;
1892 int i, r, success = 0;
1893
1894 if (authctxt->ktypes == NULL) {
1895 authctxt->oktypes = xstrdup(options.hostbased_key_types);
1896 authctxt->ktypes = authctxt->oktypes;
1897 }
1898
1899 /*
1900 * Work through each listed type pattern in HostbasedKeyTypes,
1901 * trying each hostkey that matches the type in turn.
1902 */
1903 for (;;) {
1904 if (authctxt->active_ktype == NULL)
1905 authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
1906 if (authctxt->active_ktype == NULL ||
1907 *authctxt->active_ktype == '\0')
1908 break;
1909 debug3("%s: trying key type %s", __func__,
1910 authctxt->active_ktype);
1911
1912 /* check for a useful key */
1913 private = NULL;
1914 for (i = 0; i < authctxt->sensitive->nkeys; i++) {
1915 if (authctxt->sensitive->keys[i] == NULL ||
1916 authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
1917 continue;
1918 if (match_pattern_list(
1919 sshkey_ssh_name(authctxt->sensitive->keys[i]),
1920 authctxt->active_ktype, 0) != 1)
1921 continue;
1922 /* we take and free the key */
1923 private = authctxt->sensitive->keys[i];
1924 authctxt->sensitive->keys[i] = NULL;
1925 break;
1926 }
1927 /* Found one */
1928 if (private != NULL)
1929 break;
1930 /* No more keys of this type; advance */
1931 authctxt->active_ktype = NULL;
1932 }
1933 if (private == NULL) {
1934 free(authctxt->oktypes);
1935 authctxt->oktypes = authctxt->ktypes = NULL;
1936 authctxt->active_ktype = NULL;
1937 debug("No more client hostkeys for hostbased authentication.");
1938 goto out;
1939 }
1940
1941 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
1942 SSH_FP_DEFAULT)) == NULL) {
1943 error("%s: sshkey_fingerprint failed", __func__);
1944 goto out;
1945 }
1946 debug("%s: trying hostkey %s %s",
1947 __func__, sshkey_ssh_name(private), fp);
1948
1949 /* figure out a name for the client host */
1950 if ((lname = get_local_name(packet_get_connection_in())) == NULL) {
1951 error("%s: cannot get local ipaddr/name", __func__);
1952 goto out;
1953 }
1954
1955 /* XXX sshbuf_put_stringf? */
1956 xasprintf(&chost, "%s.", lname);
1957 debug2("%s: chost %s", __func__, chost);
1958
1959 /* construct data */
1960 if ((b = sshbuf_new()) == NULL) {
1961 error("%s: sshbuf_new failed", __func__);
1962 goto out;
1963 }
1964 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
1965 error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
1966 goto out;
1967 }
1968 if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
1969 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1970 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1971 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1972 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
1973 (r = sshbuf_put_cstring(b, sshkey_ssh_name(private))) != 0 ||
1974 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
1975 (r = sshbuf_put_cstring(b, chost)) != 0 ||
1976 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
1977 error("%s: buffer error: %s", __func__, ssh_err(r));
1978 goto out;
1979 }
1980
1981 #ifdef DEBUG_PK
1982 sshbuf_dump(b, stderr);
1983 #endif
1984 r = ssh_keysign(private, &sig, &siglen,
1985 sshbuf_ptr(b), sshbuf_len(b));
1986 if (r != 0) {
1987 error("sign using hostkey %s %s failed",
1988 sshkey_ssh_name(private), fp);
1989 goto out;
1990 }
1991 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1992 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1993 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1994 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1995 (r = sshpkt_put_cstring(ssh, sshkey_ssh_name(private))) != 0 ||
1996 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
1997 (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
1998 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
1999 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
2000 (r = sshpkt_send(ssh)) != 0) {
2001 error("%s: packet error: %s", __func__, ssh_err(r));
2002 goto out;
2003 }
2004 success = 1;
2005
2006 out:
2007 if (sig != NULL)
2008 freezero(sig, siglen);
2009 free(keyblob);
2010 free(lname);
2011 free(fp);
2012 free(chost);
2013 sshkey_free(private);
2014 sshbuf_free(b);
2015
2016 return success;
2017 }
2018
2019 /* find auth method */
2020
2021 /*
2022 * given auth method name, if configurable options permit this method fill
2023 * in auth_ident field and return true, otherwise return false.
2024 */
2025 static int
2026 authmethod_is_enabled(Authmethod *method)
2027 {
2028 if (method == NULL)
2029 return 0;
2030 /* return false if options indicate this method is disabled */
2031 if (method->enabled == NULL || *method->enabled == 0)
2032 return 0;
2033 /* return false if batch mode is enabled but method needs interactive mode */
2034 if (method->batch_flag != NULL && *method->batch_flag != 0)
2035 return 0;
2036 return 1;
2037 }
2038
2039 static Authmethod *
2040 authmethod_lookup(const char *name)
2041 {
2042 Authmethod *method = NULL;
2043 if (name != NULL)
2044 for (method = authmethods; method->name != NULL; method++)
2045 if (strcmp(name, method->name) == 0)
2046 return method;
2047 debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
2048 return NULL;
2049 }
2050
2051 /* XXX internal state */
2052 static Authmethod *current = NULL;
2053 static char *supported = NULL;
2054 static char *preferred = NULL;
2055
2056 /*
2057 * Given the authentication method list sent by the server, return the
2058 * next method we should try. If the server initially sends a nil list,
2059 * use a built-in default list.
2060 */
2061 static Authmethod *
2062 authmethod_get(char *authlist)
2063 {
2064 char *name = NULL;
2065 u_int next;
2066
2067 /* Use a suitable default if we're passed a nil list. */
2068 if (authlist == NULL || strlen(authlist) == 0)
2069 authlist = options.preferred_authentications;
2070
2071 if (supported == NULL || strcmp(authlist, supported) != 0) {
2072 debug3("start over, passed a different list %s", authlist);
2073 free(supported);
2074 supported = xstrdup(authlist);
2075 preferred = options.preferred_authentications;
2076 debug3("preferred %s", preferred);
2077 current = NULL;
2078 } else if (current != NULL && authmethod_is_enabled(current))
2079 return current;
2080
2081 for (;;) {
2082 if ((name = match_list(preferred, supported, &next)) == NULL) {
2083 debug("No more authentication methods to try.");
2084 current = NULL;
2085 return NULL;
2086 }
2087 preferred += next;
2088 debug3("authmethod_lookup %s", name);
2089 debug3("remaining preferred: %s", preferred);
2090 if ((current = authmethod_lookup(name)) != NULL &&
2091 authmethod_is_enabled(current)) {
2092 debug3("authmethod_is_enabled %s", name);
2093 debug("Next authentication method: %s", name);
2094 free(name);
2095 return current;
2096 }
2097 free(name);
2098 }
2099 }
2100
2101 static char *
2102 authmethods_get(void)
2103 {
2104 Authmethod *method = NULL;
2105 struct sshbuf *b;
2106 char *list;
2107 int r;
2108
2109 if ((b = sshbuf_new()) == NULL)
2110 fatal("%s: sshbuf_new failed", __func__);
2111 for (method = authmethods; method->name != NULL; method++) {
2112 if (authmethod_is_enabled(method)) {
2113 if ((r = sshbuf_putf(b, "%s%s",
2114 sshbuf_len(b) ? "," : "", method->name)) != 0)
2115 fatal("%s: buffer error: %s",
2116 __func__, ssh_err(r));
2117 }
2118 }
2119 if ((list = sshbuf_dup_string(b)) == NULL)
2120 fatal("%s: sshbuf_dup_string failed", __func__);
2121 sshbuf_free(b);
2122 return list;
2123 }
2124