+ return 0;
+}
+
+/*
+ * Handle the key exchange and user authentication phases.
+ */
+static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
+{
+ int i, j;
+ unsigned char cookie[8];
+ 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 (!ispkt)
+ crWaitUntil(ispkt);
+
+ if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
+ bombout((ssh,"Public key packet not received"));
+ crReturn(0);
+ }
+
+ logevent("Received public keys");
+
+ memcpy(cookie, ssh->pktin.body, 8);
+
+ i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
+ j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 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 = GET_32BIT(ssh->pktin.body + 8 + i + j);
+ s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
+ s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
+
+ 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, ssh->pktin.body, 8);
+ MD5Final(s->session_id, &md5c);
+
+ for (i = 0; i < 32; i++)
+ ssh->session_key[i] = random_byte();
+
+ s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
+
+ s->rsabuf = smalloc(s->len);
+ 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 = smalloc(len);
+ 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) {
+ rsaencrypt(s->rsabuf, 32, &servkey);
+ rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
+ } else {
+ rsaencrypt(s->rsabuf, 32, &hostkey);
+ rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
+ }
+
+ 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 = 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((ssh,"Server violates SSH 1 protocol by not "
+ "supporting 3DES encryption"));
+ else
+ /* shouldn't happen */
+ bombout((ssh,"No supported ciphers found"));
+ crReturn(0);
+ }
+
+ /* Warn about chosen cipher if necessary. */
+ if (warn)
+ askcipher(ssh->frontend, cipher_string, 0);
+ }
+
+ 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);
+ {
+ char buf[256];
+ sprintf(buf, "Initialised %.200s encryption", ssh->cipher->text_name);
+ logevent(buf);
+ }
+
+ ssh->crcda_ctx = crcda_make_context();
+ logevent("Installing CRC compensation attack detector");
+
+ crWaitUntil(ispkt);
+
+ if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
+ bombout((ssh,"Encryption not successfully enabled"));
+ crReturn(0);
+ }
+
+ logevent("Successfully started encryption");
+
+ fflush(stdout);
+ {
+ if ((flags & FLAG_INTERACTIVE) && !*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->state = SSH_STATE_CLOSED;
+ crReturn(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(!ispkt);
+ 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, 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(ispkt);
+
+ 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 cfg.keyfile so we notice if it's in Pageant */
+ if (*cfg.keyfile) {
+ if (!rsakey_pubblob(cfg.keyfile,
+ &s->publickey_blob, &s->publickey_bloblen))
+ s->publickey_blob = NULL;
+ } else
+ s->publickey_blob = NULL;
+
+ while (ssh->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;
+ agent_query(s->request, 5, &r, &s->responselen);
+ 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;
+ s->p += ssh1_read_bignum(s->p, &s->key.exponent);
+ s->p += ssh1_read_bignum(s->p, &s->key.modulus);
+ s->commentlen = GET_32BIT(s->p);
+ s->p += 4;
+ s->commentp = s->p;
+ s->p += s->commentlen;
+ send_packet(ssh, SSH1_CMSG_AUTH_RSA,
+ PKT_BIGNUM, s->key.modulus, PKT_END);
+ crWaitUntil(ispkt);
+ if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
+ logevent("Key refused");
+ continue;
+ }
+ logevent("Received RSA challenge");
+ ssh1_read_bignum(ssh->pktin.body, &s->challenge);
+ {
+ 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 = smalloc(4 + len);
+ 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 */
+ agent_query(agentreq, len + 4, &vret, &retlen);
+ ret = vret;
+ sfree(agentreq);
+ 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(ispkt);
+ if (ssh->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;
+ }
+ }
+ if (s->authed)
+ break;
+ }
+ if (*cfg.keyfile && !s->tried_publickey)
+ s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
+
+ if (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(ispkt);
+ if (ssh->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 {
+ int challengelen = GET_32BIT(ssh->pktin.body);
+ logevent("Received TIS challenge");
+ if (challengelen > sizeof(s->prompt) - 1)
+ challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
+ memcpy(s->prompt, ssh->pktin.body + 4, 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 (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(ispkt);
+ if (ssh->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 {
+ int challengelen = GET_32BIT(ssh->pktin.body);
+ logevent("Received CryptoCard challenge");
+ if (challengelen > sizeof(s->prompt) - 1)
+ challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
+ memcpy(s->prompt, ssh->pktin.body + 4, 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");
+ sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
+ logevent(msgbuf);
+ type = key_type(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(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->state = SSH_STATE_CLOSED;
+ crReturn(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(!ispkt);
+ 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;
+
+ {
+ int ret = loadrsakey(cfg.keyfile, &s->key, s->password);
+ if (ret == 0) {
+ c_write_str(ssh, "Couldn't load private key from ");
+ c_write_str(ssh, cfg.keyfile);
+ 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(ispkt);
+ if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ c_write_str(ssh, "Server refused our public key.\r\n");
+ continue; /* go and try password */
+ }
+ if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
+ bombout((ssh,"Bizarre response to offer of public key"));
+ crReturn(0);
+ }
+
+ {
+ int i;
+ unsigned char buffer[32];
+ Bignum challenge, response;
+
+ ssh1_read_bignum(ssh->pktin.body, &challenge);
+ 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(ispkt);
+ if (ssh->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 (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
+ bombout((ssh,"Bizarre response to RSA authentication response"));
+ crReturn(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 = smalloc(top + 1);
+
+ for (i = bottom; i <= top; i++) {
+ if (i == pwlen)
+ defer_packet(ssh, s->pwpkt_type,
+ PKT_STR, s->password, 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);
+ }
+ 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, PKT_INT, len,
+ PKT_DATA, ss, len, 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, PKT_INT, len,
+ PKT_DATA, s->password, len, PKT_END);
+ }
+ } else {
+ send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
+ }
+ }
+ logevent("Sent password");
+ memset(s->password, 0, strlen(s->password));
+ crWaitUntil(ispkt);
+ if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ if (flags & FLAG_VERBOSE)
+ c_write_str(ssh, "Access denied\r\n");
+ logevent("Authentication refused");
+ } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
+ bombout((ssh,"Strange packet received, type %d", ssh->pktin.type));
+ crReturn(0);
+ }
+ }
+
+ logevent("Authentication successful");
+
+ crFinish(1);
+}
+
+void sshfwd_close(struct ssh_channel *c)
+{
+ Ssh ssh = c->ssh;
+
+ if (c && !c->closes) {
+ /*
+ * If the channel's remoteid is -1, we have sent
+ * CHANNEL_OPEN for this channel, but it hasn't even been
+ * acknowledged by the server. So we must set a close flag
+ * on it now, and then when the server acks the channel
+ * open, we can close it then.
+ */
+ if (((int)c->remoteid) != -1) {
+ if (ssh->version == 1) {
+ send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
+ PKT_END);
+ } else {
+ ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
+ ssh2_pkt_adduint32(ssh, c->remoteid);
+ ssh2_pkt_send(ssh);
+ }
+ }
+ c->closes = 1; /* sent MSG_CLOSE */
+ if (c->type == CHAN_X11) {
+ c->u.x11.s = NULL;
+ logevent("Forwarded X11 connection terminated");
+ } else if (c->type == CHAN_SOCKDATA ||
+ c->type == CHAN_SOCKDATA_DORMANT) {
+ c->u.pfd.s = NULL;
+ logevent("Forwarded port closed");
+ }
+ }
+}
+
+int sshfwd_write(struct ssh_channel *c, char *buf, int len)
+{
+ Ssh ssh = c->ssh;
+
+ if (ssh->version == 1) {
+ send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
+ PKT_INT, c->remoteid,
+ PKT_INT, len, PKT_DATA, buf, len, PKT_END);
+ /*
+ * In SSH1 we can return 0 here - implying that forwarded
+ * connections are never individually throttled - because
+ * the only circumstance that can cause throttling will be
+ * the whole SSH connection backing up, in which case
+ * _everything_ will be throttled as a whole.
+ */
+ return 0;
+ } else {
+ ssh2_add_channel_data(c, buf, len);
+ return ssh2_try_send(c);
+ }
+}
+
+void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
+{
+ Ssh ssh = c->ssh;
+
+ if (ssh->version == 1) {
+ if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
+ c->v.v1.throttling = 0;
+ ssh1_throttle(ssh, -1);
+ }
+ } else {
+ ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
+ }
+}
+
+static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
+{
+ crBegin(ssh->ssh1_protocol_crstate);
+
+ random_init();
+
+ while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
+ crReturnV;
+ }
+ if (ssh->state == SSH_STATE_CLOSED)
+ crReturnV;
+
+ if (cfg.agentfwd && agent_exists()) {
+ logevent("Requesting agent forwarding");
+ send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
+ do {
+ crReturnV;
+ } while (!ispkt);
+ if (ssh->pktin.type != SSH1_SMSG_SUCCESS
+ && ssh->pktin.type != SSH1_SMSG_FAILURE) {
+ bombout((ssh,"Protocol confusion"));
+ crReturnV;
+ } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ logevent("Agent forwarding refused");
+ } else {
+ logevent("Agent forwarding enabled");
+ ssh->agentfwd_enabled = TRUE;
+ }
+ }
+
+ if (cfg.x11_forward) {
+ char proto[20], data[64];
+ logevent("Requesting X11 forwarding");
+ ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
+ data, sizeof(data));
+ if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
+ send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
+ PKT_STR, proto, PKT_STR, data,
+ PKT_INT, 0, PKT_END);
+ } else {
+ send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
+ PKT_STR, proto, PKT_STR, data, PKT_END);
+ }
+ do {
+ crReturnV;
+ } while (!ispkt);
+ if (ssh->pktin.type != SSH1_SMSG_SUCCESS
+ && ssh->pktin.type != SSH1_SMSG_FAILURE) {
+ bombout((ssh,"Protocol confusion"));
+ crReturnV;
+ } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ logevent("X11 forwarding refused");
+ } else {
+ logevent("X11 forwarding enabled");
+ ssh->X11_fwd_enabled = TRUE;
+ }
+ }
+
+ {
+ char type;
+ int n;
+ int sport,dport,sserv,dserv;
+ char sports[256], dports[256], host[256];
+ char buf[1024];
+ struct servent *se;
+
+ ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
+ /* Add port forwardings. */
+ ssh->portfwd_strptr = cfg.portfwd;
+ while (*ssh->portfwd_strptr) {
+ type = *ssh->portfwd_strptr++;
+ n = 0;
+ while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
+ sports[n++] = *ssh->portfwd_strptr++;
+ sports[n] = 0;
+ if (*ssh->portfwd_strptr == '\t')
+ ssh->portfwd_strptr++;
+ n = 0;
+ while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
+ host[n++] = *ssh->portfwd_strptr++;
+ host[n] = 0;
+ if (*ssh->portfwd_strptr == ':')
+ ssh->portfwd_strptr++;
+ n = 0;
+ while (*ssh->portfwd_strptr)
+ dports[n++] = *ssh->portfwd_strptr++;
+ dports[n] = 0;
+ ssh->portfwd_strptr++;
+ dport = atoi(dports);
+ dserv = 0;
+ if (dport == 0) {
+ dserv = 1;
+ se = getservbyname(dports, NULL);
+ if (se != NULL) {
+ dport = ntohs(se->s_port);
+ } else {
+ sprintf(buf,
+ "Service lookup failed for destination port \"%s\"",
+ dports);
+ logevent(buf);
+ }
+ }
+ sport = atoi(sports);
+ sserv = 0;
+ if (sport == 0) {
+ sserv = 1;
+ se = getservbyname(sports, NULL);
+ if (se != NULL) {
+ sport = ntohs(se->s_port);
+ } else {
+ sprintf(buf,
+ "Service lookup failed for source port \"%s\"",
+ sports);
+ logevent(buf);
+ }
+ }
+ if (sport && dport) {
+ if (type == 'L') {
+ pfd_addforward(host, dport, sport, ssh);
+ sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
+ " %s:%.*s%.*s%d%.*s",
+ sserv ? strlen(sports) : 0, sports,
+ sserv, "(", sport, sserv, ")",
+ host,
+ dserv ? strlen(dports) : 0, dports,
+ dserv, "(", dport, dserv, ")");
+ logevent(buf);
+ } else {
+ struct ssh_rportfwd *pf;
+ pf = smalloc(sizeof(*pf));
+ strcpy(pf->dhost, host);
+ pf->dport = dport;
+ if (add234(ssh->rportfwds, pf) != pf) {
+ sprintf(buf,
+ "Duplicate remote port forwarding to %s:%d",
+ host, dport);
+ logevent(buf);
+ sfree(pf);
+ } else {
+ sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
+ " forward to %s:%.*s%.*s%d%.*s",
+ sserv ? strlen(sports) : 0, sports,
+ sserv, "(", sport, sserv, ")",
+ host,
+ dserv ? strlen(dports) : 0, dports,
+ dserv, "(", dport, dserv, ")");
+ logevent(buf);
+ send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
+ PKT_INT, sport,
+ PKT_STR, host,
+ PKT_INT, dport,
+ PKT_END);
+ do {
+ crReturnV;
+ } while (!ispkt);
+ if (ssh->pktin.type != SSH1_SMSG_SUCCESS
+ && ssh->pktin.type != SSH1_SMSG_FAILURE) {
+ bombout((ssh,"Protocol confusion"));
+ crReturnV;
+ } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ c_write_str(ssh, "Server refused port"
+ " forwarding\r\n");
+ }
+ logevent("Remote port forwarding enabled");
+ }
+ }
+ }
+ }
+ }
+
+ if (!cfg.nopty) {
+ send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
+ PKT_STR, cfg.termtype,
+ PKT_INT, ssh->term_height,
+ PKT_INT, ssh->term_width,
+ PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
+ ssh->state = SSH_STATE_INTERMED;
+ do {
+ crReturnV;
+ } while (!ispkt);
+ if (ssh->pktin.type != SSH1_SMSG_SUCCESS
+ && ssh->pktin.type != SSH1_SMSG_FAILURE) {
+ bombout((ssh,"Protocol confusion"));
+ crReturnV;
+ } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ c_write_str(ssh, "Server refused to allocate pty\r\n");
+ ssh->editing = ssh->echoing = 1;
+ }
+ logevent("Allocated pty");
+ } else {
+ ssh->editing = ssh->echoing = 1;
+ }
+
+ if (cfg.compression) {
+ send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
+ do {
+ crReturnV;
+ } while (!ispkt);
+ if (ssh->pktin.type != SSH1_SMSG_SUCCESS
+ && ssh->pktin.type != SSH1_SMSG_FAILURE) {
+ bombout((ssh,"Protocol confusion"));
+ crReturnV;
+ } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ c_write_str(ssh, "Server refused to compress\r\n");
+ }
+ logevent("Started compression");
+ ssh->v1_compressing = TRUE;
+ ssh->cs_comp_ctx = zlib_compress_init();
+ logevent("Initialised zlib (RFC1950) compression");
+ ssh->sc_comp_ctx = zlib_decompress_init();
+ logevent("Initialised zlib (RFC1950) decompression");
+ }
+
+ /*
+ * Start the shell or command.
+ *
+ * Special case: if the first-choice command is an SSH2
+ * subsystem (hence not usable here) and the second choice
+ * exists, we fall straight back to that.
+ */
+ {
+ char *cmd = cfg.remote_cmd_ptr;
+
+ if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
+ cmd = cfg.remote_cmd_ptr2;
+ ssh->fallback_cmd = TRUE;
+ }
+ if (*cmd)
+ send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
+ else
+ send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
+ logevent("Started session");
+ }
+
+ ssh->state = SSH_STATE_SESSION;
+ if (ssh->size_needed)
+ ssh_size(ssh, ssh->term_width, ssh->term_height);
+ if (ssh->eof_needed)
+ ssh_special(ssh, TS_EOF);
+
+ if (ssh->ldisc)
+ ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
+ ssh->send_ok = 1;
+ ssh->channels = newtree234(ssh_channelcmp);
+ while (1) {
+ crReturnV;
+ if (ispkt) {
+ if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
+ ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
+ long len = GET_32BIT(ssh->pktin.body);
+ int bufsize =
+ from_backend(ssh->frontend,
+ ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
+ ssh->pktin.body + 4, len);
+ if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
+ ssh->v1_stdout_throttling = 1;
+ ssh1_throttle(ssh, +1);
+ }
+ } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
+ ssh->state = SSH_STATE_CLOSED;
+ logevent("Received disconnect request");
+ crReturnV;
+ } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
+ /* Remote side is trying to open a channel to talk to our
+ * X-Server. Give them back a local channel number. */
+ struct ssh_channel *c;
+
+ logevent("Received X11 connect request");
+ /* Refuse if X11 forwarding is disabled. */
+ if (!ssh->X11_fwd_enabled) {
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
+ PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
+ logevent("Rejected X11 connect request");
+ } else {
+ c = smalloc(sizeof(struct ssh_channel));
+ c->ssh = ssh;
+
+ if (x11_init(&c->u.x11.s, cfg.x11_display, c,
+ ssh->x11auth) != NULL) {
+ logevent("opening X11 forward connection failed");
+ sfree(c);
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
+ PKT_INT, GET_32BIT(ssh->pktin.body),
+ PKT_END);
+ } else {
+ logevent
+ ("opening X11 forward connection succeeded");
+ c->remoteid = GET_32BIT(ssh->pktin.body);
+ c->localid = alloc_channel_id(ssh);
+ c->closes = 0;
+ c->v.v1.throttling = 0;
+ c->type = CHAN_X11; /* identify channel type */
+ add234(ssh->channels, c);
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
+ PKT_INT, c->remoteid, PKT_INT,
+ c->localid, PKT_END);
+ logevent("Opened X11 forward channel");
+ }
+ }
+ } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
+ /* Remote side is trying to open a channel to talk to our
+ * agent. Give them back a local channel number. */
+ struct ssh_channel *c;
+
+ /* Refuse if agent forwarding is disabled. */
+ if (!ssh->agentfwd_enabled) {
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
+ PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
+ } else {
+ c = smalloc(sizeof(struct ssh_channel));
+ c->ssh = ssh;
+ c->remoteid = GET_32BIT(ssh->pktin.body);
+ c->localid = alloc_channel_id(ssh);
+ c->closes = 0;
+ c->v.v1.throttling = 0;
+ c->type = CHAN_AGENT; /* identify channel type */
+ c->u.a.lensofar = 0;
+ add234(ssh->channels, c);
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
+ PKT_INT, c->remoteid, PKT_INT, c->localid,
+ PKT_END);
+ }
+ } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
+ /* Remote side is trying to open a channel to talk to a
+ * forwarded port. Give them back a local channel number. */
+ struct ssh_channel *c;
+ struct ssh_rportfwd pf;
+ int hostsize, port;
+ char host[256], buf[1024];
+ char *p, *h, *e;
+ c = smalloc(sizeof(struct ssh_channel));
+ c->ssh = ssh;
+
+ hostsize = GET_32BIT(ssh->pktin.body+4);
+ for(h = host, p = ssh->pktin.body+8; hostsize != 0; hostsize--) {
+ if (h+1 < host+sizeof(host))
+ *h++ = *p;
+ p++;
+ }
+ *h = 0;
+ port = GET_32BIT(p);
+
+ strcpy(pf.dhost, host);
+ pf.dport = port;
+
+ if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
+ sprintf(buf, "Rejected remote port open request for %s:%d",
+ host, port);
+ logevent(buf);
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
+ PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
+ } else {
+ sprintf(buf, "Received remote port open request for %s:%d",
+ host, port);
+ logevent(buf);
+ e = pfd_newconnect(&c->u.pfd.s, host, port, c);
+ if (e != NULL) {
+ char buf[256];
+ sprintf(buf, "Port open failed: %s", e);
+ logevent(buf);
+ sfree(c);
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
+ PKT_INT, GET_32BIT(ssh->pktin.body),
+ PKT_END);
+ } else {
+ c->remoteid = GET_32BIT(ssh->pktin.body);
+ c->localid = alloc_channel_id(ssh);
+ c->closes = 0;
+ c->v.v1.throttling = 0;
+ c->type = CHAN_SOCKDATA; /* identify channel type */
+ add234(ssh->channels, c);
+ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
+ PKT_INT, c->remoteid, PKT_INT,
+ c->localid, PKT_END);
+ logevent("Forwarded port opened successfully");
+ }
+ }
+
+ } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
+ unsigned int remoteid = GET_32BIT(ssh->pktin.body);
+ unsigned int localid = GET_32BIT(ssh->pktin.body+4);
+ struct ssh_channel *c;
+
+ c = find234(ssh->channels, &remoteid, ssh_channelfind);
+ if (c && c->type == CHAN_SOCKDATA_DORMANT) {
+ c->remoteid = localid;
+ c->type = CHAN_SOCKDATA;
+ c->v.v1.throttling = 0;
+ pfd_confirm(c->u.pfd.s);
+ }
+
+ if (c && c->closes) {
+ /*
+ * We have a pending close on this channel,
+ * which we decided on before the server acked
+ * the channel open. So now we know the
+ * remoteid, we can close it again.
+ */
+ send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
+ PKT_INT, c->remoteid, PKT_END);
+ }
+
+ } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
+ unsigned int remoteid = GET_32BIT(ssh->pktin.body);
+ unsigned int localid = GET_32BIT(ssh->pktin.body+4);
+ struct ssh_channel *c;
+
+ c = find234(ssh->channels, &remoteid, ssh_channelfind);
+ if (c && c->type == CHAN_SOCKDATA_DORMANT) {
+ logevent("Forwarded connection refused by server");
+ pfd_close(c->u.pfd.s);
+ del234(ssh->channels, c);
+ sfree(c);
+ }
+
+ } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
+ ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
+ /* Remote side closes a channel. */
+ unsigned i = GET_32BIT(ssh->pktin.body);
+ struct ssh_channel *c;
+ c = find234(ssh->channels, &i, ssh_channelfind);
+ if (c && ((int)c->remoteid) != -1) {
+ int closetype;
+ closetype =
+ (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
+
+ if ((c->closes == 0) && (c->type == CHAN_X11)) {
+ logevent("Forwarded X11 connection terminated");
+ assert(c->u.x11.s != NULL);
+ x11_close(c->u.x11.s);
+ c->u.x11.s = NULL;
+ }
+ if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
+ logevent("Forwarded port closed");
+ assert(c->u.pfd.s != NULL);
+ pfd_close(c->u.pfd.s);
+ c->u.pfd.s = NULL;
+ }
+
+ c->closes |= (closetype << 2); /* seen this message */
+ if (!(c->closes & closetype)) {
+ send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
+ PKT_END);
+ c->closes |= closetype; /* sent it too */
+ }
+
+ if (c->closes == 15) {
+ del234(ssh->channels, c);
+ sfree(c);
+ }
+ } else {
+ bombout((ssh,"Received CHANNEL_CLOSE%s for %s channel %d\n",
+ ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
+ "_CONFIRMATION", c ? "half-open" : "nonexistent",
+ i));
+ }
+ } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
+ /* Data sent down one of our channels. */
+ int i = GET_32BIT(ssh->pktin.body);
+ int len = GET_32BIT(ssh->pktin.body + 4);
+ unsigned char *p = ssh->pktin.body + 8;
+ struct ssh_channel *c;
+ c = find234(ssh->channels, &i, ssh_channelfind);
+ if (c) {
+ int bufsize;
+ switch (c->type) {
+ case CHAN_X11:
+ bufsize = x11_send(c->u.x11.s, p, len);
+ break;
+ case CHAN_SOCKDATA:
+ bufsize = pfd_send(c->u.pfd.s, p, len);
+ break;
+ case CHAN_AGENT:
+ /* Data for an agent message. Buffer it. */
+ while (len > 0) {
+ if (c->u.a.lensofar < 4) {
+ int l = min(4 - c->u.a.lensofar, len);
+ memcpy(c->u.a.msglen + c->u.a.lensofar, p,
+ l);
+ p += l;
+ len -= l;
+ c->u.a.lensofar += l;
+ }
+ if (c->u.a.lensofar == 4) {
+ c->u.a.totallen =
+ 4 + GET_32BIT(c->u.a.msglen);
+ c->u.a.message = smalloc(c->u.a.totallen);
+ memcpy(c->u.a.message, c->u.a.msglen, 4);
+ }
+ if (c->u.a.lensofar >= 4 && len > 0) {
+ int l =
+ min(c->u.a.totallen - c->u.a.lensofar,
+ len);
+ memcpy(c->u.a.message + c->u.a.lensofar, p,
+ l);
+ p += l;
+ len -= l;
+ c->u.a.lensofar += l;
+ }
+ if (c->u.a.lensofar == c->u.a.totallen) {
+ void *reply, *sentreply;
+ int replylen;
+ agent_query(c->u.a.message,
+ c->u.a.totallen, &reply,
+ &replylen);
+ if (reply)
+ sentreply = reply;
+ else {
+ /* Fake SSH_AGENT_FAILURE. */
+ sentreply = "\0\0\0\1\5";
+ replylen = 5;
+ }
+ send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
+ PKT_INT, c->remoteid,
+ PKT_INT, replylen,
+ PKT_DATA, sentreply, replylen,
+ PKT_END);
+ if (reply)
+ sfree(reply);
+ sfree(c->u.a.message);
+ c->u.a.lensofar = 0;
+ }
+ }
+ bufsize = 0; /* agent channels never back up */
+ break;
+ }
+ if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
+ c->v.v1.throttling = 1;
+ ssh1_throttle(ssh, +1);
+ }
+ }
+ } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
+ /* may be from EXEC_SHELL on some servers */
+ } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
+ /* may be from EXEC_SHELL on some servers
+ * if no pty is available or in other odd cases. Ignore */
+ } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
+ char buf[100];
+ ssh->exitcode = GET_32BIT(ssh->pktin.body);
+ sprintf(buf, "Server sent command exit status %d",
+ ssh->exitcode);
+ logevent(buf);
+ send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
+ /*
+ * In case `helpful' firewalls or proxies tack
+ * extra human-readable text on the end of the
+ * session which we might mistake for another
+ * encrypted packet, we close the session once
+ * we've sent EXIT_CONFIRMATION.
+ */
+ ssh->state = SSH_STATE_CLOSED;
+ crReturnV;
+ } else {
+ bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
+ crReturnV;
+ }
+ } else {
+ while (inlen > 0) {
+ int len = min(inlen, 512);
+ send_packet(ssh, SSH1_CMSG_STDIN_DATA,
+ PKT_INT, len, PKT_DATA, in, len, PKT_END);
+ in += len;
+ inlen -= len;
+ }
+ }
+ }
+
+ crFinishV;
+}
+
+/*
+ * Utility routine for decoding comma-separated strings in KEXINIT.
+ */
+static int in_commasep_string(char *needle, char *haystack, int haylen)
+{
+ int needlen = strlen(needle);
+ while (1) {
+ /*
+ * Is it at the start of the string?
+ */
+ if (haylen >= needlen && /* haystack is long enough */
+ !memcmp(needle, haystack, needlen) && /* initial match */
+ (haylen == needlen || haystack[needlen] == ',')
+ /* either , or EOS follows */
+ )
+ return 1;
+ /*
+ * If not, search for the next comma and resume after that.
+ * If no comma found, terminate.
+ */
+ while (haylen > 0 && *haystack != ',')
+ haylen--, haystack++;
+ if (haylen == 0)
+ return 0;
+ haylen--, haystack++; /* skip over comma itself */
+ }
+}
+
+/*
+ * SSH2 key creation method.
+ */
+static void ssh2_mkkey(Ssh ssh, Bignum K, char *H, char *sessid, char chr,
+ char *keyspace)
+{
+ SHA_State s;
+ /* First 20 bytes. */
+ SHA_Init(&s);
+ if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
+ sha_mpint(&s, K);
+ SHA_Bytes(&s, H, 20);
+ SHA_Bytes(&s, &chr, 1);
+ SHA_Bytes(&s, sessid, 20);
+ SHA_Final(&s, keyspace);
+ /* Next 20 bytes. */
+ SHA_Init(&s);
+ if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
+ sha_mpint(&s, K);
+ SHA_Bytes(&s, H, 20);
+ SHA_Bytes(&s, keyspace, 20);
+ SHA_Final(&s, keyspace + 20);
+}
+
+/*
+ * Handle the SSH2 transport layer.
+ */
+static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
+{
+ struct do_ssh2_transport_state {
+ int nbits, pbits, warn;
+ Bignum p, g, e, f, K;
+ int kex_init_value, kex_reply_value;
+ const struct ssh_mac **maclist;
+ int nmacs;
+ const struct ssh2_cipher *cscipher_tobe;
+ const struct ssh2_cipher *sccipher_tobe;
+ const struct ssh_mac *csmac_tobe;
+ const struct ssh_mac *scmac_tobe;
+ const struct ssh_compress *cscomp_tobe;
+ const struct ssh_compress *sccomp_tobe;
+ char *hostkeydata, *sigdata, *keystr, *fingerprint;
+ int hostkeylen, siglen;
+ void *hkey; /* actual host key */
+ unsigned char exchange_hash[20];
+ int n_preferred_ciphers;
+ const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
+ const struct ssh_compress *preferred_comp;
+ int first_kex;
+ };
+ crState(do_ssh2_transport_state);
+
+ crBegin(ssh->do_ssh2_transport_crstate);
+
+ s->cscipher_tobe = s->sccipher_tobe = NULL;
+ s->csmac_tobe = s->scmac_tobe = NULL;
+ s->cscomp_tobe = s->sccomp_tobe = NULL;
+
+ random_init();
+ s->first_kex = 1;
+
+ {
+ int i;
+ /*
+ * Set up the preferred ciphers. (NULL => warn below here)
+ */
+ s->n_preferred_ciphers = 0;
+ for (i = 0; i < CIPHER_MAX; i++) {
+ switch (cfg.ssh_cipherlist[i]) {
+ case CIPHER_BLOWFISH:
+ s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
+ break;
+ case CIPHER_DES:
+ if (cfg.ssh2_des_cbc) {
+ s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
+ }
+ break;
+ case CIPHER_3DES:
+ s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
+ break;
+ case CIPHER_AES:
+ s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
+ break;
+ case CIPHER_WARN:
+ /* Flag for later. Don't bother if it's the last in
+ * the list. */
+ if (i < CIPHER_MAX - 1) {
+ s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
+ }
+ break;
+ }
+ }
+ }
+
+ /*
+ * Set up preferred compression.
+ */
+ if (cfg.compression)
+ s->preferred_comp = &ssh_zlib;
+ else
+ s->preferred_comp = &ssh_comp_none;
+
+ /*
+ * Be prepared to work around the buggy MAC problem.
+ */
+ if (ssh->remote_bugs & BUG_SSH2_HMAC)
+ s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
+ else
+ s->maclist = macs, s->nmacs = lenof(macs);
+
+ begin_key_exchange:
+ {
+ int i, j, cipherstr_started;
+
+ /*
+ * Construct and send our key exchange packet.
+ */
+ ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
+ for (i = 0; i < 16; i++)
+ ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
+ /* List key exchange algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ for (i = 0; i < lenof(kex_algs); i++) {
+ if (kex_algs[i] == &ssh_diffiehellman_gex &&
+ (ssh->remote_bugs & BUG_SSH2_DH_GEX))
+ continue;
+ ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
+ if (i < lenof(kex_algs) - 1)
+ ssh2_pkt_addstring_str(ssh, ",");
+ }
+ /* List server host key algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ for (i = 0; i < lenof(hostkey_algs); i++) {
+ ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
+ if (i < lenof(hostkey_algs) - 1)
+ ssh2_pkt_addstring_str(ssh, ",");
+ }
+ /* List client->server encryption algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ cipherstr_started = 0;
+ for (i = 0; i < s->n_preferred_ciphers; i++) {
+ const struct ssh2_ciphers *c = s->preferred_ciphers[i];
+ if (!c) continue; /* warning flag */
+ for (j = 0; j < c->nciphers; j++) {
+ if (cipherstr_started)
+ ssh2_pkt_addstring_str(ssh, ",");
+ ssh2_pkt_addstring_str(ssh, c->list[j]->name);
+ cipherstr_started = 1;
+ }
+ }
+ /* List server->client encryption algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ cipherstr_started = 0;
+ for (i = 0; i < s->n_preferred_ciphers; i++) {
+ const struct ssh2_ciphers *c = s->preferred_ciphers[i];
+ if (!c) continue; /* warning flag */
+ for (j = 0; j < c->nciphers; j++) {
+ if (cipherstr_started)
+ ssh2_pkt_addstring_str(ssh, ",");
+ ssh2_pkt_addstring_str(ssh, c->list[j]->name);
+ cipherstr_started = 1;
+ }
+ }
+ /* List client->server MAC algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ for (i = 0; i < s->nmacs; i++) {
+ ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
+ if (i < s->nmacs - 1)
+ ssh2_pkt_addstring_str(ssh, ",");
+ }
+ /* List server->client MAC algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ for (i = 0; i < s->nmacs; i++) {
+ ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
+ if (i < s->nmacs - 1)
+ ssh2_pkt_addstring_str(ssh, ",");
+ }
+ /* List client->server compression algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ for (i = 0; i < lenof(compressions) + 1; i++) {
+ const struct ssh_compress *c =
+ i == 0 ? s->preferred_comp : compressions[i - 1];
+ ssh2_pkt_addstring_str(ssh, c->name);
+ if (i < lenof(compressions))
+ ssh2_pkt_addstring_str(ssh, ",");
+ }
+ /* List server->client compression algorithms. */
+ ssh2_pkt_addstring_start(ssh);
+ for (i = 0; i < lenof(compressions) + 1; i++) {
+ const struct ssh_compress *c =
+ i == 0 ? s->preferred_comp : compressions[i - 1];
+ ssh2_pkt_addstring_str(ssh, c->name);
+ if (i < lenof(compressions))
+ ssh2_pkt_addstring_str(ssh, ",");
+ }
+ /* List client->server languages. Empty list. */
+ ssh2_pkt_addstring_start(ssh);
+ /* List server->client languages. Empty list. */
+ ssh2_pkt_addstring_start(ssh);
+ /* First KEX packet does _not_ follow, because we're not that brave. */
+ ssh2_pkt_addbool(ssh, FALSE);
+ /* Reserved. */
+ ssh2_pkt_adduint32(ssh, 0);
+ }
+
+ ssh->exhash = ssh->exhashbase;
+ sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
+
+ ssh2_pkt_send(ssh);
+
+ if (!ispkt)
+ crWaitUntil(ispkt);
+ sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
+
+ /*
+ * Now examine the other side's KEXINIT to see what we're up
+ * to.
+ */
+ {
+ char *str;
+ int i, j, len;
+
+ if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
+ bombout((ssh,"expected key exchange packet from server"));
+ crReturn(0);
+ }
+ ssh->kex = NULL;
+ ssh->hostkey = NULL;
+ s->cscipher_tobe = NULL;
+ s->sccipher_tobe = NULL;
+ s->csmac_tobe = NULL;
+ s->scmac_tobe = NULL;
+ s->cscomp_tobe = NULL;
+ s->sccomp_tobe = NULL;
+ ssh->pktin.savedpos += 16; /* skip garbage cookie */
+ ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
+ for (i = 0; i < lenof(kex_algs); i++) {
+ if (kex_algs[i] == &ssh_diffiehellman_gex &&
+ (ssh->remote_bugs & BUG_SSH2_DH_GEX))
+ continue;
+ if (in_commasep_string(kex_algs[i]->name, str, len)) {
+ ssh->kex = kex_algs[i];
+ break;
+ }
+ }
+ ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
+ for (i = 0; i < lenof(hostkey_algs); i++) {
+ if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
+ ssh->hostkey = hostkey_algs[i];
+ break;
+ }
+ }
+ ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
+ s->warn = 0;
+ for (i = 0; i < s->n_preferred_ciphers; i++) {
+ const struct ssh2_ciphers *c = s->preferred_ciphers[i];
+ if (!c) {
+ s->warn = 1;
+ } else {
+ for (j = 0; j < c->nciphers; j++) {
+ if (in_commasep_string(c->list[j]->name, str, len)) {
+ s->cscipher_tobe = c->list[j];
+ break;
+ }
+ }
+ }
+ if (s->cscipher_tobe) {
+ if (s->warn)
+ askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
+ break;
+ }
+ }
+ if (!s->cscipher_tobe) {
+ bombout((ssh,"Couldn't agree a client-to-server cipher (available: %s)", str));
+ crReturn(0);
+ }
+
+ ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
+ s->warn = 0;
+ for (i = 0; i < s->n_preferred_ciphers; i++) {
+ const struct ssh2_ciphers *c = s->preferred_ciphers[i];
+ if (!c) {
+ s->warn = 1;
+ } else {
+ for (j = 0; j < c->nciphers; j++) {
+ if (in_commasep_string(c->list[j]->name, str, len)) {
+ s->sccipher_tobe = c->list[j];
+ break;
+ }
+ }
+ }
+ if (s->sccipher_tobe) {
+ if (s->warn)
+ askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
+ break;
+ }
+ }
+ if (!s->sccipher_tobe) {
+ bombout((ssh,"Couldn't agree a server-to-client cipher (available: %s)", str));
+ crReturn(0);
+ }
+
+ ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
+ for (i = 0; i < s->nmacs; i++) {
+ if (in_commasep_string(s->maclist[i]->name, str, len)) {
+ s->csmac_tobe = s->maclist[i];
+ break;
+ }
+ }
+ ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
+ for (i = 0; i < s->nmacs; i++) {
+ if (in_commasep_string(s->maclist[i]->name, str, len)) {
+ s->scmac_tobe = s->maclist[i];
+ break;
+ }
+ }
+ ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
+ for (i = 0; i < lenof(compressions) + 1; i++) {
+ const struct ssh_compress *c =
+ i == 0 ? s->preferred_comp : compressions[i - 1];
+ if (in_commasep_string(c->name, str, len)) {
+ s->cscomp_tobe = c;
+ break;
+ }
+ }
+ ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
+ for (i = 0; i < lenof(compressions) + 1; i++) {
+ const struct ssh_compress *c =
+ i == 0 ? s->preferred_comp : compressions[i - 1];
+ if (in_commasep_string(c->name, str, len)) {
+ s->sccomp_tobe = c;
+ break;
+ }
+ }
+ }
+
+ /*
+ * Work out the number of bits of key we will need from the key
+ * exchange. We start with the maximum key length of either
+ * cipher...
+ */
+ {
+ int csbits, scbits;
+
+ csbits = s->cscipher_tobe->keylen;
+ scbits = s->sccipher_tobe->keylen;
+ s->nbits = (csbits > scbits ? csbits : scbits);
+ }
+ /* The keys only have 160-bit entropy, since they're based on
+ * a SHA-1 hash. So cap the key size at 160 bits. */
+ if (s->nbits > 160)
+ s->nbits = 160;
+
+ /*
+ * If we're doing Diffie-Hellman group exchange, start by
+ * requesting a group.
+ */
+ if (ssh->kex == &ssh_diffiehellman_gex) {
+ logevent("Doing Diffie-Hellman group exchange");
+ ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
+ /*
+ * Work out how big a DH group we will need to allow that
+ * much data.
+ */
+ s->pbits = 512 << ((s->nbits - 1) / 64);
+ ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
+ ssh2_pkt_adduint32(ssh, s->pbits);
+ ssh2_pkt_send(ssh);
+
+ crWaitUntil(ispkt);
+ if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
+ bombout((ssh,"expected key exchange group packet from server"));
+ crReturn(0);
+ }
+ s->p = ssh2_pkt_getmp(ssh);
+ s->g = ssh2_pkt_getmp(ssh);
+ ssh->kex_ctx = dh_setup_group(s->p, s->g);
+ s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
+ s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
+ } else {
+ ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
+ ssh->kex_ctx = dh_setup_group1();
+ s->kex_init_value = SSH2_MSG_KEXDH_INIT;
+ s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
+ }
+
+ logevent("Doing Diffie-Hellman key exchange");
+ /*
+ * Now generate and send e for Diffie-Hellman.
+ */
+ s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
+ ssh2_pkt_init(ssh, s->kex_init_value);
+ ssh2_pkt_addmp(ssh, s->e);
+ ssh2_pkt_send(ssh);
+
+ crWaitUntil(ispkt);
+ if (ssh->pktin.type != s->kex_reply_value) {
+ bombout((ssh,"expected key exchange reply packet from server"));
+ crReturn(0);
+ }
+ ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
+ s->f = ssh2_pkt_getmp(ssh);
+ ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
+
+ s->K = dh_find_K(ssh->kex_ctx, s->f);
+
+ sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
+ if (ssh->kex == &ssh_diffiehellman_gex) {
+ sha_uint32(&ssh->exhash, s->pbits);
+ sha_mpint(&ssh->exhash, s->p);
+ sha_mpint(&ssh->exhash, s->g);
+ }
+ sha_mpint(&ssh->exhash, s->e);
+ sha_mpint(&ssh->exhash, s->f);
+ sha_mpint(&ssh->exhash, s->K);
+ SHA_Final(&ssh->exhash, s->exchange_hash);
+
+ dh_cleanup(ssh->kex_ctx);
+
+#if 0
+ debug(("Exchange hash is:\n"));
+ dmemdump(s->exchange_hash, 20);
+#endif
+
+ s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
+ if (!s->hkey ||
+ !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
+ s->exchange_hash, 20)) {
+ bombout((ssh,"Server's host key did not match the signature supplied"));
+ crReturn(0);
+ }
+
+ /*
+ * Authenticate remote host: verify host key. (We've already
+ * checked the signature of the exchange hash.)
+ */
+ s->keystr = ssh->hostkey->fmtkey(s->hkey);
+ s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
+ verify_ssh_host_key(ssh->frontend,
+ ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
+ s->keystr, s->fingerprint);
+ if (s->first_kex) { /* don't bother logging this in rekeys */
+ logevent("Host key fingerprint is:");
+ logevent(s->fingerprint);
+ }
+ sfree(s->fingerprint);
+ sfree(s->keystr);
+ ssh->hostkey->freekey(s->hkey);
+
+ /*
+ * Send SSH2_MSG_NEWKEYS.
+ */
+ ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
+ ssh2_pkt_send(ssh);
+
+ /*
+ * Expect SSH2_MSG_NEWKEYS from server.
+ */
+ crWaitUntil(ispkt);
+ if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
+ bombout((ssh,"expected new-keys packet from server"));
+ crReturn(0);
+ }
+
+ /*
+ * Create and initialise session keys.
+ */
+ if (ssh->cs_cipher_ctx)
+ ssh->cscipher->free_context(ssh->cs_cipher_ctx);
+ ssh->cscipher = s->cscipher_tobe;
+ ssh->cs_cipher_ctx = ssh->cscipher->make_context();
+
+ if (ssh->sc_cipher_ctx)
+ ssh->sccipher->free_context(ssh->sc_cipher_ctx);
+ ssh->sccipher = s->sccipher_tobe;
+ ssh->sc_cipher_ctx = ssh->sccipher->make_context();
+
+ if (ssh->cs_mac_ctx)
+ ssh->csmac->free_context(ssh->cs_mac_ctx);
+ ssh->csmac = s->csmac_tobe;
+ ssh->cs_mac_ctx = ssh->csmac->make_context();
+
+ if (ssh->sc_mac_ctx)
+ ssh->scmac->free_context(ssh->sc_mac_ctx);
+ ssh->scmac = s->scmac_tobe;
+ ssh->sc_mac_ctx = ssh->scmac->make_context();
+
+ if (ssh->cs_comp_ctx)
+ ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
+ ssh->cscomp = s->cscomp_tobe;
+ ssh->cs_comp_ctx = ssh->cscomp->compress_init();
+
+ if (ssh->sc_comp_ctx)
+ ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
+ ssh->sccomp = s->sccomp_tobe;
+ ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
+
+ /*
+ * Set IVs after keys. Here we use the exchange hash from the
+ * _first_ key exchange.
+ */
+ {
+ unsigned char keyspace[40];
+ if (s->first_kex)
+ memcpy(ssh->v2_session_id, s->exchange_hash,
+ sizeof(s->exchange_hash));
+ ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
+ ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
+ ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
+ ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
+ ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
+ ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
+ ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
+ ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
+ ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
+ ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
+ ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
+ ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
+ }
+ {
+ char buf[256];
+ sprintf(buf, "Initialised %.200s client->server encryption",
+ ssh->cscipher->text_name);
+ logevent(buf);
+ sprintf(buf, "Initialised %.200s server->client encryption",
+ ssh->sccipher->text_name);
+ logevent(buf);
+ if (ssh->cscomp->text_name) {
+ sprintf(buf, "Initialised %.200s compression",
+ ssh->cscomp->text_name);
+ logevent(buf);
+ }
+ if (ssh->sccomp->text_name) {
+ sprintf(buf, "Initialised %.200s decompression",
+ ssh->sccomp->text_name);
+ logevent(buf);
+ }
+ }
+
+
+ /*
+ * If this is the first key exchange phase, we must pass the
+ * SSH2_MSG_NEWKEYS packet to the next layer, not because it
+ * wants to see it but because it will need time to initialise
+ * itself before it sees an actual packet. In subsequent key
+ * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
+ * it would only confuse the layer above.
+ */
+ if (!s->first_kex) {
+ crReturn(0);
+ }
+ s->first_kex = 0;
+
+ /*
+ * Now we're encrypting. Begin returning 1 to the protocol main
+ * function so that other things can run on top of the
+ * transport. If we ever see a KEXINIT, we must go back to the
+ * start.
+ */
+ while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
+ crReturn(1);
+ }
+ logevent("Server initiated key re-exchange");
+ goto begin_key_exchange;
+
+ crFinish(1);
+}
+
+/*
+ * Add data to an SSH2 channel output buffer.
+ */
+static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
+ int len)
+{
+ bufchain_add(&c->v.v2.outbuffer, buf, len);
+}
+
+/*
+ * Attempt to send data on an SSH2 channel.
+ */
+static int ssh2_try_send(struct ssh_channel *c)
+{
+ Ssh ssh = c->ssh;
+
+ while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
+ int len;
+ void *data;
+ bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
+ if ((unsigned)len > c->v.v2.remwindow)
+ len = c->v.v2.remwindow;
+ if ((unsigned)len > c->v.v2.remmaxpkt)
+ len = c->v.v2.remmaxpkt;
+ ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
+ ssh2_pkt_adduint32(ssh, c->remoteid);
+ ssh2_pkt_addstring_start(ssh);
+ ssh2_pkt_addstring_data(ssh, data, len);
+ ssh2_pkt_send(ssh);
+ bufchain_consume(&c->v.v2.outbuffer, len);
+ c->v.v2.remwindow -= len;
+ }
+
+ /*
+ * After having sent as much data as we can, return the amount
+ * still buffered.
+ */
+ return bufchain_size(&c->v.v2.outbuffer);
+}
+
+/*
+ * Potentially enlarge the window on an SSH2 channel.
+ */
+static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
+{
+ Ssh ssh = c->ssh;
+
+ /*
+ * Never send WINDOW_ADJUST for a channel that the remote side
+ * already thinks it's closed; there's no point, since it won't
+ * be sending any more data anyway.
+ */
+ if (c->closes != 0)
+ return;
+
+ if (newwin > c->v.v2.locwindow) {
+ ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
+ ssh2_pkt_adduint32(ssh, c->remoteid);
+ ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
+ ssh2_pkt_send(ssh);
+ c->v.v2.locwindow = newwin;
+ }
+}
+
+/*
+ * Handle the SSH2 userauth and connection layers.
+ */
+static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
+{
+ struct do_ssh2_authconn_state {
+ enum {
+ AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
+ AUTH_PASSWORD,
+ AUTH_KEYBOARD_INTERACTIVE
+ } method;
+ enum {
+ AUTH_TYPE_NONE,
+ AUTH_TYPE_PUBLICKEY,
+ AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
+ AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
+ AUTH_TYPE_PASSWORD,
+ AUTH_TYPE_KEYBOARD_INTERACTIVE,
+ AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
+ } type;
+ int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
+ int tried_pubkey_config, tried_agent, tried_keyb_inter;
+ int kbd_inter_running;
+ int we_are_in;
+ int num_prompts, curr_prompt, echo;
+ char username[100];
+ int got_username;
+ char pwprompt[200];
+ char password[100];
+ void *publickey_blob;
+ int publickey_bloblen;
+ unsigned char request[5], *response, *p;
+ int responselen;
+ int keyi, nkeys;
+ int authed;
+ char *pkblob, *alg, *commentp;
+ int pklen, alglen, commentlen;
+ int siglen, retlen, len;
+ char *q, *agentreq, *ret;
+ int try_send;
+ };
+ crState(do_ssh2_authconn_state);
+
+ crBegin(ssh->do_ssh2_authconn_crstate);
+
+ /*
+ * Request userauth protocol, and await a response to it.
+ */
+ ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
+ ssh2_pkt_addstring(ssh, "ssh-userauth");
+ ssh2_pkt_send(ssh);
+ crWaitUntilV(ispkt);
+ if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
+ bombout((ssh,"Server refused user authentication protocol"));
+ crReturnV;
+ }
+
+ /*
+ * We repeat this whole loop, including the username prompt,
+ * until we manage a successful authentication. If the user
+ * types the wrong _password_, they can be sent back to the
+ * beginning to try another username, if this is configured on.
+ * (If they specify a username in the config, they are never
+ * asked, even if they do give a wrong password.)
+ *
+ * I think this best serves the needs of
+ *
+ * - the people who have no configuration, no keys, and just
+ * want to try repeated (username,password) pairs until they
+ * type both correctly
+ *
+ * - people who have keys and configuration but occasionally
+ * need to fall back to passwords
+ *
+ * - people with a key held in Pageant, who might not have
+ * logged in to a particular machine before; so they want to
+ * type a username, and then _either_ their key will be
+ * accepted, _or_ they will type a password. If they mistype
+ * the username they will want to be able to get back and
+ * retype it!
+ */
+ s->username[0] = '\0';
+ s->got_username = FALSE;
+ do {
+ /*
+ * Get a username.
+ */
+ if (s->got_username && !cfg.change_username) {
+ /*
+ * We got a username last time round this loop, and
+ * with change_username turned off we don't try to get
+ * it again.
+ */
+ } else if ((flags & FLAG_INTERACTIVE) && !*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->state = SSH_STATE_CLOSED;
+ crReturnV;
+ }
+ } else {
+ int ret; /* need not be saved across crReturn */
+ c_write_str(ssh, "login as: ");
+ ssh->send_ok = 1;
+ setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
+ do {
+ crWaitUntilV(!ispkt);
+ ret = process_userpass_input(ssh, in, inlen);
+ } while (ret == 0);
+ if (ret < 0)
+ cleanup_exit(0);
+ }
+ c_write_str(ssh, "\r\n");
+ s->username[strcspn(s->username, "\n\r")] = '\0';
+ } else {
+ char stuff[200];
+ strncpy(s->username, cfg.username, sizeof(s->username));
+ s->username[sizeof(s->username)-1] = '\0';
+ if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
+ sprintf(stuff, "Using username \"%s\".\r\n", s->username);
+ c_write_str(ssh, stuff);
+ }
+ }
+ s->got_username = TRUE;
+
+ /*
+ * Send an authentication request using method "none": (a)
+ * just in case it succeeds, and (b) so that we know what
+ * authentication methods we can usefully try next.
+ */
+ ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
+ ssh2_pkt_addstring(ssh, "none"); /* method */
+ ssh2_pkt_send(ssh);
+ s->type = AUTH_TYPE_NONE;
+ s->gotit = FALSE;
+ s->we_are_in = FALSE;
+
+ s->tried_pubkey_config = FALSE;
+ s->tried_agent = FALSE;
+ s->tried_keyb_inter = FALSE;
+ s->kbd_inter_running = FALSE;
+ /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
+ if (*cfg.keyfile) {
+ int keytype;
+ logeventf(ssh->frontend,
+ "Reading private key file \"%.150s\"", cfg.keyfile);
+ keytype = key_type(cfg.keyfile);
+ if (keytype == SSH_KEYTYPE_SSH2) {
+ s->publickey_blob =
+ ssh2_userkey_loadpub(cfg.keyfile, NULL,
+ &s->publickey_bloblen);
+ } else {
+ char msgbuf[256];
+ logeventf(ssh->frontend,
+ "Unable to use this key file (%s)",
+ key_type_to_str(keytype));
+ sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
+ cfg.keyfile, key_type_to_str(keytype));
+ c_write_str(ssh, msgbuf);
+ s->publickey_blob = NULL;
+ }
+ } else
+ s->publickey_blob = NULL;
+
+ while (1) {
+ /*
+ * Wait for the result of the last authentication request.
+ */
+ if (!s->gotit)
+ crWaitUntilV(ispkt);
+ while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
+ char *banner;
+ int size;
+ /*
+ * Don't show the banner if we're operating in
+ * non-verbose non-interactive mode. (It's probably
+ * a script, which means nobody will read the
+ * banner _anyway_, and moreover the printing of
+ * the banner will screw up processing on the
+ * output of (say) plink.)
+ */
+ if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
+ ssh2_pkt_getstring(ssh, &banner, &size);
+ if (banner)
+ c_write_untrusted(ssh, banner, size);
+ }
+ crWaitUntilV(ispkt);
+ }
+ if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
+ logevent("Access granted");
+ s->we_are_in = TRUE;
+ break;
+ }
+
+ if (s->kbd_inter_running &&
+ ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
+ /*
+ * This is either a further set-of-prompts packet
+ * in keyboard-interactive authentication, or it's
+ * the same one and we came back here with `gotit'
+ * set. In the former case, we must reset the
+ * curr_prompt variable.
+ */
+ if (!s->gotit)
+ s->curr_prompt = 0;
+ } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
+ bombout((ssh,"Strange packet received during authentication: type %d",
+ ssh->pktin.type));
+ crReturnV;
+ }
+
+ s->gotit = FALSE;
+
+ /*
+ * OK, we're now sitting on a USERAUTH_FAILURE message, so
+ * we can look at the string in it and know what we can
+ * helpfully try next.
+ */
+ if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
+ char *methods;
+ int methlen;
+ ssh2_pkt_getstring(ssh, &methods, &methlen);
+ s->kbd_inter_running = FALSE;
+ if (!ssh2_pkt_getbool(ssh)) {
+ /*
+ * We have received an unequivocal Access
+ * Denied. This can translate to a variety of
+ * messages:
+ *
+ * - if we'd just tried "none" authentication,
+ * it's not worth printing anything at all
+ *
+ * - if we'd just tried a public key _offer_,
+ * the message should be "Server refused our
+ * key" (or no message at all if the key
+ * came from Pageant)
+ *
+ * - if we'd just tried anything else, the
+ * message really should be "Access denied".
+ *
+ * Additionally, if we'd just tried password
+ * authentication, we should break out of this
+ * whole loop so as to go back to the username
+ * prompt.
+ */
+ if (s->type == AUTH_TYPE_NONE) {
+ /* do nothing */
+ } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
+ s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
+ if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
+ c_write_str(ssh, "Server refused our key\r\n");
+ logevent("Server refused public key");
+ } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
+ /* server declined keyboard-interactive; ignore */
+ } else {
+ c_write_str(ssh, "Access denied\r\n");
+ logevent("Access denied");
+ if (s->type == AUTH_TYPE_PASSWORD) {
+ s->we_are_in = FALSE;
+ break;
+ }
+ }
+ } else {
+ c_write_str(ssh, "Further authentication required\r\n");
+ logevent("Further authentication required");
+ }
+
+ s->can_pubkey =
+ in_commasep_string("publickey", methods, methlen);
+ s->can_passwd =
+ in_commasep_string("password", methods, methlen);
+ s->can_keyb_inter = cfg.try_ki_auth &&
+ in_commasep_string("keyboard-interactive", methods, methlen);
+ }
+
+ s->method = 0;
+ ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+
+ /*
+ * Most password/passphrase prompts will be
+ * non-echoing, so we set this to 0 by default.
+ * Exception is that some keyboard-interactive prompts
+ * can be echoing, in which case we'll set this to 1.
+ */
+ s->echo = 0;
+
+ if (!s->method && s->can_pubkey &&
+ agent_exists() && !s->tried_agent) {
+ /*
+ * Attempt public-key authentication using Pageant.
+ */
+ void *r;
+ s->authed = FALSE;
+
+ ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+ ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
+
+ s->tried_agent = TRUE;
+
+ logevent("Pageant is running. Requesting keys.");
+
+ /* Request the keys held by the agent. */
+ PUT_32BIT(s->request, 1);
+ s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
+ agent_query(s->request, 5, &r, &s->responselen);
+ s->response = (unsigned char *) r;
+ if (s->response && s->responselen >= 5 &&
+ s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
+ s->p = s->response + 5;
+ s->nkeys = GET_32BIT(s->p);
+ s->p += 4;
+ {
+ char buf[64];
+ sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
+ logevent(buf);
+ }
+ for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
+ void *vret;
+
+ {
+ char buf[64];
+ sprintf(buf, "Trying Pageant key #%d", s->keyi);
+ logevent(buf);
+ }
+ s->pklen = GET_32BIT(s->p);
+ s->p += 4;
+ if (s->publickey_blob &&
+ s->pklen == s->publickey_bloblen &&
+ !memcmp(s->p, s->publickey_blob,
+ s->publickey_bloblen)) {
+ logevent("This key matches configured key file");
+ s->tried_pubkey_config = 1;
+ }
+ s->pkblob = s->p;
+ s->p += s->pklen;
+ s->alglen = GET_32BIT(s->pkblob);
+ s->alg = s->pkblob + 4;
+ s->commentlen = GET_32BIT(s->p);
+ s->p += 4;
+ s->commentp = s->p;
+ s->p += s->commentlen;
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
+ ssh2_pkt_addstring(ssh, "publickey"); /* method */
+ ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
+ ssh2_pkt_addstring_start(ssh);
+ ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
+ ssh2_pkt_addstring_start(ssh);
+ ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
+ ssh2_pkt_send(ssh);
+
+ crWaitUntilV(ispkt);
+ if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
+ logevent("Key refused");
+ continue;
+ }
+
+ if (flags & FLAG_VERBOSE) {
+ c_write_str(ssh, "Authenticating with "
+ "public key \"");
+ c_write(ssh, s->commentp, s->commentlen);
+ c_write_str(ssh, "\" from agent\r\n");
+ }
+
+ /*
+ * Server is willing to accept the key.
+ * Construct a SIGN_REQUEST.
+ */
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
+ ssh2_pkt_addstring(ssh, "publickey"); /* method */
+ ssh2_pkt_addbool(ssh, TRUE);
+ ssh2_pkt_addstring_start(ssh);
+ ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
+ ssh2_pkt_addstring_start(ssh);
+ ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
+
+ s->siglen = ssh->pktout.length - 5 + 4 + 20;
+ s->len = 1; /* message type */
+ s->len += 4 + s->pklen; /* key blob */
+ s->len += 4 + s->siglen; /* data to sign */
+ s->len += 4; /* flags */
+ s->agentreq = smalloc(4 + s->len);
+ PUT_32BIT(s->agentreq, s->len);
+ s->q = s->agentreq + 4;
+ *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
+ PUT_32BIT(s->q, s->pklen);
+ s->q += 4;
+ memcpy(s->q, s->pkblob, s->pklen);
+ s->q += s->pklen;
+ PUT_32BIT(s->q, s->siglen);
+ s->q += 4;
+ /* Now the data to be signed... */
+ PUT_32BIT(s->q, 20);
+ s->q += 4;
+ memcpy(s->q, ssh->v2_session_id, 20);
+ s->q += 20;
+ memcpy(s->q, ssh->pktout.data + 5,
+ ssh->pktout.length - 5);
+ s->q += ssh->pktout.length - 5;
+ /* And finally the (zero) flags word. */
+ PUT_32BIT(s->q, 0);
+ agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
+ s->ret = vret;
+ sfree(s->agentreq);
+ if (s->ret) {
+ if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
+ logevent("Sending Pageant's response");
+ ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
+ s->ret + 9,
+ GET_32BIT(s->ret + 5));
+ ssh2_pkt_send(ssh);
+ s->authed = TRUE;
+ break;
+ } else {
+ logevent
+ ("Pageant failed to answer challenge");
+ sfree(s->ret);
+ }
+ }
+ }
+ if (s->authed)
+ continue;
+ }
+ }
+
+ if (!s->method && s->can_pubkey && s->publickey_blob
+ && !s->tried_pubkey_config) {
+ unsigned char *pub_blob;
+ char *algorithm, *comment;
+ int pub_blob_len;
+
+ s->tried_pubkey_config = TRUE;
+
+ ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+ ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
+
+ /*
+ * Try the public key supplied in the configuration.
+ *
+ * First, offer the public blob to see if the server is
+ * willing to accept it.
+ */
+ pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
+ &pub_blob_len);
+ if (pub_blob) {
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
+ ssh2_pkt_addstring(ssh, "publickey"); /* method */
+ ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
+ ssh2_pkt_addstring(ssh, algorithm);
+ ssh2_pkt_addstring_start(ssh);
+ ssh2_pkt_addstring_data(ssh, pub_blob, pub_blob_len);
+ ssh2_pkt_send(ssh);
+ logevent("Offered public key"); /* FIXME */
+
+ crWaitUntilV(ispkt);
+ if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
+ s->gotit = TRUE;
+ s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
+ continue; /* key refused; give up on it */
+ }
+
+ logevent("Offer of public key accepted");
+ /*
+ * Actually attempt a serious authentication using
+ * the key.
+ */
+ if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
+ sprintf(s->pwprompt,
+ "Passphrase for key \"%.100s\": ",
+ comment);
+ s->need_pw = TRUE;
+ } else {
+ s->need_pw = FALSE;
+ }
+ c_write_str(ssh, "Authenticating with public key \"");
+ c_write_str(ssh, comment);
+ c_write_str(ssh, "\"\r\n");
+ s->method = AUTH_PUBLICKEY_FILE;
+ }
+ }
+
+ if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
+ s->method = AUTH_KEYBOARD_INTERACTIVE;
+ s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
+ s->tried_keyb_inter = TRUE;
+
+ ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+ ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
+
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
+ ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
+ ssh2_pkt_addstring(ssh, ""); /* lang */
+ ssh2_pkt_addstring(ssh, "");
+ ssh2_pkt_send(ssh);
+
+ crWaitUntilV(ispkt);
+ if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
+ if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
+ s->gotit = TRUE;
+ logevent("Keyboard-interactive authentication refused");
+ s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
+ continue;
+ }
+
+ s->kbd_inter_running = TRUE;
+ s->curr_prompt = 0;
+ }
+
+ if (s->kbd_inter_running) {
+ s->method = AUTH_KEYBOARD_INTERACTIVE;
+ s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
+ s->tried_keyb_inter = TRUE;
+
+ ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+ ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
+
+ if (s->curr_prompt == 0) {
+ /*
+ * We've got a fresh USERAUTH_INFO_REQUEST.
+ * Display header data, and start going through
+ * the prompts.
+ */
+ char *name, *inst, *lang;
+ int name_len, inst_len, lang_len;
+
+ ssh2_pkt_getstring(ssh, &name, &name_len);
+ ssh2_pkt_getstring(ssh, &inst, &inst_len);
+ ssh2_pkt_getstring(ssh, &lang, &lang_len);
+ if (name_len > 0) {
+ c_write_untrusted(ssh, name, name_len);
+ c_write_str(ssh, "\r\n");
+ }
+ if (inst_len > 0) {
+ c_write_untrusted(ssh, inst, inst_len);
+ c_write_str(ssh, "\r\n");
+ }
+ s->num_prompts = ssh2_pkt_getuint32(ssh);
+ }
+
+ /*
+ * If there are prompts remaining in the packet,
+ * display one and get a response.
+ */
+ if (s->curr_prompt < s->num_prompts) {
+ char *prompt;
+ int prompt_len;
+
+ ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
+ if (prompt_len > 0) {
+ strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
+ s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
+ prompt_len : sizeof(s->pwprompt)-1] = '\0';
+ } else {
+ strcpy(s->pwprompt,
+ "<server failed to send prompt>: ");
+ }
+ s->echo = ssh2_pkt_getbool(ssh);
+ s->need_pw = TRUE;
+ } else
+ s->need_pw = FALSE;
+ }
+
+ if (!s->method && s->can_passwd) {
+ s->method = AUTH_PASSWORD;
+ ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+ ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
+ sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
+ ssh->savedhost);
+ s->need_pw = TRUE;
+ }
+
+ if (s->need_pw) {
+ if (ssh_get_line) {
+ if (!ssh_get_line(s->pwprompt, 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.
+ */
+ ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
+ ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
+ ssh2_pkt_addstring(ssh, "No more passwords available"
+ " to try");
+ ssh2_pkt_addstring(ssh, "en"); /* language tag */
+ ssh2_pkt_send(ssh);
+ logevent("Unable to authenticate");
+ connection_fatal(ssh->frontend,
+ "Unable to authenticate");
+ ssh->state = SSH_STATE_CLOSED;
+ crReturnV;
+ }
+ } else {
+ int ret; /* need not be saved across crReturn */
+ c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
+ ssh->send_ok = 1;
+
+ setup_userpass_input(ssh, s->password,
+ sizeof(s->password), s->echo);
+ do {
+ crWaitUntilV(!ispkt);
+ ret = process_userpass_input(ssh, in, inlen);
+ } while (ret == 0);
+ if (ret < 0)
+ cleanup_exit(0);
+ c_write_str(ssh, "\r\n");
+ }
+ }
+
+ if (s->method == AUTH_PUBLICKEY_FILE) {
+ /*
+ * We have our passphrase. Now try the actual authentication.
+ */
+ struct ssh2_userkey *key;
+
+ key = ssh2_load_userkey(cfg.keyfile, s->password);
+ if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
+ if (key == SSH2_WRONG_PASSPHRASE) {
+ c_write_str(ssh, "Wrong passphrase\r\n");
+ s->tried_pubkey_config = FALSE;
+ } else {
+ c_write_str(ssh, "Unable to load private key\r\n");
+ s->tried_pubkey_config = TRUE;
+ }
+ /* Send a spurious AUTH_NONE to return to the top. */
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
+ ssh2_pkt_addstring(ssh, "none"); /* method */
+ ssh2_pkt_send(ssh);
+ s->type = AUTH_TYPE_NONE;
+ } else {
+ unsigned char *pkblob, *sigblob, *sigdata;
+ int pkblob_len, sigblob_len, sigdata_len;
+
+ /*
+ * We have loaded the private key and the server
+ * has announced that it's willing to accept it.
+ * Hallelujah. Generate a signature and send it.
+ */
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
+ ssh2_pkt_addstring(ssh, "publickey"); /* method */
+ ssh2_pkt_addbool(ssh, TRUE);
+ ssh2_pkt_addstring(ssh, key->alg->name);
+ pkblob = key->alg->public_blob(key->data, &pkblob_len);
+ ssh2_pkt_addstring_start(ssh);
+ ssh2_pkt_addstring_data(ssh, pkblob, pkblob_len);
+
+ /*
+ * The data to be signed is:
+ *
+ * string session-id
+ *
+ * followed by everything so far placed in the
+ * outgoing packet.
+ */
+ sigdata_len = ssh->pktout.length - 5 + 4 + 20;
+ sigdata = smalloc(sigdata_len);
+ PUT_32BIT(sigdata, 20);
+ memcpy(sigdata + 4, ssh->v2_session_id, 20);
+ memcpy(sigdata + 24, ssh->pktout.data + 5,
+ ssh->pktout.length - 5);
+ sigblob = key->alg->sign(key->data, sigdata,
+ sigdata_len, &sigblob_len);
+ ssh2_add_sigblob(ssh, pkblob, pkblob_len,
+ sigblob, sigblob_len);
+ sfree(pkblob);
+ sfree(sigblob);
+ sfree(sigdata);
+
+ ssh2_pkt_send(ssh);
+ s->type = AUTH_TYPE_PUBLICKEY;
+ }
+ } else if (s->method == AUTH_PASSWORD) {
+ /*
+ * We send the password packet lumped tightly together with
+ * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
+ * string long enough to make the total length of the two
+ * packets constant. This should ensure that a passive
+ * listener doing traffic analyis can't work out the length
+ * of the password.
+ *
+ * For this to work, we need an assumption about the
+ * maximum length of the password packet. I think 256 is
+ * pretty conservative. Anyone using a password longer than
+ * that probably doesn't have much to worry about from
+ * people who find out how long their password is!
+ */
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
+ ssh2_pkt_addstring(ssh, s->username);
+ ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
+ ssh2_pkt_addstring(ssh, "password");
+ ssh2_pkt_addbool(ssh, FALSE);
+ ssh2_pkt_addstring(ssh, s->password);
+ ssh2_pkt_defer(ssh);
+ /*
+ * We'll include a string that's an exact multiple of the
+ * cipher block size. If the cipher is NULL for some
+ * reason, we don't do this trick at all because we gain
+ * nothing by it.
+ */
+ if (ssh->cscipher) {
+ int stringlen, i;
+
+ stringlen = (256 - ssh->deferred_len);
+ stringlen += ssh->cscipher->blksize - 1;
+ stringlen -= (stringlen % ssh->cscipher->blksize);
+ if (ssh->cscomp) {
+ /*
+ * Temporarily disable actual compression,
+ * so we can guarantee to get this string
+ * exactly the length we want it. The
+ * compression-disabling routine should
+ * return an integer indicating how many
+ * bytes we should adjust our string length
+ * by.
+ */
+ stringlen -=
+ ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
+ }
+ ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
+ ssh2_pkt_addstring_start(ssh);
+ for (i = 0; i < stringlen; i++) {
+ char c = (char) random_byte();
+ ssh2_pkt_addstring_data(ssh, &c, 1);
+ }
+ ssh2_pkt_defer(ssh);
+ }
+ ssh_pkt_defersend(ssh);
+ logevent("Sent password");
+ s->type = AUTH_TYPE_PASSWORD;
+ } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
+ if (s->curr_prompt == 0) {
+ ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
+ ssh2_pkt_adduint32(ssh, s->num_prompts);
+ }
+ if (s->need_pw) { /* only add pw if we just got one! */
+ ssh2_pkt_addstring(ssh, s->password);
+ memset(s->password, 0, sizeof(s->password));
+ s->curr_prompt++;
+ }
+ if (s->curr_prompt >= s->num_prompts) {
+ ssh2_pkt_send(ssh);
+ } else {
+ /*
+ * If there are prompts remaining, we set
+ * `gotit' so that we won't attempt to get
+ * another packet. Then we go back round the
+ * loop and will end up retrieving another
+ * prompt out of the existing packet. Funky or
+ * what?
+ */
+ s->gotit = TRUE;
+ }
+ s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
+ } else {
+ c_write_str(ssh, "No supported authentication methods"
+ " left to try!\r\n");
+ logevent("No supported authentications offered."
+ " Disconnecting");
+ ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
+ ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
+ ssh2_pkt_addstring(ssh, "No supported authentication"
+ " methods available");
+ ssh2_pkt_addstring(ssh, "en"); /* language tag */
+ ssh2_pkt_send(ssh);
+ ssh->state = SSH_STATE_CLOSED;
+ crReturnV;
+ }
+ }
+ } while (!s->we_are_in);