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