Fix typos
[TortoiseGit.git] / src / TortoisePlink / ssh / userauth2-client.c
blob3caa062fd751a3b964c14bb0fefc0e80c6474c70
1 /*
2 * Packet protocol layer for the client side of the SSH-2 userauth
3 * protocol (RFC 4252).
4 */
6 #include <assert.h>
8 #include "putty.h"
9 #include "ssh.h"
10 #include "bpp.h"
11 #include "ppl.h"
12 #include "sshcr.h"
14 #ifndef NO_GSSAPI
15 #include "gssc.h"
16 #include "gss.h"
17 #endif
19 #define BANNER_LIMIT 131072
21 typedef struct agent_key {
22 strbuf *blob, *comment;
23 ptrlen algorithm;
24 } agent_key;
26 struct ssh2_userauth_state {
27 int crState;
29 PacketProtocolLayer *transport_layer, *successor_layer;
30 Filename *keyfile, *detached_cert_file;
31 bool show_banner, tryagent, notrivialauth, change_username;
32 char *hostname, *fullhostname;
33 int port;
34 char *default_username;
35 bool try_ki_auth, try_gssapi_auth, try_gssapi_kex_auth, gssapi_fwd;
37 ptrlen session_id;
38 enum {
39 AUTH_TYPE_NONE,
40 AUTH_TYPE_PUBLICKEY,
41 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
42 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
43 AUTH_TYPE_PASSWORD,
44 AUTH_TYPE_GSSAPI, /* always QUIET */
45 AUTH_TYPE_KEYBOARD_INTERACTIVE,
46 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
47 } type;
48 bool need_pw, can_pubkey, can_passwd, can_keyb_inter;
49 SeatPromptResult spr;
50 bool tried_pubkey_config, done_agent;
51 struct ssh_connection_shared_gss_state *shgss;
52 #ifndef NO_GSSAPI
53 bool can_gssapi;
54 bool can_gssapi_keyex_auth;
55 bool tried_gssapi;
56 bool tried_gssapi_keyex_auth;
57 time_t gss_cred_expiry;
58 Ssh_gss_buf gss_buf;
59 Ssh_gss_buf gss_rcvtok, gss_sndtok;
60 Ssh_gss_stat gss_stat;
61 #endif
62 bool suppress_wait_for_response_packet;
63 strbuf *last_methods_string;
64 bool kbd_inter_refused;
65 prompts_t *cur_prompt;
66 uint32_t num_prompts;
67 const char *username;
68 char *locally_allocated_username;
69 char *password;
70 bool got_username;
71 strbuf *publickey_blob, *detached_cert_blob, *cert_pubkey_diagnosed;
72 bool privatekey_available, privatekey_encrypted;
73 char *publickey_algorithm;
74 char *publickey_comment;
75 void *agent_response_to_free;
76 ptrlen agent_response;
77 BinarySource asrc[1]; /* for reading SSH agent response */
78 size_t agent_keys_len;
79 agent_key *agent_keys;
80 size_t agent_key_index, agent_key_limit;
81 ptrlen agent_keyalg;
82 unsigned signflags;
83 int len;
84 PktOut *pktout;
85 bool is_trivial_auth;
87 agent_pending_query *auth_agent_query;
88 bufchain banner;
89 bufchain_sink banner_bs;
90 StripCtrlChars *banner_scc;
91 bool banner_scc_initialised;
93 char *authplugin_cmd;
94 Socket *authplugin;
95 uint32_t authplugin_version;
96 Plug authplugin_plug;
97 bufchain authplugin_bc;
98 strbuf *authplugin_incoming_msg;
99 size_t authplugin_backlog;
100 bool authplugin_eof;
101 bool authplugin_ki_active;
103 StripCtrlChars *ki_scc;
104 bool ki_scc_initialised;
105 bool ki_printed_header;
107 PacketProtocolLayer ppl;
110 static void ssh2_userauth_free(PacketProtocolLayer *);
111 static void ssh2_userauth_process_queue(PacketProtocolLayer *);
112 static bool ssh2_userauth_get_specials(
113 PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx);
114 static void ssh2_userauth_special_cmd(PacketProtocolLayer *ppl,
115 SessionSpecialCode code, int arg);
116 static void ssh2_userauth_reconfigure(PacketProtocolLayer *ppl, Conf *conf);
118 static void ssh2_userauth_agent_query(struct ssh2_userauth_state *, strbuf *);
119 static void ssh2_userauth_agent_callback(void *, void *, int);
120 static void ssh2_userauth_add_sigblob(
121 struct ssh2_userauth_state *s, PktOut *pkt, ptrlen pkblob, ptrlen sigblob);
122 static void ssh2_userauth_add_alg_and_publickey(
123 struct ssh2_userauth_state *s, PktOut *pkt, ptrlen alg, ptrlen pkblob);
124 static void ssh2_userauth_add_session_id(
125 struct ssh2_userauth_state *s, strbuf *sigdata);
126 #ifndef NO_GSSAPI
127 static PktOut *ssh2_userauth_gss_packet(
128 struct ssh2_userauth_state *s, const char *authtype);
129 #endif
130 static bool ssh2_userauth_ki_setup_prompts(
131 struct ssh2_userauth_state *s, BinarySource *src, bool plugin);
132 static bool ssh2_userauth_ki_run_prompts(struct ssh2_userauth_state *s);
133 static void ssh2_userauth_ki_write_responses(
134 struct ssh2_userauth_state *s, BinarySink *bs);
135 static void ssh2_userauth_final_output(PacketProtocolLayer *ppl);
137 static void ssh2_userauth_print_banner(struct ssh2_userauth_state *s);
138 static ptrlen workaround_rsa_sha2_cert_userauth(
139 struct ssh2_userauth_state *s, ptrlen id);
141 static const PacketProtocolLayerVtable ssh2_userauth_vtable = {
142 .free = ssh2_userauth_free,
143 .process_queue = ssh2_userauth_process_queue,
144 .get_specials = ssh2_userauth_get_specials,
145 .special_cmd = ssh2_userauth_special_cmd,
146 .reconfigure = ssh2_userauth_reconfigure,
147 .queued_data_size = ssh_ppl_default_queued_data_size,
148 .final_output = ssh2_userauth_final_output,
149 .name = "ssh-userauth",
152 PacketProtocolLayer *ssh2_userauth_new(
153 PacketProtocolLayer *successor_layer,
154 const char *hostname, int port, const char *fullhostname,
155 Filename *keyfile, Filename *detached_cert_file,
156 bool show_banner, bool tryagent, bool notrivialauth,
157 const char *default_username, bool change_username,
158 bool try_ki_auth, bool try_gssapi_auth, bool try_gssapi_kex_auth,
159 bool gssapi_fwd, struct ssh_connection_shared_gss_state *shgss,
160 const char *authplugin_cmd)
162 struct ssh2_userauth_state *s = snew(struct ssh2_userauth_state);
163 memset(s, 0, sizeof(*s));
164 s->ppl.vt = &ssh2_userauth_vtable;
166 s->successor_layer = successor_layer;
167 s->hostname = dupstr(hostname);
168 s->port = port;
169 s->fullhostname = dupstr(fullhostname);
170 s->keyfile = filename_copy(keyfile);
171 s->detached_cert_file = filename_copy(detached_cert_file);
172 s->show_banner = show_banner;
173 s->tryagent = tryagent;
174 s->notrivialauth = notrivialauth;
175 s->default_username = dupstr(default_username);
176 s->change_username = change_username;
177 s->try_ki_auth = try_ki_auth;
178 s->try_gssapi_auth = try_gssapi_auth;
179 s->try_gssapi_kex_auth = try_gssapi_kex_auth;
180 s->gssapi_fwd = gssapi_fwd;
181 s->shgss = shgss;
182 s->last_methods_string = strbuf_new();
183 s->is_trivial_auth = true;
184 bufchain_init(&s->banner);
185 bufchain_sink_init(&s->banner_bs, &s->banner);
186 s->authplugin_cmd = dupstr(authplugin_cmd);
187 bufchain_init(&s->authplugin_bc);
189 return &s->ppl;
192 void ssh2_userauth_set_transport_layer(PacketProtocolLayer *userauth,
193 PacketProtocolLayer *transport)
195 struct ssh2_userauth_state *s =
196 container_of(userauth, struct ssh2_userauth_state, ppl);
197 s->transport_layer = transport;
200 static void ssh2_userauth_free(PacketProtocolLayer *ppl)
202 struct ssh2_userauth_state *s =
203 container_of(ppl, struct ssh2_userauth_state, ppl);
204 bufchain_clear(&s->banner);
206 if (s->successor_layer)
207 ssh_ppl_free(s->successor_layer);
209 if (s->agent_keys) {
210 for (size_t i = 0; i < s->agent_keys_len; i++) {
211 strbuf_free(s->agent_keys[i].blob);
212 strbuf_free(s->agent_keys[i].comment);
214 sfree(s->agent_keys);
216 sfree(s->agent_response_to_free);
217 if (s->auth_agent_query)
218 agent_cancel_query(s->auth_agent_query);
219 filename_free(s->keyfile);
220 filename_free(s->detached_cert_file);
221 sfree(s->default_username);
222 sfree(s->locally_allocated_username);
223 sfree(s->hostname);
224 sfree(s->fullhostname);
225 if (s->cur_prompt)
226 free_prompts(s->cur_prompt);
227 sfree(s->publickey_comment);
228 sfree(s->publickey_algorithm);
229 if (s->publickey_blob)
230 strbuf_free(s->publickey_blob);
231 if (s->detached_cert_blob)
232 strbuf_free(s->detached_cert_blob);
233 if (s->cert_pubkey_diagnosed)
234 strbuf_free(s->cert_pubkey_diagnosed);
235 strbuf_free(s->last_methods_string);
236 if (s->banner_scc)
237 stripctrl_free(s->banner_scc);
238 if (s->ki_scc)
239 stripctrl_free(s->ki_scc);
240 sfree(s->authplugin_cmd);
241 if (s->authplugin)
242 sk_close(s->authplugin);
243 bufchain_clear(&s->authplugin_bc);
244 if (s->authplugin_incoming_msg)
245 strbuf_free(s->authplugin_incoming_msg);
246 sfree(s);
249 static void ssh2_userauth_handle_banner_packet(struct ssh2_userauth_state *s,
250 PktIn *pktin)
252 if (!s->show_banner)
253 return;
255 ptrlen string = get_string(pktin);
256 if (string.len > BANNER_LIMIT - bufchain_size(&s->banner))
257 string.len = BANNER_LIMIT - bufchain_size(&s->banner);
259 if (!s->banner_scc_initialised) {
260 s->banner_scc = seat_stripctrl_new(
261 s->ppl.seat, BinarySink_UPCAST(&s->banner_bs), SIC_BANNER);
262 if (s->banner_scc)
263 stripctrl_enable_line_limiting(s->banner_scc);
264 s->banner_scc_initialised = true;
267 if (s->banner_scc)
268 put_datapl(s->banner_scc, string);
269 else
270 put_datapl(&s->banner_bs, string);
273 static void ssh2_userauth_filter_queue(struct ssh2_userauth_state *s)
275 PktIn *pktin;
277 while ((pktin = pq_peek(s->ppl.in_pq)) != NULL) {
278 switch (pktin->type) {
279 case SSH2_MSG_USERAUTH_BANNER:
280 ssh2_userauth_handle_banner_packet(s, pktin);
281 pq_pop(s->ppl.in_pq);
282 break;
284 default:
285 return;
290 static PktIn *ssh2_userauth_pop(struct ssh2_userauth_state *s)
292 ssh2_userauth_filter_queue(s);
293 return pq_pop(s->ppl.in_pq);
296 static bool ssh2_userauth_signflags(struct ssh2_userauth_state *s,
297 unsigned *signflags, const char **algname)
299 *signflags = 0; /* default */
301 const ssh_keyalg *alg = find_pubkey_alg(*algname);
302 if (!alg)
303 return false; /* we don't know how to upgrade this */
305 unsigned supported_flags = ssh_keyalg_supported_flags(alg);
307 if (s->ppl.bpp->ext_info_rsa_sha512_ok &&
308 (supported_flags & SSH_AGENT_RSA_SHA2_512)) {
309 *signflags = SSH_AGENT_RSA_SHA2_512;
310 } else if (s->ppl.bpp->ext_info_rsa_sha256_ok &&
311 (supported_flags & SSH_AGENT_RSA_SHA2_256)) {
312 *signflags = SSH_AGENT_RSA_SHA2_256;
313 } else {
314 return false;
317 *algname = ssh_keyalg_alternate_ssh_id(alg, *signflags);
318 return true;
321 static void authplugin_plug_log(Plug *plug, PlugLogType type, SockAddr *addr,
322 int port, const char *err_msg, int err_code)
324 struct ssh2_userauth_state *s = container_of(
325 plug, struct ssh2_userauth_state, authplugin_plug);
326 PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
328 if (type == PLUGLOG_PROXY_MSG)
329 ppl_logevent("%s", err_msg);
332 static void authplugin_plug_closing(
333 Plug *plug, PlugCloseType type, const char *error_msg)
335 struct ssh2_userauth_state *s = container_of(
336 plug, struct ssh2_userauth_state, authplugin_plug);
337 s->authplugin_eof = true;
338 queue_idempotent_callback(&s->ppl.ic_process_queue);
341 static void authplugin_plug_receive(
342 Plug *plug, int urgent, const char *data, size_t len)
344 struct ssh2_userauth_state *s = container_of(
345 plug, struct ssh2_userauth_state, authplugin_plug);
346 bufchain_add(&s->authplugin_bc, data, len);
347 queue_idempotent_callback(&s->ppl.ic_process_queue);
350 static void authplugin_plug_sent(Plug *plug, size_t bufsize)
352 struct ssh2_userauth_state *s = container_of(
353 plug, struct ssh2_userauth_state, authplugin_plug);
354 s->authplugin_backlog = bufsize;
355 queue_idempotent_callback(&s->ppl.ic_process_queue);
358 static const PlugVtable authplugin_plugvt = {
359 .log = authplugin_plug_log,
360 .closing = authplugin_plug_closing,
361 .receive = authplugin_plug_receive,
362 .sent = authplugin_plug_sent,
365 static strbuf *authplugin_newmsg(uint8_t type)
367 strbuf *amsg = strbuf_new_nm();
368 put_uint32(amsg, 0); /* fill in later */
369 put_byte(amsg, type);
370 return amsg;
373 static void authplugin_send_free(struct ssh2_userauth_state *s, strbuf *amsg)
375 PUT_32BIT_MSB_FIRST(amsg->u, amsg->len - 4);
376 assert(s->authplugin);
377 s->authplugin_backlog = sk_write(s->authplugin, amsg->u, amsg->len);
378 strbuf_free(amsg);
381 static bool authplugin_expect_msg(struct ssh2_userauth_state *s,
382 unsigned *type, BinarySource *src)
384 if (s->authplugin_eof) {
385 *type = PLUGIN_EOF;
386 return true;
388 uint8_t len[4];
389 if (!bufchain_try_fetch(&s->authplugin_bc, len, 4))
390 return false;
391 size_t size = GET_32BIT_MSB_FIRST(len);
392 if (bufchain_size(&s->authplugin_bc) - 4 < size)
393 return false;
394 if (s->authplugin_incoming_msg) {
395 strbuf_clear(s->authplugin_incoming_msg);
396 } else {
397 s->authplugin_incoming_msg = strbuf_new_nm();
399 bufchain_consume(&s->authplugin_bc, 4); /* eat length field */
400 bufchain_fetch_consume(
401 &s->authplugin_bc, strbuf_append(s->authplugin_incoming_msg, size),
402 size);
403 BinarySource_BARE_INIT_PL(
404 src, ptrlen_from_strbuf(s->authplugin_incoming_msg));
405 *type = get_byte(src);
406 if (get_err(src))
407 *type = PLUGIN_NOTYPE;
408 return true;
411 static void authplugin_bad_packet(struct ssh2_userauth_state *s,
412 unsigned type, const char *fmt, ...)
414 strbuf *msg = strbuf_new();
415 switch (type) {
416 case PLUGIN_EOF:
417 put_dataz(msg, "Unexpected end of file from auth helper plugin");
418 break;
419 case PLUGIN_NOTYPE:
420 put_dataz(msg, "Received malformed packet from auth helper plugin "
421 "(too short to have a type code)");
422 break;
423 default:
424 put_fmt(msg, "Received unknown message type %u "
425 "from auth helper plugin", type);
426 break;
428 #define CASEDECL(name, value) \
429 case name: \
430 put_fmt(msg, "Received unexpected %s message from auth helper " \
431 "plugin", #name); \
432 break;
433 AUTHPLUGIN_MSG_NAMES(CASEDECL);
434 #undef CASEDECL
436 if (fmt) {
437 put_dataz(msg, " (");
438 va_list ap;
439 va_start(ap, fmt);
440 put_fmt(msg, fmt, ap);
441 va_end(ap);
442 put_dataz(msg, ")");
444 ssh_sw_abort(s->ppl.ssh, "%s", msg->s);
445 strbuf_free(msg);
448 static void ssh2_userauth_process_queue(PacketProtocolLayer *ppl)
450 struct ssh2_userauth_state *s =
451 container_of(ppl, struct ssh2_userauth_state, ppl);
452 PktIn *pktin;
454 ssh2_userauth_filter_queue(s); /* no matter why we were called */
456 crBegin(s->crState);
458 #ifndef NO_GSSAPI
459 s->tried_gssapi = false;
460 s->tried_gssapi_keyex_auth = false;
461 #endif
464 * Misc one-time setup for authentication.
466 s->publickey_blob = NULL;
467 s->session_id = ssh2_transport_get_session_id(s->transport_layer);
470 * Load the public half of any configured public key file for
471 * later use.
473 if (!filename_is_null(s->keyfile)) {
474 int keytype;
475 ppl_logevent("Reading key file \"%s\"",
476 filename_to_str(s->keyfile));
477 keytype = key_type(s->keyfile);
478 if (keytype == SSH_KEYTYPE_SSH2 ||
479 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
480 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
481 const char *error;
482 s->publickey_blob = strbuf_new();
483 if (ppk_loadpub_f(s->keyfile, &s->publickey_algorithm,
484 BinarySink_UPCAST(s->publickey_blob),
485 &s->publickey_comment, &error)) {
486 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
487 if (!s->privatekey_available)
488 ppl_logevent("Key file contains public key only");
489 s->privatekey_encrypted = ppk_encrypted_f(s->keyfile, NULL);
490 } else {
491 ppl_logevent("Unable to load key (%s)", error);
492 ppl_printf("Unable to load key file \"%s\" (%s)\r\n",
493 filename_to_str(s->keyfile), error);
494 strbuf_free(s->publickey_blob);
495 s->publickey_blob = NULL;
497 } else {
498 ppl_logevent("Unable to use this key file (%s)",
499 key_type_to_str(keytype));
500 ppl_printf("Unable to use key file \"%s\" (%s)\r\n",
501 filename_to_str(s->keyfile),
502 key_type_to_str(keytype));
503 s->publickey_blob = NULL;
508 * If the user provided a detached certificate file, load that.
510 if (!filename_is_null(s->detached_cert_file)) {
511 char *cert_error = NULL;
512 strbuf *cert_blob = strbuf_new();
513 char *algname = NULL;
514 char *comment = NULL;
516 ppl_logevent("Reading certificate file \"%s\"",
517 filename_to_str(s->detached_cert_file));
518 int keytype = key_type(s->detached_cert_file);
519 if (!(keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
520 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH)) {
521 cert_error = dupstr(key_type_to_str(keytype));
522 goto cert_load_done;
525 const char *error;
526 bool success = ppk_loadpub_f(
527 s->detached_cert_file, &algname,
528 BinarySink_UPCAST(cert_blob), &comment, &error);
530 if (!success) {
531 cert_error = dupstr(error);
532 goto cert_load_done;
535 const ssh_keyalg *certalg = find_pubkey_alg(algname);
536 if (!certalg) {
537 cert_error = dupprintf(
538 "unrecognised certificate type '%s'", algname);
539 goto cert_load_done;
542 if (!certalg->is_certificate) {
543 cert_error = dupprintf(
544 "key type '%s' is not a certificate", certalg->ssh_id);
545 goto cert_load_done;
548 /* OK, store the certificate blob to substitute for the
549 * public blob in all publickey auth packets. */
550 if (s->detached_cert_blob)
551 strbuf_free(s->detached_cert_blob);
552 s->detached_cert_blob = cert_blob;
553 cert_blob = NULL; /* prevent free */
555 cert_load_done:
556 if (cert_error) {
557 ppl_logevent("Unable to use this certificate file (%s)",
558 cert_error);
559 ppl_printf(
560 "Unable to use certificate file \"%s\" (%s)\r\n",
561 filename_to_str(s->detached_cert_file), cert_error);
562 sfree(cert_error);
565 if (cert_blob)
566 strbuf_free(cert_blob);
567 sfree(algname);
568 sfree(comment);
572 * Find out about any keys Pageant has (but if there's a public
573 * key configured, filter out all others).
575 if (s->tryagent && agent_exists()) {
576 ppl_logevent("Pageant is running. Requesting keys.");
578 /* Request the keys held by the agent. */
580 strbuf *request = strbuf_new_for_agent_query();
581 put_byte(request, SSH2_AGENTC_REQUEST_IDENTITIES);
582 ssh2_userauth_agent_query(s, request);
583 strbuf_free(request);
584 crWaitUntilV(!s->auth_agent_query);
586 BinarySource_BARE_INIT_PL(s->asrc, s->agent_response);
588 get_uint32(s->asrc); /* skip length field */
589 if (get_byte(s->asrc) == SSH2_AGENT_IDENTITIES_ANSWER) {
590 size_t nkeys = get_uint32(s->asrc);
591 size_t origpos = s->asrc->pos;
594 * Check that the agent response is well formed.
596 for (size_t i = 0; i < nkeys; i++) {
597 get_string(s->asrc); /* blob */
598 get_string(s->asrc); /* comment */
599 if (get_err(s->asrc)) {
600 ppl_logevent("Pageant's response was truncated");
601 goto done_agent_query;
606 * Copy the list of public-key blobs out of the Pageant
607 * response.
609 BinarySource_REWIND_TO(s->asrc, origpos);
610 s->agent_keys_len = nkeys;
611 s->agent_keys = snewn(s->agent_keys_len, agent_key);
612 for (size_t i = 0; i < nkeys; i++) {
613 s->agent_keys[i].blob = strbuf_dup(get_string(s->asrc));
614 s->agent_keys[i].comment = strbuf_dup(get_string(s->asrc));
616 /* Also, extract the algorithm string from the start
617 * of the public-key blob. */
618 s->agent_keys[i].algorithm = pubkey_blob_to_alg_name(
619 ptrlen_from_strbuf(s->agent_keys[i].blob));
622 ppl_logevent("Pageant has %"SIZEu" SSH-2 keys", nkeys);
624 if (s->publickey_blob) {
626 * If we've been given a specific public key blob,
627 * filter the list of keys to try from the agent down
628 * to only that one, or none if it's not there.
630 ptrlen our_blob = ptrlen_from_strbuf(s->publickey_blob);
631 size_t i;
633 for (i = 0; i < nkeys; i++) {
634 if (ptrlen_eq_ptrlen(our_blob, ptrlen_from_strbuf(
635 s->agent_keys[i].blob)))
636 break;
639 if (i < nkeys) {
640 ppl_logevent("Pageant key #%"SIZEu" matches "
641 "configured key file", i);
642 s->agent_key_index = i;
643 s->agent_key_limit = i+1;
644 } else {
645 ppl_logevent("Configured key file not in Pageant");
646 s->agent_key_index = 0;
647 s->agent_key_limit = 0;
649 } else {
651 * Otherwise, try them all.
653 s->agent_key_index = 0;
654 s->agent_key_limit = nkeys;
656 } else {
657 ppl_logevent("Failed to get reply from Pageant");
659 done_agent_query:;
662 s->got_username = false;
664 if (*s->authplugin_cmd) {
665 s->authplugin_plug.vt = &authplugin_plugvt;
666 s->authplugin = platform_start_subprocess(
667 s->authplugin_cmd, &s->authplugin_plug, "plugin");
668 ppl_logevent("Started authentication plugin: %s", s->authplugin_cmd);
671 if (s->authplugin) {
672 strbuf *amsg = authplugin_newmsg(PLUGIN_INIT);
673 put_uint32(amsg, PLUGIN_PROTOCOL_MAX_VERSION);
674 put_stringz(amsg, s->hostname);
675 put_uint32(amsg, s->port);
676 put_stringz(amsg, s->username ? s->username : "");
677 authplugin_send_free(s, amsg);
679 BinarySource src[1];
680 unsigned type;
681 crMaybeWaitUntilV(authplugin_expect_msg(s, &type, src));
682 switch (type) {
683 case PLUGIN_INIT_RESPONSE: {
684 s->authplugin_version = get_uint32(src);
685 ptrlen username = get_string(src);
686 if (get_err(src)) {
687 ssh_sw_abort(s->ppl.ssh, "Received malformed "
688 "PLUGIN_INIT_RESPONSE from auth helper plugin");
689 return;
691 if (s->authplugin_version > PLUGIN_PROTOCOL_MAX_VERSION) {
692 ssh_sw_abort(s->ppl.ssh, "Auth helper plugin announced "
693 "unsupported version number %"PRIu32,
694 s->authplugin_version);
695 return;
697 if (username.len) {
698 sfree(s->default_username);
699 s->default_username = mkstr(username);
700 ppl_logevent("Authentication plugin set username '%s'",
701 s->default_username);
703 break;
705 case PLUGIN_INIT_FAILURE: {
706 ptrlen message = get_string(src);
707 if (get_err(src)) {
708 ssh_sw_abort(s->ppl.ssh, "Received malformed "
709 "PLUGIN_INIT_FAILURE from auth helper plugin");
710 return;
712 /* This is a controlled error, so we need not completely
713 * abandon the connection. Instead, inform the user, and
714 * proceed as if the plugin was not present */
715 ppl_printf("Authentication plugin failed to initialise:\r\n");
716 seat_set_trust_status(s->ppl.seat, false);
717 ppl_printf("%.*s\r\n", PTRLEN_PRINTF(message));
718 seat_set_trust_status(s->ppl.seat, true);
719 sk_close(s->authplugin);
720 s->authplugin = NULL;
721 break;
723 default:
724 authplugin_bad_packet(s, type, "expected PLUGIN_INIT_RESPONSE or "
725 "PLUGIN_INIT_FAILURE");
726 return;
731 * We repeat this whole loop, including the username prompt,
732 * until we manage a successful authentication. If the user
733 * types the wrong _password_, they can be sent back to the
734 * beginning to try another username, if this is configured on.
735 * (If they specify a username in the config, they are never
736 * asked, even if they do give a wrong password.)
738 * I think this best serves the needs of
740 * - the people who have no configuration, no keys, and just
741 * want to try repeated (username,password) pairs until they
742 * type both correctly
744 * - people who have keys and configuration but occasionally
745 * need to fall back to passwords
747 * - people with a key held in Pageant, who might not have
748 * logged in to a particular machine before; so they want to
749 * type a username, and then _either_ their key will be
750 * accepted, _or_ they will type a password. If they mistype
751 * the username they will want to be able to get back and
752 * retype it!
754 while (1) {
756 * Get a username.
758 if (s->got_username && !s->change_username) {
760 * We got a username last time round this loop, and
761 * with change_username turned off we don't try to get
762 * it again.
764 } else if ((s->username = s->default_username) == NULL) {
765 s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
766 s->cur_prompt->to_server = true;
767 s->cur_prompt->from_server = false;
768 s->cur_prompt->name = dupstr("SSH login name");
769 add_prompt(s->cur_prompt, dupstr("login as: "), true);
770 s->spr = seat_get_userpass_input(
771 ppl_get_iseat(&s->ppl), s->cur_prompt);
772 while (s->spr.kind == SPRK_INCOMPLETE) {
773 crReturnV;
774 s->spr = seat_get_userpass_input(
775 ppl_get_iseat(&s->ppl), s->cur_prompt);
777 if (spr_is_abort(s->spr)) {
779 * seat_get_userpass_input() failed to get a username.
780 * Terminate.
782 free_prompts(s->cur_prompt);
783 s->cur_prompt = NULL;
784 ssh_spr_close(s->ppl.ssh, s->spr, "username prompt");
785 return;
787 sfree(s->locally_allocated_username); /* for change_username */
788 s->username = s->locally_allocated_username =
789 prompt_get_result(s->cur_prompt->prompts[0]);
790 free_prompts(s->cur_prompt);
791 s->cur_prompt = NULL;
792 } else {
793 if (seat_verbose(s->ppl.seat) || seat_interactive(s->ppl.seat))
794 ppl_printf("Using username \"%s\".\r\n", s->username);
796 s->got_username = true;
799 * Send an authentication request using method "none": (a)
800 * just in case it succeeds, and (b) so that we know what
801 * authentication methods we can usefully try next.
803 s->ppl.bpp->pls->actx = SSH2_PKTCTX_NOAUTH;
805 s->pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
806 put_stringz(s->pktout, s->username);
807 put_stringz(s->pktout, s->successor_layer->vt->name);
808 put_stringz(s->pktout, "none"); /* method */
809 pq_push(s->ppl.out_pq, s->pktout);
810 s->type = AUTH_TYPE_NONE;
812 s->tried_pubkey_config = false;
813 s->kbd_inter_refused = false;
814 s->done_agent = false;
816 while (1) {
818 * Wait for the result of the last authentication request,
819 * unless the request terminated for some reason on our
820 * own side.
822 if (s->suppress_wait_for_response_packet) {
823 pktin = NULL;
824 s->suppress_wait_for_response_packet = false;
825 } else {
826 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
830 * Now is a convenient point to spew any banner material
831 * that we've accumulated. (This should ensure that when
832 * we exit the auth loop, we haven't any left to deal
833 * with.)
835 * Don't show the banner if we're operating in non-verbose
836 * non-interactive mode. (It's probably a script, which
837 * means nobody will read the banner _anyway_, and
838 * moreover the printing of the banner will screw up
839 * processing on the output of (say) plink.)
841 * The banner data has been sanitised already by this
842 * point, but we still need to precede and follow it with
843 * anti-spoofing header lines.
845 ssh2_userauth_print_banner(s);
847 if (pktin && pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
848 ppl_logevent("Access granted");
849 goto userauth_success;
852 if (pktin && pktin->type != SSH2_MSG_USERAUTH_FAILURE &&
853 s->type != AUTH_TYPE_GSSAPI) {
854 ssh_proto_error(s->ppl.ssh, "Received unexpected packet "
855 "in response to authentication request, "
856 "type %d (%s)", pktin->type,
857 ssh2_pkt_type(s->ppl.bpp->pls->kctx,
858 s->ppl.bpp->pls->actx,
859 pktin->type));
860 return;
864 * OK, we're now sitting on a USERAUTH_FAILURE message, so
865 * we can look at the string in it and know what we can
866 * helpfully try next.
868 if (pktin && pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
869 ptrlen methods = get_string(pktin);
870 bool partial_success = get_bool(pktin);
872 if (!partial_success) {
874 * We have received an unequivocal Access
875 * Denied. This can translate to a variety of
876 * messages, or no message at all.
878 * For forms of authentication which are attempted
879 * implicitly, by which I mean without printing
880 * anything in the window indicating that we're
881 * trying them, we should never print 'Access
882 * denied'.
884 * If we do print a message saying that we're
885 * attempting some kind of authentication, it's OK
886 * to print a followup message saying it failed -
887 * but the message may sometimes be more specific
888 * than simply 'Access denied'.
890 * Additionally, if we'd just tried password
891 * authentication, we should break out of this
892 * whole loop so as to go back to the username
893 * prompt (iff we're configured to allow
894 * username change attempts).
896 if (s->type == AUTH_TYPE_NONE) {
897 /* do nothing */
898 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
899 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
900 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
901 ppl_printf("Server refused our key\r\n");
902 ppl_logevent("Server refused our key");
903 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
904 /* This _shouldn't_ happen except by a
905 * protocol bug causing client and server to
906 * disagree on what is a correct signature. */
907 ppl_printf("Server refused public-key signature"
908 " despite accepting key!\r\n");
909 ppl_logevent("Server refused public-key signature"
910 " despite accepting key!");
911 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
912 /* quiet, so no ppl_printf */
913 ppl_logevent("Server refused keyboard-interactive "
914 "authentication");
915 } else if (s->type==AUTH_TYPE_GSSAPI) {
916 /* always quiet, so no ppl_printf */
917 /* also, the code down in the GSSAPI block has
918 * already logged this in the Event Log */
919 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
920 ppl_logevent("Keyboard-interactive authentication "
921 "failed");
922 ppl_printf("Access denied\r\n");
923 } else {
924 assert(s->type == AUTH_TYPE_PASSWORD);
925 ppl_logevent("Password authentication failed");
926 ppl_printf("Access denied\r\n");
928 if (s->change_username) {
929 /* XXX perhaps we should allow
930 * keyboard-interactive to do this too? */
931 goto try_new_username;
934 } else {
935 ppl_printf("Further authentication required\r\n");
936 ppl_logevent("Further authentication required");
940 * Save the methods string for use in error messages.
942 strbuf_clear(s->last_methods_string);
943 put_datapl(s->last_methods_string, methods);
946 * Scan it for method identifiers we know about.
948 bool srv_pubkey = false, srv_passwd = false;
949 bool srv_keyb_inter = false;
950 #ifndef NO_GSSAPI
951 bool srv_gssapi = false, srv_gssapi_keyex_auth = false;
952 #endif
954 for (ptrlen method; get_commasep_word(&methods, &method) ;) {
955 if (ptrlen_eq_string(method, "publickey"))
956 srv_pubkey = true;
957 else if (ptrlen_eq_string(method, "password"))
958 srv_passwd = true;
959 else if (ptrlen_eq_string(method, "keyboard-interactive"))
960 srv_keyb_inter = true;
961 #ifndef NO_GSSAPI
962 else if (ptrlen_eq_string(method, "gssapi-with-mic"))
963 srv_gssapi = true;
964 else if (ptrlen_eq_string(method, "gssapi-keyex"))
965 srv_gssapi_keyex_auth = true;
966 #endif
970 * And combine those flags with our own configuration
971 * and context to set the main can_foo variables.
973 s->can_pubkey = srv_pubkey;
974 s->can_passwd = srv_passwd;
975 s->can_keyb_inter = s->try_ki_auth && srv_keyb_inter;
976 #ifndef NO_GSSAPI
977 s->can_gssapi = s->try_gssapi_auth && srv_gssapi &&
978 s->shgss->libs->nlibraries > 0;
979 s->can_gssapi_keyex_auth = s->try_gssapi_kex_auth &&
980 srv_gssapi_keyex_auth &&
981 s->shgss->libs->nlibraries > 0 && s->shgss->ctx;
982 #endif
985 s->ppl.bpp->pls->actx = SSH2_PKTCTX_NOAUTH;
987 #ifndef NO_GSSAPI
988 if (s->can_gssapi_keyex_auth && !s->tried_gssapi_keyex_auth) {
990 /* gssapi-keyex authentication */
992 s->type = AUTH_TYPE_GSSAPI;
993 s->tried_gssapi_keyex_auth = true;
994 s->ppl.bpp->pls->actx = SSH2_PKTCTX_GSSAPI;
996 if (s->shgss->lib->gsslogmsg)
997 ppl_logevent("%s", s->shgss->lib->gsslogmsg);
999 ppl_logevent("Trying gssapi-keyex...");
1000 s->pktout = ssh2_userauth_gss_packet(s, "gssapi-keyex");
1001 pq_push(s->ppl.out_pq, s->pktout);
1002 s->shgss->lib->release_cred(s->shgss->lib, &s->shgss->ctx);
1003 s->shgss->ctx = NULL;
1005 continue;
1006 } else
1007 #endif /* NO_GSSAPI */
1009 if (s->can_pubkey && !s->done_agent &&
1010 s->agent_key_index < s->agent_key_limit) {
1013 * Attempt public-key authentication using a key from Pageant.
1015 s->agent_keyalg = s->agent_keys[s->agent_key_index].algorithm;
1016 char *alg_tmp = mkstr(s->agent_keyalg);
1017 const char *newalg = alg_tmp;
1018 if (ssh2_userauth_signflags(s, &s->signflags, &newalg))
1019 s->agent_keyalg = ptrlen_from_asciz(newalg);
1020 sfree(alg_tmp);
1022 s->ppl.bpp->pls->actx = SSH2_PKTCTX_PUBLICKEY;
1024 ppl_logevent("Trying Pageant key #%"SIZEu, s->agent_key_index);
1026 /* See if server will accept it */
1027 s->pktout = ssh_bpp_new_pktout(
1028 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1029 put_stringz(s->pktout, s->username);
1030 put_stringz(s->pktout, s->successor_layer->vt->name);
1031 put_stringz(s->pktout, "publickey");
1032 /* method */
1033 put_bool(s->pktout, false); /* no signature included */
1034 ssh2_userauth_add_alg_and_publickey(
1035 s, s->pktout, s->agent_keyalg, ptrlen_from_strbuf(
1036 s->agent_keys[s->agent_key_index].blob));
1037 pq_push(s->ppl.out_pq, s->pktout);
1038 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
1040 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
1041 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
1043 /* Offer of key refused, presumably via
1044 * USERAUTH_FAILURE. Requeue for the next iteration. */
1045 pq_push_front(s->ppl.in_pq, pktin);
1047 } else {
1048 strbuf *agentreq, *sigdata;
1049 ptrlen comment = ptrlen_from_strbuf(
1050 s->agent_keys[s->agent_key_index].comment);
1052 if (seat_verbose(s->ppl.seat))
1053 ppl_printf("Authenticating with public key "
1054 "\"%.*s\" from agent\r\n",
1055 PTRLEN_PRINTF(comment));
1058 * Server is willing to accept the key.
1059 * Construct a SIGN_REQUEST.
1061 s->pktout = ssh_bpp_new_pktout(
1062 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1063 put_stringz(s->pktout, s->username);
1064 put_stringz(s->pktout, s->successor_layer->vt->name);
1065 put_stringz(s->pktout, "publickey");
1066 /* method */
1067 put_bool(s->pktout, true); /* signature included */
1068 ssh2_userauth_add_alg_and_publickey(
1069 s, s->pktout, s->agent_keyalg, ptrlen_from_strbuf(
1070 s->agent_keys[s->agent_key_index].blob));
1072 /* Ask agent for signature. */
1073 agentreq = strbuf_new_for_agent_query();
1074 put_byte(agentreq, SSH2_AGENTC_SIGN_REQUEST);
1075 put_stringpl(agentreq, ptrlen_from_strbuf(
1076 s->agent_keys[s->agent_key_index].blob));
1077 /* Now the data to be signed... */
1078 sigdata = strbuf_new();
1079 ssh2_userauth_add_session_id(s, sigdata);
1080 put_data(sigdata, s->pktout->data + 5,
1081 s->pktout->length - 5);
1082 put_stringsb(agentreq, sigdata);
1083 /* And finally the flags word. */
1084 put_uint32(agentreq, s->signflags);
1085 ssh2_userauth_agent_query(s, agentreq);
1086 strbuf_free(agentreq);
1087 crWaitUntilV(!s->auth_agent_query);
1089 if (s->agent_response.ptr) {
1090 ptrlen sigblob;
1091 BinarySource src[1];
1092 BinarySource_BARE_INIT(src, s->agent_response.ptr,
1093 s->agent_response.len);
1094 get_uint32(src); /* skip length field */
1095 if (get_byte(src) == SSH2_AGENT_SIGN_RESPONSE &&
1096 (sigblob = get_string(src), !get_err(src))) {
1097 ppl_logevent("Sending Pageant's response");
1098 ssh2_userauth_add_sigblob(
1099 s, s->pktout,
1100 ptrlen_from_strbuf(
1101 s->agent_keys[s->agent_key_index].blob),
1102 sigblob);
1103 pq_push(s->ppl.out_pq, s->pktout);
1104 s->type = AUTH_TYPE_PUBLICKEY;
1105 s->is_trivial_auth = false;
1106 } else {
1107 ppl_logevent("Pageant refused signing request");
1108 ppl_printf("Pageant failed to "
1109 "provide a signature\r\n");
1110 s->suppress_wait_for_response_packet = true;
1111 ssh_free_pktout(s->pktout);
1113 } else {
1114 ppl_logevent("Pageant failed to respond to "
1115 "signing request");
1116 ppl_printf("Pageant failed to "
1117 "respond to signing request\r\n");
1118 s->suppress_wait_for_response_packet = true;
1119 ssh_free_pktout(s->pktout);
1123 /* Do we have any keys left to try? */
1124 if (++s->agent_key_index >= s->agent_key_limit)
1125 s->done_agent = true;
1127 } else if (s->can_pubkey && s->publickey_blob &&
1128 s->privatekey_available && !s->tried_pubkey_config) {
1130 ssh2_userkey *key; /* not live over crReturn */
1131 char *passphrase; /* not live over crReturn */
1133 s->ppl.bpp->pls->actx = SSH2_PKTCTX_PUBLICKEY;
1135 s->tried_pubkey_config = true;
1138 * Try the public key supplied in the configuration.
1140 * First, try to upgrade its algorithm.
1142 const char *newalg = s->publickey_algorithm;
1143 if (ssh2_userauth_signflags(s, &s->signflags, &newalg)) {
1144 sfree(s->publickey_algorithm);
1145 s->publickey_algorithm = dupstr(newalg);
1149 * Offer the public blob to see if the server is willing to
1150 * accept it.
1152 s->pktout = ssh_bpp_new_pktout(
1153 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1154 put_stringz(s->pktout, s->username);
1155 put_stringz(s->pktout, s->successor_layer->vt->name);
1156 put_stringz(s->pktout, "publickey"); /* method */
1157 put_bool(s->pktout, false);
1158 /* no signature included */
1159 ssh2_userauth_add_alg_and_publickey(
1160 s, s->pktout, ptrlen_from_asciz(s->publickey_algorithm),
1161 ptrlen_from_strbuf(s->publickey_blob));
1162 pq_push(s->ppl.out_pq, s->pktout);
1163 ppl_logevent("Offered public key");
1165 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
1166 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
1167 /* Key refused. Give up. */
1168 pq_push_front(s->ppl.in_pq, pktin);
1169 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
1170 continue; /* process this new message */
1172 ppl_logevent("Offer of public key accepted");
1175 * Actually attempt a serious authentication using
1176 * the key.
1178 if (seat_verbose(s->ppl.seat))
1179 ppl_printf("Authenticating with public key \"%s\"\r\n",
1180 s->publickey_comment);
1182 key = NULL;
1183 while (!key) {
1184 const char *error; /* not live over crReturn */
1185 if (s->privatekey_encrypted) {
1187 * Get a passphrase from the user.
1189 s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
1190 s->cur_prompt->to_server = false;
1191 s->cur_prompt->from_server = false;
1192 s->cur_prompt->name = dupstr("SSH key passphrase");
1193 add_prompt(s->cur_prompt,
1194 dupprintf("Passphrase for key \"%s\": ",
1195 s->publickey_comment),
1196 false);
1197 s->spr = seat_get_userpass_input(
1198 ppl_get_iseat(&s->ppl), s->cur_prompt);
1199 while (s->spr.kind == SPRK_INCOMPLETE) {
1200 crReturnV;
1201 s->spr = seat_get_userpass_input(
1202 ppl_get_iseat(&s->ppl), s->cur_prompt);
1204 if (spr_is_abort(s->spr)) {
1205 /* Failed to get a passphrase. Terminate. */
1206 free_prompts(s->cur_prompt);
1207 s->cur_prompt = NULL;
1208 ssh_bpp_queue_disconnect(
1209 s->ppl.bpp, "Unable to authenticate",
1210 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
1211 ssh_spr_close(s->ppl.ssh, s->spr,
1212 "passphrase prompt");
1213 return;
1215 passphrase =
1216 prompt_get_result(s->cur_prompt->prompts[0]);
1217 free_prompts(s->cur_prompt);
1218 s->cur_prompt = NULL;
1219 } else {
1220 passphrase = NULL; /* no passphrase needed */
1224 * Try decrypting the key.
1226 key = ppk_load_f(s->keyfile, passphrase, &error);
1227 if (passphrase) {
1228 /* burn the evidence */
1229 smemclr(passphrase, strlen(passphrase));
1230 sfree(passphrase);
1232 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
1233 if (passphrase &&
1234 (key == SSH2_WRONG_PASSPHRASE)) {
1235 ppl_printf("Wrong passphrase\r\n");
1236 key = NULL;
1237 /* and loop again */
1238 } else {
1239 ppl_printf("Unable to load private key (%s)\r\n",
1240 error);
1241 key = NULL;
1242 s->suppress_wait_for_response_packet = true;
1243 break; /* try something else */
1245 } else {
1246 /* FIXME: if we ever support variable signature
1247 * flags, this is somewhere they'll need to be
1248 * put */
1249 char *invalid = ssh_key_invalid(key->key, 0);
1250 if (invalid) {
1251 ppl_printf("Cannot use this private key (%s)\r\n",
1252 invalid);
1253 ssh_key_free(key->key);
1254 sfree(key->comment);
1255 sfree(key);
1256 sfree(invalid);
1257 key = NULL;
1258 s->suppress_wait_for_response_packet = true;
1259 break; /* try something else */
1264 if (key) {
1265 strbuf *pkblob, *sigdata, *sigblob;
1268 * We have loaded the private key and the server
1269 * has announced that it's willing to accept it.
1270 * Hallelujah. Generate a signature and send it.
1272 s->pktout = ssh_bpp_new_pktout(
1273 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1274 put_stringz(s->pktout, s->username);
1275 put_stringz(s->pktout, s->successor_layer->vt->name);
1276 put_stringz(s->pktout, "publickey"); /* method */
1277 put_bool(s->pktout, true); /* signature follows */
1278 pkblob = strbuf_new();
1279 ssh_key_public_blob(key->key, BinarySink_UPCAST(pkblob));
1280 ssh2_userauth_add_alg_and_publickey(
1281 s, s->pktout,
1282 ptrlen_from_asciz(s->publickey_algorithm),
1283 ptrlen_from_strbuf(pkblob));
1286 * The data to be signed is:
1288 * string session-id
1290 * followed by everything so far placed in the
1291 * outgoing packet.
1293 sigdata = strbuf_new();
1294 ssh2_userauth_add_session_id(s, sigdata);
1295 put_data(sigdata, s->pktout->data + 5,
1296 s->pktout->length - 5);
1297 sigblob = strbuf_new();
1298 ssh_key_sign(key->key, ptrlen_from_strbuf(sigdata),
1299 s->signflags, BinarySink_UPCAST(sigblob));
1300 strbuf_free(sigdata);
1301 ssh2_userauth_add_sigblob(
1302 s, s->pktout, ptrlen_from_strbuf(pkblob),
1303 ptrlen_from_strbuf(sigblob));
1304 strbuf_free(pkblob);
1305 strbuf_free(sigblob);
1307 pq_push(s->ppl.out_pq, s->pktout);
1308 ppl_logevent("Sent public key signature");
1309 s->type = AUTH_TYPE_PUBLICKEY;
1310 ssh_key_free(key->key);
1311 sfree(key->comment);
1312 sfree(key);
1313 s->is_trivial_auth = false;
1316 #ifndef NO_GSSAPI
1317 } else if (s->can_gssapi && !s->tried_gssapi) {
1319 /* gssapi-with-mic authentication */
1321 ptrlen data;
1323 s->type = AUTH_TYPE_GSSAPI;
1324 s->tried_gssapi = true;
1325 s->ppl.bpp->pls->actx = SSH2_PKTCTX_GSSAPI;
1327 if (s->shgss->lib->gsslogmsg)
1328 ppl_logevent("%s", s->shgss->lib->gsslogmsg);
1330 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
1331 ppl_logevent("Trying gssapi-with-mic...");
1332 s->pktout = ssh_bpp_new_pktout(
1333 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1334 put_stringz(s->pktout, s->username);
1335 put_stringz(s->pktout, s->successor_layer->vt->name);
1336 put_stringz(s->pktout, "gssapi-with-mic");
1337 ppl_logevent("Attempting GSSAPI authentication");
1339 /* add mechanism info */
1340 s->shgss->lib->indicate_mech(s->shgss->lib, &s->gss_buf);
1342 /* number of GSSAPI mechanisms */
1343 put_uint32(s->pktout, 1);
1345 /* length of OID + 2 */
1346 put_uint32(s->pktout, s->gss_buf.length + 2);
1347 put_byte(s->pktout, SSH2_GSS_OIDTYPE);
1349 /* length of OID */
1350 put_byte(s->pktout, s->gss_buf.length);
1352 put_data(s->pktout, s->gss_buf.value, s->gss_buf.length);
1353 pq_push(s->ppl.out_pq, s->pktout);
1354 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
1355 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
1356 ppl_logevent("GSSAPI authentication request refused");
1357 pq_push_front(s->ppl.in_pq, pktin);
1358 continue;
1361 /* check returned packet ... */
1363 data = get_string(pktin);
1364 s->gss_rcvtok.value = (char *)data.ptr;
1365 s->gss_rcvtok.length = data.len;
1366 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
1367 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
1368 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
1369 memcmp((char *)s->gss_rcvtok.value + 2,
1370 s->gss_buf.value,s->gss_buf.length) ) {
1371 ppl_logevent("GSSAPI authentication - wrong response "
1372 "from server");
1373 continue;
1376 /* Import server name if not cached from KEX */
1377 if (s->shgss->srv_name == GSS_C_NO_NAME) {
1378 s->gss_stat = s->shgss->lib->import_name(
1379 s->shgss->lib, s->fullhostname, &s->shgss->srv_name);
1380 if (s->gss_stat != SSH_GSS_OK) {
1381 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
1382 ppl_logevent("GSSAPI import name failed -"
1383 " Bad service name");
1384 else
1385 ppl_logevent("GSSAPI import name failed");
1386 continue;
1390 /* Allocate our gss_ctx */
1391 s->gss_stat = s->shgss->lib->acquire_cred(
1392 s->shgss->lib, &s->shgss->ctx, NULL);
1393 if (s->gss_stat != SSH_GSS_OK) {
1394 ppl_logevent("GSSAPI authentication failed to get "
1395 "credentials");
1396 /* The failure was on our side, so the server
1397 * won't be sending a response packet indicating
1398 * failure. Avoid waiting for it next time round
1399 * the loop. */
1400 s->suppress_wait_for_response_packet = true;
1401 continue;
1404 /* initial tokens are empty */
1405 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
1406 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
1408 /* now enter the loop */
1409 do {
1411 * When acquire_cred yields no useful expiration, go with
1412 * the service ticket expiration.
1414 s->gss_stat = s->shgss->lib->init_sec_context(
1415 s->shgss->lib,
1416 &s->shgss->ctx,
1417 s->shgss->srv_name,
1418 s->gssapi_fwd,
1419 &s->gss_rcvtok,
1420 &s->gss_sndtok,
1421 NULL,
1422 NULL);
1424 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
1425 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
1426 ppl_logevent("GSSAPI authentication initialisation "
1427 "failed");
1429 if (s->shgss->lib->display_status(
1430 s->shgss->lib, s->shgss->ctx, &s->gss_buf)
1431 == SSH_GSS_OK) {
1432 ppl_logevent("%s", (char *)s->gss_buf.value);
1433 sfree(s->gss_buf.value);
1436 pq_push_front(s->ppl.in_pq, pktin);
1437 break;
1439 ppl_logevent("GSSAPI authentication initialised");
1442 * Client and server now exchange tokens until GSSAPI
1443 * no longer says CONTINUE_NEEDED
1445 if (s->gss_sndtok.length != 0) {
1446 s->is_trivial_auth = false;
1447 s->pktout =
1448 ssh_bpp_new_pktout(
1449 s->ppl.bpp, SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
1450 put_string(s->pktout,
1451 s->gss_sndtok.value, s->gss_sndtok.length);
1452 pq_push(s->ppl.out_pq, s->pktout);
1453 s->shgss->lib->free_tok(s->shgss->lib, &s->gss_sndtok);
1456 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
1457 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
1459 if (pktin->type == SSH2_MSG_USERAUTH_GSSAPI_ERRTOK) {
1461 * Per RFC 4462 section 3.9, this packet
1462 * type MUST immediately precede an
1463 * ordinary USERAUTH_FAILURE.
1465 * We currently don't know how to do
1466 * anything with the GSSAPI error token
1467 * contained in this packet, so we ignore
1468 * it and just wait for the following
1469 * FAILURE.
1471 crMaybeWaitUntilV(
1472 (pktin = ssh2_userauth_pop(s)) != NULL);
1473 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
1474 ssh_proto_error(
1475 s->ppl.ssh, "Received unexpected packet "
1476 "after SSH_MSG_USERAUTH_GSSAPI_ERRTOK "
1477 "(expected SSH_MSG_USERAUTH_FAILURE): "
1478 "type %d (%s)", pktin->type,
1479 ssh2_pkt_type(s->ppl.bpp->pls->kctx,
1480 s->ppl.bpp->pls->actx,
1481 pktin->type));
1482 return;
1486 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
1487 ppl_logevent("GSSAPI authentication failed");
1488 s->gss_stat = SSH_GSS_FAILURE;
1489 pq_push_front(s->ppl.in_pq, pktin);
1490 break;
1491 } else if (pktin->type !=
1492 SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
1493 ppl_logevent("GSSAPI authentication -"
1494 " bad server response");
1495 s->gss_stat = SSH_GSS_FAILURE;
1496 break;
1498 data = get_string(pktin);
1499 s->gss_rcvtok.value = (char *)data.ptr;
1500 s->gss_rcvtok.length = data.len;
1502 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
1504 if (s->gss_stat != SSH_GSS_OK) {
1505 s->shgss->lib->release_cred(s->shgss->lib, &s->shgss->ctx);
1506 continue;
1508 ppl_logevent("GSSAPI authentication loop finished OK");
1510 /* Now send the MIC */
1512 s->pktout = ssh2_userauth_gss_packet(s, "gssapi-with-mic");
1513 pq_push(s->ppl.out_pq, s->pktout);
1515 s->shgss->lib->release_cred(s->shgss->lib, &s->shgss->ctx);
1516 continue;
1517 #endif
1518 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
1521 * Keyboard-interactive authentication.
1524 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
1526 s->ppl.bpp->pls->actx = SSH2_PKTCTX_KBDINTER;
1528 s->pktout = ssh_bpp_new_pktout(
1529 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1530 put_stringz(s->pktout, s->username);
1531 put_stringz(s->pktout, s->successor_layer->vt->name);
1532 put_stringz(s->pktout, "keyboard-interactive");
1533 /* method */
1534 put_stringz(s->pktout, ""); /* lang */
1535 put_stringz(s->pktout, ""); /* submethods */
1536 pq_push(s->ppl.out_pq, s->pktout);
1538 ppl_logevent("Attempting keyboard-interactive authentication");
1540 if (s->authplugin) {
1541 strbuf *amsg = authplugin_newmsg(PLUGIN_PROTOCOL);
1542 put_stringz(amsg, "keyboard-interactive");
1543 authplugin_send_free(s, amsg);
1545 BinarySource src[1];
1546 unsigned type;
1547 crMaybeWaitUntilV(authplugin_expect_msg(s, &type, src));
1548 switch (type) {
1549 case PLUGIN_PROTOCOL_REJECT: {
1550 ptrlen message = PTRLEN_LITERAL("");
1551 if (s->authplugin_version >= 2) {
1552 /* draft protocol didn't include a message here */
1553 message = get_string(src);
1555 if (get_err(src)) {
1556 ssh_sw_abort(s->ppl.ssh, "Received malformed "
1557 "PLUGIN_PROTOCOL_REJECT from auth "
1558 "helper plugin");
1559 return;
1561 if (message.len) {
1562 /* If the plugin sent a message about
1563 * _why_ it didn't want to do k-i, pass
1564 * that message on to the user. (It might
1565 * say, for example, what went wrong when
1566 * it tried to open its config file.) */
1567 ppl_printf("Authentication plugin failed to set "
1568 "up keyboard-interactive "
1569 "authentication:\r\n");
1570 seat_set_trust_status(s->ppl.seat, false);
1571 ppl_printf("%.*s\r\n", PTRLEN_PRINTF(message));
1572 seat_set_trust_status(s->ppl.seat, true);
1573 ppl_logevent("Authentication plugin declined to "
1574 "help with keyboard-interactive: "
1575 "%.*s", PTRLEN_PRINTF(message));
1576 } else {
1577 ppl_logevent("Authentication plugin declined to "
1578 "help with keyboard-interactive");
1580 s->authplugin_ki_active = false;
1581 break;
1583 case PLUGIN_PROTOCOL_ACCEPT:
1584 s->authplugin_ki_active = true;
1585 ppl_logevent("Authentication plugin agreed to help "
1586 "with keyboard-interactive");
1587 break;
1588 default:
1589 authplugin_bad_packet(
1590 s, type, "expected PLUGIN_PROTOCOL_ACCEPT or "
1591 "PLUGIN_PROTOCOL_REJECT");
1592 return;
1594 } else {
1595 s->authplugin_ki_active = false;
1598 if (!s->ki_scc_initialised) {
1599 s->ki_scc = seat_stripctrl_new(
1600 s->ppl.seat, NULL, SIC_KI_PROMPTS);
1601 if (s->ki_scc)
1602 stripctrl_enable_line_limiting(s->ki_scc);
1603 s->ki_scc_initialised = true;
1606 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
1607 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
1608 /* Server is not willing to do keyboard-interactive
1609 * at all (or, bizarrely but legally, accepts the
1610 * user without actually issuing any prompts).
1611 * Give up on it entirely. */
1612 pq_push_front(s->ppl.in_pq, pktin);
1613 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
1614 s->kbd_inter_refused = true; /* don't try it again */
1615 continue;
1618 s->ki_printed_header = false;
1621 * Loop while we still have prompts to send to the user.
1623 if (!s->authplugin_ki_active) {
1625 * The simple case: INFO_REQUESTs are passed on to
1626 * the user, and responses are sent straight back
1627 * to the SSH server.
1629 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
1630 if (!ssh2_userauth_ki_setup_prompts(
1631 s, BinarySource_UPCAST(pktin), false))
1632 return;
1633 crMaybeWaitUntilV(ssh2_userauth_ki_run_prompts(s));
1635 if (spr_is_abort(s->spr)) {
1637 * Failed to get responses. Terminate.
1639 free_prompts(s->cur_prompt);
1640 s->cur_prompt = NULL;
1641 ssh_bpp_queue_disconnect(
1642 s->ppl.bpp, "Unable to authenticate",
1643 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
1644 ssh_spr_close(s->ppl.ssh, s->spr, "keyboard-"
1645 "interactive authentication prompt");
1646 return;
1650 * Send the response(s) to the server.
1652 s->pktout = ssh_bpp_new_pktout(
1653 s->ppl.bpp, SSH2_MSG_USERAUTH_INFO_RESPONSE);
1654 ssh2_userauth_ki_write_responses(
1655 s, BinarySink_UPCAST(s->pktout));
1656 s->pktout->minlen = 256;
1657 pq_push(s->ppl.out_pq, s->pktout);
1660 * Get the next packet in case it's another
1661 * INFO_REQUEST.
1663 crMaybeWaitUntilV(
1664 (pktin = ssh2_userauth_pop(s)) != NULL);
1666 } else {
1668 * The case where a plugin is involved:
1669 * INFO_REQUEST from the server is sent to the
1670 * plugin, which sends responses that we hand back
1671 * to the server. But in the meantime, the plugin
1672 * might send USER_REQUEST for us to pass to the
1673 * user, and then we send responses to that.
1675 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
1676 strbuf *amsg = authplugin_newmsg(
1677 PLUGIN_KI_SERVER_REQUEST);
1678 put_datapl(amsg, get_data(pktin, get_avail(pktin)));
1679 authplugin_send_free(s, amsg);
1681 BinarySource src[1];
1682 unsigned type;
1683 while (true) {
1684 crMaybeWaitUntilV(authplugin_expect_msg(
1685 s, &type, src));
1686 if (type != PLUGIN_KI_USER_REQUEST)
1687 break;
1689 if (!ssh2_userauth_ki_setup_prompts(s, src, true))
1690 return;
1691 crMaybeWaitUntilV(ssh2_userauth_ki_run_prompts(s));
1693 if (spr_is_abort(s->spr)) {
1695 * Failed to get responses. Terminate.
1697 free_prompts(s->cur_prompt);
1698 s->cur_prompt = NULL;
1699 ssh_bpp_queue_disconnect(
1700 s->ppl.bpp, "Unable to authenticate",
1701 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
1702 ssh_spr_close(
1703 s->ppl.ssh, s->spr, "keyboard-"
1704 "interactive authentication prompt");
1705 return;
1709 * Send the responses on to the plugin.
1711 strbuf *amsg = authplugin_newmsg(
1712 PLUGIN_KI_USER_RESPONSE);
1713 ssh2_userauth_ki_write_responses(
1714 s, BinarySink_UPCAST(amsg));
1715 authplugin_send_free(s, amsg);
1718 if (type != PLUGIN_KI_SERVER_RESPONSE) {
1719 authplugin_bad_packet(
1720 s, type, "expected PLUGIN_KI_SERVER_RESPONSE "
1721 "or PLUGIN_PROTOCOL_USER_REQUEST");
1722 return;
1725 s->pktout = ssh_bpp_new_pktout(
1726 s->ppl.bpp, SSH2_MSG_USERAUTH_INFO_RESPONSE);
1727 put_datapl(s->pktout, get_data(src, get_avail(src)));
1728 s->pktout->minlen = 256;
1729 pq_push(s->ppl.out_pq, s->pktout);
1732 * Get the next packet in case it's another
1733 * INFO_REQUEST.
1735 crMaybeWaitUntilV(
1736 (pktin = ssh2_userauth_pop(s)) != NULL);
1741 * Print our trailer line, if we printed a header.
1743 if (s->ki_printed_header) {
1744 seat_set_trust_status(s->ppl.seat, true);
1745 seat_antispoof_msg(
1746 ppl_get_iseat(&s->ppl),
1747 (s->authplugin_ki_active ?
1748 "End of keyboard-interactive prompts from plugin" :
1749 "End of keyboard-interactive prompts from server"));
1753 * We should have SUCCESS or FAILURE now.
1755 pq_push_front(s->ppl.in_pq, pktin);
1757 if (s->authplugin_ki_active) {
1759 * As our last communication with the plugin, tell
1760 * it whether the k-i authentication succeeded.
1762 int plugin_msg = -1;
1763 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
1764 plugin_msg = PLUGIN_AUTH_SUCCESS;
1765 } else if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
1767 * Peek in the failure packet to see if it's a
1768 * partial success.
1770 BinarySource src[1];
1771 BinarySource_BARE_INIT(
1772 src, get_ptr(pktin), get_avail(pktin));
1773 get_string(pktin); /* skip methods */
1774 bool partial_success = get_bool(pktin);
1775 if (!get_err(src)) {
1776 plugin_msg = partial_success ?
1777 PLUGIN_AUTH_SUCCESS : PLUGIN_AUTH_FAILURE;
1781 if (plugin_msg >= 0) {
1782 strbuf *amsg = authplugin_newmsg(plugin_msg);
1783 authplugin_send_free(s, amsg);
1785 /* Wait until we've actually sent it, in case
1786 * we close the connection to the plugin
1787 * before that outgoing message has left our
1788 * own buffers */
1789 crMaybeWaitUntilV(s->authplugin_backlog == 0);
1792 } else if (s->can_passwd) {
1793 s->is_trivial_auth = false;
1795 * Plain old password authentication.
1797 bool changereq_first_time; /* not live over crReturn */
1799 s->ppl.bpp->pls->actx = SSH2_PKTCTX_PASSWORD;
1801 s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
1802 s->cur_prompt->to_server = true;
1803 s->cur_prompt->from_server = false;
1804 s->cur_prompt->name = dupstr("SSH password");
1805 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
1806 s->username, s->hostname),
1807 false);
1809 s->spr = seat_get_userpass_input(
1810 ppl_get_iseat(&s->ppl), s->cur_prompt);
1811 while (s->spr.kind == SPRK_INCOMPLETE) {
1812 crReturnV;
1813 s->spr = seat_get_userpass_input(
1814 ppl_get_iseat(&s->ppl), s->cur_prompt);
1816 if (spr_is_abort(s->spr)) {
1818 * Failed to get responses. Terminate.
1820 free_prompts(s->cur_prompt);
1821 s->cur_prompt = NULL;
1822 ssh_bpp_queue_disconnect(
1823 s->ppl.bpp, "Unable to authenticate",
1824 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
1825 ssh_spr_close(s->ppl.ssh, s->spr, "password prompt");
1826 return;
1829 * Squirrel away the password. (We may need it later if
1830 * asked to change it.)
1832 s->password = prompt_get_result(s->cur_prompt->prompts[0]);
1833 free_prompts(s->cur_prompt);
1834 s->cur_prompt = NULL;
1837 * Send the password packet.
1839 * We pad out the password packet to 256 bytes to make
1840 * it harder for an attacker to find the length of the
1841 * user's password.
1843 * Anyone using a password longer than 256 bytes
1844 * probably doesn't have much to worry about from
1845 * people who find out how long their password is!
1847 s->pktout = ssh_bpp_new_pktout(
1848 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1849 put_stringz(s->pktout, s->username);
1850 put_stringz(s->pktout, s->successor_layer->vt->name);
1851 put_stringz(s->pktout, "password");
1852 put_bool(s->pktout, false);
1853 put_stringz(s->pktout, s->password);
1854 s->pktout->minlen = 256;
1855 pq_push(s->ppl.out_pq, s->pktout);
1856 ppl_logevent("Sent password");
1857 s->type = AUTH_TYPE_PASSWORD;
1860 * Wait for next packet, in case it's a password change
1861 * request.
1863 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
1864 changereq_first_time = true;
1866 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
1869 * We're being asked for a new password
1870 * (perhaps not for the first time).
1871 * Loop until the server accepts it.
1874 bool got_new = false; /* not live over crReturn */
1875 ptrlen prompt; /* not live over crReturn */
1878 const char *msg;
1879 if (changereq_first_time)
1880 msg = "Server requested password change";
1881 else
1882 msg = "Server rejected new password";
1883 ppl_logevent("%s", msg);
1884 ppl_printf("%s\r\n", msg);
1887 prompt = get_string(pktin);
1889 s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
1890 s->cur_prompt->to_server = true;
1891 s->cur_prompt->from_server = false;
1892 s->cur_prompt->name = dupstr("New SSH password");
1893 s->cur_prompt->instruction = mkstr(prompt);
1894 s->cur_prompt->instr_reqd = true;
1896 * There's no explicit requirement in the protocol
1897 * for the "old" passwords in the original and
1898 * password-change messages to be the same, and
1899 * apparently some Cisco kit supports password change
1900 * by the user entering a blank password originally
1901 * and the real password subsequently, so,
1902 * reluctantly, we prompt for the old password again.
1904 * (On the other hand, some servers don't even bother
1905 * to check this field.)
1907 add_prompt(s->cur_prompt,
1908 dupstr("Current password (blank for previously entered password): "),
1909 false);
1910 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
1911 false);
1912 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
1913 false);
1916 * Loop until the user manages to enter the same
1917 * password twice.
1919 while (!got_new) {
1920 s->spr = seat_get_userpass_input(
1921 ppl_get_iseat(&s->ppl), s->cur_prompt);
1922 while (s->spr.kind == SPRK_INCOMPLETE) {
1923 crReturnV;
1924 s->spr = seat_get_userpass_input(
1925 ppl_get_iseat(&s->ppl), s->cur_prompt);
1927 if (spr_is_abort(s->spr)) {
1929 * Failed to get responses. Terminate.
1931 /* burn the evidence */
1932 free_prompts(s->cur_prompt);
1933 s->cur_prompt = NULL;
1934 smemclr(s->password, strlen(s->password));
1935 sfree(s->password);
1936 ssh_bpp_queue_disconnect(
1937 s->ppl.bpp, "Unable to authenticate",
1938 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
1939 ssh_spr_close(s->ppl.ssh, s->spr,
1940 "password-change prompt");
1941 return;
1945 * If the user specified a new original password
1946 * (IYSWIM), overwrite any previously specified
1947 * one.
1948 * (A side effect is that the user doesn't have to
1949 * re-enter it if they louse up the new password.)
1951 if (s->cur_prompt->prompts[0]->result->s[0]) {
1952 smemclr(s->password, strlen(s->password));
1953 /* burn the evidence */
1954 sfree(s->password);
1955 s->password = prompt_get_result(
1956 s->cur_prompt->prompts[0]);
1960 * Check the two new passwords match.
1962 got_new = !strcmp(
1963 prompt_get_result_ref(s->cur_prompt->prompts[1]),
1964 prompt_get_result_ref(s->cur_prompt->prompts[2]));
1965 if (!got_new)
1966 /* They don't. Silly user. */
1967 ppl_printf("Passwords do not match\r\n");
1972 * Send the new password (along with the old one).
1973 * (see above for padding rationale)
1975 s->pktout = ssh_bpp_new_pktout(
1976 s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
1977 put_stringz(s->pktout, s->username);
1978 put_stringz(s->pktout, s->successor_layer->vt->name);
1979 put_stringz(s->pktout, "password");
1980 put_bool(s->pktout, true);
1981 put_stringz(s->pktout, s->password);
1982 put_stringz(s->pktout, prompt_get_result_ref(
1983 s->cur_prompt->prompts[1]));
1984 free_prompts(s->cur_prompt);
1985 s->cur_prompt = NULL;
1986 s->pktout->minlen = 256;
1987 pq_push(s->ppl.out_pq, s->pktout);
1988 ppl_logevent("Sent new password");
1991 * Now see what the server has to say about it.
1992 * (If it's CHANGEREQ again, it's not happy with the
1993 * new password.)
1995 crMaybeWaitUntilV((pktin = ssh2_userauth_pop(s)) != NULL);
1996 changereq_first_time = false;
2001 * We need to reexamine the current pktin at the top
2002 * of the loop. Either:
2003 * - we weren't asked to change password at all, in
2004 * which case it's a SUCCESS or FAILURE with the
2005 * usual meaning
2006 * - we sent a new password, and the server was
2007 * either OK with it (SUCCESS or FAILURE w/partial
2008 * success) or unhappy with the _old_ password
2009 * (FAILURE w/o partial success)
2010 * In any of these cases, we go back to the top of
2011 * the loop and start again.
2013 pq_push_front(s->ppl.in_pq, pktin);
2016 * We don't need the old password any more, in any
2017 * case. Burn the evidence.
2019 smemclr(s->password, strlen(s->password));
2020 sfree(s->password);
2022 } else {
2023 ssh_bpp_queue_disconnect(
2024 s->ppl.bpp,
2025 "No supported authentication methods available",
2026 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE);
2027 ssh_sw_abort(s->ppl.ssh, "No supported authentication methods "
2028 "available (server sent: %s)",
2029 s->last_methods_string->s);
2030 return;
2034 try_new_username:;
2037 userauth_success:
2038 if (s->notrivialauth && s->is_trivial_auth) {
2039 ssh_proto_error(s->ppl.ssh, "Authentication was trivial! "
2040 "Abandoning session as specified in configuration.");
2041 return;
2045 * We've just received USERAUTH_SUCCESS, and we haven't sent
2046 * any packets since. Signal the transport layer to consider
2047 * doing an immediate rekey, if it has any reason to want to.
2049 ssh2_transport_notify_auth_done(s->transport_layer);
2052 * Finally, hand over to our successor layer, and return
2053 * immediately without reaching the crFinishV: ssh_ppl_replace
2054 * will have freed us, so crFinishV's zeroing-out of crState would
2055 * be a use-after-free bug.
2058 PacketProtocolLayer *successor = s->successor_layer;
2059 s->successor_layer = NULL; /* avoid freeing it ourself */
2060 ssh_ppl_replace(&s->ppl, successor);
2061 return; /* we've just freed s, so avoid even touching s->crState */
2064 crFinishV;
2067 static void ssh2_userauth_print_banner(struct ssh2_userauth_state *s)
2069 if (bufchain_size(&s->banner) &&
2070 (seat_verbose(s->ppl.seat) || seat_interactive(s->ppl.seat))) {
2071 if (s->banner_scc) {
2072 seat_antispoof_msg(
2073 ppl_get_iseat(&s->ppl),
2074 "Pre-authentication banner message from server:");
2075 seat_set_trust_status(s->ppl.seat, false);
2078 bool mid_line = false;
2079 while (bufchain_size(&s->banner) > 0) {
2080 ptrlen data = bufchain_prefix(&s->banner);
2081 seat_banner_pl(ppl_get_iseat(&s->ppl), data);
2082 mid_line =
2083 (((const char *)data.ptr)[data.len-1] != '\n');
2084 bufchain_consume(&s->banner, data.len);
2086 bufchain_clear(&s->banner);
2088 if (mid_line)
2089 seat_banner_pl(ppl_get_iseat(&s->ppl),
2090 PTRLEN_LITERAL("\r\n"));
2092 if (s->banner_scc) {
2093 seat_set_trust_status(s->ppl.seat, true);
2094 seat_antispoof_msg(ppl_get_iseat(&s->ppl),
2095 "End of banner message from server");
2100 static bool ssh2_userauth_ki_setup_prompts(
2101 struct ssh2_userauth_state *s, BinarySource *src, bool plugin)
2103 ptrlen name, inst;
2104 strbuf *sb;
2107 * We've got a fresh USERAUTH_INFO_REQUEST. Get the preamble and
2108 * start building a prompt.
2110 name = get_string(src);
2111 inst = get_string(src);
2112 get_string(src); /* skip language tag */
2113 s->cur_prompt = ssh_ppl_new_prompts(&s->ppl);
2114 s->cur_prompt->to_server = true;
2115 s->cur_prompt->from_server = true;
2118 * Get any prompt(s) from the packet.
2120 s->num_prompts = get_uint32(src);
2121 for (uint32_t i = 0; i < s->num_prompts; i++) {
2122 s->is_trivial_auth = false;
2123 ptrlen prompt = get_string(src);
2124 bool echo = get_bool(src);
2126 if (get_err(src)) {
2127 ssh_proto_error(s->ppl.ssh, "%s sent truncated %s packet",
2128 plugin ? "Plugin" : "Server",
2129 plugin ? "PLUGIN_KI_USER_REQUEST" :
2130 "SSH_MSG_USERAUTH_INFO_REQUEST");
2131 return false;
2134 sb = strbuf_new();
2135 if (!prompt.len) {
2136 put_fmt(sb, "<%s failed to send prompt>: ",
2137 plugin ? "plugin" : "server");
2138 } else if (s->ki_scc) {
2139 stripctrl_retarget(s->ki_scc, BinarySink_UPCAST(sb));
2140 put_datapl(s->ki_scc, prompt);
2141 stripctrl_retarget(s->ki_scc, NULL);
2142 } else {
2143 put_datapl(sb, prompt);
2145 add_prompt(s->cur_prompt, strbuf_to_str(sb), echo);
2149 * Make the header strings. This includes the 'name' (optional
2150 * dialog-box title) and 'instruction' from the server.
2152 * First, display our disambiguating header line if this is the
2153 * first time round the loop - _unless_ the server has sent a
2154 * completely empty k-i packet with no prompts _or_ text, which
2155 * apparently some do. In that situation there's no need to alert
2156 * the user that the following text is server- supplied, because,
2157 * well, _what_ text?
2159 * We also only do this if we got a stripctrl, because if we
2160 * didn't, that suggests this is all being done via dialog boxes
2161 * anyway.
2163 if (!s->ki_printed_header && s->ki_scc &&
2164 (s->num_prompts || name.len || inst.len)) {
2165 seat_antispoof_msg(
2166 ppl_get_iseat(&s->ppl),
2167 (plugin ?
2168 "Keyboard-interactive authentication prompts from plugin:" :
2169 "Keyboard-interactive authentication prompts from server:"));
2170 s->ki_printed_header = true;
2171 seat_set_trust_status(s->ppl.seat, false);
2174 sb = strbuf_new();
2175 if (name.len) {
2176 if (s->ki_scc) {
2177 stripctrl_retarget(s->ki_scc, BinarySink_UPCAST(sb));
2178 put_datapl(s->ki_scc, name);
2179 stripctrl_retarget(s->ki_scc, NULL);
2180 } else {
2181 put_datapl(sb, name);
2183 s->cur_prompt->name_reqd = true;
2184 } else {
2185 if (plugin)
2186 put_datapl(sb, PTRLEN_LITERAL(
2187 "Communication with authentication plugin"));
2188 else
2189 put_datapl(sb, PTRLEN_LITERAL("SSH server authentication"));
2190 s->cur_prompt->name_reqd = false;
2192 s->cur_prompt->name = strbuf_to_str(sb);
2194 sb = strbuf_new();
2195 if (inst.len) {
2196 if (s->ki_scc) {
2197 stripctrl_retarget(s->ki_scc, BinarySink_UPCAST(sb));
2198 put_datapl(s->ki_scc, inst);
2199 stripctrl_retarget(s->ki_scc, NULL);
2200 } else {
2201 put_datapl(sb, inst);
2203 s->cur_prompt->instr_reqd = true;
2204 } else {
2205 s->cur_prompt->instr_reqd = false;
2207 if (sb->len)
2208 s->cur_prompt->instruction = strbuf_to_str(sb);
2209 else
2210 strbuf_free(sb);
2212 return true;
2215 static bool ssh2_userauth_ki_run_prompts(struct ssh2_userauth_state *s)
2217 s->spr = seat_get_userpass_input(
2218 ppl_get_iseat(&s->ppl), s->cur_prompt);
2219 return s->spr.kind != SPRK_INCOMPLETE;
2222 static void ssh2_userauth_ki_write_responses(
2223 struct ssh2_userauth_state *s, BinarySink *bs)
2225 put_uint32(bs, s->num_prompts);
2226 for (uint32_t i = 0; i < s->num_prompts; i++)
2227 put_stringz(bs, prompt_get_result_ref(s->cur_prompt->prompts[i]));
2230 * Free the prompts structure from this iteration. If there's
2231 * another, a new one will be allocated when we return to the top
2232 * of this while loop.
2234 free_prompts(s->cur_prompt);
2235 s->cur_prompt = NULL;
2238 static void ssh2_userauth_add_session_id(
2239 struct ssh2_userauth_state *s, strbuf *sigdata)
2241 if (s->ppl.remote_bugs & BUG_SSH2_PK_SESSIONID) {
2242 put_datapl(sigdata, s->session_id);
2243 } else {
2244 put_stringpl(sigdata, s->session_id);
2248 static void ssh2_userauth_agent_query(
2249 struct ssh2_userauth_state *s, strbuf *req)
2251 void *response;
2252 int response_len;
2254 sfree(s->agent_response_to_free);
2255 s->agent_response_to_free = NULL;
2257 s->auth_agent_query = agent_query(req, &response, &response_len,
2258 ssh2_userauth_agent_callback, s);
2259 if (!s->auth_agent_query)
2260 ssh2_userauth_agent_callback(s, response, response_len);
2263 static void ssh2_userauth_agent_callback(void *uav, void *reply, int replylen)
2265 struct ssh2_userauth_state *s = (struct ssh2_userauth_state *)uav;
2267 s->auth_agent_query = NULL;
2268 s->agent_response_to_free = reply;
2269 s->agent_response = make_ptrlen(reply, replylen);
2271 queue_idempotent_callback(&s->ppl.ic_process_queue);
2275 * Helper function to add the algorithm and public key strings to a
2276 * "publickey" auth packet. Deals with overriding both strings if the
2277 * user has provided a detached certificate which matches the public
2278 * key in question.
2280 static void ssh2_userauth_add_alg_and_publickey(
2281 struct ssh2_userauth_state *s, PktOut *pkt, ptrlen alg, ptrlen pkblob)
2283 PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
2285 if (s->detached_cert_blob) {
2286 ptrlen detached_cert_pl = ptrlen_from_strbuf(s->detached_cert_blob);
2287 strbuf *certbase = NULL, *pkbase = NULL;
2288 bool done = false;
2289 const ssh_keyalg *pkalg = find_pubkey_alg_len(alg);
2290 ssh_key *certkey = NULL, *pk = NULL;
2291 strbuf *fail_reason = strbuf_new();
2292 bool verbose = true;
2295 * Whether or not we send the certificate, we're likely to
2296 * generate a log message about it. But we don't want to log
2297 * once for the offer and once for the real auth attempt, so
2298 * we de-duplicate by remembering the last public key this
2299 * function saw. */
2300 if (!s->cert_pubkey_diagnosed)
2301 s->cert_pubkey_diagnosed = strbuf_new();
2302 if (ptrlen_eq_ptrlen(ptrlen_from_strbuf(s->cert_pubkey_diagnosed),
2303 pkblob)) {
2304 verbose = false;
2305 } else {
2306 /* Log this time, but arrange that we don't mention it next time */
2307 strbuf_clear(s->cert_pubkey_diagnosed);
2308 put_datapl(s->cert_pubkey_diagnosed, pkblob);
2312 * Check that the public key we're replacing is compatible
2313 * with the certificate, in that they should have the same
2314 * base public key.
2317 const ssh_keyalg *certalg = pubkey_blob_to_alg(detached_cert_pl);
2318 assert(certalg); /* we checked this before setting s->detached_blob */
2319 assert(certalg->is_certificate); /* and this too */
2321 certkey = ssh_key_new_pub(certalg, detached_cert_pl);
2322 if (!certkey) {
2323 put_fmt(fail_reason, "certificate key file is invalid");
2324 goto no_match;
2327 certbase = strbuf_new();
2328 ssh_key_public_blob(ssh_key_base_key(certkey),
2329 BinarySink_UPCAST(certbase));
2330 if (ptrlen_eq_ptrlen(pkblob, ptrlen_from_strbuf(certbase)))
2331 goto match; /* yes, a match! */
2334 * If we reach here, the certificate's base key was not
2335 * identical to the key we're given. But it might still be
2336 * identical to the _base_ key of the key we're given, if we
2337 * were using a differently certified version of the same key.
2338 * In that situation, the detached cert should still override.
2340 if (!pkalg) {
2341 put_fmt(fail_reason, "unable to identify algorithm of base key");
2342 goto no_match;
2345 pk = ssh_key_new_pub(pkalg, pkblob);
2346 if (!pk) {
2347 put_fmt(fail_reason, "base public key is invalid");
2348 goto no_match;
2351 pkbase = strbuf_new();
2352 ssh_key_public_blob(ssh_key_base_key(pk), BinarySink_UPCAST(pkbase));
2353 if (ptrlen_eq_ptrlen(ptrlen_from_strbuf(pkbase),
2354 ptrlen_from_strbuf(certbase)))
2355 goto match; /* yes, a match on 2nd attempt! */
2357 /* Give up; we've tried to match these keys up and failed. */
2358 put_fmt(fail_reason, "base public key does not match certificate");
2359 goto no_match;
2361 match:
2363 * The two keys match, so insert the detached certificate into
2364 * the output packet in place of the public key we were given.
2366 * However, we need to be a bit careful with the algorithm
2367 * name: we might need to upgrade it to one that matches the
2368 * original algorithm name. (If we were asked to add an
2369 * ssh-rsa key but were given algorithm name "rsa-sha2-512",
2370 * then instead of the certificate's algorithm name
2371 * ssh-rsa-cert-v01@... we need to write the corresponding
2372 * SHA-512 name rsa-sha2-512-cert-v01@... .)
2374 if (verbose) {
2375 ppl_logevent("Sending public key with certificate from \"%s\"",
2376 filename_to_str(s->detached_cert_file));
2379 /* Strip off any existing certificate-nature from pkalg,
2380 * for the case where we're replacing a cert embedded in
2381 * the key with the detached one. The second argument of
2382 * ssh_keyalg_related_alg is expected to be one of the
2383 * bare key algorithms, or nothing useful will happen. */
2384 const ssh_keyalg *pkalg_base =
2385 pkalg->base_alg ? pkalg->base_alg : pkalg;
2387 /* Construct an algorithm string that includes both the
2388 * signature subtype (e.g. rsa-sha2-512) and the
2389 * certificate-ness. Exception: in earlier versions of
2390 * OpenSSH we don't want to do that, and must send just
2391 * ssh-rsa-cert-... even when we're delivering a non-SHA-1
2392 * signature. */
2393 const ssh_keyalg *output_alg =
2394 ssh_keyalg_related_alg(certalg, pkalg_base);
2395 ptrlen output_id = ptrlen_from_asciz(output_alg->ssh_id);
2396 output_id = workaround_rsa_sha2_cert_userauth(s, output_id);
2398 put_stringpl(pkt, output_id);
2400 put_stringpl(pkt, ptrlen_from_strbuf(s->detached_cert_blob));
2401 done = true;
2402 goto out;
2404 no_match:
2405 /* Log that we didn't send the certificate, if this public key
2406 * isn't the same one as last call to this function. (Need to
2407 * avoid verbosely logging once for the offer and once for the
2408 * real auth attempt.) */
2409 if (verbose) {
2410 ppl_logevent("Not substituting certificate \"%s\" for public "
2411 "key: %s", filename_to_str(s->detached_cert_file),
2412 fail_reason->s);
2413 if (s->publickey_blob) {
2414 /* If the user provided a specific key file to use (i.e.
2415 * this wasn't just a key we picked opportunistically out
2416 * of an agent), then they probably _care_ that we didn't
2417 * send the certificate, so we should make a loud error
2418 * message about it as well as just commenting in the
2419 * Event Log. */
2420 ppl_printf("Unable to use certificate \"%s\" with public "
2421 "key \"%s\": %s\r\n",
2422 filename_to_str(s->detached_cert_file),
2423 filename_to_str(s->keyfile),
2424 fail_reason->s);
2428 out:
2429 /* Whether we did that or not, free our stuff. */
2430 if (certbase)
2431 strbuf_free(certbase);
2432 if (pkbase)
2433 strbuf_free(pkbase);
2434 if (certkey)
2435 ssh_key_free(certkey);
2436 if (pk)
2437 ssh_key_free(pk);
2438 strbuf_free(fail_reason);
2440 /* And if we did, don't fall through to the alternative below */
2441 if (done)
2442 return;
2445 /* In all other cases, basically just put in what we were given -
2446 * except for the same bug workaround as above. */
2447 alg = workaround_rsa_sha2_cert_userauth(s, alg);
2448 put_stringpl(pkt, alg);
2449 put_stringpl(pkt, pkblob);
2452 static ptrlen workaround_rsa_sha2_cert_userauth(
2453 struct ssh2_userauth_state *s, ptrlen id)
2455 if (!(s->ppl.remote_bugs & BUG_RSA_SHA2_CERT_USERAUTH))
2456 return id;
2458 * No need to try to do this in a general way based on the
2459 * relations between ssh_keyalgs; we know there are a limited
2460 * number of affected versions of OpenSSH, so this doesn't have to
2461 * be futureproof against later additions to the family.
2463 if (ptrlen_eq_string(id, "rsa-sha2-256-cert-v01@openssh.com") ||
2464 ptrlen_eq_string(id, "rsa-sha2-512-cert-v01@openssh.com"))
2465 return PTRLEN_LITERAL("ssh-rsa-cert-v01@openssh.com");
2466 return id;
2470 * Helper function to add an SSH-2 signature blob to a packet. Expects
2471 * to be shown the public key blob as well as the signature blob.
2472 * Normally just appends the sig blob unmodified as a string, except
2473 * that it optionally breaks it open and fiddle with it to work around
2474 * BUG_SSH2_RSA_PADDING.
2476 static void ssh2_userauth_add_sigblob(
2477 struct ssh2_userauth_state *s, PktOut *pkt, ptrlen pkblob, ptrlen sigblob)
2479 BinarySource pk[1], sig[1];
2480 BinarySource_BARE_INIT_PL(pk, pkblob);
2481 BinarySource_BARE_INIT_PL(sig, sigblob);
2483 /* dmemdump(pkblob, pkblob_len); */
2484 /* dmemdump(sigblob, sigblob_len); */
2487 * See if this is in fact an ssh-rsa signature and a buggy
2488 * server; otherwise we can just do this the easy way.
2490 if ((s->ppl.remote_bugs & BUG_SSH2_RSA_PADDING) &&
2491 ptrlen_eq_string(get_string(pk), "ssh-rsa") &&
2492 ptrlen_eq_string(get_string(sig), "ssh-rsa")) {
2493 ptrlen mod_mp, sig_mp;
2494 size_t sig_prefix_len;
2497 * Find the modulus and signature integers.
2499 get_string(pk); /* skip over exponent */
2500 mod_mp = get_string(pk); /* remember modulus */
2501 sig_prefix_len = sig->pos;
2502 sig_mp = get_string(sig);
2503 if (get_err(pk) || get_err(sig))
2504 goto give_up;
2507 * Find the byte length of the modulus, not counting leading
2508 * zeroes.
2510 while (mod_mp.len > 0 && *(const char *)mod_mp.ptr == 0) {
2511 mod_mp.len--;
2512 mod_mp.ptr = (const char *)mod_mp.ptr + 1;
2515 /* debug("modulus length is %d\n", len); */
2516 /* debug("signature length is %d\n", siglen); */
2518 if (mod_mp.len > sig_mp.len) {
2519 strbuf *substr = strbuf_new();
2520 put_data(substr, sigblob.ptr, sig_prefix_len);
2521 put_uint32(substr, mod_mp.len);
2522 put_padding(substr, mod_mp.len - sig_mp.len, 0);
2523 put_datapl(substr, sig_mp);
2524 put_stringsb(pkt, substr);
2525 return;
2528 /* Otherwise fall through and do it the easy way. We also come
2529 * here as a fallback if we discover above that the key blob
2530 * is misformatted in some way. */
2531 give_up:;
2534 put_stringpl(pkt, sigblob);
2537 #ifndef NO_GSSAPI
2538 static PktOut *ssh2_userauth_gss_packet(
2539 struct ssh2_userauth_state *s, const char *authtype)
2541 strbuf *sb;
2542 PktOut *p;
2543 Ssh_gss_buf buf;
2544 Ssh_gss_buf mic;
2547 * The mic is computed over the session id + intended
2548 * USERAUTH_REQUEST packet.
2550 sb = strbuf_new();
2551 put_stringpl(sb, s->session_id);
2552 put_byte(sb, SSH2_MSG_USERAUTH_REQUEST);
2553 put_stringz(sb, s->username);
2554 put_stringz(sb, s->successor_layer->vt->name);
2555 put_stringz(sb, authtype);
2557 /* Compute the mic */
2558 buf.value = sb->s;
2559 buf.length = sb->len;
2560 s->shgss->lib->get_mic(s->shgss->lib, s->shgss->ctx, &buf, &mic);
2561 strbuf_free(sb);
2563 /* Now we can build the real packet */
2564 if (strcmp(authtype, "gssapi-with-mic") == 0) {
2565 p = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_USERAUTH_GSSAPI_MIC);
2566 } else {
2567 p = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_USERAUTH_REQUEST);
2568 put_stringz(p, s->username);
2569 put_stringz(p, s->successor_layer->vt->name);
2570 put_stringz(p, authtype);
2572 put_string(p, mic.value, mic.length);
2574 return p;
2576 #endif
2578 static bool ssh2_userauth_get_specials(
2579 PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
2581 /* No specials provided by this layer. */
2582 return false;
2585 static void ssh2_userauth_special_cmd(PacketProtocolLayer *ppl,
2586 SessionSpecialCode code, int arg)
2588 /* No specials provided by this layer. */
2591 static void ssh2_userauth_reconfigure(PacketProtocolLayer *ppl, Conf *conf)
2593 struct ssh2_userauth_state *s =
2594 container_of(ppl, struct ssh2_userauth_state, ppl);
2595 ssh_ppl_reconfigure(s->successor_layer, conf);
2598 static void ssh2_userauth_final_output(PacketProtocolLayer *ppl)
2600 struct ssh2_userauth_state *s =
2601 container_of(ppl, struct ssh2_userauth_state, ppl);
2604 * Check for any unconsumed banner packets that might have landed
2605 * in our queue just before the server closed the connection, and
2606 * add them to our banner buffer.
2608 for (PktIn *pktin = pq_first(s->ppl.in_pq); pktin != NULL;
2609 pktin = pq_next(s->ppl.in_pq, pktin)) {
2610 if (pktin->type == SSH2_MSG_USERAUTH_BANNER)
2611 ssh2_userauth_handle_banner_packet(s, pktin);
2614 /* And now make sure we've shown the banner, before exiting */
2615 ssh2_userauth_print_banner(s);