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