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