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