Merged SSH1 robustness changes from 0.55 release branch on to trunk.
[u/mdw/putty] / ssh.c
diff --git a/ssh.c b/ssh.c
index a968e60..2019d48 100644 (file)
--- a/ssh.c
+++ b/ssh.c
@@ -163,6 +163,7 @@ static const char *const ssh2_disconnect_reasons[] = {
 #define BUG_SSH2_RSA_PADDING                    16
 #define BUG_SSH2_DERIVEKEY                       32
 #define BUG_SSH2_DH_GEX                          64
+#define BUG_SSH2_PK_SESSIONID                   128
 
 #define translate(x) if (type == x) return #x
 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
@@ -268,11 +269,30 @@ static char *ssh2_pkt_type(int pkt_ctx, int type)
 
 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
 
-/* Coroutine mechanics for the sillier bits of the code */
+/*
+ * Coroutine mechanics for the sillier bits of the code. If these
+ * macros look impenetrable to you, you might find it helpful to
+ * read
+ * 
+ *   http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
+ * 
+ * which explains the theory behind these macros.
+ * 
+ * In particular, if you are getting `case expression not constant'
+ * errors when building with MS Visual Studio, this is because MS's
+ * Edit and Continue debugging feature causes their compiler to
+ * violate ANSI C. To disable Edit and Continue debugging:
+ * 
+ *  - right-click ssh.c in the FileView
+ *  - click Settings
+ *  - select the C/C++ tab and the General category
+ *  - under `Debug info:', select anything _other_ than `Program
+ *    Database for Edit and Continue'.
+ */
 #define crBegin(v)     { int *crLine = &v; switch(v) { case 0:;
 #define crState(t) \
     struct t *s; \
-    if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
+    if (!ssh->t) ssh->t = snew(struct t); \
     s = ssh->t;
 #define crFinish(z)    } *crLine = 0; return (z); }
 #define crFinishV      } *crLine = 0; return; }
@@ -302,6 +322,8 @@ static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
 static void ssh2_pkt_addmp(Ssh, Bignum b);
 static int ssh2_pkt_construct(Ssh);
 static void ssh2_pkt_send(Ssh);
+static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt);
+static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt);
 
 /*
  * Buffer management constants. There are several of these for
@@ -495,6 +517,7 @@ static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
 static int ssh_sendbuffer(void *handle);
+static void ssh_do_close(Ssh ssh);
 
 struct rdpkt1_state_tag {
     long len, pad, biglen, to_read;
@@ -550,6 +573,7 @@ struct ssh_tag {
 
     void *frontend;
 
+    int ospeed, ispeed;                       /* temporaries */
     int term_width, term_height;
 
     tree234 *channels;                /* indexed by local id */
@@ -628,12 +652,18 @@ struct ssh_tag {
      * potentially reconfigure port forwardings etc in mid-session.
      */
     Config cfg;
+
+    /*
+     * Used to transfer data back from async agent callbacks.
+     */
+    void *agent_response;
+    int agent_response_len;
 };
 
 #define logevent(s) logevent(ssh->frontend, s)
 
 /* logevent, only printf-formatted. */
-static void logeventf(Ssh ssh, char *fmt, ...)
+static void logeventf(Ssh ssh, const char *fmt, ...)
 {
     va_list ap;
     char *buf;
@@ -645,9 +675,14 @@ static void logeventf(Ssh ssh, char *fmt, ...)
     sfree(buf);
 }
 
-#define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
-                          (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
-                          logeventf msg, connection_fatal msg )
+#define bombout(msg) \
+    do { \
+        char *text = dupprintf msg; \
+       ssh_do_close(ssh); \
+        logevent(text); \
+        connection_fatal(ssh->frontend, "%s", text); \
+        sfree(text); \
+    } while (0)
 
 static int ssh_channelcmp(void *av, void *bv)
 {
@@ -734,7 +769,7 @@ static int alloc_channel_id(Ssh ssh)
     return low + 1 + CHANNEL_NUMBER_OFFSET;
 }
 
-static void c_write(Ssh ssh, char *buf, int len)
+static void c_write(Ssh ssh, const char *buf, int len)
 {
     if ((flags & FLAG_STDERR)) {
        int i;
@@ -746,7 +781,7 @@ static void c_write(Ssh ssh, char *buf, int len)
     from_backend(ssh->frontend, 1, buf, len);
 }
 
-static void c_write_untrusted(Ssh ssh, char *buf, int len)
+static void c_write_untrusted(Ssh ssh, const char *buf, int len)
 {
     int i;
     for (i = 0; i < len; i++) {
@@ -757,7 +792,7 @@ static void c_write_untrusted(Ssh ssh, char *buf, int len)
     }
 }
 
-static void c_write_str(Ssh ssh, char *buf)
+static void c_write_str(Ssh ssh, const char *buf)
 {
     c_write(ssh, buf, strlen(buf));
 }
@@ -794,7 +829,8 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
 
     if (ssh->pktin.maxlen < st->biglen) {
        ssh->pktin.maxlen = st->biglen;
-       ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
+       ssh->pktin.data = sresize(ssh->pktin.data, st->biglen + APIEXTRA,
+                                 unsigned char);
     }
 
     st->to_read = st->biglen;
@@ -814,33 +850,38 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
 
     if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
                                     st->biglen, NULL)) {
-        bombout((ssh,"Network attack (CRC compensation) detected!"));
-        crReturn(0);
+        bombout(("Network attack (CRC compensation) detected!"));
+        crStop(0);
     }
 
     if (ssh->cipher)
        ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
 
-    st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
+    st->realcrc = crc32_compute(ssh->pktin.data, st->biglen - 4);
     st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
     if (st->gotcrc != st->realcrc) {
-       bombout((ssh,"Incorrect CRC received on packet"));
-       crReturn(0);
+       bombout(("Incorrect CRC received on packet"));
+       crStop(0);
     }
 
     ssh->pktin.body = ssh->pktin.data + st->pad + 1;
+    ssh->pktin.savedpos = 0;
 
     if (ssh->v1_compressing) {
        unsigned char *decompblk;
        int decomplen;
-       zlib_decompress_block(ssh->sc_comp_ctx,
-                             ssh->pktin.body - 1, ssh->pktin.length + 1,
-                             &decompblk, &decomplen);
+       if (!zlib_decompress_block(ssh->sc_comp_ctx,
+                                  ssh->pktin.body - 1, ssh->pktin.length + 1,
+                                  &decompblk, &decomplen)) {
+           bombout(("Zlib decompression encountered invalid data"));
+           crStop(0);
+       }
 
        if (ssh->pktin.maxlen < st->pad + decomplen) {
            ssh->pktin.maxlen = st->pad + decomplen;
-           ssh->pktin.data = srealloc(ssh->pktin.data,
-                                      ssh->pktin.maxlen + APIEXTRA);
+           ssh->pktin.data = sresize(ssh->pktin.data,
+                                     ssh->pktin.maxlen + APIEXTRA,
+                                     unsigned char);
            ssh->pktin.body = ssh->pktin.data + st->pad + 1;
        }
 
@@ -864,8 +905,8 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
        ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
        long stringlen = GET_32BIT(ssh->pktin.body);
        if (stringlen + 4 != ssh->pktin.length) {
-           bombout((ssh,"Received data packet with bogus string length"));
-           crReturn(0);
+           bombout(("Received data packet with bogus string length"));
+           crStop(0);
        }
     }
 
@@ -897,8 +938,8 @@ static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
        memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
        buf[nowlen + msglen] = '\0';
        /* logevent(buf); (this is now done within the bombout macro) */
-       bombout((ssh,"Server sent disconnect message:\n\"%s\"", buf+nowlen));
-       crReturn(0);
+       bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
+       crStop(0);
     }
 
     crFinish(0);
@@ -922,7 +963,8 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
 
     if (ssh->pktin.maxlen < st->cipherblk) {
        ssh->pktin.maxlen = st->cipherblk;
-       ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
+       ssh->pktin.data = sresize(ssh->pktin.data, st->cipherblk + APIEXTRA,
+                                 unsigned char);
     }
 
     /*
@@ -951,8 +993,8 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
      * do us any more damage.
      */
     if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
-       bombout((ssh,"Incoming packet was garbled on decryption"));
-       crReturn(0);
+       bombout(("Incoming packet was garbled on decryption"));
+       crStop(0);
     }
 
     /*
@@ -973,8 +1015,9 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
      */
     if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
        ssh->pktin.maxlen = st->packetlen + st->maclen;
-       ssh->pktin.data = srealloc(ssh->pktin.data,
-                                  ssh->pktin.maxlen + APIEXTRA);
+       ssh->pktin.data = sresize(ssh->pktin.data,
+                                 ssh->pktin.maxlen + APIEXTRA,
+                                 unsigned char);
     }
 
     /*
@@ -999,8 +1042,8 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
     if (ssh->scmac
        && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
                               st->incoming_sequence)) {
-       bombout((ssh,"Incorrect MAC received on packet"));
-       crReturn(0);
+       bombout(("Incorrect MAC received on packet"));
+       crStop(0);
     }
     st->incoming_sequence++;          /* whether or not we MACed */
 
@@ -1016,8 +1059,9 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
                                    &newpayload, &newlen)) {
            if (ssh->pktin.maxlen < newlen + 5) {
                ssh->pktin.maxlen = newlen + 5;
-               ssh->pktin.data = srealloc(ssh->pktin.data,
-                                          ssh->pktin.maxlen + APIEXTRA);
+               ssh->pktin.data = sresize(ssh->pktin.data,
+                                         ssh->pktin.maxlen + APIEXTRA,
+                                         unsigned char);
            }
            ssh->pktin.length = 5 + newlen;
            memcpy(ssh->pktin.data + 5, newpayload, newlen);
@@ -1026,6 +1070,7 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
     }
 
     ssh->pktin.savedpos = 6;
+    ssh->pktin.body = ssh->pktin.data;
     ssh->pktin.type = ssh->pktin.data[5];
 
     if (ssh->logctx)
@@ -1057,13 +1102,13 @@ static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
             buf = dupprintf("Disconnection message text: %n%.*s",
                            &nowlen, msglen, ssh->pktin.data + 14);
             logevent(buf);
-            bombout((ssh,"Server sent disconnect message\ntype %d (%s):\n\"%s\"",
+            bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
                      reason,
                      (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
                      ssh2_disconnect_reasons[reason] : "unknown",
                      buf+nowlen));
            sfree(buf);
-            crReturn(0);
+            crStop(0);
         }
         break;
       case SSH2_MSG_IGNORE:
@@ -1150,9 +1195,11 @@ static void ssh1_pktout_size(Ssh ssh, int len)
 #ifdef MSCRYPTOAPI
        /* Allocate enough buffer space for extra block
         * for MS CryptEncrypt() */
-       ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
+       ssh->pktout.data = sresize(ssh->pktout.data, biglen + 12,
+                                  unsigned char);
 #else
-       ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
+       ssh->pktout.data = sresize(ssh->pktout.data, biglen + 4,
+                                  unsigned char);
 #endif
     }
     ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
@@ -1166,8 +1213,18 @@ static void s_wrpkt_start(Ssh ssh, int type, int len)
 
 static int s_wrpkt_prepare(Ssh ssh)
 {
-    int pad, len, biglen, i;
+    int pad, biglen, i;
     unsigned long crc;
+#ifdef __SC__
+    /*
+     * XXX various versions of SC (including 8.8.4) screw up the
+     * register allocation in this function and use the same register
+     * (D6) for len and as a temporary, with predictable results.  The
+     * following sledgehammer prevents this.
+     */
+    volatile
+#endif
+    int len;
 
     ssh->pktout.body[-1] = ssh->pktout.type;
 
@@ -1193,7 +1250,7 @@ static int s_wrpkt_prepare(Ssh ssh)
 
     for (i = 0; i < pad; i++)
        ssh->pktout.data[i + 4] = random_byte();
-    crc = crc32(ssh->pktout.data + 4, biglen - 4);
+    crc = crc32_compute(ssh->pktout.data + 4, biglen - 4);
     PUT_32BIT(ssh->pktout.data + biglen, crc);
     PUT_32BIT(ssh->pktout.data, len);
 
@@ -1218,8 +1275,9 @@ static void s_wrpkt_defer(Ssh ssh)
     len = s_wrpkt_prepare(ssh);
     if (ssh->deferred_len + len > ssh->deferred_size) {
        ssh->deferred_size = ssh->deferred_len + len + 128;
-       ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
-                                          ssh->deferred_size);
+       ssh->deferred_send_data = sresize(ssh->deferred_send_data,
+                                         ssh->deferred_size,
+                                         unsigned char);
     }
     memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
     ssh->deferred_len += len;
@@ -1366,8 +1424,9 @@ static void ssh2_pkt_ensure(Ssh ssh, int length)
 {
     if (ssh->pktout.maxlen < length) {
        ssh->pktout.maxlen = length + 256;
-       ssh->pktout.data = srealloc(ssh->pktout.data,
-                                   ssh->pktout.maxlen + APIEXTRA);
+       ssh->pktout.data = sresize(ssh->pktout.data,
+                                  ssh->pktout.maxlen + APIEXTRA,
+                                  unsigned char);
        if (!ssh->pktout.data)
            fatalbox("Out of memory");
     }
@@ -1423,7 +1482,7 @@ static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
 {
     unsigned char *p;
     int i, n = (bignum_bitcount(b) + 7) / 8;
-    p = smalloc(n + 1);
+    p = snewn(n + 1, unsigned char);
     if (!p)
        fatalbox("out of memory");
     p[0] = 0;
@@ -1534,8 +1593,9 @@ static void ssh2_pkt_defer(Ssh ssh)
     int len = ssh2_pkt_construct(ssh);
     if (ssh->deferred_len + len > ssh->deferred_size) {
        ssh->deferred_size = ssh->deferred_len + len + 128;
-       ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
-                                          ssh->deferred_size);
+       ssh->deferred_send_data = sresize(ssh->deferred_send_data,
+                                         ssh->deferred_size,
+                                         unsigned char);
     }
     memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
     ssh->deferred_len += len;
@@ -1581,14 +1641,14 @@ static void sha_mpint(SHA_State * s, Bignum b)
 }
 
 /*
- * SSH2 packet decode functions.
+ * Packet decode functions for both SSH1 and SSH2.
  */
-static unsigned long ssh2_pkt_getuint32(Ssh ssh)
+static unsigned long ssh_pkt_getuint32(Ssh ssh)
 {
     unsigned long value;
     if (ssh->pktin.length - ssh->pktin.savedpos < 4)
        return 0;                      /* arrgh, no way to decline (FIXME?) */
-    value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
+    value = GET_32BIT(ssh->pktin.body + ssh->pktin.savedpos);
     ssh->pktin.savedpos += 4;
     return value;
 }
@@ -1597,38 +1657,76 @@ static int ssh2_pkt_getbool(Ssh ssh)
     unsigned long value;
     if (ssh->pktin.length - ssh->pktin.savedpos < 1)
        return 0;                      /* arrgh, no way to decline (FIXME?) */
-    value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
+    value = ssh->pktin.body[ssh->pktin.savedpos] != 0;
     ssh->pktin.savedpos++;
     return value;
 }
-static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
+static void ssh_pkt_getstring(Ssh ssh, char **p, int *length)
 {
     int len;
     *p = NULL;
     *length = 0;
     if (ssh->pktin.length - ssh->pktin.savedpos < 4)
        return;
-    len = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
+    len = GET_32BIT(ssh->pktin.body + ssh->pktin.savedpos);
     if (len < 0)
        return;
     *length = len;
     ssh->pktin.savedpos += 4;
     if (ssh->pktin.length - ssh->pktin.savedpos < *length)
        return;
-    *p = (char *)(ssh->pktin.data + ssh->pktin.savedpos);
+    *p = (char *)(ssh->pktin.body + ssh->pktin.savedpos);
     ssh->pktin.savedpos += *length;
 }
+static void *ssh_pkt_getdata(Ssh ssh, int length)
+{
+    if (ssh->pktin.length - ssh->pktin.savedpos < length)
+       return NULL;
+    ssh->pktin.savedpos += length;
+    return ssh->pktin.body + (ssh->pktin.savedpos - length);
+}
+static int ssh1_pkt_getrsakey(Ssh ssh, struct RSAKey *key,
+                             unsigned char **keystr)
+{
+    int j;
+
+    j = makekey(ssh->pktin.body + ssh->pktin.savedpos,
+               ssh->pktin.length - ssh->pktin.savedpos,
+               key, keystr, 0);
+
+    if (j < 0)
+       return FALSE;
+    
+    ssh->pktin.savedpos += j;
+    assert(ssh->pktin.savedpos < ssh->pktin.length);
+
+    return TRUE;
+}
+static Bignum ssh1_pkt_getmp(Ssh ssh)
+{
+    int j;
+    Bignum b;
+
+    j = ssh1_read_bignum(ssh->pktin.body + ssh->pktin.savedpos,
+                        ssh->pktin.length - ssh->pktin.savedpos, &b);
+
+    if (j < 0)
+       return NULL;
+
+    ssh->pktin.savedpos += j;
+    return b;
+}
 static Bignum ssh2_pkt_getmp(Ssh ssh)
 {
     char *p;
     int length;
     Bignum b;
 
-    ssh2_pkt_getstring(ssh, &p, &length);
+    ssh_pkt_getstring(ssh, &p, &length);
     if (!p)
        return NULL;
     if (p[0] & 0x80) {
-       bombout((ssh,"internal error: Can't handle negative mpints"));
+       bombout(("internal error: Can't handle negative mpints"));
        return NULL;
     }
     b = bignum_from_bytes((unsigned char *)p, length);
@@ -1723,7 +1821,8 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
        (ssh->cfg.sshbug_ignore1 == AUTO &&
         (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
          !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
-         !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
+         !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
+         !strcmp(imp, "OSU_1.4alpha3")))) {
        /*
         * These versions don't support SSH1_MSG_IGNORE, so we have
         * to use a different defence against password length
@@ -1735,7 +1834,7 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
 
     if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
        (ssh->cfg.sshbug_plainpw1 == AUTO &&
-        (!strcmp(imp, "Cisco-1.25")))) {
+        (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
        /*
         * These versions need a plain password sent; they can't
         * handle having a null and a random length of data after
@@ -1759,6 +1858,7 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
 
     if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
        (ssh->cfg.sshbug_hmac2 == AUTO &&
+        !wc_match("* VShell", imp) &&
         (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
          wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
          wc_match("2.1 *", imp)))) {
@@ -1771,7 +1871,8 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
 
     if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
        (ssh->cfg.sshbug_derivekey2 == AUTO &&
-        (wc_match("2.0.0*", imp) || wc_match("2.0.1[01]*", imp) ))) {
+        !wc_match("* VShell", imp) &&
+        (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
        /*
         * These versions have the key-derivation bug (failing to
         * include the literal shared secret in the hashes that
@@ -1792,6 +1893,17 @@ static void ssh_detect_bugs(Ssh ssh, char *vstring)
        logevent("We believe remote version has SSH2 RSA padding bug");
     }
 
+    if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
+       (ssh->cfg.sshbug_pksessid2 == AUTO &&
+        wc_match("OpenSSH_2.[0-2]*", imp))) {
+       /*
+        * These versions have the SSH2 session-ID bug in
+        * public-key authentication.
+        */
+       ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
+       logevent("We believe remote version has SSH2 public-key-session-ID bug");
+    }
+
     if (ssh->cfg.sshbug_dhgex2 == FORCE_ON) {
        /*
         * User specified the SSH2 DH GEX bug.
@@ -1835,7 +1947,7 @@ static int do_ssh_init(Ssh ssh, unsigned char c)
     }
 
     s->vstrsize = 16;
-    s->vstring = smalloc(s->vstrsize);
+    s->vstring = snewn(s->vstrsize, char);
     strcpy(s->vstring, "SSH-");
     s->vslen = 4;
     s->i = 0;
@@ -1843,7 +1955,7 @@ static int do_ssh_init(Ssh ssh, unsigned char c)
        crReturn(1);                   /* get another char */
        if (s->vslen >= s->vstrsize - 1) {
            s->vstrsize += 16;
-           s->vstring = srealloc(s->vstring, s->vstrsize);
+           s->vstring = sresize(s->vstring, s->vstrsize, char);
        }
        s->vstring[s->vslen++] = c;
        if (s->i >= 0) {
@@ -1863,7 +1975,7 @@ static int do_ssh_init(Ssh ssh, unsigned char c)
     s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
     {
        char *vlog;
-       vlog = smalloc(20 + s->vslen);
+       vlog = snewn(20 + s->vslen, char);
        sprintf(vlog, "Server version: %s", s->vstring);
        logevent(vlog);
        sfree(vlog);
@@ -1880,12 +1992,12 @@ static int do_ssh_init(Ssh ssh, unsigned char c)
     s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
 
     if (ssh->cfg.sshprot == 0 && !s->proto1) {
-       bombout((ssh,"SSH protocol version 1 required by user but not provided by server"));
-       crReturn(0);
+       bombout(("SSH protocol version 1 required by user but not provided by server"));
+       crStop(0);
     }
     if (ssh->cfg.sshprot == 3 && !s->proto2) {
-       bombout((ssh,"SSH protocol version 2 required by user but not provided by server"));
-       crReturn(0);
+       bombout(("SSH protocol version 2 required by user but not provided by server"));
+       crStop(0);
     }
 
     if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
@@ -1926,6 +2038,7 @@ static int do_ssh_init(Ssh ssh, unsigned char c)
        ssh->version = 1;
        ssh->s_rdpkt = ssh1_rdpkt;
     }
+    update_specials_menu(ssh->frontend);
     ssh->state = SSH_STATE_BEFORE_SIZE;
 
     sfree(s->vstring);
@@ -1979,19 +2092,47 @@ static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
     crFinishV;
 }
 
-static int ssh_closing(Plug plug, char *error_msg, int error_code,
-                      int calling_back)
+static void ssh_do_close(Ssh ssh)
 {
-    Ssh ssh = (Ssh) plug;
+    int i;
+    struct ssh_channel *c;
+
     ssh->state = SSH_STATE_CLOSED;
     if (ssh->s) {
         sk_close(ssh->s);
         ssh->s = NULL;
     }
+    /*
+     * 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, error_msg);
+       connection_fatal(ssh->frontend, "%s", error_msg);
     } else {
        /* Otherwise, the remote side closed the connection normally. */
     }
@@ -2003,10 +2144,7 @@ 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) {
-       if (ssh->s) {
-           sk_close(ssh->s);
-           ssh->s = NULL;
-       }
+       ssh_do_close(ssh);
        return 0;
     }
     return 1;
@@ -2029,8 +2167,8 @@ static void ssh_sent(Plug plug, int bufsize)
  * Also places the canonical host name into `realhost'. It must be
  * freed by the caller.
  */
-static char *connect_to_host(Ssh ssh, char *host, int port,
-                            char **realhost, int nodelay)
+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,
@@ -2040,9 +2178,9 @@ static char *connect_to_host(Ssh ssh, char *host, int port,
     };
 
     SockAddr addr;
-    char *err;
+    const char *err;
 
-    ssh->savedhost = smalloc(1 + strlen(host));
+    ssh->savedhost = snewn(1 + strlen(host), char);
     if (!ssh->savedhost)
        fatalbox("Out of memory");
     strcpy(ssh->savedhost, host);
@@ -2056,8 +2194,10 @@ static char *connect_to_host(Ssh ssh, char *host, int port,
      */
     logeventf(ssh, "Looking up host \"%s\"", host);
     addr = name_lookup(host, port, realhost, &ssh->cfg);
-    if ((err = sk_addr_error(addr)) != NULL)
+    if ((err = sk_addr_error(addr)) != NULL) {
+       sk_addr_free(addr);
        return err;
+    }
 
     /*
      * Open socket.
@@ -2069,7 +2209,7 @@ static char *connect_to_host(Ssh ssh, char *host, int port,
     }
     ssh->fn = &fn_table;
     ssh->s = new_connection(addr, *realhost, port,
-                           0, 1, nodelay, (Plug) ssh, &ssh->cfg);
+                           0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
     if ((err = sk_socket_error(ssh->s)) != NULL) {
        ssh->s = NULL;
        return err;
@@ -2122,7 +2262,7 @@ static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
            /* Agent channels require no buffer management. */
            break;
          case CHAN_SOCKDATA:
-           pfd_override_throttle(c->u.x11.s, enable);
+           pfd_override_throttle(c->u.pfd.s, enable);
            break;
        }
     }
@@ -2181,7 +2321,13 @@ static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
            return -1;
            break;
          default:
-           if (((c >= ' ' && c <= '~') ||
+           /*
+            * 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;
@@ -2194,13 +2340,51 @@ static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
     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, 0);
+    else
+       do_ssh2_authconn(ssh, NULL, -1, 0);
+}
+
+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,
+                   PKT_INT, replylen,
+                   PKT_DATA, sentreply, replylen,
+                   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, int ispkt)
 {
-    int i, j;
-    unsigned char cookie[8];
+    int i, j, ret;
+    unsigned char cookie[8], *ptr;
     struct RSAKey servkey, hostkey;
     struct MD5Context md5c;
     struct do_ssh1_login_state {
@@ -2236,16 +2420,24 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        crWaitUntil(ispkt);
 
     if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
-       bombout((ssh,"Public key packet not received"));
-       crReturn(0);
+       bombout(("Public key packet not received"));
+       crStop(0);
     }
 
     logevent("Received public keys");
 
-    memcpy(cookie, ssh->pktin.body, 8);
+    ptr = ssh_pkt_getdata(ssh, 8);
+    if (!ptr) {
+       bombout(("SSH1 public key packet stopped before random cookie"));
+       crStop(0);
+    }
+    memcpy(cookie, ptr, 8);
 
-    i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
-    j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
+    if (!ssh1_pkt_getrsakey(ssh, &servkey, &s->keystr1) ||
+       !ssh1_pkt_getrsakey(ssh, &hostkey, &s->keystr2)) {      
+       bombout(("SSH1 public key packet stopped before public keys"));
+       crStop(0);
+    }
 
     /*
      * Log the host key fingerprint.
@@ -2260,9 +2452,9 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        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_remote_protoflags = ssh_pkt_getuint32(ssh);
+    s->supported_ciphers_mask = ssh_pkt_getuint32(ssh);
+    s->supported_auths_mask = ssh_pkt_getuint32(ssh);
 
     ssh->v1_local_protoflags =
        ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
@@ -2271,15 +2463,24 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     MD5Init(&md5c);
     MD5Update(&md5c, s->keystr2, hostkey.bytes);
     MD5Update(&md5c, s->keystr1, servkey.bytes);
-    MD5Update(&md5c, ssh->pktin.body, 8);
+    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 = smalloc(s->len);
+    s->rsabuf = snewn(s->len, unsigned char);
     if (!s->rsabuf)
        fatalbox("Out of memory");
 
@@ -2292,7 +2493,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
         */
        int len = rsastr_len(&hostkey);
        char fingerprint[100];
-       char *keystr = smalloc(len);
+       char *keystr = snewn(len, char);
        if (!keystr)
            fatalbox("Out of memory");
        rsastr_fmt(keystr, &hostkey);
@@ -2310,11 +2511,17 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     }
 
     if (hostkey.bytes > servkey.bytes) {
-       rsaencrypt(s->rsabuf, 32, &servkey);
-       rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
+       ret = rsaencrypt(s->rsabuf, 32, &servkey);
+       if (ret)
+           ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
     } else {
-       rsaencrypt(s->rsabuf, 32, &hostkey);
-       rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
+       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");
@@ -2346,12 +2553,12 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        }
        if (!cipher_chosen) {
            if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
-               bombout((ssh,"Server violates SSH 1 protocol by not "
+               bombout(("Server violates SSH 1 protocol by not "
                         "supporting 3DES encryption"));
            else
                /* shouldn't happen */
-               bombout((ssh,"No supported ciphers found"));
-           crReturn(0);
+               bombout(("No supported ciphers found"));
+           crStop(0);
        }
 
        /* Warn about chosen cipher if necessary. */
@@ -2392,11 +2599,27 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     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(ispkt);
 
     if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
-       bombout((ssh,"Encryption not successfully enabled"));
-       crReturn(0);
+       bombout(("Encryption not successfully enabled"));
+       crStop(0);
     }
 
     logevent("Successfully started encryption");
@@ -2412,8 +2635,8 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                     * Terminate.
                     */
                    logevent("No username provided. Abandoning session.");
-                   ssh->state = SSH_STATE_CLOSED;
-                   crReturn(1);
+                    ssh_closing((Plug)ssh, NULL, 0, 0);
+                   crStop(1);
                }
            } else {
                int ret;               /* need not be kept over crReturn */
@@ -2457,9 +2680,9 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     }
     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 (*ssh->cfg.keyfile) {
-       if (!rsakey_pubblob(ssh->cfg.keyfile,
-                           &s->publickey_blob, &s->publickey_bloblen))
+    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;
@@ -2480,7 +2703,19 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            /* 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);
+           if (!agent_query(s->request, 5, &r, &s->responselen,
+                            ssh_agent_callback, ssh)) {
+               do {
+                   crReturn(0);
+                   if (ispkt) {
+                       bombout(("Unexpected data from server while waiting"
+                                " for agent response"));
+                       crStop(0);
+                   }
+               } while (ispkt || 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) {
@@ -2505,12 +2740,37 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        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 = (char *)s->p;
-                   s->p += s->commentlen;
+                   {
+                       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(ispkt);
@@ -2519,7 +2779,11 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        continue;
                    }
                    logevent("Received RSA challenge");
-                   ssh1_read_bignum(ssh->pktin.body, &s->challenge);
+                   if ((s->challenge = ssh1_pkt_getmp(ssh)) == NULL) {
+                       bombout(("Server's RSA challenge was badly formatted"));
+                       crStop(0);
+                   }
+
                    {
                        char *agentreq, *q, *ret;
                        void *vret;
@@ -2530,7 +2794,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        len += ssh1_bignum_length(s->challenge);
                        len += 16;     /* session id */
                        len += 4;      /* response format */
-                       agentreq = smalloc(4 + len);
+                       agentreq = snewn(4 + len, char);
                        PUT_32BIT(agentreq, len);
                        q = agentreq + 4;
                        *q++ = SSH1_AGENTC_RSA_CHALLENGE;
@@ -2542,9 +2806,23 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        memcpy(q, s->session_id, 16);
                        q += 16;
                        PUT_32BIT(q, 1);        /* response format */
-                       agent_query(agentreq, len + 4, &vret, &retlen);
+                       if (!agent_query(agentreq, len + 4, &vret, &retlen,
+                                        ssh_agent_callback, ssh)) {
+                           sfree(agentreq);
+                           do {
+                               crReturn(0);
+                               if (ispkt) {
+                                   bombout(("Unexpected data from server"
+                                            " while waiting for agent"
+                                            " response"));
+                                   crStop(0);
+                               }
+                           } while (ispkt || inlen > 0);
+                           vret = ssh->agent_response;
+                           retlen = ssh->agent_response_len;
+                       } else
+                           sfree(agentreq);
                        ret = vret;
-                       sfree(agentreq);
                        if (ret) {
                            if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
                                logevent("Sending Pageant's response");
@@ -2582,11 +2860,12 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    if (s->authed)
                        break;
                }
+               sfree(s->response);
            }
            if (s->authed)
                break;
        }
-       if (*ssh->cfg.keyfile && !s->tried_publickey)
+       if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
            s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
 
        if (ssh->cfg.try_tis_auth &&
@@ -2603,11 +2882,18 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                s->tis_auth_refused = 1;
                continue;
            } else {
-               int challengelen = GET_32BIT(ssh->pktin.body);
+               char *challenge;
+               int challengelen;
+
+               ssh_pkt_getstring(ssh, &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, ssh->pktin.body + 4, challengelen);
+               memcpy(s->prompt, challenge, challengelen);
                /* Prompt heuristic comes from OpenSSH */
                strncpy(s->prompt + challengelen,
                        memchr(s->prompt, '\n', challengelen) ?
@@ -2629,11 +2915,18 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                s->ccard_auth_refused = 1;
                continue;
            } else {
-               int challengelen = GET_32BIT(ssh->pktin.body);
+               char *challenge;
+               int challengelen;
+
+               ssh_pkt_getstring(ssh, &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, ssh->pktin.body + 4, challengelen);
+               memcpy(s->prompt, challenge, challengelen);
                strncpy(s->prompt + challengelen,
                        memchr(s->prompt, '\n', challengelen) ?
                        "" : "\r\nResponse: ",
@@ -2651,8 +2944,9 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            char msgbuf[256];
            if (flags & FLAG_VERBOSE)
                c_write_str(ssh, "Trying public key authentication.\r\n");
-           logeventf(ssh, "Trying public key \"%s\"", ssh->cfg.keyfile);
-           type = key_type(ssh->cfg.keyfile);
+           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));
@@ -2662,7 +2956,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                s->tried_publickey = 1;
                continue;
            }
-           if (!rsakey_encrypted(ssh->cfg.keyfile, &comment)) {
+           if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
                if (flags & FLAG_VERBOSE)
                    c_write_str(ssh, "No passphrase required.\r\n");
                goto tryauth;
@@ -2689,8 +2983,8 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                            PKT_END);
                logevent("Unable to authenticate");
                connection_fatal(ssh->frontend, "Unable to authenticate");
-               ssh->state = SSH_STATE_CLOSED;
-               crReturn(1);
+                ssh_closing((Plug)ssh, NULL, 0, 0);
+               crStop(1);
            }
        } else {
            /* Prompt may have come from server. We've munged it a bit, so
@@ -2718,11 +3012,15 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            s->tried_publickey = 1;
            
            {
-               int ret = loadrsakey(ssh->cfg.keyfile, &s->key, s->password);
+               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, ssh->cfg.keyfile);
-                   c_write_str(ssh, ".\r\n");
+                   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) {
@@ -2744,8 +3042,8 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                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);
+               bombout(("Bizarre response to offer of public key"));
+               crStop(0);
            }
 
            {
@@ -2753,7 +3051,10 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                unsigned char buffer[32];
                Bignum challenge, response;
 
-               ssh1_read_bignum(ssh->pktin.body, &challenge);
+               if ((challenge = ssh1_pkt_getmp(ssh)) == NULL) {
+                   bombout(("Server's RSA challenge was badly formatted"));
+                   crStop(0);
+               }
                response = rsadecrypt(challenge, &s->key);
                freebn(s->key.private_exponent);/* burn the evidence */
 
@@ -2780,8 +3081,8 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                                " 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);
+               bombout(("Bizarre response to RSA authentication response"));
+               crStop(0);
            }
 
            break;                     /* we're through! */
@@ -2844,7 +3145,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
                    assert(pwlen >= bottom && pwlen <= top);
 
-                   randomstr = smalloc(top + 1);
+                   randomstr = snewn(top + 1, char);
 
                    for (i = bottom; i <= top; i++) {
                        if (i == pwlen)
@@ -2863,6 +3164,7 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    }
                    logevent("Sending password with camouflage packets");
                    ssh_pkt_defersend(ssh);
+                   sfree(randomstr);
                } 
                else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
                    /*
@@ -2913,8 +3215,8 @@ static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                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);
+           bombout(("Strange packet received, type %d", ssh->pktin.type));
+           crStop(0);
        }
     }
 
@@ -2927,6 +3229,11 @@ void sshfwd_close(struct ssh_channel *c)
 {
     Ssh ssh = c->ssh;
 
+    if (ssh->state != SSH_STATE_SESSION) {
+       assert(ssh->state == SSH_STATE_CLOSED);
+       return;
+    }
+
     if (c && !c->closes) {
        /*
         * If the channel's remoteid is -1, we have sent
@@ -2961,6 +3268,11 @@ int sshfwd_write(struct ssh_channel *c, char *buf, int len)
 {
     Ssh ssh = c->ssh;
 
+    if (ssh->state != SSH_STATE_SESSION) {
+       assert(ssh->state == SSH_STATE_CLOSED);
+       return 0;
+    }
+
     if (ssh->version == 1) {
        send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
                    PKT_INT, c->remoteid,
@@ -2983,6 +3295,11 @@ void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
 {
     Ssh ssh = c->ssh;
 
+    if (ssh->state != SSH_STATE_SESSION) {
+       assert(ssh->state == SSH_STATE_CLOSED);
+       return;
+    }
+
     if (ssh->version == 1) {
        if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
            c->v.v1.throttling = 0;
@@ -3013,8 +3330,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (!ispkt);
        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-           bombout((ssh,"Protocol confusion"));
-           crReturnV;
+           bombout(("Protocol confusion"));
+           crStopV;
        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
            logevent("Agent forwarding refused");
        } else {
@@ -3043,8 +3360,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (!ispkt);
        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-           bombout((ssh,"Protocol confusion"));
-           crReturnV;
+           bombout(("Protocol confusion"));
+           crStopV;
        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
            logevent("X11 forwarding refused");
        } else {
@@ -3084,30 +3401,36 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                if (n < 255) 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 != ':') {
-               if (n < 255) host[n++] = *ssh->portfwd_strptr++;
-           }
-           host[n] = 0;
-           if (*ssh->portfwd_strptr == ':')
+           if (type != 'D') {
+               if (*ssh->portfwd_strptr == '\t')
+                   ssh->portfwd_strptr++;
+               n = 0;
+               while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
+                   if (n < 255) host[n++] = *ssh->portfwd_strptr++;
+               }
+               host[n] = 0;
+               if (*ssh->portfwd_strptr == ':')
+                   ssh->portfwd_strptr++;
+               n = 0;
+               while (*ssh->portfwd_strptr) {
+                   if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
+               }
+               dports[n] = 0;
                ssh->portfwd_strptr++;
-           n = 0;
-           while (*ssh->portfwd_strptr) {
-               if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
-           }
-           dports[n] = 0;
-           ssh->portfwd_strptr++;
-           dport = atoi(dports);
-           dserv = 0;
-           if (dport == 0) {
-               dserv = 1;
-               dport = net_service_lookup(dports);
-               if (!dport) {
-                   logeventf(ssh, "Service lookup failed for"
-                             " destination port \"%s\"", dports);
+               dport = atoi(dports);
+               dserv = 0;
+               if (dport == 0) {
+                   dserv = 1;
+                   dport = net_service_lookup(dports);
+                   if (!dport) {
+                       logeventf(ssh, "Service lookup failed for"
+                                 " destination port \"%s\"", dports);
+                   }
                }
+           } else {
+               while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
+               dport = dserv = -1;
+               ssh->portfwd_strptr++; /* eat the NUL and move to next one */
            }
            sport = atoi(sports);
            sserv = 0;
@@ -3132,9 +3455,18 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                              host,
                              (int)(dserv ? strlen(dports) : 0), dports,
                              dserv, "(", dport, dserv, ")");
+               } else if (type == 'D') {
+                   pfd_addforward(NULL, -1, *saddr ? saddr : NULL,
+                                  sport, ssh, &ssh->cfg);
+                   logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
+                             " doing SOCKS dynamic forwarding",
+                             (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
+                             (int)(*saddr?1:0), ":",
+                             (int)(sserv ? strlen(sports) : 0), sports,
+                             sserv, "(", sport, sserv, ")");
                } else {
                    struct ssh_rportfwd *pf;
-                   pf = smalloc(sizeof(*pf));
+                   pf = snew(struct ssh_rportfwd);
                    strcpy(pf->dhost, host);
                    pf->dport = dport;
                    if (saddr) {
@@ -3165,8 +3497,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        } while (!ispkt);
                        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
                            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-                           bombout((ssh,"Protocol confusion"));
-                           crReturnV;
+                           bombout(("Protocol confusion"));
+                           crStopV;
                        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
                            c_write_str(ssh, "Server refused port"
                                        " forwarding\r\n");
@@ -3179,24 +3511,33 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     }
 
     if (!ssh->cfg.nopty) {
+       /* Unpick the terminal-speed string. */
+       /* XXX perhaps we should allow no speeds to be sent. */
+       ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
+       sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
+       /* Send the pty request. */
        send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
                    PKT_STR, ssh->cfg.termtype,
                    PKT_INT, ssh->term_height,
                    PKT_INT, ssh->term_width,
-                   PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
+                   PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
+                   PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
+                   PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
+                   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;
+           bombout(("Protocol confusion"));
+           crStopV;
        } 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");
+       logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
+                 ssh->ospeed, ssh->ispeed);
     } else {
        ssh->editing = ssh->echoing = 1;
     }
@@ -3208,8 +3549,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        } while (!ispkt);
        if (ssh->pktin.type != SSH1_SMSG_SUCCESS
            && ssh->pktin.type != SSH1_SMSG_FAILURE) {
-           bombout((ssh,"Protocol confusion"));
-           crReturnV;
+           bombout(("Protocol confusion"));
+           crStopV;
        } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
            c_write_str(ssh, "Server refused to compress\r\n");
        }
@@ -3257,45 +3598,53 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        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 =
+               char *string;
+               int stringlen, bufsize;
+
+               ssh_pkt_getstring(ssh, &string, &stringlen);
+               if (string == NULL) {
+                   bombout(("Incoming terminal data packet was badly formed"));
+                   crStopV;
+               }
+
+               bufsize =
                    from_backend(ssh->frontend,
                                 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
-                                (char *)(ssh->pktin.body) + 4, len);
+                                string, stringlen);
                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;
+                ssh_closing((Plug)ssh, NULL, 0, 0);
                logevent("Received disconnect request");
-               crReturnV;
+               crStopV;
            } 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;
+               int remoteid = ssh_pkt_getuint32(ssh);
 
                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);
+                               PKT_INT, remoteid, PKT_END);
                    logevent("Rejected X11 connect request");
                } else {
-                   c = smalloc(sizeof(struct ssh_channel));
+                   c = snew(struct ssh_channel);
                    c->ssh = ssh;
 
                    if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
                                 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
-                       logevent("opening X11 forward connection failed");
+                       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);
+                                   PKT_INT, remoteid, PKT_END);
                    } else {
                        logevent
-                           ("opening X11 forward connection succeeded");
-                       c->remoteid = GET_32BIT(ssh->pktin.body);
+                           ("Opening X11 forward connection succeeded");
+                       c->remoteid = remoteid;
                        c->localid = alloc_channel_id(ssh);
                        c->closes = 0;
                        c->v.v1.throttling = 0;
@@ -3311,15 +3660,16 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                /* Remote side is trying to open a channel to talk to our
                 * agent. Give them back a local channel number. */
                struct ssh_channel *c;
+               int remoteid = ssh_pkt_getuint32(ssh);
 
                /* 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);
+                               PKT_INT, remoteid, PKT_END);
                } else {
-                   c = smalloc(sizeof(struct ssh_channel));
+                   c = snew(struct ssh_channel);
                    c->ssh = ssh;
-                   c->remoteid = GET_32BIT(ssh->pktin.body);
+                   c->remoteid = remoteid;
                    c->localid = alloc_channel_id(ssh);
                    c->closes = 0;
                    c->v.v1.throttling = 0;
@@ -3335,46 +3685,44 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                 * forwarded port. Give them back a local channel number. */
                struct ssh_channel *c;
                struct ssh_rportfwd pf;
+               int remoteid;
                int hostsize, port;
-               char host[256], buf[1024];
-               char *p, *h, *e;
-               c = smalloc(sizeof(struct ssh_channel));
+               char *host, buf[1024];
+               const char *e;
+               c = snew(struct ssh_channel);
                c->ssh = ssh;
 
-               hostsize = GET_32BIT(ssh->pktin.body+4);
-               for (h = host, p = (char *)(ssh->pktin.body+8);
-                    hostsize != 0; hostsize--) {
-                   if (h+1 < host+sizeof(host))
-                       *h++ = *p;
-                   p++;
-               }
-               *h = 0;
-               port = GET_32BIT(p);
+               remoteid = ssh_pkt_getuint32(ssh);
+               ssh_pkt_getstring(ssh, &host, &hostsize);
+               port = ssh_pkt_getuint32(ssh);
 
-               strcpy(pf.dhost, host);
+               if (hostsize >= lenof(pf.dhost))
+                   hostsize = lenof(pf.dhost)-1;
+               memcpy(pf.dhost, host, hostsize);
+               pf.dhost[hostsize] = '\0';
                pf.dport = port;
 
                if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
                    sprintf(buf, "Rejected remote port open request for %s:%d",
-                           host, port);
+                           pf.dhost, port);
                    logevent(buf);
                     send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
-                                PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
+                                PKT_INT, remoteid, PKT_END);
                } else {
                    sprintf(buf, "Received remote port open request for %s:%d",
-                           host, port);
+                           pf.dhost, port);
                    logevent(buf);
-                   e = pfd_newconnect(&c->u.pfd.s, host, port, c, &ssh->cfg);
+                   e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
+                                      c, &ssh->cfg);
                    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);
+                                   PKT_INT, remoteid, PKT_END);
                    } else {
-                       c->remoteid = GET_32BIT(ssh->pktin.body);
+                       c->remoteid = remoteid;
                        c->localid = alloc_channel_id(ssh);
                        c->closes = 0;
                        c->v.v1.throttling = 0;
@@ -3388,8 +3736,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                }
 
            } 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);
+               unsigned int remoteid = ssh_pkt_getuint32(ssh);
+               unsigned int localid = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
 
                c = find234(ssh->channels, &remoteid, ssh_channelfind);
@@ -3412,7 +3760,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                }
 
            } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
-               unsigned int remoteid = GET_32BIT(ssh->pktin.body);
+               unsigned int remoteid = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
 
                c = find234(ssh->channels, &remoteid, ssh_channelfind);
@@ -3426,7 +3774,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            } 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);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (c && ((int)c->remoteid) != -1) {
@@ -3459,26 +3807,30 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        sfree(c);
                    }
                } else {
-                   bombout((ssh,"Received CHANNEL_CLOSE%s for %s channel %d\n",
+                   bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
                             ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
                             "_CONFIRMATION", c ? "half-open" : "nonexistent",
                             i));
+                   crStopV;
                }
            } 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;
+               int i = ssh_pkt_getuint32(ssh);
+               char *p;
+               int len;
                struct ssh_channel *c;
+
+               ssh_pkt_getstring(ssh, &p, &len);
+
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (c) {
-                   int bufsize;
+                   int bufsize = 0;
                    switch (c->type) {
                      case CHAN_X11:
-                       bufsize = x11_send(c->u.x11.s, (char *)p, len);
+                       bufsize = x11_send(c->u.x11.s, p, len);
                        break;
                      case CHAN_SOCKDATA:
-                       bufsize = pfd_send(c->u.pfd.s, (char *)p, len);
+                       bufsize = pfd_send(c->u.pfd.s, p, len);
                        break;
                      case CHAN_AGENT:
                        /* Data for an agent message. Buffer it. */
@@ -3494,7 +3846,8 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                            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);
+                               c->u.a.message = snewn(c->u.a.totallen,
+                                                      unsigned char);
                                memcpy(c->u.a.message, c->u.a.msglen, 4);
                            }
                            if (c->u.a.lensofar >= 4 && len > 0) {
@@ -3508,25 +3861,13 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                                c->u.a.lensofar += l;
                            }
                            if (c->u.a.lensofar == c->u.a.totallen) {
-                               void *reply, *sentreply;
+                               void *reply;
                                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);
+                               if (agent_query(c->u.a.message,
+                                               c->u.a.totallen,
+                                               &reply, &replylen,
+                                               ssh_agentf_callback, c))
+                                   ssh_agentf_callback(c, reply, replylen);
                                sfree(c->u.a.message);
                                c->u.a.lensofar = 0;
                            }
@@ -3546,7 +3887,7 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                 * 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);
+               ssh->exitcode = ssh_pkt_getuint32(ssh);
                sprintf(buf, "Server sent command exit status %d",
                        ssh->exitcode);
                logevent(buf);
@@ -3558,11 +3899,11 @@ static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                  * encrypted packet, we close the session once
                  * we've sent EXIT_CONFIRMATION.
                  */
-                ssh->state = SSH_STATE_CLOSED;
-                crReturnV;
+                ssh_closing((Plug)ssh, NULL, 0, 0);
+                crStopV;
            } else {
-               bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
-               crReturnV;
+               bombout(("Strange packet received: type %d", ssh->pktin.type));
+               crStopV;
            }
        } else {
            while (inlen > 0) {
@@ -3834,8 +4175,8 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        int i, j, len;
 
        if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
-           bombout((ssh,"expected key exchange packet from server"));
-           crReturn(0);
+           bombout(("expected key exchange packet from server"));
+           crStop(0);
        }
        ssh->kex = NULL;
        ssh->hostkey = NULL;
@@ -3846,7 +4187,7 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        s->cscomp_tobe = NULL;
        s->sccomp_tobe = NULL;
        ssh->pktin.savedpos += 16;              /* skip garbage cookie */
-       ssh2_pkt_getstring(ssh, &str, &len);    /* key exchange algorithms */
+       ssh_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))
@@ -3856,14 +4197,14 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                break;
            }
        }
-       ssh2_pkt_getstring(ssh, &str, &len);    /* host key algorithms */
+       ssh_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 */
+       ssh_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];
@@ -3884,12 +4225,12 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            }
        }
        if (!s->cscipher_tobe) {
-           bombout((ssh,"Couldn't agree a client-to-server cipher (available: %s)",
+           bombout(("Couldn't agree a client-to-server cipher (available: %s)",
                     str ? str : "(null)"));
-           crReturn(0);
+           crStop(0);
        }
 
-       ssh2_pkt_getstring(ssh, &str, &len);    /* server->client cipher */
+       ssh_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];
@@ -3910,26 +4251,26 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            }
        }
        if (!s->sccipher_tobe) {
-           bombout((ssh,"Couldn't agree a server-to-client cipher (available: %s)",
+           bombout(("Couldn't agree a server-to-client cipher (available: %s)",
                     str ? str : "(null)"));
-           crReturn(0);
+           crStop(0);
        }
 
-       ssh2_pkt_getstring(ssh, &str, &len);    /* client->server mac */
+       ssh_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 */
+       ssh_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 */
+       ssh_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];
@@ -3938,7 +4279,7 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                break;
            }
        }
-       ssh2_pkt_getstring(ssh, &str, &len);  /* server->client compression */
+       ssh_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];
@@ -3984,8 +4325,8 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
        crWaitUntil(ispkt);
        if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
-           bombout((ssh,"expected key exchange group packet from server"));
-           crReturn(0);
+           bombout(("expected key exchange group packet from server"));
+           crStop(0);
        }
        s->p = ssh2_pkt_getmp(ssh);
        s->g = ssh2_pkt_getmp(ssh);
@@ -4010,12 +4351,12 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
     crWaitUntil(ispkt);
     if (ssh->pktin.type != s->kex_reply_value) {
-       bombout((ssh,"expected key exchange reply packet from server"));
-       crReturn(0);
+       bombout(("expected key exchange reply packet from server"));
+       crStop(0);
     }
-    ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
+    ssh_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
     s->f = ssh2_pkt_getmp(ssh);
-    ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
+    ssh_pkt_getstring(ssh, &s->sigdata, &s->siglen);
 
     s->K = dh_find_K(ssh->kex_ctx, s->f);
 
@@ -4042,8 +4383,8 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     if (!s->hkey ||
        !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
                                 (char *)s->exchange_hash, 20)) {
-       bombout((ssh,"Server's host key did not match the signature supplied"));
-       crReturn(0);
+       bombout(("Server's host key did not match the signature supplied"));
+       crStop(0);
     }
 
     /*
@@ -4074,8 +4415,8 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
      */
     crWaitUntil(ispkt);
     if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
-       bombout((ssh,"expected new-keys packet from server"));
-       crReturn(0);
+       bombout(("expected new-keys packet from server"));
+       crStop(0);
     }
 
     /*
@@ -4143,6 +4484,12 @@ static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     if (ssh->sccomp->text_name)
        logeventf(ssh, "Initialised %s decompression",
                  ssh->sccomp->text_name);
+    freebn(s->f);
+    freebn(s->K);
+    if (ssh->kex == &ssh_diffiehellman_gex) {
+       freebn(s->g);
+       freebn(s->p);
+    }
 
     /*
      * If this is the first key exchange phase, we must pass the
@@ -4289,8 +4636,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     ssh2_pkt_send(ssh);
     crWaitUntilV(ispkt);
     if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
-       bombout((ssh,"Server refused user authentication protocol"));
-       crReturnV;
+       bombout(("Server refused user authentication protocol"));
+       crStopV;
     }
 
     /*
@@ -4338,8 +4685,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                     * Terminate.
                     */
                    logevent("No username provided. Abandoning session.");
-                   ssh->state = SSH_STATE_CLOSED;
-                   crReturnV;
+                    ssh_closing((Plug)ssh, NULL, 0, 0);
+                   crStopV;
                }
            } else {
                int ret;               /* need not be saved across crReturn */
@@ -4388,20 +4735,22 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        s->tried_keyb_inter = FALSE;
        s->kbd_inter_running = FALSE;
        /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
-       if (*ssh->cfg.keyfile) {
+       if (!filename_is_null(ssh->cfg.keyfile)) {
            int keytype;
-           logeventf(ssh, "Reading private key file \"%.150s\"", ssh->cfg.keyfile);
-           keytype = key_type(ssh->cfg.keyfile);
+           logeventf(ssh, "Reading private key file \"%.150s\"",
+                     filename_to_str(&ssh->cfg.keyfile));
+           keytype = key_type(&ssh->cfg.keyfile);
            if (keytype == SSH_KEYTYPE_SSH2) {
                s->publickey_blob =
-                   ssh2_userkey_loadpub(ssh->cfg.keyfile, NULL,
-                                        &s->publickey_bloblen);
+                   ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
+                                        &s->publickey_bloblen, NULL);
            } else {
                char *msgbuf;
                logeventf(ssh, "Unable to use this key file (%s)",
                          key_type_to_str(keytype));
                msgbuf = dupprintf("Unable to use key file \"%.150s\""
-                                  " (%s)\r\n", ssh->cfg.keyfile,
+                                  " (%s)\r\n",
+                                  filename_to_str(&ssh->cfg.keyfile),
                                   key_type_to_str(keytype));
                c_write_str(ssh, msgbuf);
                sfree(msgbuf);
@@ -4428,7 +4777,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                 * output of (say) plink.)
                 */
                if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
-                   ssh2_pkt_getstring(ssh, &banner, &size);
+                   ssh_pkt_getstring(ssh, &banner, &size);
                    if (banner)
                        c_write_untrusted(ssh, banner, size);
                }
@@ -4452,9 +4801,9 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                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",
+               bombout(("Strange packet received during authentication: type %d",
                         ssh->pktin.type));
-               crReturnV;
+               crStopV;
            }
 
            s->gotit = FALSE;
@@ -4467,7 +4816,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
            if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
                char *methods;
                int methlen;
-               ssh2_pkt_getstring(ssh, &methods, &methlen);
+               ssh_pkt_getstring(ssh, &methods, &methlen);
                s->kbd_inter_running = FALSE;
                if (!ssh2_pkt_getbool(ssh)) {
                    /*
@@ -4523,6 +4872,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
            s->method = 0;
            ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
+           s->need_pw = FALSE;
 
            /*
             * Most password/passphrase prompts will be
@@ -4550,7 +4900,19 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                /* 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);
+               if (!agent_query(s->request, 5, &r, &s->responselen,
+                                ssh_agent_callback, ssh)) {
+                   do {
+                       crReturnV;
+                       if (ispkt) {
+                           bombout(("Unexpected data from server while"
+                                    " waiting for agent response"));
+                           crStopV;
+                       }
+                   } while (ispkt || 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] == SSH2_AGENT_IDENTITIES_ANSWER) {
@@ -4626,11 +4988,13 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
 
                        s->siglen = ssh->pktout.length - 5 + 4 + 20;
+                        if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
+                            s->siglen -= 4;
                        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);
+                       s->agentreq = snewn(4 + s->len, char);
                        PUT_32BIT(s->agentreq, s->len);
                        s->q = s->agentreq + 4;
                        *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
@@ -4641,8 +5005,10 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        PUT_32BIT(s->q, s->siglen);
                        s->q += 4;
                        /* Now the data to be signed... */
-                       PUT_32BIT(s->q, 20);
-                       s->q += 4;
+                        if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
+                            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,
@@ -4650,7 +5016,21 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        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);
+                       if (!agent_query(s->agentreq, s->len + 4,
+                                        &vret, &s->retlen,
+                                        ssh_agent_callback, ssh)) {
+                           do {
+                               crReturnV;
+                               if (ispkt) {
+                                   bombout(("Unexpected data from server"
+                                            " while waiting for agent"
+                                            " response"));
+                                   crStopV;
+                               }
+                           } while (ispkt || inlen > 0);
+                           vret = ssh->agent_response;
+                           s->retlen = ssh->agent_response_len;
+                       }
                        s->ret = vret;
                        sfree(s->agentreq);
                        if (s->ret) {
@@ -4672,6 +5052,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    if (s->authed)
                        continue;
                }
+               sfree(s->response);
            }
 
            if (!s->method && s->can_pubkey && s->publickey_blob
@@ -4692,9 +5073,10 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                 * willing to accept it.
                 */
                pub_blob =
-                   (unsigned char *)ssh2_userkey_loadpub(ssh->cfg.keyfile,
+                   (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
                                                          &algorithm,
-                                                         &pub_blob_len);
+                                                         &pub_blob_len,
+                                                         NULL);
                if (pub_blob) {
                    ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
                    ssh2_pkt_addstring(ssh, s->username);
@@ -4720,7 +5102,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                     * Actually attempt a serious authentication using
                     * the key.
                     */
-                   if (ssh2_userkey_encrypted(ssh->cfg.keyfile, &comment)) {
+                   if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
                        sprintf(s->pwprompt,
                                "Passphrase for key \"%.100s\": ",
                                comment);
@@ -4728,9 +5110,11 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    } else {
                        s->need_pw = FALSE;
                    }
-                   c_write_str(ssh, "Authenticating with public key \"");
-                   c_write_str(ssh, comment);
-                   c_write_str(ssh, "\"\r\n");
+                   if (flags & FLAG_VERBOSE) {
+                       c_write_str(ssh, "Authenticating with public key \"");
+                       c_write_str(ssh, comment);
+                       c_write_str(ssh, "\"\r\n");
+                   }
                    s->method = AUTH_PUBLICKEY_FILE;
                }
            }
@@ -4781,9 +5165,9 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    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);
+                   ssh_pkt_getstring(ssh, &name, &name_len);
+                   ssh_pkt_getstring(ssh, &inst, &inst_len);
+                   ssh_pkt_getstring(ssh, &lang, &lang_len);
                    if (name_len > 0) {
                        c_write_untrusted(ssh, name, name_len);
                        c_write_str(ssh, "\r\n");
@@ -4792,7 +5176,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        c_write_untrusted(ssh, inst, inst_len);
                        c_write_str(ssh, "\r\n");
                    }
-                   s->num_prompts = ssh2_pkt_getuint32(ssh);
+                   s->num_prompts = ssh_pkt_getuint32(ssh);
                }
 
                /*
@@ -4803,7 +5187,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    char *prompt;
                    int prompt_len;
 
-                   ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
+                   ssh_pkt_getstring(ssh, &prompt, &prompt_len);
                    if (prompt_len > 0) {
                        strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
                        s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
@@ -4846,8 +5230,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        logevent("Unable to authenticate");
                        connection_fatal(ssh->frontend,
                                         "Unable to authenticate");
-                       ssh->state = SSH_STATE_CLOSED;
-                       crReturnV;
+                        ssh_closing((Plug)ssh, NULL, 0, 0);
+                       crStopV;
                    }
                } else {
                    int ret;           /* need not be saved across crReturn */
@@ -4871,14 +5255,18 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                 * We have our passphrase. Now try the actual authentication.
                 */
                struct ssh2_userkey *key;
+               const char *error = NULL;
 
-               key = ssh2_load_userkey(ssh->cfg.keyfile, s->password);
+               key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
+                                       &error);
                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");
+                       c_write_str(ssh, "Unable to load private key (");
+                       c_write_str(ssh, error);
+                       c_write_str(ssh, ")\r\n");
                        s->tried_pubkey_config = TRUE;
                    }
                    /* Send a spurious AUTH_NONE to return to the top. */
@@ -4891,6 +5279,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                } else {
                    unsigned char *pkblob, *sigblob, *sigdata;
                    int pkblob_len, sigblob_len, sigdata_len;
+                    int p;
 
                    /*
                     * We have loaded the private key and the server
@@ -4916,11 +5305,19 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                     * 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,
+                    if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
+                        sigdata_len -= 4;
+                   sigdata = snewn(sigdata_len, unsigned char);
+                    p = 0;
+                    if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
+                        PUT_32BIT(sigdata+p, 20);
+                        p += 4;
+                    }
+                   memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
+                   memcpy(sigdata+p, ssh->pktout.data + 5,
                           ssh->pktout.length - 5);
+                    p += ssh->pktout.length - 5;
+                    assert(p == sigdata_len);
                    sigblob = key->alg->sign(key->data, (char *)sigdata,
                                             sigdata_len, &sigblob_len);
                    ssh2_add_sigblob(ssh, pkblob, pkblob_len,
@@ -4931,6 +5328,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
 
                    ssh2_pkt_send(ssh);
                    s->type = AUTH_TYPE_PUBLICKEY;
+                   key->alg->freekey(key->data);
                }
            } else if (s->method == AUTH_PASSWORD) {
                /*
@@ -5026,8 +5424,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                                   " methods available");
                ssh2_pkt_addstring(ssh, "en");  /* language tag */
                ssh2_pkt_send(ssh);
-               ssh->state = SSH_STATE_CLOSED;
-               crReturnV;
+                ssh_closing((Plug)ssh, NULL, 0, 0);
+               crStopV;
            }
        }
     } while (!s->we_are_in);
@@ -5042,7 +5440,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
      * So now create a channel with a session in it.
      */
     ssh->channels = newtree234(ssh_channelcmp);
-    ssh->mainchan = smalloc(sizeof(struct ssh_channel));
+    ssh->mainchan = snew(struct ssh_channel);
     ssh->mainchan->ssh = ssh;
     ssh->mainchan->localid = alloc_channel_id(ssh);
     ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
@@ -5054,19 +5452,19 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
     ssh2_pkt_send(ssh);
     crWaitUntilV(ispkt);
     if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
-       bombout((ssh,"Server refused to open a session"));
-       crReturnV;
+       bombout(("Server refused to open a session"));
+       crStopV;
        /* FIXME: error data comes back in FAILURE packet */
     }
-    if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
-       bombout((ssh,"Server's channel confirmation cited wrong channel"));
-       crReturnV;
+    if (ssh_pkt_getuint32(ssh) != ssh->mainchan->localid) {
+       bombout(("Server's channel confirmation cited wrong channel"));
+       crStopV;
     }
-    ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
+    ssh->mainchan->remoteid = ssh_pkt_getuint32(ssh);
     ssh->mainchan->type = CHAN_MAINSESSION;
     ssh->mainchan->closes = 0;
-    ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
-    ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
+    ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(ssh);
+    ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(ssh);
     bufchain_init(&ssh->mainchan->v.v2.outbuffer);
     add234(ssh->channels, ssh->mainchan);
     logevent("Opened channel for session");
@@ -5093,20 +5491,20 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        do {
            crWaitUntilV(ispkt);
            if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c)
                    continue;          /* nonexistent channel */
-               c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
+               c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
            }
        } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
 
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout((ssh,"Unexpected response to X11 forwarding request:"
+               bombout(("Unexpected response to X11 forwarding request:"
                         " packet type %d", ssh->pktin.type));
-               crReturnV;
+               crStopV;
            }
            logevent("X11 forwarding refused");
        } else {
@@ -5149,30 +5547,36 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                if (n < 255) 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 != ':') {
-               if (n < 255) host[n++] = *ssh->portfwd_strptr++;
-           }
-           host[n] = 0;
-           if (*ssh->portfwd_strptr == ':')
+           if (type != 'D') {
+               if (*ssh->portfwd_strptr == '\t')
+                   ssh->portfwd_strptr++;
+               n = 0;
+               while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
+                   if (n < 255) host[n++] = *ssh->portfwd_strptr++;
+               }
+               host[n] = 0;
+               if (*ssh->portfwd_strptr == ':')
+                   ssh->portfwd_strptr++;
+               n = 0;
+               while (*ssh->portfwd_strptr) {
+                   if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
+               }
+               dports[n] = 0;
                ssh->portfwd_strptr++;
-           n = 0;
-           while (*ssh->portfwd_strptr) {
-               if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
-           }
-           dports[n] = 0;
-           ssh->portfwd_strptr++;
-           dport = atoi(dports);
-           dserv = 0;
-           if (dport == 0) {
-               dserv = 1;
-               dport = net_service_lookup(dports);
-               if (!dport) {
-                   logeventf(ssh, "Service lookup failed for destination"
-                             " port \"%s\"", dports);
+               dport = atoi(dports);
+               dserv = 0;
+               if (dport == 0) {
+                   dserv = 1;
+                   dport = net_service_lookup(dports);
+                   if (!dport) {
+                       logeventf(ssh, "Service lookup failed for destination"
+                                 " port \"%s\"", dports);
+                   }
                }
+           } else {
+               while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
+               dport = dserv = -1;
+               ssh->portfwd_strptr++; /* eat the NUL and move to next one */
            }
            sport = atoi(sports);
            sserv = 0;
@@ -5197,9 +5601,18 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                              host,
                              (int)(dserv ? strlen(dports) : 0), dports,
                              dserv, "(", dport, dserv, ")");
+               } else if (type == 'D') {
+                   pfd_addforward(NULL, -1, *saddr ? saddr : NULL,
+                                  sport, ssh, &ssh->cfg);
+                   logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
+                             " doing SOCKS dynamic forwarding",
+                             (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
+                             (int)(*saddr?1:0), ":",
+                             (int)(sserv ? strlen(sports) : 0), sports,
+                             sserv, "(", sport, sserv, ")");
                } else {
                    struct ssh_rportfwd *pf;
-                   pf = smalloc(sizeof(*pf));
+                   pf = snew(struct ssh_rportfwd);
                    strcpy(pf->dhost, host);
                    pf->dport = dport;
                    pf->sport = sport;
@@ -5234,21 +5647,21 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        do {
                            crWaitUntilV(ispkt);
                            if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-                               unsigned i = ssh2_pkt_getuint32(ssh);
+                               unsigned i = ssh_pkt_getuint32(ssh);
                                struct ssh_channel *c;
                                c = find234(ssh->channels, &i, ssh_channelfind);
                                if (!c)
                                    continue;/* nonexistent channel */
-                               c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
+                               c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
                            }
                        } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
 
                        if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
                            if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
-                               bombout((ssh,"Unexpected response to port "
+                               bombout(("Unexpected response to port "
                                         "forwarding request: packet type %d",
                                         ssh->pktin.type));
-                               crReturnV;
+                               crStopV;
                            }
                            logevent("Server refused this port forwarding");
                        } else {
@@ -5274,20 +5687,20 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        do {
            crWaitUntilV(ispkt);
            if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c)
                    continue;          /* nonexistent channel */
-               c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
+               c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
            }
        } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
 
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout((ssh,"Unexpected response to agent forwarding request:"
+               bombout(("Unexpected response to agent forwarding request:"
                         " packet type %d", ssh->pktin.type));
-               crReturnV;
+               crStopV;
            }
            logevent("Agent forwarding refused");
        } else {
@@ -5300,6 +5713,11 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
      * Now allocate a pty for the session.
      */
     if (!ssh->cfg.nopty) {
+       /* Unpick the terminal-speed string. */
+       /* XXX perhaps we should allow no speeds to be sent. */
+        ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
+       sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
+       /* Build the pty request. */
        ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
        ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);       /* recipient channel */
        ssh2_pkt_addstring(ssh, "pty-req");
@@ -5310,32 +5728,37 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        ssh2_pkt_adduint32(ssh, 0);            /* pixel width */
        ssh2_pkt_adduint32(ssh, 0);            /* pixel height */
        ssh2_pkt_addstring_start(ssh);
-       ssh2_pkt_addstring_data(ssh, "\0", 1);  /* TTY_OP_END, no special options */
+       ssh2_pkt_addbyte(ssh, 128);            /* TTY_OP_ISPEED */
+       ssh2_pkt_adduint32(ssh, ssh->ispeed);
+       ssh2_pkt_addbyte(ssh, 129);            /* TTY_OP_OSPEED */
+       ssh2_pkt_adduint32(ssh, ssh->ospeed);
+       ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END */
        ssh2_pkt_send(ssh);
        ssh->state = SSH_STATE_INTERMED;
 
        do {
            crWaitUntilV(ispkt);
            if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c)
                    continue;          /* nonexistent channel */
-               c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
+               c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
            }
        } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
 
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout((ssh,"Unexpected response to pty request:"
+               bombout(("Unexpected response to pty request:"
                         " packet type %d", ssh->pktin.type));
-               crReturnV;
+               crStopV;
            }
            c_write_str(ssh, "Server refused to allocate pty\r\n");
            ssh->editing = ssh->echoing = 1;
        } else {
-           logevent("Allocated pty");
+           logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
+                     ssh->ospeed, ssh->ispeed);
        }
     } else {
        ssh->editing = ssh->echoing = 1;
@@ -5376,19 +5799,19 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
        do {
            crWaitUntilV(ispkt);
            if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c)
                    continue;          /* nonexistent channel */
-               c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
+               c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
            }
        } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
        if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
            if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
-               bombout((ssh,"Unexpected response to shell/command request:"
+               bombout(("Unexpected response to shell/command request:"
                         " packet type %d", ssh->pktin.type));
-               crReturnV;
+               crStopV;
            }
            /*
             * We failed to start the command. If this is the
@@ -5401,8 +5824,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                ssh->fallback_cmd = TRUE;
                continue;
            }
-           bombout((ssh,"Server refused to start a shell/command"));
-           crReturnV;
+           bombout(("Server refused to start a shell/command"));
+           crStopV;
        } else {
            logevent("Started a shell/command");
        }
@@ -5429,17 +5852,17 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
                char *data;
                int length;
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c)
                    continue;          /* nonexistent channel */
                if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
-                   ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
+                   ssh_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
                    continue;          /* extended but not stderr */
-               ssh2_pkt_getstring(ssh, &data, &length);
+               ssh_pkt_getstring(ssh, &data, &length);
                if (data) {
-                   int bufsize;
+                   int bufsize = 0;
                    c->v.v2.locwindow -= length;
                    switch (c->type) {
                      case CHAN_MAINSESSION:
@@ -5467,7 +5890,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                            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);
+                               c->u.a.message = snewn(c->u.a.totallen,
+                                                      unsigned char);
                                memcpy(c->u.a.message, c->u.a.msglen, 4);
                            }
                            if (c->u.a.lensofar >= 4 && length > 0) {
@@ -5481,22 +5905,13 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                                c->u.a.lensofar += l;
                            }
                            if (c->u.a.lensofar == c->u.a.totallen) {
-                               void *reply, *sentreply;
+                               void *reply;
                                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;
-                               }
-                               ssh2_add_channel_data(c, sentreply, replylen);
-                               s->try_send = TRUE;
-                               if (reply)
-                                   sfree(reply);
+                               if (agent_query(c->u.a.message,
+                                               c->u.a.totallen,
+                                               &reply, &replylen,
+                                               ssh_agentf_callback, c))
+                                   ssh_agentf_callback(c, reply, replylen);
                                sfree(c->u.a.message);
                                c->u.a.lensofar = 0;
                            }
@@ -5512,7 +5927,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                        ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
                }
            } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
 
                c = find234(ssh->channels, &i, ssh_channelfind);
@@ -5533,13 +5948,14 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    sshfwd_close(c);
                }
            } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
 
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c || ((int)c->remoteid) == -1) {
-                   bombout((ssh,"Received CHANNEL_CLOSE for %s channel %d\n",
+                   bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
                             c ? "half-open" : "nonexistent", i));
+                   crStopV;
                }
                /* Do pre-close processing on the channel. */
                switch (c->type) {
@@ -5572,6 +5988,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                 * See if that was the last channel left open.
                 */
                if (count234(ssh->channels) == 0) {
+                   logevent("All channels closed. Disconnecting");
 #if 0
                     /*
                      * We used to send SSH_MSG_DISCONNECT here,
@@ -5584,37 +6001,36 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                      * this is more polite than sending a
                      * DISCONNECT. So now we don't.
                      */
-                   logevent("All channels closed. Disconnecting");
                    ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
                    ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
                    ssh2_pkt_addstring(ssh, "All open channels closed");
                    ssh2_pkt_addstring(ssh, "en");      /* language tag */
                    ssh2_pkt_send(ssh);
 #endif
-                   ssh->state = SSH_STATE_CLOSED;
-                   crReturnV;
+                    ssh_closing((Plug)ssh, NULL, 0, 0);
+                   crStopV;
                }
                continue;              /* remote sends close; ignore (FIXME) */
            } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c || c->closes)
                    continue;          /* nonexistent or closing channel */
-               c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
+               c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
                s->try_send = TRUE;
            } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c)
                    continue;          /* nonexistent channel */
                if (c->type != CHAN_SOCKDATA_DORMANT)
                    continue;          /* dunno why they're confirming this */
-               c->remoteid = ssh2_pkt_getuint32(ssh);
+               c->remoteid = ssh_pkt_getuint32(ssh);
                c->type = CHAN_SOCKDATA;
-               c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
-               c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
+               c->v.v2.remwindow = ssh_pkt_getuint32(ssh);
+               c->v.v2.remmaxpkt = ssh_pkt_getuint32(ssh);
                if (c->u.pfd.s)
                    pfd_confirm(c->u.pfd.s);
                if (c->closes) {
@@ -5629,7 +6045,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    ssh2_pkt_send(ssh);
                }
            } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
-               unsigned i = ssh2_pkt_getuint32(ssh);
+               unsigned i = ssh_pkt_getuint32(ssh);
                struct ssh_channel *c;
                c = find234(ssh->channels, &i, ssh_channelfind);
                if (!c)
@@ -5649,8 +6065,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                int typelen, want_reply;
                struct ssh_channel *c;
 
-               localid = ssh2_pkt_getuint32(ssh);
-               ssh2_pkt_getstring(ssh, &type, &typelen);
+               localid = ssh_pkt_getuint32(ssh);
+               ssh_pkt_getstring(ssh, &type, &typelen);
                want_reply = ssh2_pkt_getbool(ssh);
 
                /*
@@ -5668,9 +6084,9 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    ssh2_pkt_addstring(ssh, buf);
                    ssh2_pkt_addstring(ssh, "en");      /* language tag */
                    ssh2_pkt_send(ssh);
-                   connection_fatal("%s", buf);
-                   ssh->state = SSH_STATE_CLOSED;
-                   crReturnV;
+                   connection_fatal(ssh->frontend, "%s", buf);
+                    ssh_closing((Plug)ssh, NULL, 0, 0);
+                   crStopV;
                }
 
                /*
@@ -5682,7 +6098,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    c == ssh->mainchan) {
                    /* We recognise "exit-status" on the primary channel. */
                    char buf[100];
-                   ssh->exitcode = ssh2_pkt_getuint32(ssh);
+                   ssh->exitcode = ssh_pkt_getuint32(ssh);
                    sprintf(buf, "Server sent command exit status %d",
                            ssh->exitcode);
                    logevent(buf);
@@ -5708,7 +6124,7 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                char *type;
                int typelen, want_reply;
 
-               ssh2_pkt_getstring(ssh, &type, &typelen);
+               ssh_pkt_getstring(ssh, &type, &typelen);
                want_reply = ssh2_pkt_getbool(ssh);
 
                 /*
@@ -5726,29 +6142,31 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                int typelen;
                char *peeraddr;
                int peeraddrlen;
-               int port;
+               int peerport;
                char *error = NULL;
                struct ssh_channel *c;
                unsigned remid, winsize, pktsize;
-               ssh2_pkt_getstring(ssh, &type, &typelen);
-               c = smalloc(sizeof(struct ssh_channel));
+               ssh_pkt_getstring(ssh, &type, &typelen);
+               c = snew(struct ssh_channel);
                c->ssh = ssh;
 
-               remid = ssh2_pkt_getuint32(ssh);
-               winsize = ssh2_pkt_getuint32(ssh);
-               pktsize = ssh2_pkt_getuint32(ssh);
-               ssh2_pkt_getstring(ssh, &peeraddr, &peeraddrlen);
-               port = ssh2_pkt_getuint32(ssh);
+               remid = ssh_pkt_getuint32(ssh);
+               winsize = ssh_pkt_getuint32(ssh);
+               pktsize = ssh_pkt_getuint32(ssh);
 
                if (typelen == 3 && !memcmp(type, "x11", 3)) {
-                   char *addrstr = smalloc(peeraddrlen+1);
+                   char *addrstr;
+
+                    ssh_pkt_getstring(ssh, &peeraddr, &peeraddrlen);
+                   addrstr = snewn(peeraddrlen+1, char);
                    memcpy(addrstr, peeraddr, peeraddrlen);
                    peeraddr[peeraddrlen] = '\0';
+                    peerport = ssh_pkt_getuint32(ssh);
 
                    if (!ssh->X11_fwd_enabled)
                        error = "X11 forwarding is not enabled";
                    else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
-                                     ssh->x11auth, addrstr, port,
+                                     ssh->x11auth, addrstr, peerport,
                                      &ssh->cfg) != NULL) {
                        error = "Unable to open an X11 connection";
                    } else {
@@ -5761,14 +6179,18 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    struct ssh_rportfwd pf, *realpf;
                    char *dummy;
                    int dummylen;
-                   ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
-                   pf.sport = ssh2_pkt_getuint32(ssh);
+                   ssh_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
+                   pf.sport = ssh_pkt_getuint32(ssh);
+                    ssh_pkt_getstring(ssh, &peeraddr, &peeraddrlen);
+                    peerport = ssh_pkt_getuint32(ssh);
                    realpf = find234(ssh->rportfwds, &pf, NULL);
                    if (realpf == NULL) {
                        error = "Remote port is not recognised";
                    } else {
-                       char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
-                                                realpf->dport, c, &ssh->cfg);
+                       const char *e = pfd_newconnect(&c->u.pfd.s,
+                                                      realpf->dhost,
+                                                      realpf->dport, c,
+                                                      &ssh->cfg);
                        logeventf(ssh, "Received remote port open request"
                                  " for %s:%d", realpf->dhost, realpf->dport);
                        if (e != NULL) {
@@ -5816,8 +6238,8 @@ static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
                    ssh2_pkt_send(ssh);
                }
            } else {
-               bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
-               crReturnV;
+               bombout(("Strange packet received: type %d", ssh->pktin.type));
+               crStopV;
            }
        } else {
            /*
@@ -5877,15 +6299,17 @@ static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
  *
  * Returns an error message, or NULL on success.
  */
-static char *ssh_init(void *frontend_handle, void **backend_handle,
-                     Config *cfg,
-                     char *host, int port, char **realhost, int nodelay)
+static const char *ssh_init(void *frontend_handle, void **backend_handle,
+                           Config *cfg,
+                           char *host, int port, char **realhost, int nodelay,
+                           int keepalive)
 {
-    char *p;
+    const char *p;
     Ssh ssh;
 
-    ssh = smalloc(sizeof(*ssh));
+    ssh = snew(struct ssh_tag);
     ssh->cfg = *cfg;                  /* STRUCTURE COPY */
+    ssh->version = 0;                 /* when not ready yet */
     ssh->s = NULL;
     ssh->cipher = NULL;
     ssh->v1_cipher_ctx = NULL;
@@ -5962,7 +6386,7 @@ static char *ssh_init(void *frontend_handle, void **backend_handle,
 
     ssh->protocol = NULL;
 
-    p = connect_to_host(ssh, host, port, realhost, nodelay);
+    p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
     if (p != NULL)
        return p;
 
@@ -5985,10 +6409,18 @@ static void ssh_free(void *handle)
        ssh->csmac->free_context(ssh->cs_mac_ctx);
     if (ssh->sc_mac_ctx)
        ssh->scmac->free_context(ssh->sc_mac_ctx);
-    if (ssh->cs_comp_ctx)
-       ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
-    if (ssh->sc_comp_ctx)
-       ssh->sccomp->compress_cleanup(ssh->sc_comp_ctx);
+    if (ssh->cs_comp_ctx) {
+       if (ssh->cscomp)
+           ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
+       else
+           zlib_compress_cleanup(ssh->cs_comp_ctx);
+    }
+    if (ssh->sc_comp_ctx) {
+       if (ssh->sccomp)
+           ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
+       else
+           zlib_decompress_cleanup(ssh->sc_comp_ctx);
+    }
     if (ssh->kex_ctx)
        dh_cleanup(ssh->kex_ctx);
     sfree(ssh->savedhost);
@@ -6022,9 +6454,24 @@ static void ssh_free(void *handle)
     sfree(ssh->do_ssh1_login_state);
     sfree(ssh->do_ssh2_transport_state);
     sfree(ssh->do_ssh2_authconn_state);
-    
+    if (ssh->pktout.data) {
+       sfree(ssh->pktout.data);
+       ssh->pktout.data = NULL;
+    }
+    if (ssh->pktin.data) {
+       sfree(ssh->pktin.data);
+       ssh->pktin.data = NULL;
+    }
+    if (ssh->crcda_ctx) {
+       crcda_free_context(ssh->crcda_ctx);
+       ssh->crcda_ctx = NULL;
+    }
+    if (ssh->logctx) {
+       log_free(ssh->logctx);
+       ssh->logctx = NULL;
+    }
     if (ssh->s)
-       sk_close(ssh->s);
+       ssh_do_close(ssh);
     sfree(ssh);
 }
 
@@ -6132,6 +6579,31 @@ static void ssh_size(void *handle, int width, int height)
 }
 
 /*
+ * Return a list of the special codes that make sense in this
+ * protocol.
+ */
+static const struct telnet_special *ssh_get_specials(void *handle)
+{
+    Ssh ssh = (Ssh) handle;
+
+    if (ssh->version == 1) {
+       static const struct telnet_special ssh1_specials[] = {
+           {"IGNORE message", TS_NOP},
+           {NULL, 0}
+       };
+       return ssh1_specials;
+    } else if (ssh->version == 2) {
+       static const struct telnet_special ssh2_specials[] = {
+           {"Break", TS_BRK},
+           {"IGNORE message", TS_NOP},
+           {NULL, 0}
+       };
+       return ssh2_specials;
+    } else
+       return NULL;
+}
+
+/*
  * Send Telnet special codes. TS_EOF is useful for `plink', so you
  * can send an EOF and collect resulting output (e.g. `plink
  * hostname sort').
@@ -6158,7 +6630,7 @@ static void ssh_special(void *handle, Telnet_Special code)
            ssh2_pkt_send(ssh);
        }
        logevent("Sent EOF message");
-    } else if (code == TS_PING) {
+    } else if (code == TS_PING || code == TS_NOP) {
        if (ssh->state == SSH_STATE_CLOSED
            || ssh->state == SSH_STATE_PREPACKET) return;
        if (ssh->version == 1) {
@@ -6169,6 +6641,19 @@ static void ssh_special(void *handle, Telnet_Special code)
            ssh2_pkt_addstring_start(ssh);
            ssh2_pkt_send(ssh);
        }
+    } else if (code == TS_BRK) {
+       if (ssh->state == SSH_STATE_CLOSED
+           || ssh->state == SSH_STATE_PREPACKET) return;
+       if (ssh->version == 1) {
+           logevent("Unable to send BREAK signal in SSH1");
+       } else {
+           ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
+           ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
+           ssh2_pkt_addstring(ssh, "break");
+           ssh2_pkt_addbool(ssh, 0);
+           ssh2_pkt_adduint32(ssh, 0);   /* default break length */
+           ssh2_pkt_send(ssh);
+       }
     } else {
        /* do nothing */
     }
@@ -6178,7 +6663,7 @@ void *new_sock_channel(void *handle, Socket s)
 {
     Ssh ssh = (Ssh) handle;
     struct ssh_channel *c;
-    c = smalloc(sizeof(struct ssh_channel));
+    c = snew(struct ssh_channel);
     c->ssh = ssh;
 
     if (c) {
@@ -6284,7 +6769,10 @@ static void ssh_provide_logctx(void *handle, void *logctx)
 static int ssh_return_exitcode(void *handle)
 {
     Ssh ssh = (Ssh) handle;
-    return ssh->exitcode;
+    if (ssh->s != NULL)
+        return -1;
+    else
+        return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
 }
 
 /*
@@ -6306,6 +6794,7 @@ Backend ssh_backend = {
     ssh_sendbuffer,
     ssh_size,
     ssh_special,
+    ssh_get_specials,
     ssh_socket,
     ssh_return_exitcode,
     ssh_sendok,