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