+ logeventf(ssh, "We claim version: %.*s",
+ strcspn(verstring, "\015\012"), verstring);
+ sk_write(ssh->s, verstring, strlen(verstring));
+ sfree(verstring);
+ }
+
+ logeventf(ssh, "Using SSH protocol version %d", ssh->version);
+
+ update_specials_menu(ssh->frontend);
+ ssh->state = SSH_STATE_BEFORE_SIZE;
+ ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
+
+ sfree(s->vstring);
+
+ crFinish(0);
+}
+
+static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
+{
+ crBegin(ssh->ssh_gotdata_crstate);
+
+ /*
+ * To begin with, feed the characters one by one to the
+ * protocol initialisation / selection function do_ssh_init().
+ * When that returns 0, we're done with the initial greeting
+ * exchange and can move on to packet discipline.
+ */
+ while (1) {
+ int ret; /* need not be kept across crReturn */
+ if (datalen == 0)
+ crReturnV; /* more data please */
+ ret = do_ssh_init(ssh, *data);
+ data++;
+ datalen--;
+ if (ret == 0)
+ break;
+ }
+
+ /*
+ * We emerge from that loop when the initial negotiation is
+ * over and we have selected an s_rdpkt function. Now pass
+ * everything to s_rdpkt, and then pass the resulting packets
+ * to the proper protocol handler.
+ */
+ if (datalen == 0)
+ crReturnV;
+ while (1) {
+ while (datalen > 0) {
+ struct Packet *pktin = ssh->s_rdpkt(ssh, &data, &datalen);
+ if (pktin) {
+ ssh->protocol(ssh, NULL, 0, pktin);
+ ssh_free_packet(pktin);
+ }
+ if (ssh->state == SSH_STATE_CLOSED)
+ return;
+ }
+ crReturnV;
+ }
+ crFinishV;
+}
+
+static void ssh_do_close(Ssh ssh)
+{
+ int i;
+ struct ssh_channel *c;
+
+ ssh->state = SSH_STATE_CLOSED;
+ if (ssh->s) {
+ sk_close(ssh->s);
+ ssh->s = NULL;
+ notify_remote_exit(ssh->frontend);
+ }
+ /*
+ * Now we must shut down any port and X forwardings going
+ * through this connection.
+ */
+ if (ssh->channels) {
+ for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
+ switch (c->type) {
+ case CHAN_X11:
+ x11_close(c->u.x11.s);
+ break;
+ case CHAN_SOCKDATA:
+ pfd_close(c->u.pfd.s);
+ break;
+ }
+ del234(ssh->channels, c);
+ if (ssh->version == 2)
+ bufchain_clear(&c->v.v2.outbuffer);
+ sfree(c);
+ }
+ }
+}
+
+static int ssh_closing(Plug plug, const char *error_msg, int error_code,
+ int calling_back)
+{
+ Ssh ssh = (Ssh) plug;
+ ssh_do_close(ssh);
+ if (error_msg) {
+ /* A socket error has occurred. */
+ logevent(error_msg);
+ connection_fatal(ssh->frontend, "%s", error_msg);
+ } else {
+ /* Otherwise, the remote side closed the connection normally. */
+ }
+ return 0;
+}
+
+static int ssh_receive(Plug plug, int urgent, char *data, int len)
+{
+ Ssh ssh = (Ssh) plug;
+ ssh_gotdata(ssh, (unsigned char *)data, len);
+ if (ssh->state == SSH_STATE_CLOSED) {
+ ssh_do_close(ssh);
+ return 0;
+ }
+ return 1;
+}
+
+static void ssh_sent(Plug plug, int bufsize)
+{
+ Ssh ssh = (Ssh) plug;
+ /*
+ * If the send backlog on the SSH socket itself clears, we
+ * should unthrottle the whole world if it was throttled.
+ */
+ if (bufsize < SSH_MAX_BACKLOG)
+ ssh_throttle_all(ssh, 0, bufsize);
+}
+
+/*
+ * Connect to specified host and port.
+ * Returns an error message, or NULL on success.
+ * Also places the canonical host name into `realhost'. It must be
+ * freed by the caller.
+ */
+static const char *connect_to_host(Ssh ssh, char *host, int port,
+ char **realhost, int nodelay, int keepalive)
+{
+ static const struct plug_function_table fn_table = {
+ ssh_closing,
+ ssh_receive,
+ ssh_sent,
+ NULL
+ };
+
+ SockAddr addr;
+ const char *err;
+
+ ssh->savedhost = snewn(1 + strlen(host), char);
+ if (!ssh->savedhost)
+ fatalbox("Out of memory");
+ strcpy(ssh->savedhost, host);
+
+ if (port < 0)
+ port = 22; /* default ssh port */
+ ssh->savedport = port;
+
+ /*
+ * Try to find host.
+ */
+ logeventf(ssh, "Looking up host \"%s\"%s", host,
+ (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
+ (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
+ addr = name_lookup(host, port, realhost, &ssh->cfg,
+ ssh->cfg.addressfamily);
+ if ((err = sk_addr_error(addr)) != NULL) {
+ sk_addr_free(addr);
+ return err;
+ }
+
+ /*
+ * Open socket.
+ */
+ {
+ char addrbuf[100];
+ sk_getaddr(addr, addrbuf, 100);
+ logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
+ }
+ ssh->fn = &fn_table;
+ ssh->s = new_connection(addr, *realhost, port,
+ 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
+ if ((err = sk_socket_error(ssh->s)) != NULL) {
+ ssh->s = NULL;
+ notify_remote_exit(ssh->frontend);
+ return err;
+ }
+
+ return NULL;
+}
+
+/*
+ * Throttle or unthrottle the SSH connection.
+ */
+static void ssh1_throttle(Ssh ssh, int adjust)
+{
+ int old_count = ssh->v1_throttle_count;
+ ssh->v1_throttle_count += adjust;
+ assert(ssh->v1_throttle_count >= 0);
+ if (ssh->v1_throttle_count && !old_count) {
+ sk_set_frozen(ssh->s, 1);
+ } else if (!ssh->v1_throttle_count && old_count) {
+ sk_set_frozen(ssh->s, 0);
+ }
+}
+
+/*
+ * Throttle or unthrottle _all_ local data streams (for when sends
+ * on the SSH connection itself back up).
+ */
+static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
+{
+ int i;
+ struct ssh_channel *c;
+
+ if (enable == ssh->throttled_all)
+ return;
+ ssh->throttled_all = enable;
+ ssh->overall_bufsize = bufsize;
+ if (!ssh->channels)
+ return;
+ for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
+ switch (c->type) {
+ case CHAN_MAINSESSION:
+ /*
+ * This is treated separately, outside the switch.
+ */
+ break;
+ case CHAN_X11:
+ x11_override_throttle(c->u.x11.s, enable);
+ break;
+ case CHAN_AGENT:
+ /* Agent channels require no buffer management. */
+ break;
+ case CHAN_SOCKDATA:
+ pfd_override_throttle(c->u.pfd.s, enable);
+ break;
+ }
+ }
+}
+
+/*
+ * Username and password input, abstracted off into routines
+ * reusable in several places - even between SSH1 and SSH2.
+ */
+
+/* Set up a username or password input loop on a given buffer. */
+static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
+{
+ ssh->userpass_input_buffer = buffer;
+ ssh->userpass_input_buflen = buflen;
+ ssh->userpass_input_bufpos = 0;
+ ssh->userpass_input_echo = echo;
+}
+
+/*
+ * Process some terminal data in the course of username/password
+ * input. Returns >0 for success (line of input returned in
+ * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
+ * for inconclusive (keep waiting for more input please).
+ */
+static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
+{
+ char c;
+
+ while (inlen--) {
+ switch (c = *in++) {
+ case 10:
+ case 13:
+ ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
+ ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
+ return +1;
+ break;
+ case 8:
+ case 127:
+ if (ssh->userpass_input_bufpos > 0) {
+ if (ssh->userpass_input_echo)
+ c_write_str(ssh, "\b \b");
+ ssh->userpass_input_bufpos--;
+ }
+ break;
+ case 21:
+ case 27:
+ while (ssh->userpass_input_bufpos > 0) {
+ if (ssh->userpass_input_echo)
+ c_write_str(ssh, "\b \b");
+ ssh->userpass_input_bufpos--;
+ }
+ break;
+ case 3:
+ case 4:
+ return -1;
+ break;
+ default:
+ /*
+ * This simplistic check for printability is disabled
+ * when we're doing password input, because some people
+ * have control characters in their passwords.o
+ */
+ if ((!ssh->userpass_input_echo ||
+ (c >= ' ' && c <= '~') ||
+ ((unsigned char) c >= 160))
+ && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
+ ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
+ if (ssh->userpass_input_echo)
+ c_write(ssh, &c, 1);
+ }
+ break;
+ }
+ }
+ return 0;
+}
+
+static void ssh_agent_callback(void *sshv, void *reply, int replylen)
+{
+ Ssh ssh = (Ssh) sshv;
+
+ ssh->agent_response = reply;
+ ssh->agent_response_len = replylen;
+
+ if (ssh->version == 1)
+ do_ssh1_login(ssh, NULL, -1, NULL);
+ else
+ do_ssh2_authconn(ssh, NULL, -1, NULL);
+}
+
+static void ssh_agentf_callback(void *cv, void *reply, int replylen)
+{
+ struct ssh_channel *c = (struct ssh_channel *)cv;
+ Ssh ssh = c->ssh;
+ void *sentreply = reply;
+
+ if (!sentreply) {
+ /* Fake SSH_AGENT_FAILURE. */
+ sentreply = "\0\0\0\1\5";
+ replylen = 5;
+ }
+ if (ssh->version == 2) {
+ ssh2_add_channel_data(c, sentreply, replylen);
+ ssh2_try_send(c);
+ } else {
+ send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
+ PKT_INT, c->remoteid,
+ PKTT_DATA,
+ PKT_INT, replylen,
+ PKT_DATA, sentreply, replylen,
+ PKTT_OTHER,
+ PKT_END);
+ }
+ if (reply)
+ sfree(reply);
+}
+
+/*
+ * Handle the key exchange and user authentication phases.
+ */
+static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
+ struct Packet *pktin)
+{
+ int i, j, ret;
+ unsigned char cookie[8], *ptr;
+ struct RSAKey servkey, hostkey;
+ struct MD5Context md5c;
+ struct do_ssh1_login_state {
+ int len;
+ unsigned char *rsabuf, *keystr1, *keystr2;
+ unsigned long supported_ciphers_mask, supported_auths_mask;
+ int tried_publickey, tried_agent;
+ int tis_auth_refused, ccard_auth_refused;
+ unsigned char session_id[16];
+ int cipher_type;
+ char username[100];
+ void *publickey_blob;
+ int publickey_bloblen;
+ char password[100];
+ char prompt[200];
+ int pos;
+ char c;
+ int pwpkt_type;
+ unsigned char request[5], *response, *p;
+ int responselen;
+ int keyi, nkeys;
+ int authed;
+ struct RSAKey key;
+ Bignum challenge;
+ char *commentp;
+ int commentlen;
+ };
+ crState(do_ssh1_login_state);
+
+ crBegin(ssh->do_ssh1_login_crstate);
+
+ if (!pktin)
+ crWaitUntil(pktin);
+
+ if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
+ bombout(("Public key packet not received"));
+ crStop(0);
+ }
+
+ logevent("Received public keys");
+
+ ptr = ssh_pkt_getdata(pktin, 8);
+ if (!ptr) {
+ bombout(("SSH1 public key packet stopped before random cookie"));
+ crStop(0);
+ }
+ memcpy(cookie, ptr, 8);
+
+ if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
+ !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
+ bombout(("Failed to read SSH1 public keys from public key packet"));
+ crStop(0);
+ }
+
+ /*
+ * Log the host key fingerprint.
+ */
+ {
+ char logmsg[80];
+ logevent("Host key fingerprint is:");
+ strcpy(logmsg, " ");
+ hostkey.comment = NULL;
+ rsa_fingerprint(logmsg + strlen(logmsg),
+ sizeof(logmsg) - strlen(logmsg), &hostkey);
+ logevent(logmsg);
+ }
+
+ ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
+ s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
+ s->supported_auths_mask = ssh_pkt_getuint32(pktin);
+
+ ssh->v1_local_protoflags =
+ ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
+ ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
+
+ MD5Init(&md5c);
+ MD5Update(&md5c, s->keystr2, hostkey.bytes);
+ MD5Update(&md5c, s->keystr1, servkey.bytes);
+ MD5Update(&md5c, cookie, 8);
+ MD5Final(s->session_id, &md5c);
+
+ for (i = 0; i < 32; i++)
+ ssh->session_key[i] = random_byte();
+
+ /*
+ * Verify that the `bits' and `bytes' parameters match.
+ */
+ if (hostkey.bits > hostkey.bytes * 8 ||
+ servkey.bits > servkey.bytes * 8) {
+ bombout(("SSH1 public keys were badly formatted"));
+ crStop(0);
+ }
+
+ s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
+
+ s->rsabuf = snewn(s->len, unsigned char);
+ if (!s->rsabuf)
+ fatalbox("Out of memory");
+
+ /*
+ * Verify the host key.
+ */
+ {
+ /*
+ * First format the key into a string.
+ */
+ int len = rsastr_len(&hostkey);
+ char fingerprint[100];
+ char *keystr = snewn(len, char);
+ if (!keystr)
+ fatalbox("Out of memory");
+ rsastr_fmt(keystr, &hostkey);
+ rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
+ verify_ssh_host_key(ssh->frontend,
+ ssh->savedhost, ssh->savedport, "rsa", keystr,
+ fingerprint);
+ sfree(keystr);
+ }
+
+ for (i = 0; i < 32; i++) {
+ s->rsabuf[i] = ssh->session_key[i];
+ if (i < 16)
+ s->rsabuf[i] ^= s->session_id[i];
+ }
+
+ if (hostkey.bytes > servkey.bytes) {
+ ret = rsaencrypt(s->rsabuf, 32, &servkey);
+ if (ret)
+ ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
+ } else {
+ ret = rsaencrypt(s->rsabuf, 32, &hostkey);
+ if (ret)
+ ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
+ }
+ if (!ret) {
+ bombout(("SSH1 public key encryptions failed due to bad formatting"));
+ crStop(0);
+ }
+
+ logevent("Encrypted session key");
+
+ {
+ int cipher_chosen = 0, warn = 0;
+ char *cipher_string = NULL;
+ int i;
+ for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
+ int next_cipher = ssh->cfg.ssh_cipherlist[i];
+ if (next_cipher == CIPHER_WARN) {
+ /* If/when we choose a cipher, warn about it */
+ warn = 1;
+ } else if (next_cipher == CIPHER_AES) {
+ /* XXX Probably don't need to mention this. */
+ logevent("AES not supported in SSH1, skipping");
+ } else {
+ switch (next_cipher) {
+ case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
+ cipher_string = "3DES"; break;
+ case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
+ cipher_string = "Blowfish"; break;
+ case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
+ cipher_string = "single-DES"; break;
+ }
+ if (s->supported_ciphers_mask & (1 << s->cipher_type))
+ cipher_chosen = 1;
+ }
+ }
+ if (!cipher_chosen) {
+ if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
+ bombout(("Server violates SSH 1 protocol by not "
+ "supporting 3DES encryption"));
+ else
+ /* shouldn't happen */
+ bombout(("No supported ciphers found"));
+ crStop(0);
+ }
+
+ /* Warn about chosen cipher if necessary. */
+ if (warn)
+ askalg(ssh->frontend, "cipher", cipher_string);
+ }
+
+ switch (s->cipher_type) {
+ case SSH_CIPHER_3DES:
+ logevent("Using 3DES encryption");
+ break;
+ case SSH_CIPHER_DES:
+ logevent("Using single-DES encryption");
+ break;
+ case SSH_CIPHER_BLOWFISH:
+ logevent("Using Blowfish encryption");
+ break;
+ }
+
+ send_packet(ssh, SSH1_CMSG_SESSION_KEY,
+ PKT_CHAR, s->cipher_type,
+ PKT_DATA, cookie, 8,
+ PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
+ PKT_DATA, s->rsabuf, s->len,
+ PKT_INT, ssh->v1_local_protoflags, PKT_END);
+
+ logevent("Trying to enable encryption...");
+
+ sfree(s->rsabuf);
+
+ ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
+ s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
+ &ssh_3des);
+ ssh->v1_cipher_ctx = ssh->cipher->make_context();
+ ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
+ logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
+
+ ssh->crcda_ctx = crcda_make_context();
+ logevent("Installing CRC compensation attack detector");
+
+ if (servkey.modulus) {
+ sfree(servkey.modulus);
+ servkey.modulus = NULL;
+ }
+ if (servkey.exponent) {
+ sfree(servkey.exponent);
+ servkey.exponent = NULL;
+ }
+ if (hostkey.modulus) {
+ sfree(hostkey.modulus);
+ hostkey.modulus = NULL;
+ }
+ if (hostkey.exponent) {
+ sfree(hostkey.exponent);
+ hostkey.exponent = NULL;
+ }
+ crWaitUntil(pktin);
+
+ if (pktin->type != SSH1_SMSG_SUCCESS) {
+ bombout(("Encryption not successfully enabled"));
+ crStop(0);
+ }
+
+ logevent("Successfully started encryption");
+
+ fflush(stdout);
+ {
+ if (!*ssh->cfg.username) {
+ if (ssh_get_line && !ssh_getline_pw_only) {
+ if (!ssh_get_line("login as: ",
+ s->username, sizeof(s->username), FALSE)) {
+ /*
+ * get_line failed to get a username.
+ * Terminate.
+ */
+ logevent("No username provided. Abandoning session.");
+ ssh_closing((Plug)ssh, NULL, 0, 0);
+ crStop(1);
+ }
+ } else {
+ int ret; /* need not be kept over crReturn */
+ c_write_str(ssh, "login as: ");
+ ssh->send_ok = 1;
+
+ setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
+ do {
+ crWaitUntil(!pktin);
+ ret = process_userpass_input(ssh, in, inlen);
+ } while (ret == 0);
+ if (ret < 0)
+ cleanup_exit(0);
+ c_write_str(ssh, "\r\n");
+ }
+ } else {
+ strncpy(s->username, ssh->cfg.username, sizeof(s->username));
+ s->username[sizeof(s->username)-1] = '\0';
+ }
+
+ send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
+ {
+ char userlog[22 + sizeof(s->username)];
+ sprintf(userlog, "Sent username \"%s\"", s->username);
+ logevent(userlog);
+ if (flags & FLAG_INTERACTIVE &&
+ (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
+ strcat(userlog, "\r\n");
+ c_write_str(ssh, userlog);
+ }
+ }
+ }
+
+ crWaitUntil(pktin);
+
+ if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
+ /* We must not attempt PK auth. Pretend we've already tried it. */
+ s->tried_publickey = s->tried_agent = 1;
+ } else {
+ s->tried_publickey = s->tried_agent = 0;
+ }
+ s->tis_auth_refused = s->ccard_auth_refused = 0;
+ /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
+ if (!filename_is_null(ssh->cfg.keyfile)) {
+ if (!rsakey_pubblob(&ssh->cfg.keyfile,
+ &s->publickey_blob, &s->publickey_bloblen, NULL))
+ s->publickey_blob = NULL;
+ } else
+ s->publickey_blob = NULL;
+
+ while (pktin->type == SSH1_SMSG_FAILURE) {
+ s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
+
+ if (agent_exists() && !s->tried_agent) {
+ /*
+ * Attempt RSA authentication using Pageant.
+ */
+ void *r;
+
+ s->authed = FALSE;
+ s->tried_agent = 1;
+ logevent("Pageant is running. Requesting keys.");
+
+ /* Request the keys held by the agent. */
+ PUT_32BIT(s->request, 1);
+ s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
+ if (!agent_query(s->request, 5, &r, &s->responselen,
+ ssh_agent_callback, ssh)) {
+ do {
+ crReturn(0);
+ if (pktin) {
+ bombout(("Unexpected data from server while waiting"
+ " for agent response"));
+ crStop(0);
+ }
+ } while (pktin || inlen > 0);
+ r = ssh->agent_response;
+ s->responselen = ssh->agent_response_len;
+ }
+ s->response = (unsigned char *) r;
+ if (s->response && s->responselen >= 5 &&
+ s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
+ s->p = s->response + 5;
+ s->nkeys = GET_32BIT(s->p);
+ s->p += 4;
+ {
+ char buf[64];
+ sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
+ logevent(buf);
+ }
+ for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
+ {
+ char buf[64];
+ sprintf(buf, "Trying Pageant key #%d", s->keyi);
+ logevent(buf);
+ }
+ if (s->publickey_blob &&
+ !memcmp(s->p, s->publickey_blob,
+ s->publickey_bloblen)) {
+ logevent("This key matches configured key file");
+ s->tried_publickey = 1;
+ }
+ s->p += 4;
+ {
+ int n, ok = FALSE;
+ do { /* do while (0) to make breaking easy */
+ n = ssh1_read_bignum
+ (s->p, s->responselen-(s->p-s->response),
+ &s->key.exponent);
+ if (n < 0)
+ break;
+ s->p += n;
+ n = ssh1_read_bignum
+ (s->p, s->responselen-(s->p-s->response),
+ &s->key.modulus);
+ if (n < 0)
+ break;
+ s->p += n;
+ if (s->responselen - (s->p-s->response) < 4)
+ break;
+ s->commentlen = GET_32BIT(s->p);
+ s->p += 4;
+ if (s->responselen - (s->p-s->response) <
+ s->commentlen)
+ break;
+ s->commentp = (char *)s->p;
+ s->p += s->commentlen;
+ ok = TRUE;
+ } while (0);
+ if (!ok) {
+ logevent("Pageant key list packet was truncated");
+ break;
+ }
+ }
+ send_packet(ssh, SSH1_CMSG_AUTH_RSA,
+ PKT_BIGNUM, s->key.modulus, PKT_END);
+ crWaitUntil(pktin);
+ if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
+ logevent("Key refused");
+ continue;
+ }
+ logevent("Received RSA challenge");
+ if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
+ bombout(("Server's RSA challenge was badly formatted"));
+ crStop(0);
+ }
+
+ {
+ char *agentreq, *q, *ret;
+ void *vret;
+ int len, retlen;
+ len = 1 + 4; /* message type, bit count */
+ len += ssh1_bignum_length(s->key.exponent);
+ len += ssh1_bignum_length(s->key.modulus);
+ len += ssh1_bignum_length(s->challenge);
+ len += 16; /* session id */
+ len += 4; /* response format */
+ agentreq = snewn(4 + len, char);
+ PUT_32BIT(agentreq, len);
+ q = agentreq + 4;
+ *q++ = SSH1_AGENTC_RSA_CHALLENGE;
+ PUT_32BIT(q, bignum_bitcount(s->key.modulus));
+ q += 4;
+ q += ssh1_write_bignum(q, s->key.exponent);
+ q += ssh1_write_bignum(q, s->key.modulus);
+ q += ssh1_write_bignum(q, s->challenge);
+ memcpy(q, s->session_id, 16);
+ q += 16;
+ PUT_32BIT(q, 1); /* response format */
+ if (!agent_query(agentreq, len + 4, &vret, &retlen,
+ ssh_agent_callback, ssh)) {
+ sfree(agentreq);
+ do {
+ crReturn(0);
+ if (pktin) {
+ bombout(("Unexpected data from server"
+ " while waiting for agent"
+ " response"));
+ crStop(0);
+ }
+ } while (pktin || inlen > 0);
+ vret = ssh->agent_response;
+ retlen = ssh->agent_response_len;
+ } else
+ sfree(agentreq);
+ ret = vret;
+ if (ret) {
+ if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
+ logevent("Sending Pageant's response");
+ send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
+ PKT_DATA, ret + 5, 16,
+ PKT_END);
+ sfree(ret);
+ crWaitUntil(pktin);
+ if (pktin->type == SSH1_SMSG_SUCCESS) {
+ logevent
+ ("Pageant's response accepted");
+ if (flags & FLAG_VERBOSE) {
+ c_write_str(ssh, "Authenticated using"
+ " RSA key \"");
+ c_write(ssh, s->commentp,
+ s->commentlen);
+ c_write_str(ssh, "\" from agent\r\n");
+ }
+ s->authed = TRUE;
+ } else
+ logevent
+ ("Pageant's response not accepted");
+ } else {
+ logevent
+ ("Pageant failed to answer challenge");
+ sfree(ret);
+ }
+ } else {
+ logevent("No reply received from Pageant");
+ }
+ }
+ freebn(s->key.exponent);
+ freebn(s->key.modulus);
+ freebn(s->challenge);
+ if (s->authed)
+ break;
+ }
+ sfree(s->response);
+ }
+ if (s->authed)
+ break;
+ }
+ if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
+ s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
+
+ if (ssh->cfg.try_tis_auth &&
+ (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
+ !s->tis_auth_refused) {
+ s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
+ logevent("Requested TIS authentication");
+ send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
+ crWaitUntil(pktin);
+ if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
+ logevent("TIS authentication declined");
+ if (flags & FLAG_INTERACTIVE)
+ c_write_str(ssh, "TIS authentication refused.\r\n");
+ s->tis_auth_refused = 1;
+ continue;
+ } else {
+ char *challenge;
+ int challengelen;
+
+ ssh_pkt_getstring(pktin, &challenge, &challengelen);
+ if (!challenge) {
+ bombout(("TIS challenge packet was badly formed"));
+ crStop(0);
+ }
+ logevent("Received TIS challenge");
+ if (challengelen > sizeof(s->prompt) - 1)
+ challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
+ memcpy(s->prompt, challenge, challengelen);
+ /* Prompt heuristic comes from OpenSSH */
+ strncpy(s->prompt + challengelen,
+ memchr(s->prompt, '\n', challengelen) ?
+ "": "\r\nResponse: ",
+ (sizeof s->prompt) - challengelen);
+ s->prompt[(sizeof s->prompt) - 1] = '\0';
+ }
+ }
+ if (ssh->cfg.try_tis_auth &&
+ (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
+ !s->ccard_auth_refused) {
+ s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
+ logevent("Requested CryptoCard authentication");
+ send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
+ crWaitUntil(pktin);
+ if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
+ logevent("CryptoCard authentication declined");
+ c_write_str(ssh, "CryptoCard authentication refused.\r\n");
+ s->ccard_auth_refused = 1;
+ continue;
+ } else {
+ char *challenge;
+ int challengelen;
+
+ ssh_pkt_getstring(pktin, &challenge, &challengelen);
+ if (!challenge) {
+ bombout(("CryptoCard challenge packet was badly formed"));
+ crStop(0);
+ }
+ logevent("Received CryptoCard challenge");
+ if (challengelen > sizeof(s->prompt) - 1)
+ challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
+ memcpy(s->prompt, challenge, challengelen);
+ strncpy(s->prompt + challengelen,
+ memchr(s->prompt, '\n', challengelen) ?
+ "" : "\r\nResponse: ",
+ sizeof(s->prompt) - challengelen);
+ s->prompt[sizeof(s->prompt) - 1] = '\0';
+ }
+ }
+ if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
+ sprintf(s->prompt, "%.90s@%.90s's password: ",
+ s->username, ssh->savedhost);
+ }
+ if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
+ char *comment = NULL;
+ int type;
+ char msgbuf[256];
+ if (flags & FLAG_VERBOSE)
+ c_write_str(ssh, "Trying public key authentication.\r\n");
+ logeventf(ssh, "Trying public key \"%s\"",
+ filename_to_str(&ssh->cfg.keyfile));
+ type = key_type(&ssh->cfg.keyfile);
+ if (type != SSH_KEYTYPE_SSH1) {
+ sprintf(msgbuf, "Key is of wrong type (%s)",
+ key_type_to_str(type));
+ logevent(msgbuf);
+ c_write_str(ssh, msgbuf);
+ c_write_str(ssh, "\r\n");
+ s->tried_publickey = 1;
+ continue;
+ }
+ if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
+ if (flags & FLAG_VERBOSE)
+ c_write_str(ssh, "No passphrase required.\r\n");
+ goto tryauth;
+ }
+ sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
+ sfree(comment);
+ }
+
+ /*
+ * Show password prompt, having first obtained it via a TIS
+ * or CryptoCard exchange if we're doing TIS or CryptoCard
+ * authentication.
+ */
+ if (ssh_get_line) {
+ if (!ssh_get_line(s->prompt, s->password,
+ sizeof(s->password), TRUE)) {
+ /*
+ * get_line failed to get a password (for example
+ * because one was supplied on the command line
+ * which has already failed to work). Terminate.
+ */
+ send_packet(ssh, SSH1_MSG_DISCONNECT,
+ PKT_STR, "No more passwords available to try",
+ PKT_END);
+ logevent("Unable to authenticate");
+ connection_fatal(ssh->frontend, "Unable to authenticate");
+ ssh_closing((Plug)ssh, NULL, 0, 0);
+ crStop(1);
+ }
+ } else {
+ /* Prompt may have come from server. We've munged it a bit, so
+ * we know it to be zero-terminated at least once. */
+ int ret; /* need not be saved over crReturn */
+ c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
+ s->pos = 0;
+
+ setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
+ do {
+ crWaitUntil(!pktin);
+ ret = process_userpass_input(ssh, in, inlen);
+ } while (ret == 0);
+ if (ret < 0)
+ cleanup_exit(0);
+ c_write_str(ssh, "\r\n");
+ }
+
+ tryauth:
+ if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
+ /*
+ * Try public key authentication with the specified
+ * key file.
+ */
+ s->tried_publickey = 1;
+
+ {
+ const char *error = NULL;
+ int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
+ &error);
+ if (ret == 0) {
+ c_write_str(ssh, "Couldn't load private key from ");
+ c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
+ c_write_str(ssh, " (");
+ c_write_str(ssh, error);
+ c_write_str(ssh, ").\r\n");
+ continue; /* go and try password */
+ }
+ if (ret == -1) {
+ c_write_str(ssh, "Wrong passphrase.\r\n");
+ s->tried_publickey = 0;
+ continue; /* try again */
+ }
+ }
+
+ /*
+ * Send a public key attempt.
+ */
+ send_packet(ssh, SSH1_CMSG_AUTH_RSA,
+ PKT_BIGNUM, s->key.modulus, PKT_END);
+
+ crWaitUntil(pktin);
+ if (pktin->type == SSH1_SMSG_FAILURE) {
+ c_write_str(ssh, "Server refused our public key.\r\n");
+ continue; /* go and try password */
+ }
+ if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
+ bombout(("Bizarre response to offer of public key"));
+ crStop(0);
+ }
+
+ {
+ int i;
+ unsigned char buffer[32];
+ Bignum challenge, response;
+
+ if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
+ bombout(("Server's RSA challenge was badly formatted"));
+ crStop(0);
+ }
+ response = rsadecrypt(challenge, &s->key);
+ freebn(s->key.private_exponent);/* burn the evidence */
+
+ for (i = 0; i < 32; i++) {
+ buffer[i] = bignum_byte(response, 31 - i);
+ }
+
+ MD5Init(&md5c);
+ MD5Update(&md5c, buffer, 32);
+ MD5Update(&md5c, s->session_id, 16);
+ MD5Final(buffer, &md5c);
+
+ send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
+ PKT_DATA, buffer, 16, PKT_END);
+
+ freebn(challenge);
+ freebn(response);
+ }
+
+ crWaitUntil(pktin);
+ if (pktin->type == SSH1_SMSG_FAILURE) {
+ if (flags & FLAG_VERBOSE)
+ c_write_str(ssh, "Failed to authenticate with"
+ " our public key.\r\n");
+ continue; /* go and try password */
+ } else if (pktin->type != SSH1_SMSG_SUCCESS) {
+ bombout(("Bizarre response to RSA authentication response"));
+ crStop(0);
+ }
+
+ break; /* we're through! */
+ } else {
+ if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
+ /*
+ * Defence against traffic analysis: we send a
+ * whole bunch of packets containing strings of
+ * different lengths. One of these strings is the
+ * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
+ * The others are all random data in
+ * SSH1_MSG_IGNORE packets. This way a passive
+ * listener can't tell which is the password, and
+ * hence can't deduce the password length.
+ *
+ * Anybody with a password length greater than 16
+ * bytes is going to have enough entropy in their
+ * password that a listener won't find it _that_
+ * much help to know how long it is. So what we'll
+ * do is:
+ *
+ * - if password length < 16, we send 15 packets
+ * containing string lengths 1 through 15
+ *
+ * - otherwise, we let N be the nearest multiple
+ * of 8 below the password length, and send 8
+ * packets containing string lengths N through
+ * N+7. This won't obscure the order of
+ * magnitude of the password length, but it will
+ * introduce a bit of extra uncertainty.
+ *
+ * A few servers (the old 1.2.18 through 1.2.22)
+ * can't deal with SSH1_MSG_IGNORE. For these
+ * servers, we need an alternative defence. We make
+ * use of the fact that the password is interpreted
+ * as a C string: so we can append a NUL, then some
+ * random data.
+ *
+ * One server (a Cisco one) can deal with neither
+ * SSH1_MSG_IGNORE _nor_ a padded password string.
+ * For this server we are left with no defences
+ * against password length sniffing.
+ */
+ if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
+ /*
+ * The server can deal with SSH1_MSG_IGNORE, so
+ * we can use the primary defence.
+ */
+ int bottom, top, pwlen, i;
+ char *randomstr;
+
+ pwlen = strlen(s->password);
+ if (pwlen < 16) {
+ bottom = 0; /* zero length passwords are OK! :-) */
+ top = 15;
+ } else {
+ bottom = pwlen & ~7;
+ top = bottom + 7;
+ }
+
+ assert(pwlen >= bottom && pwlen <= top);
+
+ randomstr = snewn(top + 1, char);
+
+ for (i = bottom; i <= top; i++) {
+ if (i == pwlen) {
+ defer_packet(ssh, s->pwpkt_type,
+ PKTT_PASSWORD, PKT_STR, s->password,
+ PKTT_OTHER, PKT_END);
+ } else {
+ for (j = 0; j < i; j++) {
+ do {
+ randomstr[j] = random_byte();
+ } while (randomstr[j] == '\0');
+ }
+ randomstr[i] = '\0';
+ defer_packet(ssh, SSH1_MSG_IGNORE,
+ PKT_STR, randomstr, PKT_END);
+ }
+ }
+ logevent("Sending password with camouflage packets");
+ ssh_pkt_defersend(ssh);
+ sfree(randomstr);
+ }
+ else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
+ /*
+ * The server can't deal with SSH1_MSG_IGNORE
+ * but can deal with padded passwords, so we
+ * can use the secondary defence.
+ */
+ char string[64];
+ char *ss;
+ int len;
+
+ len = strlen(s->password);
+ if (len < sizeof(string)) {
+ ss = string;
+ strcpy(string, s->password);
+ len++; /* cover the zero byte */
+ while (len < sizeof(string)) {
+ string[len++] = (char) random_byte();
+ }
+ } else {
+ ss = s->password;
+ }
+ logevent("Sending length-padded password");
+ send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
+ PKT_INT, len, PKT_DATA, ss, len,
+ PKTT_OTHER, PKT_END);
+ } else {
+ /*
+ * The server has _both_
+ * BUG_CHOKES_ON_SSH1_IGNORE and
+ * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
+ * therefore nothing we can do.
+ */
+ int len;
+ len = strlen(s->password);
+ logevent("Sending unpadded password");
+ send_packet(ssh, s->pwpkt_type,
+ PKTT_PASSWORD, PKT_INT, len,
+ PKT_DATA, s->password, len,
+ PKTT_OTHER, PKT_END);
+ }
+ } else {
+ send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
+ PKT_STR, s->password, PKTT_OTHER, PKT_END);
+ }
+ }
+ logevent("Sent password");
+ memset(s->password, 0, strlen(s->password));
+ crWaitUntil(pktin);
+ if (pktin->type == SSH1_SMSG_FAILURE) {
+ if (flags & FLAG_VERBOSE)
+ c_write_str(ssh, "Access denied\r\n");