]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Clean up elliptic curve selection and naming.
[PuTTY.git] / ssh.c
1 /*
2  * SSH backend.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <assert.h>
9 #include <limits.h>
10 #include <signal.h>
11
12 #include "putty.h"
13 #include "tree234.h"
14 #include "ssh.h"
15 #ifndef NO_GSSAPI
16 #include "sshgssc.h"
17 #include "sshgss.h"
18 #endif
19
20 #ifndef FALSE
21 #define FALSE 0
22 #endif
23 #ifndef TRUE
24 #define TRUE 1
25 #endif
26
27 /*
28  * Packet type contexts, so that ssh2_pkt_type can correctly decode
29  * the ambiguous type numbers back into the correct type strings.
30  */
31 typedef enum {
32     SSH2_PKTCTX_NOKEX,
33     SSH2_PKTCTX_DHGROUP,
34     SSH2_PKTCTX_DHGEX,
35     SSH2_PKTCTX_ECDHKEX,
36     SSH2_PKTCTX_RSAKEX
37 } Pkt_KCtx;
38 typedef enum {
39     SSH2_PKTCTX_NOAUTH,
40     SSH2_PKTCTX_PUBLICKEY,
41     SSH2_PKTCTX_PASSWORD,
42     SSH2_PKTCTX_GSSAPI,
43     SSH2_PKTCTX_KBDINTER
44 } Pkt_ACtx;
45
46 static const char *const ssh2_disconnect_reasons[] = {
47     NULL,
48     "host not allowed to connect",
49     "protocol error",
50     "key exchange failed",
51     "host authentication failed",
52     "MAC error",
53     "compression error",
54     "service not available",
55     "protocol version not supported",
56     "host key not verifiable",
57     "connection lost",
58     "by application",
59     "too many connections",
60     "auth cancelled by user",
61     "no more auth methods available",
62     "illegal user name",
63 };
64
65 /*
66  * Various remote-bug flags.
67  */
68 #define BUG_CHOKES_ON_SSH1_IGNORE                 1
69 #define BUG_SSH2_HMAC                             2
70 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD             4
71 #define BUG_CHOKES_ON_RSA                         8
72 #define BUG_SSH2_RSA_PADDING                     16
73 #define BUG_SSH2_DERIVEKEY                       32
74 #define BUG_SSH2_REKEY                           64
75 #define BUG_SSH2_PK_SESSIONID                   128
76 #define BUG_SSH2_MAXPKT                         256
77 #define BUG_CHOKES_ON_SSH2_IGNORE               512
78 #define BUG_CHOKES_ON_WINADJ                   1024
79 #define BUG_SENDS_LATE_REQUEST_REPLY           2048
80 #define BUG_SSH2_OLDGEX                        4096
81
82 #define DH_MIN_SIZE 1024
83 #define DH_MAX_SIZE 8192
84
85 /*
86  * Codes for terminal modes.
87  * Most of these are the same in SSH-1 and SSH-2.
88  * This list is derived from RFC 4254 and
89  * SSH-1 RFC-1.2.31.
90  */
91 static const struct {
92     const char* const mode;
93     int opcode;
94     enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
95 } ssh_ttymodes[] = {
96     /* "V" prefix discarded for special characters relative to SSH specs */
97     { "INTR",         1, TTY_OP_CHAR },
98     { "QUIT",         2, TTY_OP_CHAR },
99     { "ERASE",        3, TTY_OP_CHAR },
100     { "KILL",         4, TTY_OP_CHAR },
101     { "EOF",          5, TTY_OP_CHAR },
102     { "EOL",          6, TTY_OP_CHAR },
103     { "EOL2",         7, TTY_OP_CHAR },
104     { "START",        8, TTY_OP_CHAR },
105     { "STOP",         9, TTY_OP_CHAR },
106     { "SUSP",        10, TTY_OP_CHAR },
107     { "DSUSP",       11, TTY_OP_CHAR },
108     { "REPRINT",     12, TTY_OP_CHAR },
109     { "WERASE",      13, TTY_OP_CHAR },
110     { "LNEXT",       14, TTY_OP_CHAR },
111     { "FLUSH",       15, TTY_OP_CHAR },
112     { "SWTCH",       16, TTY_OP_CHAR },
113     { "STATUS",      17, TTY_OP_CHAR },
114     { "DISCARD",     18, TTY_OP_CHAR },
115     { "IGNPAR",      30, TTY_OP_BOOL },
116     { "PARMRK",      31, TTY_OP_BOOL },
117     { "INPCK",       32, TTY_OP_BOOL },
118     { "ISTRIP",      33, TTY_OP_BOOL },
119     { "INLCR",       34, TTY_OP_BOOL },
120     { "IGNCR",       35, TTY_OP_BOOL },
121     { "ICRNL",       36, TTY_OP_BOOL },
122     { "IUCLC",       37, TTY_OP_BOOL },
123     { "IXON",        38, TTY_OP_BOOL },
124     { "IXANY",       39, TTY_OP_BOOL },
125     { "IXOFF",       40, TTY_OP_BOOL },
126     { "IMAXBEL",     41, TTY_OP_BOOL },
127     { "ISIG",        50, TTY_OP_BOOL },
128     { "ICANON",      51, TTY_OP_BOOL },
129     { "XCASE",       52, TTY_OP_BOOL },
130     { "ECHO",        53, TTY_OP_BOOL },
131     { "ECHOE",       54, TTY_OP_BOOL },
132     { "ECHOK",       55, TTY_OP_BOOL },
133     { "ECHONL",      56, TTY_OP_BOOL },
134     { "NOFLSH",      57, TTY_OP_BOOL },
135     { "TOSTOP",      58, TTY_OP_BOOL },
136     { "IEXTEN",      59, TTY_OP_BOOL },
137     { "ECHOCTL",     60, TTY_OP_BOOL },
138     { "ECHOKE",      61, TTY_OP_BOOL },
139     { "PENDIN",      62, TTY_OP_BOOL }, /* XXX is this a real mode? */
140     { "OPOST",       70, TTY_OP_BOOL },
141     { "OLCUC",       71, TTY_OP_BOOL },
142     { "ONLCR",       72, TTY_OP_BOOL },
143     { "OCRNL",       73, TTY_OP_BOOL },
144     { "ONOCR",       74, TTY_OP_BOOL },
145     { "ONLRET",      75, TTY_OP_BOOL },
146     { "CS7",         90, TTY_OP_BOOL },
147     { "CS8",         91, TTY_OP_BOOL },
148     { "PARENB",      92, TTY_OP_BOOL },
149     { "PARODD",      93, TTY_OP_BOOL }
150 };
151
152 /* Miscellaneous other tty-related constants. */
153 #define SSH_TTY_OP_END            0
154 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
155 #define SSH1_TTY_OP_ISPEED      192
156 #define SSH1_TTY_OP_OSPEED      193
157 #define SSH2_TTY_OP_ISPEED      128
158 #define SSH2_TTY_OP_OSPEED      129
159
160 /* Helper functions for parsing tty-related config. */
161 static unsigned int ssh_tty_parse_specchar(char *s)
162 {
163     unsigned int ret;
164     if (*s) {
165         char *next = NULL;
166         ret = ctrlparse(s, &next);
167         if (!next) ret = s[0];
168     } else {
169         ret = 255; /* special value meaning "don't set" */
170     }
171     return ret;
172 }
173 static unsigned int ssh_tty_parse_boolean(char *s)
174 {
175     if (stricmp(s, "yes") == 0 ||
176         stricmp(s, "on") == 0 ||
177         stricmp(s, "true") == 0 ||
178         stricmp(s, "+") == 0)
179         return 1; /* true */
180     else if (stricmp(s, "no") == 0 ||
181              stricmp(s, "off") == 0 ||
182              stricmp(s, "false") == 0 ||
183              stricmp(s, "-") == 0)
184         return 0; /* false */
185     else
186         return (atoi(s) != 0);
187 }
188
189 #define translate(x) if (type == x) return #x
190 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
191 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
192 static char *ssh1_pkt_type(int type)
193 {
194     translate(SSH1_MSG_DISCONNECT);
195     translate(SSH1_SMSG_PUBLIC_KEY);
196     translate(SSH1_CMSG_SESSION_KEY);
197     translate(SSH1_CMSG_USER);
198     translate(SSH1_CMSG_AUTH_RSA);
199     translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
200     translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
201     translate(SSH1_CMSG_AUTH_PASSWORD);
202     translate(SSH1_CMSG_REQUEST_PTY);
203     translate(SSH1_CMSG_WINDOW_SIZE);
204     translate(SSH1_CMSG_EXEC_SHELL);
205     translate(SSH1_CMSG_EXEC_CMD);
206     translate(SSH1_SMSG_SUCCESS);
207     translate(SSH1_SMSG_FAILURE);
208     translate(SSH1_CMSG_STDIN_DATA);
209     translate(SSH1_SMSG_STDOUT_DATA);
210     translate(SSH1_SMSG_STDERR_DATA);
211     translate(SSH1_CMSG_EOF);
212     translate(SSH1_SMSG_EXIT_STATUS);
213     translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
214     translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
215     translate(SSH1_MSG_CHANNEL_DATA);
216     translate(SSH1_MSG_CHANNEL_CLOSE);
217     translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
218     translate(SSH1_SMSG_X11_OPEN);
219     translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
220     translate(SSH1_MSG_PORT_OPEN);
221     translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
222     translate(SSH1_SMSG_AGENT_OPEN);
223     translate(SSH1_MSG_IGNORE);
224     translate(SSH1_CMSG_EXIT_CONFIRMATION);
225     translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
226     translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
227     translate(SSH1_MSG_DEBUG);
228     translate(SSH1_CMSG_REQUEST_COMPRESSION);
229     translate(SSH1_CMSG_AUTH_TIS);
230     translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
231     translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
232     translate(SSH1_CMSG_AUTH_CCARD);
233     translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
234     translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
235     return "unknown";
236 }
237 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
238 {
239     translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
240     translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
241     translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
242     translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
243     translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
244     translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
245     translate(SSH2_MSG_DISCONNECT);
246     translate(SSH2_MSG_IGNORE);
247     translate(SSH2_MSG_UNIMPLEMENTED);
248     translate(SSH2_MSG_DEBUG);
249     translate(SSH2_MSG_SERVICE_REQUEST);
250     translate(SSH2_MSG_SERVICE_ACCEPT);
251     translate(SSH2_MSG_KEXINIT);
252     translate(SSH2_MSG_NEWKEYS);
253     translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
254     translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
255     translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
256     translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
257     translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
258     translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
259     translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
260     translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
261     translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
262     translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
263     translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
264     translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
265     translate(SSH2_MSG_USERAUTH_REQUEST);
266     translate(SSH2_MSG_USERAUTH_FAILURE);
267     translate(SSH2_MSG_USERAUTH_SUCCESS);
268     translate(SSH2_MSG_USERAUTH_BANNER);
269     translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
270     translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
271     translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
272     translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
273     translate(SSH2_MSG_GLOBAL_REQUEST);
274     translate(SSH2_MSG_REQUEST_SUCCESS);
275     translate(SSH2_MSG_REQUEST_FAILURE);
276     translate(SSH2_MSG_CHANNEL_OPEN);
277     translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
278     translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
279     translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
280     translate(SSH2_MSG_CHANNEL_DATA);
281     translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
282     translate(SSH2_MSG_CHANNEL_EOF);
283     translate(SSH2_MSG_CHANNEL_CLOSE);
284     translate(SSH2_MSG_CHANNEL_REQUEST);
285     translate(SSH2_MSG_CHANNEL_SUCCESS);
286     translate(SSH2_MSG_CHANNEL_FAILURE);
287     return "unknown";
288 }
289 #undef translate
290 #undef translatec
291
292 /* Enumeration values for fields in SSH-1 packets */
293 enum {
294     PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
295 };
296
297 /*
298  * Coroutine mechanics for the sillier bits of the code. If these
299  * macros look impenetrable to you, you might find it helpful to
300  * read
301  * 
302  *   http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
303  * 
304  * which explains the theory behind these macros.
305  * 
306  * In particular, if you are getting `case expression not constant'
307  * errors when building with MS Visual Studio, this is because MS's
308  * Edit and Continue debugging feature causes their compiler to
309  * violate ANSI C. To disable Edit and Continue debugging:
310  * 
311  *  - right-click ssh.c in the FileView
312  *  - click Settings
313  *  - select the C/C++ tab and the General category
314  *  - under `Debug info:', select anything _other_ than `Program
315  *    Database for Edit and Continue'.
316  */
317 #define crBegin(v)      { int *crLine = &v; switch(v) { case 0:;
318 #define crBeginState    crBegin(s->crLine)
319 #define crStateP(t, v)                          \
320     struct t *s;                                \
321     if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; }      \
322     s = (v);
323 #define crState(t)      crStateP(t, ssh->t)
324 #define crFinish(z)     } *crLine = 0; return (z); }
325 #define crFinishV       } *crLine = 0; return; }
326 #define crFinishFree(z) } sfree(s); return (z); }
327 #define crFinishFreeV   } sfree(s); return; }
328 #define crReturn(z)     \
329         do {\
330             *crLine =__LINE__; return (z); case __LINE__:;\
331         } while (0)
332 #define crReturnV       \
333         do {\
334             *crLine=__LINE__; return; case __LINE__:;\
335         } while (0)
336 #define crStop(z)       do{ *crLine = 0; return (z); }while(0)
337 #define crStopV         do{ *crLine = 0; return; }while(0)
338 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
339 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
340
341 struct Packet;
342
343 static struct Packet *ssh1_pkt_init(int pkt_type);
344 static struct Packet *ssh2_pkt_init(int pkt_type);
345 static void ssh_pkt_ensure(struct Packet *, int length);
346 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
347 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
348 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
349 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
350 static void ssh_pkt_addstring_start(struct Packet *);
351 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
352 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
353 static void ssh_pkt_addstring(struct Packet *, const char *data);
354 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
355 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
356 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
357 static int ssh2_pkt_construct(Ssh, struct Packet *);
358 static void ssh2_pkt_send(Ssh, struct Packet *);
359 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
360 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
361                          struct Packet *pktin);
362 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
363                              struct Packet *pktin);
364 static void ssh2_channel_check_close(struct ssh_channel *c);
365 static void ssh_channel_destroy(struct ssh_channel *c);
366
367 /*
368  * Buffer management constants. There are several of these for
369  * various different purposes:
370  * 
371  *  - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
372  *    on a local data stream before we throttle the whole SSH
373  *    connection (in SSH-1 only). Throttling the whole connection is
374  *    pretty drastic so we set this high in the hope it won't
375  *    happen very often.
376  * 
377  *  - SSH_MAX_BACKLOG is the amount of backlog that must build up
378  *    on the SSH connection itself before we defensively throttle
379  *    _all_ local data streams. This is pretty drastic too (though
380  *    thankfully unlikely in SSH-2 since the window mechanism should
381  *    ensure that the server never has any need to throttle its end
382  *    of the connection), so we set this high as well.
383  * 
384  *  - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
385  *    channels.
386  *
387  *  - OUR_V2_BIGWIN is the window size we advertise for the only
388  *    channel in a simple connection.  It must be <= INT_MAX.
389  *
390  *  - OUR_V2_MAXPKT is the official "maximum packet size" we send
391  *    to the remote side. This actually has nothing to do with the
392  *    size of the _packet_, but is instead a limit on the amount
393  *    of data we're willing to receive in a single SSH2 channel
394  *    data message.
395  *
396  *  - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
397  *    _packet_ we're prepared to cope with.  It must be a multiple
398  *    of the cipher block size, and must be at least 35000.
399  */
400
401 #define SSH1_BUFFER_LIMIT 32768
402 #define SSH_MAX_BACKLOG 32768
403 #define OUR_V2_WINSIZE 16384
404 #define OUR_V2_BIGWIN 0x7fffffff
405 #define OUR_V2_MAXPKT 0x4000UL
406 #define OUR_V2_PACKETLIMIT 0x9000UL
407
408 const static struct ssh_signkey *hostkey_algs[] = {
409     &ssh_ecdsa_ed25519,
410     &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
411     &ssh_rsa, &ssh_dss
412 };
413
414 const static struct ssh_mac *macs[] = {
415     &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
416 };
417 const static struct ssh_mac *buggymacs[] = {
418     &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
419 };
420
421 static void *ssh_comp_none_init(void)
422 {
423     return NULL;
424 }
425 static void ssh_comp_none_cleanup(void *handle)
426 {
427 }
428 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
429                                unsigned char **outblock, int *outlen)
430 {
431     return 0;
432 }
433 static int ssh_comp_none_disable(void *handle)
434 {
435     return 0;
436 }
437 const static struct ssh_compress ssh_comp_none = {
438     "none", NULL,
439     ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
440     ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
441     ssh_comp_none_disable, NULL
442 };
443 extern const struct ssh_compress ssh_zlib;
444 const static struct ssh_compress *compressions[] = {
445     &ssh_zlib, &ssh_comp_none
446 };
447
448 enum {                                 /* channel types */
449     CHAN_MAINSESSION,
450     CHAN_X11,
451     CHAN_AGENT,
452     CHAN_SOCKDATA,
453     CHAN_SOCKDATA_DORMANT,             /* one the remote hasn't confirmed */
454     /*
455      * CHAN_SHARING indicates a channel which is tracked here on
456      * behalf of a connection-sharing downstream. We do almost nothing
457      * with these channels ourselves: all messages relating to them
458      * get thrown straight to sshshare.c and passed on almost
459      * unmodified to downstream.
460      */
461     CHAN_SHARING,
462     /*
463      * CHAN_ZOMBIE is used to indicate a channel for which we've
464      * already destroyed the local data source: for instance, if a
465      * forwarded port experiences a socket error on the local side, we
466      * immediately destroy its local socket and turn the SSH channel
467      * into CHAN_ZOMBIE.
468      */
469     CHAN_ZOMBIE
470 };
471
472 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
473 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
474 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
475
476 /*
477  * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
478  * handlers.
479  */
480 struct outstanding_channel_request {
481     cchandler_fn_t handler;
482     void *ctx;
483     struct outstanding_channel_request *next;
484 };
485
486 /*
487  * 2-3-4 tree storing channels.
488  */
489 struct ssh_channel {
490     Ssh ssh;                           /* pointer back to main context */
491     unsigned remoteid, localid;
492     int type;
493     /* True if we opened this channel but server hasn't confirmed. */
494     int halfopen;
495     /*
496      * In SSH-1, this value contains four bits:
497      * 
498      *   1   We have sent SSH1_MSG_CHANNEL_CLOSE.
499      *   2   We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
500      *   4   We have received SSH1_MSG_CHANNEL_CLOSE.
501      *   8   We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
502      * 
503      * A channel is completely finished with when all four bits are set.
504      *
505      * In SSH-2, the four bits mean:
506      *
507      *   1   We have sent SSH2_MSG_CHANNEL_EOF.
508      *   2   We have sent SSH2_MSG_CHANNEL_CLOSE.
509      *   4   We have received SSH2_MSG_CHANNEL_EOF.
510      *   8   We have received SSH2_MSG_CHANNEL_CLOSE.
511      *
512      * A channel is completely finished with when we have both sent
513      * and received CLOSE.
514      *
515      * The symbolic constants below use the SSH-2 terminology, which
516      * is a bit confusing in SSH-1, but we have to use _something_.
517      */
518 #define CLOSES_SENT_EOF    1
519 #define CLOSES_SENT_CLOSE  2
520 #define CLOSES_RCVD_EOF    4
521 #define CLOSES_RCVD_CLOSE  8
522     int closes;
523
524     /*
525      * This flag indicates that an EOF is pending on the outgoing side
526      * of the channel: that is, wherever we're getting the data for
527      * this channel has sent us some data followed by EOF. We can't
528      * actually send the EOF until we've finished sending the data, so
529      * we set this flag instead to remind us to do so once our buffer
530      * is clear.
531      */
532     int pending_eof;
533
534     /*
535      * True if this channel is causing the underlying connection to be
536      * throttled.
537      */
538     int throttling_conn;
539     union {
540         struct ssh2_data_channel {
541             bufchain outbuffer;
542             unsigned remwindow, remmaxpkt;
543             /* locwindow is signed so we can cope with excess data. */
544             int locwindow, locmaxwin;
545             /*
546              * remlocwin is the amount of local window that we think
547              * the remote end had available to it after it sent the
548              * last data packet or window adjust ack.
549              */
550             int remlocwin;
551             /*
552              * These store the list of channel requests that haven't
553              * been acked.
554              */
555             struct outstanding_channel_request *chanreq_head, *chanreq_tail;
556             enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
557         } v2;
558     } v;
559     union {
560         struct ssh_agent_channel {
561             unsigned char *message;
562             unsigned char msglen[4];
563             unsigned lensofar, totallen;
564             int outstanding_requests;
565         } a;
566         struct ssh_x11_channel {
567             struct X11Connection *xconn;
568             int initial;
569         } x11;
570         struct ssh_pfd_channel {
571             struct PortForwarding *pf;
572         } pfd;
573         struct ssh_sharing_channel {
574             void *ctx;
575         } sharing;
576     } u;
577 };
578
579 /*
580  * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
581  * use this structure in different ways, reflecting SSH-2's
582  * altogether saner approach to port forwarding.
583  * 
584  * In SSH-1, you arrange a remote forwarding by sending the server
585  * the remote port number, and the local destination host:port.
586  * When a connection comes in, the server sends you back that
587  * host:port pair, and you connect to it. This is a ready-made
588  * security hole if you're not on the ball: a malicious server
589  * could send you back _any_ host:port pair, so if you trustingly
590  * connect to the address it gives you then you've just opened the
591  * entire inside of your corporate network just by connecting
592  * through it to a dodgy SSH server. Hence, we must store a list of
593  * host:port pairs we _are_ trying to forward to, and reject a
594  * connection request from the server if it's not in the list.
595  * 
596  * In SSH-2, each side of the connection minds its own business and
597  * doesn't send unnecessary information to the other. You arrange a
598  * remote forwarding by sending the server just the remote port
599  * number. When a connection comes in, the server tells you which
600  * of its ports was connected to; and _you_ have to remember what
601  * local host:port pair went with that port number.
602  * 
603  * Hence, in SSH-1 this structure is indexed by destination
604  * host:port pair, whereas in SSH-2 it is indexed by source port.
605  */
606 struct ssh_portfwd; /* forward declaration */
607
608 struct ssh_rportfwd {
609     unsigned sport, dport;
610     char *shost, *dhost;
611     char *sportdesc;
612     void *share_ctx;
613     struct ssh_portfwd *pfrec;
614 };
615
616 static void free_rportfwd(struct ssh_rportfwd *pf)
617 {
618     if (pf) {
619         sfree(pf->sportdesc);
620         sfree(pf->shost);
621         sfree(pf->dhost);
622         sfree(pf);
623     }
624 }
625
626 /*
627  * Separately to the rportfwd tree (which is for looking up port
628  * open requests from the server), a tree of _these_ structures is
629  * used to keep track of all the currently open port forwardings,
630  * so that we can reconfigure in mid-session if the user requests
631  * it.
632  */
633 struct ssh_portfwd {
634     enum { DESTROY, KEEP, CREATE } status;
635     int type;
636     unsigned sport, dport;
637     char *saddr, *daddr;
638     char *sserv, *dserv;
639     struct ssh_rportfwd *remote;
640     int addressfamily;
641     struct PortListener *local;
642 };
643 #define free_portfwd(pf) ( \
644     ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
645              sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
646
647 struct Packet {
648     long length;            /* length of packet: see below */
649     long forcepad;          /* SSH-2: force padding to at least this length */
650     int type;               /* only used for incoming packets */
651     unsigned long sequence; /* SSH-2 incoming sequence number */
652     unsigned char *data;    /* allocated storage */
653     unsigned char *body;    /* offset of payload within `data' */
654     long savedpos;          /* dual-purpose saved packet position: see below */
655     long maxlen;            /* amount of storage allocated for `data' */
656     long encrypted_len;     /* for SSH-2 total-size counting */
657
658     /*
659      * A note on the 'length' and 'savedpos' fields above.
660      *
661      * Incoming packets are set up so that pkt->length is measured
662      * relative to pkt->body, which itself points to a few bytes after
663      * pkt->data (skipping some uninteresting header fields including
664      * the packet type code). The ssh_pkt_get* functions all expect
665      * this setup, and they also use pkt->savedpos to indicate how far
666      * through the packet being decoded they've got - and that, too,
667      * is an offset from pkt->body rather than pkt->data.
668      *
669      * During construction of an outgoing packet, however, pkt->length
670      * is measured relative to the base pointer pkt->data, and
671      * pkt->body is not really used for anything until the packet is
672      * ready for sending. In this mode, pkt->savedpos is reused as a
673      * temporary variable by the addstring functions, which write out
674      * a string length field and then keep going back and updating it
675      * as more data is appended to the subsequent string data field;
676      * pkt->savedpos stores the offset (again relative to pkt->data)
677      * of the start of the string data field.
678      */
679
680     /* Extra metadata used in SSH packet logging mode, allowing us to
681      * log in the packet header line that the packet came from a
682      * connection-sharing downstream and what if anything unusual was
683      * done to it. The additional_log_text field is expected to be a
684      * static string - it will not be freed. */
685     unsigned downstream_id;
686     const char *additional_log_text;
687 };
688
689 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
690                           struct Packet *pktin);
691 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
692                           struct Packet *pktin);
693 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
694                                           struct Packet *pktin);
695 static void ssh1_protocol_setup(Ssh ssh);
696 static void ssh2_protocol_setup(Ssh ssh);
697 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
698 static void ssh_size(void *handle, int width, int height);
699 static void ssh_special(void *handle, Telnet_Special);
700 static int ssh2_try_send(struct ssh_channel *c);
701 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
702 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
703 static void ssh2_set_window(struct ssh_channel *c, int newwin);
704 static int ssh_sendbuffer(void *handle);
705 static int ssh_do_close(Ssh ssh, int notify_exit);
706 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
707 static int ssh2_pkt_getbool(struct Packet *pkt);
708 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
709 static void ssh2_timer(void *ctx, unsigned long now);
710 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
711                               struct Packet *pktin);
712 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
713
714 struct rdpkt1_state_tag {
715     long len, pad, biglen, to_read;
716     unsigned long realcrc, gotcrc;
717     unsigned char *p;
718     int i;
719     int chunk;
720     struct Packet *pktin;
721 };
722
723 struct rdpkt2_state_tag {
724     long len, pad, payload, packetlen, maclen;
725     int i;
726     int cipherblk;
727     unsigned long incoming_sequence;
728     struct Packet *pktin;
729 };
730
731 struct rdpkt2_bare_state_tag {
732     char length[4];
733     long packetlen;
734     int i;
735     unsigned long incoming_sequence;
736     struct Packet *pktin;
737 };
738
739 struct queued_handler;
740 struct queued_handler {
741     int msg1, msg2;
742     chandler_fn_t handler;
743     void *ctx;
744     struct queued_handler *next;
745 };
746
747 struct ssh_tag {
748     const struct plug_function_table *fn;
749     /* the above field _must_ be first in the structure */
750
751     char *v_c, *v_s;
752     void *exhash;
753
754     Socket s;
755
756     void *ldisc;
757     void *logctx;
758
759     unsigned char session_key[32];
760     int v1_compressing;
761     int v1_remote_protoflags;
762     int v1_local_protoflags;
763     int agentfwd_enabled;
764     int X11_fwd_enabled;
765     int remote_bugs;
766     const struct ssh_cipher *cipher;
767     void *v1_cipher_ctx;
768     void *crcda_ctx;
769     const struct ssh2_cipher *cscipher, *sccipher;
770     void *cs_cipher_ctx, *sc_cipher_ctx;
771     const struct ssh_mac *csmac, *scmac;
772     int csmac_etm, scmac_etm;
773     void *cs_mac_ctx, *sc_mac_ctx;
774     const struct ssh_compress *cscomp, *sccomp;
775     void *cs_comp_ctx, *sc_comp_ctx;
776     const struct ssh_kex *kex;
777     const struct ssh_signkey *hostkey;
778     char *hostkey_str; /* string representation, for easy checking in rekeys */
779     unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
780     int v2_session_id_len;
781     void *kex_ctx;
782
783     int bare_connection;
784     int attempting_connshare;
785     void *connshare;
786
787     char *savedhost;
788     int savedport;
789     int send_ok;
790     int echoing, editing;
791
792     void *frontend;
793
794     int ospeed, ispeed;                /* temporaries */
795     int term_width, term_height;
796
797     tree234 *channels;                 /* indexed by local id */
798     struct ssh_channel *mainchan;      /* primary session channel */
799     int ncmode;                        /* is primary channel direct-tcpip? */
800     int exitcode;
801     int close_expected;
802     int clean_exit;
803
804     tree234 *rportfwds, *portfwds;
805
806     enum {
807         SSH_STATE_PREPACKET,
808         SSH_STATE_BEFORE_SIZE,
809         SSH_STATE_INTERMED,
810         SSH_STATE_SESSION,
811         SSH_STATE_CLOSED
812     } state;
813
814     int size_needed, eof_needed;
815     int sent_console_eof;
816     int got_pty;           /* affects EOF behaviour on main channel */
817
818     struct Packet **queue;
819     int queuelen, queuesize;
820     int queueing;
821     unsigned char *deferred_send_data;
822     int deferred_len, deferred_size;
823
824     /*
825      * Gross hack: pscp will try to start SFTP but fall back to
826      * scp1 if that fails. This variable is the means by which
827      * scp.c can reach into the SSH code and find out which one it
828      * got.
829      */
830     int fallback_cmd;
831
832     bufchain banner;    /* accumulates banners during do_ssh2_authconn */
833
834     Pkt_KCtx pkt_kctx;
835     Pkt_ACtx pkt_actx;
836
837     struct X11Display *x11disp;
838     struct X11FakeAuth *x11auth;
839     tree234 *x11authtree;
840
841     int version;
842     int conn_throttle_count;
843     int overall_bufsize;
844     int throttled_all;
845     int v1_stdout_throttling;
846     unsigned long v2_outgoing_sequence;
847
848     int ssh1_rdpkt_crstate;
849     int ssh2_rdpkt_crstate;
850     int ssh2_bare_rdpkt_crstate;
851     int ssh_gotdata_crstate;
852     int do_ssh1_connection_crstate;
853
854     void *do_ssh_init_state;
855     void *do_ssh1_login_state;
856     void *do_ssh2_transport_state;
857     void *do_ssh2_authconn_state;
858     void *do_ssh_connection_init_state;
859
860     struct rdpkt1_state_tag rdpkt1_state;
861     struct rdpkt2_state_tag rdpkt2_state;
862     struct rdpkt2_bare_state_tag rdpkt2_bare_state;
863
864     /* SSH-1 and SSH-2 use this for different things, but both use it */
865     int protocol_initial_phase_done;
866
867     void (*protocol) (Ssh ssh, void *vin, int inlen,
868                       struct Packet *pkt);
869     struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
870     int (*do_ssh_init)(Ssh ssh, unsigned char c);
871
872     /*
873      * We maintain our own copy of a Conf structure here. That way,
874      * when we're passed a new one for reconfiguration, we can check
875      * the differences and potentially reconfigure port forwardings
876      * etc in mid-session.
877      */
878     Conf *conf;
879
880     /*
881      * Values cached out of conf so as to avoid the tree234 lookup
882      * cost every time they're used.
883      */
884     int logomitdata;
885
886     /*
887      * Dynamically allocated username string created during SSH
888      * login. Stored in here rather than in the coroutine state so
889      * that it'll be reliably freed if we shut down the SSH session
890      * at some unexpected moment.
891      */
892     char *username;
893
894     /*
895      * Used to transfer data back from async callbacks.
896      */
897     void *agent_response;
898     int agent_response_len;
899     int user_response;
900
901     /*
902      * The SSH connection can be set as `frozen', meaning we are
903      * not currently accepting incoming data from the network. This
904      * is slightly more serious than setting the _socket_ as
905      * frozen, because we may already have had data passed to us
906      * from the network which we need to delay processing until
907      * after the freeze is lifted, so we also need a bufchain to
908      * store that data.
909      */
910     int frozen;
911     bufchain queued_incoming_data;
912
913     /*
914      * Dispatch table for packet types that we may have to deal
915      * with at any time.
916      */
917     handler_fn_t packet_dispatch[256];
918
919     /*
920      * Queues of one-off handler functions for success/failure
921      * indications from a request.
922      */
923     struct queued_handler *qhead, *qtail;
924     handler_fn_t q_saved_handler1, q_saved_handler2;
925
926     /*
927      * This module deals with sending keepalives.
928      */
929     Pinger pinger;
930
931     /*
932      * Track incoming and outgoing data sizes and time, for
933      * size-based rekeys.
934      */
935     unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
936     unsigned long max_data_size;
937     int kex_in_progress;
938     unsigned long next_rekey, last_rekey;
939     char *deferred_rekey_reason;    /* points to STATIC string; don't free */
940
941     /*
942      * Fully qualified host name, which we need if doing GSSAPI.
943      */
944     char *fullhostname;
945
946 #ifndef NO_GSSAPI
947     /*
948      * GSSAPI libraries for this session.
949      */
950     struct ssh_gss_liblist *gsslibs;
951 #endif
952 };
953
954 #define logevent(s) logevent(ssh->frontend, s)
955
956 /* logevent, only printf-formatted. */
957 static void logeventf(Ssh ssh, const char *fmt, ...)
958 {
959     va_list ap;
960     char *buf;
961
962     va_start(ap, fmt);
963     buf = dupvprintf(fmt, ap);
964     va_end(ap);
965     logevent(buf);
966     sfree(buf);
967 }
968
969 static void bomb_out(Ssh ssh, char *text)
970 {
971     ssh_do_close(ssh, FALSE);
972     logevent(text);
973     connection_fatal(ssh->frontend, "%s", text);
974     sfree(text);
975 }
976
977 #define bombout(msg) bomb_out(ssh, dupprintf msg)
978
979 /* Helper function for common bits of parsing ttymodes. */
980 static void parse_ttymodes(Ssh ssh,
981                            void (*do_mode)(void *data, char *mode, char *val),
982                            void *data)
983 {
984     char *key, *val;
985
986     for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
987          val != NULL;
988          val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
989         /*
990          * val[0] is either 'V', indicating that an explicit value
991          * follows it, or 'A' indicating that we should pass the
992          * value through from the local environment via get_ttymode.
993          */
994         if (val[0] == 'A') {
995             val = get_ttymode(ssh->frontend, key);
996             if (val) {
997                 do_mode(data, key, val);
998                 sfree(val);
999             }
1000         } else
1001             do_mode(data, key, val + 1);               /* skip the 'V' */
1002     }
1003 }
1004
1005 static int ssh_channelcmp(void *av, void *bv)
1006 {
1007     struct ssh_channel *a = (struct ssh_channel *) av;
1008     struct ssh_channel *b = (struct ssh_channel *) bv;
1009     if (a->localid < b->localid)
1010         return -1;
1011     if (a->localid > b->localid)
1012         return +1;
1013     return 0;
1014 }
1015 static int ssh_channelfind(void *av, void *bv)
1016 {
1017     unsigned *a = (unsigned *) av;
1018     struct ssh_channel *b = (struct ssh_channel *) bv;
1019     if (*a < b->localid)
1020         return -1;
1021     if (*a > b->localid)
1022         return +1;
1023     return 0;
1024 }
1025
1026 static int ssh_rportcmp_ssh1(void *av, void *bv)
1027 {
1028     struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1029     struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1030     int i;
1031     if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1032         return i < 0 ? -1 : +1;
1033     if (a->dport > b->dport)
1034         return +1;
1035     if (a->dport < b->dport)
1036         return -1;
1037     return 0;
1038 }
1039
1040 static int ssh_rportcmp_ssh2(void *av, void *bv)
1041 {
1042     struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1043     struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1044     int i;
1045     if ( (i = strcmp(a->shost, b->shost)) != 0)
1046         return i < 0 ? -1 : +1;
1047     if (a->sport > b->sport)
1048         return +1;
1049     if (a->sport < b->sport)
1050         return -1;
1051     return 0;
1052 }
1053
1054 /*
1055  * Special form of strcmp which can cope with NULL inputs. NULL is
1056  * defined to sort before even the empty string.
1057  */
1058 static int nullstrcmp(const char *a, const char *b)
1059 {
1060     if (a == NULL && b == NULL)
1061         return 0;
1062     if (a == NULL)
1063         return -1;
1064     if (b == NULL)
1065         return +1;
1066     return strcmp(a, b);
1067 }
1068
1069 static int ssh_portcmp(void *av, void *bv)
1070 {
1071     struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1072     struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1073     int i;
1074     if (a->type > b->type)
1075         return +1;
1076     if (a->type < b->type)
1077         return -1;
1078     if (a->addressfamily > b->addressfamily)
1079         return +1;
1080     if (a->addressfamily < b->addressfamily)
1081         return -1;
1082     if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1083         return i < 0 ? -1 : +1;
1084     if (a->sport > b->sport)
1085         return +1;
1086     if (a->sport < b->sport)
1087         return -1;
1088     if (a->type != 'D') {
1089         if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1090             return i < 0 ? -1 : +1;
1091         if (a->dport > b->dport)
1092             return +1;
1093         if (a->dport < b->dport)
1094             return -1;
1095     }
1096     return 0;
1097 }
1098
1099 static int alloc_channel_id(Ssh ssh)
1100 {
1101     const unsigned CHANNEL_NUMBER_OFFSET = 256;
1102     unsigned low, high, mid;
1103     int tsize;
1104     struct ssh_channel *c;
1105
1106     /*
1107      * First-fit allocation of channel numbers: always pick the
1108      * lowest unused one. To do this, binary-search using the
1109      * counted B-tree to find the largest channel ID which is in a
1110      * contiguous sequence from the beginning. (Precisely
1111      * everything in that sequence must have ID equal to its tree
1112      * index plus CHANNEL_NUMBER_OFFSET.)
1113      */
1114     tsize = count234(ssh->channels);
1115
1116     low = -1;
1117     high = tsize;
1118     while (high - low > 1) {
1119         mid = (high + low) / 2;
1120         c = index234(ssh->channels, mid);
1121         if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1122             low = mid;                 /* this one is fine */
1123         else
1124             high = mid;                /* this one is past it */
1125     }
1126     /*
1127      * Now low points to either -1, or the tree index of the
1128      * largest ID in the initial sequence.
1129      */
1130     {
1131         unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1132         assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1133     }
1134     return low + 1 + CHANNEL_NUMBER_OFFSET;
1135 }
1136
1137 static void c_write_stderr(int trusted, const char *buf, int len)
1138 {
1139     int i;
1140     for (i = 0; i < len; i++)
1141         if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1142             fputc(buf[i], stderr);
1143 }
1144
1145 static void c_write(Ssh ssh, const char *buf, int len)
1146 {
1147     if (flags & FLAG_STDERR)
1148         c_write_stderr(1, buf, len);
1149     else
1150         from_backend(ssh->frontend, 1, buf, len);
1151 }
1152
1153 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1154 {
1155     if (flags & FLAG_STDERR)
1156         c_write_stderr(0, buf, len);
1157     else
1158         from_backend_untrusted(ssh->frontend, buf, len);
1159 }
1160
1161 static void c_write_str(Ssh ssh, const char *buf)
1162 {
1163     c_write(ssh, buf, strlen(buf));
1164 }
1165
1166 static void ssh_free_packet(struct Packet *pkt)
1167 {
1168     sfree(pkt->data);
1169     sfree(pkt);
1170 }
1171 static struct Packet *ssh_new_packet(void)
1172 {
1173     struct Packet *pkt = snew(struct Packet);
1174
1175     pkt->body = pkt->data = NULL;
1176     pkt->maxlen = 0;
1177
1178     return pkt;
1179 }
1180
1181 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1182 {
1183     int nblanks = 0;
1184     struct logblank_t blanks[4];
1185     char *str;
1186     int slen;
1187
1188     pkt->savedpos = 0;
1189
1190     if (ssh->logomitdata &&
1191         (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1192          pkt->type == SSH1_SMSG_STDERR_DATA ||
1193          pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1194         /* "Session data" packets - omit the data string. */
1195         if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1196             ssh_pkt_getuint32(pkt);    /* skip channel id */
1197         blanks[nblanks].offset = pkt->savedpos + 4;
1198         blanks[nblanks].type = PKTLOG_OMIT;
1199         ssh_pkt_getstring(pkt, &str, &slen);
1200         if (str) {
1201             blanks[nblanks].len = slen;
1202             nblanks++;
1203         }
1204     }
1205     log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1206                ssh1_pkt_type(pkt->type),
1207                pkt->body, pkt->length, nblanks, blanks, NULL,
1208                0, NULL);
1209 }
1210
1211 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1212 {
1213     int nblanks = 0;
1214     struct logblank_t blanks[4];
1215     char *str;
1216     int slen;
1217
1218     /*
1219      * For outgoing packets, pkt->length represents the length of the
1220      * whole packet starting at pkt->data (including some header), and
1221      * pkt->body refers to the point within that where the log-worthy
1222      * payload begins. However, incoming packets expect pkt->length to
1223      * represent only the payload length (that is, it's measured from
1224      * pkt->body not from pkt->data). Temporarily adjust our outgoing
1225      * packet to conform to the incoming-packet semantics, so that we
1226      * can analyse it with the ssh_pkt_get functions.
1227      */
1228     pkt->length -= (pkt->body - pkt->data);
1229     pkt->savedpos = 0;
1230
1231     if (ssh->logomitdata &&
1232         (pkt->type == SSH1_CMSG_STDIN_DATA ||
1233          pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1234         /* "Session data" packets - omit the data string. */
1235         if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1236             ssh_pkt_getuint32(pkt);    /* skip channel id */
1237         blanks[nblanks].offset = pkt->savedpos + 4;
1238         blanks[nblanks].type = PKTLOG_OMIT;
1239         ssh_pkt_getstring(pkt, &str, &slen);
1240         if (str) {
1241             blanks[nblanks].len = slen;
1242             nblanks++;
1243         }
1244     }
1245
1246     if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1247          pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1248          pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1249         conf_get_int(ssh->conf, CONF_logomitpass)) {
1250         /* If this is a password or similar packet, blank the password(s). */
1251         blanks[nblanks].offset = 0;
1252         blanks[nblanks].len = pkt->length;
1253         blanks[nblanks].type = PKTLOG_BLANK;
1254         nblanks++;
1255     } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1256                conf_get_int(ssh->conf, CONF_logomitpass)) {
1257         /*
1258          * If this is an X forwarding request packet, blank the fake
1259          * auth data.
1260          *
1261          * Note that while we blank the X authentication data here, we
1262          * don't take any special action to blank the start of an X11
1263          * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1264          * an X connection without having session blanking enabled is
1265          * likely to leak your cookie into the log.
1266          */
1267         pkt->savedpos = 0;
1268         ssh_pkt_getstring(pkt, &str, &slen);
1269         blanks[nblanks].offset = pkt->savedpos;
1270         blanks[nblanks].type = PKTLOG_BLANK;
1271         ssh_pkt_getstring(pkt, &str, &slen);
1272         if (str) {
1273             blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1274             nblanks++;
1275         }
1276     }
1277
1278     log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1279                ssh1_pkt_type(pkt->data[12]),
1280                pkt->body, pkt->length,
1281                nblanks, blanks, NULL, 0, NULL);
1282
1283     /*
1284      * Undo the above adjustment of pkt->length, to put the packet
1285      * back in the state we found it.
1286      */
1287     pkt->length += (pkt->body - pkt->data);
1288 }
1289
1290 /*
1291  * Collect incoming data in the incoming packet buffer.
1292  * Decipher and verify the packet when it is completely read.
1293  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1294  * Update the *data and *datalen variables.
1295  * Return a Packet structure when a packet is completed.
1296  */
1297 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1298 {
1299     struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1300
1301     crBegin(ssh->ssh1_rdpkt_crstate);
1302
1303     st->pktin = ssh_new_packet();
1304
1305     st->pktin->type = 0;
1306     st->pktin->length = 0;
1307
1308     for (st->i = st->len = 0; st->i < 4; st->i++) {
1309         while ((*datalen) == 0)
1310             crReturn(NULL);
1311         st->len = (st->len << 8) + **data;
1312         (*data)++, (*datalen)--;
1313     }
1314
1315     st->pad = 8 - (st->len % 8);
1316     st->biglen = st->len + st->pad;
1317     st->pktin->length = st->len - 5;
1318
1319     if (st->biglen < 0) {
1320         bombout(("Extremely large packet length from server suggests"
1321                  " data stream corruption"));
1322         ssh_free_packet(st->pktin);
1323         crStop(NULL);
1324     }
1325
1326     st->pktin->maxlen = st->biglen;
1327     st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1328
1329     st->to_read = st->biglen;
1330     st->p = st->pktin->data;
1331     while (st->to_read > 0) {
1332         st->chunk = st->to_read;
1333         while ((*datalen) == 0)
1334             crReturn(NULL);
1335         if (st->chunk > (*datalen))
1336             st->chunk = (*datalen);
1337         memcpy(st->p, *data, st->chunk);
1338         *data += st->chunk;
1339         *datalen -= st->chunk;
1340         st->p += st->chunk;
1341         st->to_read -= st->chunk;
1342     }
1343
1344     if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1345                                      st->biglen, NULL)) {
1346         bombout(("Network attack (CRC compensation) detected!"));
1347         ssh_free_packet(st->pktin);
1348         crStop(NULL);
1349     }
1350
1351     if (ssh->cipher)
1352         ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1353
1354     st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1355     st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1356     if (st->gotcrc != st->realcrc) {
1357         bombout(("Incorrect CRC received on packet"));
1358         ssh_free_packet(st->pktin);
1359         crStop(NULL);
1360     }
1361
1362     st->pktin->body = st->pktin->data + st->pad + 1;
1363
1364     if (ssh->v1_compressing) {
1365         unsigned char *decompblk;
1366         int decomplen;
1367         if (!zlib_decompress_block(ssh->sc_comp_ctx,
1368                                    st->pktin->body - 1, st->pktin->length + 1,
1369                                    &decompblk, &decomplen)) {
1370             bombout(("Zlib decompression encountered invalid data"));
1371             ssh_free_packet(st->pktin);
1372             crStop(NULL);
1373         }
1374
1375         if (st->pktin->maxlen < st->pad + decomplen) {
1376             st->pktin->maxlen = st->pad + decomplen;
1377             st->pktin->data = sresize(st->pktin->data,
1378                                       st->pktin->maxlen + APIEXTRA,
1379                                       unsigned char);
1380             st->pktin->body = st->pktin->data + st->pad + 1;
1381         }
1382
1383         memcpy(st->pktin->body - 1, decompblk, decomplen);
1384         sfree(decompblk);
1385         st->pktin->length = decomplen - 1;
1386     }
1387
1388     st->pktin->type = st->pktin->body[-1];
1389
1390     /*
1391      * Now pktin->body and pktin->length identify the semantic content
1392      * of the packet, excluding the initial type byte.
1393      */
1394
1395     if (ssh->logctx)
1396         ssh1_log_incoming_packet(ssh, st->pktin);
1397
1398     st->pktin->savedpos = 0;
1399
1400     crFinish(st->pktin);
1401 }
1402
1403 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1404 {
1405     int nblanks = 0;
1406     struct logblank_t blanks[4];
1407     char *str;
1408     int slen;
1409
1410     pkt->savedpos = 0;
1411
1412     if (ssh->logomitdata &&
1413         (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1414          pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1415         /* "Session data" packets - omit the data string. */
1416         ssh_pkt_getuint32(pkt);    /* skip channel id */
1417         if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1418             ssh_pkt_getuint32(pkt);    /* skip extended data type */
1419         blanks[nblanks].offset = pkt->savedpos + 4;
1420         blanks[nblanks].type = PKTLOG_OMIT;
1421         ssh_pkt_getstring(pkt, &str, &slen);
1422         if (str) {
1423             blanks[nblanks].len = slen;
1424             nblanks++;
1425         }
1426     }
1427
1428     log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1429                ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1430                pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1431                0, NULL);
1432 }
1433
1434 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1435 {
1436     int nblanks = 0;
1437     struct logblank_t blanks[4];
1438     char *str;
1439     int slen;
1440
1441     /*
1442      * For outgoing packets, pkt->length represents the length of the
1443      * whole packet starting at pkt->data (including some header), and
1444      * pkt->body refers to the point within that where the log-worthy
1445      * payload begins. However, incoming packets expect pkt->length to
1446      * represent only the payload length (that is, it's measured from
1447      * pkt->body not from pkt->data). Temporarily adjust our outgoing
1448      * packet to conform to the incoming-packet semantics, so that we
1449      * can analyse it with the ssh_pkt_get functions.
1450      */
1451     pkt->length -= (pkt->body - pkt->data);
1452     pkt->savedpos = 0;
1453
1454     if (ssh->logomitdata &&
1455         (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1456          pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1457         /* "Session data" packets - omit the data string. */
1458         ssh_pkt_getuint32(pkt);    /* skip channel id */
1459         if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1460             ssh_pkt_getuint32(pkt);    /* skip extended data type */
1461         blanks[nblanks].offset = pkt->savedpos + 4;
1462         blanks[nblanks].type = PKTLOG_OMIT;
1463         ssh_pkt_getstring(pkt, &str, &slen);
1464         if (str) {
1465             blanks[nblanks].len = slen;
1466             nblanks++;
1467         }
1468     }
1469
1470     if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1471         conf_get_int(ssh->conf, CONF_logomitpass)) {
1472         /* If this is a password packet, blank the password(s). */
1473         pkt->savedpos = 0;
1474         ssh_pkt_getstring(pkt, &str, &slen);
1475         ssh_pkt_getstring(pkt, &str, &slen);
1476         ssh_pkt_getstring(pkt, &str, &slen);
1477         if (slen == 8 && !memcmp(str, "password", 8)) {
1478             ssh2_pkt_getbool(pkt);
1479             /* Blank the password field. */
1480             blanks[nblanks].offset = pkt->savedpos;
1481             blanks[nblanks].type = PKTLOG_BLANK;
1482             ssh_pkt_getstring(pkt, &str, &slen);
1483             if (str) {
1484                 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1485                 nblanks++;
1486                 /* If there's another password field beyond it (change of
1487                  * password), blank that too. */
1488                 ssh_pkt_getstring(pkt, &str, &slen);
1489                 if (str)
1490                     blanks[nblanks-1].len =
1491                         pkt->savedpos - blanks[nblanks].offset;
1492             }
1493         }
1494     } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1495                pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1496                conf_get_int(ssh->conf, CONF_logomitpass)) {
1497         /* If this is a keyboard-interactive response packet, blank
1498          * the responses. */
1499         pkt->savedpos = 0;
1500         ssh_pkt_getuint32(pkt);
1501         blanks[nblanks].offset = pkt->savedpos;
1502         blanks[nblanks].type = PKTLOG_BLANK;
1503         while (1) {
1504             ssh_pkt_getstring(pkt, &str, &slen);
1505             if (!str)
1506                 break;
1507         }
1508         blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1509         nblanks++;
1510     } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1511                conf_get_int(ssh->conf, CONF_logomitpass)) {
1512         /*
1513          * If this is an X forwarding request packet, blank the fake
1514          * auth data.
1515          *
1516          * Note that while we blank the X authentication data here, we
1517          * don't take any special action to blank the start of an X11
1518          * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1519          * an X connection without having session blanking enabled is
1520          * likely to leak your cookie into the log.
1521          */
1522         pkt->savedpos = 0;
1523         ssh_pkt_getuint32(pkt);
1524         ssh_pkt_getstring(pkt, &str, &slen);
1525         if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1526             ssh2_pkt_getbool(pkt);
1527             ssh2_pkt_getbool(pkt);
1528             ssh_pkt_getstring(pkt, &str, &slen);
1529             blanks[nblanks].offset = pkt->savedpos;
1530             blanks[nblanks].type = PKTLOG_BLANK;
1531             ssh_pkt_getstring(pkt, &str, &slen);
1532             if (str) {
1533                 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1534                 nblanks++;
1535             }
1536         }
1537     }
1538
1539     log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1540                ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1541                pkt->body, pkt->length, nblanks, blanks,
1542                &ssh->v2_outgoing_sequence,
1543                pkt->downstream_id, pkt->additional_log_text);
1544
1545     /*
1546      * Undo the above adjustment of pkt->length, to put the packet
1547      * back in the state we found it.
1548      */
1549     pkt->length += (pkt->body - pkt->data);
1550 }
1551
1552 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1553 {
1554     struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1555
1556     crBegin(ssh->ssh2_rdpkt_crstate);
1557
1558     st->pktin = ssh_new_packet();
1559
1560     st->pktin->type = 0;
1561     st->pktin->length = 0;
1562     if (ssh->sccipher)
1563         st->cipherblk = ssh->sccipher->blksize;
1564     else
1565         st->cipherblk = 8;
1566     if (st->cipherblk < 8)
1567         st->cipherblk = 8;
1568     st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1569
1570     if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1571         ssh->scmac && !ssh->scmac_etm) {
1572         /*
1573          * When dealing with a CBC-mode cipher, we want to avoid the
1574          * possibility of an attacker's tweaking the ciphertext stream
1575          * so as to cause us to feed the same block to the block
1576          * cipher more than once and thus leak information
1577          * (VU#958563).  The way we do this is not to take any
1578          * decisions on the basis of anything we've decrypted until
1579          * we've verified it with a MAC.  That includes the packet
1580          * length, so we just read data and check the MAC repeatedly,
1581          * and when the MAC passes, see if the length we've got is
1582          * plausible.
1583          *
1584          * This defence is unnecessary in OpenSSH ETM mode, because
1585          * the whole point of ETM mode is that the attacker can't
1586          * tweak the ciphertext stream at all without the MAC
1587          * detecting it before we decrypt anything.
1588          */
1589
1590         /* May as well allocate the whole lot now. */
1591         st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1592                                 unsigned char);
1593
1594         /* Read an amount corresponding to the MAC. */
1595         for (st->i = 0; st->i < st->maclen; st->i++) {
1596             while ((*datalen) == 0)
1597                 crReturn(NULL);
1598             st->pktin->data[st->i] = *(*data)++;
1599             (*datalen)--;
1600         }
1601
1602         st->packetlen = 0;
1603         {
1604             unsigned char seq[4];
1605             ssh->scmac->start(ssh->sc_mac_ctx);
1606             PUT_32BIT(seq, st->incoming_sequence);
1607             ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1608         }
1609
1610         for (;;) { /* Once around this loop per cipher block. */
1611             /* Read another cipher-block's worth, and tack it onto the end. */
1612             for (st->i = 0; st->i < st->cipherblk; st->i++) {
1613                 while ((*datalen) == 0)
1614                     crReturn(NULL);
1615                 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1616                 (*datalen)--;
1617             }
1618             /* Decrypt one more block (a little further back in the stream). */
1619             ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1620                                    st->pktin->data + st->packetlen,
1621                                    st->cipherblk);
1622             /* Feed that block to the MAC. */
1623             ssh->scmac->bytes(ssh->sc_mac_ctx,
1624                               st->pktin->data + st->packetlen, st->cipherblk);
1625             st->packetlen += st->cipherblk;
1626             /* See if that gives us a valid packet. */
1627             if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1628                                       st->pktin->data + st->packetlen) &&
1629                 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1630                  st->packetlen-4))
1631                     break;
1632             if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1633                 bombout(("No valid incoming packet found"));
1634                 ssh_free_packet(st->pktin);
1635                 crStop(NULL);
1636             }       
1637         }
1638         st->pktin->maxlen = st->packetlen + st->maclen;
1639         st->pktin->data = sresize(st->pktin->data,
1640                                   st->pktin->maxlen + APIEXTRA,
1641                                   unsigned char);
1642     } else if (ssh->scmac && ssh->scmac_etm) {
1643         st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1644
1645         /*
1646          * OpenSSH encrypt-then-MAC mode: the packet length is
1647          * unencrypted.
1648          */
1649         for (st->i = st->len = 0; st->i < 4; st->i++) {
1650             while ((*datalen) == 0)
1651                 crReturn(NULL);
1652             st->pktin->data[st->i] = *(*data)++;
1653             (*datalen)--;
1654         }
1655         st->len = toint(GET_32BIT(st->pktin->data));
1656
1657         /*
1658          * _Completely_ silly lengths should be stomped on before they
1659          * do us any more damage.
1660          */
1661         if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1662             st->len % st->cipherblk != 0) {
1663             bombout(("Incoming packet length field was garbled"));
1664             ssh_free_packet(st->pktin);
1665             crStop(NULL);
1666         }
1667
1668         /*
1669          * So now we can work out the total packet length.
1670          */
1671         st->packetlen = st->len + 4;
1672
1673         /*
1674          * Allocate memory for the rest of the packet.
1675          */
1676         st->pktin->maxlen = st->packetlen + st->maclen;
1677         st->pktin->data = sresize(st->pktin->data,
1678                                   st->pktin->maxlen + APIEXTRA,
1679                                   unsigned char);
1680
1681         /*
1682          * Read the remainder of the packet.
1683          */
1684         for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1685             while ((*datalen) == 0)
1686                 crReturn(NULL);
1687             st->pktin->data[st->i] = *(*data)++;
1688             (*datalen)--;
1689         }
1690
1691         /*
1692          * Check the MAC.
1693          */
1694         if (ssh->scmac
1695             && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1696                                    st->len + 4, st->incoming_sequence)) {
1697             bombout(("Incorrect MAC received on packet"));
1698             ssh_free_packet(st->pktin);
1699             crStop(NULL);
1700         }
1701
1702         /* Decrypt everything between the length field and the MAC. */
1703         if (ssh->sccipher)
1704             ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1705                                    st->pktin->data + 4,
1706                                    st->packetlen - 4);
1707     } else {
1708         st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1709
1710         /*
1711          * Acquire and decrypt the first block of the packet. This will
1712          * contain the length and padding details.
1713          */
1714         for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1715             while ((*datalen) == 0)
1716                 crReturn(NULL);
1717             st->pktin->data[st->i] = *(*data)++;
1718             (*datalen)--;
1719         }
1720
1721         if (ssh->sccipher)
1722             ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1723                                    st->pktin->data, st->cipherblk);
1724
1725         /*
1726          * Now get the length figure.
1727          */
1728         st->len = toint(GET_32BIT(st->pktin->data));
1729
1730         /*
1731          * _Completely_ silly lengths should be stomped on before they
1732          * do us any more damage.
1733          */
1734         if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1735             (st->len + 4) % st->cipherblk != 0) {
1736             bombout(("Incoming packet was garbled on decryption"));
1737             ssh_free_packet(st->pktin);
1738             crStop(NULL);
1739         }
1740
1741         /*
1742          * So now we can work out the total packet length.
1743          */
1744         st->packetlen = st->len + 4;
1745
1746         /*
1747          * Allocate memory for the rest of the packet.
1748          */
1749         st->pktin->maxlen = st->packetlen + st->maclen;
1750         st->pktin->data = sresize(st->pktin->data,
1751                                   st->pktin->maxlen + APIEXTRA,
1752                                   unsigned char);
1753
1754         /*
1755          * Read and decrypt the remainder of the packet.
1756          */
1757         for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1758              st->i++) {
1759             while ((*datalen) == 0)
1760                 crReturn(NULL);
1761             st->pktin->data[st->i] = *(*data)++;
1762             (*datalen)--;
1763         }
1764         /* Decrypt everything _except_ the MAC. */
1765         if (ssh->sccipher)
1766             ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1767                                    st->pktin->data + st->cipherblk,
1768                                    st->packetlen - st->cipherblk);
1769
1770         /*
1771          * Check the MAC.
1772          */
1773         if (ssh->scmac
1774             && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1775                                    st->len + 4, st->incoming_sequence)) {
1776             bombout(("Incorrect MAC received on packet"));
1777             ssh_free_packet(st->pktin);
1778             crStop(NULL);
1779         }
1780     }
1781     /* Get and sanity-check the amount of random padding. */
1782     st->pad = st->pktin->data[4];
1783     if (st->pad < 4 || st->len - st->pad < 1) {
1784         bombout(("Invalid padding length on received packet"));
1785         ssh_free_packet(st->pktin);
1786         crStop(NULL);
1787     }
1788     /*
1789      * This enables us to deduce the payload length.
1790      */
1791     st->payload = st->len - st->pad - 1;
1792
1793     st->pktin->length = st->payload + 5;
1794     st->pktin->encrypted_len = st->packetlen;
1795
1796     st->pktin->sequence = st->incoming_sequence++;
1797
1798     st->pktin->length = st->packetlen - st->pad;
1799     assert(st->pktin->length >= 0);
1800
1801     /*
1802      * Decompress packet payload.
1803      */
1804     {
1805         unsigned char *newpayload;
1806         int newlen;
1807         if (ssh->sccomp &&
1808             ssh->sccomp->decompress(ssh->sc_comp_ctx,
1809                                     st->pktin->data + 5, st->pktin->length - 5,
1810                                     &newpayload, &newlen)) {
1811             if (st->pktin->maxlen < newlen + 5) {
1812                 st->pktin->maxlen = newlen + 5;
1813                 st->pktin->data = sresize(st->pktin->data,
1814                                           st->pktin->maxlen + APIEXTRA,
1815                                           unsigned char);
1816             }
1817             st->pktin->length = 5 + newlen;
1818             memcpy(st->pktin->data + 5, newpayload, newlen);
1819             sfree(newpayload);
1820         }
1821     }
1822
1823     /*
1824      * pktin->body and pktin->length should identify the semantic
1825      * content of the packet, excluding the initial type byte.
1826      */
1827     st->pktin->type = st->pktin->data[5];
1828     st->pktin->body = st->pktin->data + 6;
1829     st->pktin->length -= 6;
1830     assert(st->pktin->length >= 0);    /* one last double-check */
1831
1832     if (ssh->logctx)
1833         ssh2_log_incoming_packet(ssh, st->pktin);
1834
1835     st->pktin->savedpos = 0;
1836
1837     crFinish(st->pktin);
1838 }
1839
1840 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1841                                                  int *datalen)
1842 {
1843     struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1844
1845     crBegin(ssh->ssh2_bare_rdpkt_crstate);
1846
1847     /*
1848      * Read the packet length field.
1849      */
1850     for (st->i = 0; st->i < 4; st->i++) {
1851         while ((*datalen) == 0)
1852             crReturn(NULL);
1853         st->length[st->i] = *(*data)++;
1854         (*datalen)--;
1855     }
1856
1857     st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1858     if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1859         bombout(("Invalid packet length received"));
1860         crStop(NULL);
1861     }
1862
1863     st->pktin = ssh_new_packet();
1864     st->pktin->data = snewn(st->packetlen, unsigned char);
1865
1866     st->pktin->encrypted_len = st->packetlen;
1867
1868     st->pktin->sequence = st->incoming_sequence++;
1869
1870     /*
1871      * Read the remainder of the packet.
1872      */
1873     for (st->i = 0; st->i < st->packetlen; st->i++) {
1874         while ((*datalen) == 0)
1875             crReturn(NULL);
1876         st->pktin->data[st->i] = *(*data)++;
1877         (*datalen)--;
1878     }
1879
1880     /*
1881      * pktin->body and pktin->length should identify the semantic
1882      * content of the packet, excluding the initial type byte.
1883      */
1884     st->pktin->type = st->pktin->data[0];
1885     st->pktin->body = st->pktin->data + 1;
1886     st->pktin->length = st->packetlen - 1;
1887
1888     /*
1889      * Log incoming packet, possibly omitting sensitive fields.
1890      */
1891     if (ssh->logctx)
1892         ssh2_log_incoming_packet(ssh, st->pktin);
1893
1894     st->pktin->savedpos = 0;
1895
1896     crFinish(st->pktin);
1897 }
1898
1899 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1900 {
1901     int pad, biglen, i, pktoffs;
1902     unsigned long crc;
1903 #ifdef __SC__
1904     /*
1905      * XXX various versions of SC (including 8.8.4) screw up the
1906      * register allocation in this function and use the same register
1907      * (D6) for len and as a temporary, with predictable results.  The
1908      * following sledgehammer prevents this.
1909      */
1910     volatile
1911 #endif
1912     int len;
1913
1914     if (ssh->logctx)
1915         ssh1_log_outgoing_packet(ssh, pkt);
1916
1917     if (ssh->v1_compressing) {
1918         unsigned char *compblk;
1919         int complen;
1920         zlib_compress_block(ssh->cs_comp_ctx,
1921                             pkt->data + 12, pkt->length - 12,
1922                             &compblk, &complen);
1923         ssh_pkt_ensure(pkt, complen + 2);   /* just in case it's got bigger */
1924         memcpy(pkt->data + 12, compblk, complen);
1925         sfree(compblk);
1926         pkt->length = complen + 12;
1927     }
1928
1929     ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1930     pkt->length += 4;
1931     len = pkt->length - 4 - 8;  /* len(type+data+CRC) */
1932     pad = 8 - (len % 8);
1933     pktoffs = 8 - pad;
1934     biglen = len + pad;         /* len(padding+type+data+CRC) */
1935
1936     for (i = pktoffs; i < 4+8; i++)
1937         pkt->data[i] = random_byte();
1938     crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1939     PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1940     PUT_32BIT(pkt->data + pktoffs, len);
1941
1942     if (ssh->cipher)
1943         ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1944                              pkt->data + pktoffs + 4, biglen);
1945
1946     if (offset_p) *offset_p = pktoffs;
1947     return biglen + 4;          /* len(length+padding+type+data+CRC) */
1948 }
1949
1950 static int s_write(Ssh ssh, void *data, int len)
1951 {
1952     if (ssh->logctx)
1953         log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1954                    0, NULL, NULL, 0, NULL);
1955     if (!ssh->s)
1956         return 0;
1957     return sk_write(ssh->s, (char *)data, len);
1958 }
1959
1960 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1961 {
1962     int len, backlog, offset;
1963     len = s_wrpkt_prepare(ssh, pkt, &offset);
1964     backlog = s_write(ssh, pkt->data + offset, len);
1965     if (backlog > SSH_MAX_BACKLOG)
1966         ssh_throttle_all(ssh, 1, backlog);
1967     ssh_free_packet(pkt);
1968 }
1969
1970 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1971 {
1972     int len, offset;
1973     len = s_wrpkt_prepare(ssh, pkt, &offset);
1974     if (ssh->deferred_len + len > ssh->deferred_size) {
1975         ssh->deferred_size = ssh->deferred_len + len + 128;
1976         ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1977                                           ssh->deferred_size,
1978                                           unsigned char);
1979     }
1980     memcpy(ssh->deferred_send_data + ssh->deferred_len,
1981            pkt->data + offset, len);
1982     ssh->deferred_len += len;
1983     ssh_free_packet(pkt);
1984 }
1985
1986 /*
1987  * Construct a SSH-1 packet with the specified contents.
1988  * (This all-at-once interface used to be the only one, but now SSH-1
1989  * packets can also be constructed incrementally.)
1990  */
1991 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1992 {
1993     int argtype;
1994     Bignum bn;
1995     struct Packet *pkt;
1996
1997     pkt = ssh1_pkt_init(pkttype);
1998
1999     while ((argtype = va_arg(ap, int)) != PKT_END) {
2000         unsigned char *argp, argchar;
2001         char *sargp;
2002         unsigned long argint;
2003         int arglen;
2004         switch (argtype) {
2005           /* Actual fields in the packet */
2006           case PKT_INT:
2007             argint = va_arg(ap, int);
2008             ssh_pkt_adduint32(pkt, argint);
2009             break;
2010           case PKT_CHAR:
2011             argchar = (unsigned char) va_arg(ap, int);
2012             ssh_pkt_addbyte(pkt, argchar);
2013             break;
2014           case PKT_DATA:
2015             argp = va_arg(ap, unsigned char *);
2016             arglen = va_arg(ap, int);
2017             ssh_pkt_adddata(pkt, argp, arglen);
2018             break;
2019           case PKT_STR:
2020             sargp = va_arg(ap, char *);
2021             ssh_pkt_addstring(pkt, sargp);
2022             break;
2023           case PKT_BIGNUM:
2024             bn = va_arg(ap, Bignum);
2025             ssh1_pkt_addmp(pkt, bn);
2026             break;
2027         }
2028     }
2029
2030     return pkt;
2031 }
2032
2033 static void send_packet(Ssh ssh, int pkttype, ...)
2034 {
2035     struct Packet *pkt;
2036     va_list ap;
2037     va_start(ap, pkttype);
2038     pkt = construct_packet(ssh, pkttype, ap);
2039     va_end(ap);
2040     s_wrpkt(ssh, pkt);
2041 }
2042
2043 static void defer_packet(Ssh ssh, int pkttype, ...)
2044 {
2045     struct Packet *pkt;
2046     va_list ap;
2047     va_start(ap, pkttype);
2048     pkt = construct_packet(ssh, pkttype, ap);
2049     va_end(ap);
2050     s_wrpkt_defer(ssh, pkt);
2051 }
2052
2053 static int ssh_versioncmp(char *a, char *b)
2054 {
2055     char *ae, *be;
2056     unsigned long av, bv;
2057
2058     av = strtoul(a, &ae, 10);
2059     bv = strtoul(b, &be, 10);
2060     if (av != bv)
2061         return (av < bv ? -1 : +1);
2062     if (*ae == '.')
2063         ae++;
2064     if (*be == '.')
2065         be++;
2066     av = strtoul(ae, &ae, 10);
2067     bv = strtoul(be, &be, 10);
2068     if (av != bv)
2069         return (av < bv ? -1 : +1);
2070     return 0;
2071 }
2072
2073 /*
2074  * Utility routines for putting an SSH-protocol `string' and
2075  * `uint32' into a hash state.
2076  */
2077 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2078 {
2079     unsigned char lenblk[4];
2080     PUT_32BIT(lenblk, len);
2081     h->bytes(s, lenblk, 4);
2082     h->bytes(s, str, len);
2083 }
2084
2085 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2086 {
2087     unsigned char intblk[4];
2088     PUT_32BIT(intblk, i);
2089     h->bytes(s, intblk, 4);
2090 }
2091
2092 /*
2093  * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2094  */
2095 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2096 {
2097     if (pkt->maxlen < length) {
2098         unsigned char *body = pkt->body;
2099         int offset = body ? body - pkt->data : 0;
2100         pkt->maxlen = length + 256;
2101         pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2102         if (body) pkt->body = pkt->data + offset;
2103     }
2104 }
2105 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2106 {
2107     pkt->length += len;
2108     ssh_pkt_ensure(pkt, pkt->length);
2109     memcpy(pkt->data + pkt->length - len, data, len);
2110 }
2111 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2112 {
2113     ssh_pkt_adddata(pkt, &byte, 1);
2114 }
2115 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2116 {
2117     ssh_pkt_adddata(pkt, &value, 1);
2118 }
2119 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2120 {
2121     unsigned char x[4];
2122     PUT_32BIT(x, value);
2123     ssh_pkt_adddata(pkt, x, 4);
2124 }
2125 static void ssh_pkt_addstring_start(struct Packet *pkt)
2126 {
2127     ssh_pkt_adduint32(pkt, 0);
2128     pkt->savedpos = pkt->length;
2129 }
2130 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2131                                    int len)
2132 {
2133     ssh_pkt_adddata(pkt, data, len);
2134     PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2135 }
2136 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2137 {
2138   ssh_pkt_addstring_data(pkt, data, strlen(data));
2139 }
2140 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2141 {
2142     ssh_pkt_addstring_start(pkt);
2143     ssh_pkt_addstring_str(pkt, data);
2144 }
2145 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2146 {
2147     int len = ssh1_bignum_length(b);
2148     unsigned char *data = snewn(len, unsigned char);
2149     (void) ssh1_write_bignum(data, b);
2150     ssh_pkt_adddata(pkt, data, len);
2151     sfree(data);
2152 }
2153 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2154 {
2155     unsigned char *p;
2156     int i, n = (bignum_bitcount(b) + 7) / 8;
2157     p = snewn(n + 1, unsigned char);
2158     p[0] = 0;
2159     for (i = 1; i <= n; i++)
2160         p[i] = bignum_byte(b, n - i);
2161     i = 0;
2162     while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2163         i++;
2164     memmove(p, p + i, n + 1 - i);
2165     *len = n + 1 - i;
2166     return p;
2167 }
2168 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2169 {
2170     unsigned char *p;
2171     int len;
2172     p = ssh2_mpint_fmt(b, &len);
2173     ssh_pkt_addstring_start(pkt);
2174     ssh_pkt_addstring_data(pkt, (char *)p, len);
2175     sfree(p);
2176 }
2177
2178 static struct Packet *ssh1_pkt_init(int pkt_type)
2179 {
2180     struct Packet *pkt = ssh_new_packet();
2181     pkt->length = 4 + 8;            /* space for length + max padding */
2182     ssh_pkt_addbyte(pkt, pkt_type);
2183     pkt->body = pkt->data + pkt->length;
2184     pkt->type = pkt_type;
2185     pkt->downstream_id = 0;
2186     pkt->additional_log_text = NULL;
2187     return pkt;
2188 }
2189
2190 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2191 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2192 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2193 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2194 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2195 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2196 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2197 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2198 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2199
2200 static struct Packet *ssh2_pkt_init(int pkt_type)
2201 {
2202     struct Packet *pkt = ssh_new_packet();
2203     pkt->length = 5; /* space for packet length + padding length */
2204     pkt->forcepad = 0;
2205     pkt->type = pkt_type;
2206     ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2207     pkt->body = pkt->data + pkt->length; /* after packet type */
2208     pkt->downstream_id = 0;
2209     pkt->additional_log_text = NULL;
2210     return pkt;
2211 }
2212
2213 /*
2214  * Construct an SSH-2 final-form packet: compress it, encrypt it,
2215  * put the MAC on it. Final packet, ready to be sent, is stored in
2216  * pkt->data. Total length is returned.
2217  */
2218 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2219 {
2220     int cipherblk, maclen, padding, unencrypted_prefix, i;
2221
2222     if (ssh->logctx)
2223         ssh2_log_outgoing_packet(ssh, pkt);
2224
2225     if (ssh->bare_connection) {
2226         /*
2227          * Trivial packet construction for the bare connection
2228          * protocol.
2229          */
2230         PUT_32BIT(pkt->data + 1, pkt->length - 5);
2231         pkt->body = pkt->data + 1;
2232         ssh->v2_outgoing_sequence++;   /* only for diagnostics, really */
2233         return pkt->length - 1;
2234     }
2235
2236     /*
2237      * Compress packet payload.
2238      */
2239     {
2240         unsigned char *newpayload;
2241         int newlen;
2242         if (ssh->cscomp &&
2243             ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2244                                   pkt->length - 5,
2245                                   &newpayload, &newlen)) {
2246             pkt->length = 5;
2247             ssh2_pkt_adddata(pkt, newpayload, newlen);
2248             sfree(newpayload);
2249         }
2250     }
2251
2252     /*
2253      * Add padding. At least four bytes, and must also bring total
2254      * length (minus MAC) up to a multiple of the block size.
2255      * If pkt->forcepad is set, make sure the packet is at least that size
2256      * after padding.
2257      */
2258     cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8;  /* block size */
2259     cipherblk = cipherblk < 8 ? 8 : cipherblk;  /* or 8 if blksize < 8 */
2260     padding = 4;
2261     unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2262     if (pkt->length + padding < pkt->forcepad)
2263         padding = pkt->forcepad - pkt->length;
2264     padding +=
2265         (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2266         % cipherblk;
2267     assert(padding <= 255);
2268     maclen = ssh->csmac ? ssh->csmac->len : 0;
2269     ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2270     pkt->data[4] = padding;
2271     for (i = 0; i < padding; i++)
2272         pkt->data[pkt->length + i] = random_byte();
2273     PUT_32BIT(pkt->data, pkt->length + padding - 4);
2274     if (ssh->csmac && ssh->csmac_etm) {
2275         /*
2276          * OpenSSH-defined encrypt-then-MAC protocol.
2277          */
2278         if (ssh->cscipher)
2279             ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2280                                    pkt->data + 4, pkt->length + padding - 4);
2281         ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2282                              pkt->length + padding,
2283                              ssh->v2_outgoing_sequence);
2284     } else {
2285         /*
2286          * SSH-2 standard protocol.
2287          */
2288         if (ssh->csmac)
2289             ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2290                                  pkt->length + padding,
2291                                  ssh->v2_outgoing_sequence);
2292         if (ssh->cscipher)
2293             ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2294                                    pkt->data, pkt->length + padding);
2295     }
2296
2297     ssh->v2_outgoing_sequence++;       /* whether or not we MACed */
2298     pkt->encrypted_len = pkt->length + padding;
2299
2300     /* Ready-to-send packet starts at pkt->data. We return length. */
2301     pkt->body = pkt->data;
2302     return pkt->length + padding + maclen;
2303 }
2304
2305 /*
2306  * Routines called from the main SSH code to send packets. There
2307  * are quite a few of these, because we have two separate
2308  * mechanisms for delaying the sending of packets:
2309  * 
2310  *  - In order to send an IGNORE message and a password message in
2311  *    a single fixed-length blob, we require the ability to
2312  *    concatenate the encrypted forms of those two packets _into_ a
2313  *    single blob and then pass it to our <network.h> transport
2314  *    layer in one go. Hence, there's a deferment mechanism which
2315  *    works after packet encryption.
2316  * 
2317  *  - In order to avoid sending any connection-layer messages
2318  *    during repeat key exchange, we have to queue up any such
2319  *    outgoing messages _before_ they are encrypted (and in
2320  *    particular before they're allocated sequence numbers), and
2321  *    then send them once we've finished.
2322  * 
2323  * I call these mechanisms `defer' and `queue' respectively, so as
2324  * to distinguish them reasonably easily.
2325  * 
2326  * The functions send_noqueue() and defer_noqueue() free the packet
2327  * structure they are passed. Every outgoing packet goes through
2328  * precisely one of these functions in its life; packets passed to
2329  * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2330  * these or get queued, and then when the queue is later emptied
2331  * the packets are all passed to defer_noqueue().
2332  *
2333  * When using a CBC-mode cipher, it's necessary to ensure that an
2334  * attacker can't provide data to be encrypted using an IV that they
2335  * know.  We ensure this by prefixing each packet that might contain
2336  * user data with an SSH_MSG_IGNORE.  This is done using the deferral
2337  * mechanism, so in this case send_noqueue() ends up redirecting to
2338  * defer_noqueue().  If you don't like this inefficiency, don't use
2339  * CBC.
2340  */
2341
2342 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2343 static void ssh_pkt_defersend(Ssh);
2344
2345 /*
2346  * Send an SSH-2 packet immediately, without queuing or deferring.
2347  */
2348 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2349 {
2350     int len;
2351     int backlog;
2352     if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2353         /* We need to send two packets, so use the deferral mechanism. */
2354         ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2355         ssh_pkt_defersend(ssh);
2356         return;
2357     }
2358     len = ssh2_pkt_construct(ssh, pkt);
2359     backlog = s_write(ssh, pkt->body, len);
2360     if (backlog > SSH_MAX_BACKLOG)
2361         ssh_throttle_all(ssh, 1, backlog);
2362
2363     ssh->outgoing_data_size += pkt->encrypted_len;
2364     if (!ssh->kex_in_progress &&
2365         !ssh->bare_connection &&
2366         ssh->max_data_size != 0 &&
2367         ssh->outgoing_data_size > ssh->max_data_size)
2368         do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2369
2370     ssh_free_packet(pkt);
2371 }
2372
2373 /*
2374  * Defer an SSH-2 packet.
2375  */
2376 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2377 {
2378     int len;
2379     if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2380         ssh->deferred_len == 0 && !noignore &&
2381         !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2382         /*
2383          * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2384          * get encrypted with a known IV.
2385          */
2386         struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2387         ssh2_pkt_addstring_start(ipkt);
2388         ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2389     }
2390     len = ssh2_pkt_construct(ssh, pkt);
2391     if (ssh->deferred_len + len > ssh->deferred_size) {
2392         ssh->deferred_size = ssh->deferred_len + len + 128;
2393         ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2394                                           ssh->deferred_size,
2395                                           unsigned char);
2396     }
2397     memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2398     ssh->deferred_len += len;
2399     ssh->deferred_data_size += pkt->encrypted_len;
2400     ssh_free_packet(pkt);
2401 }
2402
2403 /*
2404  * Queue an SSH-2 packet.
2405  */
2406 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2407 {
2408     assert(ssh->queueing);
2409
2410     if (ssh->queuelen >= ssh->queuesize) {
2411         ssh->queuesize = ssh->queuelen + 32;
2412         ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2413     }
2414
2415     ssh->queue[ssh->queuelen++] = pkt;
2416 }
2417
2418 /*
2419  * Either queue or send a packet, depending on whether queueing is
2420  * set.
2421  */
2422 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2423 {
2424     if (ssh->queueing)
2425         ssh2_pkt_queue(ssh, pkt);
2426     else
2427         ssh2_pkt_send_noqueue(ssh, pkt);
2428 }
2429
2430 /*
2431  * Either queue or defer a packet, depending on whether queueing is
2432  * set.
2433  */
2434 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2435 {
2436     if (ssh->queueing)
2437         ssh2_pkt_queue(ssh, pkt);
2438     else
2439         ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2440 }
2441
2442 /*
2443  * Send the whole deferred data block constructed by
2444  * ssh2_pkt_defer() or SSH-1's defer_packet().
2445  * 
2446  * The expected use of the defer mechanism is that you call
2447  * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2448  * not currently queueing, this simply sets up deferred_send_data
2449  * and then sends it. If we _are_ currently queueing, the calls to
2450  * ssh2_pkt_defer() put the deferred packets on to the queue
2451  * instead, and therefore ssh_pkt_defersend() has no deferred data
2452  * to send. Hence, there's no need to make it conditional on
2453  * ssh->queueing.
2454  */
2455 static void ssh_pkt_defersend(Ssh ssh)
2456 {
2457     int backlog;
2458     backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2459     ssh->deferred_len = ssh->deferred_size = 0;
2460     sfree(ssh->deferred_send_data);
2461     ssh->deferred_send_data = NULL;
2462     if (backlog > SSH_MAX_BACKLOG)
2463         ssh_throttle_all(ssh, 1, backlog);
2464
2465     ssh->outgoing_data_size += ssh->deferred_data_size;
2466     if (!ssh->kex_in_progress &&
2467         !ssh->bare_connection &&
2468         ssh->max_data_size != 0 &&
2469         ssh->outgoing_data_size > ssh->max_data_size)
2470         do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2471     ssh->deferred_data_size = 0;
2472 }
2473
2474 /*
2475  * Send a packet whose length needs to be disguised (typically
2476  * passwords or keyboard-interactive responses).
2477  */
2478 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2479                                        int padsize)
2480 {
2481 #if 0
2482     if (0) {
2483         /*
2484          * The simplest way to do this is to adjust the
2485          * variable-length padding field in the outgoing packet.
2486          * 
2487          * Currently compiled out, because some Cisco SSH servers
2488          * don't like excessively padded packets (bah, why's it
2489          * always Cisco?)
2490          */
2491         pkt->forcepad = padsize;
2492         ssh2_pkt_send(ssh, pkt);
2493     } else
2494 #endif
2495     {
2496         /*
2497          * If we can't do that, however, an alternative approach is
2498          * to use the pkt_defer mechanism to bundle the packet
2499          * tightly together with an SSH_MSG_IGNORE such that their
2500          * combined length is a constant. So first we construct the
2501          * final form of this packet and defer its sending.
2502          */
2503         ssh2_pkt_defer(ssh, pkt);
2504
2505         /*
2506          * Now construct an SSH_MSG_IGNORE which includes a string
2507          * that's an exact multiple of the cipher block size. (If
2508          * the cipher is NULL so that the block size is
2509          * unavailable, we don't do this trick at all, because we
2510          * gain nothing by it.)
2511          */
2512         if (ssh->cscipher &&
2513             !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2514             int stringlen, i;
2515
2516             stringlen = (256 - ssh->deferred_len);
2517             stringlen += ssh->cscipher->blksize - 1;
2518             stringlen -= (stringlen % ssh->cscipher->blksize);
2519             if (ssh->cscomp) {
2520                 /*
2521                  * Temporarily disable actual compression, so we
2522                  * can guarantee to get this string exactly the
2523                  * length we want it. The compression-disabling
2524                  * routine should return an integer indicating how
2525                  * many bytes we should adjust our string length
2526                  * by.
2527                  */
2528                 stringlen -=
2529                     ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2530             }
2531             pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2532             ssh2_pkt_addstring_start(pkt);
2533             for (i = 0; i < stringlen; i++) {
2534                 char c = (char) random_byte();
2535                 ssh2_pkt_addstring_data(pkt, &c, 1);
2536             }
2537             ssh2_pkt_defer(ssh, pkt);
2538         }
2539         ssh_pkt_defersend(ssh);
2540     }
2541 }
2542
2543 /*
2544  * Send all queued SSH-2 packets. We send them by means of
2545  * ssh2_pkt_defer_noqueue(), in case they included a pair of
2546  * packets that needed to be lumped together.
2547  */
2548 static void ssh2_pkt_queuesend(Ssh ssh)
2549 {
2550     int i;
2551
2552     assert(!ssh->queueing);
2553
2554     for (i = 0; i < ssh->queuelen; i++)
2555         ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2556     ssh->queuelen = 0;
2557
2558     ssh_pkt_defersend(ssh);
2559 }
2560
2561 #if 0
2562 void bndebug(char *string, Bignum b)
2563 {
2564     unsigned char *p;
2565     int i, len;
2566     p = ssh2_mpint_fmt(b, &len);
2567     debug(("%s", string));
2568     for (i = 0; i < len; i++)
2569         debug((" %02x", p[i]));
2570     debug(("\n"));
2571     sfree(p);
2572 }
2573 #endif
2574
2575 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2576 {
2577     unsigned char *p;
2578     int len;
2579     p = ssh2_mpint_fmt(b, &len);
2580     hash_string(h, s, p, len);
2581     sfree(p);
2582 }
2583
2584 /*
2585  * Packet decode functions for both SSH-1 and SSH-2.
2586  */
2587 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2588 {
2589     unsigned long value;
2590     if (pkt->length - pkt->savedpos < 4)
2591         return 0;                      /* arrgh, no way to decline (FIXME?) */
2592     value = GET_32BIT(pkt->body + pkt->savedpos);
2593     pkt->savedpos += 4;
2594     return value;
2595 }
2596 static int ssh2_pkt_getbool(struct Packet *pkt)
2597 {
2598     unsigned long value;
2599     if (pkt->length - pkt->savedpos < 1)
2600         return 0;                      /* arrgh, no way to decline (FIXME?) */
2601     value = pkt->body[pkt->savedpos] != 0;
2602     pkt->savedpos++;
2603     return value;
2604 }
2605 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2606 {
2607     int len;
2608     *p = NULL;
2609     *length = 0;
2610     if (pkt->length - pkt->savedpos < 4)
2611         return;
2612     len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2613     if (len < 0)
2614         return;
2615     *length = len;
2616     pkt->savedpos += 4;
2617     if (pkt->length - pkt->savedpos < *length)
2618         return;
2619     *p = (char *)(pkt->body + pkt->savedpos);
2620     pkt->savedpos += *length;
2621 }
2622 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2623 {
2624     if (pkt->length - pkt->savedpos < length)
2625         return NULL;
2626     pkt->savedpos += length;
2627     return pkt->body + (pkt->savedpos - length);
2628 }
2629 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2630                               const unsigned char **keystr)
2631 {
2632     int j;
2633
2634     j = makekey(pkt->body + pkt->savedpos,
2635                 pkt->length - pkt->savedpos,
2636                 key, keystr, 0);
2637
2638     if (j < 0)
2639         return FALSE;
2640     
2641     pkt->savedpos += j;
2642     assert(pkt->savedpos < pkt->length);
2643
2644     return TRUE;
2645 }
2646 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2647 {
2648     int j;
2649     Bignum b;
2650
2651     j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2652                          pkt->length - pkt->savedpos, &b);
2653
2654     if (j < 0)
2655         return NULL;
2656
2657     pkt->savedpos += j;
2658     return b;
2659 }
2660 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2661 {
2662     char *p;
2663     int length;
2664     Bignum b;
2665
2666     ssh_pkt_getstring(pkt, &p, &length);
2667     if (!p)
2668         return NULL;
2669     if (p[0] & 0x80)
2670         return NULL;
2671     b = bignum_from_bytes((unsigned char *)p, length);
2672     return b;
2673 }
2674
2675 /*
2676  * Helper function to add an SSH-2 signature blob to a packet.
2677  * Expects to be shown the public key blob as well as the signature
2678  * blob. Normally works just like ssh2_pkt_addstring, but will
2679  * fiddle with the signature packet if necessary for
2680  * BUG_SSH2_RSA_PADDING.
2681  */
2682 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2683                              void *pkblob_v, int pkblob_len,
2684                              void *sigblob_v, int sigblob_len)
2685 {
2686     unsigned char *pkblob = (unsigned char *)pkblob_v;
2687     unsigned char *sigblob = (unsigned char *)sigblob_v;
2688
2689     /* dmemdump(pkblob, pkblob_len); */
2690     /* dmemdump(sigblob, sigblob_len); */
2691
2692     /*
2693      * See if this is in fact an ssh-rsa signature and a buggy
2694      * server; otherwise we can just do this the easy way.
2695      */
2696     if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2697         (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2698         int pos, len, siglen;
2699
2700         /*
2701          * Find the byte length of the modulus.
2702          */
2703
2704         pos = 4+7;                     /* skip over "ssh-rsa" */
2705         len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2706         if (len < 0 || len > pkblob_len - pos - 4)
2707             goto give_up;
2708         pos += 4 + len;                /* skip over exponent */
2709         if (pkblob_len - pos < 4)
2710             goto give_up;
2711         len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2712         if (len < 0 || len > pkblob_len - pos - 4)
2713             goto give_up;
2714         pos += 4;                      /* find modulus itself */
2715         while (len > 0 && pkblob[pos] == 0)
2716             len--, pos++;
2717         /* debug(("modulus length is %d\n", len)); */
2718
2719         /*
2720          * Now find the signature integer.
2721          */
2722         pos = 4+7;                     /* skip over "ssh-rsa" */
2723         if (sigblob_len < pos+4)
2724             goto give_up;
2725         siglen = toint(GET_32BIT(sigblob+pos));
2726         if (siglen != sigblob_len - pos - 4)
2727             goto give_up;
2728         /* debug(("signature length is %d\n", siglen)); */
2729
2730         if (len != siglen) {
2731             unsigned char newlen[4];
2732             ssh2_pkt_addstring_start(pkt);
2733             ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2734             /* dmemdump(sigblob, pos); */
2735             pos += 4;                  /* point to start of actual sig */
2736             PUT_32BIT(newlen, len);
2737             ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2738             /* dmemdump(newlen, 4); */
2739             newlen[0] = 0;
2740             while (len-- > siglen) {
2741                 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2742                 /* dmemdump(newlen, 1); */
2743             }
2744             ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2745             /* dmemdump(sigblob+pos, siglen); */
2746             return;
2747         }
2748
2749         /* Otherwise fall through and do it the easy way. We also come
2750          * here as a fallback if we discover above that the key blob
2751          * is misformatted in some way. */
2752       give_up:;
2753     }
2754
2755     ssh2_pkt_addstring_start(pkt);
2756     ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2757 }
2758
2759 /*
2760  * Examine the remote side's version string and compare it against
2761  * a list of known buggy implementations.
2762  */
2763 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2764 {
2765     char *imp;                         /* pointer to implementation part */
2766     imp = vstring;
2767     imp += strcspn(imp, "-");
2768     if (*imp) imp++;
2769     imp += strcspn(imp, "-");
2770     if (*imp) imp++;
2771
2772     ssh->remote_bugs = 0;
2773
2774     /*
2775      * General notes on server version strings:
2776      *  - Not all servers reporting "Cisco-1.25" have all the bugs listed
2777      *    here -- in particular, we've heard of one that's perfectly happy
2778      *    with SSH1_MSG_IGNOREs -- but this string never seems to change,
2779      *    so we can't distinguish them.
2780      */
2781     if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2782         (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2783          (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2784           !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2785           !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2786           !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2787         /*
2788          * These versions don't support SSH1_MSG_IGNORE, so we have
2789          * to use a different defence against password length
2790          * sniffing.
2791          */
2792         ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2793         logevent("We believe remote version has SSH-1 ignore bug");
2794     }
2795
2796     if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2797         (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2798          (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2799         /*
2800          * These versions need a plain password sent; they can't
2801          * handle having a null and a random length of data after
2802          * the password.
2803          */
2804         ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2805         logevent("We believe remote version needs a plain SSH-1 password");
2806     }
2807
2808     if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2809         (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2810          (!strcmp(imp, "Cisco-1.25")))) {
2811         /*
2812          * These versions apparently have no clue whatever about
2813          * RSA authentication and will panic and die if they see
2814          * an AUTH_RSA message.
2815          */
2816         ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2817         logevent("We believe remote version can't handle SSH-1 RSA authentication");
2818     }
2819
2820     if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2821         (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2822          !wc_match("* VShell", imp) &&
2823          (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2824           wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2825           wc_match("2.1 *", imp)))) {
2826         /*
2827          * These versions have the HMAC bug.
2828          */
2829         ssh->remote_bugs |= BUG_SSH2_HMAC;
2830         logevent("We believe remote version has SSH-2 HMAC bug");
2831     }
2832
2833     if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2834         (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2835          !wc_match("* VShell", imp) &&
2836          (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2837         /*
2838          * These versions have the key-derivation bug (failing to
2839          * include the literal shared secret in the hashes that
2840          * generate the keys).
2841          */
2842         ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2843         logevent("We believe remote version has SSH-2 key-derivation bug");
2844     }
2845
2846     if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2847         (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2848          (wc_match("OpenSSH_2.[5-9]*", imp) ||
2849           wc_match("OpenSSH_3.[0-2]*", imp) ||
2850           wc_match("mod_sftp/0.[0-8]*", imp) ||
2851           wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2852         /*
2853          * These versions have the SSH-2 RSA padding bug.
2854          */
2855         ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2856         logevent("We believe remote version has SSH-2 RSA padding bug");
2857     }
2858
2859     if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2860         (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2861          wc_match("OpenSSH_2.[0-2]*", imp))) {
2862         /*
2863          * These versions have the SSH-2 session-ID bug in
2864          * public-key authentication.
2865          */
2866         ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2867         logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2868     }
2869
2870     if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2871         (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2872          (wc_match("DigiSSH_2.0", imp) ||
2873           wc_match("OpenSSH_2.[0-4]*", imp) ||
2874           wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2875           wc_match("Sun_SSH_1.0", imp) ||
2876           wc_match("Sun_SSH_1.0.1", imp) ||
2877           /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2878           wc_match("WeOnlyDo-*", imp)))) {
2879         /*
2880          * These versions have the SSH-2 rekey bug.
2881          */
2882         ssh->remote_bugs |= BUG_SSH2_REKEY;
2883         logevent("We believe remote version has SSH-2 rekey bug");
2884     }
2885
2886     if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2887         (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2888          (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2889           wc_match("1.36 sshlib: GlobalScape", imp)))) {
2890         /*
2891          * This version ignores our makpkt and needs to be throttled.
2892          */
2893         ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2894         logevent("We believe remote version ignores SSH-2 maximum packet size");
2895     }
2896
2897     if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2898         /*
2899          * Servers that don't support SSH2_MSG_IGNORE. Currently,
2900          * none detected automatically.
2901          */
2902         ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2903         logevent("We believe remote version has SSH-2 ignore bug");
2904     }
2905
2906     if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2907         (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2908          (wc_match("OpenSSH_2.[235]*", imp)))) {
2909         /*
2910          * These versions only support the original (pre-RFC4419)
2911          * SSH-2 GEX request, and disconnect with a protocol error if
2912          * we use the newer version.
2913          */
2914         ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2915         logevent("We believe remote version has outdated SSH-2 GEX");
2916     }
2917
2918     if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2919         /*
2920          * Servers that don't support our winadj request for one
2921          * reason or another. Currently, none detected automatically.
2922          */
2923         ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2924         logevent("We believe remote version has winadj bug");
2925     }
2926
2927     if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2928         (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2929          (wc_match("OpenSSH_[2-5].*", imp) ||
2930           wc_match("OpenSSH_6.[0-6]*", imp) ||
2931           wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2932           wc_match("dropbear_0.5[01]*", imp)))) {
2933         /*
2934          * These versions have the SSH-2 channel request bug.
2935          * OpenSSH 6.7 and above do not:
2936          * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2937          * dropbear_0.52 and above do not:
2938          * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2939          */
2940         ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2941         logevent("We believe remote version has SSH-2 channel request bug");
2942     }
2943 }
2944
2945 /*
2946  * The `software version' part of an SSH version string is required
2947  * to contain no spaces or minus signs.
2948  */
2949 static void ssh_fix_verstring(char *str)
2950 {
2951     /* Eat "<protoversion>-". */
2952     while (*str && *str != '-') str++;
2953     assert(*str == '-'); str++;
2954
2955     /* Convert minus signs and spaces in the remaining string into
2956      * underscores. */
2957     while (*str) {
2958         if (*str == '-' || *str == ' ')
2959             *str = '_';
2960         str++;
2961     }
2962 }
2963
2964 /*
2965  * Send an appropriate SSH version string.
2966  */
2967 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2968 {
2969     char *verstring;
2970
2971     if (ssh->version == 2) {
2972         /*
2973          * Construct a v2 version string.
2974          */
2975         verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2976     } else {
2977         /*
2978          * Construct a v1 version string.
2979          */
2980         assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2981         verstring = dupprintf("SSH-%s-%s\012",
2982                               (ssh_versioncmp(svers, "1.5") <= 0 ?
2983                                svers : "1.5"),
2984                               sshver);
2985     }
2986
2987     ssh_fix_verstring(verstring + strlen(protoname));
2988
2989     if (ssh->version == 2) {
2990         size_t len;
2991         /*
2992          * Record our version string.
2993          */
2994         len = strcspn(verstring, "\015\012");
2995         ssh->v_c = snewn(len + 1, char);
2996         memcpy(ssh->v_c, verstring, len);
2997         ssh->v_c[len] = 0;
2998     }
2999
3000     logeventf(ssh, "We claim version: %.*s",
3001               strcspn(verstring, "\015\012"), verstring);
3002     s_write(ssh, verstring, strlen(verstring));
3003     sfree(verstring);
3004 }
3005
3006 static int do_ssh_init(Ssh ssh, unsigned char c)
3007 {
3008     static const char protoname[] = "SSH-";
3009
3010     struct do_ssh_init_state {
3011         int crLine;
3012         int vslen;
3013         char version[10];
3014         char *vstring;
3015         int vstrsize;
3016         int i;
3017         int proto1, proto2;
3018     };
3019     crState(do_ssh_init_state);
3020     
3021     crBeginState;
3022
3023     /* Search for a line beginning with the protocol name prefix in
3024      * the input. */
3025     for (;;) {
3026         for (s->i = 0; protoname[s->i]; s->i++) {
3027             if ((char)c != protoname[s->i]) goto no;
3028             crReturn(1);
3029         }
3030         break;
3031       no:
3032         while (c != '\012')
3033             crReturn(1);
3034         crReturn(1);
3035     }
3036
3037     s->vstrsize = sizeof(protoname) + 16;
3038     s->vstring = snewn(s->vstrsize, char);
3039     strcpy(s->vstring, protoname);
3040     s->vslen = strlen(protoname);
3041     s->i = 0;
3042     while (1) {
3043         if (s->vslen >= s->vstrsize - 1) {
3044             s->vstrsize += 16;
3045             s->vstring = sresize(s->vstring, s->vstrsize, char);
3046         }
3047         s->vstring[s->vslen++] = c;
3048         if (s->i >= 0) {
3049             if (c == '-') {
3050                 s->version[s->i] = '\0';
3051                 s->i = -1;
3052             } else if (s->i < sizeof(s->version) - 1)
3053                 s->version[s->i++] = c;
3054         } else if (c == '\012')
3055             break;
3056         crReturn(1);                   /* get another char */
3057     }
3058
3059     ssh->agentfwd_enabled = FALSE;
3060     ssh->rdpkt2_state.incoming_sequence = 0;
3061
3062     s->vstring[s->vslen] = 0;
3063     s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3064     logeventf(ssh, "Server version: %s", s->vstring);
3065     ssh_detect_bugs(ssh, s->vstring);
3066
3067     /*
3068      * Decide which SSH protocol version to support.
3069      */
3070
3071     /* Anything strictly below "2.0" means protocol 1 is supported. */
3072     s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3073     /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3074     s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3075
3076     if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
3077         bombout(("SSH protocol version 1 required by configuration but "
3078                  "not provided by server"));
3079         crStop(0);
3080     }
3081     if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
3082         bombout(("SSH protocol version 2 required by configuration but "
3083                  "not provided by server"));
3084         crStop(0);
3085     }
3086
3087     if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3088         ssh->version = 2;
3089     else
3090         ssh->version = 1;
3091
3092     logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3093
3094     /* Send the version string, if we haven't already */
3095     if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3096         ssh_send_verstring(ssh, protoname, s->version);
3097
3098     if (ssh->version == 2) {
3099         size_t len;
3100         /*
3101          * Record their version string.
3102          */
3103         len = strcspn(s->vstring, "\015\012");
3104         ssh->v_s = snewn(len + 1, char);
3105         memcpy(ssh->v_s, s->vstring, len);
3106         ssh->v_s[len] = 0;
3107             
3108         /*
3109          * Initialise SSH-2 protocol.
3110          */
3111         ssh->protocol = ssh2_protocol;
3112         ssh2_protocol_setup(ssh);
3113         ssh->s_rdpkt = ssh2_rdpkt;
3114     } else {
3115         /*
3116          * Initialise SSH-1 protocol.
3117          */
3118         ssh->protocol = ssh1_protocol;
3119         ssh1_protocol_setup(ssh);
3120         ssh->s_rdpkt = ssh1_rdpkt;
3121     }
3122     if (ssh->version == 2)
3123         do_ssh2_transport(ssh, NULL, -1, NULL);
3124
3125     update_specials_menu(ssh->frontend);
3126     ssh->state = SSH_STATE_BEFORE_SIZE;
3127     ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3128
3129     sfree(s->vstring);
3130
3131     crFinish(0);
3132 }
3133
3134 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3135 {
3136     /*
3137      * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3138      * the ssh-connection part, extracted and given a trivial binary
3139      * packet protocol, so we replace 'SSH-' at the start with a new
3140      * name. In proper SSH style (though of course this part of the
3141      * proper SSH protocol _isn't_ subject to this kind of
3142      * DNS-domain-based extension), we define the new name in our
3143      * extension space.
3144      */
3145     static const char protoname[] =
3146         "SSHCONNECTION@putty.projects.tartarus.org-";
3147
3148     struct do_ssh_connection_init_state {
3149         int crLine;
3150         int vslen;
3151         char version[10];
3152         char *vstring;
3153         int vstrsize;
3154         int i;
3155     };
3156     crState(do_ssh_connection_init_state);
3157     
3158     crBeginState;
3159
3160     /* Search for a line beginning with the protocol name prefix in
3161      * the input. */
3162     for (;;) {
3163         for (s->i = 0; protoname[s->i]; s->i++) {
3164             if ((char)c != protoname[s->i]) goto no;
3165             crReturn(1);
3166         }
3167         break;
3168       no:
3169         while (c != '\012')
3170             crReturn(1);
3171         crReturn(1);
3172     }
3173
3174     s->vstrsize = sizeof(protoname) + 16;
3175     s->vstring = snewn(s->vstrsize, char);
3176     strcpy(s->vstring, protoname);
3177     s->vslen = strlen(protoname);
3178     s->i = 0;
3179     while (1) {
3180         if (s->vslen >= s->vstrsize - 1) {
3181             s->vstrsize += 16;
3182             s->vstring = sresize(s->vstring, s->vstrsize, char);
3183         }
3184         s->vstring[s->vslen++] = c;
3185         if (s->i >= 0) {
3186             if (c == '-') {
3187                 s->version[s->i] = '\0';
3188                 s->i = -1;
3189             } else if (s->i < sizeof(s->version) - 1)
3190                 s->version[s->i++] = c;
3191         } else if (c == '\012')
3192             break;
3193         crReturn(1);                   /* get another char */
3194     }
3195
3196     ssh->agentfwd_enabled = FALSE;
3197     ssh->rdpkt2_bare_state.incoming_sequence = 0;
3198
3199     s->vstring[s->vslen] = 0;
3200     s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3201     logeventf(ssh, "Server version: %s", s->vstring);
3202     ssh_detect_bugs(ssh, s->vstring);
3203
3204     /*
3205      * Decide which SSH protocol version to support. This is easy in
3206      * bare ssh-connection mode: only 2.0 is legal.
3207      */
3208     if (ssh_versioncmp(s->version, "2.0") < 0) {
3209         bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3210         crStop(0);
3211     }
3212     if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3213         bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3214         crStop(0);
3215     }
3216
3217     ssh->version = 2;
3218
3219     logeventf(ssh, "Using bare ssh-connection protocol");
3220
3221     /* Send the version string, if we haven't already */
3222     ssh_send_verstring(ssh, protoname, s->version);
3223
3224     /*
3225      * Initialise bare connection protocol.
3226      */
3227     ssh->protocol = ssh2_bare_connection_protocol;
3228     ssh2_bare_connection_protocol_setup(ssh);
3229     ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3230
3231     update_specials_menu(ssh->frontend);
3232     ssh->state = SSH_STATE_BEFORE_SIZE;
3233     ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3234
3235     /*
3236      * Get authconn (really just conn) under way.
3237      */
3238     do_ssh2_authconn(ssh, NULL, 0, NULL);
3239
3240     sfree(s->vstring);
3241
3242     crFinish(0);
3243 }
3244
3245 static void ssh_process_incoming_data(Ssh ssh,
3246                                       unsigned char **data, int *datalen)
3247 {
3248     struct Packet *pktin;
3249
3250     pktin = ssh->s_rdpkt(ssh, data, datalen);
3251     if (pktin) {
3252         ssh->protocol(ssh, NULL, 0, pktin);
3253         ssh_free_packet(pktin);
3254     }
3255 }
3256
3257 static void ssh_queue_incoming_data(Ssh ssh,
3258                                     unsigned char **data, int *datalen)
3259 {
3260     bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3261     *data += *datalen;
3262     *datalen = 0;
3263 }
3264
3265 static void ssh_process_queued_incoming_data(Ssh ssh)
3266 {
3267     void *vdata;
3268     unsigned char *data;
3269     int len, origlen;
3270
3271     while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3272         bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3273         data = vdata;
3274         origlen = len;
3275
3276         while (!ssh->frozen && len > 0)
3277             ssh_process_incoming_data(ssh, &data, &len);
3278
3279         if (origlen > len)
3280             bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3281     }
3282 }
3283
3284 static void ssh_set_frozen(Ssh ssh, int frozen)
3285 {
3286     if (ssh->s)
3287         sk_set_frozen(ssh->s, frozen);
3288     ssh->frozen = frozen;
3289 }
3290
3291 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3292 {
3293     /* Log raw data, if we're in that mode. */
3294     if (ssh->logctx)
3295         log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3296                    0, NULL, NULL, 0, NULL);
3297
3298     crBegin(ssh->ssh_gotdata_crstate);
3299
3300     /*
3301      * To begin with, feed the characters one by one to the
3302      * protocol initialisation / selection function do_ssh_init().
3303      * When that returns 0, we're done with the initial greeting
3304      * exchange and can move on to packet discipline.
3305      */
3306     while (1) {
3307         int ret;                       /* need not be kept across crReturn */
3308         if (datalen == 0)
3309             crReturnV;                 /* more data please */
3310         ret = ssh->do_ssh_init(ssh, *data);
3311         data++;
3312         datalen--;
3313         if (ret == 0)
3314             break;
3315     }
3316
3317     /*
3318      * We emerge from that loop when the initial negotiation is
3319      * over and we have selected an s_rdpkt function. Now pass
3320      * everything to s_rdpkt, and then pass the resulting packets
3321      * to the proper protocol handler.
3322      */
3323
3324     while (1) {
3325         while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3326             if (ssh->frozen) {
3327                 ssh_queue_incoming_data(ssh, &data, &datalen);
3328                 /* This uses up all data and cannot cause anything interesting
3329                  * to happen; indeed, for anything to happen at all, we must
3330                  * return, so break out. */
3331                 break;
3332             } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3333                 /* This uses up some or all data, and may freeze the
3334                  * session. */
3335                 ssh_process_queued_incoming_data(ssh);
3336             } else {
3337                 /* This uses up some or all data, and may freeze the
3338                  * session. */
3339                 ssh_process_incoming_data(ssh, &data, &datalen);
3340             }
3341             /* FIXME this is probably EBW. */
3342             if (ssh->state == SSH_STATE_CLOSED)
3343                 return;
3344         }
3345         /* We're out of data. Go and get some more. */
3346         crReturnV;
3347     }
3348     crFinishV;
3349 }
3350
3351 static int ssh_do_close(Ssh ssh, int notify_exit)
3352 {
3353     int ret = 0;
3354     struct ssh_channel *c;
3355
3356     ssh->state = SSH_STATE_CLOSED;
3357     expire_timer_context(ssh);
3358     if (ssh->s) {
3359         sk_close(ssh->s);
3360         ssh->s = NULL;
3361         if (notify_exit)
3362             notify_remote_exit(ssh->frontend);
3363         else
3364             ret = 1;
3365     }
3366     /*
3367      * Now we must shut down any port- and X-forwarded channels going
3368      * through this connection.
3369      */
3370     if (ssh->channels) {
3371         while (NULL != (c = index234(ssh->channels, 0))) {
3372             switch (c->type) {
3373               case CHAN_X11:
3374                 x11_close(c->u.x11.xconn);
3375                 break;
3376               case CHAN_SOCKDATA:
3377               case CHAN_SOCKDATA_DORMANT:
3378                 pfd_close(c->u.pfd.pf);
3379                 break;
3380             }
3381             del234(ssh->channels, c); /* moving next one to index 0 */
3382             if (ssh->version == 2)
3383                 bufchain_clear(&c->v.v2.outbuffer);
3384             sfree(c);
3385         }
3386     }
3387     /*
3388      * Go through port-forwardings, and close any associated
3389      * listening sockets.
3390      */
3391     if (ssh->portfwds) {
3392         struct ssh_portfwd *pf;
3393         while (NULL != (pf = index234(ssh->portfwds, 0))) {
3394             /* Dispose of any listening socket. */
3395             if (pf->local)
3396                 pfl_terminate(pf->local);
3397             del234(ssh->portfwds, pf); /* moving next one to index 0 */
3398             free_portfwd(pf);
3399         }
3400         freetree234(ssh->portfwds);
3401         ssh->portfwds = NULL;
3402     }
3403
3404     /*
3405      * Also stop attempting to connection-share.
3406      */
3407     if (ssh->connshare) {
3408         sharestate_free(ssh->connshare);
3409         ssh->connshare = NULL;
3410     }
3411
3412     return ret;
3413 }
3414
3415 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3416                            const char *error_msg, int error_code)
3417 {
3418     Ssh ssh = (Ssh) plug;
3419     char addrbuf[256], *msg;
3420
3421     if (ssh->attempting_connshare) {
3422         /*
3423          * While we're attempting connection sharing, don't loudly log
3424          * everything that happens. Real TCP connections need to be
3425          * logged when we _start_ trying to connect, because it might
3426          * be ages before they respond if something goes wrong; but
3427          * connection sharing is local and quick to respond, and it's
3428          * sufficient to simply wait and see whether it worked
3429          * afterwards.
3430          */
3431     } else {
3432         sk_getaddr(addr, addrbuf, lenof(addrbuf));
3433
3434         if (type == 0) {
3435             if (sk_addr_needs_port(addr)) {
3436                 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3437             } else {
3438                 msg = dupprintf("Connecting to %s", addrbuf);
3439             }
3440         } else {
3441             msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3442         }
3443
3444         logevent(msg);
3445         sfree(msg);
3446     }
3447 }
3448
3449 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3450                        const char *ds_err, const char *us_err)
3451 {
3452     if (event == SHARE_NONE) {
3453         /* In this case, 'logtext' is an error message indicating a
3454          * reason why connection sharing couldn't be set up _at all_.
3455          * Failing that, ds_err and us_err indicate why we couldn't be
3456          * a downstream and an upstream respectively. */
3457         if (logtext) {
3458             logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3459         } else {
3460             if (ds_err)
3461                 logeventf(ssh, "Could not set up connection sharing"
3462                           " as downstream: %s", ds_err);
3463             if (us_err)
3464                 logeventf(ssh, "Could not set up connection sharing"
3465                           " as upstream: %s", us_err);
3466         }
3467     } else if (event == SHARE_DOWNSTREAM) {
3468         /* In this case, 'logtext' is a local endpoint address */
3469         logeventf(ssh, "Using existing shared connection at %s", logtext);
3470         /* Also we should mention this in the console window to avoid
3471          * confusing users as to why this window doesn't behave the
3472          * usual way. */
3473         if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3474             c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3475         }
3476     } else if (event == SHARE_UPSTREAM) {
3477         /* In this case, 'logtext' is a local endpoint address too */
3478         logeventf(ssh, "Sharing this connection at %s", logtext);
3479     }
3480 }
3481
3482 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3483                        int calling_back)
3484 {
3485     Ssh ssh = (Ssh) plug;
3486     int need_notify = ssh_do_close(ssh, FALSE);
3487
3488     if (!error_msg) {
3489         if (!ssh->close_expected)
3490             error_msg = "Server unexpectedly closed network connection";
3491         else
3492             error_msg = "Server closed network connection";
3493     }
3494
3495     if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3496         ssh->exitcode = 0;
3497
3498     if (need_notify)
3499         notify_remote_exit(ssh->frontend);
3500
3501     if (error_msg)
3502         logevent(error_msg);
3503     if (!ssh->close_expected || !ssh->clean_exit)
3504         connection_fatal(ssh->frontend, "%s", error_msg);
3505     return 0;
3506 }
3507
3508 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3509 {
3510     Ssh ssh = (Ssh) plug;
3511     ssh_gotdata(ssh, (unsigned char *)data, len);
3512     if (ssh->state == SSH_STATE_CLOSED) {
3513         ssh_do_close(ssh, TRUE);
3514         return 0;
3515     }
3516     return 1;
3517 }
3518
3519 static void ssh_sent(Plug plug, int bufsize)
3520 {
3521     Ssh ssh = (Ssh) plug;
3522     /*
3523      * If the send backlog on the SSH socket itself clears, we
3524      * should unthrottle the whole world if it was throttled.
3525      */
3526     if (bufsize < SSH_MAX_BACKLOG)
3527         ssh_throttle_all(ssh, 0, bufsize);
3528 }
3529
3530 /*
3531  * Connect to specified host and port.
3532  * Returns an error message, or NULL on success.
3533  * Also places the canonical host name into `realhost'. It must be
3534  * freed by the caller.
3535  */
3536 static const char *connect_to_host(Ssh ssh, char *host, int port,
3537                                    char **realhost, int nodelay, int keepalive)
3538 {
3539     static const struct plug_function_table fn_table = {
3540         ssh_socket_log,
3541         ssh_closing,
3542         ssh_receive,
3543         ssh_sent,
3544         NULL
3545     };
3546
3547     SockAddr addr;
3548     const char *err;
3549     char *loghost;
3550     int addressfamily, sshprot;
3551     
3552     loghost = conf_get_str(ssh->conf, CONF_loghost);
3553     if (*loghost) {
3554         char *tmphost;
3555         char *colon;
3556
3557         tmphost = dupstr(loghost);
3558         ssh->savedport = 22;           /* default ssh port */
3559
3560         /*
3561          * A colon suffix on the hostname string also lets us affect
3562          * savedport. (Unless there are multiple colons, in which case
3563          * we assume this is an unbracketed IPv6 literal.)
3564          */
3565         colon = host_strrchr(tmphost, ':');
3566         if (colon && colon == host_strchr(tmphost, ':')) {
3567             *colon++ = '\0';
3568             if (*colon)
3569                 ssh->savedport = atoi(colon);
3570         }
3571
3572         ssh->savedhost = host_strduptrim(tmphost);
3573         sfree(tmphost);
3574     } else {
3575         ssh->savedhost = host_strduptrim(host);
3576         if (port < 0)
3577             port = 22;                 /* default ssh port */
3578         ssh->savedport = port;
3579     }
3580
3581     ssh->fn = &fn_table;               /* make 'ssh' usable as a Plug */
3582
3583     /*
3584      * Try connection-sharing, in case that means we don't open a
3585      * socket after all. ssh_connection_sharing_init will connect to a
3586      * previously established upstream if it can, and failing that,
3587      * establish a listening socket for _us_ to be the upstream. In
3588      * the latter case it will return NULL just as if it had done
3589      * nothing, because here we only need to care if we're a
3590      * downstream and need to do our connection setup differently.
3591      */
3592     ssh->connshare = NULL;
3593     ssh->attempting_connshare = TRUE;  /* affects socket logging behaviour */
3594     ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3595                                          ssh->conf, ssh, &ssh->connshare);
3596     ssh->attempting_connshare = FALSE;
3597     if (ssh->s != NULL) {
3598         /*
3599          * We are a downstream.
3600          */
3601         ssh->bare_connection = TRUE;
3602         ssh->do_ssh_init = do_ssh_connection_init;
3603         ssh->fullhostname = NULL;
3604         *realhost = dupstr(host);      /* best we can do */
3605     } else {
3606         /*
3607          * We're not a downstream, so open a normal socket.
3608          */
3609         ssh->do_ssh_init = do_ssh_init;
3610
3611         /*
3612          * Try to find host.
3613          */
3614         addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3615         logeventf(ssh, "Looking up host \"%s\"%s", host,
3616                   (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3617                    (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3618         addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3619         if ((err = sk_addr_error(addr)) != NULL) {
3620             sk_addr_free(addr);
3621             return err;
3622         }
3623         ssh->fullhostname = dupstr(*realhost);   /* save in case of GSSAPI */
3624
3625         ssh->s = new_connection(addr, *realhost, port,
3626                                 0, 1, nodelay, keepalive,
3627                                 (Plug) ssh, ssh->conf);
3628         if ((err = sk_socket_error(ssh->s)) != NULL) {
3629             ssh->s = NULL;
3630             notify_remote_exit(ssh->frontend);
3631             return err;
3632         }
3633     }
3634
3635     /*
3636      * If the SSH version number's fixed, set it now, and if it's SSH-2,
3637      * send the version string too.
3638      */
3639     sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3640     if (sshprot == 0)
3641         ssh->version = 1;
3642     if (sshprot == 3 && !ssh->bare_connection) {
3643         ssh->version = 2;
3644         ssh_send_verstring(ssh, "SSH-", NULL);
3645     }
3646
3647     /*
3648      * loghost, if configured, overrides realhost.
3649      */
3650     if (*loghost) {
3651         sfree(*realhost);
3652         *realhost = dupstr(loghost);
3653     }
3654
3655     return NULL;
3656 }
3657
3658 /*
3659  * Throttle or unthrottle the SSH connection.
3660  */
3661 static void ssh_throttle_conn(Ssh ssh, int adjust)
3662 {
3663     int old_count = ssh->conn_throttle_count;
3664     ssh->conn_throttle_count += adjust;
3665     assert(ssh->conn_throttle_count >= 0);
3666     if (ssh->conn_throttle_count && !old_count) {
3667         ssh_set_frozen(ssh, 1);
3668     } else if (!ssh->conn_throttle_count && old_count) {
3669         ssh_set_frozen(ssh, 0);
3670     }
3671 }
3672
3673 /*
3674  * Throttle or unthrottle _all_ local data streams (for when sends
3675  * on the SSH connection itself back up).
3676  */
3677 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3678 {
3679     int i;
3680     struct ssh_channel *c;
3681
3682     if (enable == ssh->throttled_all)
3683         return;
3684     ssh->throttled_all = enable;
3685     ssh->overall_bufsize = bufsize;
3686     if (!ssh->channels)
3687         return;
3688     for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3689         switch (c->type) {
3690           case CHAN_MAINSESSION:
3691             /*
3692              * This is treated separately, outside the switch.
3693              */
3694             break;
3695           case CHAN_X11:
3696             x11_override_throttle(c->u.x11.xconn, enable);
3697             break;
3698           case CHAN_AGENT:
3699             /* Agent channels require no buffer management. */
3700             break;
3701           case CHAN_SOCKDATA:
3702             pfd_override_throttle(c->u.pfd.pf, enable);
3703             break;
3704         }
3705     }
3706 }
3707
3708 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3709 {
3710     Ssh ssh = (Ssh) sshv;
3711
3712     ssh->agent_response = reply;
3713     ssh->agent_response_len = replylen;
3714
3715     if (ssh->version == 1)
3716         do_ssh1_login(ssh, NULL, -1, NULL);
3717     else
3718         do_ssh2_authconn(ssh, NULL, -1, NULL);
3719 }
3720
3721 static void ssh_dialog_callback(void *sshv, int ret)
3722 {
3723     Ssh ssh = (Ssh) sshv;
3724
3725     ssh->user_response = ret;
3726
3727     if (ssh->version == 1)
3728         do_ssh1_login(ssh, NULL, -1, NULL);
3729     else
3730         do_ssh2_transport(ssh, NULL, -1, NULL);
3731
3732     /*
3733      * This may have unfrozen the SSH connection, so do a
3734      * queued-data run.
3735      */
3736     ssh_process_queued_incoming_data(ssh);
3737 }
3738
3739 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3740 {
3741     struct ssh_channel *c = (struct ssh_channel *)cv;
3742     Ssh ssh = c->ssh;
3743     void *sentreply = reply;
3744
3745     c->u.a.outstanding_requests--;
3746     if (!sentreply) {
3747         /* Fake SSH_AGENT_FAILURE. */
3748         sentreply = "\0\0\0\1\5";
3749         replylen = 5;
3750     }
3751     if (ssh->version == 2) {
3752         ssh2_add_channel_data(c, sentreply, replylen);
3753         ssh2_try_send(c);
3754     } else {
3755         send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3756                     PKT_INT, c->remoteid,
3757                     PKT_INT, replylen,
3758                     PKT_DATA, sentreply, replylen,
3759                     PKT_END);
3760     }
3761     if (reply)
3762         sfree(reply);
3763     /*
3764      * If we've already seen an incoming EOF but haven't sent an
3765      * outgoing one, this may be the moment to send it.
3766      */
3767     if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3768         sshfwd_write_eof(c);
3769 }
3770
3771 /*
3772  * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3773  * non-NULL, otherwise just close the connection. `client_reason' == NULL
3774  * => log `wire_reason'.
3775  */
3776 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3777                            int code, int clean_exit)
3778 {
3779     char *error;
3780     if (!client_reason)
3781         client_reason = wire_reason;
3782     if (client_reason)
3783         error = dupprintf("Disconnected: %s", client_reason);
3784     else
3785         error = dupstr("Disconnected");
3786     if (wire_reason) {
3787         if (ssh->version == 1) {
3788             send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3789                         PKT_END);
3790         } else if (ssh->version == 2) {
3791             struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3792             ssh2_pkt_adduint32(pktout, code);
3793             ssh2_pkt_addstring(pktout, wire_reason);
3794             ssh2_pkt_addstring(pktout, "en");   /* language tag */
3795             ssh2_pkt_send_noqueue(ssh, pktout);
3796         }
3797     }
3798     ssh->close_expected = TRUE;
3799     ssh->clean_exit = clean_exit;
3800     ssh_closing((Plug)ssh, error, 0, 0);
3801     sfree(error);
3802 }
3803
3804 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3805                                const struct ssh_signkey *ssh2keytype,
3806                                void *ssh2keydata)
3807 {
3808     if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3809         return -1;                     /* no manual keys configured */
3810     }
3811
3812     if (fingerprint) {
3813         /*
3814          * The fingerprint string we've been given will have things
3815          * like 'ssh-rsa 2048' at the front of it. Strip those off and
3816          * narrow down to just the colon-separated hex block at the
3817          * end of the string.
3818          */
3819         const char *p = strrchr(fingerprint, ' ');
3820         fingerprint = p ? p+1 : fingerprint;
3821         /* Quick sanity checks, including making sure it's in lowercase */
3822         assert(strlen(fingerprint) == 16*3 - 1);
3823         assert(fingerprint[2] == ':');
3824         assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3825
3826         if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3827                                  fingerprint))
3828             return 1;                  /* success */
3829     }
3830
3831     if (ssh2keydata) {
3832         /*
3833          * Construct the base64-encoded public key blob and see if
3834          * that's listed.
3835          */
3836         unsigned char *binblob;
3837         char *base64blob;
3838         int binlen, atoms, i;
3839         binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3840         atoms = (binlen + 2) / 3;
3841         base64blob = snewn(atoms * 4 + 1, char);
3842         for (i = 0; i < atoms; i++)
3843             base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3844         base64blob[atoms * 4] = '\0';
3845         sfree(binblob);
3846         if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3847                                  base64blob)) {
3848             sfree(base64blob);
3849             return 1;                  /* success */
3850         }
3851         sfree(base64blob);
3852     }
3853
3854     return 0;
3855 }
3856
3857 /*
3858  * Handle the key exchange and user authentication phases.
3859  */
3860 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3861                          struct Packet *pktin)
3862 {
3863     int i, j, ret;
3864     unsigned char cookie[8], *ptr;
3865     struct MD5Context md5c;
3866     struct do_ssh1_login_state {
3867         int crLine;
3868         int len;
3869         unsigned char *rsabuf;
3870         const unsigned char *keystr1, *keystr2;
3871         unsigned long supported_ciphers_mask, supported_auths_mask;
3872         int tried_publickey, tried_agent;
3873         int tis_auth_refused, ccard_auth_refused;
3874         unsigned char session_id[16];
3875         int cipher_type;
3876         void *publickey_blob;
3877         int publickey_bloblen;
3878         char *publickey_comment;
3879         int privatekey_available, privatekey_encrypted;
3880         prompts_t *cur_prompt;
3881         char c;
3882         int pwpkt_type;
3883         unsigned char request[5], *response, *p;
3884         int responselen;
3885         int keyi, nkeys;
3886         int authed;
3887         struct RSAKey key;
3888         Bignum challenge;
3889         char *commentp;
3890         int commentlen;
3891         int dlgret;
3892         Filename *keyfile;
3893         struct RSAKey servkey, hostkey;
3894     };
3895     crState(do_ssh1_login_state);
3896
3897     crBeginState;
3898
3899     if (!pktin)
3900         crWaitUntil(pktin);
3901
3902     if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3903         bombout(("Public key packet not received"));
3904         crStop(0);
3905     }
3906
3907     logevent("Received public keys");
3908
3909     ptr = ssh_pkt_getdata(pktin, 8);
3910     if (!ptr) {
3911         bombout(("SSH-1 public key packet stopped before random cookie"));
3912         crStop(0);
3913     }
3914     memcpy(cookie, ptr, 8);
3915
3916     if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3917         !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) { 
3918         bombout(("Failed to read SSH-1 public keys from public key packet"));
3919         crStop(0);
3920     }
3921
3922     /*
3923      * Log the host key fingerprint.
3924      */
3925     {
3926         char logmsg[80];
3927         logevent("Host key fingerprint is:");
3928         strcpy(logmsg, "      ");
3929         s->hostkey.comment = NULL;
3930         rsa_fingerprint(logmsg + strlen(logmsg),
3931                         sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3932         logevent(logmsg);
3933     }
3934
3935     ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3936     s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3937     s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3938     if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3939         s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3940
3941     ssh->v1_local_protoflags =
3942         ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3943     ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3944
3945     MD5Init(&md5c);
3946     MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3947     MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3948     MD5Update(&md5c, cookie, 8);
3949     MD5Final(s->session_id, &md5c);
3950
3951     for (i = 0; i < 32; i++)
3952         ssh->session_key[i] = random_byte();
3953
3954     /*
3955      * Verify that the `bits' and `bytes' parameters match.
3956      */
3957     if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3958         s->servkey.bits > s->servkey.bytes * 8) {
3959         bombout(("SSH-1 public keys were badly formatted"));
3960         crStop(0);
3961     }
3962
3963     s->len = (s->hostkey.bytes > s->servkey.bytes ?
3964               s->hostkey.bytes : s->servkey.bytes);
3965
3966     s->rsabuf = snewn(s->len, unsigned char);
3967
3968     /*
3969      * Verify the host key.
3970      */
3971     {
3972         /*
3973          * First format the key into a string.
3974          */
3975         int len = rsastr_len(&s->hostkey);
3976         char fingerprint[100];
3977         char *keystr = snewn(len, char);
3978         rsastr_fmt(keystr, &s->hostkey);
3979         rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3980
3981         /* First check against manually configured host keys. */
3982         s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3983         if (s->dlgret == 0) {          /* did not match */
3984             bombout(("Host key did not appear in manually configured list"));
3985             sfree(keystr);
3986             crStop(0);
3987         } else if (s->dlgret < 0) { /* none configured; use standard handling */
3988             ssh_set_frozen(ssh, 1);
3989             s->dlgret = verify_ssh_host_key(ssh->frontend,
3990                                             ssh->savedhost, ssh->savedport,
3991                                             "rsa", keystr, fingerprint,
3992                                             ssh_dialog_callback, ssh);
3993             sfree(keystr);
3994             if (s->dlgret < 0) {
3995                 do {
3996                     crReturn(0);
3997                     if (pktin) {
3998                         bombout(("Unexpected data from server while waiting"
3999                                  " for user host key response"));
4000                         crStop(0);
4001                     }
4002                 } while (pktin || inlen > 0);
4003                 s->dlgret = ssh->user_response;
4004             }
4005             ssh_set_frozen(ssh, 0);
4006
4007             if (s->dlgret == 0) {
4008                 ssh_disconnect(ssh, "User aborted at host key verification",
4009                                NULL, 0, TRUE);
4010                 crStop(0);
4011             }
4012         } else {
4013             sfree(keystr);
4014         }
4015     }
4016
4017     for (i = 0; i < 32; i++) {
4018         s->rsabuf[i] = ssh->session_key[i];
4019         if (i < 16)
4020             s->rsabuf[i] ^= s->session_id[i];
4021     }
4022
4023     if (s->hostkey.bytes > s->servkey.bytes) {
4024         ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4025         if (ret)
4026             ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4027     } else {
4028         ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4029         if (ret)
4030             ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4031     }
4032     if (!ret) {
4033         bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4034         crStop(0);      
4035     }
4036
4037     logevent("Encrypted session key");
4038
4039     {
4040         int cipher_chosen = 0, warn = 0;
4041         char *cipher_string = NULL;
4042         int i;
4043         for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4044             int next_cipher = conf_get_int_int(ssh->conf,
4045                                                CONF_ssh_cipherlist, i);
4046             if (next_cipher == CIPHER_WARN) {
4047                 /* If/when we choose a cipher, warn about it */
4048                 warn = 1;
4049             } else if (next_cipher == CIPHER_AES) {
4050                 /* XXX Probably don't need to mention this. */
4051                 logevent("AES not supported in SSH-1, skipping");
4052             } else {
4053                 switch (next_cipher) {
4054                   case CIPHER_3DES:     s->cipher_type = SSH_CIPHER_3DES;
4055                                         cipher_string = "3DES"; break;
4056                   case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4057                                         cipher_string = "Blowfish"; break;
4058                   case CIPHER_DES:      s->cipher_type = SSH_CIPHER_DES;
4059                                         cipher_string = "single-DES"; break;
4060                 }
4061                 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4062                     cipher_chosen = 1;
4063             }
4064         }
4065         if (!cipher_chosen) {
4066             if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4067                 bombout(("Server violates SSH-1 protocol by not "
4068                          "supporting 3DES encryption"));
4069             else
4070                 /* shouldn't happen */
4071                 bombout(("No supported ciphers found"));
4072             crStop(0);
4073         }
4074
4075         /* Warn about chosen cipher if necessary. */
4076         if (warn) {
4077             ssh_set_frozen(ssh, 1);
4078             s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4079                                ssh_dialog_callback, ssh);
4080             if (s->dlgret < 0) {
4081                 do {
4082                     crReturn(0);
4083                     if (pktin) {
4084                         bombout(("Unexpected data from server while waiting"
4085                                  " for user response"));
4086                         crStop(0);
4087                     }
4088                 } while (pktin || inlen > 0);
4089                 s->dlgret = ssh->user_response;
4090             }
4091             ssh_set_frozen(ssh, 0);
4092             if (s->dlgret == 0) {
4093                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4094                                0, TRUE);
4095                 crStop(0);
4096             }
4097         }
4098     }
4099
4100     switch (s->cipher_type) {
4101       case SSH_CIPHER_3DES:
4102         logevent("Using 3DES encryption");
4103         break;
4104       case SSH_CIPHER_DES:
4105         logevent("Using single-DES encryption");
4106         break;
4107       case SSH_CIPHER_BLOWFISH:
4108         logevent("Using Blowfish encryption");
4109         break;
4110     }
4111
4112     send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4113                 PKT_CHAR, s->cipher_type,
4114                 PKT_DATA, cookie, 8,
4115                 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4116                 PKT_DATA, s->rsabuf, s->len,
4117                 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4118
4119     logevent("Trying to enable encryption...");
4120
4121     sfree(s->rsabuf);
4122
4123     ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4124                    s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4125                    &ssh_3des);
4126     ssh->v1_cipher_ctx = ssh->cipher->make_context();
4127     ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4128     logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4129
4130     ssh->crcda_ctx = crcda_make_context();
4131     logevent("Installing CRC compensation attack detector");
4132
4133     if (s->servkey.modulus) {
4134         sfree(s->servkey.modulus);
4135         s->servkey.modulus = NULL;
4136     }
4137     if (s->servkey.exponent) {
4138         sfree(s->servkey.exponent);
4139         s->servkey.exponent = NULL;
4140     }
4141     if (s->hostkey.modulus) {
4142         sfree(s->hostkey.modulus);
4143         s->hostkey.modulus = NULL;
4144     }
4145     if (s->hostkey.exponent) {
4146         sfree(s->hostkey.exponent);
4147         s->hostkey.exponent = NULL;
4148     }
4149     crWaitUntil(pktin);
4150
4151     if (pktin->type != SSH1_SMSG_SUCCESS) {
4152         bombout(("Encryption not successfully enabled"));
4153         crStop(0);
4154     }
4155
4156     logevent("Successfully started encryption");
4157
4158     fflush(stdout); /* FIXME eh? */
4159     {
4160         if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4161             int ret; /* need not be kept over crReturn */
4162             s->cur_prompt = new_prompts(ssh->frontend);
4163             s->cur_prompt->to_server = TRUE;
4164             s->cur_prompt->name = dupstr("SSH login name");
4165             add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4166             ret = get_userpass_input(s->cur_prompt, NULL, 0);
4167             while (ret < 0) {
4168                 ssh->send_ok = 1;
4169                 crWaitUntil(!pktin);
4170                 ret = get_userpass_input(s->cur_prompt, in, inlen);
4171                 ssh->send_ok = 0;
4172             }
4173             if (!ret) {
4174                 /*
4175                  * Failed to get a username. Terminate.
4176                  */
4177                 free_prompts(s->cur_prompt);
4178                 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4179                 crStop(0);
4180             }
4181             ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4182             free_prompts(s->cur_prompt);
4183         }
4184
4185         send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4186         {
4187             char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4188             logevent(userlog);
4189             if (flags & FLAG_INTERACTIVE &&
4190                 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4191                 c_write_str(ssh, userlog);
4192                 c_write_str(ssh, "\r\n");
4193             }
4194             sfree(userlog);
4195         }
4196     }
4197
4198     crWaitUntil(pktin);
4199
4200     if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4201         /* We must not attempt PK auth. Pretend we've already tried it. */
4202         s->tried_publickey = s->tried_agent = 1;
4203     } else {
4204         s->tried_publickey = s->tried_agent = 0;
4205     }
4206     s->tis_auth_refused = s->ccard_auth_refused = 0;
4207     /*
4208      * Load the public half of any configured keyfile for later use.
4209      */
4210     s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4211     if (!filename_is_null(s->keyfile)) {
4212         int keytype;
4213         logeventf(ssh, "Reading key file \"%.150s\"",
4214                   filename_to_str(s->keyfile));
4215         keytype = key_type(s->keyfile);
4216         if (keytype == SSH_KEYTYPE_SSH1 ||
4217             keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4218             const char *error;
4219             if (rsakey_pubblob(s->keyfile,
4220                                &s->publickey_blob, &s->publickey_bloblen,
4221                                &s->publickey_comment, &error)) {
4222                 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4223                 if (!s->privatekey_available)
4224                     logeventf(ssh, "Key file contains public key only");
4225                 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4226                                                            NULL);
4227             } else {
4228                 char *msgbuf;
4229                 logeventf(ssh, "Unable to load key (%s)", error);
4230                 msgbuf = dupprintf("Unable to load key file "
4231                                    "\"%.150s\" (%s)\r\n",
4232                                    filename_to_str(s->keyfile),
4233                                    error);
4234                 c_write_str(ssh, msgbuf);
4235                 sfree(msgbuf);
4236                 s->publickey_blob = NULL;
4237             }
4238         } else {
4239             char *msgbuf;
4240             logeventf(ssh, "Unable to use this key file (%s)",
4241                       key_type_to_str(keytype));
4242             msgbuf = dupprintf("Unable to use key file \"%.150s\""
4243                                " (%s)\r\n",
4244                                filename_to_str(s->keyfile),
4245                                key_type_to_str(keytype));
4246             c_write_str(ssh, msgbuf);
4247             sfree(msgbuf);
4248             s->publickey_blob = NULL;
4249         }
4250     } else
4251         s->publickey_blob = NULL;
4252
4253     while (pktin->type == SSH1_SMSG_FAILURE) {
4254         s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4255
4256         if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4257             /*
4258              * Attempt RSA authentication using Pageant.
4259              */
4260             void *r;
4261
4262             s->authed = FALSE;
4263             s->tried_agent = 1;
4264             logevent("Pageant is running. Requesting keys.");
4265
4266             /* Request the keys held by the agent. */
4267             PUT_32BIT(s->request, 1);
4268             s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4269             if (!agent_query(s->request, 5, &r, &s->responselen,
4270                              ssh_agent_callback, ssh)) {
4271                 do {
4272                     crReturn(0);
4273                     if (pktin) {
4274                         bombout(("Unexpected data from server while waiting"
4275                                  " for agent response"));
4276                         crStop(0);
4277                     }
4278                 } while (pktin || inlen > 0);
4279                 r = ssh->agent_response;
4280                 s->responselen = ssh->agent_response_len;
4281             }
4282             s->response = (unsigned char *) r;
4283             if (s->response && s->responselen >= 5 &&
4284                 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4285                 s->p = s->response + 5;
4286                 s->nkeys = toint(GET_32BIT(s->p));
4287                 if (s->nkeys < 0) {
4288                     logeventf(ssh, "Pageant reported negative key count %d",
4289                               s->nkeys);
4290                     s->nkeys = 0;
4291                 }
4292                 s->p += 4;
4293                 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4294                 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4295                     unsigned char *pkblob = s->p;
4296                     s->p += 4;
4297                     {
4298                         int n, ok = FALSE;
4299                         do {           /* do while (0) to make breaking easy */
4300                             n = ssh1_read_bignum
4301                                 (s->p, toint(s->responselen-(s->p-s->response)),
4302                                  &s->key.exponent);
4303                             if (n < 0)
4304                                 break;
4305                             s->p += n;
4306                             n = ssh1_read_bignum
4307                                 (s->p, toint(s->responselen-(s->p-s->response)),
4308                                  &s->key.modulus);
4309                             if (n < 0)
4310                                 break;
4311                             s->p += n;
4312                             if (s->responselen - (s->p-s->response) < 4)
4313                                 break;
4314                             s->commentlen = toint(GET_32BIT(s->p));
4315                             s->p += 4;
4316                             if (s->commentlen < 0 ||
4317                                 toint(s->responselen - (s->p-s->response)) <
4318                                 s->commentlen)
4319                                 break;
4320                             s->commentp = (char *)s->p;
4321                             s->p += s->commentlen;
4322                             ok = TRUE;
4323                         } while (0);
4324                         if (!ok) {
4325                             logevent("Pageant key list packet was truncated");
4326                             break;
4327                         }
4328                     }
4329                     if (s->publickey_blob) {
4330                         if (!memcmp(pkblob, s->publickey_blob,
4331                                     s->publickey_bloblen)) {
4332                             logeventf(ssh, "Pageant key #%d matches "
4333                                       "configured key file", s->keyi);
4334                             s->tried_publickey = 1;
4335                         } else
4336                             /* Skip non-configured key */
4337                             continue;
4338                     }
4339                     logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4340                     send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4341                                 PKT_BIGNUM, s->key.modulus, PKT_END);
4342                     crWaitUntil(pktin);
4343                     if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4344                         logevent("Key refused");
4345                         continue;
4346                     }
4347                     logevent("Received RSA challenge");
4348                     if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4349                         bombout(("Server's RSA challenge was badly formatted"));
4350                         crStop(0);
4351                     }
4352
4353                     {
4354                         char *agentreq, *q, *ret;
4355                         void *vret;
4356                         int len, retlen;
4357                         len = 1 + 4;   /* message type, bit count */
4358                         len += ssh1_bignum_length(s->key.exponent);
4359                         len += ssh1_bignum_length(s->key.modulus);
4360                         len += ssh1_bignum_length(s->challenge);
4361                         len += 16;     /* session id */
4362                         len += 4;      /* response format */
4363                         agentreq = snewn(4 + len, char);
4364                         PUT_32BIT(agentreq, len);
4365                         q = agentreq + 4;
4366                         *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4367                         PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4368                         q += 4;
4369                         q += ssh1_write_bignum(q, s->key.exponent);
4370                         q += ssh1_write_bignum(q, s->key.modulus);
4371                         q += ssh1_write_bignum(q, s->challenge);
4372                         memcpy(q, s->session_id, 16);
4373                         q += 16;
4374                         PUT_32BIT(q, 1);        /* response format */
4375                         if (!agent_query(agentreq, len + 4, &vret, &retlen,
4376                                          ssh_agent_callback, ssh)) {
4377                             sfree(agentreq);
4378                             do {
4379                                 crReturn(0);
4380                                 if (pktin) {
4381                                     bombout(("Unexpected data from server"
4382                                              " while waiting for agent"
4383                                              " response"));
4384                                     crStop(0);
4385                                 }
4386                             } while (pktin || inlen > 0);
4387                             vret = ssh->agent_response;
4388                             retlen = ssh->agent_response_len;
4389                         } else
4390                             sfree(agentreq);
4391                         ret = vret;
4392                         if (ret) {
4393                             if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4394                                 logevent("Sending Pageant's response");
4395                                 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4396                                             PKT_DATA, ret + 5, 16,
4397                                             PKT_END);
4398                                 sfree(ret);
4399                                 crWaitUntil(pktin);
4400                                 if (pktin->type == SSH1_SMSG_SUCCESS) {
4401                                     logevent
4402                                         ("Pageant's response accepted");
4403                                     if (flags & FLAG_VERBOSE) {
4404                                         c_write_str(ssh, "Authenticated using"
4405                                                     " RSA key \"");
4406                                         c_write(ssh, s->commentp,
4407                                                 s->commentlen);
4408                                         c_write_str(ssh, "\" from agent\r\n");
4409                                     }
4410                                     s->authed = TRUE;
4411                                 } else
4412                                     logevent
4413                                         ("Pageant's response not accepted");
4414                             } else {
4415                                 logevent
4416                                     ("Pageant failed to answer challenge");
4417                                 sfree(ret);
4418                             }
4419                         } else {
4420                             logevent("No reply received from Pageant");
4421                         }
4422                     }
4423                     freebn(s->key.exponent);
4424                     freebn(s->key.modulus);
4425                     freebn(s->challenge);
4426                     if (s->authed)
4427                         break;
4428                 }
4429                 sfree(s->response);
4430                 if (s->publickey_blob && !s->tried_publickey)
4431                     logevent("Configured key file not in Pageant");
4432             } else {
4433                 logevent("Failed to get reply from Pageant");
4434             }
4435             if (s->authed)
4436                 break;
4437         }
4438         if (s->publickey_blob && s->privatekey_available &&
4439             !s->tried_publickey) {
4440             /*
4441              * Try public key authentication with the specified
4442              * key file.
4443              */
4444             int got_passphrase; /* need not be kept over crReturn */
4445             if (flags & FLAG_VERBOSE)
4446                 c_write_str(ssh, "Trying public key authentication.\r\n");
4447             s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4448             logeventf(ssh, "Trying public key \"%s\"",
4449                       filename_to_str(s->keyfile));
4450             s->tried_publickey = 1;
4451             got_passphrase = FALSE;
4452             while (!got_passphrase) {
4453                 /*
4454                  * Get a passphrase, if necessary.
4455                  */
4456                 char *passphrase = NULL;    /* only written after crReturn */
4457                 const char *error;
4458                 if (!s->privatekey_encrypted) {
4459                     if (flags & FLAG_VERBOSE)
4460                         c_write_str(ssh, "No passphrase required.\r\n");
4461                     passphrase = NULL;
4462                 } else {
4463                     int ret; /* need not be kept over crReturn */
4464                     s->cur_prompt = new_prompts(ssh->frontend);
4465                     s->cur_prompt->to_server = FALSE;
4466                     s->cur_prompt->name = dupstr("SSH key passphrase");
4467                     add_prompt(s->cur_prompt,
4468                                dupprintf("Passphrase for key \"%.100s\": ",
4469                                          s->publickey_comment), FALSE);
4470                     ret = get_userpass_input(s->cur_prompt, NULL, 0);
4471                     while (ret < 0) {
4472                         ssh->send_ok = 1;
4473                         crWaitUntil(!pktin);
4474                         ret = get_userpass_input(s->cur_prompt, in, inlen);
4475                         ssh->send_ok = 0;
4476                     }
4477                     if (!ret) {
4478                         /* Failed to get a passphrase. Terminate. */
4479                         free_prompts(s->cur_prompt);
4480                         ssh_disconnect(ssh, NULL, "Unable to authenticate",
4481                                        0, TRUE);
4482                         crStop(0);
4483                     }
4484                     passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4485                     free_prompts(s->cur_prompt);
4486                 }
4487                 /*
4488                  * Try decrypting key with passphrase.
4489                  */
4490                 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4491                 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4492                                  &error);
4493                 if (passphrase) {
4494                     smemclr(passphrase, strlen(passphrase));
4495                     sfree(passphrase);
4496                 }
4497                 if (ret == 1) {
4498                     /* Correct passphrase. */
4499                     got_passphrase = TRUE;
4500                 } else if (ret == 0) {
4501                     c_write_str(ssh, "Couldn't load private key from ");
4502                     c_write_str(ssh, filename_to_str(s->keyfile));
4503                     c_write_str(ssh, " (");
4504                     c_write_str(ssh, error);
4505                     c_write_str(ssh, ").\r\n");
4506                     got_passphrase = FALSE;
4507                     break;             /* go and try something else */
4508                 } else if (ret == -1) {
4509                     c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4510                     got_passphrase = FALSE;
4511                     /* and try again */
4512                 } else {
4513                     assert(0 && "unexpected return from loadrsakey()");
4514                     got_passphrase = FALSE;   /* placate optimisers */
4515                 }
4516             }
4517
4518             if (got_passphrase) {
4519
4520                 /*
4521                  * Send a public key attempt.
4522                  */
4523                 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4524                             PKT_BIGNUM, s->key.modulus, PKT_END);
4525
4526                 crWaitUntil(pktin);
4527                 if (pktin->type == SSH1_SMSG_FAILURE) {
4528                     c_write_str(ssh, "Server refused our public key.\r\n");
4529                     continue;          /* go and try something else */
4530                 }
4531                 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4532                     bombout(("Bizarre response to offer of public key"));
4533                     crStop(0);
4534                 }
4535
4536                 {
4537                     int i;
4538                     unsigned char buffer[32];
4539                     Bignum challenge, response;
4540
4541                     if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4542                         bombout(("Server's RSA challenge was badly formatted"));
4543                         crStop(0);
4544                     }
4545                     response = rsadecrypt(challenge, &s->key);
4546                     freebn(s->key.private_exponent);/* burn the evidence */
4547
4548                     for (i = 0; i < 32; i++) {
4549                         buffer[i] = bignum_byte(response, 31 - i);
4550                     }
4551
4552                     MD5Init(&md5c);
4553                     MD5Update(&md5c, buffer, 32);
4554                     MD5Update(&md5c, s->session_id, 16);
4555                     MD5Final(buffer, &md5c);
4556
4557                     send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4558                                 PKT_DATA, buffer, 16, PKT_END);
4559
4560                     freebn(challenge);
4561                     freebn(response);
4562                 }
4563
4564                 crWaitUntil(pktin);
4565                 if (pktin->type == SSH1_SMSG_FAILURE) {
4566                     if (flags & FLAG_VERBOSE)
4567                         c_write_str(ssh, "Failed to authenticate with"
4568                                     " our public key.\r\n");
4569                     continue;          /* go and try something else */
4570                 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4571                     bombout(("Bizarre response to RSA authentication response"));
4572                     crStop(0);
4573                 }
4574
4575                 break;                 /* we're through! */
4576             }
4577
4578         }
4579
4580         /*
4581          * Otherwise, try various forms of password-like authentication.
4582          */
4583         s->cur_prompt = new_prompts(ssh->frontend);
4584
4585         if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4586             (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4587             !s->tis_auth_refused) {
4588             s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4589             logevent("Requested TIS authentication");
4590             send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4591             crWaitUntil(pktin);
4592             if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4593                 logevent("TIS authentication declined");
4594                 if (flags & FLAG_INTERACTIVE)
4595                     c_write_str(ssh, "TIS authentication refused.\r\n");
4596                 s->tis_auth_refused = 1;
4597                 continue;
4598             } else {
4599                 char *challenge;
4600                 int challengelen;
4601                 char *instr_suf, *prompt;
4602
4603                 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4604                 if (!challenge) {
4605                     bombout(("TIS challenge packet was badly formed"));
4606                     crStop(0);
4607                 }
4608                 logevent("Received TIS challenge");
4609                 s->cur_prompt->to_server = TRUE;
4610                 s->cur_prompt->name = dupstr("SSH TIS authentication");
4611                 /* Prompt heuristic comes from OpenSSH */
4612                 if (memchr(challenge, '\n', challengelen)) {
4613                     instr_suf = dupstr("");
4614                     prompt = dupprintf("%.*s", challengelen, challenge);
4615                 } else {
4616                     instr_suf = dupprintf("%.*s", challengelen, challenge);
4617                     prompt = dupstr("Response: ");
4618                 }
4619                 s->cur_prompt->instruction =
4620                     dupprintf("Using TIS authentication.%s%s",
4621                               (*instr_suf) ? "\n" : "",
4622                               instr_suf);
4623                 s->cur_prompt->instr_reqd = TRUE;
4624                 add_prompt(s->cur_prompt, prompt, FALSE);
4625                 sfree(instr_suf);
4626             }
4627         }
4628         if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4629             (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4630             !s->ccard_auth_refused) {
4631             s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4632             logevent("Requested CryptoCard authentication");
4633             send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4634             crWaitUntil(pktin);
4635             if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4636                 logevent("CryptoCard authentication declined");
4637                 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4638                 s->ccard_auth_refused = 1;
4639                 continue;
4640             } else {
4641                 char *challenge;
4642                 int challengelen;
4643                 char *instr_suf, *prompt;
4644
4645                 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4646                 if (!challenge) {
4647                     bombout(("CryptoCard challenge packet was badly formed"));
4648                     crStop(0);
4649                 }
4650                 logevent("Received CryptoCard challenge");
4651                 s->cur_prompt->to_server = TRUE;
4652                 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4653                 s->cur_prompt->name_reqd = FALSE;
4654                 /* Prompt heuristic comes from OpenSSH */
4655                 if (memchr(challenge, '\n', challengelen)) {
4656                     instr_suf = dupstr("");
4657                     prompt = dupprintf("%.*s", challengelen, challenge);
4658                 } else {
4659                     instr_suf = dupprintf("%.*s", challengelen, challenge);
4660                     prompt = dupstr("Response: ");
4661                 }
4662                 s->cur_prompt->instruction =
4663                     dupprintf("Using CryptoCard authentication.%s%s",
4664                               (*instr_suf) ? "\n" : "",
4665                               instr_suf);
4666                 s->cur_prompt->instr_reqd = TRUE;
4667                 add_prompt(s->cur_prompt, prompt, FALSE);
4668                 sfree(instr_suf);
4669             }
4670         }
4671         if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4672             if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4673                 bombout(("No supported authentication methods available"));
4674                 crStop(0);
4675             }
4676             s->cur_prompt->to_server = TRUE;
4677             s->cur_prompt->name = dupstr("SSH password");
4678             add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4679                                                 ssh->username, ssh->savedhost),
4680                        FALSE);
4681         }
4682
4683         /*
4684          * Show password prompt, having first obtained it via a TIS
4685          * or CryptoCard exchange if we're doing TIS or CryptoCard
4686          * authentication.
4687          */
4688         {
4689             int ret; /* need not be kept over crReturn */
4690             ret = get_userpass_input(s->cur_prompt, NULL, 0);
4691             while (ret < 0) {
4692                 ssh->send_ok = 1;
4693                 crWaitUntil(!pktin);
4694                 ret = get_userpass_input(s->cur_prompt, in, inlen);
4695                 ssh->send_ok = 0;
4696             }
4697             if (!ret) {
4698                 /*
4699                  * Failed to get a password (for example
4700                  * because one was supplied on the command line
4701                  * which has already failed to work). Terminate.
4702                  */
4703                 free_prompts(s->cur_prompt);
4704                 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4705                 crStop(0);
4706             }
4707         }
4708
4709         if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4710             /*
4711              * Defence against traffic analysis: we send a
4712              * whole bunch of packets containing strings of
4713              * different lengths. One of these strings is the
4714              * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4715              * The others are all random data in
4716              * SSH1_MSG_IGNORE packets. This way a passive
4717              * listener can't tell which is the password, and
4718              * hence can't deduce the password length.
4719              * 
4720              * Anybody with a password length greater than 16
4721              * bytes is going to have enough entropy in their
4722              * password that a listener won't find it _that_
4723              * much help to know how long it is. So what we'll
4724              * do is:
4725              * 
4726              *  - if password length < 16, we send 15 packets
4727              *    containing string lengths 1 through 15
4728              * 
4729              *  - otherwise, we let N be the nearest multiple
4730              *    of 8 below the password length, and send 8
4731              *    packets containing string lengths N through
4732              *    N+7. This won't obscure the order of
4733              *    magnitude of the password length, but it will
4734              *    introduce a bit of extra uncertainty.
4735              * 
4736              * A few servers can't deal with SSH1_MSG_IGNORE, at
4737              * least in this context. For these servers, we need
4738              * an alternative defence. We make use of the fact
4739              * that the password is interpreted as a C string:
4740              * so we can append a NUL, then some random data.
4741              * 
4742              * A few servers can deal with neither SSH1_MSG_IGNORE
4743              * here _nor_ a padded password string.
4744              * For these servers we are left with no defences
4745              * against password length sniffing.
4746              */
4747             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4748                 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4749                 /*
4750                  * The server can deal with SSH1_MSG_IGNORE, so
4751                  * we can use the primary defence.
4752                  */
4753                 int bottom, top, pwlen, i;
4754                 char *randomstr;
4755
4756                 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4757                 if (pwlen < 16) {
4758                     bottom = 0;    /* zero length passwords are OK! :-) */
4759                     top = 15;
4760                 } else {
4761                     bottom = pwlen & ~7;
4762                     top = bottom + 7;
4763                 }
4764
4765                 assert(pwlen >= bottom && pwlen <= top);
4766
4767                 randomstr = snewn(top + 1, char);
4768
4769                 for (i = bottom; i <= top; i++) {
4770                     if (i == pwlen) {
4771                         defer_packet(ssh, s->pwpkt_type,
4772                                      PKT_STR,s->cur_prompt->prompts[0]->result,
4773                                      PKT_END);
4774                     } else {
4775                         for (j = 0; j < i; j++) {
4776                             do {
4777                                 randomstr[j] = random_byte();
4778                             } while (randomstr[j] == '\0');
4779                         }
4780                         randomstr[i] = '\0';
4781                         defer_packet(ssh, SSH1_MSG_IGNORE,
4782                                      PKT_STR, randomstr, PKT_END);
4783                     }
4784                 }
4785                 logevent("Sending password with camouflage packets");
4786                 ssh_pkt_defersend(ssh);
4787                 sfree(randomstr);
4788             } 
4789             else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4790                 /*
4791                  * The server can't deal with SSH1_MSG_IGNORE
4792                  * but can deal with padded passwords, so we
4793                  * can use the secondary defence.
4794                  */
4795                 char string[64];
4796                 char *ss;
4797                 int len;
4798
4799                 len = strlen(s->cur_prompt->prompts[0]->result);
4800                 if (len < sizeof(string)) {
4801                     ss = string;
4802                     strcpy(string, s->cur_prompt->prompts[0]->result);
4803                     len++;             /* cover the zero byte */
4804                     while (len < sizeof(string)) {
4805                         string[len++] = (char) random_byte();
4806                     }
4807                 } else {
4808                     ss = s->cur_prompt->prompts[0]->result;
4809                 }
4810                 logevent("Sending length-padded password");
4811                 send_packet(ssh, s->pwpkt_type,
4812                             PKT_INT, len, PKT_DATA, ss, len,
4813                             PKT_END);
4814             } else {
4815                 /*
4816                  * The server is believed unable to cope with
4817                  * any of our password camouflage methods.
4818                  */
4819                 int len;
4820                 len = strlen(s->cur_prompt->prompts[0]->result);
4821                 logevent("Sending unpadded password");
4822                 send_packet(ssh, s->pwpkt_type,
4823                             PKT_INT, len,
4824                             PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4825                             PKT_END);
4826             }
4827         } else {
4828             send_packet(ssh, s->pwpkt_type,
4829                         PKT_STR, s->cur_prompt->prompts[0]->result,
4830                         PKT_END);
4831         }
4832         logevent("Sent password");
4833         free_prompts(s->cur_prompt);
4834         crWaitUntil(pktin);
4835         if (pktin->type == SSH1_SMSG_FAILURE) {
4836             if (flags & FLAG_VERBOSE)
4837                 c_write_str(ssh, "Access denied\r\n");
4838             logevent("Authentication refused");
4839         } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4840             bombout(("Strange packet received, type %d", pktin->type));
4841             crStop(0);
4842         }
4843     }
4844
4845     /* Clear up */
4846     if (s->publickey_blob) {
4847         sfree(s->publickey_blob);
4848         sfree(s->publickey_comment);
4849     }
4850
4851     logevent("Authentication successful");
4852
4853     crFinish(1);
4854 }
4855
4856 static void ssh_channel_try_eof(struct ssh_channel *c)
4857 {
4858     Ssh ssh = c->ssh;
4859     assert(c->pending_eof);          /* precondition for calling us */
4860     if (c->halfopen)
4861         return;                 /* can't close: not even opened yet */
4862     if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4863         return;              /* can't send EOF: pending outgoing data */
4864
4865     c->pending_eof = FALSE;            /* we're about to send it */
4866     if (ssh->version == 1) {
4867         send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4868                     PKT_END);
4869         c->closes |= CLOSES_SENT_EOF;
4870     } else {
4871         struct Packet *pktout;
4872         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4873         ssh2_pkt_adduint32(pktout, c->remoteid);
4874         ssh2_pkt_send(ssh, pktout);
4875         c->closes |= CLOSES_SENT_EOF;
4876         ssh2_channel_check_close(c);
4877     }
4878 }
4879
4880 Conf *sshfwd_get_conf(struct ssh_channel *c)
4881 {
4882     Ssh ssh = c->ssh;
4883     return ssh->conf;
4884 }
4885
4886 void sshfwd_write_eof(struct ssh_channel *c)
4887 {
4888     Ssh ssh = c->ssh;
4889
4890     if (ssh->state == SSH_STATE_CLOSED)
4891         return;
4892
4893     if (c->closes & CLOSES_SENT_EOF)
4894         return;
4895
4896     c->pending_eof = TRUE;
4897     ssh_channel_try_eof(c);
4898 }
4899
4900 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4901 {
4902     Ssh ssh = c->ssh;
4903
4904     if (ssh->state == SSH_STATE_CLOSED)
4905         return;
4906
4907     switch (c->type) {
4908       case CHAN_X11:
4909         x11_close(c->u.x11.xconn);
4910         logeventf(ssh, "Forwarded X11 connection terminated due to local "
4911                   "error: %s", err);
4912         break;
4913       case CHAN_SOCKDATA:
4914       case CHAN_SOCKDATA_DORMANT:
4915         pfd_close(c->u.pfd.pf);
4916         logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4917         break;
4918     }
4919     c->type = CHAN_ZOMBIE;
4920     c->pending_eof = FALSE;   /* this will confuse a zombie channel */
4921
4922     ssh2_channel_check_close(c);
4923 }
4924
4925 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4926 {
4927     Ssh ssh = c->ssh;
4928
4929     if (ssh->state == SSH_STATE_CLOSED)
4930         return 0;
4931
4932     if (ssh->version == 1) {
4933         send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4934                     PKT_INT, c->remoteid,
4935                     PKT_INT, len, PKT_DATA, buf, len,
4936                     PKT_END);
4937         /*
4938          * In SSH-1 we can return 0 here - implying that forwarded
4939          * connections are never individually throttled - because
4940          * the only circumstance that can cause throttling will be
4941          * the whole SSH connection backing up, in which case
4942          * _everything_ will be throttled as a whole.
4943          */
4944         return 0;
4945     } else {
4946         ssh2_add_channel_data(c, buf, len);
4947         return ssh2_try_send(c);
4948     }
4949 }
4950
4951 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4952 {
4953     Ssh ssh = c->ssh;
4954     int buflimit;
4955
4956     if (ssh->state == SSH_STATE_CLOSED)
4957         return;
4958
4959     if (ssh->version == 1) {
4960         buflimit = SSH1_BUFFER_LIMIT;
4961     } else {
4962         buflimit = c->v.v2.locmaxwin;
4963         ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4964     }
4965     if (c->throttling_conn && bufsize <= buflimit) {
4966         c->throttling_conn = 0;
4967         ssh_throttle_conn(ssh, -1);
4968     }
4969 }
4970
4971 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4972 {
4973     struct queued_handler *qh = ssh->qhead;
4974
4975     assert(qh != NULL);
4976
4977     assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4978
4979     if (qh->msg1 > 0) {
4980         assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4981         ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4982     }
4983     if (qh->msg2 > 0) {
4984         assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4985         ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4986     }
4987
4988     if (qh->next) {
4989         ssh->qhead = qh->next;
4990
4991         if (ssh->qhead->msg1 > 0) {
4992             ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4993             ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4994         }
4995         if (ssh->qhead->msg2 > 0) {
4996             ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4997             ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4998         }
4999     } else {
5000         ssh->qhead = ssh->qtail = NULL;
5001     }
5002
5003     qh->handler(ssh, pktin, qh->ctx);
5004
5005     sfree(qh);
5006 }
5007
5008 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5009                               chandler_fn_t handler, void *ctx)
5010 {
5011     struct queued_handler *qh;
5012
5013     qh = snew(struct queued_handler);
5014     qh->msg1 = msg1;
5015     qh->msg2 = msg2;
5016     qh->handler = handler;
5017     qh->ctx = ctx;
5018     qh->next = NULL;
5019
5020     if (ssh->qtail == NULL) {
5021         ssh->qhead = qh;
5022
5023         if (qh->msg1 > 0) {
5024             ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5025             ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5026         }
5027         if (qh->msg2 > 0) {
5028             ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5029             ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5030         }
5031     } else {
5032         ssh->qtail->next = qh;
5033     }
5034     ssh->qtail = qh;
5035 }
5036
5037 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5038 {
5039     struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5040
5041     if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5042                         SSH2_MSG_REQUEST_SUCCESS)) {
5043         logeventf(ssh, "Remote port forwarding from %s enabled",
5044                   pf->sportdesc);
5045     } else {
5046         logeventf(ssh, "Remote port forwarding from %s refused",
5047                   pf->sportdesc);
5048
5049         rpf = del234(ssh->rportfwds, pf);
5050         assert(rpf == pf);
5051         pf->pfrec->remote = NULL;
5052         free_rportfwd(pf);
5053     }
5054 }
5055
5056 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5057                                void *share_ctx)
5058 {
5059     struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5060     pf->dhost = NULL;
5061     pf->dport = 0;
5062     pf->share_ctx = share_ctx;
5063     pf->shost = dupstr(shost);
5064     pf->sport = sport;
5065     pf->sportdesc = NULL;
5066     if (!ssh->rportfwds) {
5067         assert(ssh->version == 2);
5068         ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5069     }
5070     if (add234(ssh->rportfwds, pf) != pf) {
5071         sfree(pf->shost);
5072         sfree(pf);
5073         return FALSE;
5074     }
5075     return TRUE;
5076 }
5077
5078 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5079                                                 void *ctx)
5080 {
5081     share_got_pkt_from_server(ctx, pktin->type,
5082                               pktin->body, pktin->length);
5083 }
5084
5085 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5086 {
5087     ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5088                       ssh_sharing_global_request_response, share_ctx);
5089 }
5090
5091 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5092 {
5093     struct ssh_portfwd *epf;
5094     int i;
5095     char *key, *val;
5096
5097     if (!ssh->portfwds) {
5098         ssh->portfwds = newtree234(ssh_portcmp);
5099     } else {
5100         /*
5101          * Go through the existing port forwardings and tag them
5102          * with status==DESTROY. Any that we want to keep will be
5103          * re-enabled (status==KEEP) as we go through the
5104          * configuration and find out which bits are the same as
5105          * they were before.
5106          */
5107         struct ssh_portfwd *epf;
5108         int i;
5109         for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5110             epf->status = DESTROY;
5111     }
5112
5113     for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5114          val != NULL;
5115          val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5116         char *kp, *kp2, *vp, *vp2;
5117         char address_family, type;
5118         int sport,dport,sserv,dserv;
5119         char *sports, *dports, *saddr, *host;
5120
5121         kp = key;
5122
5123         address_family = 'A';
5124         type = 'L';
5125         if (*kp == 'A' || *kp == '4' || *kp == '6')
5126             address_family = *kp++;
5127         if (*kp == 'L' || *kp == 'R')
5128             type = *kp++;
5129
5130         if ((kp2 = host_strchr(kp, ':')) != NULL) {
5131             /*
5132              * There's a colon in the middle of the source port
5133              * string, which means that the part before it is
5134              * actually a source address.
5135              */
5136             char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5137             saddr = host_strduptrim(saddr_tmp);
5138             sfree(saddr_tmp);
5139             sports = kp2+1;
5140         } else {
5141             saddr = NULL;
5142             sports = kp;
5143         }
5144         sport = atoi(sports);
5145         sserv = 0;
5146         if (sport == 0) {
5147             sserv = 1;
5148             sport = net_service_lookup(sports);
5149             if (!sport) {
5150                 logeventf(ssh, "Service lookup failed for source"
5151                           " port \"%s\"", sports);
5152             }
5153         }
5154
5155         if (type == 'L' && !strcmp(val, "D")) {
5156             /* dynamic forwarding */
5157             host = NULL;
5158             dports = NULL;
5159             dport = -1;
5160             dserv = 0;
5161             type = 'D';
5162         } else {
5163             /* ordinary forwarding */
5164             vp = val;
5165             vp2 = vp + host_strcspn(vp, ":");
5166             host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5167             if (*vp2)
5168                 vp2++;
5169             dports = vp2;
5170             dport = atoi(dports);
5171             dserv = 0;
5172             if (dport == 0) {
5173                 dserv = 1;
5174                 dport = net_service_lookup(dports);
5175                 if (!dport) {
5176                     logeventf(ssh, "Service lookup failed for destination"
5177                               " port \"%s\"", dports);
5178                 }
5179             }
5180         }
5181
5182         if (sport && dport) {
5183             /* Set up a description of the source port. */
5184             struct ssh_portfwd *pfrec, *epfrec;
5185
5186             pfrec = snew(struct ssh_portfwd);
5187             pfrec->type = type;
5188             pfrec->saddr = saddr;
5189             pfrec->sserv = sserv ? dupstr(sports) : NULL;
5190             pfrec->sport = sport;
5191             pfrec->daddr = host;
5192             pfrec->dserv = dserv ? dupstr(dports) : NULL;
5193             pfrec->dport = dport;
5194             pfrec->local = NULL;
5195             pfrec->remote = NULL;
5196             pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5197                                     address_family == '6' ? ADDRTYPE_IPV6 :
5198                                     ADDRTYPE_UNSPEC);
5199
5200             epfrec = add234(ssh->portfwds, pfrec);
5201             if (epfrec != pfrec) {
5202                 if (epfrec->status == DESTROY) {
5203                     /*
5204                      * We already have a port forwarding up and running
5205                      * with precisely these parameters. Hence, no need
5206                      * to do anything; simply re-tag the existing one
5207                      * as KEEP.
5208                      */
5209                     epfrec->status = KEEP;
5210                 }
5211                 /*
5212                  * Anything else indicates that there was a duplicate
5213                  * in our input, which we'll silently ignore.
5214                  */
5215                 free_portfwd(pfrec);
5216             } else {
5217                 pfrec->status = CREATE;
5218             }
5219         } else {
5220             sfree(saddr);
5221             sfree(host);
5222         }
5223     }
5224
5225     /*
5226      * Now go through and destroy any port forwardings which were
5227      * not re-enabled.
5228      */
5229     for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5230         if (epf->status == DESTROY) {
5231             char *message;
5232
5233             message = dupprintf("%s port forwarding from %s%s%d",
5234                                 epf->type == 'L' ? "local" :
5235                                 epf->type == 'R' ? "remote" : "dynamic",
5236                                 epf->saddr ? epf->saddr : "",
5237                                 epf->saddr ? ":" : "",
5238                                 epf->sport);
5239
5240             if (epf->type != 'D') {
5241                 char *msg2 = dupprintf("%s to %s:%d", message,
5242                                        epf->daddr, epf->dport);
5243                 sfree(message);
5244                 message = msg2;
5245             }
5246
5247             logeventf(ssh, "Cancelling %s", message);
5248             sfree(message);
5249
5250             /* epf->remote or epf->local may be NULL if setting up a
5251              * forwarding failed. */
5252             if (epf->remote) {
5253                 struct ssh_rportfwd *rpf = epf->remote;
5254                 struct Packet *pktout;
5255
5256                 /*
5257                  * Cancel the port forwarding at the server
5258                  * end.
5259                  */
5260                 if (ssh->version == 1) {
5261                     /*
5262                      * We cannot cancel listening ports on the
5263                      * server side in SSH-1! There's no message
5264                      * to support it. Instead, we simply remove
5265                      * the rportfwd record from the local end
5266                      * so that any connections the server tries
5267                      * to make on it are rejected.
5268                      */
5269                 } else {
5270                     pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5271                     ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5272                     ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5273                     if (epf->saddr) {
5274                         ssh2_pkt_addstring(pktout, epf->saddr);
5275                     } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5276                         /* XXX: rport_acceptall may not represent
5277                          * what was used to open the original connection,
5278                          * since it's reconfigurable. */
5279                         ssh2_pkt_addstring(pktout, "");
5280                     } else {
5281                         ssh2_pkt_addstring(pktout, "localhost");
5282                     }
5283                     ssh2_pkt_adduint32(pktout, epf->sport);
5284                     ssh2_pkt_send(ssh, pktout);
5285                 }
5286
5287                 del234(ssh->rportfwds, rpf);
5288                 free_rportfwd(rpf);
5289             } else if (epf->local) {
5290                 pfl_terminate(epf->local);
5291             }
5292
5293             delpos234(ssh->portfwds, i);
5294             free_portfwd(epf);
5295             i--;                       /* so we don't skip one in the list */
5296         }
5297
5298     /*
5299      * And finally, set up any new port forwardings (status==CREATE).
5300      */
5301     for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5302         if (epf->status == CREATE) {
5303             char *sportdesc, *dportdesc;
5304             sportdesc = dupprintf("%s%s%s%s%d%s",
5305                                   epf->saddr ? epf->saddr : "",
5306                                   epf->saddr ? ":" : "",
5307                                   epf->sserv ? epf->sserv : "",
5308                                   epf->sserv ? "(" : "",
5309                                   epf->sport,
5310                                   epf->sserv ? ")" : "");
5311             if (epf->type == 'D') {
5312                 dportdesc = NULL;
5313             } else {
5314                 dportdesc = dupprintf("%s:%s%s%d%s",
5315                                       epf->daddr,
5316                                       epf->dserv ? epf->dserv : "",
5317                                       epf->dserv ? "(" : "",
5318                                       epf->dport,
5319                                       epf->dserv ? ")" : "");
5320             }
5321
5322             if (epf->type == 'L') {
5323                 char *err = pfl_listen(epf->daddr, epf->dport,
5324                                        epf->saddr, epf->sport,
5325                                        ssh, conf, &epf->local,
5326                                        epf->addressfamily);
5327
5328                 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5329                           epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5330                           epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5331                           sportdesc, dportdesc,
5332                           err ? " failed: " : "", err ? err : "");
5333                 if (err)
5334                     sfree(err);
5335             } else if (epf->type == 'D') {
5336                 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5337                                        ssh, conf, &epf->local,
5338                                        epf->addressfamily);
5339
5340                 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5341                           epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5342                           epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5343                           sportdesc,
5344                           err ? " failed: " : "", err ? err : "");
5345
5346                 if (err)
5347                     sfree(err);
5348             } else {
5349                 struct ssh_rportfwd *pf;
5350
5351                 /*
5352                  * Ensure the remote port forwardings tree exists.
5353                  */
5354                 if (!ssh->rportfwds) {
5355                     if (ssh->version == 1)
5356                         ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5357                     else
5358                         ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5359                 }
5360
5361                 pf = snew(struct ssh_rportfwd);
5362                 pf->share_ctx = NULL;
5363                 pf->dhost = dupstr(epf->daddr);
5364                 pf->dport = epf->dport;
5365                 if (epf->saddr) {
5366                     pf->shost = dupstr(epf->saddr);
5367                 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5368                     pf->shost = dupstr("");
5369                 } else {
5370                     pf->shost = dupstr("localhost");
5371                 }
5372                 pf->sport = epf->sport;
5373                 if (add234(ssh->rportfwds, pf) != pf) {
5374                     logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5375                               epf->daddr, epf->dport);
5376                     sfree(pf);
5377                 } else {
5378                     logeventf(ssh, "Requesting remote port %s"
5379                               " forward to %s", sportdesc, dportdesc);
5380
5381                     pf->sportdesc = sportdesc;
5382                     sportdesc = NULL;
5383                     epf->remote = pf;
5384                     pf->pfrec = epf;
5385
5386                     if (ssh->version == 1) {
5387                         send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5388                                     PKT_INT, epf->sport,
5389                                     PKT_STR, epf->daddr,
5390                                     PKT_INT, epf->dport,
5391                                     PKT_END);
5392                         ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5393                                           SSH1_SMSG_FAILURE,
5394                                           ssh_rportfwd_succfail, pf);
5395                     } else {
5396                         struct Packet *pktout;
5397                         pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5398                         ssh2_pkt_addstring(pktout, "tcpip-forward");
5399                         ssh2_pkt_addbool(pktout, 1);/* want reply */
5400                         ssh2_pkt_addstring(pktout, pf->shost);
5401                         ssh2_pkt_adduint32(pktout, pf->sport);
5402                         ssh2_pkt_send(ssh, pktout);
5403
5404                         ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5405                                           SSH2_MSG_REQUEST_FAILURE,
5406                                           ssh_rportfwd_succfail, pf);
5407                     }
5408                 }
5409             }
5410             sfree(sportdesc);
5411             sfree(dportdesc);
5412         }
5413 }
5414
5415 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5416 {
5417     char *string;
5418     int stringlen, bufsize;
5419
5420     ssh_pkt_getstring(pktin, &string, &stringlen);
5421     if (string == NULL) {
5422         bombout(("Incoming terminal data packet was badly formed"));
5423         return;
5424     }
5425
5426     bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5427                            string, stringlen);
5428     if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5429         ssh->v1_stdout_throttling = 1;
5430         ssh_throttle_conn(ssh, +1);
5431     }
5432 }
5433
5434 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5435 {
5436     /* Remote side is trying to open a channel to talk to our
5437      * X-Server. Give them back a local channel number. */
5438     struct ssh_channel *c;
5439     int remoteid = ssh_pkt_getuint32(pktin);
5440
5441     logevent("Received X11 connect request");
5442     /* Refuse if X11 forwarding is disabled. */
5443     if (!ssh->X11_fwd_enabled) {
5444         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5445                     PKT_INT, remoteid, PKT_END);
5446         logevent("Rejected X11 connect request");
5447     } else {
5448         c = snew(struct ssh_channel);
5449         c->ssh = ssh;
5450
5451         c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5452         c->remoteid = remoteid;
5453         c->halfopen = FALSE;
5454         c->localid = alloc_channel_id(ssh);
5455         c->closes = 0;
5456         c->pending_eof = FALSE;
5457         c->throttling_conn = 0;
5458         c->type = CHAN_X11;     /* identify channel type */
5459         add234(ssh->channels, c);
5460         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5461                     PKT_INT, c->remoteid, PKT_INT,
5462                     c->localid, PKT_END);
5463         logevent("Opened X11 forward channel");
5464     }
5465 }
5466
5467 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5468 {
5469     /* Remote side is trying to open a channel to talk to our
5470      * agent. Give them back a local channel number. */
5471     struct ssh_channel *c;
5472     int remoteid = ssh_pkt_getuint32(pktin);
5473
5474     /* Refuse if agent forwarding is disabled. */
5475     if (!ssh->agentfwd_enabled) {
5476         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5477                     PKT_INT, remoteid, PKT_END);
5478     } else {
5479         c = snew(struct ssh_channel);
5480         c->ssh = ssh;
5481         c->remoteid = remoteid;
5482         c->halfopen = FALSE;
5483         c->localid = alloc_channel_id(ssh);
5484         c->closes = 0;
5485         c->pending_eof = FALSE;
5486         c->throttling_conn = 0;
5487         c->type = CHAN_AGENT;   /* identify channel type */
5488         c->u.a.lensofar = 0;
5489         c->u.a.message = NULL;
5490         c->u.a.outstanding_requests = 0;
5491         add234(ssh->channels, c);
5492         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5493                     PKT_INT, c->remoteid, PKT_INT, c->localid,
5494                     PKT_END);
5495     }
5496 }
5497
5498 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5499 {
5500     /* Remote side is trying to open a channel to talk to a
5501      * forwarded port. Give them back a local channel number. */
5502     struct ssh_rportfwd pf, *pfp;
5503     int remoteid;
5504     int hostsize, port;
5505     char *host;
5506     char *err;
5507
5508     remoteid = ssh_pkt_getuint32(pktin);
5509     ssh_pkt_getstring(pktin, &host, &hostsize);
5510     port = ssh_pkt_getuint32(pktin);
5511
5512     pf.dhost = dupprintf("%.*s", hostsize, host);
5513     pf.dport = port;
5514     pfp = find234(ssh->rportfwds, &pf, NULL);
5515
5516     if (pfp == NULL) {
5517         logeventf(ssh, "Rejected remote port open request for %s:%d",
5518                   pf.dhost, port);
5519         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5520                     PKT_INT, remoteid, PKT_END);
5521     } else {
5522         struct ssh_channel *c = snew(struct ssh_channel);
5523         c->ssh = ssh;
5524
5525         logeventf(ssh, "Received remote port open request for %s:%d",
5526                   pf.dhost, port);
5527         err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5528                           c, ssh->conf, pfp->pfrec->addressfamily);
5529         if (err != NULL) {
5530             logeventf(ssh, "Port open failed: %s", err);
5531             sfree(err);
5532             sfree(c);
5533             send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5534                         PKT_INT, remoteid, PKT_END);
5535         } else {
5536             c->remoteid = remoteid;
5537             c->halfopen = FALSE;
5538             c->localid = alloc_channel_id(ssh);
5539             c->closes = 0;
5540             c->pending_eof = FALSE;
5541             c->throttling_conn = 0;
5542             c->type = CHAN_SOCKDATA;    /* identify channel type */
5543             add234(ssh->channels, c);
5544             send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5545                         PKT_INT, c->remoteid, PKT_INT,
5546                         c->localid, PKT_END);
5547             logevent("Forwarded port opened successfully");
5548         }
5549     }
5550
5551     sfree(pf.dhost);
5552 }
5553
5554 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5555 {
5556     unsigned int remoteid = ssh_pkt_getuint32(pktin);
5557     unsigned int localid = ssh_pkt_getuint32(pktin);
5558     struct ssh_channel *c;
5559
5560     c = find234(ssh->channels, &remoteid, ssh_channelfind);
5561     if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5562         c->remoteid = localid;
5563         c->halfopen = FALSE;
5564         c->type = CHAN_SOCKDATA;
5565         c->throttling_conn = 0;
5566         pfd_confirm(c->u.pfd.pf);
5567     }
5568
5569     if (c && c->pending_eof) {
5570         /*
5571          * We have a pending close on this channel,
5572          * which we decided on before the server acked
5573          * the channel open. So now we know the
5574          * remoteid, we can close it again.
5575          */
5576         ssh_channel_try_eof(c);
5577     }
5578 }
5579
5580 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5581 {
5582     unsigned int remoteid = ssh_pkt_getuint32(pktin);
5583     struct ssh_channel *c;
5584
5585     c = find234(ssh->channels, &remoteid, ssh_channelfind);
5586     if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5587         logevent("Forwarded connection refused by server");
5588         pfd_close(c->u.pfd.pf);
5589         del234(ssh->channels, c);
5590         sfree(c);
5591     }
5592 }
5593
5594 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5595 {
5596     /* Remote side closes a channel. */
5597     unsigned i = ssh_pkt_getuint32(pktin);
5598     struct ssh_channel *c;
5599     c = find234(ssh->channels, &i, ssh_channelfind);
5600     if (c && !c->halfopen) {
5601
5602         if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5603             !(c->closes & CLOSES_RCVD_EOF)) {
5604             /*
5605              * Received CHANNEL_CLOSE, which we translate into
5606              * outgoing EOF.
5607              */
5608             int send_close = FALSE;
5609
5610             c->closes |= CLOSES_RCVD_EOF;
5611
5612             switch (c->type) {
5613               case CHAN_X11:
5614                 if (c->u.x11.xconn)
5615                     x11_send_eof(c->u.x11.xconn);
5616                 else
5617                     send_close = TRUE;
5618                 break;
5619               case CHAN_SOCKDATA:
5620                 if (c->u.pfd.pf)
5621                     pfd_send_eof(c->u.pfd.pf);
5622                 else
5623                     send_close = TRUE;
5624                 break;
5625               case CHAN_AGENT:
5626                 send_close = TRUE;
5627                 break;
5628             }
5629
5630             if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5631                 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5632                             PKT_END);
5633                 c->closes |= CLOSES_SENT_EOF;
5634             }
5635         }
5636
5637         if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5638             !(c->closes & CLOSES_RCVD_CLOSE)) {
5639
5640             if (!(c->closes & CLOSES_SENT_EOF)) {
5641                 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5642                          " for which we never sent CHANNEL_CLOSE\n", i));
5643             }
5644
5645             c->closes |= CLOSES_RCVD_CLOSE;
5646         }
5647
5648         if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5649             !(c->closes & CLOSES_SENT_CLOSE)) {
5650             send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5651                         PKT_INT, c->remoteid, PKT_END);
5652             c->closes |= CLOSES_SENT_CLOSE;
5653         }
5654
5655         if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5656             ssh_channel_destroy(c);
5657     } else {
5658         bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5659                  pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5660                  "_CONFIRMATION", c ? "half-open" : "nonexistent",
5661                  i));
5662     }
5663 }
5664
5665 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5666 {
5667     /* Data sent down one of our channels. */
5668     int i = ssh_pkt_getuint32(pktin);
5669     char *p;
5670     int len;
5671     struct ssh_channel *c;
5672
5673     ssh_pkt_getstring(pktin, &p, &len);
5674
5675     c = find234(ssh->channels, &i, ssh_channelfind);
5676     if (c) {
5677         int bufsize = 0;
5678         switch (c->type) {
5679           case CHAN_X11:
5680             bufsize = x11_send(c->u.x11.xconn, p, len);
5681             break;
5682           case CHAN_SOCKDATA:
5683             bufsize = pfd_send(c->u.pfd.pf, p, len);
5684             break;
5685           case CHAN_AGENT:
5686             /* Data for an agent message. Buffer it. */
5687             while (len > 0) {
5688                 if (c->u.a.lensofar < 4) {
5689                     unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5690                     memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5691                            l);
5692                     p += l;
5693                     len -= l;
5694                     c->u.a.lensofar += l;
5695                 }
5696                 if (c->u.a.lensofar == 4) {
5697                     c->u.a.totallen =
5698                         4 + GET_32BIT(c->u.a.msglen);
5699                     c->u.a.message = snewn(c->u.a.totallen,
5700                                            unsigned char);
5701                     memcpy(c->u.a.message, c->u.a.msglen, 4);
5702                 }
5703                 if (c->u.a.lensofar >= 4 && len > 0) {
5704                     unsigned int l =
5705                         min(c->u.a.totallen - c->u.a.lensofar,
5706                             (unsigned)len);
5707                     memcpy(c->u.a.message + c->u.a.lensofar, p,
5708                            l);
5709                     p += l;
5710                     len -= l;
5711                     c->u.a.lensofar += l;
5712                 }
5713                 if (c->u.a.lensofar == c->u.a.totallen) {
5714                     void *reply;
5715                     int replylen;
5716                     c->u.a.outstanding_requests++;
5717                     if (agent_query(c->u.a.message,
5718                                     c->u.a.totallen,
5719                                     &reply, &replylen,
5720                                     ssh_agentf_callback, c))
5721                         ssh_agentf_callback(c, reply, replylen);
5722                     sfree(c->u.a.message);
5723                     c->u.a.lensofar = 0;
5724                 }
5725             }
5726             bufsize = 0;   /* agent channels never back up */
5727             break;
5728         }
5729         if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5730             c->throttling_conn = 1;
5731             ssh_throttle_conn(ssh, +1);
5732         }
5733     }
5734 }
5735
5736 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5737 {
5738     ssh->exitcode = ssh_pkt_getuint32(pktin);
5739     logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5740     send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5741     /*
5742      * In case `helpful' firewalls or proxies tack
5743      * extra human-readable text on the end of the
5744      * session which we might mistake for another
5745      * encrypted packet, we close the session once
5746      * we've sent EXIT_CONFIRMATION.
5747      */
5748     ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5749 }
5750
5751 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5752 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5753 {
5754     struct Packet *pktout = (struct Packet *)data;
5755     int i = 0;
5756     unsigned int arg = 0;
5757     while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5758     if (i == lenof(ssh_ttymodes)) return;
5759     switch (ssh_ttymodes[i].type) {
5760       case TTY_OP_CHAR:
5761         arg = ssh_tty_parse_specchar(val);
5762         break;
5763       case TTY_OP_BOOL:
5764         arg = ssh_tty_parse_boolean(val);
5765         break;
5766     }
5767     ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5768     ssh2_pkt_addbyte(pktout, arg);
5769 }
5770
5771 int ssh_agent_forwarding_permitted(Ssh ssh)
5772 {
5773     return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5774 }
5775
5776 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5777                                struct Packet *pktin)
5778 {
5779     crBegin(ssh->do_ssh1_connection_crstate);
5780
5781     ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] = 
5782         ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5783         ssh1_smsg_stdout_stderr_data;
5784
5785     ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5786         ssh1_msg_channel_open_confirmation;
5787     ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5788         ssh1_msg_channel_open_failure;
5789     ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5790         ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5791         ssh1_msg_channel_close;
5792     ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5793     ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5794
5795     if (ssh_agent_forwarding_permitted(ssh)) {
5796         logevent("Requesting agent forwarding");
5797         send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5798         do {
5799             crReturnV;
5800         } while (!pktin);
5801         if (pktin->type != SSH1_SMSG_SUCCESS
5802             && pktin->type != SSH1_SMSG_FAILURE) {
5803             bombout(("Protocol confusion"));
5804             crStopV;
5805         } else if (pktin->type == SSH1_SMSG_FAILURE) {
5806             logevent("Agent forwarding refused");
5807         } else {
5808             logevent("Agent forwarding enabled");
5809             ssh->agentfwd_enabled = TRUE;
5810             ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5811         }
5812     }
5813
5814     if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5815         ssh->x11disp =
5816             x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5817                               ssh->conf);
5818         if (!ssh->x11disp) {
5819             /* FIXME: return an error message from x11_setup_display */
5820             logevent("X11 forwarding not enabled: unable to"
5821                      " initialise X display");
5822         } else {
5823             ssh->x11auth = x11_invent_fake_auth
5824                 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5825             ssh->x11auth->disp = ssh->x11disp;
5826
5827             logevent("Requesting X11 forwarding");
5828             if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5829                 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5830                             PKT_STR, ssh->x11auth->protoname,
5831                             PKT_STR, ssh->x11auth->datastring,
5832                             PKT_INT, ssh->x11disp->screennum,
5833                             PKT_END);
5834             } else {
5835                 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5836                             PKT_STR, ssh->x11auth->protoname,
5837                             PKT_STR, ssh->x11auth->datastring,
5838                             PKT_END);
5839             }
5840             do {
5841                 crReturnV;
5842             } while (!pktin);
5843             if (pktin->type != SSH1_SMSG_SUCCESS
5844                 && pktin->type != SSH1_SMSG_FAILURE) {
5845                 bombout(("Protocol confusion"));
5846                 crStopV;
5847             } else if (pktin->type == SSH1_SMSG_FAILURE) {
5848                 logevent("X11 forwarding refused");
5849             } else {
5850                 logevent("X11 forwarding enabled");
5851                 ssh->X11_fwd_enabled = TRUE;
5852                 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5853             }
5854         }
5855     }
5856
5857     ssh_setup_portfwd(ssh, ssh->conf);
5858     ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5859
5860     if (!conf_get_int(ssh->conf, CONF_nopty)) {
5861         struct Packet *pkt;
5862         /* Unpick the terminal-speed string. */
5863         /* XXX perhaps we should allow no speeds to be sent. */
5864         ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5865         sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5866         /* Send the pty request. */
5867         pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5868         ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5869         ssh_pkt_adduint32(pkt, ssh->term_height);
5870         ssh_pkt_adduint32(pkt, ssh->term_width);
5871         ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5872         ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5873         parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5874         ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5875         ssh_pkt_adduint32(pkt, ssh->ispeed);
5876         ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5877         ssh_pkt_adduint32(pkt, ssh->ospeed);
5878         ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5879         s_wrpkt(ssh, pkt);
5880         ssh->state = SSH_STATE_INTERMED;
5881         do {
5882             crReturnV;
5883         } while (!pktin);
5884         if (pktin->type != SSH1_SMSG_SUCCESS
5885             && pktin->type != SSH1_SMSG_FAILURE) {
5886             bombout(("Protocol confusion"));
5887             crStopV;
5888         } else if (pktin->type == SSH1_SMSG_FAILURE) {
5889             c_write_str(ssh, "Server refused to allocate pty\r\n");
5890             ssh->editing = ssh->echoing = 1;
5891         } else {
5892             logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5893                       ssh->ospeed, ssh->ispeed);
5894             ssh->got_pty = TRUE;
5895         }
5896     } else {
5897         ssh->editing = ssh->echoing = 1;
5898     }
5899
5900     if (conf_get_int(ssh->conf, CONF_compression)) {
5901         send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5902         do {
5903             crReturnV;
5904         } while (!pktin);
5905         if (pktin->type != SSH1_SMSG_SUCCESS
5906             && pktin->type != SSH1_SMSG_FAILURE) {
5907             bombout(("Protocol confusion"));
5908             crStopV;
5909         } else if (pktin->type == SSH1_SMSG_FAILURE) {
5910             c_write_str(ssh, "Server refused to compress\r\n");
5911         }
5912         logevent("Started compression");
5913         ssh->v1_compressing = TRUE;
5914         ssh->cs_comp_ctx = zlib_compress_init();
5915         logevent("Initialised zlib (RFC1950) compression");
5916         ssh->sc_comp_ctx = zlib_decompress_init();
5917         logevent("Initialised zlib (RFC1950) decompression");
5918     }
5919
5920     /*
5921      * Start the shell or command.
5922      * 
5923      * Special case: if the first-choice command is an SSH-2
5924      * subsystem (hence not usable here) and the second choice
5925      * exists, we fall straight back to that.
5926      */
5927     {
5928         char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5929         
5930         if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5931             conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5932             cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5933             ssh->fallback_cmd = TRUE;
5934         }
5935         if (*cmd)
5936             send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5937         else
5938             send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5939         logevent("Started session");
5940     }
5941
5942     ssh->state = SSH_STATE_SESSION;
5943     if (ssh->size_needed)
5944         ssh_size(ssh, ssh->term_width, ssh->term_height);
5945     if (ssh->eof_needed)
5946         ssh_special(ssh, TS_EOF);
5947
5948     if (ssh->ldisc)
5949         ldisc_echoedit_update(ssh->ldisc);  /* cause ldisc to notice changes */
5950     ssh->send_ok = 1;
5951     ssh->channels = newtree234(ssh_channelcmp);
5952     while (1) {
5953
5954         /*
5955          * By this point, most incoming packets are already being
5956          * handled by the dispatch table, and we need only pay
5957          * attention to the unusual ones.
5958          */
5959
5960         crReturnV;
5961         if (pktin) {
5962             if (pktin->type == SSH1_SMSG_SUCCESS) {
5963                 /* may be from EXEC_SHELL on some servers */
5964             } else if (pktin->type == SSH1_SMSG_FAILURE) {
5965                 /* may be from EXEC_SHELL on some servers
5966                  * if no pty is available or in other odd cases. Ignore */
5967             } else {
5968                 bombout(("Strange packet received: type %d", pktin->type));
5969                 crStopV;
5970             }
5971         } else {
5972             while (inlen > 0) {
5973                 int len = min(inlen, 512);
5974                 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5975                             PKT_INT, len, PKT_DATA, in, len,
5976                             PKT_END);
5977                 in += len;
5978                 inlen -= len;
5979             }
5980         }
5981     }
5982
5983     crFinishV;
5984 }
5985
5986 /*
5987  * Handle the top-level SSH-2 protocol.
5988  */
5989 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5990 {
5991     char *msg;
5992     int msglen;
5993
5994     ssh_pkt_getstring(pktin, &msg, &msglen);
5995     logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5996 }
5997
5998 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5999 {
6000     /* log reason code in disconnect message */
6001     char *msg;
6002     int msglen;
6003
6004     ssh_pkt_getstring(pktin, &msg, &msglen);
6005     bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
6006 }
6007
6008 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6009 {
6010     /* Do nothing, because we're ignoring it! Duhh. */
6011 }
6012
6013 static void ssh1_protocol_setup(Ssh ssh)
6014 {
6015     int i;
6016
6017     /*
6018      * Most messages are handled by the coroutines.
6019      */
6020     for (i = 0; i < 256; i++)
6021         ssh->packet_dispatch[i] = NULL;
6022
6023     /*
6024      * These special message types we install handlers for.
6025      */
6026     ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6027     ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6028     ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6029 }
6030
6031 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
6032                           struct Packet *pktin)
6033 {
6034     unsigned char *in=(unsigned char*)vin;
6035     if (ssh->state == SSH_STATE_CLOSED)
6036         return;
6037
6038     if (pktin && ssh->packet_dispatch[pktin->type]) {
6039         ssh->packet_dispatch[pktin->type](ssh, pktin);
6040         return;
6041     }
6042
6043     if (!ssh->protocol_initial_phase_done) {
6044         if (do_ssh1_login(ssh, in, inlen, pktin))
6045             ssh->protocol_initial_phase_done = TRUE;
6046         else
6047             return;
6048     }
6049
6050     do_ssh1_connection(ssh, in, inlen, pktin);
6051 }
6052
6053 /*
6054  * Utility routine for decoding comma-separated strings in KEXINIT.
6055  */
6056 static int in_commasep_string(char const *needle, char const *haystack,
6057                               int haylen)
6058 {
6059     int needlen;
6060     if (!needle || !haystack)          /* protect against null pointers */
6061         return 0;
6062     needlen = strlen(needle);
6063     while (1) {
6064         /*
6065          * Is it at the start of the string?
6066          */
6067         if (haylen >= needlen &&       /* haystack is long enough */
6068             !memcmp(needle, haystack, needlen) &&       /* initial match */
6069             (haylen == needlen || haystack[needlen] == ',')
6070             /* either , or EOS follows */
6071             )
6072             return 1;
6073         /*
6074          * If not, search for the next comma and resume after that.
6075          * If no comma found, terminate.
6076          */
6077         while (haylen > 0 && *haystack != ',')
6078             haylen--, haystack++;
6079         if (haylen == 0)
6080             return 0;
6081         haylen--, haystack++;          /* skip over comma itself */
6082     }
6083 }
6084
6085 /*
6086  * Similar routine for checking whether we have the first string in a list.
6087  */
6088 static int first_in_commasep_string(char const *needle, char const *haystack,
6089                                     int haylen)
6090 {
6091     int needlen;
6092     if (!needle || !haystack)          /* protect against null pointers */
6093         return 0;
6094     needlen = strlen(needle);
6095     /*
6096      * Is it at the start of the string?
6097      */
6098     if (haylen >= needlen &&       /* haystack is long enough */
6099         !memcmp(needle, haystack, needlen) &&   /* initial match */
6100         (haylen == needlen || haystack[needlen] == ',')
6101         /* either , or EOS follows */
6102         )
6103         return 1;
6104     return 0;
6105 }
6106
6107 /*
6108  * Add a value to the comma-separated string at the end of the packet.
6109  * If the value is already in the string, don't bother adding it again.
6110  */
6111 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6112 {
6113     if (in_commasep_string(data, (char *)pkt->data + pkt->savedpos,
6114                            pkt->length - pkt->savedpos)) return;
6115     if (pkt->length - pkt->savedpos > 0)
6116         ssh_pkt_addstring_str(pkt, ",");
6117     ssh_pkt_addstring_str(pkt, data);
6118 }
6119
6120
6121 /*
6122  * SSH-2 key creation method.
6123  * (Currently assumes 2 lots of any hash are sufficient to generate
6124  * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
6125  */
6126 #define SSH2_MKKEY_ITERS (2)
6127 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
6128                        unsigned char *keyspace)
6129 {
6130     const struct ssh_hash *h = ssh->kex->hash;
6131     void *s;
6132     /* First hlen bytes. */
6133     s = h->init();
6134     if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6135         hash_mpint(h, s, K);
6136     h->bytes(s, H, h->hlen);
6137     h->bytes(s, &chr, 1);
6138     h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6139     h->final(s, keyspace);
6140     /* Next hlen bytes. */
6141     s = h->init();
6142     if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6143         hash_mpint(h, s, K);
6144     h->bytes(s, H, h->hlen);
6145     h->bytes(s, keyspace, h->hlen);
6146     h->final(s, keyspace + h->hlen);
6147 }
6148
6149 /*
6150  * Handle the SSH-2 transport layer.
6151  */
6152 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6153                              struct Packet *pktin)
6154 {
6155     unsigned char *in = (unsigned char *)vin;
6156     struct do_ssh2_transport_state {
6157         int crLine;
6158         int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6159         Bignum p, g, e, f, K;
6160         void *our_kexinit;
6161         int our_kexinitlen;
6162         int kex_init_value, kex_reply_value;
6163         const struct ssh_mac **maclist;
6164         int nmacs;
6165         const struct ssh2_cipher *cscipher_tobe;
6166         const struct ssh2_cipher *sccipher_tobe;
6167         const struct ssh_mac *csmac_tobe;
6168         const struct ssh_mac *scmac_tobe;
6169         int csmac_etm_tobe, scmac_etm_tobe;
6170         const struct ssh_compress *cscomp_tobe;
6171         const struct ssh_compress *sccomp_tobe;
6172         char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6173         int hostkeylen, siglen, rsakeylen;
6174         void *hkey;                    /* actual host key */
6175         void *rsakey;                  /* for RSA kex */
6176         void *eckey;                   /* for ECDH kex */
6177         unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6178         int n_preferred_kex;
6179         const struct ssh_kexes *preferred_kex[KEX_MAX];
6180         int n_preferred_ciphers;
6181         const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6182         const struct ssh_compress *preferred_comp;
6183         int userauth_succeeded;     /* for delayed compression */
6184         int pending_compression;
6185         int got_session_id, activated_authconn;
6186         struct Packet *pktout;
6187         int dlgret;
6188         int guessok;
6189         int ignorepkt;
6190     };
6191     crState(do_ssh2_transport_state);
6192
6193     assert(!ssh->bare_connection);
6194
6195     crBeginState;
6196
6197     s->cscipher_tobe = s->sccipher_tobe = NULL;
6198     s->csmac_tobe = s->scmac_tobe = NULL;
6199     s->cscomp_tobe = s->sccomp_tobe = NULL;
6200
6201     s->got_session_id = s->activated_authconn = FALSE;
6202     s->userauth_succeeded = FALSE;
6203     s->pending_compression = FALSE;
6204
6205     /*
6206      * Be prepared to work around the buggy MAC problem.
6207      */
6208     if (ssh->remote_bugs & BUG_SSH2_HMAC)
6209         s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6210     else
6211         s->maclist = macs, s->nmacs = lenof(macs);
6212
6213   begin_key_exchange:
6214     ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6215     {
6216         int i, j, k;
6217
6218         /*
6219          * Set up the preferred key exchange. (NULL => warn below here)
6220          */
6221         s->n_preferred_kex = 0;
6222         for (i = 0; i < KEX_MAX; i++) {
6223             switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6224               case KEX_DHGEX:
6225                 s->preferred_kex[s->n_preferred_kex++] =
6226                     &ssh_diffiehellman_gex;
6227                 break;
6228               case KEX_DHGROUP14:
6229                 s->preferred_kex[s->n_preferred_kex++] =
6230                     &ssh_diffiehellman_group14;
6231                 break;
6232               case KEX_DHGROUP1:
6233                 s->preferred_kex[s->n_preferred_kex++] =
6234                     &ssh_diffiehellman_group1;
6235                 break;
6236               case KEX_RSA:
6237                 s->preferred_kex[s->n_preferred_kex++] =
6238                     &ssh_rsa_kex;
6239                 break;
6240               case KEX_ECDH:
6241                 s->preferred_kex[s->n_preferred_kex++] =
6242                     &ssh_ecdh_kex;
6243                 break;
6244               case KEX_WARN:
6245                 /* Flag for later. Don't bother if it's the last in
6246                  * the list. */
6247                 if (i < KEX_MAX - 1) {
6248                     s->preferred_kex[s->n_preferred_kex++] = NULL;
6249                 }
6250                 break;
6251             }
6252         }
6253
6254         /*
6255          * Set up the preferred ciphers. (NULL => warn below here)
6256          */
6257         s->n_preferred_ciphers = 0;
6258         for (i = 0; i < CIPHER_MAX; i++) {
6259             switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6260               case CIPHER_BLOWFISH:
6261                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6262                 break;
6263               case CIPHER_DES:
6264                 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6265                     s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6266                 }
6267                 break;
6268               case CIPHER_3DES:
6269                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6270                 break;
6271               case CIPHER_AES:
6272                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6273                 break;
6274               case CIPHER_ARCFOUR:
6275                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6276                 break;
6277               case CIPHER_WARN:
6278                 /* Flag for later. Don't bother if it's the last in
6279                  * the list. */
6280                 if (i < CIPHER_MAX - 1) {
6281                     s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6282                 }
6283                 break;
6284             }
6285         }
6286
6287         /*
6288          * Set up preferred compression.
6289          */
6290         if (conf_get_int(ssh->conf, CONF_compression))
6291             s->preferred_comp = &ssh_zlib;
6292         else
6293             s->preferred_comp = &ssh_comp_none;
6294
6295         /*
6296          * Enable queueing of outgoing auth- or connection-layer
6297          * packets while we are in the middle of a key exchange.
6298          */
6299         ssh->queueing = TRUE;
6300
6301         /*
6302          * Flag that KEX is in progress.
6303          */
6304         ssh->kex_in_progress = TRUE;
6305
6306         /*
6307          * Construct and send our key exchange packet.
6308          */
6309         s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6310         for (i = 0; i < 16; i++)
6311             ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6312         /* List key exchange algorithms. */
6313         ssh2_pkt_addstring_start(s->pktout);
6314         for (i = 0; i < s->n_preferred_kex; i++) {
6315             const struct ssh_kexes *k = s->preferred_kex[i];
6316             if (!k) continue;          /* warning flag */
6317             for (j = 0; j < k->nkexes; j++)
6318                 ssh2_pkt_addstring_commasep(s->pktout, k->list[j]->name);
6319         }
6320         /* List server host key algorithms. */
6321         if (!s->got_session_id) {
6322             /*
6323              * In the first key exchange, we list all the algorithms
6324              * we're prepared to cope with.
6325              */
6326             ssh2_pkt_addstring_start(s->pktout);
6327             for (i = 0; i < lenof(hostkey_algs); i++)
6328                 ssh2_pkt_addstring_commasep(s->pktout, hostkey_algs[i]->name);
6329         } else {
6330             /*
6331              * In subsequent key exchanges, we list only the kex
6332              * algorithm that was selected in the first key exchange,
6333              * so that we keep getting the same host key and hence
6334              * don't have to interrupt the user's session to ask for
6335              * reverification.
6336              */
6337             assert(ssh->kex);
6338             ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6339         }
6340         /* List encryption algorithms (client->server then server->client). */
6341         for (k = 0; k < 2; k++) {
6342             ssh2_pkt_addstring_start(s->pktout);
6343             for (i = 0; i < s->n_preferred_ciphers; i++) {
6344                 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6345                 if (!c) continue;              /* warning flag */
6346                 for (j = 0; j < c->nciphers; j++)
6347                     ssh2_pkt_addstring_commasep(s->pktout, c->list[j]->name);
6348             }
6349         }
6350         /* List MAC algorithms (client->server then server->client). */
6351         for (j = 0; j < 2; j++) {
6352             ssh2_pkt_addstring_start(s->pktout);
6353             for (i = 0; i < s->nmacs; i++) {
6354                 ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->name);
6355             }
6356             for (i = 0; i < s->nmacs; i++) {
6357                 /* For each MAC, there may also be an ETM version,
6358                  * which we list second. */
6359                 if (s->maclist[i]->etm_name)
6360                     ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->etm_name);
6361             }
6362         }
6363         /* List client->server compression algorithms,
6364          * then server->client compression algorithms. (We use the
6365          * same set twice.) */
6366         for (j = 0; j < 2; j++) {
6367             ssh2_pkt_addstring_start(s->pktout);
6368             assert(lenof(compressions) > 1);
6369             /* Prefer non-delayed versions */
6370             ssh2_pkt_addstring_commasep(s->pktout, s->preferred_comp->name);
6371             /* We don't even list delayed versions of algorithms until
6372              * they're allowed to be used, to avoid a race. See the end of
6373              * this function. */
6374             if (s->userauth_succeeded && s->preferred_comp->delayed_name)
6375                 ssh2_pkt_addstring_commasep(s->pktout,
6376                                             s->preferred_comp->delayed_name);
6377             for (i = 0; i < lenof(compressions); i++) {
6378                 const struct ssh_compress *c = compressions[i];
6379                 ssh2_pkt_addstring_commasep(s->pktout, c->name);
6380                 if (s->userauth_succeeded && c->delayed_name)
6381                     ssh2_pkt_addstring_commasep(s->pktout, c->delayed_name);
6382             }
6383         }
6384         /* List client->server languages. Empty list. */
6385         ssh2_pkt_addstring_start(s->pktout);
6386         /* List server->client languages. Empty list. */
6387         ssh2_pkt_addstring_start(s->pktout);
6388         /* First KEX packet does _not_ follow, because we're not that brave. */
6389         ssh2_pkt_addbool(s->pktout, FALSE);
6390         /* Reserved. */
6391         ssh2_pkt_adduint32(s->pktout, 0);
6392     }
6393
6394     s->our_kexinitlen = s->pktout->length - 5;
6395     s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6396     memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen); 
6397
6398     ssh2_pkt_send_noqueue(ssh, s->pktout);
6399
6400     if (!pktin)
6401         crWaitUntilV(pktin);
6402
6403     /*
6404      * Now examine the other side's KEXINIT to see what we're up
6405      * to.
6406      */
6407     {
6408         char *str, *preferred;
6409         int i, j, len;
6410
6411         if (pktin->type != SSH2_MSG_KEXINIT) {
6412             bombout(("expected key exchange packet from server"));
6413             crStopV;
6414         }
6415         ssh->kex = NULL;
6416         ssh->hostkey = NULL;
6417         s->cscipher_tobe = NULL;
6418         s->sccipher_tobe = NULL;
6419         s->csmac_tobe = NULL;
6420         s->scmac_tobe = NULL;
6421         s->cscomp_tobe = NULL;
6422         s->sccomp_tobe = NULL;
6423         s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6424
6425         pktin->savedpos += 16;          /* skip garbage cookie */
6426         ssh_pkt_getstring(pktin, &str, &len);    /* key exchange algorithms */
6427         if (!str) {
6428             bombout(("KEXINIT packet was incomplete"));
6429             crStopV;
6430         }
6431
6432         preferred = NULL;
6433         for (i = 0; i < s->n_preferred_kex; i++) {
6434             const struct ssh_kexes *k = s->preferred_kex[i];
6435             if (!k) {
6436                 s->warn_kex = TRUE;
6437             } else {
6438                 for (j = 0; j < k->nkexes; j++) {
6439                     if (!preferred) preferred = k->list[j]->name;
6440                     if (in_commasep_string(k->list[j]->name, str, len)) {
6441                         ssh->kex = k->list[j];
6442                         break;
6443                     }
6444                 }
6445             }
6446             if (ssh->kex)
6447                 break;
6448         }
6449         if (!ssh->kex) {
6450             bombout(("Couldn't agree a key exchange algorithm"
6451                      " (available: %.*s)", len, str));
6452             crStopV;
6453         }
6454         /*
6455          * Note that the server's guess is considered wrong if it doesn't match
6456          * the first algorithm in our list, even if it's still the algorithm
6457          * we end up using.
6458          */
6459         s->guessok = first_in_commasep_string(preferred, str, len);
6460         ssh_pkt_getstring(pktin, &str, &len);    /* host key algorithms */
6461         if (!str) {
6462             bombout(("KEXINIT packet was incomplete"));
6463             crStopV;
6464         }
6465         for (i = 0; i < lenof(hostkey_algs); i++) {
6466             if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6467                 ssh->hostkey = hostkey_algs[i];
6468                 break;
6469             }
6470         }
6471         if (!ssh->hostkey) {
6472             bombout(("Couldn't agree a host key algorithm"
6473                      " (available: %.*s)", len, str));
6474             crStopV;
6475         }
6476
6477         s->guessok = s->guessok &&
6478             first_in_commasep_string(hostkey_algs[0]->name, str, len);
6479         ssh_pkt_getstring(pktin, &str, &len);    /* client->server cipher */
6480         if (!str) {
6481             bombout(("KEXINIT packet was incomplete"));
6482             crStopV;
6483         }
6484         for (i = 0; i < s->n_preferred_ciphers; i++) {
6485             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6486             if (!c) {
6487                 s->warn_cscipher = TRUE;
6488             } else {
6489                 for (j = 0; j < c->nciphers; j++) {
6490                     if (in_commasep_string(c->list[j]->name, str, len)) {
6491                         s->cscipher_tobe = c->list[j];
6492                         break;
6493                     }
6494                 }
6495             }
6496             if (s->cscipher_tobe)
6497                 break;
6498         }
6499         if (!s->cscipher_tobe) {
6500             bombout(("Couldn't agree a client-to-server cipher"
6501                      " (available: %.*s)", len, str));
6502             crStopV;
6503         }
6504
6505         ssh_pkt_getstring(pktin, &str, &len);    /* server->client cipher */
6506         if (!str) {
6507             bombout(("KEXINIT packet was incomplete"));
6508             crStopV;
6509         }
6510         for (i = 0; i < s->n_preferred_ciphers; i++) {
6511             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6512             if (!c) {
6513                 s->warn_sccipher = TRUE;
6514             } else {
6515                 for (j = 0; j < c->nciphers; j++) {
6516                     if (in_commasep_string(c->list[j]->name, str, len)) {
6517                         s->sccipher_tobe = c->list[j];
6518                         break;
6519                     }
6520                 }
6521             }
6522             if (s->sccipher_tobe)
6523                 break;
6524         }
6525         if (!s->sccipher_tobe) {
6526             bombout(("Couldn't agree a server-to-client cipher"
6527                      " (available: %.*s)", len, str));
6528             crStopV;
6529         }
6530
6531         ssh_pkt_getstring(pktin, &str, &len);    /* client->server mac */
6532         if (!str) {
6533             bombout(("KEXINIT packet was incomplete"));
6534             crStopV;
6535         }
6536         for (i = 0; i < s->nmacs; i++) {
6537             if (in_commasep_string(s->maclist[i]->name, str, len)) {
6538                 s->csmac_tobe = s->maclist[i];
6539                 s->csmac_etm_tobe = FALSE;
6540                 break;
6541             }
6542         }
6543         if (!s->csmac_tobe) {
6544             for (i = 0; i < s->nmacs; i++) {
6545                 if (s->maclist[i]->etm_name &&
6546                     in_commasep_string(s->maclist[i]->etm_name, str, len)) {
6547                     s->csmac_tobe = s->maclist[i];
6548                     s->csmac_etm_tobe = TRUE;
6549                     break;
6550                 }
6551             }
6552         }
6553         if (!s->csmac_tobe) {
6554             bombout(("Couldn't agree a client-to-server MAC"
6555                      " (available: %.*s)", len, str));
6556             crStopV;
6557         }
6558         ssh_pkt_getstring(pktin, &str, &len);    /* server->client mac */
6559         if (!str) {
6560             bombout(("KEXINIT packet was incomplete"));
6561             crStopV;
6562         }
6563         for (i = 0; i < s->nmacs; i++) {
6564             if (in_commasep_string(s->maclist[i]->name, str, len)) {
6565                 s->scmac_tobe = s->maclist[i];
6566                 s->scmac_etm_tobe = FALSE;
6567                 break;
6568             }
6569         }
6570         if (!s->scmac_tobe) {
6571             for (i = 0; i < s->nmacs; i++) {
6572                 if (s->maclist[i]->etm_name &&
6573                     in_commasep_string(s->maclist[i]->etm_name, str, len)) {
6574                     s->scmac_tobe = s->maclist[i];
6575                     s->scmac_etm_tobe = TRUE;
6576                     break;
6577                 }
6578             }
6579         }
6580         if (!s->scmac_tobe) {
6581             bombout(("Couldn't agree a server-to-client MAC"
6582                      " (available: %.*s)", len, str));
6583             crStopV;
6584         }
6585         ssh_pkt_getstring(pktin, &str, &len);  /* client->server compression */
6586         if (!str) {
6587             bombout(("KEXINIT packet was incomplete"));
6588             crStopV;
6589         }
6590         for (i = 0; i < lenof(compressions) + 1; i++) {
6591             const struct ssh_compress *c =
6592                 i == 0 ? s->preferred_comp : compressions[i - 1];
6593             if (in_commasep_string(c->name, str, len)) {
6594                 s->cscomp_tobe = c;
6595                 break;
6596             } else if (in_commasep_string(c->delayed_name, str, len)) {
6597                 if (s->userauth_succeeded) {
6598                     s->cscomp_tobe = c;
6599                     break;
6600                 } else {
6601                     s->pending_compression = TRUE;  /* try this later */
6602                 }
6603             }
6604         }
6605         ssh_pkt_getstring(pktin, &str, &len);  /* server->client compression */
6606         if (!str) {
6607             bombout(("KEXINIT packet was incomplete"));
6608             crStopV;
6609         }
6610         for (i = 0; i < lenof(compressions) + 1; i++) {
6611             const struct ssh_compress *c =
6612                 i == 0 ? s->preferred_comp : compressions[i - 1];
6613             if (in_commasep_string(c->name, str, len)) {
6614                 s->sccomp_tobe = c;
6615                 break;
6616             } else if (in_commasep_string(c->delayed_name, str, len)) {
6617                 if (s->userauth_succeeded) {
6618                     s->sccomp_tobe = c;
6619                     break;
6620                 } else {
6621                     s->pending_compression = TRUE;  /* try this later */
6622                 }
6623             }
6624         }
6625         if (s->pending_compression) {
6626             logevent("Server supports delayed compression; "
6627                      "will try this later");
6628         }
6629         ssh_pkt_getstring(pktin, &str, &len);  /* client->server language */
6630         ssh_pkt_getstring(pktin, &str, &len);  /* server->client language */
6631         s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6632
6633         ssh->exhash = ssh->kex->hash->init();
6634         hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6635         hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6636         hash_string(ssh->kex->hash, ssh->exhash,
6637             s->our_kexinit, s->our_kexinitlen);
6638         sfree(s->our_kexinit);
6639         /* Include the type byte in the hash of server's KEXINIT */
6640         hash_string(ssh->kex->hash, ssh->exhash,
6641                     pktin->body - 1, pktin->length + 1);
6642
6643         if (s->warn_kex) {
6644             ssh_set_frozen(ssh, 1);
6645             s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6646                                ssh->kex->name,
6647                                ssh_dialog_callback, ssh);
6648             if (s->dlgret < 0) {
6649                 do {
6650                     crReturnV;
6651                     if (pktin) {
6652                         bombout(("Unexpected data from server while"
6653                                  " waiting for user response"));
6654                         crStopV;
6655                     }
6656                 } while (pktin || inlen > 0);
6657                 s->dlgret = ssh->user_response;
6658             }
6659             ssh_set_frozen(ssh, 0);
6660             if (s->dlgret == 0) {
6661                 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6662                                0, TRUE);
6663                 crStopV;
6664             }
6665         }
6666
6667         if (s->warn_cscipher) {
6668             ssh_set_frozen(ssh, 1);
6669             s->dlgret = askalg(ssh->frontend,
6670                                "client-to-server cipher",
6671                                s->cscipher_tobe->name,
6672                                ssh_dialog_callback, ssh);
6673             if (s->dlgret < 0) {
6674                 do {
6675                     crReturnV;
6676                     if (pktin) {
6677                         bombout(("Unexpected data from server while"
6678                                  " waiting for user response"));
6679                         crStopV;
6680                     }
6681                 } while (pktin || inlen > 0);
6682                 s->dlgret = ssh->user_response;
6683             }
6684             ssh_set_frozen(ssh, 0);
6685             if (s->dlgret == 0) {
6686                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6687                                0, TRUE);
6688                 crStopV;
6689             }
6690         }
6691
6692         if (s->warn_sccipher) {
6693             ssh_set_frozen(ssh, 1);
6694             s->dlgret = askalg(ssh->frontend,
6695                                "server-to-client cipher",
6696                                s->sccipher_tobe->name,
6697                                ssh_dialog_callback, ssh);
6698             if (s->dlgret < 0) {
6699                 do {
6700                     crReturnV;
6701                     if (pktin) {
6702                         bombout(("Unexpected data from server while"
6703                                  " waiting for user response"));
6704                         crStopV;
6705                     }
6706                 } while (pktin || inlen > 0);
6707                 s->dlgret = ssh->user_response;
6708             }
6709             ssh_set_frozen(ssh, 0);
6710             if (s->dlgret == 0) {
6711                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6712                                0, TRUE);
6713                 crStopV;
6714             }
6715         }
6716
6717         if (s->ignorepkt) /* first_kex_packet_follows */
6718             crWaitUntilV(pktin);                /* Ignore packet */
6719     }
6720
6721     if (ssh->kex->main_type == KEXTYPE_DH) {
6722         /*
6723          * Work out the number of bits of key we will need from the
6724          * key exchange. We start with the maximum key length of
6725          * either cipher...
6726          */
6727         {
6728             int csbits, scbits;
6729
6730             csbits = s->cscipher_tobe->keylen;
6731             scbits = s->sccipher_tobe->keylen;
6732             s->nbits = (csbits > scbits ? csbits : scbits);
6733         }
6734         /* The keys only have hlen-bit entropy, since they're based on
6735          * a hash. So cap the key size at hlen bits. */
6736         if (s->nbits > ssh->kex->hash->hlen * 8)
6737             s->nbits = ssh->kex->hash->hlen * 8;
6738
6739         /*
6740          * If we're doing Diffie-Hellman group exchange, start by
6741          * requesting a group.
6742          */
6743         if (dh_is_gex(ssh->kex)) {
6744             logevent("Doing Diffie-Hellman group exchange");
6745             ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6746             /*
6747              * Work out how big a DH group we will need to allow that
6748              * much data.
6749              */
6750             s->pbits = 512 << ((s->nbits - 1) / 64);
6751             if (s->pbits < DH_MIN_SIZE)
6752                 s->pbits = DH_MIN_SIZE;
6753             if (s->pbits > DH_MAX_SIZE)
6754                 s->pbits = DH_MAX_SIZE;
6755             if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6756                 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6757                 ssh2_pkt_adduint32(s->pktout, s->pbits);
6758             } else {
6759                 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6760                 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6761                 ssh2_pkt_adduint32(s->pktout, s->pbits);
6762                 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6763             }
6764             ssh2_pkt_send_noqueue(ssh, s->pktout);
6765
6766             crWaitUntilV(pktin);
6767             if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6768                 bombout(("expected key exchange group packet from server"));
6769                 crStopV;
6770             }
6771             s->p = ssh2_pkt_getmp(pktin);
6772             s->g = ssh2_pkt_getmp(pktin);
6773             if (!s->p || !s->g) {
6774                 bombout(("unable to read mp-ints from incoming group packet"));
6775                 crStopV;
6776             }
6777             ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6778             s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6779             s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6780         } else {
6781             ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6782             ssh->kex_ctx = dh_setup_group(ssh->kex);
6783             s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6784             s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6785             logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6786                       ssh->kex->groupname);
6787         }
6788
6789         logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6790                   ssh->kex->hash->text_name);
6791         /*
6792          * Now generate and send e for Diffie-Hellman.
6793          */
6794         set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6795         s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6796         s->pktout = ssh2_pkt_init(s->kex_init_value);
6797         ssh2_pkt_addmp(s->pktout, s->e);
6798         ssh2_pkt_send_noqueue(ssh, s->pktout);
6799
6800         set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6801         crWaitUntilV(pktin);
6802         if (pktin->type != s->kex_reply_value) {
6803             bombout(("expected key exchange reply packet from server"));
6804             crStopV;
6805         }
6806         set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6807         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6808         s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6809                                        s->hostkeydata, s->hostkeylen);
6810         s->f = ssh2_pkt_getmp(pktin);
6811         if (!s->f) {
6812             bombout(("unable to parse key exchange reply packet"));
6813             crStopV;
6814         }
6815         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6816
6817         {
6818             const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6819             if (err) {
6820                 bombout(("key exchange reply failed validation: %s", err));
6821                 crStopV;
6822             }
6823         }
6824         s->K = dh_find_K(ssh->kex_ctx, s->f);
6825
6826         /* We assume everything from now on will be quick, and it might
6827          * involve user interaction. */
6828         set_busy_status(ssh->frontend, BUSY_NOT);
6829
6830         hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6831         if (dh_is_gex(ssh->kex)) {
6832             if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6833                 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6834             hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6835             if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6836                 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6837             hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6838             hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6839         }
6840         hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6841         hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6842
6843         dh_cleanup(ssh->kex_ctx);
6844         freebn(s->f);
6845         if (dh_is_gex(ssh->kex)) {
6846             freebn(s->g);
6847             freebn(s->p);
6848         }
6849     } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6850
6851         logeventf(ssh, "Doing ECDH key exchange with hash %s",
6852                   ssh->kex->hash->text_name);
6853         ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6854
6855         s->eckey = ssh_ecdhkex_newkey(ssh->kex);
6856         if (!s->eckey) {
6857             bombout(("Unable to generate key for ECDH"));
6858             crStopV;
6859         }
6860
6861         {
6862             char *publicPoint;
6863             int publicPointLength;
6864             publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6865             if (!publicPoint) {
6866                 ssh_ecdhkex_freekey(s->eckey);
6867                 bombout(("Unable to encode public key for ECDH"));
6868                 crStopV;
6869             }
6870             s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6871             ssh2_pkt_addstring_start(s->pktout);
6872             ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6873             sfree(publicPoint);
6874         }
6875
6876         ssh2_pkt_send_noqueue(ssh, s->pktout);
6877
6878         crWaitUntilV(pktin);
6879         if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6880             ssh_ecdhkex_freekey(s->eckey);
6881             bombout(("expected ECDH reply packet from server"));
6882             crStopV;
6883         }
6884
6885         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6886         hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6887         s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6888                                        s->hostkeydata, s->hostkeylen);
6889
6890         {
6891             char *publicPoint;
6892             int publicPointLength;
6893             publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6894             if (!publicPoint) {
6895                 ssh_ecdhkex_freekey(s->eckey);
6896                 bombout(("Unable to encode public key for ECDH hash"));
6897                 crStopV;
6898             }
6899             hash_string(ssh->kex->hash, ssh->exhash,
6900                         publicPoint, publicPointLength);
6901             sfree(publicPoint);
6902         }
6903
6904         {
6905             char *keydata;
6906             int keylen;
6907             ssh_pkt_getstring(pktin, &keydata, &keylen);
6908             hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6909             s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6910             if (!s->K) {
6911                 ssh_ecdhkex_freekey(s->eckey);
6912                 bombout(("point received in ECDH was not valid"));
6913                 crStopV;
6914             }
6915         }
6916
6917         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6918
6919         ssh_ecdhkex_freekey(s->eckey);
6920     } else {
6921         logeventf(ssh, "Doing RSA key exchange with hash %s",
6922                   ssh->kex->hash->text_name);
6923         ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6924         /*
6925          * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6926          * from the server.
6927          */
6928         crWaitUntilV(pktin);
6929         if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6930             bombout(("expected RSA public key packet from server"));
6931             crStopV;
6932         }
6933
6934         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6935         hash_string(ssh->kex->hash, ssh->exhash,
6936                     s->hostkeydata, s->hostkeylen);
6937         s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6938                                        s->hostkeydata, s->hostkeylen);
6939
6940         {
6941             char *keydata;
6942             ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6943             s->rsakeydata = snewn(s->rsakeylen, char);
6944             memcpy(s->rsakeydata, keydata, s->rsakeylen);
6945         }
6946
6947         s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6948         if (!s->rsakey) {
6949             sfree(s->rsakeydata);
6950             bombout(("unable to parse RSA public key from server"));
6951             crStopV;
6952         }
6953
6954         hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6955
6956         /*
6957          * Next, set up a shared secret K, of precisely KLEN -
6958          * 2*HLEN - 49 bits, where KLEN is the bit length of the
6959          * RSA key modulus and HLEN is the bit length of the hash
6960          * we're using.
6961          */
6962         {
6963             int klen = ssh_rsakex_klen(s->rsakey);
6964             int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6965             int i, byte = 0;
6966             unsigned char *kstr1, *kstr2, *outstr;
6967             int kstr1len, kstr2len, outstrlen;
6968
6969             s->K = bn_power_2(nbits - 1);
6970
6971             for (i = 0; i < nbits; i++) {
6972                 if ((i & 7) == 0) {
6973                     byte = random_byte();
6974                 }
6975                 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6976             }
6977
6978             /*
6979              * Encode this as an mpint.
6980              */
6981             kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6982             kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6983             PUT_32BIT(kstr2, kstr1len);
6984             memcpy(kstr2 + 4, kstr1, kstr1len);
6985
6986             /*
6987              * Encrypt it with the given RSA key.
6988              */
6989             outstrlen = (klen + 7) / 8;
6990             outstr = snewn(outstrlen, unsigned char);
6991             ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6992                                outstr, outstrlen, s->rsakey);
6993
6994             /*
6995              * And send it off in a return packet.
6996              */
6997             s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6998             ssh2_pkt_addstring_start(s->pktout);
6999             ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7000             ssh2_pkt_send_noqueue(ssh, s->pktout);
7001
7002             hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7003
7004             sfree(kstr2);
7005             sfree(kstr1);
7006             sfree(outstr);
7007         }
7008
7009         ssh_rsakex_freekey(s->rsakey);
7010
7011         crWaitUntilV(pktin);
7012         if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7013             sfree(s->rsakeydata);
7014             bombout(("expected signature packet from server"));
7015             crStopV;
7016         }
7017
7018         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7019
7020         sfree(s->rsakeydata);
7021     }
7022
7023     hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7024     assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7025     ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7026
7027     ssh->kex_ctx = NULL;
7028
7029 #if 0
7030     debug(("Exchange hash is:\n"));
7031     dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7032 #endif
7033
7034     if (!s->hkey ||
7035         !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7036                                  (char *)s->exchange_hash,
7037                                  ssh->kex->hash->hlen)) {
7038         bombout(("Server's host key did not match the signature supplied"));
7039         crStopV;
7040     }
7041
7042     s->keystr = ssh->hostkey->fmtkey(s->hkey);
7043     if (!s->got_session_id) {
7044         /*
7045          * Authenticate remote host: verify host key. (We've already
7046          * checked the signature of the exchange hash.)
7047          */
7048         s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7049         logevent("Host key fingerprint is:");
7050         logevent(s->fingerprint);
7051         /* First check against manually configured host keys. */
7052         s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7053                                                ssh->hostkey, s->hkey);
7054         if (s->dlgret == 0) {          /* did not match */
7055             bombout(("Host key did not appear in manually configured list"));
7056             crStopV;
7057         } else if (s->dlgret < 0) { /* none configured; use standard handling */
7058             ssh_set_frozen(ssh, 1);
7059             s->dlgret = verify_ssh_host_key(ssh->frontend,
7060                                             ssh->savedhost, ssh->savedport,
7061                                             ssh->hostkey->keytype, s->keystr,
7062                                             s->fingerprint,
7063                                             ssh_dialog_callback, ssh);
7064             if (s->dlgret < 0) {
7065                 do {
7066                     crReturnV;
7067                     if (pktin) {
7068                         bombout(("Unexpected data from server while waiting"
7069                                  " for user host key response"));
7070                         crStopV;
7071                     }
7072                 } while (pktin || inlen > 0);
7073                 s->dlgret = ssh->user_response;
7074             }
7075             ssh_set_frozen(ssh, 0);
7076             if (s->dlgret == 0) {
7077                 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7078                                0, TRUE);
7079                 crStopV;
7080             }
7081         }
7082         sfree(s->fingerprint);
7083         /*
7084          * Save this host key, to check against the one presented in
7085          * subsequent rekeys.
7086          */
7087         ssh->hostkey_str = s->keystr;
7088     } else {
7089         /*
7090          * In a rekey, we never present an interactive host key
7091          * verification request to the user. Instead, we simply
7092          * enforce that the key we're seeing this time is identical to
7093          * the one we saw before.
7094          */
7095         if (strcmp(ssh->hostkey_str, s->keystr)) {
7096             bombout(("Host key was different in repeat key exchange"));
7097             crStopV;
7098         }
7099         sfree(s->keystr);
7100     }
7101     ssh->hostkey->freekey(s->hkey);
7102
7103     /*
7104      * The exchange hash from the very first key exchange is also
7105      * the session id, used in session key construction and
7106      * authentication.
7107      */
7108     if (!s->got_session_id) {
7109         assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7110         memcpy(ssh->v2_session_id, s->exchange_hash,
7111                sizeof(s->exchange_hash));
7112         ssh->v2_session_id_len = ssh->kex->hash->hlen;
7113         assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7114         s->got_session_id = TRUE;
7115     }
7116
7117     /*
7118      * Send SSH2_MSG_NEWKEYS.
7119      */
7120     s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7121     ssh2_pkt_send_noqueue(ssh, s->pktout);
7122     ssh->outgoing_data_size = 0;       /* start counting from here */
7123
7124     /*
7125      * We've sent client NEWKEYS, so create and initialise
7126      * client-to-server session keys.
7127      */
7128     if (ssh->cs_cipher_ctx)
7129         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7130     ssh->cscipher = s->cscipher_tobe;
7131     ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7132
7133     if (ssh->cs_mac_ctx)
7134         ssh->csmac->free_context(ssh->cs_mac_ctx);
7135     ssh->csmac = s->csmac_tobe;
7136     ssh->csmac_etm = s->csmac_etm_tobe;
7137     ssh->cs_mac_ctx = ssh->csmac->make_context();
7138
7139     if (ssh->cs_comp_ctx)
7140         ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7141     ssh->cscomp = s->cscomp_tobe;
7142     ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7143
7144     /*
7145      * Set IVs on client-to-server keys. Here we use the exchange
7146      * hash from the _first_ key exchange.
7147      */
7148     {
7149         unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7150         assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7151         ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
7152         assert((ssh->cscipher->keylen+7) / 8 <=
7153                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7154         ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
7155         ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
7156         assert(ssh->cscipher->blksize <=
7157                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7158         ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
7159         ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
7160         assert(ssh->csmac->len <=
7161                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7162         ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
7163         smemclr(keyspace, sizeof(keyspace));
7164     }
7165
7166     logeventf(ssh, "Initialised %.200s client->server encryption",
7167               ssh->cscipher->text_name);
7168     logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s",
7169               ssh->csmac->text_name,
7170               ssh->csmac_etm ? " (in ETM mode)" : "");
7171     if (ssh->cscomp->text_name)
7172         logeventf(ssh, "Initialised %s compression",
7173                   ssh->cscomp->text_name);
7174
7175     /*
7176      * Now our end of the key exchange is complete, we can send all
7177      * our queued higher-layer packets.
7178      */
7179     ssh->queueing = FALSE;
7180     ssh2_pkt_queuesend(ssh);
7181
7182     /*
7183      * Expect SSH2_MSG_NEWKEYS from server.
7184      */
7185     crWaitUntilV(pktin);
7186     if (pktin->type != SSH2_MSG_NEWKEYS) {
7187         bombout(("expected new-keys packet from server"));
7188         crStopV;
7189     }
7190     ssh->incoming_data_size = 0;       /* start counting from here */
7191
7192     /*
7193      * We've seen server NEWKEYS, so create and initialise
7194      * server-to-client session keys.
7195      */
7196     if (ssh->sc_cipher_ctx)
7197         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7198     ssh->sccipher = s->sccipher_tobe;
7199     ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7200
7201     if (ssh->sc_mac_ctx)
7202         ssh->scmac->free_context(ssh->sc_mac_ctx);
7203     ssh->scmac = s->scmac_tobe;
7204     ssh->scmac_etm = s->scmac_etm_tobe;
7205     ssh->sc_mac_ctx = ssh->scmac->make_context();
7206
7207     if (ssh->sc_comp_ctx)
7208         ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7209     ssh->sccomp = s->sccomp_tobe;
7210     ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7211
7212     /*
7213      * Set IVs on server-to-client keys. Here we use the exchange
7214      * hash from the _first_ key exchange.
7215      */
7216     {
7217         unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7218         assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7219         ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
7220         assert((ssh->sccipher->keylen+7) / 8 <=
7221                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7222         ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
7223         ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
7224         assert(ssh->sccipher->blksize <=
7225                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7226         ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
7227         ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
7228         assert(ssh->scmac->len <=
7229                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7230         ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
7231         smemclr(keyspace, sizeof(keyspace));
7232     }
7233     logeventf(ssh, "Initialised %.200s server->client encryption",
7234               ssh->sccipher->text_name);
7235     logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s",
7236               ssh->scmac->text_name,
7237               ssh->scmac_etm ? " (in ETM mode)" : "");
7238     if (ssh->sccomp->text_name)
7239         logeventf(ssh, "Initialised %s decompression",
7240                   ssh->sccomp->text_name);
7241
7242     /*
7243      * Free shared secret.
7244      */
7245     freebn(s->K);
7246
7247     /*
7248      * Key exchange is over. Loop straight back round if we have a
7249      * deferred rekey reason.
7250      */
7251     if (ssh->deferred_rekey_reason) {
7252         logevent(ssh->deferred_rekey_reason);
7253         pktin = NULL;
7254         ssh->deferred_rekey_reason = NULL;
7255         goto begin_key_exchange;
7256     }
7257
7258     /*
7259      * Otherwise, schedule a timer for our next rekey.
7260      */
7261     ssh->kex_in_progress = FALSE;
7262     ssh->last_rekey = GETTICKCOUNT();
7263     if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7264         ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7265                                          ssh2_timer, ssh);
7266
7267     /*
7268      * Now we're encrypting. Begin returning 1 to the protocol main
7269      * function so that other things can run on top of the
7270      * transport. If we ever see a KEXINIT, we must go back to the
7271      * start.
7272      * 
7273      * We _also_ go back to the start if we see pktin==NULL and
7274      * inlen negative, because this is a special signal meaning
7275      * `initiate client-driven rekey', and `in' contains a message
7276      * giving the reason for the rekey.
7277      *
7278      * inlen==-1 means always initiate a rekey;
7279      * inlen==-2 means that userauth has completed successfully and
7280      *   we should consider rekeying (for delayed compression).
7281      */
7282     while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7283              (!pktin && inlen < 0))) {
7284         wait_for_rekey:
7285         if (!ssh->protocol_initial_phase_done) {
7286             ssh->protocol_initial_phase_done = TRUE;
7287             /*
7288              * Allow authconn to initialise itself.
7289              */
7290             do_ssh2_authconn(ssh, NULL, 0, NULL);
7291         }
7292         crReturnV;
7293     }
7294     if (pktin) {
7295         logevent("Server initiated key re-exchange");
7296     } else {
7297         if (inlen == -2) {
7298             /* 
7299              * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7300              * delayed compression, if it's available.
7301              *
7302              * draft-miller-secsh-compression-delayed-00 says that you
7303              * negotiate delayed compression in the first key exchange, and
7304              * both sides start compressing when the server has sent
7305              * USERAUTH_SUCCESS. This has a race condition -- the server
7306              * can't know when the client has seen it, and thus which incoming
7307              * packets it should treat as compressed.
7308              *
7309              * Instead, we do the initial key exchange without offering the
7310              * delayed methods, but note if the server offers them; when we
7311              * get here, if a delayed method was available that was higher
7312              * on our list than what we got, we initiate a rekey in which we
7313              * _do_ list the delayed methods (and hopefully get it as a
7314              * result). Subsequent rekeys will do the same.
7315              */
7316             assert(!s->userauth_succeeded); /* should only happen once */
7317             s->userauth_succeeded = TRUE;
7318             if (!s->pending_compression)
7319                 /* Can't see any point rekeying. */
7320                 goto wait_for_rekey;       /* this is utterly horrid */
7321             /* else fall through to rekey... */
7322             s->pending_compression = FALSE;
7323         }
7324         /*
7325          * Now we've decided to rekey.
7326          *
7327          * Special case: if the server bug is set that doesn't
7328          * allow rekeying, we give a different log message and
7329          * continue waiting. (If such a server _initiates_ a rekey,
7330          * we process it anyway!)
7331          */
7332         if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7333             logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7334                       (char *)in);
7335             /* Reset the counters, so that at least this message doesn't
7336              * hit the event log _too_ often. */
7337             ssh->outgoing_data_size = 0;
7338             ssh->incoming_data_size = 0;
7339             if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7340                 ssh->next_rekey =
7341                     schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7342                                    ssh2_timer, ssh);
7343             }
7344             goto wait_for_rekey;       /* this is still utterly horrid */
7345         } else {
7346             logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7347         }
7348     }
7349     goto begin_key_exchange;
7350
7351     crFinishV;
7352 }
7353
7354 /*
7355  * Add data to an SSH-2 channel output buffer.
7356  */
7357 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7358                                   int len)
7359 {
7360     bufchain_add(&c->v.v2.outbuffer, buf, len);
7361 }
7362
7363 /*
7364  * Attempt to send data on an SSH-2 channel.
7365  */
7366 static int ssh2_try_send(struct ssh_channel *c)
7367 {
7368     Ssh ssh = c->ssh;
7369     struct Packet *pktout;
7370     int ret;
7371
7372     while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7373         int len;
7374         void *data;
7375         bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7376         if ((unsigned)len > c->v.v2.remwindow)
7377             len = c->v.v2.remwindow;
7378         if ((unsigned)len > c->v.v2.remmaxpkt)
7379             len = c->v.v2.remmaxpkt;
7380         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7381         ssh2_pkt_adduint32(pktout, c->remoteid);
7382         ssh2_pkt_addstring_start(pktout);
7383         ssh2_pkt_addstring_data(pktout, data, len);
7384         ssh2_pkt_send(ssh, pktout);
7385         bufchain_consume(&c->v.v2.outbuffer, len);
7386         c->v.v2.remwindow -= len;
7387     }
7388
7389     /*
7390      * After having sent as much data as we can, return the amount
7391      * still buffered.
7392      */
7393     ret = bufchain_size(&c->v.v2.outbuffer);
7394
7395     /*
7396      * And if there's no data pending but we need to send an EOF, send
7397      * it.
7398      */
7399     if (!ret && c->pending_eof)
7400         ssh_channel_try_eof(c);
7401
7402     return ret;
7403 }
7404
7405 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7406 {
7407     int bufsize;
7408     if (c->closes & CLOSES_SENT_EOF)
7409         return;                   /* don't send on channels we've EOFed */
7410     bufsize = ssh2_try_send(c);
7411     if (bufsize == 0) {
7412         switch (c->type) {
7413           case CHAN_MAINSESSION:
7414             /* stdin need not receive an unthrottle
7415              * notification since it will be polled */
7416             break;
7417           case CHAN_X11:
7418             x11_unthrottle(c->u.x11.xconn);
7419             break;
7420           case CHAN_AGENT:
7421             /* agent sockets are request/response and need no
7422              * buffer management */
7423             break;
7424           case CHAN_SOCKDATA:
7425             pfd_unthrottle(c->u.pfd.pf);
7426             break;
7427         }
7428     }
7429 }
7430
7431 static int ssh_is_simple(Ssh ssh)
7432 {
7433     /*
7434      * We use the 'simple' variant of the SSH protocol if we're asked
7435      * to, except not if we're also doing connection-sharing (either
7436      * tunnelling our packets over an upstream or expecting to be
7437      * tunnelled over ourselves), since then the assumption that we
7438      * have only one channel to worry about is not true after all.
7439      */
7440     return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7441             !ssh->bare_connection && !ssh->connshare);
7442 }
7443
7444 /*
7445  * Set up most of a new ssh_channel for SSH-2.
7446  */
7447 static void ssh2_channel_init(struct ssh_channel *c)
7448 {
7449     Ssh ssh = c->ssh;
7450     c->localid = alloc_channel_id(ssh);
7451     c->closes = 0;
7452     c->pending_eof = FALSE;
7453     c->throttling_conn = FALSE;
7454     c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7455         ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7456     c->v.v2.chanreq_head = NULL;
7457     c->v.v2.throttle_state = UNTHROTTLED;
7458     bufchain_init(&c->v.v2.outbuffer);
7459 }
7460
7461 /*
7462  * Construct the common parts of a CHANNEL_OPEN.
7463  */
7464 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7465 {
7466     struct Packet *pktout;
7467
7468     pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7469     ssh2_pkt_addstring(pktout, type);
7470     ssh2_pkt_adduint32(pktout, c->localid);
7471     ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7472     ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
7473     return pktout;
7474 }
7475
7476 /*
7477  * CHANNEL_FAILURE doesn't come with any indication of what message
7478  * caused it, so we have to keep track of the outstanding
7479  * CHANNEL_REQUESTs ourselves.
7480  */
7481 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7482                                        cchandler_fn_t handler, void *ctx)
7483 {
7484     struct outstanding_channel_request *ocr =
7485         snew(struct outstanding_channel_request);
7486
7487     assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7488     ocr->handler = handler;
7489     ocr->ctx = ctx;
7490     ocr->next = NULL;
7491     if (!c->v.v2.chanreq_head)
7492         c->v.v2.chanreq_head = ocr;
7493     else
7494         c->v.v2.chanreq_tail->next = ocr;
7495     c->v.v2.chanreq_tail = ocr;
7496 }
7497
7498 /*
7499  * Construct the common parts of a CHANNEL_REQUEST.  If handler is not
7500  * NULL then a reply will be requested and the handler will be called
7501  * when it arrives.  The returned packet is ready to have any
7502  * request-specific data added and be sent.  Note that if a handler is
7503  * provided, it's essential that the request actually be sent.
7504  *
7505  * The handler will usually be passed the response packet in pktin. If
7506  * pktin is NULL, this means that no reply will ever be forthcoming
7507  * (e.g. because the entire connection is being destroyed, or because
7508  * the server initiated channel closure before we saw the response)
7509  * and the handler should free any storage it's holding.
7510  */
7511 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7512                                         cchandler_fn_t handler, void *ctx)
7513 {
7514     struct Packet *pktout;
7515
7516     assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7517     pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7518     ssh2_pkt_adduint32(pktout, c->remoteid);
7519     ssh2_pkt_addstring(pktout, type);
7520     ssh2_pkt_addbool(pktout, handler != NULL);
7521     if (handler != NULL)
7522         ssh2_queue_chanreq_handler(c, handler, ctx);
7523     return pktout;
7524 }
7525
7526 /*
7527  * Potentially enlarge the window on an SSH-2 channel.
7528  */
7529 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7530                                         void *);
7531 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7532 {
7533     Ssh ssh = c->ssh;
7534
7535     /*
7536      * Never send WINDOW_ADJUST for a channel that the remote side has
7537      * already sent EOF on; there's no point, since it won't be
7538      * sending any more data anyway. Ditto if _we've_ already sent
7539      * CLOSE.
7540      */
7541     if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7542         return;
7543
7544     /*
7545      * Also, never widen the window for an X11 channel when we're
7546      * still waiting to see its initial auth and may yet hand it off
7547      * to a downstream.
7548      */
7549     if (c->type == CHAN_X11 && c->u.x11.initial)
7550         return;
7551
7552     /*
7553      * If the remote end has a habit of ignoring maxpkt, limit the
7554      * window so that it has no choice (assuming it doesn't ignore the
7555      * window as well).
7556      */
7557     if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7558         newwin = OUR_V2_MAXPKT;
7559
7560     /*
7561      * Only send a WINDOW_ADJUST if there's significantly more window
7562      * available than the other end thinks there is.  This saves us
7563      * sending a WINDOW_ADJUST for every character in a shell session.
7564      *
7565      * "Significant" is arbitrarily defined as half the window size.
7566      */
7567     if (newwin / 2 >= c->v.v2.locwindow) {
7568         struct Packet *pktout;
7569         unsigned *up;
7570
7571         /*
7572          * In order to keep track of how much window the client
7573          * actually has available, we'd like it to acknowledge each
7574          * WINDOW_ADJUST.  We can't do that directly, so we accompany
7575          * it with a CHANNEL_REQUEST that has to be acknowledged.
7576          *
7577          * This is only necessary if we're opening the window wide.
7578          * If we're not, then throughput is being constrained by
7579          * something other than the maximum window size anyway.
7580          */
7581         if (newwin == c->v.v2.locmaxwin &&
7582             !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7583             up = snew(unsigned);
7584             *up = newwin - c->v.v2.locwindow;
7585             pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7586                                        ssh2_handle_winadj_response, up);
7587             ssh2_pkt_send(ssh, pktout);
7588
7589             if (c->v.v2.throttle_state != UNTHROTTLED)
7590                 c->v.v2.throttle_state = UNTHROTTLING;
7591         } else {
7592             /* Pretend the WINDOW_ADJUST was acked immediately. */
7593             c->v.v2.remlocwin = newwin;
7594             c->v.v2.throttle_state = THROTTLED;
7595         }
7596         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7597         ssh2_pkt_adduint32(pktout, c->remoteid);
7598         ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7599         ssh2_pkt_send(ssh, pktout);
7600         c->v.v2.locwindow = newwin;
7601     }
7602 }
7603
7604 /*
7605  * Find the channel associated with a message.  If there's no channel,
7606  * or it's not properly open, make a noise about it and return NULL.
7607  */
7608 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7609 {
7610     unsigned localid = ssh_pkt_getuint32(pktin);
7611     struct ssh_channel *c;
7612
7613     c = find234(ssh->channels, &localid, ssh_channelfind);
7614     if (!c ||
7615         (c->type != CHAN_SHARING && c->halfopen &&
7616          pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7617          pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7618         char *buf = dupprintf("Received %s for %s channel %u",
7619                               ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7620                                             pktin->type),
7621                               c ? "half-open" : "nonexistent", localid);
7622         ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7623         sfree(buf);
7624         return NULL;
7625     }
7626     return c;
7627 }
7628
7629 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7630                                         struct Packet *pktin, void *ctx)
7631 {
7632     unsigned *sizep = ctx;
7633
7634     /*
7635      * Winadj responses should always be failures. However, at least
7636      * one server ("boks_sshd") is known to return SUCCESS for channel
7637      * requests it's never heard of, such as "winadj@putty". Raised
7638      * with foxt.com as bug 090916-090424, but for the sake of a quiet
7639      * life, we don't worry about what kind of response we got.
7640      */
7641
7642     c->v.v2.remlocwin += *sizep;
7643     sfree(sizep);
7644     /*
7645      * winadj messages are only sent when the window is fully open, so
7646      * if we get an ack of one, we know any pending unthrottle is
7647      * complete.
7648      */
7649     if (c->v.v2.throttle_state == UNTHROTTLING)
7650         c->v.v2.throttle_state = UNTHROTTLED;
7651 }
7652
7653 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7654 {
7655     struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7656     struct outstanding_channel_request *ocr;
7657
7658     if (!c) return;
7659     if (c->type == CHAN_SHARING) {
7660         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7661                                   pktin->body, pktin->length);
7662         return;
7663     }
7664     ocr = c->v.v2.chanreq_head;
7665     if (!ocr) {
7666         ssh2_msg_unexpected(ssh, pktin);
7667         return;
7668     }
7669     ocr->handler(c, pktin, ocr->ctx);
7670     c->v.v2.chanreq_head = ocr->next;
7671     sfree(ocr);
7672     /*
7673      * We may now initiate channel-closing procedures, if that
7674      * CHANNEL_REQUEST was the last thing outstanding before we send
7675      * CHANNEL_CLOSE.
7676      */
7677     ssh2_channel_check_close(c);
7678 }
7679
7680 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7681 {
7682     struct ssh_channel *c;
7683     c = ssh2_channel_msg(ssh, pktin);
7684     if (!c)
7685         return;
7686     if (c->type == CHAN_SHARING) {
7687         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7688                                   pktin->body, pktin->length);
7689         return;
7690     }
7691     if (!(c->closes & CLOSES_SENT_EOF)) {
7692         c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7693         ssh2_try_send_and_unthrottle(ssh, c);
7694     }
7695 }
7696
7697 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7698 {
7699     char *data;
7700     int length;
7701     struct ssh_channel *c;
7702     c = ssh2_channel_msg(ssh, pktin);
7703     if (!c)
7704         return;
7705     if (c->type == CHAN_SHARING) {
7706         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7707                                   pktin->body, pktin->length);
7708         return;
7709     }
7710     if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7711         ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7712         return;                        /* extended but not stderr */
7713     ssh_pkt_getstring(pktin, &data, &length);
7714     if (data) {
7715         int bufsize = 0;
7716         c->v.v2.locwindow -= length;
7717         c->v.v2.remlocwin -= length;
7718         switch (c->type) {
7719           case CHAN_MAINSESSION:
7720             bufsize =
7721                 from_backend(ssh->frontend, pktin->type ==
7722                              SSH2_MSG_CHANNEL_EXTENDED_DATA,
7723                              data, length);
7724             break;
7725           case CHAN_X11:
7726             bufsize = x11_send(c->u.x11.xconn, data, length);
7727             break;
7728           case CHAN_SOCKDATA:
7729             bufsize = pfd_send(c->u.pfd.pf, data, length);
7730             break;
7731           case CHAN_AGENT:
7732             while (length > 0) {
7733                 if (c->u.a.lensofar < 4) {
7734                     unsigned int l = min(4 - c->u.a.lensofar,
7735                                          (unsigned)length);
7736                     memcpy(c->u.a.msglen + c->u.a.lensofar,
7737                            data, l);
7738                     data += l;
7739                     length -= l;
7740                     c->u.a.lensofar += l;
7741                 }
7742                 if (c->u.a.lensofar == 4) {
7743                     c->u.a.totallen =
7744                         4 + GET_32BIT(c->u.a.msglen);
7745                     c->u.a.message = snewn(c->u.a.totallen,
7746                                            unsigned char);
7747                     memcpy(c->u.a.message, c->u.a.msglen, 4);
7748                 }
7749                 if (c->u.a.lensofar >= 4 && length > 0) {
7750                     unsigned int l =
7751                         min(c->u.a.totallen - c->u.a.lensofar,
7752                             (unsigned)length);
7753                     memcpy(c->u.a.message + c->u.a.lensofar,
7754                            data, l);
7755                     data += l;
7756                     length -= l;
7757                     c->u.a.lensofar += l;
7758                 }
7759                 if (c->u.a.lensofar == c->u.a.totallen) {
7760                     void *reply;
7761                     int replylen;
7762                     c->u.a.outstanding_requests++;
7763                     if (agent_query(c->u.a.message,
7764                                     c->u.a.totallen,
7765                                     &reply, &replylen,
7766                                     ssh_agentf_callback, c))
7767                         ssh_agentf_callback(c, reply, replylen);
7768                     sfree(c->u.a.message);
7769                     c->u.a.message = NULL;
7770                     c->u.a.lensofar = 0;
7771                 }
7772             }
7773             bufsize = 0;
7774             break;
7775         }
7776         /*
7777          * If it looks like the remote end hit the end of its window,
7778          * and we didn't want it to do that, think about using a
7779          * larger window.
7780          */
7781         if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7782             c->v.v2.locmaxwin < 0x40000000)
7783             c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7784         /*
7785          * If we are not buffering too much data,
7786          * enlarge the window again at the remote side.
7787          * If we are buffering too much, we may still
7788          * need to adjust the window if the server's
7789          * sent excess data.
7790          */
7791         ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7792                         c->v.v2.locmaxwin - bufsize : 0);
7793         /*
7794          * If we're either buffering way too much data, or if we're
7795          * buffering anything at all and we're in "simple" mode,
7796          * throttle the whole channel.
7797          */
7798         if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7799             && !c->throttling_conn) {
7800             c->throttling_conn = 1;
7801             ssh_throttle_conn(ssh, +1);
7802         }
7803     }
7804 }
7805
7806 static void ssh_check_termination(Ssh ssh)
7807 {
7808     if (ssh->version == 2 &&
7809         !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7810         count234(ssh->channels) == 0 &&
7811         !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7812         /*
7813          * We used to send SSH_MSG_DISCONNECT here, because I'd
7814          * believed that _every_ conforming SSH-2 connection had to
7815          * end with a disconnect being sent by at least one side;
7816          * apparently I was wrong and it's perfectly OK to
7817          * unceremoniously slam the connection shut when you're done,
7818          * and indeed OpenSSH feels this is more polite than sending a
7819          * DISCONNECT. So now we don't.
7820          */
7821         ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7822     }
7823 }
7824
7825 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7826 {
7827     logeventf(ssh, "Connection sharing downstream #%u connected", id);
7828 }
7829
7830 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7831 {
7832     logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7833     ssh_check_termination(ssh);
7834 }
7835
7836 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7837 {
7838     va_list ap;
7839     char *buf;
7840
7841     va_start(ap, logfmt);
7842     buf = dupvprintf(logfmt, ap);
7843     va_end(ap);
7844     if (id)
7845         logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7846     else
7847         logeventf(ssh, "Connection sharing: %s", buf);
7848     sfree(buf);
7849 }
7850
7851 static void ssh_channel_destroy(struct ssh_channel *c)
7852 {
7853     Ssh ssh = c->ssh;
7854
7855     switch (c->type) {
7856       case CHAN_MAINSESSION:
7857         ssh->mainchan = NULL;
7858         update_specials_menu(ssh->frontend);
7859         break;
7860       case CHAN_X11:
7861         if (c->u.x11.xconn != NULL)
7862             x11_close(c->u.x11.xconn);
7863         logevent("Forwarded X11 connection terminated");
7864         break;
7865       case CHAN_AGENT:
7866         sfree(c->u.a.message);
7867         break;
7868       case CHAN_SOCKDATA:
7869         if (c->u.pfd.pf != NULL)
7870             pfd_close(c->u.pfd.pf);
7871         logevent("Forwarded port closed");
7872         break;
7873     }
7874
7875     del234(ssh->channels, c);
7876     if (ssh->version == 2) {
7877         bufchain_clear(&c->v.v2.outbuffer);
7878         assert(c->v.v2.chanreq_head == NULL);
7879     }
7880     sfree(c);
7881
7882     /*
7883      * If that was the last channel left open, we might need to
7884      * terminate.
7885      */
7886     ssh_check_termination(ssh);
7887 }
7888
7889 static void ssh2_channel_check_close(struct ssh_channel *c)
7890 {
7891     Ssh ssh = c->ssh;
7892     struct Packet *pktout;
7893
7894     if (c->halfopen) {
7895         /*
7896          * If we've sent out our own CHANNEL_OPEN but not yet seen
7897          * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7898          * it's too early to be sending close messages of any kind.
7899          */
7900         return;
7901     }
7902
7903     if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7904          c->type == CHAN_ZOMBIE) &&
7905         !c->v.v2.chanreq_head &&
7906         !(c->closes & CLOSES_SENT_CLOSE)) {
7907         /*
7908          * We have both sent and received EOF (or the channel is a
7909          * zombie), and we have no outstanding channel requests, which
7910          * means the channel is in final wind-up. But we haven't sent
7911          * CLOSE, so let's do so now.
7912          */
7913         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7914         ssh2_pkt_adduint32(pktout, c->remoteid);
7915         ssh2_pkt_send(ssh, pktout);
7916         c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7917     }
7918
7919     if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7920         assert(c->v.v2.chanreq_head == NULL);
7921         /*
7922          * We have both sent and received CLOSE, which means we're
7923          * completely done with the channel.
7924          */
7925         ssh_channel_destroy(c);
7926     }
7927 }
7928
7929 static void ssh2_channel_got_eof(struct ssh_channel *c)
7930 {
7931     if (c->closes & CLOSES_RCVD_EOF)
7932         return;                        /* already seen EOF */
7933     c->closes |= CLOSES_RCVD_EOF;
7934
7935     if (c->type == CHAN_X11) {
7936         x11_send_eof(c->u.x11.xconn);
7937     } else if (c->type == CHAN_AGENT) {
7938         if (c->u.a.outstanding_requests == 0) {
7939             /* Manufacture an outgoing EOF in response to the incoming one. */
7940             sshfwd_write_eof(c);
7941         }
7942     } else if (c->type == CHAN_SOCKDATA) {
7943         pfd_send_eof(c->u.pfd.pf);
7944     } else if (c->type == CHAN_MAINSESSION) {
7945         Ssh ssh = c->ssh;
7946
7947         if (!ssh->sent_console_eof &&
7948             (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7949             /*
7950              * Either from_backend_eof told us that the front end
7951              * wants us to close the outgoing side of the connection
7952              * as soon as we see EOF from the far end, or else we've
7953              * unilaterally decided to do that because we've allocated
7954              * a remote pty and hence EOF isn't a particularly
7955              * meaningful concept.
7956              */
7957             sshfwd_write_eof(c);
7958         }
7959         ssh->sent_console_eof = TRUE;
7960     }
7961
7962     ssh2_channel_check_close(c);
7963 }
7964
7965 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7966 {
7967     struct ssh_channel *c;
7968
7969     c = ssh2_channel_msg(ssh, pktin);
7970     if (!c)
7971         return;
7972     if (c->type == CHAN_SHARING) {
7973         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7974                                   pktin->body, pktin->length);
7975         return;
7976     }
7977     ssh2_channel_got_eof(c);
7978 }
7979
7980 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7981 {
7982     struct ssh_channel *c;
7983
7984     c = ssh2_channel_msg(ssh, pktin);
7985     if (!c)
7986         return;
7987     if (c->type == CHAN_SHARING) {
7988         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7989                                   pktin->body, pktin->length);
7990         return;
7991     }
7992
7993     /*
7994      * When we receive CLOSE on a channel, we assume it comes with an
7995      * implied EOF if we haven't seen EOF yet.
7996      */
7997     ssh2_channel_got_eof(c);
7998
7999     if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8000         /*
8001          * It also means we stop expecting to see replies to any
8002          * outstanding channel requests, so clean those up too.
8003          * (ssh_chanreq_init will enforce by assertion that we don't
8004          * subsequently put anything back on this list.)
8005          */
8006         while (c->v.v2.chanreq_head) {
8007             struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8008             ocr->handler(c, NULL, ocr->ctx);
8009             c->v.v2.chanreq_head = ocr->next;
8010             sfree(ocr);
8011         }
8012     }
8013
8014     /*
8015      * And we also send an outgoing EOF, if we haven't already, on the
8016      * assumption that CLOSE is a pretty forceful announcement that
8017      * the remote side is doing away with the entire channel. (If it
8018      * had wanted to send us EOF and continue receiving data from us,
8019      * it would have just sent CHANNEL_EOF.)
8020      */
8021     if (!(c->closes & CLOSES_SENT_EOF)) {
8022         /*
8023          * Make sure we don't read any more from whatever our local
8024          * data source is for this channel.
8025          */
8026         switch (c->type) {
8027           case CHAN_MAINSESSION:
8028             ssh->send_ok = 0;     /* stop trying to read from stdin */
8029             break;
8030           case CHAN_X11:
8031             x11_override_throttle(c->u.x11.xconn, 1);
8032             break;
8033           case CHAN_SOCKDATA:
8034             pfd_override_throttle(c->u.pfd.pf, 1);
8035             break;
8036         }
8037
8038         /*
8039          * Abandon any buffered data we still wanted to send to this
8040          * channel. Receiving a CHANNEL_CLOSE is an indication that
8041          * the server really wants to get on and _destroy_ this
8042          * channel, and it isn't going to send us any further
8043          * WINDOW_ADJUSTs to permit us to send pending stuff.
8044          */
8045         bufchain_clear(&c->v.v2.outbuffer);
8046
8047         /*
8048          * Send outgoing EOF.
8049          */
8050         sshfwd_write_eof(c);
8051     }
8052
8053     /*
8054      * Now process the actual close.
8055      */
8056     if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8057         c->closes |= CLOSES_RCVD_CLOSE;
8058         ssh2_channel_check_close(c);
8059     }
8060 }
8061
8062 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8063 {
8064     struct ssh_channel *c;
8065
8066     c = ssh2_channel_msg(ssh, pktin);
8067     if (!c)
8068         return;
8069     if (c->type == CHAN_SHARING) {
8070         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8071                                   pktin->body, pktin->length);
8072         return;
8073     }
8074     assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8075     c->remoteid = ssh_pkt_getuint32(pktin);
8076     c->halfopen = FALSE;
8077     c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8078     c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8079
8080     if (c->type == CHAN_SOCKDATA_DORMANT) {
8081         c->type = CHAN_SOCKDATA;
8082         if (c->u.pfd.pf)
8083             pfd_confirm(c->u.pfd.pf);
8084     } else if (c->type == CHAN_ZOMBIE) {
8085         /*
8086          * This case can occur if a local socket error occurred
8087          * between us sending out CHANNEL_OPEN and receiving
8088          * OPEN_CONFIRMATION. In this case, all we can do is
8089          * immediately initiate close proceedings now that we know the
8090          * server's id to put in the close message.
8091          */
8092         ssh2_channel_check_close(c);
8093     } else {
8094         /*
8095          * We never expect to receive OPEN_CONFIRMATION for any
8096          * *other* channel type (since only local-to-remote port
8097          * forwardings cause us to send CHANNEL_OPEN after the main
8098          * channel is live - all other auxiliary channel types are
8099          * initiated from the server end). It's safe to enforce this
8100          * by assertion rather than by ssh_disconnect, because the
8101          * real point is that we never constructed a half-open channel
8102          * structure in the first place with any type other than the
8103          * above.
8104          */
8105         assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8106     }
8107
8108     if (c->pending_eof)
8109         ssh_channel_try_eof(c);        /* in case we had a pending EOF */
8110 }
8111
8112 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8113 {
8114     static const char *const reasons[] = {
8115         "<unknown reason code>",
8116             "Administratively prohibited",
8117             "Connect failed",
8118             "Unknown channel type",
8119             "Resource shortage",
8120     };
8121     unsigned reason_code;
8122     char *reason_string;
8123     int reason_length;
8124     struct ssh_channel *c;
8125
8126     c = ssh2_channel_msg(ssh, pktin);
8127     if (!c)
8128         return;
8129     if (c->type == CHAN_SHARING) {
8130         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8131                                   pktin->body, pktin->length);
8132         return;
8133     }
8134     assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8135
8136     if (c->type == CHAN_SOCKDATA_DORMANT) {
8137         reason_code = ssh_pkt_getuint32(pktin);
8138         if (reason_code >= lenof(reasons))
8139             reason_code = 0; /* ensure reasons[reason_code] in range */
8140         ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8141         logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8142                   reasons[reason_code], reason_length, reason_string);
8143
8144         pfd_close(c->u.pfd.pf);
8145     } else if (c->type == CHAN_ZOMBIE) {
8146         /*
8147          * This case can occur if a local socket error occurred
8148          * between us sending out CHANNEL_OPEN and receiving
8149          * OPEN_FAILURE. In this case, we need do nothing except allow
8150          * the code below to throw the half-open channel away.
8151          */
8152     } else {
8153         /*
8154          * We never expect to receive OPEN_FAILURE for any *other*
8155          * channel type (since only local-to-remote port forwardings
8156          * cause us to send CHANNEL_OPEN after the main channel is
8157          * live - all other auxiliary channel types are initiated from
8158          * the server end). It's safe to enforce this by assertion
8159          * rather than by ssh_disconnect, because the real point is
8160          * that we never constructed a half-open channel structure in
8161          * the first place with any type other than the above.
8162          */
8163         assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8164     }
8165
8166     del234(ssh->channels, c);
8167     sfree(c);
8168 }
8169
8170 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8171 {
8172     char *type;
8173     int typelen, want_reply;
8174     int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8175     struct ssh_channel *c;
8176     struct Packet *pktout;
8177
8178     c = ssh2_channel_msg(ssh, pktin);
8179     if (!c)
8180         return;
8181     if (c->type == CHAN_SHARING) {
8182         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8183                                   pktin->body, pktin->length);
8184         return;
8185     }
8186     ssh_pkt_getstring(pktin, &type, &typelen);
8187     want_reply = ssh2_pkt_getbool(pktin);
8188
8189     if (c->closes & CLOSES_SENT_CLOSE) {
8190         /*
8191          * We don't reply to channel requests after we've sent
8192          * CHANNEL_CLOSE for the channel, because our reply might
8193          * cross in the network with the other side's CHANNEL_CLOSE
8194          * and arrive after they have wound the channel up completely.
8195          */
8196         want_reply = FALSE;
8197     }
8198
8199     /*
8200      * Having got the channel number, we now look at
8201      * the request type string to see if it's something
8202      * we recognise.
8203      */
8204     if (c == ssh->mainchan) {
8205         /*
8206          * We recognise "exit-status" and "exit-signal" on
8207          * the primary channel.
8208          */
8209         if (typelen == 11 &&
8210             !memcmp(type, "exit-status", 11)) {
8211
8212             ssh->exitcode = ssh_pkt_getuint32(pktin);
8213             logeventf(ssh, "Server sent command exit status %d",
8214                       ssh->exitcode);
8215             reply = SSH2_MSG_CHANNEL_SUCCESS;
8216
8217         } else if (typelen == 11 &&
8218                    !memcmp(type, "exit-signal", 11)) {
8219
8220             int is_plausible = TRUE, is_int = FALSE;
8221             char *fmt_sig = "", *fmt_msg = "";
8222             char *msg;
8223             int msglen = 0, core = FALSE;
8224             /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8225              * provide an `int' for the signal, despite its
8226              * having been a `string' in the drafts of RFC 4254 since at
8227              * least 2001. (Fixed in session.c 1.147.) Try to
8228              * infer which we can safely parse it as. */
8229             {
8230                 unsigned char *p = pktin->body +
8231                     pktin->savedpos;
8232                 long len = pktin->length - pktin->savedpos;
8233                 unsigned long num = GET_32BIT(p); /* what is it? */
8234                 /* If it's 0, it hardly matters; assume string */
8235                 if (num == 0) {
8236                     is_int = FALSE;
8237                 } else {
8238                     int maybe_int = FALSE, maybe_str = FALSE;
8239 #define CHECK_HYPOTHESIS(offset, result)                                \
8240                     do                                                  \
8241                     {                                                   \
8242                         int q = toint(offset);                          \
8243                         if (q >= 0 && q+4 <= len) {                     \
8244                             q = toint(q + 4 + GET_32BIT(p+q));          \
8245                             if (q >= 0 && q+4 <= len &&                 \
8246                                 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8247                                 q == len)                               \
8248                                 result = TRUE;                          \
8249                         }                                               \
8250                     } while(0)
8251                     CHECK_HYPOTHESIS(4+1, maybe_int);
8252                     CHECK_HYPOTHESIS(4+num+1, maybe_str);
8253 #undef CHECK_HYPOTHESIS
8254                     if (maybe_int && !maybe_str)
8255                         is_int = TRUE;
8256                     else if (!maybe_int && maybe_str)
8257                         is_int = FALSE;
8258                     else
8259                         /* Crikey. Either or neither. Panic. */
8260                         is_plausible = FALSE;
8261                 }
8262             }
8263             ssh->exitcode = 128;       /* means `unknown signal' */
8264             if (is_plausible) {
8265                 if (is_int) {
8266                     /* Old non-standard OpenSSH. */
8267                     int signum = ssh_pkt_getuint32(pktin);
8268                     fmt_sig = dupprintf(" %d", signum);
8269                     ssh->exitcode = 128 + signum;
8270                 } else {
8271                     /* As per RFC 4254. */
8272                     char *sig;
8273                     int siglen;
8274                     ssh_pkt_getstring(pktin, &sig, &siglen);
8275                     /* Signal name isn't supposed to be blank, but
8276                      * let's cope gracefully if it is. */
8277                     if (siglen) {
8278                         fmt_sig = dupprintf(" \"%.*s\"",
8279                                             siglen, sig);
8280                     }
8281
8282                     /*
8283                      * Really hideous method of translating the
8284                      * signal description back into a locally
8285                      * meaningful number.
8286                      */
8287
8288                     if (0)
8289                         ;
8290 #define TRANSLATE_SIGNAL(s) \
8291     else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8292         ssh->exitcode = 128 + SIG ## s
8293 #ifdef SIGABRT
8294                     TRANSLATE_SIGNAL(ABRT);
8295 #endif
8296 #ifdef SIGALRM
8297                     TRANSLATE_SIGNAL(ALRM);
8298 #endif
8299 #ifdef SIGFPE
8300                     TRANSLATE_SIGNAL(FPE);
8301 #endif
8302 #ifdef SIGHUP
8303                     TRANSLATE_SIGNAL(HUP);
8304 #endif
8305 #ifdef SIGILL
8306                     TRANSLATE_SIGNAL(ILL);
8307 #endif
8308 #ifdef SIGINT
8309                     TRANSLATE_SIGNAL(INT);
8310 #endif
8311 #ifdef SIGKILL
8312                     TRANSLATE_SIGNAL(KILL);
8313 #endif
8314 #ifdef SIGPIPE
8315                     TRANSLATE_SIGNAL(PIPE);
8316 #endif
8317 #ifdef SIGQUIT
8318                     TRANSLATE_SIGNAL(QUIT);
8319 #endif
8320 #ifdef SIGSEGV
8321                     TRANSLATE_SIGNAL(SEGV);
8322 #endif
8323 #ifdef SIGTERM
8324                     TRANSLATE_SIGNAL(TERM);
8325 #endif
8326 #ifdef SIGUSR1
8327                     TRANSLATE_SIGNAL(USR1);
8328 #endif
8329 #ifdef SIGUSR2
8330                     TRANSLATE_SIGNAL(USR2);
8331 #endif
8332 #undef TRANSLATE_SIGNAL
8333                     else
8334                         ssh->exitcode = 128;
8335                 }
8336                 core = ssh2_pkt_getbool(pktin);
8337                 ssh_pkt_getstring(pktin, &msg, &msglen);
8338                 if (msglen) {
8339                     fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8340                 }
8341                 /* ignore lang tag */
8342             } /* else don't attempt to parse */
8343             logeventf(ssh, "Server exited on signal%s%s%s",
8344                       fmt_sig, core ? " (core dumped)" : "",
8345                       fmt_msg);
8346             if (*fmt_sig) sfree(fmt_sig);
8347             if (*fmt_msg) sfree(fmt_msg);
8348             reply = SSH2_MSG_CHANNEL_SUCCESS;
8349
8350         }
8351     } else {
8352         /*
8353          * This is a channel request we don't know
8354          * about, so we now either ignore the request
8355          * or respond with CHANNEL_FAILURE, depending
8356          * on want_reply.
8357          */
8358         reply = SSH2_MSG_CHANNEL_FAILURE;
8359     }
8360     if (want_reply) {
8361         pktout = ssh2_pkt_init(reply);
8362         ssh2_pkt_adduint32(pktout, c->remoteid);
8363         ssh2_pkt_send(ssh, pktout);
8364     }
8365 }
8366
8367 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8368 {
8369     char *type;
8370     int typelen, want_reply;
8371     struct Packet *pktout;
8372
8373     ssh_pkt_getstring(pktin, &type, &typelen);
8374     want_reply = ssh2_pkt_getbool(pktin);
8375
8376     /*
8377      * We currently don't support any global requests
8378      * at all, so we either ignore the request or
8379      * respond with REQUEST_FAILURE, depending on
8380      * want_reply.
8381      */
8382     if (want_reply) {
8383         pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8384         ssh2_pkt_send(ssh, pktout);
8385     }
8386 }
8387
8388 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8389                                                 void *share_cs,
8390                                                 void *share_chan)
8391 {
8392     struct X11FakeAuth *auth;
8393
8394     /*
8395      * Make up a new set of fake X11 auth data, and add it to the tree
8396      * of currently valid ones with an indication of the sharing
8397      * context that it's relevant to.
8398      */
8399     auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8400     auth->share_cs = share_cs;
8401     auth->share_chan = share_chan;
8402
8403     return auth;
8404 }
8405
8406 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8407 {
8408     del234(ssh->x11authtree, auth);
8409     x11_free_fake_auth(auth);
8410 }
8411
8412 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8413 {
8414     char *type;
8415     int typelen;
8416     char *peeraddr;
8417     int peeraddrlen;
8418     int peerport;
8419     char *error = NULL;
8420     struct ssh_channel *c;
8421     unsigned remid, winsize, pktsize;
8422     unsigned our_winsize_override = 0;
8423     struct Packet *pktout;
8424
8425     ssh_pkt_getstring(pktin, &type, &typelen);
8426     c = snew(struct ssh_channel);
8427     c->ssh = ssh;
8428
8429     remid = ssh_pkt_getuint32(pktin);
8430     winsize = ssh_pkt_getuint32(pktin);
8431     pktsize = ssh_pkt_getuint32(pktin);
8432
8433     if (typelen == 3 && !memcmp(type, "x11", 3)) {
8434         char *addrstr;
8435
8436         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8437         addrstr = snewn(peeraddrlen+1, char);
8438         memcpy(addrstr, peeraddr, peeraddrlen);
8439         addrstr[peeraddrlen] = '\0';
8440         peerport = ssh_pkt_getuint32(pktin);
8441
8442         logeventf(ssh, "Received X11 connect request from %s:%d",
8443                   addrstr, peerport);
8444
8445         if (!ssh->X11_fwd_enabled && !ssh->connshare)
8446             error = "X11 forwarding is not enabled";
8447         else {
8448             c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8449                                       addrstr, peerport);
8450             c->type = CHAN_X11;
8451             c->u.x11.initial = TRUE;
8452
8453             /*
8454              * If we are a connection-sharing upstream, then we should
8455              * initially present a very small window, adequate to take
8456              * the X11 initial authorisation packet but not much more.
8457              * Downstream will then present us a larger window (by
8458              * fiat of the connection-sharing protocol) and we can
8459              * guarantee to send a positive-valued WINDOW_ADJUST.
8460              */
8461             if (ssh->connshare)
8462                 our_winsize_override = 128;
8463
8464             logevent("Opened X11 forward channel");
8465         }
8466
8467         sfree(addrstr);
8468     } else if (typelen == 15 &&
8469                !memcmp(type, "forwarded-tcpip", 15)) {
8470         struct ssh_rportfwd pf, *realpf;
8471         char *shost;
8472         int shostlen;
8473         ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8474         pf.shost = dupprintf("%.*s", shostlen, shost);
8475         pf.sport = ssh_pkt_getuint32(pktin);
8476         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8477         peerport = ssh_pkt_getuint32(pktin);
8478         realpf = find234(ssh->rportfwds, &pf, NULL);
8479         logeventf(ssh, "Received remote port %s:%d open request "
8480                   "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8481         sfree(pf.shost);
8482
8483         if (realpf == NULL) {
8484             error = "Remote port is not recognised";
8485         } else {
8486             char *err;
8487
8488             if (realpf->share_ctx) {
8489                 /*
8490                  * This port forwarding is on behalf of a
8491                  * connection-sharing downstream, so abandon our own
8492                  * channel-open procedure and just pass the message on
8493                  * to sshshare.c.
8494                  */
8495                 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8496                                           pktin->body, pktin->length);
8497                 sfree(c);
8498                 return;
8499             }
8500
8501             err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8502                               c, ssh->conf, realpf->pfrec->addressfamily);
8503             logeventf(ssh, "Attempting to forward remote port to "
8504                       "%s:%d", realpf->dhost, realpf->dport);
8505             if (err != NULL) {
8506                 logeventf(ssh, "Port open failed: %s", err);
8507                 sfree(err);
8508                 error = "Port open failed";
8509             } else {
8510                 logevent("Forwarded port opened successfully");
8511                 c->type = CHAN_SOCKDATA;
8512             }
8513         }
8514     } else if (typelen == 22 &&
8515                !memcmp(type, "auth-agent@openssh.com", 22)) {
8516         if (!ssh->agentfwd_enabled)
8517             error = "Agent forwarding is not enabled";
8518         else {
8519             c->type = CHAN_AGENT;       /* identify channel type */
8520             c->u.a.lensofar = 0;
8521             c->u.a.message = NULL;
8522             c->u.a.outstanding_requests = 0;
8523         }
8524     } else {
8525         error = "Unsupported channel type requested";
8526     }
8527
8528     c->remoteid = remid;
8529     c->halfopen = FALSE;
8530     if (error) {
8531         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8532         ssh2_pkt_adduint32(pktout, c->remoteid);
8533         ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8534         ssh2_pkt_addstring(pktout, error);
8535         ssh2_pkt_addstring(pktout, "en");       /* language tag */
8536         ssh2_pkt_send(ssh, pktout);
8537         logeventf(ssh, "Rejected channel open: %s", error);
8538         sfree(c);
8539     } else {
8540         ssh2_channel_init(c);
8541         c->v.v2.remwindow = winsize;
8542         c->v.v2.remmaxpkt = pktsize;
8543         if (our_winsize_override) {
8544             c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8545                 our_winsize_override;
8546         }
8547         add234(ssh->channels, c);
8548         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8549         ssh2_pkt_adduint32(pktout, c->remoteid);
8550         ssh2_pkt_adduint32(pktout, c->localid);
8551         ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8552         ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
8553         ssh2_pkt_send(ssh, pktout);
8554     }
8555 }
8556
8557 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8558                                  void *share_cs, void *share_chan,
8559                                  const char *peer_addr, int peer_port,
8560                                  int endian, int protomajor, int protominor,
8561                                  const void *initial_data, int initial_len)
8562 {
8563     /*
8564      * This function is called when we've just discovered that an X
8565      * forwarding channel on which we'd been handling the initial auth
8566      * ourselves turns out to be destined for a connection-sharing
8567      * downstream. So we turn the channel into a CHAN_SHARING, meaning
8568      * that we completely stop tracking windows and buffering data and
8569      * just pass more or less unmodified SSH messages back and forth.
8570      */
8571     c->type = CHAN_SHARING;
8572     c->u.sharing.ctx = share_cs;
8573     share_setup_x11_channel(share_cs, share_chan,
8574                             c->localid, c->remoteid, c->v.v2.remwindow,
8575                             c->v.v2.remmaxpkt, c->v.v2.locwindow,
8576                             peer_addr, peer_port, endian,
8577                             protomajor, protominor,
8578                             initial_data, initial_len);
8579 }
8580
8581 void sshfwd_x11_is_local(struct ssh_channel *c)
8582 {
8583     /*
8584      * This function is called when we've just discovered that an X
8585      * forwarding channel is _not_ destined for a connection-sharing
8586      * downstream but we're going to handle it ourselves. We stop
8587      * presenting a cautiously small window and go into ordinary data
8588      * exchange mode.
8589      */
8590     c->u.x11.initial = FALSE;
8591     ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8592 }
8593
8594 /*
8595  * Buffer banner messages for later display at some convenient point,
8596  * if we're going to display them.
8597  */
8598 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8599 {
8600     /* Arbitrary limit to prevent unbounded inflation of buffer */
8601     if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8602         bufchain_size(&ssh->banner) <= 131072) {
8603         char *banner = NULL;
8604         int size = 0;
8605         ssh_pkt_getstring(pktin, &banner, &size);
8606         if (banner)
8607             bufchain_add(&ssh->banner, banner, size);
8608     }
8609 }
8610
8611 /* Helper function to deal with sending tty modes for "pty-req" */
8612 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8613 {
8614     struct Packet *pktout = (struct Packet *)data;
8615     int i = 0;
8616     unsigned int arg = 0;
8617     while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8618     if (i == lenof(ssh_ttymodes)) return;
8619     switch (ssh_ttymodes[i].type) {
8620       case TTY_OP_CHAR:
8621         arg = ssh_tty_parse_specchar(val);
8622         break;
8623       case TTY_OP_BOOL:
8624         arg = ssh_tty_parse_boolean(val);
8625         break;
8626     }
8627     ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8628     ssh2_pkt_adduint32(pktout, arg);
8629 }
8630
8631 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8632                            void *ctx)
8633 {
8634     struct ssh2_setup_x11_state {
8635         int crLine;
8636     };
8637     Ssh ssh = c->ssh;
8638     struct Packet *pktout;
8639     crStateP(ssh2_setup_x11_state, ctx);
8640
8641     crBeginState;
8642
8643     logevent("Requesting X11 forwarding");
8644     pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8645                                ssh2_setup_x11, s);
8646     ssh2_pkt_addbool(pktout, 0);               /* many connections */
8647     ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8648     ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8649     ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8650     ssh2_pkt_send(ssh, pktout);
8651
8652     /* Wait to be called back with either a response packet, or NULL
8653      * meaning clean up and free our data */
8654     crReturnV;
8655
8656     if (pktin) {
8657         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8658             logevent("X11 forwarding enabled");
8659             ssh->X11_fwd_enabled = TRUE;
8660         } else
8661             logevent("X11 forwarding refused");
8662     }
8663
8664     crFinishFreeV;
8665 }
8666
8667 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8668                                    void *ctx)
8669 {
8670     struct ssh2_setup_agent_state {
8671         int crLine;
8672     };
8673     Ssh ssh = c->ssh;
8674     struct Packet *pktout;
8675     crStateP(ssh2_setup_agent_state, ctx);
8676
8677     crBeginState;
8678
8679     logevent("Requesting OpenSSH-style agent forwarding");
8680     pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8681                                ssh2_setup_agent, s);
8682     ssh2_pkt_send(ssh, pktout);
8683
8684     /* Wait to be called back with either a response packet, or NULL
8685      * meaning clean up and free our data */
8686     crReturnV;
8687
8688     if (pktin) {
8689         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8690             logevent("Agent forwarding enabled");
8691             ssh->agentfwd_enabled = TRUE;
8692         } else
8693             logevent("Agent forwarding refused");
8694     }
8695
8696     crFinishFreeV;
8697 }
8698
8699 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8700                                  void *ctx)
8701 {
8702     struct ssh2_setup_pty_state {
8703         int crLine;
8704     };
8705     Ssh ssh = c->ssh;
8706     struct Packet *pktout;
8707     crStateP(ssh2_setup_pty_state, ctx);
8708
8709     crBeginState;
8710
8711     /* Unpick the terminal-speed string. */
8712     /* XXX perhaps we should allow no speeds to be sent. */
8713     ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8714     sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8715     /* Build the pty request. */
8716     pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8717                                ssh2_setup_pty, s);
8718     ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8719     ssh2_pkt_adduint32(pktout, ssh->term_width);
8720     ssh2_pkt_adduint32(pktout, ssh->term_height);
8721     ssh2_pkt_adduint32(pktout, 0);             /* pixel width */
8722     ssh2_pkt_adduint32(pktout, 0);             /* pixel height */
8723     ssh2_pkt_addstring_start(pktout);
8724     parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8725     ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8726     ssh2_pkt_adduint32(pktout, ssh->ispeed);
8727     ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8728     ssh2_pkt_adduint32(pktout, ssh->ospeed);
8729     ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8730     ssh2_pkt_send(ssh, pktout);
8731     ssh->state = SSH_STATE_INTERMED;
8732
8733     /* Wait to be called back with either a response packet, or NULL
8734      * meaning clean up and free our data */
8735     crReturnV;
8736
8737     if (pktin) {
8738         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8739             logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8740                       ssh->ospeed, ssh->ispeed);
8741             ssh->got_pty = TRUE;
8742         } else {
8743             c_write_str(ssh, "Server refused to allocate pty\r\n");
8744             ssh->editing = ssh->echoing = 1;
8745         }
8746     }
8747
8748     crFinishFreeV;
8749 }
8750
8751 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8752                            void *ctx)
8753 {
8754     struct ssh2_setup_env_state {
8755         int crLine;
8756         int num_env, env_left, env_ok;
8757     };
8758     Ssh ssh = c->ssh;
8759     struct Packet *pktout;
8760     crStateP(ssh2_setup_env_state, ctx);
8761
8762     crBeginState;
8763
8764     /*
8765      * Send environment variables.
8766      * 
8767      * Simplest thing here is to send all the requests at once, and
8768      * then wait for a whole bunch of successes or failures.
8769      */
8770     s->num_env = 0;
8771     {
8772         char *key, *val;
8773
8774         for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8775              val != NULL;
8776              val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8777             pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8778             ssh2_pkt_addstring(pktout, key);
8779             ssh2_pkt_addstring(pktout, val);
8780             ssh2_pkt_send(ssh, pktout);
8781
8782             s->num_env++;
8783         }
8784         if (s->num_env)
8785             logeventf(ssh, "Sent %d environment variables", s->num_env);
8786     }
8787
8788     if (s->num_env) {
8789         s->env_ok = 0;
8790         s->env_left = s->num_env;
8791
8792         while (s->env_left > 0) {
8793             /* Wait to be called back with either a response packet,
8794              * or NULL meaning clean up and free our data */
8795             crReturnV;
8796             if (!pktin) goto out;
8797             if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8798                 s->env_ok++;
8799             s->env_left--;
8800         }
8801
8802         if (s->env_ok == s->num_env) {
8803             logevent("All environment variables successfully set");
8804         } else if (s->env_ok == 0) {
8805             logevent("All environment variables refused");
8806             c_write_str(ssh, "Server refused to set environment variables\r\n");
8807         } else {
8808             logeventf(ssh, "%d environment variables refused",
8809                       s->num_env - s->env_ok);
8810             c_write_str(ssh, "Server refused to set all environment variables\r\n");
8811         }
8812     }
8813   out:;
8814     crFinishFreeV;
8815 }
8816
8817 /*
8818  * Handle the SSH-2 userauth and connection layers.
8819  */
8820 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8821 {
8822     do_ssh2_authconn(ssh, NULL, 0, pktin);
8823 }
8824
8825 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8826                                    void *ctx)
8827 {
8828     if (pktin)
8829         do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8830 }
8831
8832 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8833                              struct Packet *pktin)
8834 {
8835     struct do_ssh2_authconn_state {
8836         int crLine;
8837         enum {
8838             AUTH_TYPE_NONE,
8839                 AUTH_TYPE_PUBLICKEY,
8840                 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8841                 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8842                 AUTH_TYPE_PASSWORD,
8843                 AUTH_TYPE_GSSAPI,      /* always QUIET */
8844                 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8845                 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8846         } type;
8847         int done_service_req;
8848         int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8849         int tried_pubkey_config, done_agent;
8850 #ifndef NO_GSSAPI
8851         int can_gssapi;
8852         int tried_gssapi;
8853 #endif
8854         int kbd_inter_refused;
8855         int we_are_in, userauth_success;
8856         prompts_t *cur_prompt;
8857         int num_prompts;
8858         char *username;
8859         char *password;
8860         int got_username;
8861         void *publickey_blob;
8862         int publickey_bloblen;
8863         int privatekey_available, privatekey_encrypted;
8864         char *publickey_algorithm;
8865         char *publickey_comment;
8866         unsigned char agent_request[5], *agent_response, *agentp;
8867         int agent_responselen;
8868         unsigned char *pkblob_in_agent;
8869         int keyi, nkeys;
8870         char *pkblob, *alg, *commentp;
8871         int pklen, alglen, commentlen;
8872         int siglen, retlen, len;
8873         char *q, *agentreq, *ret;
8874         int try_send;
8875         struct Packet *pktout;
8876         Filename *keyfile;
8877 #ifndef NO_GSSAPI
8878         struct ssh_gss_library *gsslib;
8879         Ssh_gss_ctx gss_ctx;
8880         Ssh_gss_buf gss_buf;
8881         Ssh_gss_buf gss_rcvtok, gss_sndtok;
8882         Ssh_gss_name gss_srv_name;
8883         Ssh_gss_stat gss_stat;
8884 #endif
8885     };
8886     crState(do_ssh2_authconn_state);
8887
8888     crBeginState;
8889
8890     /* Register as a handler for all the messages this coroutine handles. */
8891     ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8892     ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8893     ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8894     ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8895     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8896     ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8897     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8898     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8899     ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8900     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8901     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8902     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8903     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8904     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8905     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8906     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8907     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8908     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8909     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8910     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8911     
8912     s->done_service_req = FALSE;
8913     s->we_are_in = s->userauth_success = FALSE;
8914     s->agent_response = NULL;
8915 #ifndef NO_GSSAPI
8916     s->tried_gssapi = FALSE;
8917 #endif
8918
8919     if (!ssh->bare_connection) {
8920         if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8921             /*
8922              * Request userauth protocol, and await a response to it.
8923              */
8924             s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8925             ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8926             ssh2_pkt_send(ssh, s->pktout);
8927             crWaitUntilV(pktin);
8928             if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8929                 s->done_service_req = TRUE;
8930         }
8931         if (!s->done_service_req) {
8932             /*
8933              * Request connection protocol directly, without authentication.
8934              */
8935             s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8936             ssh2_pkt_addstring(s->pktout, "ssh-connection");
8937             ssh2_pkt_send(ssh, s->pktout);
8938             crWaitUntilV(pktin);
8939             if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8940                 s->we_are_in = TRUE; /* no auth required */
8941             } else {
8942                 bombout(("Server refused service request"));
8943                 crStopV;
8944             }
8945         }
8946     } else {
8947         s->we_are_in = TRUE;
8948     }
8949
8950     /* Arrange to be able to deal with any BANNERs that come in.
8951      * (We do this now as packets may come in during the next bit.) */
8952     bufchain_init(&ssh->banner);
8953     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8954         ssh2_msg_userauth_banner;
8955
8956     /*
8957      * Misc one-time setup for authentication.
8958      */
8959     s->publickey_blob = NULL;
8960     if (!s->we_are_in) {
8961
8962         /*
8963          * Load the public half of any configured public key file
8964          * for later use.
8965          */
8966         s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8967         if (!filename_is_null(s->keyfile)) {
8968             int keytype;
8969             logeventf(ssh, "Reading key file \"%.150s\"",
8970                       filename_to_str(s->keyfile));
8971             keytype = key_type(s->keyfile);
8972             if (keytype == SSH_KEYTYPE_SSH2 ||
8973                 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
8974                 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
8975                 const char *error;
8976                 s->publickey_blob =
8977                     ssh2_userkey_loadpub(s->keyfile,
8978                                          &s->publickey_algorithm,
8979                                          &s->publickey_bloblen, 
8980                                          &s->publickey_comment, &error);
8981                 if (s->publickey_blob) {
8982                     s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
8983                     if (!s->privatekey_available)
8984                         logeventf(ssh, "Key file contains public key only");
8985                     s->privatekey_encrypted =
8986                         ssh2_userkey_encrypted(s->keyfile, NULL);
8987                 } else {
8988                     char *msgbuf;
8989                     logeventf(ssh, "Unable to load key (%s)", 
8990                               error);
8991                     msgbuf = dupprintf("Unable to load key file "
8992                                        "\"%.150s\" (%s)\r\n",
8993                                        filename_to_str(s->keyfile),
8994                                        error);
8995                     c_write_str(ssh, msgbuf);
8996                     sfree(msgbuf);
8997                 }
8998             } else {
8999                 char *msgbuf;
9000                 logeventf(ssh, "Unable to use this key file (%s)",
9001                           key_type_to_str(keytype));
9002                 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9003                                    " (%s)\r\n",
9004                                    filename_to_str(s->keyfile),
9005                                    key_type_to_str(keytype));
9006                 c_write_str(ssh, msgbuf);
9007                 sfree(msgbuf);
9008                 s->publickey_blob = NULL;
9009             }
9010         }
9011
9012         /*
9013          * Find out about any keys Pageant has (but if there's a
9014          * public key configured, filter out all others).
9015          */
9016         s->nkeys = 0;
9017         s->agent_response = NULL;
9018         s->pkblob_in_agent = NULL;
9019         if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9020
9021             void *r;
9022
9023             logevent("Pageant is running. Requesting keys.");
9024
9025             /* Request the keys held by the agent. */
9026             PUT_32BIT(s->agent_request, 1);
9027             s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9028             if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9029                              ssh_agent_callback, ssh)) {
9030                 do {
9031                     crReturnV;
9032                     if (pktin) {
9033                         bombout(("Unexpected data from server while"
9034                                  " waiting for agent response"));
9035                         crStopV;
9036                     }
9037                 } while (pktin || inlen > 0);
9038                 r = ssh->agent_response;
9039                 s->agent_responselen = ssh->agent_response_len;
9040             }
9041             s->agent_response = (unsigned char *) r;
9042             if (s->agent_response && s->agent_responselen >= 5 &&
9043                 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9044                 int keyi;
9045                 unsigned char *p;
9046                 p = s->agent_response + 5;
9047                 s->nkeys = toint(GET_32BIT(p));
9048
9049                 /*
9050                  * Vet the Pageant response to ensure that the key
9051                  * count and blob lengths make sense.
9052                  */
9053                 if (s->nkeys < 0) {
9054                     logeventf(ssh, "Pageant response contained a negative"
9055                               " key count %d", s->nkeys);
9056                     s->nkeys = 0;
9057                     goto done_agent_query;
9058                 } else {
9059                     unsigned char *q = p + 4;
9060                     int lenleft = s->agent_responselen - 5 - 4;
9061
9062                     for (keyi = 0; keyi < s->nkeys; keyi++) {
9063                         int bloblen, commentlen;
9064                         if (lenleft < 4) {
9065                             logeventf(ssh, "Pageant response was truncated");
9066                             s->nkeys = 0;
9067                             goto done_agent_query;
9068                         }
9069                         bloblen = toint(GET_32BIT(q));
9070                         if (bloblen < 0 || bloblen > lenleft) {
9071                             logeventf(ssh, "Pageant response was truncated");
9072                             s->nkeys = 0;
9073                             goto done_agent_query;
9074                         }
9075                         lenleft -= 4 + bloblen;
9076                         q += 4 + bloblen;
9077                         commentlen = toint(GET_32BIT(q));
9078                         if (commentlen < 0 || commentlen > lenleft) {
9079                             logeventf(ssh, "Pageant response was truncated");
9080                             s->nkeys = 0;
9081                             goto done_agent_query;
9082                         }
9083                         lenleft -= 4 + commentlen;
9084                         q += 4 + commentlen;
9085                     }
9086                 }
9087
9088                 p += 4;
9089                 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9090                 if (s->publickey_blob) {
9091                     /* See if configured key is in agent. */
9092                     for (keyi = 0; keyi < s->nkeys; keyi++) {
9093                         s->pklen = toint(GET_32BIT(p));
9094                         if (s->pklen == s->publickey_bloblen &&
9095                             !memcmp(p+4, s->publickey_blob,
9096                                     s->publickey_bloblen)) {
9097                             logeventf(ssh, "Pageant key #%d matches "
9098                                       "configured key file", keyi);
9099                             s->keyi = keyi;
9100                             s->pkblob_in_agent = p;
9101                             break;
9102                         }
9103                         p += 4 + s->pklen;
9104                         p += toint(GET_32BIT(p)) + 4; /* comment */
9105                     }
9106                     if (!s->pkblob_in_agent) {
9107                         logevent("Configured key file not in Pageant");
9108                         s->nkeys = 0;
9109                     }
9110                 }
9111             } else {
9112                 logevent("Failed to get reply from Pageant");
9113             }
9114           done_agent_query:;
9115         }
9116
9117     }
9118
9119     /*
9120      * We repeat this whole loop, including the username prompt,
9121      * until we manage a successful authentication. If the user
9122      * types the wrong _password_, they can be sent back to the
9123      * beginning to try another username, if this is configured on.
9124      * (If they specify a username in the config, they are never
9125      * asked, even if they do give a wrong password.)
9126      * 
9127      * I think this best serves the needs of
9128      * 
9129      *  - the people who have no configuration, no keys, and just
9130      *    want to try repeated (username,password) pairs until they
9131      *    type both correctly
9132      * 
9133      *  - people who have keys and configuration but occasionally
9134      *    need to fall back to passwords
9135      * 
9136      *  - people with a key held in Pageant, who might not have
9137      *    logged in to a particular machine before; so they want to
9138      *    type a username, and then _either_ their key will be
9139      *    accepted, _or_ they will type a password. If they mistype
9140      *    the username they will want to be able to get back and
9141      *    retype it!
9142      */
9143     s->got_username = FALSE;
9144     while (!s->we_are_in) {
9145         /*
9146          * Get a username.
9147          */
9148         if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9149             /*
9150              * We got a username last time round this loop, and
9151              * with change_username turned off we don't try to get
9152              * it again.
9153              */
9154         } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9155             int ret; /* need not be kept over crReturn */
9156             s->cur_prompt = new_prompts(ssh->frontend);
9157             s->cur_prompt->to_server = TRUE;
9158             s->cur_prompt->name = dupstr("SSH login name");
9159             add_prompt(s->cur_prompt, dupstr("login as: "), TRUE); 
9160             ret = get_userpass_input(s->cur_prompt, NULL, 0);
9161             while (ret < 0) {
9162                 ssh->send_ok = 1;
9163                 crWaitUntilV(!pktin);
9164                 ret = get_userpass_input(s->cur_prompt, in, inlen);
9165                 ssh->send_ok = 0;
9166             }
9167             if (!ret) {
9168                 /*
9169                  * get_userpass_input() failed to get a username.
9170                  * Terminate.
9171                  */
9172                 free_prompts(s->cur_prompt);
9173                 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9174                 crStopV;
9175             }
9176             ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9177             free_prompts(s->cur_prompt);
9178         } else {
9179             char *stuff;
9180             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9181                 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9182                 c_write_str(ssh, stuff);
9183                 sfree(stuff);
9184             }
9185         }
9186         s->got_username = TRUE;
9187
9188         /*
9189          * Send an authentication request using method "none": (a)
9190          * just in case it succeeds, and (b) so that we know what
9191          * authentication methods we can usefully try next.
9192          */
9193         ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9194
9195         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9196         ssh2_pkt_addstring(s->pktout, ssh->username);
9197         ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9198         ssh2_pkt_addstring(s->pktout, "none");    /* method */
9199         ssh2_pkt_send(ssh, s->pktout);
9200         s->type = AUTH_TYPE_NONE;
9201         s->gotit = FALSE;
9202         s->we_are_in = FALSE;
9203
9204         s->tried_pubkey_config = FALSE;
9205         s->kbd_inter_refused = FALSE;
9206
9207         /* Reset agent request state. */
9208         s->done_agent = FALSE;
9209         if (s->agent_response) {
9210             if (s->pkblob_in_agent) {
9211                 s->agentp = s->pkblob_in_agent;
9212             } else {
9213                 s->agentp = s->agent_response + 5 + 4;
9214                 s->keyi = 0;
9215             }
9216         }
9217
9218         while (1) {
9219             char *methods = NULL;
9220             int methlen = 0;
9221
9222             /*
9223              * Wait for the result of the last authentication request.
9224              */
9225             if (!s->gotit)
9226                 crWaitUntilV(pktin);
9227             /*
9228              * Now is a convenient point to spew any banner material
9229              * that we've accumulated. (This should ensure that when
9230              * we exit the auth loop, we haven't any left to deal
9231              * with.)
9232              */
9233             {
9234                 int size = bufchain_size(&ssh->banner);
9235                 /*
9236                  * Don't show the banner if we're operating in
9237                  * non-verbose non-interactive mode. (It's probably
9238                  * a script, which means nobody will read the
9239                  * banner _anyway_, and moreover the printing of
9240                  * the banner will screw up processing on the
9241                  * output of (say) plink.)
9242                  */
9243                 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9244                     char *banner = snewn(size, char);
9245                     bufchain_fetch(&ssh->banner, banner, size);
9246                     c_write_untrusted(ssh, banner, size);
9247                     sfree(banner);
9248                 }
9249                 bufchain_clear(&ssh->banner);
9250             }
9251             if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9252                 logevent("Access granted");
9253                 s->we_are_in = s->userauth_success = TRUE;
9254                 break;
9255             }
9256
9257             if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9258                 bombout(("Strange packet received during authentication: "
9259                          "type %d", pktin->type));
9260                 crStopV;
9261             }
9262
9263             s->gotit = FALSE;
9264
9265             /*
9266              * OK, we're now sitting on a USERAUTH_FAILURE message, so
9267              * we can look at the string in it and know what we can
9268              * helpfully try next.
9269              */
9270             if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9271                 ssh_pkt_getstring(pktin, &methods, &methlen);
9272                 if (!ssh2_pkt_getbool(pktin)) {
9273                     /*
9274                      * We have received an unequivocal Access
9275                      * Denied. This can translate to a variety of
9276                      * messages, or no message at all.
9277                      *
9278                      * For forms of authentication which are attempted
9279                      * implicitly, by which I mean without printing
9280                      * anything in the window indicating that we're
9281                      * trying them, we should never print 'Access
9282                      * denied'.
9283                      *
9284                      * If we do print a message saying that we're
9285                      * attempting some kind of authentication, it's OK
9286                      * to print a followup message saying it failed -
9287                      * but the message may sometimes be more specific
9288                      * than simply 'Access denied'.
9289                      *
9290                      * Additionally, if we'd just tried password
9291                      * authentication, we should break out of this
9292                      * whole loop so as to go back to the username
9293                      * prompt (iff we're configured to allow
9294                      * username change attempts).
9295                      */
9296                     if (s->type == AUTH_TYPE_NONE) {
9297                         /* do nothing */
9298                     } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9299                                s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9300                         if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9301                             c_write_str(ssh, "Server refused our key\r\n");
9302                         logevent("Server refused our key");
9303                     } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9304                         /* This _shouldn't_ happen except by a
9305                          * protocol bug causing client and server to
9306                          * disagree on what is a correct signature. */
9307                         c_write_str(ssh, "Server refused public-key signature"
9308                                     " despite accepting key!\r\n");
9309                         logevent("Server refused public-key signature"
9310                                  " despite accepting key!");
9311                     } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9312                         /* quiet, so no c_write */
9313                         logevent("Server refused keyboard-interactive authentication");
9314                     } else if (s->type==AUTH_TYPE_GSSAPI) {
9315                         /* always quiet, so no c_write */
9316                         /* also, the code down in the GSSAPI block has
9317                          * already logged this in the Event Log */
9318                     } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9319                         logevent("Keyboard-interactive authentication failed");
9320                         c_write_str(ssh, "Access denied\r\n");
9321                     } else {
9322                         assert(s->type == AUTH_TYPE_PASSWORD);
9323                         logevent("Password authentication failed");
9324                         c_write_str(ssh, "Access denied\r\n");
9325
9326                         if (conf_get_int(ssh->conf, CONF_change_username)) {
9327                             /* XXX perhaps we should allow
9328                              * keyboard-interactive to do this too? */
9329                             s->we_are_in = FALSE;
9330                             break;
9331                         }
9332                     }
9333                 } else {
9334                     c_write_str(ssh, "Further authentication required\r\n");
9335                     logevent("Further authentication required");
9336                 }
9337
9338                 s->can_pubkey =
9339                     in_commasep_string("publickey", methods, methlen);
9340                 s->can_passwd =
9341                     in_commasep_string("password", methods, methlen);
9342                 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9343                     in_commasep_string("keyboard-interactive", methods, methlen);
9344 #ifndef NO_GSSAPI
9345                 if (!ssh->gsslibs)
9346                     ssh->gsslibs = ssh_gss_setup(ssh->conf);
9347                 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9348                     in_commasep_string("gssapi-with-mic", methods, methlen) &&
9349                     ssh->gsslibs->nlibraries > 0;
9350 #endif
9351             }
9352
9353             ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9354
9355             if (s->can_pubkey && !s->done_agent && s->nkeys) {
9356
9357                 /*
9358                  * Attempt public-key authentication using a key from Pageant.
9359                  */
9360
9361                 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9362
9363                 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9364
9365                 /* Unpack key from agent response */
9366                 s->pklen = toint(GET_32BIT(s->agentp));
9367                 s->agentp += 4;
9368                 s->pkblob = (char *)s->agentp;
9369                 s->agentp += s->pklen;
9370                 s->alglen = toint(GET_32BIT(s->pkblob));
9371                 s->alg = s->pkblob + 4;
9372                 s->commentlen = toint(GET_32BIT(s->agentp));
9373                 s->agentp += 4;
9374                 s->commentp = (char *)s->agentp;
9375                 s->agentp += s->commentlen;
9376                 /* s->agentp now points at next key, if any */
9377
9378                 /* See if server will accept it */
9379                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9380                 ssh2_pkt_addstring(s->pktout, ssh->username);
9381                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9382                                                     /* service requested */
9383                 ssh2_pkt_addstring(s->pktout, "publickey");
9384                                                     /* method */
9385                 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9386                 ssh2_pkt_addstring_start(s->pktout);
9387                 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9388                 ssh2_pkt_addstring_start(s->pktout);
9389                 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9390                 ssh2_pkt_send(ssh, s->pktout);
9391                 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9392
9393                 crWaitUntilV(pktin);
9394                 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9395
9396                     /* Offer of key refused. */
9397                     s->gotit = TRUE;
9398
9399                 } else {
9400                     
9401                     void *vret;
9402
9403                     if (flags & FLAG_VERBOSE) {
9404                         c_write_str(ssh, "Authenticating with "
9405                                     "public key \"");
9406                         c_write(ssh, s->commentp, s->commentlen);
9407                         c_write_str(ssh, "\" from agent\r\n");
9408                     }
9409
9410                     /*
9411                      * Server is willing to accept the key.
9412                      * Construct a SIGN_REQUEST.
9413                      */
9414                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9415                     ssh2_pkt_addstring(s->pktout, ssh->username);
9416                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
9417                                                         /* service requested */
9418                     ssh2_pkt_addstring(s->pktout, "publickey");
9419                                                         /* method */
9420                     ssh2_pkt_addbool(s->pktout, TRUE);  /* signature included */
9421                     ssh2_pkt_addstring_start(s->pktout);
9422                     ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9423                     ssh2_pkt_addstring_start(s->pktout);
9424                     ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9425
9426                     /* Ask agent for signature. */
9427                     s->siglen = s->pktout->length - 5 + 4 +
9428                         ssh->v2_session_id_len;
9429                     if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9430                         s->siglen -= 4;
9431                     s->len = 1;       /* message type */
9432                     s->len += 4 + s->pklen;     /* key blob */
9433                     s->len += 4 + s->siglen;    /* data to sign */
9434                     s->len += 4;      /* flags */
9435                     s->agentreq = snewn(4 + s->len, char);
9436                     PUT_32BIT(s->agentreq, s->len);
9437                     s->q = s->agentreq + 4;
9438                     *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9439                     PUT_32BIT(s->q, s->pklen);
9440                     s->q += 4;
9441                     memcpy(s->q, s->pkblob, s->pklen);
9442                     s->q += s->pklen;
9443                     PUT_32BIT(s->q, s->siglen);
9444                     s->q += 4;
9445                     /* Now the data to be signed... */
9446                     if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9447                         PUT_32BIT(s->q, ssh->v2_session_id_len);
9448                         s->q += 4;
9449                     }
9450                     memcpy(s->q, ssh->v2_session_id,
9451                            ssh->v2_session_id_len);
9452                     s->q += ssh->v2_session_id_len;
9453                     memcpy(s->q, s->pktout->data + 5,
9454                            s->pktout->length - 5);
9455                     s->q += s->pktout->length - 5;
9456                     /* And finally the (zero) flags word. */
9457                     PUT_32BIT(s->q, 0);
9458                     if (!agent_query(s->agentreq, s->len + 4,
9459                                      &vret, &s->retlen,
9460                                      ssh_agent_callback, ssh)) {
9461                         do {
9462                             crReturnV;
9463                             if (pktin) {
9464                                 bombout(("Unexpected data from server"
9465                                          " while waiting for agent"
9466                                          " response"));
9467                                 crStopV;
9468                             }
9469                         } while (pktin || inlen > 0);
9470                         vret = ssh->agent_response;
9471                         s->retlen = ssh->agent_response_len;
9472                     }
9473                     s->ret = vret;
9474                     sfree(s->agentreq);
9475                     if (s->ret) {
9476                         if (s->retlen >= 9 &&
9477                             s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9478                             GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9479                             logevent("Sending Pageant's response");
9480                             ssh2_add_sigblob(ssh, s->pktout,
9481                                              s->pkblob, s->pklen,
9482                                              s->ret + 9,
9483                                              GET_32BIT(s->ret + 5));
9484                             ssh2_pkt_send(ssh, s->pktout);
9485                             s->type = AUTH_TYPE_PUBLICKEY;
9486                         } else {
9487                             /* FIXME: less drastic response */
9488                             bombout(("Pageant failed to answer challenge"));
9489                             crStopV;
9490                         }
9491                     }
9492                 }
9493
9494                 /* Do we have any keys left to try? */
9495                 if (s->pkblob_in_agent) {
9496                     s->done_agent = TRUE;
9497                     s->tried_pubkey_config = TRUE;
9498                 } else {
9499                     s->keyi++;
9500                     if (s->keyi >= s->nkeys)
9501                         s->done_agent = TRUE;
9502                 }
9503
9504             } else if (s->can_pubkey && s->publickey_blob &&
9505                        s->privatekey_available && !s->tried_pubkey_config) {
9506
9507                 struct ssh2_userkey *key;   /* not live over crReturn */
9508                 char *passphrase;           /* not live over crReturn */
9509
9510                 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9511
9512                 s->tried_pubkey_config = TRUE;
9513
9514                 /*
9515                  * Try the public key supplied in the configuration.
9516                  *
9517                  * First, offer the public blob to see if the server is
9518                  * willing to accept it.
9519                  */
9520                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9521                 ssh2_pkt_addstring(s->pktout, ssh->username);
9522                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9523                                                 /* service requested */
9524                 ssh2_pkt_addstring(s->pktout, "publickey");     /* method */
9525                 ssh2_pkt_addbool(s->pktout, FALSE);
9526                                                 /* no signature included */
9527                 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9528                 ssh2_pkt_addstring_start(s->pktout);
9529                 ssh2_pkt_addstring_data(s->pktout,
9530                                         (char *)s->publickey_blob,
9531                                         s->publickey_bloblen);
9532                 ssh2_pkt_send(ssh, s->pktout);
9533                 logevent("Offered public key");
9534
9535                 crWaitUntilV(pktin);
9536                 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9537                     /* Key refused. Give up. */
9538                     s->gotit = TRUE; /* reconsider message next loop */
9539                     s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9540                     continue; /* process this new message */
9541                 }
9542                 logevent("Offer of public key accepted");
9543
9544                 /*
9545                  * Actually attempt a serious authentication using
9546                  * the key.
9547                  */
9548                 if (flags & FLAG_VERBOSE) {
9549                     c_write_str(ssh, "Authenticating with public key \"");
9550                     c_write_str(ssh, s->publickey_comment);
9551                     c_write_str(ssh, "\"\r\n");
9552                 }
9553                 key = NULL;
9554                 while (!key) {
9555                     const char *error;  /* not live over crReturn */
9556                     if (s->privatekey_encrypted) {
9557                         /*
9558                          * Get a passphrase from the user.
9559                          */
9560                         int ret; /* need not be kept over crReturn */
9561                         s->cur_prompt = new_prompts(ssh->frontend);
9562                         s->cur_prompt->to_server = FALSE;
9563                         s->cur_prompt->name = dupstr("SSH key passphrase");
9564                         add_prompt(s->cur_prompt,
9565                                    dupprintf("Passphrase for key \"%.100s\": ",
9566                                              s->publickey_comment),
9567                                    FALSE);
9568                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
9569                         while (ret < 0) {
9570                             ssh->send_ok = 1;
9571                             crWaitUntilV(!pktin);
9572                             ret = get_userpass_input(s->cur_prompt,
9573                                                      in, inlen);
9574                             ssh->send_ok = 0;
9575                         }
9576                         if (!ret) {
9577                             /* Failed to get a passphrase. Terminate. */
9578                             free_prompts(s->cur_prompt);
9579                             ssh_disconnect(ssh, NULL,
9580                                            "Unable to authenticate",
9581                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9582                                            TRUE);
9583                             crStopV;
9584                         }
9585                         passphrase =
9586                             dupstr(s->cur_prompt->prompts[0]->result);
9587                         free_prompts(s->cur_prompt);
9588                     } else {
9589                         passphrase = NULL; /* no passphrase needed */
9590                     }
9591
9592                     /*
9593                      * Try decrypting the key.
9594                      */
9595                     s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9596                     key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9597                     if (passphrase) {
9598                         /* burn the evidence */
9599                         smemclr(passphrase, strlen(passphrase));
9600                         sfree(passphrase);
9601                     }
9602                     if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9603                         if (passphrase &&
9604                             (key == SSH2_WRONG_PASSPHRASE)) {
9605                             c_write_str(ssh, "Wrong passphrase\r\n");
9606                             key = NULL;
9607                             /* and loop again */
9608                         } else {
9609                             c_write_str(ssh, "Unable to load private key (");
9610                             c_write_str(ssh, error);
9611                             c_write_str(ssh, ")\r\n");
9612                             key = NULL;
9613                             break; /* try something else */
9614                         }
9615                     }
9616                 }
9617
9618                 if (key) {
9619                     unsigned char *pkblob, *sigblob, *sigdata;
9620                     int pkblob_len, sigblob_len, sigdata_len;
9621                     int p;
9622
9623                     /*
9624                      * We have loaded the private key and the server
9625                      * has announced that it's willing to accept it.
9626                      * Hallelujah. Generate a signature and send it.
9627                      */
9628                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9629                     ssh2_pkt_addstring(s->pktout, ssh->username);
9630                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
9631                                                     /* service requested */
9632                     ssh2_pkt_addstring(s->pktout, "publickey");
9633                                                     /* method */
9634                     ssh2_pkt_addbool(s->pktout, TRUE);
9635                                                     /* signature follows */
9636                     ssh2_pkt_addstring(s->pktout, key->alg->name);
9637                     pkblob = key->alg->public_blob(key->data,
9638                                                    &pkblob_len);
9639                     ssh2_pkt_addstring_start(s->pktout);
9640                     ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9641                                             pkblob_len);
9642
9643                     /*
9644                      * The data to be signed is:
9645                      *
9646                      *   string  session-id
9647                      *
9648                      * followed by everything so far placed in the
9649                      * outgoing packet.
9650                      */
9651                     sigdata_len = s->pktout->length - 5 + 4 +
9652                         ssh->v2_session_id_len;
9653                     if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9654                         sigdata_len -= 4;
9655                     sigdata = snewn(sigdata_len, unsigned char);
9656                     p = 0;
9657                     if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9658                         PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9659                         p += 4;
9660                     }
9661                     memcpy(sigdata+p, ssh->v2_session_id,
9662                            ssh->v2_session_id_len);
9663                     p += ssh->v2_session_id_len;
9664                     memcpy(sigdata+p, s->pktout->data + 5,
9665                            s->pktout->length - 5);
9666                     p += s->pktout->length - 5;
9667                     assert(p == sigdata_len);
9668                     sigblob = key->alg->sign(key->data, (char *)sigdata,
9669                                              sigdata_len, &sigblob_len);
9670                     ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9671                                      sigblob, sigblob_len);
9672                     sfree(pkblob);
9673                     sfree(sigblob);
9674                     sfree(sigdata);
9675
9676                     ssh2_pkt_send(ssh, s->pktout);
9677                     logevent("Sent public key signature");
9678                     s->type = AUTH_TYPE_PUBLICKEY;
9679                     key->alg->freekey(key->data);
9680                     sfree(key->comment);
9681                     sfree(key);
9682                 }
9683
9684 #ifndef NO_GSSAPI
9685             } else if (s->can_gssapi && !s->tried_gssapi) {
9686
9687                 /* GSSAPI Authentication */
9688
9689                 int micoffset, len;
9690                 char *data;
9691                 Ssh_gss_buf mic;
9692                 s->type = AUTH_TYPE_GSSAPI;
9693                 s->tried_gssapi = TRUE;
9694                 s->gotit = TRUE;
9695                 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9696
9697                 /*
9698                  * Pick the highest GSS library on the preference
9699                  * list.
9700                  */
9701                 {
9702                     int i, j;
9703                     s->gsslib = NULL;
9704                     for (i = 0; i < ngsslibs; i++) {
9705                         int want_id = conf_get_int_int(ssh->conf,
9706                                                        CONF_ssh_gsslist, i);
9707                         for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9708                             if (ssh->gsslibs->libraries[j].id == want_id) {
9709                                 s->gsslib = &ssh->gsslibs->libraries[j];
9710                                 goto got_gsslib;   /* double break */
9711                             }
9712                     }
9713                     got_gsslib:
9714                     /*
9715                      * We always expect to have found something in
9716                      * the above loop: we only came here if there
9717                      * was at least one viable GSS library, and the
9718                      * preference list should always mention
9719                      * everything and only change the order.
9720                      */
9721                     assert(s->gsslib);
9722                 }
9723
9724                 if (s->gsslib->gsslogmsg)
9725                     logevent(s->gsslib->gsslogmsg);
9726
9727                 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9728                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9729                 ssh2_pkt_addstring(s->pktout, ssh->username);
9730                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9731                 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9732                 logevent("Attempting GSSAPI authentication");
9733
9734                 /* add mechanism info */
9735                 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9736
9737                 /* number of GSSAPI mechanisms */
9738                 ssh2_pkt_adduint32(s->pktout,1);
9739
9740                 /* length of OID + 2 */
9741                 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9742                 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9743
9744                 /* length of OID */
9745                 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9746
9747                 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9748                                 s->gss_buf.length);
9749                 ssh2_pkt_send(ssh, s->pktout);
9750                 crWaitUntilV(pktin);
9751                 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9752                     logevent("GSSAPI authentication request refused");
9753                     continue;
9754                 }
9755
9756                 /* check returned packet ... */
9757
9758                 ssh_pkt_getstring(pktin, &data, &len);
9759                 s->gss_rcvtok.value = data;
9760                 s->gss_rcvtok.length = len;
9761                 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9762                     ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9763                     ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9764                     memcmp((char *)s->gss_rcvtok.value + 2,
9765                            s->gss_buf.value,s->gss_buf.length) ) {
9766                     logevent("GSSAPI authentication - wrong response from server");
9767                     continue;
9768                 }
9769
9770                 /* now start running */
9771                 s->gss_stat = s->gsslib->import_name(s->gsslib,
9772                                                      ssh->fullhostname,
9773                                                      &s->gss_srv_name);
9774                 if (s->gss_stat != SSH_GSS_OK) {
9775                     if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9776                         logevent("GSSAPI import name failed - Bad service name");
9777                     else
9778                         logevent("GSSAPI import name failed");
9779                     continue;
9780                 }
9781
9782                 /* fetch TGT into GSS engine */
9783                 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9784
9785                 if (s->gss_stat != SSH_GSS_OK) {
9786                     logevent("GSSAPI authentication failed to get credentials");
9787                     s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9788                     continue;
9789                 }
9790
9791                 /* initial tokens are empty */
9792                 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9793                 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9794
9795                 /* now enter the loop */
9796                 do {
9797                     s->gss_stat = s->gsslib->init_sec_context
9798                         (s->gsslib,
9799                          &s->gss_ctx,
9800                          s->gss_srv_name,
9801                          conf_get_int(ssh->conf, CONF_gssapifwd),
9802                          &s->gss_rcvtok,
9803                          &s->gss_sndtok);
9804
9805                     if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9806                         s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9807                         logevent("GSSAPI authentication initialisation failed");
9808
9809                         if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9810                                                       &s->gss_buf) == SSH_GSS_OK) {
9811                             logevent(s->gss_buf.value);
9812                             sfree(s->gss_buf.value);
9813                         }
9814
9815                         break;
9816                     }
9817                     logevent("GSSAPI authentication initialised");
9818
9819                     /* Client and server now exchange tokens until GSSAPI
9820                      * no longer says CONTINUE_NEEDED */
9821
9822                     if (s->gss_sndtok.length != 0) {
9823                         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9824                         ssh_pkt_addstring_start(s->pktout);
9825                         ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9826                         ssh2_pkt_send(ssh, s->pktout);
9827                         s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9828                     }
9829
9830                     if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9831                         crWaitUntilV(pktin);
9832                         if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9833                             logevent("GSSAPI authentication - bad server response");
9834                             s->gss_stat = SSH_GSS_FAILURE;
9835                             break;
9836                         }
9837                         ssh_pkt_getstring(pktin, &data, &len);
9838                         s->gss_rcvtok.value = data;
9839                         s->gss_rcvtok.length = len;
9840                     }
9841                 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9842
9843                 if (s->gss_stat != SSH_GSS_OK) {
9844                     s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9845                     s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9846                     continue;
9847                 }
9848                 logevent("GSSAPI authentication loop finished OK");
9849
9850                 /* Now send the MIC */
9851
9852                 s->pktout = ssh2_pkt_init(0);
9853                 micoffset = s->pktout->length;
9854                 ssh_pkt_addstring_start(s->pktout);
9855                 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9856                 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9857                 ssh_pkt_addstring(s->pktout, ssh->username);
9858                 ssh_pkt_addstring(s->pktout, "ssh-connection");
9859                 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9860
9861                 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9862                 s->gss_buf.length = s->pktout->length - micoffset;
9863
9864                 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9865                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9866                 ssh_pkt_addstring_start(s->pktout);
9867                 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9868                 ssh2_pkt_send(ssh, s->pktout);
9869                 s->gsslib->free_mic(s->gsslib, &mic);
9870
9871                 s->gotit = FALSE;
9872
9873                 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9874                 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9875                 continue;
9876 #endif
9877             } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9878
9879                 /*
9880                  * Keyboard-interactive authentication.
9881                  */
9882
9883                 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9884
9885                 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9886
9887                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9888                 ssh2_pkt_addstring(s->pktout, ssh->username);
9889                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9890                                                         /* service requested */
9891                 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9892                                                         /* method */
9893                 ssh2_pkt_addstring(s->pktout, "");      /* lang */
9894                 ssh2_pkt_addstring(s->pktout, "");      /* submethods */
9895                 ssh2_pkt_send(ssh, s->pktout);
9896                 
9897                 logevent("Attempting keyboard-interactive authentication");
9898
9899                 crWaitUntilV(pktin);
9900                 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9901                     /* Server is not willing to do keyboard-interactive
9902                      * at all (or, bizarrely but legally, accepts the
9903                      * user without actually issuing any prompts).
9904                      * Give up on it entirely. */
9905                     s->gotit = TRUE;
9906                     s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9907                     s->kbd_inter_refused = TRUE; /* don't try it again */
9908                     continue;
9909                 }
9910
9911                 /*
9912                  * Loop while the server continues to send INFO_REQUESTs.
9913                  */
9914                 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9915
9916                     char *name, *inst, *lang;
9917                     int name_len, inst_len, lang_len;
9918                     int i;
9919
9920                     /*
9921                      * We've got a fresh USERAUTH_INFO_REQUEST.
9922                      * Get the preamble and start building a prompt.
9923                      */
9924                     ssh_pkt_getstring(pktin, &name, &name_len);
9925                     ssh_pkt_getstring(pktin, &inst, &inst_len);
9926                     ssh_pkt_getstring(pktin, &lang, &lang_len);
9927                     s->cur_prompt = new_prompts(ssh->frontend);
9928                     s->cur_prompt->to_server = TRUE;
9929
9930                     /*
9931                      * Get any prompt(s) from the packet.
9932                      */
9933                     s->num_prompts = ssh_pkt_getuint32(pktin);
9934                     for (i = 0; i < s->num_prompts; i++) {
9935                         char *prompt;
9936                         int prompt_len;
9937                         int echo;
9938                         static char noprompt[] =
9939                             "<server failed to send prompt>: ";
9940
9941                         ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9942                         echo = ssh2_pkt_getbool(pktin);
9943                         if (!prompt_len) {
9944                             prompt = noprompt;
9945                             prompt_len = lenof(noprompt)-1;
9946                         }
9947                         add_prompt(s->cur_prompt,
9948                                    dupprintf("%.*s", prompt_len, prompt),
9949                                    echo);
9950                     }
9951
9952                     if (name_len) {
9953                         /* FIXME: better prefix to distinguish from
9954                          * local prompts? */
9955                         s->cur_prompt->name =
9956                             dupprintf("SSH server: %.*s", name_len, name);
9957                         s->cur_prompt->name_reqd = TRUE;
9958                     } else {
9959                         s->cur_prompt->name =
9960                             dupstr("SSH server authentication");
9961                         s->cur_prompt->name_reqd = FALSE;
9962                     }
9963                     /* We add a prefix to try to make it clear that a prompt
9964                      * has come from the server.
9965                      * FIXME: ugly to print "Using..." in prompt _every_
9966                      * time round. Can this be done more subtly? */
9967                     /* Special case: for reasons best known to themselves,
9968                      * some servers send k-i requests with no prompts and
9969                      * nothing to display. Keep quiet in this case. */
9970                     if (s->num_prompts || name_len || inst_len) {
9971                         s->cur_prompt->instruction =
9972                             dupprintf("Using keyboard-interactive authentication.%s%.*s",
9973                                       inst_len ? "\n" : "", inst_len, inst);
9974                         s->cur_prompt->instr_reqd = TRUE;
9975                     } else {
9976                         s->cur_prompt->instr_reqd = FALSE;
9977                     }
9978
9979                     /*
9980                      * Display any instructions, and get the user's
9981                      * response(s).
9982                      */
9983                     {
9984                         int ret; /* not live over crReturn */
9985                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
9986                         while (ret < 0) {
9987                             ssh->send_ok = 1;
9988                             crWaitUntilV(!pktin);
9989                             ret = get_userpass_input(s->cur_prompt, in, inlen);
9990                             ssh->send_ok = 0;
9991                         }
9992                         if (!ret) {
9993                             /*
9994                              * Failed to get responses. Terminate.
9995                              */
9996                             free_prompts(s->cur_prompt);
9997                             ssh_disconnect(ssh, NULL, "Unable to authenticate",
9998                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9999                                            TRUE);
10000                             crStopV;
10001                         }
10002                     }
10003
10004                     /*
10005                      * Send the response(s) to the server.
10006                      */
10007                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10008                     ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10009                     for (i=0; i < s->num_prompts; i++) {
10010                         ssh2_pkt_addstring(s->pktout,
10011                                            s->cur_prompt->prompts[i]->result);
10012                     }
10013                     ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10014
10015                     /*
10016                      * Free the prompts structure from this iteration.
10017                      * If there's another, a new one will be allocated
10018                      * when we return to the top of this while loop.
10019                      */
10020                     free_prompts(s->cur_prompt);
10021
10022                     /*
10023                      * Get the next packet in case it's another
10024                      * INFO_REQUEST.
10025                      */
10026                     crWaitUntilV(pktin);
10027
10028                 }
10029
10030                 /*
10031                  * We should have SUCCESS or FAILURE now.
10032                  */
10033                 s->gotit = TRUE;
10034
10035             } else if (s->can_passwd) {
10036
10037                 /*
10038                  * Plain old password authentication.
10039                  */
10040                 int ret; /* not live over crReturn */
10041                 int changereq_first_time; /* not live over crReturn */
10042
10043                 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10044
10045                 s->cur_prompt = new_prompts(ssh->frontend);
10046                 s->cur_prompt->to_server = TRUE;
10047                 s->cur_prompt->name = dupstr("SSH password");
10048                 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10049                                                     ssh->username,
10050                                                     ssh->savedhost),
10051                            FALSE);
10052
10053                 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10054                 while (ret < 0) {
10055                     ssh->send_ok = 1;
10056                     crWaitUntilV(!pktin);
10057                     ret = get_userpass_input(s->cur_prompt, in, inlen);
10058                     ssh->send_ok = 0;
10059                 }
10060                 if (!ret) {
10061                     /*
10062                      * Failed to get responses. Terminate.
10063                      */
10064                     free_prompts(s->cur_prompt);
10065                     ssh_disconnect(ssh, NULL, "Unable to authenticate",
10066                                    SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10067                                    TRUE);
10068                     crStopV;
10069                 }
10070                 /*
10071                  * Squirrel away the password. (We may need it later if
10072                  * asked to change it.)
10073                  */
10074                 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10075                 free_prompts(s->cur_prompt);
10076
10077                 /*
10078                  * Send the password packet.
10079                  *
10080                  * We pad out the password packet to 256 bytes to make
10081                  * it harder for an attacker to find the length of the
10082                  * user's password.
10083                  *
10084                  * Anyone using a password longer than 256 bytes
10085                  * probably doesn't have much to worry about from
10086                  * people who find out how long their password is!
10087                  */
10088                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10089                 ssh2_pkt_addstring(s->pktout, ssh->username);
10090                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10091                                                         /* service requested */
10092                 ssh2_pkt_addstring(s->pktout, "password");
10093                 ssh2_pkt_addbool(s->pktout, FALSE);
10094                 ssh2_pkt_addstring(s->pktout, s->password);
10095                 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10096                 logevent("Sent password");
10097                 s->type = AUTH_TYPE_PASSWORD;
10098
10099                 /*
10100                  * Wait for next packet, in case it's a password change
10101                  * request.
10102                  */
10103                 crWaitUntilV(pktin);
10104                 changereq_first_time = TRUE;
10105
10106                 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10107
10108                     /* 
10109                      * We're being asked for a new password
10110                      * (perhaps not for the first time).
10111                      * Loop until the server accepts it.
10112                      */
10113
10114                     int got_new = FALSE; /* not live over crReturn */
10115                     char *prompt;   /* not live over crReturn */
10116                     int prompt_len; /* not live over crReturn */
10117                     
10118                     {
10119                         char *msg;
10120                         if (changereq_first_time)
10121                             msg = "Server requested password change";
10122                         else
10123                             msg = "Server rejected new password";
10124                         logevent(msg);
10125                         c_write_str(ssh, msg);
10126                         c_write_str(ssh, "\r\n");
10127                     }
10128
10129                     ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10130
10131                     s->cur_prompt = new_prompts(ssh->frontend);
10132                     s->cur_prompt->to_server = TRUE;
10133                     s->cur_prompt->name = dupstr("New SSH password");
10134                     s->cur_prompt->instruction =
10135                         dupprintf("%.*s", prompt_len, prompt);
10136                     s->cur_prompt->instr_reqd = TRUE;
10137                     /*
10138                      * There's no explicit requirement in the protocol
10139                      * for the "old" passwords in the original and
10140                      * password-change messages to be the same, and
10141                      * apparently some Cisco kit supports password change
10142                      * by the user entering a blank password originally
10143                      * and the real password subsequently, so,
10144                      * reluctantly, we prompt for the old password again.
10145                      *
10146                      * (On the other hand, some servers don't even bother
10147                      * to check this field.)
10148                      */
10149                     add_prompt(s->cur_prompt,
10150                                dupstr("Current password (blank for previously entered password): "),
10151                                FALSE);
10152                     add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10153                                FALSE);
10154                     add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10155                                FALSE);
10156
10157                     /*
10158                      * Loop until the user manages to enter the same
10159                      * password twice.
10160                      */
10161                     while (!got_new) {
10162
10163                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
10164                         while (ret < 0) {
10165                             ssh->send_ok = 1;
10166                             crWaitUntilV(!pktin);
10167                             ret = get_userpass_input(s->cur_prompt, in, inlen);
10168                             ssh->send_ok = 0;
10169                         }
10170                         if (!ret) {
10171                             /*
10172                              * Failed to get responses. Terminate.
10173                              */
10174                             /* burn the evidence */
10175                             free_prompts(s->cur_prompt);
10176                             smemclr(s->password, strlen(s->password));
10177                             sfree(s->password);
10178                             ssh_disconnect(ssh, NULL, "Unable to authenticate",
10179                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10180                                            TRUE);
10181                             crStopV;
10182                         }
10183
10184                         /*
10185                          * If the user specified a new original password
10186                          * (IYSWIM), overwrite any previously specified
10187                          * one.
10188                          * (A side effect is that the user doesn't have to
10189                          * re-enter it if they louse up the new password.)
10190                          */
10191                         if (s->cur_prompt->prompts[0]->result[0]) {
10192                             smemclr(s->password, strlen(s->password));
10193                                 /* burn the evidence */
10194                             sfree(s->password);
10195                             s->password =
10196                                 dupstr(s->cur_prompt->prompts[0]->result);
10197                         }
10198
10199                         /*
10200                          * Check the two new passwords match.
10201                          */
10202                         got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10203                                           s->cur_prompt->prompts[2]->result)
10204                                    == 0);
10205                         if (!got_new)
10206                             /* They don't. Silly user. */
10207                             c_write_str(ssh, "Passwords do not match\r\n");
10208
10209                     }
10210
10211                     /*
10212                      * Send the new password (along with the old one).
10213                      * (see above for padding rationale)
10214                      */
10215                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10216                     ssh2_pkt_addstring(s->pktout, ssh->username);
10217                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
10218                                                         /* service requested */
10219                     ssh2_pkt_addstring(s->pktout, "password");
10220                     ssh2_pkt_addbool(s->pktout, TRUE);
10221                     ssh2_pkt_addstring(s->pktout, s->password);
10222                     ssh2_pkt_addstring(s->pktout,
10223                                        s->cur_prompt->prompts[1]->result);
10224                     free_prompts(s->cur_prompt);
10225                     ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10226                     logevent("Sent new password");
10227                     
10228                     /*
10229                      * Now see what the server has to say about it.
10230                      * (If it's CHANGEREQ again, it's not happy with the
10231                      * new password.)
10232                      */
10233                     crWaitUntilV(pktin);
10234                     changereq_first_time = FALSE;
10235
10236                 }
10237
10238                 /*
10239                  * We need to reexamine the current pktin at the top
10240                  * of the loop. Either:
10241                  *  - we weren't asked to change password at all, in
10242                  *    which case it's a SUCCESS or FAILURE with the
10243                  *    usual meaning
10244                  *  - we sent a new password, and the server was
10245                  *    either OK with it (SUCCESS or FAILURE w/partial
10246                  *    success) or unhappy with the _old_ password
10247                  *    (FAILURE w/o partial success)
10248                  * In any of these cases, we go back to the top of
10249                  * the loop and start again.
10250                  */
10251                 s->gotit = TRUE;
10252
10253                 /*
10254                  * We don't need the old password any more, in any
10255                  * case. Burn the evidence.
10256                  */
10257                 smemclr(s->password, strlen(s->password));
10258                 sfree(s->password);
10259
10260             } else {
10261                 char *str = dupprintf("No supported authentication methods available"
10262                                       " (server sent: %.*s)",
10263                                       methlen, methods);
10264
10265                 ssh_disconnect(ssh, str,
10266                                "No supported authentication methods available",
10267                                SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10268                                FALSE);
10269                 sfree(str);
10270
10271                 crStopV;
10272
10273             }
10274
10275         }
10276     }
10277     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10278
10279     /* Clear up various bits and pieces from authentication. */
10280     if (s->publickey_blob) {
10281         sfree(s->publickey_algorithm);
10282         sfree(s->publickey_blob);
10283         sfree(s->publickey_comment);
10284     }
10285     if (s->agent_response)
10286         sfree(s->agent_response);
10287
10288     if (s->userauth_success && !ssh->bare_connection) {
10289         /*
10290          * We've just received USERAUTH_SUCCESS, and we haven't sent any
10291          * packets since. Signal the transport layer to consider enacting
10292          * delayed compression.
10293          *
10294          * (Relying on we_are_in is not sufficient, as
10295          * draft-miller-secsh-compression-delayed is quite clear that it
10296          * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10297          * become set for other reasons.)
10298          */
10299         do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10300     }
10301
10302     ssh->channels = newtree234(ssh_channelcmp);
10303
10304     /*
10305      * Set up handlers for some connection protocol messages, so we
10306      * don't have to handle them repeatedly in this coroutine.
10307      */
10308     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10309         ssh2_msg_channel_window_adjust;
10310     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10311         ssh2_msg_global_request;
10312
10313     /*
10314      * Create the main session channel.
10315      */
10316     if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10317         ssh->mainchan = NULL;
10318     } else {
10319         ssh->mainchan = snew(struct ssh_channel);
10320         ssh->mainchan->ssh = ssh;
10321         ssh2_channel_init(ssh->mainchan);
10322
10323         if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10324             /*
10325              * Just start a direct-tcpip channel and use it as the main
10326              * channel.
10327              */
10328             ssh_send_port_open(ssh->mainchan,
10329                                conf_get_str(ssh->conf, CONF_ssh_nc_host),
10330                                conf_get_int(ssh->conf, CONF_ssh_nc_port),
10331                                "main channel");
10332             ssh->ncmode = TRUE;
10333         } else {
10334             s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10335             logevent("Opening session as main channel");
10336             ssh2_pkt_send(ssh, s->pktout);
10337             ssh->ncmode = FALSE;
10338         }
10339         crWaitUntilV(pktin);
10340         if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10341             bombout(("Server refused to open channel"));
10342             crStopV;
10343             /* FIXME: error data comes back in FAILURE packet */
10344         }
10345         if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10346             bombout(("Server's channel confirmation cited wrong channel"));
10347             crStopV;
10348         }
10349         ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10350         ssh->mainchan->halfopen = FALSE;
10351         ssh->mainchan->type = CHAN_MAINSESSION;
10352         ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10353         ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10354         add234(ssh->channels, ssh->mainchan);
10355         update_specials_menu(ssh->frontend);
10356         logevent("Opened main channel");
10357     }
10358
10359     /*
10360      * Now we have a channel, make dispatch table entries for
10361      * general channel-based messages.
10362      */
10363     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10364     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10365         ssh2_msg_channel_data;
10366     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10367     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10368     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10369         ssh2_msg_channel_open_confirmation;
10370     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10371         ssh2_msg_channel_open_failure;
10372     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10373         ssh2_msg_channel_request;
10374     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10375         ssh2_msg_channel_open;
10376     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10377     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10378
10379     /*
10380      * Now the connection protocol is properly up and running, with
10381      * all those dispatch table entries, so it's safe to let
10382      * downstreams start trying to open extra channels through us.
10383      */
10384     if (ssh->connshare)
10385         share_activate(ssh->connshare, ssh->v_s);
10386
10387     if (ssh->mainchan && ssh_is_simple(ssh)) {
10388         /*
10389          * This message indicates to the server that we promise
10390          * not to try to run any other channel in parallel with
10391          * this one, so it's safe for it to advertise a very large
10392          * window and leave the flow control to TCP.
10393          */
10394         s->pktout = ssh2_chanreq_init(ssh->mainchan,
10395                                       "simple@putty.projects.tartarus.org",
10396                                       NULL, NULL);
10397         ssh2_pkt_send(ssh, s->pktout);
10398     }
10399
10400     /*
10401      * Enable port forwardings.
10402      */
10403     ssh_setup_portfwd(ssh, ssh->conf);
10404
10405     if (ssh->mainchan && !ssh->ncmode) {
10406         /*
10407          * Send the CHANNEL_REQUESTS for the main session channel.
10408          * Each one is handled by its own little asynchronous
10409          * co-routine.
10410          */
10411
10412         /* Potentially enable X11 forwarding. */
10413         if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10414             ssh->x11disp =
10415                 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10416                                   ssh->conf);
10417             if (!ssh->x11disp) {
10418                 /* FIXME: return an error message from x11_setup_display */
10419                 logevent("X11 forwarding not enabled: unable to"
10420                          " initialise X display");
10421             } else {
10422                 ssh->x11auth = x11_invent_fake_auth
10423                     (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10424                 ssh->x11auth->disp = ssh->x11disp;
10425
10426                 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10427             }
10428         }
10429
10430         /* Potentially enable agent forwarding. */
10431         if (ssh_agent_forwarding_permitted(ssh))
10432             ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10433
10434         /* Now allocate a pty for the session. */
10435         if (!conf_get_int(ssh->conf, CONF_nopty))
10436             ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10437
10438         /* Send environment variables. */
10439         ssh2_setup_env(ssh->mainchan, NULL, NULL);
10440
10441         /*
10442          * Start a shell or a remote command. We may have to attempt
10443          * this twice if the config data has provided a second choice
10444          * of command.
10445          */
10446         while (1) {
10447             int subsys;
10448             char *cmd;
10449
10450             if (ssh->fallback_cmd) {
10451                 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10452                 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10453             } else {
10454                 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10455                 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10456             }
10457
10458             if (subsys) {
10459                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10460                                               ssh2_response_authconn, NULL);
10461                 ssh2_pkt_addstring(s->pktout, cmd);
10462             } else if (*cmd) {
10463                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10464                                               ssh2_response_authconn, NULL);
10465                 ssh2_pkt_addstring(s->pktout, cmd);
10466             } else {
10467                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10468                                               ssh2_response_authconn, NULL);
10469             }
10470             ssh2_pkt_send(ssh, s->pktout);
10471
10472             crWaitUntilV(pktin);
10473
10474             if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10475                 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10476                     bombout(("Unexpected response to shell/command request:"
10477                              " packet type %d", pktin->type));
10478                     crStopV;
10479                 }
10480                 /*
10481                  * We failed to start the command. If this is the
10482                  * fallback command, we really are finished; if it's
10483                  * not, and if the fallback command exists, try falling
10484                  * back to it before complaining.
10485                  */
10486                 if (!ssh->fallback_cmd &&
10487                     *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10488                     logevent("Primary command failed; attempting fallback");
10489                     ssh->fallback_cmd = TRUE;
10490                     continue;
10491                 }
10492                 bombout(("Server refused to start a shell/command"));
10493                 crStopV;
10494             } else {
10495                 logevent("Started a shell/command");
10496             }
10497             break;
10498         }
10499     } else {
10500         ssh->editing = ssh->echoing = TRUE;
10501     }
10502
10503     ssh->state = SSH_STATE_SESSION;
10504     if (ssh->size_needed)
10505         ssh_size(ssh, ssh->term_width, ssh->term_height);
10506     if (ssh->eof_needed)
10507         ssh_special(ssh, TS_EOF);
10508
10509     /*
10510      * Transfer data!
10511      */
10512     if (ssh->ldisc)
10513         ldisc_echoedit_update(ssh->ldisc);  /* cause ldisc to notice changes */
10514     if (ssh->mainchan)
10515         ssh->send_ok = 1;
10516     while (1) {
10517         crReturnV;
10518         s->try_send = FALSE;
10519         if (pktin) {
10520
10521             /*
10522              * _All_ the connection-layer packets we expect to
10523              * receive are now handled by the dispatch table.
10524              * Anything that reaches here must be bogus.
10525              */
10526
10527             bombout(("Strange packet received: type %d", pktin->type));
10528             crStopV;
10529         } else if (ssh->mainchan) {
10530             /*
10531              * We have spare data. Add it to the channel buffer.
10532              */
10533             ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10534             s->try_send = TRUE;
10535         }
10536         if (s->try_send) {
10537             int i;
10538             struct ssh_channel *c;
10539             /*
10540              * Try to send data on all channels if we can.
10541              */
10542             for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10543                 ssh2_try_send_and_unthrottle(ssh, c);
10544         }
10545     }
10546
10547     crFinishV;
10548 }
10549
10550 /*
10551  * Handlers for SSH-2 messages that might arrive at any moment.
10552  */
10553 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10554 {
10555     /* log reason code in disconnect message */
10556     char *buf, *msg;
10557     int reason, msglen;
10558
10559     reason = ssh_pkt_getuint32(pktin);
10560     ssh_pkt_getstring(pktin, &msg, &msglen);
10561
10562     if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10563         buf = dupprintf("Received disconnect message (%s)",
10564                         ssh2_disconnect_reasons[reason]);
10565     } else {
10566         buf = dupprintf("Received disconnect message (unknown"
10567                         " type %d)", reason);
10568     }
10569     logevent(buf);
10570     sfree(buf);
10571     buf = dupprintf("Disconnection message text: %.*s",
10572                     msglen, msg);
10573     logevent(buf);
10574     bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10575              reason,
10576              (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10577              ssh2_disconnect_reasons[reason] : "unknown",
10578              msglen, msg));
10579     sfree(buf);
10580 }
10581
10582 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10583 {
10584     /* log the debug message */
10585     char *msg;
10586     int msglen;
10587
10588     /* XXX maybe we should actually take notice of the return value */
10589     ssh2_pkt_getbool(pktin);
10590     ssh_pkt_getstring(pktin, &msg, &msglen);
10591
10592     logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10593 }
10594
10595 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10596 {
10597     do_ssh2_transport(ssh, NULL, 0, pktin);
10598 }
10599
10600 /*
10601  * Called if we receive a packet that isn't allowed by the protocol.
10602  * This only applies to packets whose meaning PuTTY understands.
10603  * Entirely unknown packets are handled below.
10604  */
10605 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10606 {
10607     char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10608                           ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10609                                         pktin->type));
10610     ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10611     sfree(buf);
10612 }
10613
10614 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10615 {
10616     struct Packet *pktout;
10617     pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10618     ssh2_pkt_adduint32(pktout, pktin->sequence);
10619     /*
10620      * UNIMPLEMENTED messages MUST appear in the same order as the
10621      * messages they respond to. Hence, never queue them.
10622      */
10623     ssh2_pkt_send_noqueue(ssh, pktout);
10624 }
10625
10626 /*
10627  * Handle the top-level SSH-2 protocol.
10628  */
10629 static void ssh2_protocol_setup(Ssh ssh)
10630 {
10631     int i;
10632
10633     /*
10634      * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10635      */
10636     for (i = 0; i < 256; i++)
10637         ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10638
10639     /*
10640      * Initially, we only accept transport messages (and a few generic
10641      * ones).  do_ssh2_authconn will add more when it starts.
10642      * Messages that are understood but not currently acceptable go to
10643      * ssh2_msg_unexpected.
10644      */
10645     ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10646     ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10647     ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10648     ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10649     ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10650     ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10651     ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10652     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10653     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10654     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10655     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10656     ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10657     ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10658     ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10659     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10660     ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10661     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10662     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10663     ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10664     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10665     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10666     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10667     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10668     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10669     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10670     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10671     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10672     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10673     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10674     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10675     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10676     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10677     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10678
10679     /*
10680      * These messages have a special handler from the start.
10681      */
10682     ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10683     ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10684     ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10685 }
10686
10687 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10688 {
10689     int i;
10690
10691     /*
10692      * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10693      */
10694     for (i = 0; i < 256; i++)
10695         ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10696
10697     /*
10698      * Initially, we set all ssh-connection messages to 'unexpected';
10699      * do_ssh2_authconn will fill things in properly. We also handle a
10700      * couple of messages from the transport protocol which aren't
10701      * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10702      * DISCONNECT).
10703      */
10704     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10705     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10706     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10707     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10708     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10709     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10710     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10711     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10712     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10713     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10714     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10715     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10716     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10717     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10718
10719     ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10720
10721     /*
10722      * These messages have a special handler from the start.
10723      */
10724     ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10725     ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10726     ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10727 }
10728
10729 static void ssh2_timer(void *ctx, unsigned long now)
10730 {
10731     Ssh ssh = (Ssh)ctx;
10732
10733     if (ssh->state == SSH_STATE_CLOSED)
10734         return;
10735
10736     if (!ssh->kex_in_progress && !ssh->bare_connection &&
10737         conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10738         now == ssh->next_rekey) {
10739         do_ssh2_transport(ssh, "timeout", -1, NULL);
10740     }
10741 }
10742
10743 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10744                           struct Packet *pktin)
10745 {
10746     unsigned char *in = (unsigned char *)vin;
10747     if (ssh->state == SSH_STATE_CLOSED)
10748         return;
10749
10750     if (pktin) {
10751         ssh->incoming_data_size += pktin->encrypted_len;
10752         if (!ssh->kex_in_progress &&
10753             ssh->max_data_size != 0 &&
10754             ssh->incoming_data_size > ssh->max_data_size)
10755             do_ssh2_transport(ssh, "too much data received", -1, NULL);
10756     }
10757
10758     if (pktin)
10759         ssh->packet_dispatch[pktin->type](ssh, pktin);
10760     else if (!ssh->protocol_initial_phase_done)
10761         do_ssh2_transport(ssh, in, inlen, pktin);
10762     else
10763         do_ssh2_authconn(ssh, in, inlen, pktin);
10764 }
10765
10766 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10767                                           struct Packet *pktin)
10768 {
10769     unsigned char *in = (unsigned char *)vin;
10770     if (ssh->state == SSH_STATE_CLOSED)
10771         return;
10772
10773     if (pktin)
10774         ssh->packet_dispatch[pktin->type](ssh, pktin);
10775     else
10776         do_ssh2_authconn(ssh, in, inlen, pktin);
10777 }
10778
10779 static void ssh_cache_conf_values(Ssh ssh)
10780 {
10781     ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10782 }
10783
10784 /*
10785  * Called to set up the connection.
10786  *
10787  * Returns an error message, or NULL on success.
10788  */
10789 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10790                             Conf *conf, char *host, int port, char **realhost,
10791                             int nodelay, int keepalive)
10792 {
10793     const char *p;
10794     Ssh ssh;
10795
10796     ssh = snew(struct ssh_tag);
10797     ssh->conf = conf_copy(conf);
10798     ssh_cache_conf_values(ssh);
10799     ssh->version = 0;                  /* when not ready yet */
10800     ssh->s = NULL;
10801     ssh->cipher = NULL;
10802     ssh->v1_cipher_ctx = NULL;
10803     ssh->crcda_ctx = NULL;
10804     ssh->cscipher = NULL;
10805     ssh->cs_cipher_ctx = NULL;
10806     ssh->sccipher = NULL;
10807     ssh->sc_cipher_ctx = NULL;
10808     ssh->csmac = NULL;
10809     ssh->cs_mac_ctx = NULL;
10810     ssh->scmac = NULL;
10811     ssh->sc_mac_ctx = NULL;
10812     ssh->cscomp = NULL;
10813     ssh->cs_comp_ctx = NULL;
10814     ssh->sccomp = NULL;
10815     ssh->sc_comp_ctx = NULL;
10816     ssh->kex = NULL;
10817     ssh->kex_ctx = NULL;
10818     ssh->hostkey = NULL;
10819     ssh->hostkey_str = NULL;
10820     ssh->exitcode = -1;
10821     ssh->close_expected = FALSE;
10822     ssh->clean_exit = FALSE;
10823     ssh->state = SSH_STATE_PREPACKET;
10824     ssh->size_needed = FALSE;
10825     ssh->eof_needed = FALSE;
10826     ssh->ldisc = NULL;
10827     ssh->logctx = NULL;
10828     ssh->deferred_send_data = NULL;
10829     ssh->deferred_len = 0;
10830     ssh->deferred_size = 0;
10831     ssh->fallback_cmd = 0;
10832     ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10833     ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10834     ssh->x11disp = NULL;
10835     ssh->x11auth = NULL;
10836     ssh->x11authtree = newtree234(x11_authcmp);
10837     ssh->v1_compressing = FALSE;
10838     ssh->v2_outgoing_sequence = 0;
10839     ssh->ssh1_rdpkt_crstate = 0;
10840     ssh->ssh2_rdpkt_crstate = 0;
10841     ssh->ssh2_bare_rdpkt_crstate = 0;
10842     ssh->ssh_gotdata_crstate = 0;
10843     ssh->do_ssh1_connection_crstate = 0;
10844     ssh->do_ssh_init_state = NULL;
10845     ssh->do_ssh_connection_init_state = NULL;
10846     ssh->do_ssh1_login_state = NULL;
10847     ssh->do_ssh2_transport_state = NULL;
10848     ssh->do_ssh2_authconn_state = NULL;
10849     ssh->v_c = NULL;
10850     ssh->v_s = NULL;
10851     ssh->mainchan = NULL;
10852     ssh->throttled_all = 0;
10853     ssh->v1_stdout_throttling = 0;
10854     ssh->queue = NULL;
10855     ssh->queuelen = ssh->queuesize = 0;
10856     ssh->queueing = FALSE;
10857     ssh->qhead = ssh->qtail = NULL;
10858     ssh->deferred_rekey_reason = NULL;
10859     bufchain_init(&ssh->queued_incoming_data);
10860     ssh->frozen = FALSE;
10861     ssh->username = NULL;
10862     ssh->sent_console_eof = FALSE;
10863     ssh->got_pty = FALSE;
10864     ssh->bare_connection = FALSE;
10865     ssh->X11_fwd_enabled = FALSE;
10866     ssh->connshare = NULL;
10867     ssh->attempting_connshare = FALSE;
10868
10869     *backend_handle = ssh;
10870
10871 #ifdef MSCRYPTOAPI
10872     if (crypto_startup() == 0)
10873         return "Microsoft high encryption pack not installed!";
10874 #endif
10875
10876     ssh->frontend = frontend_handle;
10877     ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10878     ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10879
10880     ssh->channels = NULL;
10881     ssh->rportfwds = NULL;
10882     ssh->portfwds = NULL;
10883
10884     ssh->send_ok = 0;
10885     ssh->editing = 0;
10886     ssh->echoing = 0;
10887     ssh->conn_throttle_count = 0;
10888     ssh->overall_bufsize = 0;
10889     ssh->fallback_cmd = 0;
10890
10891     ssh->protocol = NULL;
10892
10893     ssh->protocol_initial_phase_done = FALSE;
10894
10895     ssh->pinger = NULL;
10896
10897     ssh->incoming_data_size = ssh->outgoing_data_size =
10898         ssh->deferred_data_size = 0L;
10899     ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10900                                                       CONF_ssh_rekey_data));
10901     ssh->kex_in_progress = FALSE;
10902
10903 #ifndef NO_GSSAPI
10904     ssh->gsslibs = NULL;
10905 #endif
10906
10907     random_ref(); /* do this now - may be needed by sharing setup code */
10908
10909     p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10910     if (p != NULL) {
10911         random_unref();
10912         return p;
10913     }
10914
10915     return NULL;
10916 }
10917
10918 static void ssh_free(void *handle)
10919 {
10920     Ssh ssh = (Ssh) handle;
10921     struct ssh_channel *c;
10922     struct ssh_rportfwd *pf;
10923     struct X11FakeAuth *auth;
10924
10925     if (ssh->v1_cipher_ctx)
10926         ssh->cipher->free_context(ssh->v1_cipher_ctx);
10927     if (ssh->cs_cipher_ctx)
10928         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10929     if (ssh->sc_cipher_ctx)
10930         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10931     if (ssh->cs_mac_ctx)
10932         ssh->csmac->free_context(ssh->cs_mac_ctx);
10933     if (ssh->sc_mac_ctx)
10934         ssh->scmac->free_context(ssh->sc_mac_ctx);
10935     if (ssh->cs_comp_ctx) {
10936         if (ssh->cscomp)
10937             ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10938         else
10939             zlib_compress_cleanup(ssh->cs_comp_ctx);
10940     }
10941     if (ssh->sc_comp_ctx) {
10942         if (ssh->sccomp)
10943             ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10944         else
10945             zlib_decompress_cleanup(ssh->sc_comp_ctx);
10946     }
10947     if (ssh->kex_ctx)
10948         dh_cleanup(ssh->kex_ctx);
10949     sfree(ssh->savedhost);
10950
10951     while (ssh->queuelen-- > 0)
10952         ssh_free_packet(ssh->queue[ssh->queuelen]);
10953     sfree(ssh->queue);
10954
10955     while (ssh->qhead) {
10956         struct queued_handler *qh = ssh->qhead;
10957         ssh->qhead = qh->next;
10958         sfree(qh);
10959     }
10960     ssh->qhead = ssh->qtail = NULL;
10961
10962     if (ssh->channels) {
10963         while ((c = delpos234(ssh->channels, 0)) != NULL) {
10964             switch (c->type) {
10965               case CHAN_X11:
10966                 if (c->u.x11.xconn != NULL)
10967                     x11_close(c->u.x11.xconn);
10968                 break;
10969               case CHAN_SOCKDATA:
10970               case CHAN_SOCKDATA_DORMANT:
10971                 if (c->u.pfd.pf != NULL)
10972                     pfd_close(c->u.pfd.pf);
10973                 break;
10974             }
10975             if (ssh->version == 2) {
10976                 struct outstanding_channel_request *ocr, *nocr;
10977                 ocr = c->v.v2.chanreq_head;
10978                 while (ocr) {
10979                     ocr->handler(c, NULL, ocr->ctx);
10980                     nocr = ocr->next;
10981                     sfree(ocr);
10982                     ocr = nocr;
10983                 }
10984                 bufchain_clear(&c->v.v2.outbuffer);
10985             }
10986             sfree(c);
10987         }
10988         freetree234(ssh->channels);
10989         ssh->channels = NULL;
10990     }
10991
10992     if (ssh->connshare)
10993         sharestate_free(ssh->connshare);
10994
10995     if (ssh->rportfwds) {
10996         while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10997             free_rportfwd(pf);
10998         freetree234(ssh->rportfwds);
10999         ssh->rportfwds = NULL;
11000     }
11001     sfree(ssh->deferred_send_data);
11002     if (ssh->x11disp)
11003         x11_free_display(ssh->x11disp);
11004     while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11005         x11_free_fake_auth(auth);
11006     freetree234(ssh->x11authtree);
11007     sfree(ssh->do_ssh_init_state);
11008     sfree(ssh->do_ssh1_login_state);
11009     sfree(ssh->do_ssh2_transport_state);
11010     sfree(ssh->do_ssh2_authconn_state);
11011     sfree(ssh->v_c);
11012     sfree(ssh->v_s);
11013     sfree(ssh->fullhostname);
11014     sfree(ssh->hostkey_str);
11015     if (ssh->crcda_ctx) {
11016         crcda_free_context(ssh->crcda_ctx);
11017         ssh->crcda_ctx = NULL;
11018     }
11019     if (ssh->s)
11020         ssh_do_close(ssh, TRUE);
11021     expire_timer_context(ssh);
11022     if (ssh->pinger)
11023         pinger_free(ssh->pinger);
11024     bufchain_clear(&ssh->queued_incoming_data);
11025     sfree(ssh->username);
11026     conf_free(ssh->conf);
11027 #ifndef NO_GSSAPI
11028     if (ssh->gsslibs)
11029         ssh_gss_cleanup(ssh->gsslibs);
11030 #endif
11031     sfree(ssh);
11032
11033     random_unref();
11034 }
11035
11036 /*
11037  * Reconfigure the SSH backend.
11038  */
11039 static void ssh_reconfig(void *handle, Conf *conf)
11040 {
11041     Ssh ssh = (Ssh) handle;
11042     char *rekeying = NULL, rekey_mandatory = FALSE;
11043     unsigned long old_max_data_size;
11044     int i, rekey_time;
11045
11046     pinger_reconfig(ssh->pinger, ssh->conf, conf);
11047     if (ssh->portfwds)
11048         ssh_setup_portfwd(ssh, conf);
11049
11050     rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11051     if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11052         rekey_time != 0) {
11053         unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11054         unsigned long now = GETTICKCOUNT();
11055
11056         if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11057             rekeying = "timeout shortened";
11058         } else {
11059             ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11060         }
11061     }
11062
11063     old_max_data_size = ssh->max_data_size;
11064     ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11065                                                       CONF_ssh_rekey_data));
11066     if (old_max_data_size != ssh->max_data_size &&
11067         ssh->max_data_size != 0) {
11068         if (ssh->outgoing_data_size > ssh->max_data_size ||
11069             ssh->incoming_data_size > ssh->max_data_size)
11070             rekeying = "data limit lowered";
11071     }
11072
11073     if (conf_get_int(ssh->conf, CONF_compression) !=
11074         conf_get_int(conf, CONF_compression)) {
11075         rekeying = "compression setting changed";
11076         rekey_mandatory = TRUE;
11077     }
11078
11079     for (i = 0; i < CIPHER_MAX; i++)
11080         if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11081             conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11082         rekeying = "cipher settings changed";
11083         rekey_mandatory = TRUE;
11084     }
11085     if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11086         conf_get_int(conf, CONF_ssh2_des_cbc)) {
11087         rekeying = "cipher settings changed";
11088         rekey_mandatory = TRUE;
11089     }
11090
11091     conf_free(ssh->conf);
11092     ssh->conf = conf_copy(conf);
11093     ssh_cache_conf_values(ssh);
11094
11095     if (!ssh->bare_connection && rekeying) {
11096         if (!ssh->kex_in_progress) {
11097             do_ssh2_transport(ssh, rekeying, -1, NULL);
11098         } else if (rekey_mandatory) {
11099             ssh->deferred_rekey_reason = rekeying;
11100         }
11101     }
11102 }
11103
11104 /*
11105  * Called to send data down the SSH connection.
11106  */
11107 static int ssh_send(void *handle, char *buf, int len)
11108 {
11109     Ssh ssh = (Ssh) handle;
11110
11111     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11112         return 0;
11113
11114     ssh->protocol(ssh, (unsigned char *)buf, len, 0);
11115
11116     return ssh_sendbuffer(ssh);
11117 }
11118
11119 /*
11120  * Called to query the current amount of buffered stdin data.
11121  */
11122 static int ssh_sendbuffer(void *handle)
11123 {
11124     Ssh ssh = (Ssh) handle;
11125     int override_value;
11126
11127     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11128         return 0;
11129
11130     /*
11131      * If the SSH socket itself has backed up, add the total backup
11132      * size on that to any individual buffer on the stdin channel.
11133      */
11134     override_value = 0;
11135     if (ssh->throttled_all)
11136         override_value = ssh->overall_bufsize;
11137
11138     if (ssh->version == 1) {
11139         return override_value;
11140     } else if (ssh->version == 2) {
11141         if (!ssh->mainchan)
11142             return override_value;
11143         else
11144             return (override_value +
11145                     bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11146     }
11147
11148     return 0;
11149 }
11150
11151 /*
11152  * Called to set the size of the window from SSH's POV.
11153  */
11154 static void ssh_size(void *handle, int width, int height)
11155 {
11156     Ssh ssh = (Ssh) handle;
11157     struct Packet *pktout;
11158
11159     ssh->term_width = width;
11160     ssh->term_height = height;
11161
11162     switch (ssh->state) {
11163       case SSH_STATE_BEFORE_SIZE:
11164       case SSH_STATE_PREPACKET:
11165       case SSH_STATE_CLOSED:
11166         break;                         /* do nothing */
11167       case SSH_STATE_INTERMED:
11168         ssh->size_needed = TRUE;       /* buffer for later */
11169         break;
11170       case SSH_STATE_SESSION:
11171         if (!conf_get_int(ssh->conf, CONF_nopty)) {
11172             if (ssh->version == 1) {
11173                 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11174                             PKT_INT, ssh->term_height,
11175                             PKT_INT, ssh->term_width,
11176                             PKT_INT, 0, PKT_INT, 0, PKT_END);
11177             } else if (ssh->mainchan) {
11178                 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11179                                            NULL, NULL);
11180                 ssh2_pkt_adduint32(pktout, ssh->term_width);
11181                 ssh2_pkt_adduint32(pktout, ssh->term_height);
11182                 ssh2_pkt_adduint32(pktout, 0);
11183                 ssh2_pkt_adduint32(pktout, 0);
11184                 ssh2_pkt_send(ssh, pktout);
11185             }
11186         }
11187         break;
11188     }
11189 }
11190
11191 /*
11192  * Return a list of the special codes that make sense in this
11193  * protocol.
11194  */
11195 static const struct telnet_special *ssh_get_specials(void *handle)
11196 {
11197     static const struct telnet_special ssh1_ignore_special[] = {
11198         {"IGNORE message", TS_NOP}
11199     };
11200     static const struct telnet_special ssh2_ignore_special[] = {
11201         {"IGNORE message", TS_NOP},
11202     };
11203     static const struct telnet_special ssh2_rekey_special[] = {
11204         {"Repeat key exchange", TS_REKEY},
11205     };
11206     static const struct telnet_special ssh2_session_specials[] = {
11207         {NULL, TS_SEP},
11208         {"Break", TS_BRK},
11209         /* These are the signal names defined by RFC 4254.
11210          * They include all the ISO C signals, but are a subset of the POSIX
11211          * required signals. */
11212         {"SIGINT (Interrupt)", TS_SIGINT},
11213         {"SIGTERM (Terminate)", TS_SIGTERM},
11214         {"SIGKILL (Kill)", TS_SIGKILL},
11215         {"SIGQUIT (Quit)", TS_SIGQUIT},
11216         {"SIGHUP (Hangup)", TS_SIGHUP},
11217         {"More signals", TS_SUBMENU},
11218           {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11219           {"SIGFPE",  TS_SIGFPE},  {"SIGILL",  TS_SIGILL},
11220           {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11221           {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11222         {NULL, TS_EXITMENU}
11223     };
11224     static const struct telnet_special specials_end[] = {
11225         {NULL, TS_EXITMENU}
11226     };
11227     /* XXX review this length for any changes: */
11228     static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11229                                               lenof(ssh2_rekey_special) +
11230                                               lenof(ssh2_session_specials) +
11231                                               lenof(specials_end)];
11232     Ssh ssh = (Ssh) handle;
11233     int i = 0;
11234 #define ADD_SPECIALS(name) \
11235     do { \
11236         assert((i + lenof(name)) <= lenof(ssh_specials)); \
11237         memcpy(&ssh_specials[i], name, sizeof name); \
11238         i += lenof(name); \
11239     } while(0)
11240
11241     if (ssh->version == 1) {
11242         /* Don't bother offering IGNORE if we've decided the remote
11243          * won't cope with it, since we wouldn't bother sending it if
11244          * asked anyway. */
11245         if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11246             ADD_SPECIALS(ssh1_ignore_special);
11247     } else if (ssh->version == 2) {
11248         if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11249             ADD_SPECIALS(ssh2_ignore_special);
11250         if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11251             ADD_SPECIALS(ssh2_rekey_special);
11252         if (ssh->mainchan)
11253             ADD_SPECIALS(ssh2_session_specials);
11254     } /* else we're not ready yet */
11255
11256     if (i) {
11257         ADD_SPECIALS(specials_end);
11258         return ssh_specials;
11259     } else {
11260         return NULL;
11261     }
11262 #undef ADD_SPECIALS
11263 }
11264
11265 /*
11266  * Send special codes. TS_EOF is useful for `plink', so you
11267  * can send an EOF and collect resulting output (e.g. `plink
11268  * hostname sort').
11269  */
11270 static void ssh_special(void *handle, Telnet_Special code)
11271 {
11272     Ssh ssh = (Ssh) handle;
11273     struct Packet *pktout;
11274
11275     if (code == TS_EOF) {
11276         if (ssh->state != SSH_STATE_SESSION) {
11277             /*
11278              * Buffer the EOF in case we are pre-SESSION, so we can
11279              * send it as soon as we reach SESSION.
11280              */
11281             if (code == TS_EOF)
11282                 ssh->eof_needed = TRUE;
11283             return;
11284         }
11285         if (ssh->version == 1) {
11286             send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11287         } else if (ssh->mainchan) {
11288             sshfwd_write_eof(ssh->mainchan);
11289             ssh->send_ok = 0;          /* now stop trying to read from stdin */
11290         }
11291         logevent("Sent EOF message");
11292     } else if (code == TS_PING || code == TS_NOP) {
11293         if (ssh->state == SSH_STATE_CLOSED
11294             || ssh->state == SSH_STATE_PREPACKET) return;
11295         if (ssh->version == 1) {
11296             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11297                 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11298         } else {
11299             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11300                 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11301                 ssh2_pkt_addstring_start(pktout);
11302                 ssh2_pkt_send_noqueue(ssh, pktout);
11303             }
11304         }
11305     } else if (code == TS_REKEY) {
11306         if (!ssh->kex_in_progress && !ssh->bare_connection &&
11307             ssh->version == 2) {
11308             do_ssh2_transport(ssh, "at user request", -1, NULL);
11309         }
11310     } else if (code == TS_BRK) {
11311         if (ssh->state == SSH_STATE_CLOSED
11312             || ssh->state == SSH_STATE_PREPACKET) return;
11313         if (ssh->version == 1) {
11314             logevent("Unable to send BREAK signal in SSH-1");
11315         } else if (ssh->mainchan) {
11316             pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11317             ssh2_pkt_adduint32(pktout, 0);   /* default break length */
11318             ssh2_pkt_send(ssh, pktout);
11319         }
11320     } else {
11321         /* Is is a POSIX signal? */
11322         char *signame = NULL;
11323         if (code == TS_SIGABRT) signame = "ABRT";
11324         if (code == TS_SIGALRM) signame = "ALRM";
11325         if (code == TS_SIGFPE)  signame = "FPE";
11326         if (code == TS_SIGHUP)  signame = "HUP";
11327         if (code == TS_SIGILL)  signame = "ILL";
11328         if (code == TS_SIGINT)  signame = "INT";
11329         if (code == TS_SIGKILL) signame = "KILL";
11330         if (code == TS_SIGPIPE) signame = "PIPE";
11331         if (code == TS_SIGQUIT) signame = "QUIT";
11332         if (code == TS_SIGSEGV) signame = "SEGV";
11333         if (code == TS_SIGTERM) signame = "TERM";
11334         if (code == TS_SIGUSR1) signame = "USR1";
11335         if (code == TS_SIGUSR2) signame = "USR2";
11336         /* The SSH-2 protocol does in principle support arbitrary named
11337          * signals, including signame@domain, but we don't support those. */
11338         if (signame) {
11339             /* It's a signal. */
11340             if (ssh->version == 2 && ssh->mainchan) {
11341                 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11342                 ssh2_pkt_addstring(pktout, signame);
11343                 ssh2_pkt_send(ssh, pktout);
11344                 logeventf(ssh, "Sent signal SIG%s", signame);
11345             }
11346         } else {
11347             /* Never heard of it. Do nothing */
11348         }
11349     }
11350 }
11351
11352 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11353 {
11354     Ssh ssh = (Ssh) handle;
11355     struct ssh_channel *c;
11356     c = snew(struct ssh_channel);
11357
11358     c->ssh = ssh;
11359     ssh2_channel_init(c);
11360     c->halfopen = TRUE;
11361     c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11362     c->u.pfd.pf = pf;
11363     add234(ssh->channels, c);
11364     return c;
11365 }
11366
11367 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11368 {
11369     struct ssh_channel *c;
11370     c = snew(struct ssh_channel);
11371
11372     c->ssh = ssh;
11373     ssh2_channel_init(c);
11374     c->type = CHAN_SHARING;
11375     c->u.sharing.ctx = sharing_ctx;
11376     add234(ssh->channels, c);
11377     return c->localid;
11378 }
11379
11380 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11381 {
11382     struct ssh_channel *c;
11383
11384     c = find234(ssh->channels, &localid, ssh_channelfind);
11385     if (c)
11386         ssh_channel_destroy(c);
11387 }
11388
11389 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11390                                      const void *data, int datalen,
11391                                      const char *additional_log_text)
11392 {
11393     struct Packet *pkt;
11394
11395     pkt = ssh2_pkt_init(type);
11396     pkt->downstream_id = id;
11397     pkt->additional_log_text = additional_log_text;
11398     ssh2_pkt_adddata(pkt, data, datalen);
11399     ssh2_pkt_send(ssh, pkt);
11400 }
11401
11402 /*
11403  * This is called when stdout/stderr (the entity to which
11404  * from_backend sends data) manages to clear some backlog.
11405  */
11406 static void ssh_unthrottle(void *handle, int bufsize)
11407 {
11408     Ssh ssh = (Ssh) handle;
11409     int buflimit;
11410
11411     if (ssh->version == 1) {
11412         if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11413             ssh->v1_stdout_throttling = 0;
11414             ssh_throttle_conn(ssh, -1);
11415         }
11416     } else {
11417         if (ssh->mainchan) {
11418             ssh2_set_window(ssh->mainchan,
11419                             bufsize < ssh->mainchan->v.v2.locmaxwin ?
11420                             ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11421             if (ssh_is_simple(ssh))
11422                 buflimit = 0;
11423             else
11424                 buflimit = ssh->mainchan->v.v2.locmaxwin;
11425             if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11426                 ssh->mainchan->throttling_conn = 0;
11427                 ssh_throttle_conn(ssh, -1);
11428             }
11429         }
11430     }
11431
11432     /*
11433      * Now process any SSH connection data that was stashed in our
11434      * queue while we were frozen.
11435      */
11436     ssh_process_queued_incoming_data(ssh);
11437 }
11438
11439 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11440 {
11441     struct ssh_channel *c = (struct ssh_channel *)channel;
11442     Ssh ssh = c->ssh;
11443     struct Packet *pktout;
11444
11445     logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11446
11447     if (ssh->version == 1) {
11448         send_packet(ssh, SSH1_MSG_PORT_OPEN,
11449                     PKT_INT, c->localid,
11450                     PKT_STR, hostname,
11451                     PKT_INT, port,
11452                     /* PKT_STR, <org:orgport>, */
11453                     PKT_END);
11454     } else {
11455         pktout = ssh2_chanopen_init(c, "direct-tcpip");
11456         {
11457             char *trimmed_host = host_strduptrim(hostname);
11458             ssh2_pkt_addstring(pktout, trimmed_host);
11459             sfree(trimmed_host);
11460         }
11461         ssh2_pkt_adduint32(pktout, port);
11462         /*
11463          * We make up values for the originator data; partly it's
11464          * too much hassle to keep track, and partly I'm not
11465          * convinced the server should be told details like that
11466          * about my local network configuration.
11467          * The "originator IP address" is syntactically a numeric
11468          * IP address, and some servers (e.g., Tectia) get upset
11469          * if it doesn't match this syntax.
11470          */
11471         ssh2_pkt_addstring(pktout, "0.0.0.0");
11472         ssh2_pkt_adduint32(pktout, 0);
11473         ssh2_pkt_send(ssh, pktout);
11474     }
11475 }
11476
11477 static int ssh_connected(void *handle)
11478 {
11479     Ssh ssh = (Ssh) handle;
11480     return ssh->s != NULL;
11481 }
11482
11483 static int ssh_sendok(void *handle)
11484 {
11485     Ssh ssh = (Ssh) handle;
11486     return ssh->send_ok;
11487 }
11488
11489 static int ssh_ldisc(void *handle, int option)
11490 {
11491     Ssh ssh = (Ssh) handle;
11492     if (option == LD_ECHO)
11493         return ssh->echoing;
11494     if (option == LD_EDIT)
11495         return ssh->editing;
11496     return FALSE;
11497 }
11498
11499 static void ssh_provide_ldisc(void *handle, void *ldisc)
11500 {
11501     Ssh ssh = (Ssh) handle;
11502     ssh->ldisc = ldisc;
11503 }
11504
11505 static void ssh_provide_logctx(void *handle, void *logctx)
11506 {
11507     Ssh ssh = (Ssh) handle;
11508     ssh->logctx = logctx;
11509 }
11510
11511 static int ssh_return_exitcode(void *handle)
11512 {
11513     Ssh ssh = (Ssh) handle;
11514     if (ssh->s != NULL)
11515         return -1;
11516     else
11517         return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11518 }
11519
11520 /*
11521  * cfg_info for SSH is the protocol running in this session.
11522  * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11523  * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11524  */
11525 static int ssh_cfg_info(void *handle)
11526 {
11527     Ssh ssh = (Ssh) handle;
11528     if (ssh->version == 0)
11529         return 0; /* don't know yet */
11530     else if (ssh->bare_connection)
11531         return -1;
11532     else
11533         return ssh->version;
11534 }
11535
11536 /*
11537  * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11538  * that fails. This variable is the means by which scp.c can reach
11539  * into the SSH code and find out which one it got.
11540  */
11541 extern int ssh_fallback_cmd(void *handle)
11542 {
11543     Ssh ssh = (Ssh) handle;
11544     return ssh->fallback_cmd;
11545 }
11546
11547 Backend ssh_backend = {
11548     ssh_init,
11549     ssh_free,
11550     ssh_reconfig,
11551     ssh_send,
11552     ssh_sendbuffer,
11553     ssh_size,
11554     ssh_special,
11555     ssh_get_specials,
11556     ssh_connected,
11557     ssh_return_exitcode,
11558     ssh_sendok,
11559     ssh_ldisc,
11560     ssh_provide_ldisc,
11561     ssh_provide_logctx,
11562     ssh_unthrottle,
11563     ssh_cfg_info,
11564     "ssh",
11565     PROT_SSH,
11566     22
11567 };