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