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