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