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