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