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