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