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