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