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