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