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