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