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