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