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