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