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