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