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