]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Clarify when ldisc->term may be NULL.
[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 configuration but "
2964                  "not provided by server"));
2965         crStop(0);
2966     }
2967     if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2968         bombout(("SSH protocol version 2 required by configuration but "
2969                  "not provided by server"));
2970         crStop(0);
2971     }
2972
2973     if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2974         ssh->version = 2;
2975     else
2976         ssh->version = 1;
2977
2978     logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2979
2980     /* Send the version string, if we haven't already */
2981     if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2982         ssh_send_verstring(ssh, protoname, s->version);
2983
2984     if (ssh->version == 2) {
2985         size_t len;
2986         /*
2987          * Record their version string.
2988          */
2989         len = strcspn(s->vstring, "\015\012");
2990         ssh->v_s = snewn(len + 1, char);
2991         memcpy(ssh->v_s, s->vstring, len);
2992         ssh->v_s[len] = 0;
2993             
2994         /*
2995          * Initialise SSH-2 protocol.
2996          */
2997         ssh->protocol = ssh2_protocol;
2998         ssh2_protocol_setup(ssh);
2999         ssh->s_rdpkt = ssh2_rdpkt;
3000     } else {
3001         /*
3002          * Initialise SSH-1 protocol.
3003          */
3004         ssh->protocol = ssh1_protocol;
3005         ssh1_protocol_setup(ssh);
3006         ssh->s_rdpkt = ssh1_rdpkt;
3007     }
3008     if (ssh->version == 2)
3009         do_ssh2_transport(ssh, NULL, -1, NULL);
3010
3011     update_specials_menu(ssh->frontend);
3012     ssh->state = SSH_STATE_BEFORE_SIZE;
3013     ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3014
3015     sfree(s->vstring);
3016
3017     crFinish(0);
3018 }
3019
3020 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3021 {
3022     /*
3023      * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3024      * the ssh-connection part, extracted and given a trivial binary
3025      * packet protocol, so we replace 'SSH-' at the start with a new
3026      * name. In proper SSH style (though of course this part of the
3027      * proper SSH protocol _isn't_ subject to this kind of
3028      * DNS-domain-based extension), we define the new name in our
3029      * extension space.
3030      */
3031     static const char protoname[] =
3032         "SSHCONNECTION@putty.projects.tartarus.org-";
3033
3034     struct do_ssh_connection_init_state {
3035         int crLine;
3036         int vslen;
3037         char version[10];
3038         char *vstring;
3039         int vstrsize;
3040         int i;
3041     };
3042     crState(do_ssh_connection_init_state);
3043     
3044     crBeginState;
3045
3046     /* Search for a line beginning with the protocol name prefix in
3047      * the input. */
3048     for (;;) {
3049         for (s->i = 0; protoname[s->i]; s->i++) {
3050             if ((char)c != protoname[s->i]) goto no;
3051             crReturn(1);
3052         }
3053         break;
3054       no:
3055         while (c != '\012')
3056             crReturn(1);
3057         crReturn(1);
3058     }
3059
3060     s->vstrsize = sizeof(protoname) + 16;
3061     s->vstring = snewn(s->vstrsize, char);
3062     strcpy(s->vstring, protoname);
3063     s->vslen = strlen(protoname);
3064     s->i = 0;
3065     while (1) {
3066         if (s->vslen >= s->vstrsize - 1) {
3067             s->vstrsize += 16;
3068             s->vstring = sresize(s->vstring, s->vstrsize, char);
3069         }
3070         s->vstring[s->vslen++] = c;
3071         if (s->i >= 0) {
3072             if (c == '-') {
3073                 s->version[s->i] = '\0';
3074                 s->i = -1;
3075             } else if (s->i < sizeof(s->version) - 1)
3076                 s->version[s->i++] = c;
3077         } else if (c == '\012')
3078             break;
3079         crReturn(1);                   /* get another char */
3080     }
3081
3082     ssh->agentfwd_enabled = FALSE;
3083     ssh->rdpkt2_bare_state.incoming_sequence = 0;
3084
3085     s->vstring[s->vslen] = 0;
3086     s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3087     logeventf(ssh, "Server version: %s", s->vstring);
3088     ssh_detect_bugs(ssh, s->vstring);
3089
3090     /*
3091      * Decide which SSH protocol version to support. This is easy in
3092      * bare ssh-connection mode: only 2.0 is legal.
3093      */
3094     if (ssh_versioncmp(s->version, "2.0") < 0) {
3095         bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3096         crStop(0);
3097     }
3098     if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3099         bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3100         crStop(0);
3101     }
3102
3103     ssh->version = 2;
3104
3105     logeventf(ssh, "Using bare ssh-connection protocol");
3106
3107     /* Send the version string, if we haven't already */
3108     ssh_send_verstring(ssh, protoname, s->version);
3109
3110     /*
3111      * Initialise bare connection protocol.
3112      */
3113     ssh->protocol = ssh2_bare_connection_protocol;
3114     ssh2_bare_connection_protocol_setup(ssh);
3115     ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3116
3117     update_specials_menu(ssh->frontend);
3118     ssh->state = SSH_STATE_BEFORE_SIZE;
3119     ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3120
3121     /*
3122      * Get authconn (really just conn) under way.
3123      */
3124     do_ssh2_authconn(ssh, NULL, 0, NULL);
3125
3126     sfree(s->vstring);
3127
3128     crFinish(0);
3129 }
3130
3131 static void ssh_process_incoming_data(Ssh ssh,
3132                                       unsigned char **data, int *datalen)
3133 {
3134     struct Packet *pktin;
3135
3136     pktin = ssh->s_rdpkt(ssh, data, datalen);
3137     if (pktin) {
3138         ssh->protocol(ssh, NULL, 0, pktin);
3139         ssh_free_packet(pktin);
3140     }
3141 }
3142
3143 static void ssh_queue_incoming_data(Ssh ssh,
3144                                     unsigned char **data, int *datalen)
3145 {
3146     bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3147     *data += *datalen;
3148     *datalen = 0;
3149 }
3150
3151 static void ssh_process_queued_incoming_data(Ssh ssh)
3152 {
3153     void *vdata;
3154     unsigned char *data;
3155     int len, origlen;
3156
3157     while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3158         bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3159         data = vdata;
3160         origlen = len;
3161
3162         while (!ssh->frozen && len > 0)
3163             ssh_process_incoming_data(ssh, &data, &len);
3164
3165         if (origlen > len)
3166             bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3167     }
3168 }
3169
3170 static void ssh_set_frozen(Ssh ssh, int frozen)
3171 {
3172     if (ssh->s)
3173         sk_set_frozen(ssh->s, frozen);
3174     ssh->frozen = frozen;
3175 }
3176
3177 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3178 {
3179     /* Log raw data, if we're in that mode. */
3180     if (ssh->logctx)
3181         log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3182                    0, NULL, NULL, 0, NULL);
3183
3184     crBegin(ssh->ssh_gotdata_crstate);
3185
3186     /*
3187      * To begin with, feed the characters one by one to the
3188      * protocol initialisation / selection function do_ssh_init().
3189      * When that returns 0, we're done with the initial greeting
3190      * exchange and can move on to packet discipline.
3191      */
3192     while (1) {
3193         int ret;                       /* need not be kept across crReturn */
3194         if (datalen == 0)
3195             crReturnV;                 /* more data please */
3196         ret = ssh->do_ssh_init(ssh, *data);
3197         data++;
3198         datalen--;
3199         if (ret == 0)
3200             break;
3201     }
3202
3203     /*
3204      * We emerge from that loop when the initial negotiation is
3205      * over and we have selected an s_rdpkt function. Now pass
3206      * everything to s_rdpkt, and then pass the resulting packets
3207      * to the proper protocol handler.
3208      */
3209
3210     while (1) {
3211         while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3212             if (ssh->frozen) {
3213                 ssh_queue_incoming_data(ssh, &data, &datalen);
3214                 /* This uses up all data and cannot cause anything interesting
3215                  * to happen; indeed, for anything to happen at all, we must
3216                  * return, so break out. */
3217                 break;
3218             } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3219                 /* This uses up some or all data, and may freeze the
3220                  * session. */
3221                 ssh_process_queued_incoming_data(ssh);
3222             } else {
3223                 /* This uses up some or all data, and may freeze the
3224                  * session. */
3225                 ssh_process_incoming_data(ssh, &data, &datalen);
3226             }
3227             /* FIXME this is probably EBW. */
3228             if (ssh->state == SSH_STATE_CLOSED)
3229                 return;
3230         }
3231         /* We're out of data. Go and get some more. */
3232         crReturnV;
3233     }
3234     crFinishV;
3235 }
3236
3237 static int ssh_do_close(Ssh ssh, int notify_exit)
3238 {
3239     int ret = 0;
3240     struct ssh_channel *c;
3241
3242     ssh->state = SSH_STATE_CLOSED;
3243     expire_timer_context(ssh);
3244     if (ssh->s) {
3245         sk_close(ssh->s);
3246         ssh->s = NULL;
3247         if (notify_exit)
3248             notify_remote_exit(ssh->frontend);
3249         else
3250             ret = 1;
3251     }
3252     /*
3253      * Now we must shut down any port- and X-forwarded channels going
3254      * through this connection.
3255      */
3256     if (ssh->channels) {
3257         while (NULL != (c = index234(ssh->channels, 0))) {
3258             switch (c->type) {
3259               case CHAN_X11:
3260                 x11_close(c->u.x11.xconn);
3261                 break;
3262               case CHAN_SOCKDATA:
3263               case CHAN_SOCKDATA_DORMANT:
3264                 pfd_close(c->u.pfd.pf);
3265                 break;
3266             }
3267             del234(ssh->channels, c); /* moving next one to index 0 */
3268             if (ssh->version == 2)
3269                 bufchain_clear(&c->v.v2.outbuffer);
3270             sfree(c);
3271         }
3272     }
3273     /*
3274      * Go through port-forwardings, and close any associated
3275      * listening sockets.
3276      */
3277     if (ssh->portfwds) {
3278         struct ssh_portfwd *pf;
3279         while (NULL != (pf = index234(ssh->portfwds, 0))) {
3280             /* Dispose of any listening socket. */
3281             if (pf->local)
3282                 pfl_terminate(pf->local);
3283             del234(ssh->portfwds, pf); /* moving next one to index 0 */
3284             free_portfwd(pf);
3285         }
3286         freetree234(ssh->portfwds);
3287         ssh->portfwds = NULL;
3288     }
3289
3290     /*
3291      * Also stop attempting to connection-share.
3292      */
3293     if (ssh->connshare) {
3294         sharestate_free(ssh->connshare);
3295         ssh->connshare = NULL;
3296     }
3297
3298     return ret;
3299 }
3300
3301 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3302                            const char *error_msg, int error_code)
3303 {
3304     Ssh ssh = (Ssh) plug;
3305     char addrbuf[256], *msg;
3306
3307     if (ssh->attempting_connshare) {
3308         /*
3309          * While we're attempting connection sharing, don't loudly log
3310          * everything that happens. Real TCP connections need to be
3311          * logged when we _start_ trying to connect, because it might
3312          * be ages before they respond if something goes wrong; but
3313          * connection sharing is local and quick to respond, and it's
3314          * sufficient to simply wait and see whether it worked
3315          * afterwards.
3316          */
3317     } else {
3318         sk_getaddr(addr, addrbuf, lenof(addrbuf));
3319
3320         if (type == 0) {
3321             if (sk_addr_needs_port(addr)) {
3322                 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3323             } else {
3324                 msg = dupprintf("Connecting to %s", addrbuf);
3325             }
3326         } else {
3327             msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3328         }
3329
3330         logevent(msg);
3331         sfree(msg);
3332     }
3333 }
3334
3335 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3336                        const char *ds_err, const char *us_err)
3337 {
3338     if (event == SHARE_NONE) {
3339         /* In this case, 'logtext' is an error message indicating a
3340          * reason why connection sharing couldn't be set up _at all_.
3341          * Failing that, ds_err and us_err indicate why we couldn't be
3342          * a downstream and an upstream respectively. */
3343         if (logtext) {
3344             logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3345         } else {
3346             if (ds_err)
3347                 logeventf(ssh, "Could not set up connection sharing"
3348                           " as downstream: %s", ds_err);
3349             if (us_err)
3350                 logeventf(ssh, "Could not set up connection sharing"
3351                           " as upstream: %s", us_err);
3352         }
3353     } else if (event == SHARE_DOWNSTREAM) {
3354         /* In this case, 'logtext' is a local endpoint address */
3355         logeventf(ssh, "Using existing shared connection at %s", logtext);
3356         /* Also we should mention this in the console window to avoid
3357          * confusing users as to why this window doesn't behave the
3358          * usual way. */
3359         if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3360             c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3361         }
3362     } else if (event == SHARE_UPSTREAM) {
3363         /* In this case, 'logtext' is a local endpoint address too */
3364         logeventf(ssh, "Sharing this connection at %s", logtext);
3365     }
3366 }
3367
3368 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3369                        int calling_back)
3370 {
3371     Ssh ssh = (Ssh) plug;
3372     int need_notify = ssh_do_close(ssh, FALSE);
3373
3374     if (!error_msg) {
3375         if (!ssh->close_expected)
3376             error_msg = "Server unexpectedly closed network connection";
3377         else
3378             error_msg = "Server closed network connection";
3379     }
3380
3381     if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3382         ssh->exitcode = 0;
3383
3384     if (need_notify)
3385         notify_remote_exit(ssh->frontend);
3386
3387     if (error_msg)
3388         logevent(error_msg);
3389     if (!ssh->close_expected || !ssh->clean_exit)
3390         connection_fatal(ssh->frontend, "%s", error_msg);
3391     return 0;
3392 }
3393
3394 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3395 {
3396     Ssh ssh = (Ssh) plug;
3397     ssh_gotdata(ssh, (unsigned char *)data, len);
3398     if (ssh->state == SSH_STATE_CLOSED) {
3399         ssh_do_close(ssh, TRUE);
3400         return 0;
3401     }
3402     return 1;
3403 }
3404
3405 static void ssh_sent(Plug plug, int bufsize)
3406 {
3407     Ssh ssh = (Ssh) plug;
3408     /*
3409      * If the send backlog on the SSH socket itself clears, we
3410      * should unthrottle the whole world if it was throttled.
3411      */
3412     if (bufsize < SSH_MAX_BACKLOG)
3413         ssh_throttle_all(ssh, 0, bufsize);
3414 }
3415
3416 /*
3417  * Connect to specified host and port.
3418  * Returns an error message, or NULL on success.
3419  * Also places the canonical host name into `realhost'. It must be
3420  * freed by the caller.
3421  */
3422 static const char *connect_to_host(Ssh ssh, char *host, int port,
3423                                    char **realhost, int nodelay, int keepalive)
3424 {
3425     static const struct plug_function_table fn_table = {
3426         ssh_socket_log,
3427         ssh_closing,
3428         ssh_receive,
3429         ssh_sent,
3430         NULL
3431     };
3432
3433     SockAddr addr;
3434     const char *err;
3435     char *loghost;
3436     int addressfamily, sshprot;
3437     
3438     loghost = conf_get_str(ssh->conf, CONF_loghost);
3439     if (*loghost) {
3440         char *tmphost;
3441         char *colon;
3442
3443         tmphost = dupstr(loghost);
3444         ssh->savedport = 22;           /* default ssh port */
3445
3446         /*
3447          * A colon suffix on the hostname string also lets us affect
3448          * savedport. (Unless there are multiple colons, in which case
3449          * we assume this is an unbracketed IPv6 literal.)
3450          */
3451         colon = host_strrchr(tmphost, ':');
3452         if (colon && colon == host_strchr(tmphost, ':')) {
3453             *colon++ = '\0';
3454             if (*colon)
3455                 ssh->savedport = atoi(colon);
3456         }
3457
3458         ssh->savedhost = host_strduptrim(tmphost);
3459         sfree(tmphost);
3460     } else {
3461         ssh->savedhost = host_strduptrim(host);
3462         if (port < 0)
3463             port = 22;                 /* default ssh port */
3464         ssh->savedport = port;
3465     }
3466
3467     ssh->fn = &fn_table;               /* make 'ssh' usable as a Plug */
3468
3469     /*
3470      * Try connection-sharing, in case that means we don't open a
3471      * socket after all. ssh_connection_sharing_init will connect to a
3472      * previously established upstream if it can, and failing that,
3473      * establish a listening socket for _us_ to be the upstream. In
3474      * the latter case it will return NULL just as if it had done
3475      * nothing, because here we only need to care if we're a
3476      * downstream and need to do our connection setup differently.
3477      */
3478     ssh->connshare = NULL;
3479     ssh->attempting_connshare = TRUE;  /* affects socket logging behaviour */
3480     ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3481                                          ssh->conf, ssh, &ssh->connshare);
3482     ssh->attempting_connshare = FALSE;
3483     if (ssh->s != NULL) {
3484         /*
3485          * We are a downstream.
3486          */
3487         ssh->bare_connection = TRUE;
3488         ssh->do_ssh_init = do_ssh_connection_init;
3489         ssh->fullhostname = NULL;
3490         *realhost = dupstr(host);      /* best we can do */
3491     } else {
3492         /*
3493          * We're not a downstream, so open a normal socket.
3494          */
3495         ssh->do_ssh_init = do_ssh_init;
3496
3497         /*
3498          * Try to find host.
3499          */
3500         addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3501         logeventf(ssh, "Looking up host \"%s\"%s", host,
3502                   (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3503                    (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3504         addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3505         if ((err = sk_addr_error(addr)) != NULL) {
3506             sk_addr_free(addr);
3507             return err;
3508         }
3509         ssh->fullhostname = dupstr(*realhost);   /* save in case of GSSAPI */
3510
3511         ssh->s = new_connection(addr, *realhost, port,
3512                                 0, 1, nodelay, keepalive,
3513                                 (Plug) ssh, ssh->conf);
3514         if ((err = sk_socket_error(ssh->s)) != NULL) {
3515             ssh->s = NULL;
3516             notify_remote_exit(ssh->frontend);
3517             return err;
3518         }
3519     }
3520
3521     /*
3522      * If the SSH version number's fixed, set it now, and if it's SSH-2,
3523      * send the version string too.
3524      */
3525     sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3526     if (sshprot == 0)
3527         ssh->version = 1;
3528     if (sshprot == 3 && !ssh->bare_connection) {
3529         ssh->version = 2;
3530         ssh_send_verstring(ssh, "SSH-", NULL);
3531     }
3532
3533     /*
3534      * loghost, if configured, overrides realhost.
3535      */
3536     if (*loghost) {
3537         sfree(*realhost);
3538         *realhost = dupstr(loghost);
3539     }
3540
3541     return NULL;
3542 }
3543
3544 /*
3545  * Throttle or unthrottle the SSH connection.
3546  */
3547 static void ssh_throttle_conn(Ssh ssh, int adjust)
3548 {
3549     int old_count = ssh->conn_throttle_count;
3550     ssh->conn_throttle_count += adjust;
3551     assert(ssh->conn_throttle_count >= 0);
3552     if (ssh->conn_throttle_count && !old_count) {
3553         ssh_set_frozen(ssh, 1);
3554     } else if (!ssh->conn_throttle_count && old_count) {
3555         ssh_set_frozen(ssh, 0);
3556     }
3557 }
3558
3559 /*
3560  * Throttle or unthrottle _all_ local data streams (for when sends
3561  * on the SSH connection itself back up).
3562  */
3563 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3564 {
3565     int i;
3566     struct ssh_channel *c;
3567
3568     if (enable == ssh->throttled_all)
3569         return;
3570     ssh->throttled_all = enable;
3571     ssh->overall_bufsize = bufsize;
3572     if (!ssh->channels)
3573         return;
3574     for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3575         switch (c->type) {
3576           case CHAN_MAINSESSION:
3577             /*
3578              * This is treated separately, outside the switch.
3579              */
3580             break;
3581           case CHAN_X11:
3582             x11_override_throttle(c->u.x11.xconn, enable);
3583             break;
3584           case CHAN_AGENT:
3585             /* Agent channels require no buffer management. */
3586             break;
3587           case CHAN_SOCKDATA:
3588             pfd_override_throttle(c->u.pfd.pf, enable);
3589             break;
3590         }
3591     }
3592 }
3593
3594 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3595 {
3596     Ssh ssh = (Ssh) sshv;
3597
3598     ssh->agent_response = reply;
3599     ssh->agent_response_len = replylen;
3600
3601     if (ssh->version == 1)
3602         do_ssh1_login(ssh, NULL, -1, NULL);
3603     else
3604         do_ssh2_authconn(ssh, NULL, -1, NULL);
3605 }
3606
3607 static void ssh_dialog_callback(void *sshv, int ret)
3608 {
3609     Ssh ssh = (Ssh) sshv;
3610
3611     ssh->user_response = ret;
3612
3613     if (ssh->version == 1)
3614         do_ssh1_login(ssh, NULL, -1, NULL);
3615     else
3616         do_ssh2_transport(ssh, NULL, -1, NULL);
3617
3618     /*
3619      * This may have unfrozen the SSH connection, so do a
3620      * queued-data run.
3621      */
3622     ssh_process_queued_incoming_data(ssh);
3623 }
3624
3625 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3626 {
3627     struct ssh_channel *c = (struct ssh_channel *)cv;
3628     Ssh ssh = c->ssh;
3629     void *sentreply = reply;
3630
3631     c->u.a.outstanding_requests--;
3632     if (!sentreply) {
3633         /* Fake SSH_AGENT_FAILURE. */
3634         sentreply = "\0\0\0\1\5";
3635         replylen = 5;
3636     }
3637     if (ssh->version == 2) {
3638         ssh2_add_channel_data(c, sentreply, replylen);
3639         ssh2_try_send(c);
3640     } else {
3641         send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3642                     PKT_INT, c->remoteid,
3643                     PKT_INT, replylen,
3644                     PKT_DATA, sentreply, replylen,
3645                     PKT_END);
3646     }
3647     if (reply)
3648         sfree(reply);
3649     /*
3650      * If we've already seen an incoming EOF but haven't sent an
3651      * outgoing one, this may be the moment to send it.
3652      */
3653     if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3654         sshfwd_write_eof(c);
3655 }
3656
3657 /*
3658  * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3659  * non-NULL, otherwise just close the connection. `client_reason' == NULL
3660  * => log `wire_reason'.
3661  */
3662 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3663                            int code, int clean_exit)
3664 {
3665     char *error;
3666     if (!client_reason)
3667         client_reason = wire_reason;
3668     if (client_reason)
3669         error = dupprintf("Disconnected: %s", client_reason);
3670     else
3671         error = dupstr("Disconnected");
3672     if (wire_reason) {
3673         if (ssh->version == 1) {
3674             send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3675                         PKT_END);
3676         } else if (ssh->version == 2) {
3677             struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3678             ssh2_pkt_adduint32(pktout, code);
3679             ssh2_pkt_addstring(pktout, wire_reason);
3680             ssh2_pkt_addstring(pktout, "en");   /* language tag */
3681             ssh2_pkt_send_noqueue(ssh, pktout);
3682         }
3683     }
3684     ssh->close_expected = TRUE;
3685     ssh->clean_exit = clean_exit;
3686     ssh_closing((Plug)ssh, error, 0, 0);
3687     sfree(error);
3688 }
3689
3690 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3691                                const struct ssh_signkey *ssh2keytype,
3692                                void *ssh2keydata)
3693 {
3694     if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3695         return -1;                     /* no manual keys configured */
3696     }
3697
3698     if (fingerprint) {
3699         /*
3700          * The fingerprint string we've been given will have things
3701          * like 'ssh-rsa 2048' at the front of it. Strip those off and
3702          * narrow down to just the colon-separated hex block at the
3703          * end of the string.
3704          */
3705         const char *p = strrchr(fingerprint, ' ');
3706         fingerprint = p ? p+1 : fingerprint;
3707         /* Quick sanity checks, including making sure it's in lowercase */
3708         assert(strlen(fingerprint) == 16*3 - 1);
3709         assert(fingerprint[2] == ':');
3710         assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3711
3712         if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3713                                  fingerprint))
3714             return 1;                  /* success */
3715     }
3716
3717     if (ssh2keydata) {
3718         /*
3719          * Construct the base64-encoded public key blob and see if
3720          * that's listed.
3721          */
3722         unsigned char *binblob;
3723         char *base64blob;
3724         int binlen, atoms, i;
3725         binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3726         atoms = (binlen + 2) / 3;
3727         base64blob = snewn(atoms * 4 + 1, char);
3728         for (i = 0; i < atoms; i++)
3729             base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3730         base64blob[atoms * 4] = '\0';
3731         sfree(binblob);
3732         if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3733                                  base64blob)) {
3734             sfree(base64blob);
3735             return 1;                  /* success */
3736         }
3737         sfree(base64blob);
3738     }
3739
3740     return 0;
3741 }
3742
3743 /*
3744  * Handle the key exchange and user authentication phases.
3745  */
3746 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3747                          struct Packet *pktin)
3748 {
3749     int i, j, ret;
3750     unsigned char cookie[8], *ptr;
3751     struct MD5Context md5c;
3752     struct do_ssh1_login_state {
3753         int crLine;
3754         int len;
3755         unsigned char *rsabuf, *keystr1, *keystr2;
3756         unsigned long supported_ciphers_mask, supported_auths_mask;
3757         int tried_publickey, tried_agent;
3758         int tis_auth_refused, ccard_auth_refused;
3759         unsigned char session_id[16];
3760         int cipher_type;
3761         void *publickey_blob;
3762         int publickey_bloblen;
3763         char *publickey_comment;
3764         int publickey_encrypted;
3765         prompts_t *cur_prompt;
3766         char c;
3767         int pwpkt_type;
3768         unsigned char request[5], *response, *p;
3769         int responselen;
3770         int keyi, nkeys;
3771         int authed;
3772         struct RSAKey key;
3773         Bignum challenge;
3774         char *commentp;
3775         int commentlen;
3776         int dlgret;
3777         Filename *keyfile;
3778         struct RSAKey servkey, hostkey;
3779     };
3780     crState(do_ssh1_login_state);
3781
3782     crBeginState;
3783
3784     if (!pktin)
3785         crWaitUntil(pktin);
3786
3787     if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3788         bombout(("Public key packet not received"));
3789         crStop(0);
3790     }
3791
3792     logevent("Received public keys");
3793
3794     ptr = ssh_pkt_getdata(pktin, 8);
3795     if (!ptr) {
3796         bombout(("SSH-1 public key packet stopped before random cookie"));
3797         crStop(0);
3798     }
3799     memcpy(cookie, ptr, 8);
3800
3801     if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3802         !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) { 
3803         bombout(("Failed to read SSH-1 public keys from public key packet"));
3804         crStop(0);
3805     }
3806
3807     /*
3808      * Log the host key fingerprint.
3809      */
3810     {
3811         char logmsg[80];
3812         logevent("Host key fingerprint is:");
3813         strcpy(logmsg, "      ");
3814         s->hostkey.comment = NULL;
3815         rsa_fingerprint(logmsg + strlen(logmsg),
3816                         sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3817         logevent(logmsg);
3818     }
3819
3820     ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3821     s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3822     s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3823     if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3824         s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3825
3826     ssh->v1_local_protoflags =
3827         ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3828     ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3829
3830     MD5Init(&md5c);
3831     MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3832     MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3833     MD5Update(&md5c, cookie, 8);
3834     MD5Final(s->session_id, &md5c);
3835
3836     for (i = 0; i < 32; i++)
3837         ssh->session_key[i] = random_byte();
3838
3839     /*
3840      * Verify that the `bits' and `bytes' parameters match.
3841      */
3842     if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3843         s->servkey.bits > s->servkey.bytes * 8) {
3844         bombout(("SSH-1 public keys were badly formatted"));
3845         crStop(0);
3846     }
3847
3848     s->len = (s->hostkey.bytes > s->servkey.bytes ?
3849               s->hostkey.bytes : s->servkey.bytes);
3850
3851     s->rsabuf = snewn(s->len, unsigned char);
3852
3853     /*
3854      * Verify the host key.
3855      */
3856     {
3857         /*
3858          * First format the key into a string.
3859          */
3860         int len = rsastr_len(&s->hostkey);
3861         char fingerprint[100];
3862         char *keystr = snewn(len, char);
3863         rsastr_fmt(keystr, &s->hostkey);
3864         rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3865
3866         /* First check against manually configured host keys. */
3867         s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3868         if (s->dlgret == 0) {          /* did not match */
3869             bombout(("Host key did not appear in manually configured list"));
3870             crStop(0);
3871         } else if (s->dlgret < 0) { /* none configured; use standard handling */
3872             ssh_set_frozen(ssh, 1);
3873             s->dlgret = verify_ssh_host_key(ssh->frontend,
3874                                             ssh->savedhost, ssh->savedport,
3875                                             "rsa", keystr, fingerprint,
3876                                             ssh_dialog_callback, ssh);
3877             sfree(keystr);
3878             if (s->dlgret < 0) {
3879                 do {
3880                     crReturn(0);
3881                     if (pktin) {
3882                         bombout(("Unexpected data from server while waiting"
3883                                  " for user host key response"));
3884                         crStop(0);
3885                     }
3886                 } while (pktin || inlen > 0);
3887                 s->dlgret = ssh->user_response;
3888             }
3889             ssh_set_frozen(ssh, 0);
3890
3891             if (s->dlgret == 0) {
3892                 ssh_disconnect(ssh, "User aborted at host key verification",
3893                                NULL, 0, TRUE);
3894                 crStop(0);
3895             }
3896         }
3897     }
3898
3899     for (i = 0; i < 32; i++) {
3900         s->rsabuf[i] = ssh->session_key[i];
3901         if (i < 16)
3902             s->rsabuf[i] ^= s->session_id[i];
3903     }
3904
3905     if (s->hostkey.bytes > s->servkey.bytes) {
3906         ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3907         if (ret)
3908             ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3909     } else {
3910         ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3911         if (ret)
3912             ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3913     }
3914     if (!ret) {
3915         bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3916         crStop(0);      
3917     }
3918
3919     logevent("Encrypted session key");
3920
3921     {
3922         int cipher_chosen = 0, warn = 0;
3923         char *cipher_string = NULL;
3924         int i;
3925         for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3926             int next_cipher = conf_get_int_int(ssh->conf,
3927                                                CONF_ssh_cipherlist, i);
3928             if (next_cipher == CIPHER_WARN) {
3929                 /* If/when we choose a cipher, warn about it */
3930                 warn = 1;
3931             } else if (next_cipher == CIPHER_AES) {
3932                 /* XXX Probably don't need to mention this. */
3933                 logevent("AES not supported in SSH-1, skipping");
3934             } else {
3935                 switch (next_cipher) {
3936                   case CIPHER_3DES:     s->cipher_type = SSH_CIPHER_3DES;
3937                                         cipher_string = "3DES"; break;
3938                   case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3939                                         cipher_string = "Blowfish"; break;
3940                   case CIPHER_DES:      s->cipher_type = SSH_CIPHER_DES;
3941                                         cipher_string = "single-DES"; break;
3942                 }
3943                 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3944                     cipher_chosen = 1;
3945             }
3946         }
3947         if (!cipher_chosen) {
3948             if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3949                 bombout(("Server violates SSH-1 protocol by not "
3950                          "supporting 3DES encryption"));
3951             else
3952                 /* shouldn't happen */
3953                 bombout(("No supported ciphers found"));
3954             crStop(0);
3955         }
3956
3957         /* Warn about chosen cipher if necessary. */
3958         if (warn) {
3959             ssh_set_frozen(ssh, 1);
3960             s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3961                                ssh_dialog_callback, ssh);
3962             if (s->dlgret < 0) {
3963                 do {
3964                     crReturn(0);
3965                     if (pktin) {
3966                         bombout(("Unexpected data from server while waiting"
3967                                  " for user response"));
3968                         crStop(0);
3969                     }
3970                 } while (pktin || inlen > 0);
3971                 s->dlgret = ssh->user_response;
3972             }
3973             ssh_set_frozen(ssh, 0);
3974             if (s->dlgret == 0) {
3975                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3976                                0, TRUE);
3977                 crStop(0);
3978             }
3979         }
3980     }
3981
3982     switch (s->cipher_type) {
3983       case SSH_CIPHER_3DES:
3984         logevent("Using 3DES encryption");
3985         break;
3986       case SSH_CIPHER_DES:
3987         logevent("Using single-DES encryption");
3988         break;
3989       case SSH_CIPHER_BLOWFISH:
3990         logevent("Using Blowfish encryption");
3991         break;
3992     }
3993
3994     send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3995                 PKT_CHAR, s->cipher_type,
3996                 PKT_DATA, cookie, 8,
3997                 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3998                 PKT_DATA, s->rsabuf, s->len,
3999                 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4000
4001     logevent("Trying to enable encryption...");
4002
4003     sfree(s->rsabuf);
4004
4005     ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4006                    s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4007                    &ssh_3des);
4008     ssh->v1_cipher_ctx = ssh->cipher->make_context();
4009     ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4010     logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4011
4012     ssh->crcda_ctx = crcda_make_context();
4013     logevent("Installing CRC compensation attack detector");
4014
4015     if (s->servkey.modulus) {
4016         sfree(s->servkey.modulus);
4017         s->servkey.modulus = NULL;
4018     }
4019     if (s->servkey.exponent) {
4020         sfree(s->servkey.exponent);
4021         s->servkey.exponent = NULL;
4022     }
4023     if (s->hostkey.modulus) {
4024         sfree(s->hostkey.modulus);
4025         s->hostkey.modulus = NULL;
4026     }
4027     if (s->hostkey.exponent) {
4028         sfree(s->hostkey.exponent);
4029         s->hostkey.exponent = NULL;
4030     }
4031     crWaitUntil(pktin);
4032
4033     if (pktin->type != SSH1_SMSG_SUCCESS) {
4034         bombout(("Encryption not successfully enabled"));
4035         crStop(0);
4036     }
4037
4038     logevent("Successfully started encryption");
4039
4040     fflush(stdout); /* FIXME eh? */
4041     {
4042         if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4043             int ret; /* need not be kept over crReturn */
4044             s->cur_prompt = new_prompts(ssh->frontend);
4045             s->cur_prompt->to_server = TRUE;
4046             s->cur_prompt->name = dupstr("SSH login name");
4047             add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4048             ret = get_userpass_input(s->cur_prompt, NULL, 0);
4049             while (ret < 0) {
4050                 ssh->send_ok = 1;
4051                 crWaitUntil(!pktin);
4052                 ret = get_userpass_input(s->cur_prompt, in, inlen);
4053                 ssh->send_ok = 0;
4054             }
4055             if (!ret) {
4056                 /*
4057                  * Failed to get a username. Terminate.
4058                  */
4059                 free_prompts(s->cur_prompt);
4060                 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4061                 crStop(0);
4062             }
4063             ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4064             free_prompts(s->cur_prompt);
4065         }
4066
4067         send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4068         {
4069             char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4070             logevent(userlog);
4071             if (flags & FLAG_INTERACTIVE &&
4072                 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4073                 c_write_str(ssh, userlog);
4074                 c_write_str(ssh, "\r\n");
4075             }
4076             sfree(userlog);
4077         }
4078     }
4079
4080     crWaitUntil(pktin);
4081
4082     if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4083         /* We must not attempt PK auth. Pretend we've already tried it. */
4084         s->tried_publickey = s->tried_agent = 1;
4085     } else {
4086         s->tried_publickey = s->tried_agent = 0;
4087     }
4088     s->tis_auth_refused = s->ccard_auth_refused = 0;
4089     /*
4090      * Load the public half of any configured keyfile for later use.
4091      */
4092     s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4093     if (!filename_is_null(s->keyfile)) {
4094         int keytype;
4095         logeventf(ssh, "Reading private key file \"%.150s\"",
4096                   filename_to_str(s->keyfile));
4097         keytype = key_type(s->keyfile);
4098         if (keytype == SSH_KEYTYPE_SSH1) {
4099             const char *error;
4100             if (rsakey_pubblob(s->keyfile,
4101                                &s->publickey_blob, &s->publickey_bloblen,
4102                                &s->publickey_comment, &error)) {
4103                 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4104                                                           NULL);
4105             } else {
4106                 char *msgbuf;
4107                 logeventf(ssh, "Unable to load private key (%s)", error);
4108                 msgbuf = dupprintf("Unable to load private key file "
4109                                    "\"%.150s\" (%s)\r\n",
4110                                    filename_to_str(s->keyfile),
4111                                    error);
4112                 c_write_str(ssh, msgbuf);
4113                 sfree(msgbuf);
4114                 s->publickey_blob = NULL;
4115             }
4116         } else {
4117             char *msgbuf;
4118             logeventf(ssh, "Unable to use this key file (%s)",
4119                       key_type_to_str(keytype));
4120             msgbuf = dupprintf("Unable to use key file \"%.150s\""
4121                                " (%s)\r\n",
4122                                filename_to_str(s->keyfile),
4123                                key_type_to_str(keytype));
4124             c_write_str(ssh, msgbuf);
4125             sfree(msgbuf);
4126             s->publickey_blob = NULL;
4127         }
4128     } else
4129         s->publickey_blob = NULL;
4130
4131     while (pktin->type == SSH1_SMSG_FAILURE) {
4132         s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4133
4134         if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4135             /*
4136              * Attempt RSA authentication using Pageant.
4137              */
4138             void *r;
4139
4140             s->authed = FALSE;
4141             s->tried_agent = 1;
4142             logevent("Pageant is running. Requesting keys.");
4143
4144             /* Request the keys held by the agent. */
4145             PUT_32BIT(s->request, 1);
4146             s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4147             if (!agent_query(s->request, 5, &r, &s->responselen,
4148                              ssh_agent_callback, ssh)) {
4149                 do {
4150                     crReturn(0);
4151                     if (pktin) {
4152                         bombout(("Unexpected data from server while waiting"
4153                                  " for agent response"));
4154                         crStop(0);
4155                     }
4156                 } while (pktin || inlen > 0);
4157                 r = ssh->agent_response;
4158                 s->responselen = ssh->agent_response_len;
4159             }
4160             s->response = (unsigned char *) r;
4161             if (s->response && s->responselen >= 5 &&
4162                 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4163                 s->p = s->response + 5;
4164                 s->nkeys = toint(GET_32BIT(s->p));
4165                 if (s->nkeys < 0) {
4166                     logeventf(ssh, "Pageant reported negative key count %d",
4167                               s->nkeys);
4168                     s->nkeys = 0;
4169                 }
4170                 s->p += 4;
4171                 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4172                 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4173                     unsigned char *pkblob = s->p;
4174                     s->p += 4;
4175                     {
4176                         int n, ok = FALSE;
4177                         do {           /* do while (0) to make breaking easy */
4178                             n = ssh1_read_bignum
4179                                 (s->p, toint(s->responselen-(s->p-s->response)),
4180                                  &s->key.exponent);
4181                             if (n < 0)
4182                                 break;
4183                             s->p += n;
4184                             n = ssh1_read_bignum
4185                                 (s->p, toint(s->responselen-(s->p-s->response)),
4186                                  &s->key.modulus);
4187                             if (n < 0)
4188                                 break;
4189                             s->p += n;
4190                             if (s->responselen - (s->p-s->response) < 4)
4191                                 break;
4192                             s->commentlen = toint(GET_32BIT(s->p));
4193                             s->p += 4;
4194                             if (s->commentlen < 0 ||
4195                                 toint(s->responselen - (s->p-s->response)) <
4196                                 s->commentlen)
4197                                 break;
4198                             s->commentp = (char *)s->p;
4199                             s->p += s->commentlen;
4200                             ok = TRUE;
4201                         } while (0);
4202                         if (!ok) {
4203                             logevent("Pageant key list packet was truncated");
4204                             break;
4205                         }
4206                     }
4207                     if (s->publickey_blob) {
4208                         if (!memcmp(pkblob, s->publickey_blob,
4209                                     s->publickey_bloblen)) {
4210                             logeventf(ssh, "Pageant key #%d matches "
4211                                       "configured key file", s->keyi);
4212                             s->tried_publickey = 1;
4213                         } else
4214                             /* Skip non-configured key */
4215                             continue;
4216                     }
4217                     logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4218                     send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4219                                 PKT_BIGNUM, s->key.modulus, PKT_END);
4220                     crWaitUntil(pktin);
4221                     if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4222                         logevent("Key refused");
4223                         continue;
4224                     }
4225                     logevent("Received RSA challenge");
4226                     if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4227                         bombout(("Server's RSA challenge was badly formatted"));
4228                         crStop(0);
4229                     }
4230
4231                     {
4232                         char *agentreq, *q, *ret;
4233                         void *vret;
4234                         int len, retlen;
4235                         len = 1 + 4;   /* message type, bit count */
4236                         len += ssh1_bignum_length(s->key.exponent);
4237                         len += ssh1_bignum_length(s->key.modulus);
4238                         len += ssh1_bignum_length(s->challenge);
4239                         len += 16;     /* session id */
4240                         len += 4;      /* response format */
4241                         agentreq = snewn(4 + len, char);
4242                         PUT_32BIT(agentreq, len);
4243                         q = agentreq + 4;
4244                         *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4245                         PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4246                         q += 4;
4247                         q += ssh1_write_bignum(q, s->key.exponent);
4248                         q += ssh1_write_bignum(q, s->key.modulus);
4249                         q += ssh1_write_bignum(q, s->challenge);
4250                         memcpy(q, s->session_id, 16);
4251                         q += 16;
4252                         PUT_32BIT(q, 1);        /* response format */
4253                         if (!agent_query(agentreq, len + 4, &vret, &retlen,
4254                                          ssh_agent_callback, ssh)) {
4255                             sfree(agentreq);
4256                             do {
4257                                 crReturn(0);
4258                                 if (pktin) {
4259                                     bombout(("Unexpected data from server"
4260                                              " while waiting for agent"
4261                                              " response"));
4262                                     crStop(0);
4263                                 }
4264                             } while (pktin || inlen > 0);
4265                             vret = ssh->agent_response;
4266                             retlen = ssh->agent_response_len;
4267                         } else
4268                             sfree(agentreq);
4269                         ret = vret;
4270                         if (ret) {
4271                             if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4272                                 logevent("Sending Pageant's response");
4273                                 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4274                                             PKT_DATA, ret + 5, 16,
4275                                             PKT_END);
4276                                 sfree(ret);
4277                                 crWaitUntil(pktin);
4278                                 if (pktin->type == SSH1_SMSG_SUCCESS) {
4279                                     logevent
4280                                         ("Pageant's response accepted");
4281                                     if (flags & FLAG_VERBOSE) {
4282                                         c_write_str(ssh, "Authenticated using"
4283                                                     " RSA key \"");
4284                                         c_write(ssh, s->commentp,
4285                                                 s->commentlen);
4286                                         c_write_str(ssh, "\" from agent\r\n");
4287                                     }
4288                                     s->authed = TRUE;
4289                                 } else
4290                                     logevent
4291                                         ("Pageant's response not accepted");
4292                             } else {
4293                                 logevent
4294                                     ("Pageant failed to answer challenge");
4295                                 sfree(ret);
4296                             }
4297                         } else {
4298                             logevent("No reply received from Pageant");
4299                         }
4300                     }
4301                     freebn(s->key.exponent);
4302                     freebn(s->key.modulus);
4303                     freebn(s->challenge);
4304                     if (s->authed)
4305                         break;
4306                 }
4307                 sfree(s->response);
4308                 if (s->publickey_blob && !s->tried_publickey)
4309                     logevent("Configured key file not in Pageant");
4310             } else {
4311                 logevent("Failed to get reply from Pageant");
4312             }
4313             if (s->authed)
4314                 break;
4315         }
4316         if (s->publickey_blob && !s->tried_publickey) {
4317             /*
4318              * Try public key authentication with the specified
4319              * key file.
4320              */
4321             int got_passphrase; /* need not be kept over crReturn */
4322             if (flags & FLAG_VERBOSE)
4323                 c_write_str(ssh, "Trying public key authentication.\r\n");
4324             s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4325             logeventf(ssh, "Trying public key \"%s\"",
4326                       filename_to_str(s->keyfile));
4327             s->tried_publickey = 1;
4328             got_passphrase = FALSE;
4329             while (!got_passphrase) {
4330                 /*
4331                  * Get a passphrase, if necessary.
4332                  */
4333                 char *passphrase = NULL;    /* only written after crReturn */
4334                 const char *error;
4335                 if (!s->publickey_encrypted) {
4336                     if (flags & FLAG_VERBOSE)
4337                         c_write_str(ssh, "No passphrase required.\r\n");
4338                     passphrase = NULL;
4339                 } else {
4340                     int ret; /* need not be kept over crReturn */
4341                     s->cur_prompt = new_prompts(ssh->frontend);
4342                     s->cur_prompt->to_server = FALSE;
4343                     s->cur_prompt->name = dupstr("SSH key passphrase");
4344                     add_prompt(s->cur_prompt,
4345                                dupprintf("Passphrase for key \"%.100s\": ",
4346                                          s->publickey_comment), FALSE);
4347                     ret = get_userpass_input(s->cur_prompt, NULL, 0);
4348                     while (ret < 0) {
4349                         ssh->send_ok = 1;
4350                         crWaitUntil(!pktin);
4351                         ret = get_userpass_input(s->cur_prompt, in, inlen);
4352                         ssh->send_ok = 0;
4353                     }
4354                     if (!ret) {
4355                         /* Failed to get a passphrase. Terminate. */
4356                         free_prompts(s->cur_prompt);
4357                         ssh_disconnect(ssh, NULL, "Unable to authenticate",
4358                                        0, TRUE);
4359                         crStop(0);
4360                     }
4361                     passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4362                     free_prompts(s->cur_prompt);
4363                 }
4364                 /*
4365                  * Try decrypting key with passphrase.
4366                  */
4367                 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4368                 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4369                                  &error);
4370                 if (passphrase) {
4371                     smemclr(passphrase, strlen(passphrase));
4372                     sfree(passphrase);
4373                 }
4374                 if (ret == 1) {
4375                     /* Correct passphrase. */
4376                     got_passphrase = TRUE;
4377                 } else if (ret == 0) {
4378                     c_write_str(ssh, "Couldn't load private key from ");
4379                     c_write_str(ssh, filename_to_str(s->keyfile));
4380                     c_write_str(ssh, " (");
4381                     c_write_str(ssh, error);
4382                     c_write_str(ssh, ").\r\n");
4383                     got_passphrase = FALSE;
4384                     break;             /* go and try something else */
4385                 } else if (ret == -1) {
4386                     c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4387                     got_passphrase = FALSE;
4388                     /* and try again */
4389                 } else {
4390                     assert(0 && "unexpected return from loadrsakey()");
4391                     got_passphrase = FALSE;   /* placate optimisers */
4392                 }
4393             }
4394
4395             if (got_passphrase) {
4396
4397                 /*
4398                  * Send a public key attempt.
4399                  */
4400                 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4401                             PKT_BIGNUM, s->key.modulus, PKT_END);
4402
4403                 crWaitUntil(pktin);
4404                 if (pktin->type == SSH1_SMSG_FAILURE) {
4405                     c_write_str(ssh, "Server refused our public key.\r\n");
4406                     continue;          /* go and try something else */
4407                 }
4408                 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4409                     bombout(("Bizarre response to offer of public key"));
4410                     crStop(0);
4411                 }
4412
4413                 {
4414                     int i;
4415                     unsigned char buffer[32];
4416                     Bignum challenge, response;
4417
4418                     if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4419                         bombout(("Server's RSA challenge was badly formatted"));
4420                         crStop(0);
4421                     }
4422                     response = rsadecrypt(challenge, &s->key);
4423                     freebn(s->key.private_exponent);/* burn the evidence */
4424
4425                     for (i = 0; i < 32; i++) {
4426                         buffer[i] = bignum_byte(response, 31 - i);
4427                     }
4428
4429                     MD5Init(&md5c);
4430                     MD5Update(&md5c, buffer, 32);
4431                     MD5Update(&md5c, s->session_id, 16);
4432                     MD5Final(buffer, &md5c);
4433
4434                     send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4435                                 PKT_DATA, buffer, 16, PKT_END);
4436
4437                     freebn(challenge);
4438                     freebn(response);
4439                 }
4440
4441                 crWaitUntil(pktin);
4442                 if (pktin->type == SSH1_SMSG_FAILURE) {
4443                     if (flags & FLAG_VERBOSE)
4444                         c_write_str(ssh, "Failed to authenticate with"
4445                                     " our public key.\r\n");
4446                     continue;          /* go and try something else */
4447                 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4448                     bombout(("Bizarre response to RSA authentication response"));
4449                     crStop(0);
4450                 }
4451
4452                 break;                 /* we're through! */
4453             }
4454
4455         }
4456
4457         /*
4458          * Otherwise, try various forms of password-like authentication.
4459          */
4460         s->cur_prompt = new_prompts(ssh->frontend);
4461
4462         if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4463             (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4464             !s->tis_auth_refused) {
4465             s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4466             logevent("Requested TIS authentication");
4467             send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4468             crWaitUntil(pktin);
4469             if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4470                 logevent("TIS authentication declined");
4471                 if (flags & FLAG_INTERACTIVE)
4472                     c_write_str(ssh, "TIS authentication refused.\r\n");
4473                 s->tis_auth_refused = 1;
4474                 continue;
4475             } else {
4476                 char *challenge;
4477                 int challengelen;
4478                 char *instr_suf, *prompt;
4479
4480                 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4481                 if (!challenge) {
4482                     bombout(("TIS challenge packet was badly formed"));
4483                     crStop(0);
4484                 }
4485                 logevent("Received TIS challenge");
4486                 s->cur_prompt->to_server = TRUE;
4487                 s->cur_prompt->name = dupstr("SSH TIS authentication");
4488                 /* Prompt heuristic comes from OpenSSH */
4489                 if (memchr(challenge, '\n', challengelen)) {
4490                     instr_suf = dupstr("");
4491                     prompt = dupprintf("%.*s", challengelen, challenge);
4492                 } else {
4493                     instr_suf = dupprintf("%.*s", challengelen, challenge);
4494                     prompt = dupstr("Response: ");
4495                 }
4496                 s->cur_prompt->instruction =
4497                     dupprintf("Using TIS authentication.%s%s",
4498                               (*instr_suf) ? "\n" : "",
4499                               instr_suf);
4500                 s->cur_prompt->instr_reqd = TRUE;
4501                 add_prompt(s->cur_prompt, prompt, FALSE);
4502                 sfree(instr_suf);
4503             }
4504         }
4505         if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4506             (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4507             !s->ccard_auth_refused) {
4508             s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4509             logevent("Requested CryptoCard authentication");
4510             send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4511             crWaitUntil(pktin);
4512             if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4513                 logevent("CryptoCard authentication declined");
4514                 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4515                 s->ccard_auth_refused = 1;
4516                 continue;
4517             } else {
4518                 char *challenge;
4519                 int challengelen;
4520                 char *instr_suf, *prompt;
4521
4522                 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4523                 if (!challenge) {
4524                     bombout(("CryptoCard challenge packet was badly formed"));
4525                     crStop(0);
4526                 }
4527                 logevent("Received CryptoCard challenge");
4528                 s->cur_prompt->to_server = TRUE;
4529                 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4530                 s->cur_prompt->name_reqd = FALSE;
4531                 /* Prompt heuristic comes from OpenSSH */
4532                 if (memchr(challenge, '\n', challengelen)) {
4533                     instr_suf = dupstr("");
4534                     prompt = dupprintf("%.*s", challengelen, challenge);
4535                 } else {
4536                     instr_suf = dupprintf("%.*s", challengelen, challenge);
4537                     prompt = dupstr("Response: ");
4538                 }
4539                 s->cur_prompt->instruction =
4540                     dupprintf("Using CryptoCard authentication.%s%s",
4541                               (*instr_suf) ? "\n" : "",
4542                               instr_suf);
4543                 s->cur_prompt->instr_reqd = TRUE;
4544                 add_prompt(s->cur_prompt, prompt, FALSE);
4545                 sfree(instr_suf);
4546             }
4547         }
4548         if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4549             if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4550                 bombout(("No supported authentication methods available"));
4551                 crStop(0);
4552             }
4553             s->cur_prompt->to_server = TRUE;
4554             s->cur_prompt->name = dupstr("SSH password");
4555             add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4556                                                 ssh->username, ssh->savedhost),
4557                        FALSE);
4558         }
4559
4560         /*
4561          * Show password prompt, having first obtained it via a TIS
4562          * or CryptoCard exchange if we're doing TIS or CryptoCard
4563          * authentication.
4564          */
4565         {
4566             int ret; /* need not be kept over crReturn */
4567             ret = get_userpass_input(s->cur_prompt, NULL, 0);
4568             while (ret < 0) {
4569                 ssh->send_ok = 1;
4570                 crWaitUntil(!pktin);
4571                 ret = get_userpass_input(s->cur_prompt, in, inlen);
4572                 ssh->send_ok = 0;
4573             }
4574             if (!ret) {
4575                 /*
4576                  * Failed to get a password (for example
4577                  * because one was supplied on the command line
4578                  * which has already failed to work). Terminate.
4579                  */
4580                 free_prompts(s->cur_prompt);
4581                 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4582                 crStop(0);
4583             }
4584         }
4585
4586         if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4587             /*
4588              * Defence against traffic analysis: we send a
4589              * whole bunch of packets containing strings of
4590              * different lengths. One of these strings is the
4591              * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4592              * The others are all random data in
4593              * SSH1_MSG_IGNORE packets. This way a passive
4594              * listener can't tell which is the password, and
4595              * hence can't deduce the password length.
4596              * 
4597              * Anybody with a password length greater than 16
4598              * bytes is going to have enough entropy in their
4599              * password that a listener won't find it _that_
4600              * much help to know how long it is. So what we'll
4601              * do is:
4602              * 
4603              *  - if password length < 16, we send 15 packets
4604              *    containing string lengths 1 through 15
4605              * 
4606              *  - otherwise, we let N be the nearest multiple
4607              *    of 8 below the password length, and send 8
4608              *    packets containing string lengths N through
4609              *    N+7. This won't obscure the order of
4610              *    magnitude of the password length, but it will
4611              *    introduce a bit of extra uncertainty.
4612              * 
4613              * A few servers can't deal with SSH1_MSG_IGNORE, at
4614              * least in this context. For these servers, we need
4615              * an alternative defence. We make use of the fact
4616              * that the password is interpreted as a C string:
4617              * so we can append a NUL, then some random data.
4618              * 
4619              * A few servers can deal with neither SSH1_MSG_IGNORE
4620              * here _nor_ a padded password string.
4621              * For these servers we are left with no defences
4622              * against password length sniffing.
4623              */
4624             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4625                 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4626                 /*
4627                  * The server can deal with SSH1_MSG_IGNORE, so
4628                  * we can use the primary defence.
4629                  */
4630                 int bottom, top, pwlen, i;
4631                 char *randomstr;
4632
4633                 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4634                 if (pwlen < 16) {
4635                     bottom = 0;    /* zero length passwords are OK! :-) */
4636                     top = 15;
4637                 } else {
4638                     bottom = pwlen & ~7;
4639                     top = bottom + 7;
4640                 }
4641
4642                 assert(pwlen >= bottom && pwlen <= top);
4643
4644                 randomstr = snewn(top + 1, char);
4645
4646                 for (i = bottom; i <= top; i++) {
4647                     if (i == pwlen) {
4648                         defer_packet(ssh, s->pwpkt_type,
4649                                      PKT_STR,s->cur_prompt->prompts[0]->result,
4650                                      PKT_END);
4651                     } else {
4652                         for (j = 0; j < i; j++) {
4653                             do {
4654                                 randomstr[j] = random_byte();
4655                             } while (randomstr[j] == '\0');
4656                         }
4657                         randomstr[i] = '\0';
4658                         defer_packet(ssh, SSH1_MSG_IGNORE,
4659                                      PKT_STR, randomstr, PKT_END);
4660                     }
4661                 }
4662                 logevent("Sending password with camouflage packets");
4663                 ssh_pkt_defersend(ssh);
4664                 sfree(randomstr);
4665             } 
4666             else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4667                 /*
4668                  * The server can't deal with SSH1_MSG_IGNORE
4669                  * but can deal with padded passwords, so we
4670                  * can use the secondary defence.
4671                  */
4672                 char string[64];
4673                 char *ss;
4674                 int len;
4675
4676                 len = strlen(s->cur_prompt->prompts[0]->result);
4677                 if (len < sizeof(string)) {
4678                     ss = string;
4679                     strcpy(string, s->cur_prompt->prompts[0]->result);
4680                     len++;             /* cover the zero byte */
4681                     while (len < sizeof(string)) {
4682                         string[len++] = (char) random_byte();
4683                     }
4684                 } else {
4685                     ss = s->cur_prompt->prompts[0]->result;
4686                 }
4687                 logevent("Sending length-padded password");
4688                 send_packet(ssh, s->pwpkt_type,
4689                             PKT_INT, len, PKT_DATA, ss, len,
4690                             PKT_END);
4691             } else {
4692                 /*
4693                  * The server is believed unable to cope with
4694                  * any of our password camouflage methods.
4695                  */
4696                 int len;
4697                 len = strlen(s->cur_prompt->prompts[0]->result);
4698                 logevent("Sending unpadded password");
4699                 send_packet(ssh, s->pwpkt_type,
4700                             PKT_INT, len,
4701                             PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4702                             PKT_END);
4703             }
4704         } else {
4705             send_packet(ssh, s->pwpkt_type,
4706                         PKT_STR, s->cur_prompt->prompts[0]->result,
4707                         PKT_END);
4708         }
4709         logevent("Sent password");
4710         free_prompts(s->cur_prompt);
4711         crWaitUntil(pktin);
4712         if (pktin->type == SSH1_SMSG_FAILURE) {
4713             if (flags & FLAG_VERBOSE)
4714                 c_write_str(ssh, "Access denied\r\n");
4715             logevent("Authentication refused");
4716         } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4717             bombout(("Strange packet received, type %d", pktin->type));
4718             crStop(0);
4719         }
4720     }
4721
4722     /* Clear up */
4723     if (s->publickey_blob) {
4724         sfree(s->publickey_blob);
4725         sfree(s->publickey_comment);
4726     }
4727
4728     logevent("Authentication successful");
4729
4730     crFinish(1);
4731 }
4732
4733 static void ssh_channel_try_eof(struct ssh_channel *c)
4734 {
4735     Ssh ssh = c->ssh;
4736     assert(c->pending_eof);          /* precondition for calling us */
4737     if (c->halfopen)
4738         return;                 /* can't close: not even opened yet */
4739     if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4740         return;              /* can't send EOF: pending outgoing data */
4741
4742     c->pending_eof = FALSE;            /* we're about to send it */
4743     if (ssh->version == 1) {
4744         send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4745                     PKT_END);
4746         c->closes |= CLOSES_SENT_EOF;
4747     } else {
4748         struct Packet *pktout;
4749         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4750         ssh2_pkt_adduint32(pktout, c->remoteid);
4751         ssh2_pkt_send(ssh, pktout);
4752         c->closes |= CLOSES_SENT_EOF;
4753         ssh2_channel_check_close(c);
4754     }
4755 }
4756
4757 Conf *sshfwd_get_conf(struct ssh_channel *c)
4758 {
4759     Ssh ssh = c->ssh;
4760     return ssh->conf;
4761 }
4762
4763 void sshfwd_write_eof(struct ssh_channel *c)
4764 {
4765     Ssh ssh = c->ssh;
4766
4767     if (ssh->state == SSH_STATE_CLOSED)
4768         return;
4769
4770     if (c->closes & CLOSES_SENT_EOF)
4771         return;
4772
4773     c->pending_eof = TRUE;
4774     ssh_channel_try_eof(c);
4775 }
4776
4777 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4778 {
4779     Ssh ssh = c->ssh;
4780
4781     if (ssh->state == SSH_STATE_CLOSED)
4782         return;
4783
4784     switch (c->type) {
4785       case CHAN_X11:
4786         x11_close(c->u.x11.xconn);
4787         logeventf(ssh, "Forwarded X11 connection terminated due to local "
4788                   "error: %s", err);
4789         break;
4790       case CHAN_SOCKDATA:
4791       case CHAN_SOCKDATA_DORMANT:
4792         pfd_close(c->u.pfd.pf);
4793         logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4794         break;
4795     }
4796     c->type = CHAN_ZOMBIE;
4797     c->pending_eof = FALSE;   /* this will confuse a zombie channel */
4798
4799     ssh2_channel_check_close(c);
4800 }
4801
4802 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4803 {
4804     Ssh ssh = c->ssh;
4805
4806     if (ssh->state == SSH_STATE_CLOSED)
4807         return 0;
4808
4809     if (ssh->version == 1) {
4810         send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4811                     PKT_INT, c->remoteid,
4812                     PKT_INT, len, PKT_DATA, buf, len,
4813                     PKT_END);
4814         /*
4815          * In SSH-1 we can return 0 here - implying that forwarded
4816          * connections are never individually throttled - because
4817          * the only circumstance that can cause throttling will be
4818          * the whole SSH connection backing up, in which case
4819          * _everything_ will be throttled as a whole.
4820          */
4821         return 0;
4822     } else {
4823         ssh2_add_channel_data(c, buf, len);
4824         return ssh2_try_send(c);
4825     }
4826 }
4827
4828 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4829 {
4830     Ssh ssh = c->ssh;
4831     int buflimit;
4832
4833     if (ssh->state == SSH_STATE_CLOSED)
4834         return;
4835
4836     if (ssh->version == 1) {
4837         buflimit = SSH1_BUFFER_LIMIT;
4838     } else {
4839         buflimit = c->v.v2.locmaxwin;
4840         ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4841     }
4842     if (c->throttling_conn && bufsize <= buflimit) {
4843         c->throttling_conn = 0;
4844         ssh_throttle_conn(ssh, -1);
4845     }
4846 }
4847
4848 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4849 {
4850     struct queued_handler *qh = ssh->qhead;
4851
4852     assert(qh != NULL);
4853
4854     assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4855
4856     if (qh->msg1 > 0) {
4857         assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4858         ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4859     }
4860     if (qh->msg2 > 0) {
4861         assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4862         ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4863     }
4864
4865     if (qh->next) {
4866         ssh->qhead = qh->next;
4867
4868         if (ssh->qhead->msg1 > 0) {
4869             ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4870             ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4871         }
4872         if (ssh->qhead->msg2 > 0) {
4873             ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4874             ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4875         }
4876     } else {
4877         ssh->qhead = ssh->qtail = NULL;
4878     }
4879
4880     qh->handler(ssh, pktin, qh->ctx);
4881
4882     sfree(qh);
4883 }
4884
4885 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4886                               chandler_fn_t handler, void *ctx)
4887 {
4888     struct queued_handler *qh;
4889
4890     qh = snew(struct queued_handler);
4891     qh->msg1 = msg1;
4892     qh->msg2 = msg2;
4893     qh->handler = handler;
4894     qh->ctx = ctx;
4895     qh->next = NULL;
4896
4897     if (ssh->qtail == NULL) {
4898         ssh->qhead = qh;
4899
4900         if (qh->msg1 > 0) {
4901             ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4902             ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4903         }
4904         if (qh->msg2 > 0) {
4905             ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4906             ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4907         }
4908     } else {
4909         ssh->qtail->next = qh;
4910     }
4911     ssh->qtail = qh;
4912 }
4913
4914 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4915 {
4916     struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4917
4918     if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4919                         SSH2_MSG_REQUEST_SUCCESS)) {
4920         logeventf(ssh, "Remote port forwarding from %s enabled",
4921                   pf->sportdesc);
4922     } else {
4923         logeventf(ssh, "Remote port forwarding from %s refused",
4924                   pf->sportdesc);
4925
4926         rpf = del234(ssh->rportfwds, pf);
4927         assert(rpf == pf);
4928         pf->pfrec->remote = NULL;
4929         free_rportfwd(pf);
4930     }
4931 }
4932
4933 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
4934                                void *share_ctx)
4935 {
4936     struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
4937     pf->dhost = NULL;
4938     pf->dport = 0;
4939     pf->share_ctx = share_ctx;
4940     pf->shost = dupstr(shost);
4941     pf->sport = sport;
4942     pf->sportdesc = NULL;
4943     if (!ssh->rportfwds) {
4944         assert(ssh->version == 2);
4945         ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4946     }
4947     if (add234(ssh->rportfwds, pf) != pf) {
4948         sfree(pf->shost);
4949         sfree(pf);
4950         return FALSE;
4951     }
4952     return TRUE;
4953 }
4954
4955 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
4956                                                 void *ctx)
4957 {
4958     share_got_pkt_from_server(ctx, pktin->type,
4959                               pktin->body, pktin->length);
4960 }
4961
4962 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
4963 {
4964     ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
4965                       ssh_sharing_global_request_response, share_ctx);
4966 }
4967
4968 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4969 {
4970     struct ssh_portfwd *epf;
4971     int i;
4972     char *key, *val;
4973
4974     if (!ssh->portfwds) {
4975         ssh->portfwds = newtree234(ssh_portcmp);
4976     } else {
4977         /*
4978          * Go through the existing port forwardings and tag them
4979          * with status==DESTROY. Any that we want to keep will be
4980          * re-enabled (status==KEEP) as we go through the
4981          * configuration and find out which bits are the same as
4982          * they were before.
4983          */
4984         struct ssh_portfwd *epf;
4985         int i;
4986         for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4987             epf->status = DESTROY;
4988     }
4989
4990     for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4991          val != NULL;
4992          val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4993         char *kp, *kp2, *vp, *vp2;
4994         char address_family, type;
4995         int sport,dport,sserv,dserv;
4996         char *sports, *dports, *saddr, *host;
4997
4998         kp = key;
4999
5000         address_family = 'A';
5001         type = 'L';
5002         if (*kp == 'A' || *kp == '4' || *kp == '6')
5003             address_family = *kp++;
5004         if (*kp == 'L' || *kp == 'R')
5005             type = *kp++;
5006
5007         if ((kp2 = host_strchr(kp, ':')) != NULL) {
5008             /*
5009              * There's a colon in the middle of the source port
5010              * string, which means that the part before it is
5011              * actually a source address.
5012              */
5013             char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5014             saddr = host_strduptrim(saddr_tmp);
5015             sfree(saddr_tmp);
5016             sports = kp2+1;
5017         } else {
5018             saddr = NULL;
5019             sports = kp;
5020         }
5021         sport = atoi(sports);
5022         sserv = 0;
5023         if (sport == 0) {
5024             sserv = 1;
5025             sport = net_service_lookup(sports);
5026             if (!sport) {
5027                 logeventf(ssh, "Service lookup failed for source"
5028                           " port \"%s\"", sports);
5029             }
5030         }
5031
5032         if (type == 'L' && !strcmp(val, "D")) {
5033             /* dynamic forwarding */
5034             host = NULL;
5035             dports = NULL;
5036             dport = -1;
5037             dserv = 0;
5038             type = 'D';
5039         } else {
5040             /* ordinary forwarding */
5041             vp = val;
5042             vp2 = vp + host_strcspn(vp, ":");
5043             host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5044             if (*vp2)
5045                 vp2++;
5046             dports = vp2;
5047             dport = atoi(dports);
5048             dserv = 0;
5049             if (dport == 0) {
5050                 dserv = 1;
5051                 dport = net_service_lookup(dports);
5052                 if (!dport) {
5053                     logeventf(ssh, "Service lookup failed for destination"
5054                               " port \"%s\"", dports);
5055                 }
5056             }
5057         }
5058
5059         if (sport && dport) {
5060             /* Set up a description of the source port. */
5061             struct ssh_portfwd *pfrec, *epfrec;
5062
5063             pfrec = snew(struct ssh_portfwd);
5064             pfrec->type = type;
5065             pfrec->saddr = saddr;
5066             pfrec->sserv = sserv ? dupstr(sports) : NULL;
5067             pfrec->sport = sport;
5068             pfrec->daddr = host;
5069             pfrec->dserv = dserv ? dupstr(dports) : NULL;
5070             pfrec->dport = dport;
5071             pfrec->local = NULL;
5072             pfrec->remote = NULL;
5073             pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5074                                     address_family == '6' ? ADDRTYPE_IPV6 :
5075                                     ADDRTYPE_UNSPEC);
5076
5077             epfrec = add234(ssh->portfwds, pfrec);
5078             if (epfrec != pfrec) {
5079                 if (epfrec->status == DESTROY) {
5080                     /*
5081                      * We already have a port forwarding up and running
5082                      * with precisely these parameters. Hence, no need
5083                      * to do anything; simply re-tag the existing one
5084                      * as KEEP.
5085                      */
5086                     epfrec->status = KEEP;
5087                 }
5088                 /*
5089                  * Anything else indicates that there was a duplicate
5090                  * in our input, which we'll silently ignore.
5091                  */
5092                 free_portfwd(pfrec);
5093             } else {
5094                 pfrec->status = CREATE;
5095             }
5096         } else {
5097             sfree(saddr);
5098             sfree(host);
5099         }
5100     }
5101
5102     /*
5103      * Now go through and destroy any port forwardings which were
5104      * not re-enabled.
5105      */
5106     for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5107         if (epf->status == DESTROY) {
5108             char *message;
5109
5110             message = dupprintf("%s port forwarding from %s%s%d",
5111                                 epf->type == 'L' ? "local" :
5112                                 epf->type == 'R' ? "remote" : "dynamic",
5113                                 epf->saddr ? epf->saddr : "",
5114                                 epf->saddr ? ":" : "",
5115                                 epf->sport);
5116
5117             if (epf->type != 'D') {
5118                 char *msg2 = dupprintf("%s to %s:%d", message,
5119                                        epf->daddr, epf->dport);
5120                 sfree(message);
5121                 message = msg2;
5122             }
5123
5124             logeventf(ssh, "Cancelling %s", message);
5125             sfree(message);
5126
5127             /* epf->remote or epf->local may be NULL if setting up a
5128              * forwarding failed. */
5129             if (epf->remote) {
5130                 struct ssh_rportfwd *rpf = epf->remote;
5131                 struct Packet *pktout;
5132
5133                 /*
5134                  * Cancel the port forwarding at the server
5135                  * end.
5136                  */
5137                 if (ssh->version == 1) {
5138                     /*
5139                      * We cannot cancel listening ports on the
5140                      * server side in SSH-1! There's no message
5141                      * to support it. Instead, we simply remove
5142                      * the rportfwd record from the local end
5143                      * so that any connections the server tries
5144                      * to make on it are rejected.
5145                      */
5146                 } else {
5147                     pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5148                     ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5149                     ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5150                     if (epf->saddr) {
5151                         ssh2_pkt_addstring(pktout, epf->saddr);
5152                     } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5153                         /* XXX: rport_acceptall may not represent
5154                          * what was used to open the original connection,
5155                          * since it's reconfigurable. */
5156                         ssh2_pkt_addstring(pktout, "");
5157                     } else {
5158                         ssh2_pkt_addstring(pktout, "localhost");
5159                     }
5160                     ssh2_pkt_adduint32(pktout, epf->sport);
5161                     ssh2_pkt_send(ssh, pktout);
5162                 }
5163
5164                 del234(ssh->rportfwds, rpf);
5165                 free_rportfwd(rpf);
5166             } else if (epf->local) {
5167                 pfl_terminate(epf->local);
5168             }
5169
5170             delpos234(ssh->portfwds, i);
5171             free_portfwd(epf);
5172             i--;                       /* so we don't skip one in the list */
5173         }
5174
5175     /*
5176      * And finally, set up any new port forwardings (status==CREATE).
5177      */
5178     for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5179         if (epf->status == CREATE) {
5180             char *sportdesc, *dportdesc;
5181             sportdesc = dupprintf("%s%s%s%s%d%s",
5182                                   epf->saddr ? epf->saddr : "",
5183                                   epf->saddr ? ":" : "",
5184                                   epf->sserv ? epf->sserv : "",
5185                                   epf->sserv ? "(" : "",
5186                                   epf->sport,
5187                                   epf->sserv ? ")" : "");
5188             if (epf->type == 'D') {
5189                 dportdesc = NULL;
5190             } else {
5191                 dportdesc = dupprintf("%s:%s%s%d%s",
5192                                       epf->daddr,
5193                                       epf->dserv ? epf->dserv : "",
5194                                       epf->dserv ? "(" : "",
5195                                       epf->dport,
5196                                       epf->dserv ? ")" : "");
5197             }
5198
5199             if (epf->type == 'L') {
5200                 char *err = pfl_listen(epf->daddr, epf->dport,
5201                                        epf->saddr, epf->sport,
5202                                        ssh, conf, &epf->local,
5203                                        epf->addressfamily);
5204
5205                 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5206                           epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5207                           epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5208                           sportdesc, dportdesc,
5209                           err ? " failed: " : "", err ? err : "");
5210                 if (err)
5211                     sfree(err);
5212             } else if (epf->type == 'D') {
5213                 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5214                                        ssh, conf, &epf->local,
5215                                        epf->addressfamily);
5216
5217                 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5218                           epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5219                           epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5220                           sportdesc,
5221                           err ? " failed: " : "", err ? err : "");
5222
5223                 if (err)
5224                     sfree(err);
5225             } else {
5226                 struct ssh_rportfwd *pf;
5227
5228                 /*
5229                  * Ensure the remote port forwardings tree exists.
5230                  */
5231                 if (!ssh->rportfwds) {
5232                     if (ssh->version == 1)
5233                         ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5234                     else
5235                         ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5236                 }
5237
5238                 pf = snew(struct ssh_rportfwd);
5239                 pf->share_ctx = NULL;
5240                 pf->dhost = dupstr(epf->daddr);
5241                 pf->dport = epf->dport;
5242                 if (epf->saddr) {
5243                     pf->shost = dupstr(epf->saddr);
5244                 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5245                     pf->shost = dupstr("");
5246                 } else {
5247                     pf->shost = dupstr("localhost");
5248                 }
5249                 pf->sport = epf->sport;
5250                 if (add234(ssh->rportfwds, pf) != pf) {
5251                     logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5252                               epf->daddr, epf->dport);
5253                     sfree(pf);
5254                 } else {
5255                     logeventf(ssh, "Requesting remote port %s"
5256                               " forward to %s", sportdesc, dportdesc);
5257
5258                     pf->sportdesc = sportdesc;
5259                     sportdesc = NULL;
5260                     epf->remote = pf;
5261                     pf->pfrec = epf;
5262
5263                     if (ssh->version == 1) {
5264                         send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5265                                     PKT_INT, epf->sport,
5266                                     PKT_STR, epf->daddr,
5267                                     PKT_INT, epf->dport,
5268                                     PKT_END);
5269                         ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5270                                           SSH1_SMSG_FAILURE,
5271                                           ssh_rportfwd_succfail, pf);
5272                     } else {
5273                         struct Packet *pktout;
5274                         pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5275                         ssh2_pkt_addstring(pktout, "tcpip-forward");
5276                         ssh2_pkt_addbool(pktout, 1);/* want reply */
5277                         ssh2_pkt_addstring(pktout, pf->shost);
5278                         ssh2_pkt_adduint32(pktout, pf->sport);
5279                         ssh2_pkt_send(ssh, pktout);
5280
5281                         ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5282                                           SSH2_MSG_REQUEST_FAILURE,
5283                                           ssh_rportfwd_succfail, pf);
5284                     }
5285                 }
5286             }
5287             sfree(sportdesc);
5288             sfree(dportdesc);
5289         }
5290 }
5291
5292 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5293 {
5294     char *string;
5295     int stringlen, bufsize;
5296
5297     ssh_pkt_getstring(pktin, &string, &stringlen);
5298     if (string == NULL) {
5299         bombout(("Incoming terminal data packet was badly formed"));
5300         return;
5301     }
5302
5303     bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5304                            string, stringlen);
5305     if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5306         ssh->v1_stdout_throttling = 1;
5307         ssh_throttle_conn(ssh, +1);
5308     }
5309 }
5310
5311 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5312 {
5313     /* Remote side is trying to open a channel to talk to our
5314      * X-Server. Give them back a local channel number. */
5315     struct ssh_channel *c;
5316     int remoteid = ssh_pkt_getuint32(pktin);
5317
5318     logevent("Received X11 connect request");
5319     /* Refuse if X11 forwarding is disabled. */
5320     if (!ssh->X11_fwd_enabled) {
5321         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5322                     PKT_INT, remoteid, PKT_END);
5323         logevent("Rejected X11 connect request");
5324     } else {
5325         c = snew(struct ssh_channel);
5326         c->ssh = ssh;
5327
5328         c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5329         c->remoteid = remoteid;
5330         c->halfopen = FALSE;
5331         c->localid = alloc_channel_id(ssh);
5332         c->closes = 0;
5333         c->pending_eof = FALSE;
5334         c->throttling_conn = 0;
5335         c->type = CHAN_X11;     /* identify channel type */
5336         add234(ssh->channels, c);
5337         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5338                     PKT_INT, c->remoteid, PKT_INT,
5339                     c->localid, PKT_END);
5340         logevent("Opened X11 forward channel");
5341     }
5342 }
5343
5344 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5345 {
5346     /* Remote side is trying to open a channel to talk to our
5347      * agent. Give them back a local channel number. */
5348     struct ssh_channel *c;
5349     int remoteid = ssh_pkt_getuint32(pktin);
5350
5351     /* Refuse if agent forwarding is disabled. */
5352     if (!ssh->agentfwd_enabled) {
5353         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5354                     PKT_INT, remoteid, PKT_END);
5355     } else {
5356         c = snew(struct ssh_channel);
5357         c->ssh = ssh;
5358         c->remoteid = remoteid;
5359         c->halfopen = FALSE;
5360         c->localid = alloc_channel_id(ssh);
5361         c->closes = 0;
5362         c->pending_eof = FALSE;
5363         c->throttling_conn = 0;
5364         c->type = CHAN_AGENT;   /* identify channel type */
5365         c->u.a.lensofar = 0;
5366         c->u.a.message = NULL;
5367         c->u.a.outstanding_requests = 0;
5368         add234(ssh->channels, c);
5369         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5370                     PKT_INT, c->remoteid, PKT_INT, c->localid,
5371                     PKT_END);
5372     }
5373 }
5374
5375 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5376 {
5377     /* Remote side is trying to open a channel to talk to a
5378      * forwarded port. Give them back a local channel number. */
5379     struct ssh_rportfwd pf, *pfp;
5380     int remoteid;
5381     int hostsize, port;
5382     char *host;
5383     char *err;
5384
5385     remoteid = ssh_pkt_getuint32(pktin);
5386     ssh_pkt_getstring(pktin, &host, &hostsize);
5387     port = ssh_pkt_getuint32(pktin);
5388
5389     pf.dhost = dupprintf("%.*s", hostsize, host);
5390     pf.dport = port;
5391     pfp = find234(ssh->rportfwds, &pf, NULL);
5392
5393     if (pfp == NULL) {
5394         logeventf(ssh, "Rejected remote port open request for %s:%d",
5395                   pf.dhost, port);
5396         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5397                     PKT_INT, remoteid, PKT_END);
5398     } else {
5399         struct ssh_channel *c = snew(struct ssh_channel);
5400         c->ssh = ssh;
5401
5402         logeventf(ssh, "Received remote port open request for %s:%d",
5403                   pf.dhost, port);
5404         err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5405                           c, ssh->conf, pfp->pfrec->addressfamily);
5406         if (err != NULL) {
5407             logeventf(ssh, "Port open failed: %s", err);
5408             sfree(err);
5409             sfree(c);
5410             send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5411                         PKT_INT, remoteid, PKT_END);
5412         } else {
5413             c->remoteid = remoteid;
5414             c->halfopen = FALSE;
5415             c->localid = alloc_channel_id(ssh);
5416             c->closes = 0;
5417             c->pending_eof = FALSE;
5418             c->throttling_conn = 0;
5419             c->type = CHAN_SOCKDATA;    /* identify channel type */
5420             add234(ssh->channels, c);
5421             send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5422                         PKT_INT, c->remoteid, PKT_INT,
5423                         c->localid, PKT_END);
5424             logevent("Forwarded port opened successfully");
5425         }
5426     }
5427
5428     sfree(pf.dhost);
5429 }
5430
5431 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5432 {
5433     unsigned int remoteid = ssh_pkt_getuint32(pktin);
5434     unsigned int localid = ssh_pkt_getuint32(pktin);
5435     struct ssh_channel *c;
5436
5437     c = find234(ssh->channels, &remoteid, ssh_channelfind);
5438     if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5439         c->remoteid = localid;
5440         c->halfopen = FALSE;
5441         c->type = CHAN_SOCKDATA;
5442         c->throttling_conn = 0;
5443         pfd_confirm(c->u.pfd.pf);
5444     }
5445
5446     if (c && c->pending_eof) {
5447         /*
5448          * We have a pending close on this channel,
5449          * which we decided on before the server acked
5450          * the channel open. So now we know the
5451          * remoteid, we can close it again.
5452          */
5453         ssh_channel_try_eof(c);
5454     }
5455 }
5456
5457 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5458 {
5459     unsigned int remoteid = ssh_pkt_getuint32(pktin);
5460     struct ssh_channel *c;
5461
5462     c = find234(ssh->channels, &remoteid, ssh_channelfind);
5463     if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5464         logevent("Forwarded connection refused by server");
5465         pfd_close(c->u.pfd.pf);
5466         del234(ssh->channels, c);
5467         sfree(c);
5468     }
5469 }
5470
5471 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5472 {
5473     /* Remote side closes a channel. */
5474     unsigned i = ssh_pkt_getuint32(pktin);
5475     struct ssh_channel *c;
5476     c = find234(ssh->channels, &i, ssh_channelfind);
5477     if (c && !c->halfopen) {
5478
5479         if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5480             !(c->closes & CLOSES_RCVD_EOF)) {
5481             /*
5482              * Received CHANNEL_CLOSE, which we translate into
5483              * outgoing EOF.
5484              */
5485             int send_close = FALSE;
5486
5487             c->closes |= CLOSES_RCVD_EOF;
5488
5489             switch (c->type) {
5490               case CHAN_X11:
5491                 if (c->u.x11.xconn)
5492                     x11_send_eof(c->u.x11.xconn);
5493                 else
5494                     send_close = TRUE;
5495                 break;
5496               case CHAN_SOCKDATA:
5497                 if (c->u.pfd.pf)
5498                     pfd_send_eof(c->u.pfd.pf);
5499                 else
5500                     send_close = TRUE;
5501                 break;
5502               case CHAN_AGENT:
5503                 send_close = TRUE;
5504                 break;
5505             }
5506
5507             if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5508                 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5509                             PKT_END);
5510                 c->closes |= CLOSES_SENT_EOF;
5511             }
5512         }
5513
5514         if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5515             !(c->closes & CLOSES_RCVD_CLOSE)) {
5516
5517             if (!(c->closes & CLOSES_SENT_EOF)) {
5518                 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5519                          " for which we never sent CHANNEL_CLOSE\n", i));
5520             }
5521
5522             c->closes |= CLOSES_RCVD_CLOSE;
5523         }
5524
5525         if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5526             !(c->closes & CLOSES_SENT_CLOSE)) {
5527             send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5528                         PKT_INT, c->remoteid, PKT_END);
5529             c->closes |= CLOSES_SENT_CLOSE;
5530         }
5531
5532         if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5533             ssh_channel_destroy(c);
5534     } else {
5535         bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5536                  pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5537                  "_CONFIRMATION", c ? "half-open" : "nonexistent",
5538                  i));
5539     }
5540 }
5541
5542 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5543 {
5544     /* Data sent down one of our channels. */
5545     int i = ssh_pkt_getuint32(pktin);
5546     char *p;
5547     int len;
5548     struct ssh_channel *c;
5549
5550     ssh_pkt_getstring(pktin, &p, &len);
5551
5552     c = find234(ssh->channels, &i, ssh_channelfind);
5553     if (c) {
5554         int bufsize = 0;
5555         switch (c->type) {
5556           case CHAN_X11:
5557             bufsize = x11_send(c->u.x11.xconn, p, len);
5558             break;
5559           case CHAN_SOCKDATA:
5560             bufsize = pfd_send(c->u.pfd.pf, p, len);
5561             break;
5562           case CHAN_AGENT:
5563             /* Data for an agent message. Buffer it. */
5564             while (len > 0) {
5565                 if (c->u.a.lensofar < 4) {
5566                     unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5567                     memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5568                            l);
5569                     p += l;
5570                     len -= l;
5571                     c->u.a.lensofar += l;
5572                 }
5573                 if (c->u.a.lensofar == 4) {
5574                     c->u.a.totallen =
5575                         4 + GET_32BIT(c->u.a.msglen);
5576                     c->u.a.message = snewn(c->u.a.totallen,
5577                                            unsigned char);
5578                     memcpy(c->u.a.message, c->u.a.msglen, 4);
5579                 }
5580                 if (c->u.a.lensofar >= 4 && len > 0) {
5581                     unsigned int l =
5582                         min(c->u.a.totallen - c->u.a.lensofar,
5583                             (unsigned)len);
5584                     memcpy(c->u.a.message + c->u.a.lensofar, p,
5585                            l);
5586                     p += l;
5587                     len -= l;
5588                     c->u.a.lensofar += l;
5589                 }
5590                 if (c->u.a.lensofar == c->u.a.totallen) {
5591                     void *reply;
5592                     int replylen;
5593                     c->u.a.outstanding_requests++;
5594                     if (agent_query(c->u.a.message,
5595                                     c->u.a.totallen,
5596                                     &reply, &replylen,
5597                                     ssh_agentf_callback, c))
5598                         ssh_agentf_callback(c, reply, replylen);
5599                     sfree(c->u.a.message);
5600                     c->u.a.lensofar = 0;
5601                 }
5602             }
5603             bufsize = 0;   /* agent channels never back up */
5604             break;
5605         }
5606         if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5607             c->throttling_conn = 1;
5608             ssh_throttle_conn(ssh, +1);
5609         }
5610     }
5611 }
5612
5613 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5614 {
5615     ssh->exitcode = ssh_pkt_getuint32(pktin);
5616     logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5617     send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5618     /*
5619      * In case `helpful' firewalls or proxies tack
5620      * extra human-readable text on the end of the
5621      * session which we might mistake for another
5622      * encrypted packet, we close the session once
5623      * we've sent EXIT_CONFIRMATION.
5624      */
5625     ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5626 }
5627
5628 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5629 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5630 {
5631     struct Packet *pktout = (struct Packet *)data;
5632     int i = 0;
5633     unsigned int arg = 0;
5634     while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5635     if (i == lenof(ssh_ttymodes)) return;
5636     switch (ssh_ttymodes[i].type) {
5637       case TTY_OP_CHAR:
5638         arg = ssh_tty_parse_specchar(val);
5639         break;
5640       case TTY_OP_BOOL:
5641         arg = ssh_tty_parse_boolean(val);
5642         break;
5643     }
5644     ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5645     ssh2_pkt_addbyte(pktout, arg);
5646 }
5647
5648 int ssh_agent_forwarding_permitted(Ssh ssh)
5649 {
5650     return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5651 }
5652
5653 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5654                                struct Packet *pktin)
5655 {
5656     crBegin(ssh->do_ssh1_connection_crstate);
5657
5658     ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] = 
5659         ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5660         ssh1_smsg_stdout_stderr_data;
5661
5662     ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5663         ssh1_msg_channel_open_confirmation;
5664     ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5665         ssh1_msg_channel_open_failure;
5666     ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5667         ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5668         ssh1_msg_channel_close;
5669     ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5670     ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5671
5672     if (ssh_agent_forwarding_permitted(ssh)) {
5673         logevent("Requesting agent forwarding");
5674         send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5675         do {
5676             crReturnV;
5677         } while (!pktin);
5678         if (pktin->type != SSH1_SMSG_SUCCESS
5679             && pktin->type != SSH1_SMSG_FAILURE) {
5680             bombout(("Protocol confusion"));
5681             crStopV;
5682         } else if (pktin->type == SSH1_SMSG_FAILURE) {
5683             logevent("Agent forwarding refused");
5684         } else {
5685             logevent("Agent forwarding enabled");
5686             ssh->agentfwd_enabled = TRUE;
5687             ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5688         }
5689     }
5690
5691     if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5692         ssh->x11disp =
5693             x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5694                               ssh->conf);
5695         if (!ssh->x11disp) {
5696             /* FIXME: return an error message from x11_setup_display */
5697             logevent("X11 forwarding not enabled: unable to"
5698                      " initialise X display");
5699         } else {
5700             ssh->x11auth = x11_invent_fake_auth
5701                 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5702             ssh->x11auth->disp = ssh->x11disp;
5703
5704             logevent("Requesting X11 forwarding");
5705             if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5706                 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5707                             PKT_STR, ssh->x11auth->protoname,
5708                             PKT_STR, ssh->x11auth->datastring,
5709                             PKT_INT, ssh->x11disp->screennum,
5710                             PKT_END);
5711             } else {
5712                 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5713                             PKT_STR, ssh->x11auth->protoname,
5714                             PKT_STR, ssh->x11auth->datastring,
5715                             PKT_END);
5716             }
5717             do {
5718                 crReturnV;
5719             } while (!pktin);
5720             if (pktin->type != SSH1_SMSG_SUCCESS
5721                 && pktin->type != SSH1_SMSG_FAILURE) {
5722                 bombout(("Protocol confusion"));
5723                 crStopV;
5724             } else if (pktin->type == SSH1_SMSG_FAILURE) {
5725                 logevent("X11 forwarding refused");
5726             } else {
5727                 logevent("X11 forwarding enabled");
5728                 ssh->X11_fwd_enabled = TRUE;
5729                 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5730             }
5731         }
5732     }
5733
5734     ssh_setup_portfwd(ssh, ssh->conf);
5735     ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5736
5737     if (!conf_get_int(ssh->conf, CONF_nopty)) {
5738         struct Packet *pkt;
5739         /* Unpick the terminal-speed string. */
5740         /* XXX perhaps we should allow no speeds to be sent. */
5741         ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5742         sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5743         /* Send the pty request. */
5744         pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5745         ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5746         ssh_pkt_adduint32(pkt, ssh->term_height);
5747         ssh_pkt_adduint32(pkt, ssh->term_width);
5748         ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5749         ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5750         parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5751         ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5752         ssh_pkt_adduint32(pkt, ssh->ispeed);
5753         ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5754         ssh_pkt_adduint32(pkt, ssh->ospeed);
5755         ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5756         s_wrpkt(ssh, pkt);
5757         ssh->state = SSH_STATE_INTERMED;
5758         do {
5759             crReturnV;
5760         } while (!pktin);
5761         if (pktin->type != SSH1_SMSG_SUCCESS
5762             && pktin->type != SSH1_SMSG_FAILURE) {
5763             bombout(("Protocol confusion"));
5764             crStopV;
5765         } else if (pktin->type == SSH1_SMSG_FAILURE) {
5766             c_write_str(ssh, "Server refused to allocate pty\r\n");
5767             ssh->editing = ssh->echoing = 1;
5768         } else {
5769             logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5770                       ssh->ospeed, ssh->ispeed);
5771             ssh->got_pty = TRUE;
5772         }
5773     } else {
5774         ssh->editing = ssh->echoing = 1;
5775     }
5776
5777     if (conf_get_int(ssh->conf, CONF_compression)) {
5778         send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5779         do {
5780             crReturnV;
5781         } while (!pktin);
5782         if (pktin->type != SSH1_SMSG_SUCCESS
5783             && pktin->type != SSH1_SMSG_FAILURE) {
5784             bombout(("Protocol confusion"));
5785             crStopV;
5786         } else if (pktin->type == SSH1_SMSG_FAILURE) {
5787             c_write_str(ssh, "Server refused to compress\r\n");
5788         }
5789         logevent("Started compression");
5790         ssh->v1_compressing = TRUE;
5791         ssh->cs_comp_ctx = zlib_compress_init();
5792         logevent("Initialised zlib (RFC1950) compression");
5793         ssh->sc_comp_ctx = zlib_decompress_init();
5794         logevent("Initialised zlib (RFC1950) decompression");
5795     }
5796
5797     /*
5798      * Start the shell or command.
5799      * 
5800      * Special case: if the first-choice command is an SSH-2
5801      * subsystem (hence not usable here) and the second choice
5802      * exists, we fall straight back to that.
5803      */
5804     {
5805         char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5806         
5807         if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5808             conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5809             cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5810             ssh->fallback_cmd = TRUE;
5811         }
5812         if (*cmd)
5813             send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5814         else
5815             send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5816         logevent("Started session");
5817     }
5818
5819     ssh->state = SSH_STATE_SESSION;
5820     if (ssh->size_needed)
5821         ssh_size(ssh, ssh->term_width, ssh->term_height);
5822     if (ssh->eof_needed)
5823         ssh_special(ssh, TS_EOF);
5824
5825     if (ssh->ldisc)
5826         ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5827     ssh->send_ok = 1;
5828     ssh->channels = newtree234(ssh_channelcmp);
5829     while (1) {
5830
5831         /*
5832          * By this point, most incoming packets are already being
5833          * handled by the dispatch table, and we need only pay
5834          * attention to the unusual ones.
5835          */
5836
5837         crReturnV;
5838         if (pktin) {
5839             if (pktin->type == SSH1_SMSG_SUCCESS) {
5840                 /* may be from EXEC_SHELL on some servers */
5841             } else if (pktin->type == SSH1_SMSG_FAILURE) {
5842                 /* may be from EXEC_SHELL on some servers
5843                  * if no pty is available or in other odd cases. Ignore */
5844             } else {
5845                 bombout(("Strange packet received: type %d", pktin->type));
5846                 crStopV;
5847             }
5848         } else {
5849             while (inlen > 0) {
5850                 int len = min(inlen, 512);
5851                 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5852                             PKT_INT, len, PKT_DATA, in, len,
5853                             PKT_END);
5854                 in += len;
5855                 inlen -= len;
5856             }
5857         }
5858     }
5859
5860     crFinishV;
5861 }
5862
5863 /*
5864  * Handle the top-level SSH-2 protocol.
5865  */
5866 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5867 {
5868     char *msg;
5869     int msglen;
5870
5871     ssh_pkt_getstring(pktin, &msg, &msglen);
5872     logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5873 }
5874
5875 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5876 {
5877     /* log reason code in disconnect message */
5878     char *msg;
5879     int msglen;
5880
5881     ssh_pkt_getstring(pktin, &msg, &msglen);
5882     bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5883 }
5884
5885 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5886 {
5887     /* Do nothing, because we're ignoring it! Duhh. */
5888 }
5889
5890 static void ssh1_protocol_setup(Ssh ssh)
5891 {
5892     int i;
5893
5894     /*
5895      * Most messages are handled by the coroutines.
5896      */
5897     for (i = 0; i < 256; i++)
5898         ssh->packet_dispatch[i] = NULL;
5899
5900     /*
5901      * These special message types we install handlers for.
5902      */
5903     ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5904     ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5905     ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5906 }
5907
5908 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5909                           struct Packet *pktin)
5910 {
5911     unsigned char *in=(unsigned char*)vin;
5912     if (ssh->state == SSH_STATE_CLOSED)
5913         return;
5914
5915     if (pktin && ssh->packet_dispatch[pktin->type]) {
5916         ssh->packet_dispatch[pktin->type](ssh, pktin);
5917         return;
5918     }
5919
5920     if (!ssh->protocol_initial_phase_done) {
5921         if (do_ssh1_login(ssh, in, inlen, pktin))
5922             ssh->protocol_initial_phase_done = TRUE;
5923         else
5924             return;
5925     }
5926
5927     do_ssh1_connection(ssh, in, inlen, pktin);
5928 }
5929
5930 /*
5931  * Utility routine for decoding comma-separated strings in KEXINIT.
5932  */
5933 static int in_commasep_string(char *needle, char *haystack, int haylen)
5934 {
5935     int needlen;
5936     if (!needle || !haystack)          /* protect against null pointers */
5937         return 0;
5938     needlen = strlen(needle);
5939     while (1) {
5940         /*
5941          * Is it at the start of the string?
5942          */
5943         if (haylen >= needlen &&       /* haystack is long enough */
5944             !memcmp(needle, haystack, needlen) &&       /* initial match */
5945             (haylen == needlen || haystack[needlen] == ',')
5946             /* either , or EOS follows */
5947             )
5948             return 1;
5949         /*
5950          * If not, search for the next comma and resume after that.
5951          * If no comma found, terminate.
5952          */
5953         while (haylen > 0 && *haystack != ',')
5954             haylen--, haystack++;
5955         if (haylen == 0)
5956             return 0;
5957         haylen--, haystack++;          /* skip over comma itself */
5958     }
5959 }
5960
5961 /*
5962  * Similar routine for checking whether we have the first string in a list.
5963  */
5964 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5965 {
5966     int needlen;
5967     if (!needle || !haystack)          /* protect against null pointers */
5968         return 0;
5969     needlen = strlen(needle);
5970     /*
5971      * Is it at the start of the string?
5972      */
5973     if (haylen >= needlen &&       /* haystack is long enough */
5974         !memcmp(needle, haystack, needlen) &&   /* initial match */
5975         (haylen == needlen || haystack[needlen] == ',')
5976         /* either , or EOS follows */
5977         )
5978         return 1;
5979     return 0;
5980 }
5981
5982
5983 /*
5984  * SSH-2 key creation method.
5985  * (Currently assumes 2 lots of any hash are sufficient to generate
5986  * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5987  */
5988 #define SSH2_MKKEY_ITERS (2)
5989 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5990                        unsigned char *keyspace)
5991 {
5992     const struct ssh_hash *h = ssh->kex->hash;
5993     void *s;
5994     /* First hlen bytes. */
5995     s = h->init();
5996     if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5997         hash_mpint(h, s, K);
5998     h->bytes(s, H, h->hlen);
5999     h->bytes(s, &chr, 1);
6000     h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6001     h->final(s, keyspace);
6002     /* Next hlen bytes. */
6003     s = h->init();
6004     if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6005         hash_mpint(h, s, K);
6006     h->bytes(s, H, h->hlen);
6007     h->bytes(s, keyspace, h->hlen);
6008     h->final(s, keyspace + h->hlen);
6009 }
6010
6011 /*
6012  * Handle the SSH-2 transport layer.
6013  */
6014 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6015                              struct Packet *pktin)
6016 {
6017     unsigned char *in = (unsigned char *)vin;
6018     struct do_ssh2_transport_state {
6019         int crLine;
6020         int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6021         Bignum p, g, e, f, K;
6022         void *our_kexinit;
6023         int our_kexinitlen;
6024         int kex_init_value, kex_reply_value;
6025         const struct ssh_mac **maclist;
6026         int nmacs;
6027         const struct ssh2_cipher *cscipher_tobe;
6028         const struct ssh2_cipher *sccipher_tobe;
6029         const struct ssh_mac *csmac_tobe;
6030         const struct ssh_mac *scmac_tobe;
6031         const struct ssh_compress *cscomp_tobe;
6032         const struct ssh_compress *sccomp_tobe;
6033         char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6034         int hostkeylen, siglen, rsakeylen;
6035         void *hkey;                    /* actual host key */
6036         void *rsakey;                  /* for RSA kex */
6037         unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6038         int n_preferred_kex;
6039         const struct ssh_kexes *preferred_kex[KEX_MAX];
6040         int n_preferred_ciphers;
6041         const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6042         const struct ssh_compress *preferred_comp;
6043         int userauth_succeeded;     /* for delayed compression */
6044         int pending_compression;
6045         int got_session_id, activated_authconn;
6046         struct Packet *pktout;
6047         int dlgret;
6048         int guessok;
6049         int ignorepkt;
6050     };
6051     crState(do_ssh2_transport_state);
6052
6053     assert(!ssh->bare_connection);
6054
6055     crBeginState;
6056
6057     s->cscipher_tobe = s->sccipher_tobe = NULL;
6058     s->csmac_tobe = s->scmac_tobe = NULL;
6059     s->cscomp_tobe = s->sccomp_tobe = NULL;
6060
6061     s->got_session_id = s->activated_authconn = FALSE;
6062     s->userauth_succeeded = FALSE;
6063     s->pending_compression = FALSE;
6064
6065     /*
6066      * Be prepared to work around the buggy MAC problem.
6067      */
6068     if (ssh->remote_bugs & BUG_SSH2_HMAC)
6069         s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6070     else
6071         s->maclist = macs, s->nmacs = lenof(macs);
6072
6073   begin_key_exchange:
6074     ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6075     {
6076         int i, j, k, commalist_started;
6077
6078         /*
6079          * Set up the preferred key exchange. (NULL => warn below here)
6080          */
6081         s->n_preferred_kex = 0;
6082         for (i = 0; i < KEX_MAX; i++) {
6083             switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6084               case KEX_DHGEX:
6085                 s->preferred_kex[s->n_preferred_kex++] =
6086                     &ssh_diffiehellman_gex;
6087                 break;
6088               case KEX_DHGROUP14:
6089                 s->preferred_kex[s->n_preferred_kex++] =
6090                     &ssh_diffiehellman_group14;
6091                 break;
6092               case KEX_DHGROUP1:
6093                 s->preferred_kex[s->n_preferred_kex++] =
6094                     &ssh_diffiehellman_group1;
6095                 break;
6096               case KEX_RSA:
6097                 s->preferred_kex[s->n_preferred_kex++] =
6098                     &ssh_rsa_kex;
6099                 break;
6100               case KEX_WARN:
6101                 /* Flag for later. Don't bother if it's the last in
6102                  * the list. */
6103                 if (i < KEX_MAX - 1) {
6104                     s->preferred_kex[s->n_preferred_kex++] = NULL;
6105                 }
6106                 break;
6107             }
6108         }
6109
6110         /*
6111          * Set up the preferred ciphers. (NULL => warn below here)
6112          */
6113         s->n_preferred_ciphers = 0;
6114         for (i = 0; i < CIPHER_MAX; i++) {
6115             switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6116               case CIPHER_BLOWFISH:
6117                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6118                 break;
6119               case CIPHER_DES:
6120                 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6121                     s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6122                 }
6123                 break;
6124               case CIPHER_3DES:
6125                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6126                 break;
6127               case CIPHER_AES:
6128                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6129                 break;
6130               case CIPHER_ARCFOUR:
6131                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6132                 break;
6133               case CIPHER_WARN:
6134                 /* Flag for later. Don't bother if it's the last in
6135                  * the list. */
6136                 if (i < CIPHER_MAX - 1) {
6137                     s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6138                 }
6139                 break;
6140             }
6141         }
6142
6143         /*
6144          * Set up preferred compression.
6145          */
6146         if (conf_get_int(ssh->conf, CONF_compression))
6147             s->preferred_comp = &ssh_zlib;
6148         else
6149             s->preferred_comp = &ssh_comp_none;
6150
6151         /*
6152          * Enable queueing of outgoing auth- or connection-layer
6153          * packets while we are in the middle of a key exchange.
6154          */
6155         ssh->queueing = TRUE;
6156
6157         /*
6158          * Flag that KEX is in progress.
6159          */
6160         ssh->kex_in_progress = TRUE;
6161
6162         /*
6163          * Construct and send our key exchange packet.
6164          */
6165         s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6166         for (i = 0; i < 16; i++)
6167             ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6168         /* List key exchange algorithms. */
6169         ssh2_pkt_addstring_start(s->pktout);
6170         commalist_started = 0;
6171         for (i = 0; i < s->n_preferred_kex; i++) {
6172             const struct ssh_kexes *k = s->preferred_kex[i];
6173             if (!k) continue;          /* warning flag */
6174             for (j = 0; j < k->nkexes; j++) {
6175                 if (commalist_started)
6176                     ssh2_pkt_addstring_str(s->pktout, ",");
6177                 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
6178                 commalist_started = 1;
6179             }
6180         }
6181         /* List server host key algorithms. */
6182         if (!s->got_session_id) {
6183             /*
6184              * In the first key exchange, we list all the algorithms
6185              * we're prepared to cope with.
6186              */
6187             ssh2_pkt_addstring_start(s->pktout);
6188             for (i = 0; i < lenof(hostkey_algs); i++) {
6189                 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
6190                 if (i < lenof(hostkey_algs) - 1)
6191                     ssh2_pkt_addstring_str(s->pktout, ",");
6192             }
6193         } else {
6194             /*
6195              * In subsequent key exchanges, we list only the kex
6196              * algorithm that was selected in the first key exchange,
6197              * so that we keep getting the same host key and hence
6198              * don't have to interrupt the user's session to ask for
6199              * reverification.
6200              */
6201             assert(ssh->kex);
6202             ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6203         }
6204         /* List encryption algorithms (client->server then server->client). */
6205         for (k = 0; k < 2; k++) {
6206             ssh2_pkt_addstring_start(s->pktout);
6207             commalist_started = 0;
6208             for (i = 0; i < s->n_preferred_ciphers; i++) {
6209                 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6210                 if (!c) continue;              /* warning flag */
6211                 for (j = 0; j < c->nciphers; j++) {
6212                     if (commalist_started)
6213                         ssh2_pkt_addstring_str(s->pktout, ",");
6214                     ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
6215                     commalist_started = 1;
6216                 }
6217             }
6218         }
6219         /* List MAC algorithms (client->server then server->client). */
6220         for (j = 0; j < 2; j++) {
6221             ssh2_pkt_addstring_start(s->pktout);
6222             for (i = 0; i < s->nmacs; i++) {
6223                 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
6224                 if (i < s->nmacs - 1)
6225                     ssh2_pkt_addstring_str(s->pktout, ",");
6226             }
6227         }
6228         /* List client->server compression algorithms,
6229          * then server->client compression algorithms. (We use the
6230          * same set twice.) */
6231         for (j = 0; j < 2; j++) {
6232             ssh2_pkt_addstring_start(s->pktout);
6233             assert(lenof(compressions) > 1);
6234             /* Prefer non-delayed versions */
6235             ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
6236             /* We don't even list delayed versions of algorithms until
6237              * they're allowed to be used, to avoid a race. See the end of
6238              * this function. */
6239             if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6240                 ssh2_pkt_addstring_str(s->pktout, ",");
6241                 ssh2_pkt_addstring_str(s->pktout,
6242                                        s->preferred_comp->delayed_name);
6243             }
6244             for (i = 0; i < lenof(compressions); i++) {
6245                 const struct ssh_compress *c = compressions[i];
6246                 if (c != s->preferred_comp) {
6247                     ssh2_pkt_addstring_str(s->pktout, ",");
6248                     ssh2_pkt_addstring_str(s->pktout, c->name);
6249                     if (s->userauth_succeeded && c->delayed_name) {
6250                         ssh2_pkt_addstring_str(s->pktout, ",");
6251                         ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
6252                     }
6253                 }
6254             }
6255         }
6256         /* List client->server languages. Empty list. */
6257         ssh2_pkt_addstring_start(s->pktout);
6258         /* List server->client languages. Empty list. */
6259         ssh2_pkt_addstring_start(s->pktout);
6260         /* First KEX packet does _not_ follow, because we're not that brave. */
6261         ssh2_pkt_addbool(s->pktout, FALSE);
6262         /* Reserved. */
6263         ssh2_pkt_adduint32(s->pktout, 0);
6264     }
6265
6266     s->our_kexinitlen = s->pktout->length - 5;
6267     s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6268     memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen); 
6269
6270     ssh2_pkt_send_noqueue(ssh, s->pktout);
6271
6272     if (!pktin)
6273         crWaitUntilV(pktin);
6274
6275     /*
6276      * Now examine the other side's KEXINIT to see what we're up
6277      * to.
6278      */
6279     {
6280         char *str, *preferred;
6281         int i, j, len;
6282
6283         if (pktin->type != SSH2_MSG_KEXINIT) {
6284             bombout(("expected key exchange packet from server"));
6285             crStopV;
6286         }
6287         ssh->kex = NULL;
6288         ssh->hostkey = NULL;
6289         s->cscipher_tobe = NULL;
6290         s->sccipher_tobe = NULL;
6291         s->csmac_tobe = NULL;
6292         s->scmac_tobe = NULL;
6293         s->cscomp_tobe = NULL;
6294         s->sccomp_tobe = NULL;
6295         s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6296
6297         pktin->savedpos += 16;          /* skip garbage cookie */
6298         ssh_pkt_getstring(pktin, &str, &len);    /* key exchange algorithms */
6299         if (!str) {
6300             bombout(("KEXINIT packet was incomplete"));
6301             crStopV;
6302         }
6303
6304         preferred = NULL;
6305         for (i = 0; i < s->n_preferred_kex; i++) {
6306             const struct ssh_kexes *k = s->preferred_kex[i];
6307             if (!k) {
6308                 s->warn_kex = TRUE;
6309             } else {
6310                 for (j = 0; j < k->nkexes; j++) {
6311                     if (!preferred) preferred = k->list[j]->name;
6312                     if (in_commasep_string(k->list[j]->name, str, len)) {
6313                         ssh->kex = k->list[j];
6314                         break;
6315                     }
6316                 }
6317             }
6318             if (ssh->kex)
6319                 break;
6320         }
6321         if (!ssh->kex) {
6322             bombout(("Couldn't agree a key exchange algorithm"
6323                      " (available: %.*s)", len, str));
6324             crStopV;
6325         }
6326         /*
6327          * Note that the server's guess is considered wrong if it doesn't match
6328          * the first algorithm in our list, even if it's still the algorithm
6329          * we end up using.
6330          */
6331         s->guessok = first_in_commasep_string(preferred, str, len);
6332         ssh_pkt_getstring(pktin, &str, &len);    /* host key algorithms */
6333         if (!str) {
6334             bombout(("KEXINIT packet was incomplete"));
6335             crStopV;
6336         }
6337         for (i = 0; i < lenof(hostkey_algs); i++) {
6338             if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6339                 ssh->hostkey = hostkey_algs[i];
6340                 break;
6341             }
6342         }
6343         if (!ssh->hostkey) {
6344             bombout(("Couldn't agree a host key algorithm"
6345                      " (available: %.*s)", len, str));
6346             crStopV;
6347         }
6348
6349         s->guessok = s->guessok &&
6350             first_in_commasep_string(hostkey_algs[0]->name, str, len);
6351         ssh_pkt_getstring(pktin, &str, &len);    /* client->server cipher */
6352         if (!str) {
6353             bombout(("KEXINIT packet was incomplete"));
6354             crStopV;
6355         }
6356         for (i = 0; i < s->n_preferred_ciphers; i++) {
6357             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6358             if (!c) {
6359                 s->warn_cscipher = TRUE;
6360             } else {
6361                 for (j = 0; j < c->nciphers; j++) {
6362                     if (in_commasep_string(c->list[j]->name, str, len)) {
6363                         s->cscipher_tobe = c->list[j];
6364                         break;
6365                     }
6366                 }
6367             }
6368             if (s->cscipher_tobe)
6369                 break;
6370         }
6371         if (!s->cscipher_tobe) {
6372             bombout(("Couldn't agree a client-to-server cipher"
6373                      " (available: %.*s)", len, str));
6374             crStopV;
6375         }
6376
6377         ssh_pkt_getstring(pktin, &str, &len);    /* server->client cipher */
6378         if (!str) {
6379             bombout(("KEXINIT packet was incomplete"));
6380             crStopV;
6381         }
6382         for (i = 0; i < s->n_preferred_ciphers; i++) {
6383             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6384             if (!c) {
6385                 s->warn_sccipher = TRUE;
6386             } else {
6387                 for (j = 0; j < c->nciphers; j++) {
6388                     if (in_commasep_string(c->list[j]->name, str, len)) {
6389                         s->sccipher_tobe = c->list[j];
6390                         break;
6391                     }
6392                 }
6393             }
6394             if (s->sccipher_tobe)
6395                 break;
6396         }
6397         if (!s->sccipher_tobe) {
6398             bombout(("Couldn't agree a server-to-client cipher"
6399                      " (available: %.*s)", len, str));
6400             crStopV;
6401         }
6402
6403         ssh_pkt_getstring(pktin, &str, &len);    /* client->server mac */
6404         if (!str) {
6405             bombout(("KEXINIT packet was incomplete"));
6406             crStopV;
6407         }
6408         for (i = 0; i < s->nmacs; i++) {
6409             if (in_commasep_string(s->maclist[i]->name, str, len)) {
6410                 s->csmac_tobe = s->maclist[i];
6411                 break;
6412             }
6413         }
6414         ssh_pkt_getstring(pktin, &str, &len);    /* server->client mac */
6415         if (!str) {
6416             bombout(("KEXINIT packet was incomplete"));
6417             crStopV;
6418         }
6419         for (i = 0; i < s->nmacs; i++) {
6420             if (in_commasep_string(s->maclist[i]->name, str, len)) {
6421                 s->scmac_tobe = s->maclist[i];
6422                 break;
6423             }
6424         }
6425         ssh_pkt_getstring(pktin, &str, &len);  /* client->server compression */
6426         if (!str) {
6427             bombout(("KEXINIT packet was incomplete"));
6428             crStopV;
6429         }
6430         for (i = 0; i < lenof(compressions) + 1; i++) {
6431             const struct ssh_compress *c =
6432                 i == 0 ? s->preferred_comp : compressions[i - 1];
6433             if (in_commasep_string(c->name, str, len)) {
6434                 s->cscomp_tobe = c;
6435                 break;
6436             } else if (in_commasep_string(c->delayed_name, str, len)) {
6437                 if (s->userauth_succeeded) {
6438                     s->cscomp_tobe = c;
6439                     break;
6440                 } else {
6441                     s->pending_compression = TRUE;  /* try this later */
6442                 }
6443             }
6444         }
6445         ssh_pkt_getstring(pktin, &str, &len);  /* server->client compression */
6446         if (!str) {
6447             bombout(("KEXINIT packet was incomplete"));
6448             crStopV;
6449         }
6450         for (i = 0; i < lenof(compressions) + 1; i++) {
6451             const struct ssh_compress *c =
6452                 i == 0 ? s->preferred_comp : compressions[i - 1];
6453             if (in_commasep_string(c->name, str, len)) {
6454                 s->sccomp_tobe = c;
6455                 break;
6456             } else if (in_commasep_string(c->delayed_name, str, len)) {
6457                 if (s->userauth_succeeded) {
6458                     s->sccomp_tobe = c;
6459                     break;
6460                 } else {
6461                     s->pending_compression = TRUE;  /* try this later */
6462                 }
6463             }
6464         }
6465         if (s->pending_compression) {
6466             logevent("Server supports delayed compression; "
6467                      "will try this later");
6468         }
6469         ssh_pkt_getstring(pktin, &str, &len);  /* client->server language */
6470         ssh_pkt_getstring(pktin, &str, &len);  /* server->client language */
6471         s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6472
6473         ssh->exhash = ssh->kex->hash->init();
6474         hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6475         hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6476         hash_string(ssh->kex->hash, ssh->exhash,
6477             s->our_kexinit, s->our_kexinitlen);
6478         sfree(s->our_kexinit);
6479         /* Include the type byte in the hash of server's KEXINIT */
6480         hash_string(ssh->kex->hash, ssh->exhash,
6481                     pktin->body - 1, pktin->length + 1);
6482
6483         if (s->warn_kex) {
6484             ssh_set_frozen(ssh, 1);
6485             s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6486                                ssh->kex->name,
6487                                ssh_dialog_callback, ssh);
6488             if (s->dlgret < 0) {
6489                 do {
6490                     crReturnV;
6491                     if (pktin) {
6492                         bombout(("Unexpected data from server while"
6493                                  " waiting for user response"));
6494                         crStopV;
6495                     }
6496                 } while (pktin || inlen > 0);
6497                 s->dlgret = ssh->user_response;
6498             }
6499             ssh_set_frozen(ssh, 0);
6500             if (s->dlgret == 0) {
6501                 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6502                                0, TRUE);
6503                 crStopV;
6504             }
6505         }
6506
6507         if (s->warn_cscipher) {
6508             ssh_set_frozen(ssh, 1);
6509             s->dlgret = askalg(ssh->frontend,
6510                                "client-to-server cipher",
6511                                s->cscipher_tobe->name,
6512                                ssh_dialog_callback, ssh);
6513             if (s->dlgret < 0) {
6514                 do {
6515                     crReturnV;
6516                     if (pktin) {
6517                         bombout(("Unexpected data from server while"
6518                                  " waiting for user response"));
6519                         crStopV;
6520                     }
6521                 } while (pktin || inlen > 0);
6522                 s->dlgret = ssh->user_response;
6523             }
6524             ssh_set_frozen(ssh, 0);
6525             if (s->dlgret == 0) {
6526                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6527                                0, TRUE);
6528                 crStopV;
6529             }
6530         }
6531
6532         if (s->warn_sccipher) {
6533             ssh_set_frozen(ssh, 1);
6534             s->dlgret = askalg(ssh->frontend,
6535                                "server-to-client cipher",
6536                                s->sccipher_tobe->name,
6537                                ssh_dialog_callback, ssh);
6538             if (s->dlgret < 0) {
6539                 do {
6540                     crReturnV;
6541                     if (pktin) {
6542                         bombout(("Unexpected data from server while"
6543                                  " waiting for user response"));
6544                         crStopV;
6545                     }
6546                 } while (pktin || inlen > 0);
6547                 s->dlgret = ssh->user_response;
6548             }
6549             ssh_set_frozen(ssh, 0);
6550             if (s->dlgret == 0) {
6551                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6552                                0, TRUE);
6553                 crStopV;
6554             }
6555         }
6556
6557         if (s->ignorepkt) /* first_kex_packet_follows */
6558             crWaitUntilV(pktin);                /* Ignore packet */
6559     }
6560
6561     if (ssh->kex->main_type == KEXTYPE_DH) {
6562         /*
6563          * Work out the number of bits of key we will need from the
6564          * key exchange. We start with the maximum key length of
6565          * either cipher...
6566          */
6567         {
6568             int csbits, scbits;
6569
6570             csbits = s->cscipher_tobe->keylen;
6571             scbits = s->sccipher_tobe->keylen;
6572             s->nbits = (csbits > scbits ? csbits : scbits);
6573         }
6574         /* The keys only have hlen-bit entropy, since they're based on
6575          * a hash. So cap the key size at hlen bits. */
6576         if (s->nbits > ssh->kex->hash->hlen * 8)
6577             s->nbits = ssh->kex->hash->hlen * 8;
6578
6579         /*
6580          * If we're doing Diffie-Hellman group exchange, start by
6581          * requesting a group.
6582          */
6583         if (!ssh->kex->pdata) {
6584             logevent("Doing Diffie-Hellman group exchange");
6585             ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6586             /*
6587              * Work out how big a DH group we will need to allow that
6588              * much data.
6589              */
6590             s->pbits = 512 << ((s->nbits - 1) / 64);
6591             s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6592             ssh2_pkt_adduint32(s->pktout, s->pbits);
6593             ssh2_pkt_send_noqueue(ssh, s->pktout);
6594
6595             crWaitUntilV(pktin);
6596             if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6597                 bombout(("expected key exchange group packet from server"));
6598                 crStopV;
6599             }
6600             s->p = ssh2_pkt_getmp(pktin);
6601             s->g = ssh2_pkt_getmp(pktin);
6602             if (!s->p || !s->g) {
6603                 bombout(("unable to read mp-ints from incoming group packet"));
6604                 crStopV;
6605             }
6606             ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6607             s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6608             s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6609         } else {
6610             ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6611             ssh->kex_ctx = dh_setup_group(ssh->kex);
6612             s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6613             s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6614             logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6615                       ssh->kex->groupname);
6616         }
6617
6618         logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6619                   ssh->kex->hash->text_name);
6620         /*
6621          * Now generate and send e for Diffie-Hellman.
6622          */
6623         set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6624         s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6625         s->pktout = ssh2_pkt_init(s->kex_init_value);
6626         ssh2_pkt_addmp(s->pktout, s->e);
6627         ssh2_pkt_send_noqueue(ssh, s->pktout);
6628
6629         set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6630         crWaitUntilV(pktin);
6631         if (pktin->type != s->kex_reply_value) {
6632             bombout(("expected key exchange reply packet from server"));
6633             crStopV;
6634         }
6635         set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6636         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6637         s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6638         s->f = ssh2_pkt_getmp(pktin);
6639         if (!s->f) {
6640             bombout(("unable to parse key exchange reply packet"));
6641             crStopV;
6642         }
6643         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6644
6645         s->K = dh_find_K(ssh->kex_ctx, s->f);
6646
6647         /* We assume everything from now on will be quick, and it might
6648          * involve user interaction. */
6649         set_busy_status(ssh->frontend, BUSY_NOT);
6650
6651         hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6652         if (!ssh->kex->pdata) {
6653             hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6654             hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6655             hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6656         }
6657         hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6658         hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6659
6660         dh_cleanup(ssh->kex_ctx);
6661         freebn(s->f);
6662         if (!ssh->kex->pdata) {
6663             freebn(s->g);
6664             freebn(s->p);
6665         }
6666     } else {
6667         logeventf(ssh, "Doing RSA key exchange with hash %s",
6668                   ssh->kex->hash->text_name);
6669         ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6670         /*
6671          * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6672          * from the server.
6673          */
6674         crWaitUntilV(pktin);
6675         if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6676             bombout(("expected RSA public key packet from server"));
6677             crStopV;
6678         }
6679
6680         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6681         hash_string(ssh->kex->hash, ssh->exhash,
6682                     s->hostkeydata, s->hostkeylen);
6683         s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6684
6685         {
6686             char *keydata;
6687             ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6688             s->rsakeydata = snewn(s->rsakeylen, char);
6689             memcpy(s->rsakeydata, keydata, s->rsakeylen);
6690         }
6691
6692         s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6693         if (!s->rsakey) {
6694             sfree(s->rsakeydata);
6695             bombout(("unable to parse RSA public key from server"));
6696             crStopV;
6697         }
6698
6699         hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6700
6701         /*
6702          * Next, set up a shared secret K, of precisely KLEN -
6703          * 2*HLEN - 49 bits, where KLEN is the bit length of the
6704          * RSA key modulus and HLEN is the bit length of the hash
6705          * we're using.
6706          */
6707         {
6708             int klen = ssh_rsakex_klen(s->rsakey);
6709             int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6710             int i, byte = 0;
6711             unsigned char *kstr1, *kstr2, *outstr;
6712             int kstr1len, kstr2len, outstrlen;
6713
6714             s->K = bn_power_2(nbits - 1);
6715
6716             for (i = 0; i < nbits; i++) {
6717                 if ((i & 7) == 0) {
6718                     byte = random_byte();
6719                 }
6720                 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6721             }
6722
6723             /*
6724              * Encode this as an mpint.
6725              */
6726             kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6727             kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6728             PUT_32BIT(kstr2, kstr1len);
6729             memcpy(kstr2 + 4, kstr1, kstr1len);
6730
6731             /*
6732              * Encrypt it with the given RSA key.
6733              */
6734             outstrlen = (klen + 7) / 8;
6735             outstr = snewn(outstrlen, unsigned char);
6736             ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6737                                outstr, outstrlen, s->rsakey);
6738
6739             /*
6740              * And send it off in a return packet.
6741              */
6742             s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6743             ssh2_pkt_addstring_start(s->pktout);
6744             ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6745             ssh2_pkt_send_noqueue(ssh, s->pktout);
6746
6747             hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6748
6749             sfree(kstr2);
6750             sfree(kstr1);
6751             sfree(outstr);
6752         }
6753
6754         ssh_rsakex_freekey(s->rsakey);
6755
6756         crWaitUntilV(pktin);
6757         if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6758             sfree(s->rsakeydata);
6759             bombout(("expected signature packet from server"));
6760             crStopV;
6761         }
6762
6763         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6764
6765         sfree(s->rsakeydata);
6766     }
6767
6768     hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6769     assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6770     ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6771
6772     ssh->kex_ctx = NULL;
6773
6774 #if 0
6775     debug(("Exchange hash is:\n"));
6776     dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6777 #endif
6778
6779     if (!s->hkey ||
6780         !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6781                                  (char *)s->exchange_hash,
6782                                  ssh->kex->hash->hlen)) {
6783         bombout(("Server's host key did not match the signature supplied"));
6784         crStopV;
6785     }
6786
6787     s->keystr = ssh->hostkey->fmtkey(s->hkey);
6788     if (!s->got_session_id) {
6789         /*
6790          * Authenticate remote host: verify host key. (We've already
6791          * checked the signature of the exchange hash.)
6792          */
6793         s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6794         logevent("Host key fingerprint is:");
6795         logevent(s->fingerprint);
6796         /* First check against manually configured host keys. */
6797         s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
6798                                                ssh->hostkey, s->hkey);
6799         if (s->dlgret == 0) {          /* did not match */
6800             bombout(("Host key did not appear in manually configured list"));
6801             crStopV;
6802         } else if (s->dlgret < 0) { /* none configured; use standard handling */
6803             ssh_set_frozen(ssh, 1);
6804             s->dlgret = verify_ssh_host_key(ssh->frontend,
6805                                             ssh->savedhost, ssh->savedport,
6806                                             ssh->hostkey->keytype, s->keystr,
6807                                             s->fingerprint,
6808                                             ssh_dialog_callback, ssh);
6809             if (s->dlgret < 0) {
6810                 do {
6811                     crReturnV;
6812                     if (pktin) {
6813                         bombout(("Unexpected data from server while waiting"
6814                                  " for user host key response"));
6815                         crStopV;
6816                     }
6817                 } while (pktin || inlen > 0);
6818                 s->dlgret = ssh->user_response;
6819             }
6820             ssh_set_frozen(ssh, 0);
6821             if (s->dlgret == 0) {
6822                 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
6823                                0, TRUE);
6824                 crStopV;
6825             }
6826         }
6827         sfree(s->fingerprint);
6828         /*
6829          * Save this host key, to check against the one presented in
6830          * subsequent rekeys.
6831          */
6832         ssh->hostkey_str = s->keystr;
6833     } else {
6834         /*
6835          * In a rekey, we never present an interactive host key
6836          * verification request to the user. Instead, we simply
6837          * enforce that the key we're seeing this time is identical to
6838          * the one we saw before.
6839          */
6840         if (strcmp(ssh->hostkey_str, s->keystr)) {
6841             bombout(("Host key was different in repeat key exchange"));
6842             crStopV;
6843         }
6844         sfree(s->keystr);
6845     }
6846     ssh->hostkey->freekey(s->hkey);
6847
6848     /*
6849      * The exchange hash from the very first key exchange is also
6850      * the session id, used in session key construction and
6851      * authentication.
6852      */
6853     if (!s->got_session_id) {
6854         assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6855         memcpy(ssh->v2_session_id, s->exchange_hash,
6856                sizeof(s->exchange_hash));
6857         ssh->v2_session_id_len = ssh->kex->hash->hlen;
6858         assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6859         s->got_session_id = TRUE;
6860     }
6861
6862     /*
6863      * Send SSH2_MSG_NEWKEYS.
6864      */
6865     s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6866     ssh2_pkt_send_noqueue(ssh, s->pktout);
6867     ssh->outgoing_data_size = 0;       /* start counting from here */
6868
6869     /*
6870      * We've sent client NEWKEYS, so create and initialise
6871      * client-to-server session keys.
6872      */
6873     if (ssh->cs_cipher_ctx)
6874         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6875     ssh->cscipher = s->cscipher_tobe;
6876     ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6877
6878     if (ssh->cs_mac_ctx)
6879         ssh->csmac->free_context(ssh->cs_mac_ctx);
6880     ssh->csmac = s->csmac_tobe;
6881     ssh->cs_mac_ctx = ssh->csmac->make_context();
6882
6883     if (ssh->cs_comp_ctx)
6884         ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6885     ssh->cscomp = s->cscomp_tobe;
6886     ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6887
6888     /*
6889      * Set IVs on client-to-server keys. Here we use the exchange
6890      * hash from the _first_ key exchange.
6891      */
6892     {
6893         unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6894         assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6895         ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6896         assert((ssh->cscipher->keylen+7) / 8 <=
6897                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6898         ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6899         ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6900         assert(ssh->cscipher->blksize <=
6901                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6902         ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6903         ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6904         assert(ssh->csmac->len <=
6905                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6906         ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6907         smemclr(keyspace, sizeof(keyspace));
6908     }
6909
6910     logeventf(ssh, "Initialised %.200s client->server encryption",
6911               ssh->cscipher->text_name);
6912     logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6913               ssh->csmac->text_name);
6914     if (ssh->cscomp->text_name)
6915         logeventf(ssh, "Initialised %s compression",
6916                   ssh->cscomp->text_name);
6917
6918     /*
6919      * Now our end of the key exchange is complete, we can send all
6920      * our queued higher-layer packets.
6921      */
6922     ssh->queueing = FALSE;
6923     ssh2_pkt_queuesend(ssh);
6924
6925     /*
6926      * Expect SSH2_MSG_NEWKEYS from server.
6927      */
6928     crWaitUntilV(pktin);
6929     if (pktin->type != SSH2_MSG_NEWKEYS) {
6930         bombout(("expected new-keys packet from server"));
6931         crStopV;
6932     }
6933     ssh->incoming_data_size = 0;       /* start counting from here */
6934
6935     /*
6936      * We've seen server NEWKEYS, so create and initialise
6937      * server-to-client session keys.
6938      */
6939     if (ssh->sc_cipher_ctx)
6940         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6941     ssh->sccipher = s->sccipher_tobe;
6942     ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6943
6944     if (ssh->sc_mac_ctx)
6945         ssh->scmac->free_context(ssh->sc_mac_ctx);
6946     ssh->scmac = s->scmac_tobe;
6947     ssh->sc_mac_ctx = ssh->scmac->make_context();
6948
6949     if (ssh->sc_comp_ctx)
6950         ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6951     ssh->sccomp = s->sccomp_tobe;
6952     ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6953
6954     /*
6955      * Set IVs on server-to-client keys. Here we use the exchange
6956      * hash from the _first_ key exchange.
6957      */
6958     {
6959         unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6960         assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6961         ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6962         assert((ssh->sccipher->keylen+7) / 8 <=
6963                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6964         ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6965         ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6966         assert(ssh->sccipher->blksize <=
6967                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6968         ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6969         ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6970         assert(ssh->scmac->len <=
6971                ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6972         ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6973         smemclr(keyspace, sizeof(keyspace));
6974     }
6975     logeventf(ssh, "Initialised %.200s server->client encryption",
6976               ssh->sccipher->text_name);
6977     logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6978               ssh->scmac->text_name);
6979     if (ssh->sccomp->text_name)
6980         logeventf(ssh, "Initialised %s decompression",
6981                   ssh->sccomp->text_name);
6982
6983     /*
6984      * Free shared secret.
6985      */
6986     freebn(s->K);
6987
6988     /*
6989      * Key exchange is over. Loop straight back round if we have a
6990      * deferred rekey reason.
6991      */
6992     if (ssh->deferred_rekey_reason) {
6993         logevent(ssh->deferred_rekey_reason);
6994         pktin = NULL;
6995         ssh->deferred_rekey_reason = NULL;
6996         goto begin_key_exchange;
6997     }
6998
6999     /*
7000      * Otherwise, schedule a timer for our next rekey.
7001      */
7002     ssh->kex_in_progress = FALSE;
7003     ssh->last_rekey = GETTICKCOUNT();
7004     if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7005         ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7006                                          ssh2_timer, ssh);
7007
7008     /*
7009      * Now we're encrypting. Begin returning 1 to the protocol main
7010      * function so that other things can run on top of the
7011      * transport. If we ever see a KEXINIT, we must go back to the
7012      * start.
7013      * 
7014      * We _also_ go back to the start if we see pktin==NULL and
7015      * inlen negative, because this is a special signal meaning
7016      * `initiate client-driven rekey', and `in' contains a message
7017      * giving the reason for the rekey.
7018      *
7019      * inlen==-1 means always initiate a rekey;
7020      * inlen==-2 means that userauth has completed successfully and
7021      *   we should consider rekeying (for delayed compression).
7022      */
7023     while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7024              (!pktin && inlen < 0))) {
7025         wait_for_rekey:
7026         if (!ssh->protocol_initial_phase_done) {
7027             ssh->protocol_initial_phase_done = TRUE;
7028             /*
7029              * Allow authconn to initialise itself.
7030              */
7031             do_ssh2_authconn(ssh, NULL, 0, NULL);
7032         }
7033         crReturnV;
7034     }
7035     if (pktin) {
7036         logevent("Server initiated key re-exchange");
7037     } else {
7038         if (inlen == -2) {
7039             /* 
7040              * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7041              * delayed compression, if it's available.
7042              *
7043              * draft-miller-secsh-compression-delayed-00 says that you
7044              * negotiate delayed compression in the first key exchange, and
7045              * both sides start compressing when the server has sent
7046              * USERAUTH_SUCCESS. This has a race condition -- the server
7047              * can't know when the client has seen it, and thus which incoming
7048              * packets it should treat as compressed.
7049              *
7050              * Instead, we do the initial key exchange without offering the
7051              * delayed methods, but note if the server offers them; when we
7052              * get here, if a delayed method was available that was higher
7053              * on our list than what we got, we initiate a rekey in which we
7054              * _do_ list the delayed methods (and hopefully get it as a
7055              * result). Subsequent rekeys will do the same.
7056              */
7057             assert(!s->userauth_succeeded); /* should only happen once */
7058             s->userauth_succeeded = TRUE;
7059             if (!s->pending_compression)
7060                 /* Can't see any point rekeying. */
7061                 goto wait_for_rekey;       /* this is utterly horrid */
7062             /* else fall through to rekey... */
7063             s->pending_compression = FALSE;
7064         }
7065         /*
7066          * Now we've decided to rekey.
7067          *
7068          * Special case: if the server bug is set that doesn't
7069          * allow rekeying, we give a different log message and
7070          * continue waiting. (If such a server _initiates_ a rekey,
7071          * we process it anyway!)
7072          */
7073         if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7074             logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7075                       (char *)in);
7076             /* Reset the counters, so that at least this message doesn't
7077              * hit the event log _too_ often. */
7078             ssh->outgoing_data_size = 0;
7079             ssh->incoming_data_size = 0;
7080             if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7081                 ssh->next_rekey =
7082                     schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7083                                    ssh2_timer, ssh);
7084             }
7085             goto wait_for_rekey;       /* this is still utterly horrid */
7086         } else {
7087             logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7088         }
7089     }
7090     goto begin_key_exchange;
7091
7092     crFinishV;
7093 }
7094
7095 /*
7096  * Add data to an SSH-2 channel output buffer.
7097  */
7098 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7099                                   int len)
7100 {
7101     bufchain_add(&c->v.v2.outbuffer, buf, len);
7102 }
7103
7104 /*
7105  * Attempt to send data on an SSH-2 channel.
7106  */
7107 static int ssh2_try_send(struct ssh_channel *c)
7108 {
7109     Ssh ssh = c->ssh;
7110     struct Packet *pktout;
7111     int ret;
7112
7113     while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7114         int len;
7115         void *data;
7116         bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7117         if ((unsigned)len > c->v.v2.remwindow)
7118             len = c->v.v2.remwindow;
7119         if ((unsigned)len > c->v.v2.remmaxpkt)
7120             len = c->v.v2.remmaxpkt;
7121         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7122         ssh2_pkt_adduint32(pktout, c->remoteid);
7123         ssh2_pkt_addstring_start(pktout);
7124         ssh2_pkt_addstring_data(pktout, data, len);
7125         ssh2_pkt_send(ssh, pktout);
7126         bufchain_consume(&c->v.v2.outbuffer, len);
7127         c->v.v2.remwindow -= len;
7128     }
7129
7130     /*
7131      * After having sent as much data as we can, return the amount
7132      * still buffered.
7133      */
7134     ret = bufchain_size(&c->v.v2.outbuffer);
7135
7136     /*
7137      * And if there's no data pending but we need to send an EOF, send
7138      * it.
7139      */
7140     if (!ret && c->pending_eof)
7141         ssh_channel_try_eof(c);
7142
7143     return ret;
7144 }
7145
7146 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7147 {
7148     int bufsize;
7149     if (c->closes & CLOSES_SENT_EOF)
7150         return;                   /* don't send on channels we've EOFed */
7151     bufsize = ssh2_try_send(c);
7152     if (bufsize == 0) {
7153         switch (c->type) {
7154           case CHAN_MAINSESSION:
7155             /* stdin need not receive an unthrottle
7156              * notification since it will be polled */
7157             break;
7158           case CHAN_X11:
7159             x11_unthrottle(c->u.x11.xconn);
7160             break;
7161           case CHAN_AGENT:
7162             /* agent sockets are request/response and need no
7163              * buffer management */
7164             break;
7165           case CHAN_SOCKDATA:
7166             pfd_unthrottle(c->u.pfd.pf);
7167             break;
7168         }
7169     }
7170 }
7171
7172 static int ssh_is_simple(Ssh ssh)
7173 {
7174     /*
7175      * We use the 'simple' variant of the SSH protocol if we're asked
7176      * to, except not if we're also doing connection-sharing (either
7177      * tunnelling our packets over an upstream or expecting to be
7178      * tunnelled over ourselves), since then the assumption that we
7179      * have only one channel to worry about is not true after all.
7180      */
7181     return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7182             !ssh->bare_connection && !ssh->connshare);
7183 }
7184
7185 /*
7186  * Set up most of a new ssh_channel for SSH-2.
7187  */
7188 static void ssh2_channel_init(struct ssh_channel *c)
7189 {
7190     Ssh ssh = c->ssh;
7191     c->localid = alloc_channel_id(ssh);
7192     c->closes = 0;
7193     c->pending_eof = FALSE;
7194     c->throttling_conn = FALSE;
7195     c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7196         ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7197     c->v.v2.chanreq_head = NULL;
7198     c->v.v2.throttle_state = UNTHROTTLED;
7199     bufchain_init(&c->v.v2.outbuffer);
7200 }
7201
7202 /*
7203  * Construct the common parts of a CHANNEL_OPEN.
7204  */
7205 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7206 {
7207     struct Packet *pktout;
7208
7209     pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7210     ssh2_pkt_addstring(pktout, type);
7211     ssh2_pkt_adduint32(pktout, c->localid);
7212     ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7213     ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
7214     return pktout;
7215 }
7216
7217 /*
7218  * CHANNEL_FAILURE doesn't come with any indication of what message
7219  * caused it, so we have to keep track of the outstanding
7220  * CHANNEL_REQUESTs ourselves.
7221  */
7222 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7223                                        cchandler_fn_t handler, void *ctx)
7224 {
7225     struct outstanding_channel_request *ocr =
7226         snew(struct outstanding_channel_request);
7227
7228     assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7229     ocr->handler = handler;
7230     ocr->ctx = ctx;
7231     ocr->next = NULL;
7232     if (!c->v.v2.chanreq_head)
7233         c->v.v2.chanreq_head = ocr;
7234     else
7235         c->v.v2.chanreq_tail->next = ocr;
7236     c->v.v2.chanreq_tail = ocr;
7237 }
7238
7239 /*
7240  * Construct the common parts of a CHANNEL_REQUEST.  If handler is not
7241  * NULL then a reply will be requested and the handler will be called
7242  * when it arrives.  The returned packet is ready to have any
7243  * request-specific data added and be sent.  Note that if a handler is
7244  * provided, it's essential that the request actually be sent.
7245  *
7246  * The handler will usually be passed the response packet in pktin. If
7247  * pktin is NULL, this means that no reply will ever be forthcoming
7248  * (e.g. because the entire connection is being destroyed, or because
7249  * the server initiated channel closure before we saw the response)
7250  * and the handler should free any storage it's holding.
7251  */
7252 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7253                                         cchandler_fn_t handler, void *ctx)
7254 {
7255     struct Packet *pktout;
7256
7257     assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7258     pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7259     ssh2_pkt_adduint32(pktout, c->remoteid);
7260     ssh2_pkt_addstring(pktout, type);
7261     ssh2_pkt_addbool(pktout, handler != NULL);
7262     if (handler != NULL)
7263         ssh2_queue_chanreq_handler(c, handler, ctx);
7264     return pktout;
7265 }
7266
7267 /*
7268  * Potentially enlarge the window on an SSH-2 channel.
7269  */
7270 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7271                                         void *);
7272 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7273 {
7274     Ssh ssh = c->ssh;
7275
7276     /*
7277      * Never send WINDOW_ADJUST for a channel that the remote side has
7278      * already sent EOF on; there's no point, since it won't be
7279      * sending any more data anyway. Ditto if _we've_ already sent
7280      * CLOSE.
7281      */
7282     if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7283         return;
7284
7285     /*
7286      * Also, never widen the window for an X11 channel when we're
7287      * still waiting to see its initial auth and may yet hand it off
7288      * to a downstream.
7289      */
7290     if (c->type == CHAN_X11 && c->u.x11.initial)
7291         return;
7292
7293     /*
7294      * If the remote end has a habit of ignoring maxpkt, limit the
7295      * window so that it has no choice (assuming it doesn't ignore the
7296      * window as well).
7297      */
7298     if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7299         newwin = OUR_V2_MAXPKT;
7300
7301     /*
7302      * Only send a WINDOW_ADJUST if there's significantly more window
7303      * available than the other end thinks there is.  This saves us
7304      * sending a WINDOW_ADJUST for every character in a shell session.
7305      *
7306      * "Significant" is arbitrarily defined as half the window size.
7307      */
7308     if (newwin / 2 >= c->v.v2.locwindow) {
7309         struct Packet *pktout;
7310         unsigned *up;
7311
7312         /*
7313          * In order to keep track of how much window the client
7314          * actually has available, we'd like it to acknowledge each
7315          * WINDOW_ADJUST.  We can't do that directly, so we accompany
7316          * it with a CHANNEL_REQUEST that has to be acknowledged.
7317          *
7318          * This is only necessary if we're opening the window wide.
7319          * If we're not, then throughput is being constrained by
7320          * something other than the maximum window size anyway.
7321          */
7322         if (newwin == c->v.v2.locmaxwin &&
7323             !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7324             up = snew(unsigned);
7325             *up = newwin - c->v.v2.locwindow;
7326             pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7327                                        ssh2_handle_winadj_response, up);
7328             ssh2_pkt_send(ssh, pktout);
7329
7330             if (c->v.v2.throttle_state != UNTHROTTLED)
7331                 c->v.v2.throttle_state = UNTHROTTLING;
7332         } else {
7333             /* Pretend the WINDOW_ADJUST was acked immediately. */
7334             c->v.v2.remlocwin = newwin;
7335             c->v.v2.throttle_state = THROTTLED;
7336         }
7337         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7338         ssh2_pkt_adduint32(pktout, c->remoteid);
7339         ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7340         ssh2_pkt_send(ssh, pktout);
7341         c->v.v2.locwindow = newwin;
7342     }
7343 }
7344
7345 /*
7346  * Find the channel associated with a message.  If there's no channel,
7347  * or it's not properly open, make a noise about it and return NULL.
7348  */
7349 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7350 {
7351     unsigned localid = ssh_pkt_getuint32(pktin);
7352     struct ssh_channel *c;
7353
7354     c = find234(ssh->channels, &localid, ssh_channelfind);
7355     if (!c ||
7356         (c->type != CHAN_SHARING && c->halfopen &&
7357          pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7358          pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7359         char *buf = dupprintf("Received %s for %s channel %u",
7360                               ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7361                                             pktin->type),
7362                               c ? "half-open" : "nonexistent", localid);
7363         ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7364         sfree(buf);
7365         return NULL;
7366     }
7367     return c;
7368 }
7369
7370 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7371                                         struct Packet *pktin, void *ctx)
7372 {
7373     unsigned *sizep = ctx;
7374
7375     /*
7376      * Winadj responses should always be failures. However, at least
7377      * one server ("boks_sshd") is known to return SUCCESS for channel
7378      * requests it's never heard of, such as "winadj@putty". Raised
7379      * with foxt.com as bug 090916-090424, but for the sake of a quiet
7380      * life, we don't worry about what kind of response we got.
7381      */
7382
7383     c->v.v2.remlocwin += *sizep;
7384     sfree(sizep);
7385     /*
7386      * winadj messages are only sent when the window is fully open, so
7387      * if we get an ack of one, we know any pending unthrottle is
7388      * complete.
7389      */
7390     if (c->v.v2.throttle_state == UNTHROTTLING)
7391         c->v.v2.throttle_state = UNTHROTTLED;
7392 }
7393
7394 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7395 {
7396     struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7397     struct outstanding_channel_request *ocr;
7398
7399     if (!c) return;
7400     if (c->type == CHAN_SHARING) {
7401         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7402                                   pktin->body, pktin->length);
7403         return;
7404     }
7405     ocr = c->v.v2.chanreq_head;
7406     if (!ocr) {
7407         ssh2_msg_unexpected(ssh, pktin);
7408         return;
7409     }
7410     ocr->handler(c, pktin, ocr->ctx);
7411     c->v.v2.chanreq_head = ocr->next;
7412     sfree(ocr);
7413     /*
7414      * We may now initiate channel-closing procedures, if that
7415      * CHANNEL_REQUEST was the last thing outstanding before we send
7416      * CHANNEL_CLOSE.
7417      */
7418     ssh2_channel_check_close(c);
7419 }
7420
7421 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7422 {
7423     struct ssh_channel *c;
7424     c = ssh2_channel_msg(ssh, pktin);
7425     if (!c)
7426         return;
7427     if (c->type == CHAN_SHARING) {
7428         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7429                                   pktin->body, pktin->length);
7430         return;
7431     }
7432     if (!(c->closes & CLOSES_SENT_EOF)) {
7433         c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7434         ssh2_try_send_and_unthrottle(ssh, c);
7435     }
7436 }
7437
7438 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7439 {
7440     char *data;
7441     int length;
7442     struct ssh_channel *c;
7443     c = ssh2_channel_msg(ssh, pktin);
7444     if (!c)
7445         return;
7446     if (c->type == CHAN_SHARING) {
7447         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7448                                   pktin->body, pktin->length);
7449         return;
7450     }
7451     if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7452         ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7453         return;                        /* extended but not stderr */
7454     ssh_pkt_getstring(pktin, &data, &length);
7455     if (data) {
7456         int bufsize = 0;
7457         c->v.v2.locwindow -= length;
7458         c->v.v2.remlocwin -= length;
7459         switch (c->type) {
7460           case CHAN_MAINSESSION:
7461             bufsize =
7462                 from_backend(ssh->frontend, pktin->type ==
7463                              SSH2_MSG_CHANNEL_EXTENDED_DATA,
7464                              data, length);
7465             break;
7466           case CHAN_X11:
7467             bufsize = x11_send(c->u.x11.xconn, data, length);
7468             break;
7469           case CHAN_SOCKDATA:
7470             bufsize = pfd_send(c->u.pfd.pf, data, length);
7471             break;
7472           case CHAN_AGENT:
7473             while (length > 0) {
7474                 if (c->u.a.lensofar < 4) {
7475                     unsigned int l = min(4 - c->u.a.lensofar,
7476                                          (unsigned)length);
7477                     memcpy(c->u.a.msglen + c->u.a.lensofar,
7478                            data, l);
7479                     data += l;
7480                     length -= l;
7481                     c->u.a.lensofar += l;
7482                 }
7483                 if (c->u.a.lensofar == 4) {
7484                     c->u.a.totallen =
7485                         4 + GET_32BIT(c->u.a.msglen);
7486                     c->u.a.message = snewn(c->u.a.totallen,
7487                                            unsigned char);
7488                     memcpy(c->u.a.message, c->u.a.msglen, 4);
7489                 }
7490                 if (c->u.a.lensofar >= 4 && length > 0) {
7491                     unsigned int l =
7492                         min(c->u.a.totallen - c->u.a.lensofar,
7493                             (unsigned)length);
7494                     memcpy(c->u.a.message + c->u.a.lensofar,
7495                            data, l);
7496                     data += l;
7497                     length -= l;
7498                     c->u.a.lensofar += l;
7499                 }
7500                 if (c->u.a.lensofar == c->u.a.totallen) {
7501                     void *reply;
7502                     int replylen;
7503                     c->u.a.outstanding_requests++;
7504                     if (agent_query(c->u.a.message,
7505                                     c->u.a.totallen,
7506                                     &reply, &replylen,
7507                                     ssh_agentf_callback, c))
7508                         ssh_agentf_callback(c, reply, replylen);
7509                     sfree(c->u.a.message);
7510                     c->u.a.message = NULL;
7511                     c->u.a.lensofar = 0;
7512                 }
7513             }
7514             bufsize = 0;
7515             break;
7516         }
7517         /*
7518          * If it looks like the remote end hit the end of its window,
7519          * and we didn't want it to do that, think about using a
7520          * larger window.
7521          */
7522         if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7523             c->v.v2.locmaxwin < 0x40000000)
7524             c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7525         /*
7526          * If we are not buffering too much data,
7527          * enlarge the window again at the remote side.
7528          * If we are buffering too much, we may still
7529          * need to adjust the window if the server's
7530          * sent excess data.
7531          */
7532         ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7533                         c->v.v2.locmaxwin - bufsize : 0);
7534         /*
7535          * If we're either buffering way too much data, or if we're
7536          * buffering anything at all and we're in "simple" mode,
7537          * throttle the whole channel.
7538          */
7539         if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7540             && !c->throttling_conn) {
7541             c->throttling_conn = 1;
7542             ssh_throttle_conn(ssh, +1);
7543         }
7544     }
7545 }
7546
7547 static void ssh_check_termination(Ssh ssh)
7548 {
7549     if (ssh->version == 2 &&
7550         !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7551         count234(ssh->channels) == 0 &&
7552         !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7553         /*
7554          * We used to send SSH_MSG_DISCONNECT here, because I'd
7555          * believed that _every_ conforming SSH-2 connection had to
7556          * end with a disconnect being sent by at least one side;
7557          * apparently I was wrong and it's perfectly OK to
7558          * unceremoniously slam the connection shut when you're done,
7559          * and indeed OpenSSH feels this is more polite than sending a
7560          * DISCONNECT. So now we don't.
7561          */
7562         ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7563     }
7564 }
7565
7566 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7567 {
7568     logeventf(ssh, "Connection sharing downstream #%u connected", id);
7569 }
7570
7571 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7572 {
7573     logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7574     ssh_check_termination(ssh);
7575 }
7576
7577 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7578 {
7579     va_list ap;
7580     char *buf;
7581
7582     va_start(ap, logfmt);
7583     buf = dupvprintf(logfmt, ap);
7584     va_end(ap);
7585     if (id)
7586         logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7587     else
7588         logeventf(ssh, "Connection sharing: %s", buf);
7589     sfree(buf);
7590 }
7591
7592 static void ssh_channel_destroy(struct ssh_channel *c)
7593 {
7594     Ssh ssh = c->ssh;
7595
7596     switch (c->type) {
7597       case CHAN_MAINSESSION:
7598         ssh->mainchan = NULL;
7599         update_specials_menu(ssh->frontend);
7600         break;
7601       case CHAN_X11:
7602         if (c->u.x11.xconn != NULL)
7603             x11_close(c->u.x11.xconn);
7604         logevent("Forwarded X11 connection terminated");
7605         break;
7606       case CHAN_AGENT:
7607         sfree(c->u.a.message);
7608         break;
7609       case CHAN_SOCKDATA:
7610         if (c->u.pfd.pf != NULL)
7611             pfd_close(c->u.pfd.pf);
7612         logevent("Forwarded port closed");
7613         break;
7614     }
7615
7616     del234(ssh->channels, c);
7617     if (ssh->version == 2) {
7618         bufchain_clear(&c->v.v2.outbuffer);
7619         assert(c->v.v2.chanreq_head == NULL);
7620     }
7621     sfree(c);
7622
7623     /*
7624      * If that was the last channel left open, we might need to
7625      * terminate.
7626      */
7627     ssh_check_termination(ssh);
7628 }
7629
7630 static void ssh2_channel_check_close(struct ssh_channel *c)
7631 {
7632     Ssh ssh = c->ssh;
7633     struct Packet *pktout;
7634
7635     if (c->halfopen) {
7636         /*
7637          * If we've sent out our own CHANNEL_OPEN but not yet seen
7638          * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7639          * it's too early to be sending close messages of any kind.
7640          */
7641         return;
7642     }
7643
7644     if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7645          c->type == CHAN_ZOMBIE) &&
7646         !c->v.v2.chanreq_head &&
7647         !(c->closes & CLOSES_SENT_CLOSE)) {
7648         /*
7649          * We have both sent and received EOF (or the channel is a
7650          * zombie), and we have no outstanding channel requests, which
7651          * means the channel is in final wind-up. But we haven't sent
7652          * CLOSE, so let's do so now.
7653          */
7654         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7655         ssh2_pkt_adduint32(pktout, c->remoteid);
7656         ssh2_pkt_send(ssh, pktout);
7657         c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7658     }
7659
7660     if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7661         assert(c->v.v2.chanreq_head == NULL);
7662         /*
7663          * We have both sent and received CLOSE, which means we're
7664          * completely done with the channel.
7665          */
7666         ssh_channel_destroy(c);
7667     }
7668 }
7669
7670 static void ssh2_channel_got_eof(struct ssh_channel *c)
7671 {
7672     if (c->closes & CLOSES_RCVD_EOF)
7673         return;                        /* already seen EOF */
7674     c->closes |= CLOSES_RCVD_EOF;
7675
7676     if (c->type == CHAN_X11) {
7677         x11_send_eof(c->u.x11.xconn);
7678     } else if (c->type == CHAN_AGENT) {
7679         if (c->u.a.outstanding_requests == 0) {
7680             /* Manufacture an outgoing EOF in response to the incoming one. */
7681             sshfwd_write_eof(c);
7682         }
7683     } else if (c->type == CHAN_SOCKDATA) {
7684         pfd_send_eof(c->u.pfd.pf);
7685     } else if (c->type == CHAN_MAINSESSION) {
7686         Ssh ssh = c->ssh;
7687
7688         if (!ssh->sent_console_eof &&
7689             (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7690             /*
7691              * Either from_backend_eof told us that the front end
7692              * wants us to close the outgoing side of the connection
7693              * as soon as we see EOF from the far end, or else we've
7694              * unilaterally decided to do that because we've allocated
7695              * a remote pty and hence EOF isn't a particularly
7696              * meaningful concept.
7697              */
7698             sshfwd_write_eof(c);
7699         }
7700         ssh->sent_console_eof = TRUE;
7701     }
7702
7703     ssh2_channel_check_close(c);
7704 }
7705
7706 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7707 {
7708     struct ssh_channel *c;
7709
7710     c = ssh2_channel_msg(ssh, pktin);
7711     if (!c)
7712         return;
7713     if (c->type == CHAN_SHARING) {
7714         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7715                                   pktin->body, pktin->length);
7716         return;
7717     }
7718     ssh2_channel_got_eof(c);
7719 }
7720
7721 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7722 {
7723     struct ssh_channel *c;
7724
7725     c = ssh2_channel_msg(ssh, pktin);
7726     if (!c)
7727         return;
7728     if (c->type == CHAN_SHARING) {
7729         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7730                                   pktin->body, pktin->length);
7731         return;
7732     }
7733
7734     /*
7735      * When we receive CLOSE on a channel, we assume it comes with an
7736      * implied EOF if we haven't seen EOF yet.
7737      */
7738     ssh2_channel_got_eof(c);
7739
7740     if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7741         /*
7742          * It also means we stop expecting to see replies to any
7743          * outstanding channel requests, so clean those up too.
7744          * (ssh_chanreq_init will enforce by assertion that we don't
7745          * subsequently put anything back on this list.)
7746          */
7747         while (c->v.v2.chanreq_head) {
7748             struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
7749             ocr->handler(c, NULL, ocr->ctx);
7750             c->v.v2.chanreq_head = ocr->next;
7751             sfree(ocr);
7752         }
7753     }
7754
7755     /*
7756      * And we also send an outgoing EOF, if we haven't already, on the
7757      * assumption that CLOSE is a pretty forceful announcement that
7758      * the remote side is doing away with the entire channel. (If it
7759      * had wanted to send us EOF and continue receiving data from us,
7760      * it would have just sent CHANNEL_EOF.)
7761      */
7762     if (!(c->closes & CLOSES_SENT_EOF)) {
7763         /*
7764          * Make sure we don't read any more from whatever our local
7765          * data source is for this channel.
7766          */
7767         switch (c->type) {
7768           case CHAN_MAINSESSION:
7769             ssh->send_ok = 0;     /* stop trying to read from stdin */
7770             break;
7771           case CHAN_X11:
7772             x11_override_throttle(c->u.x11.xconn, 1);
7773             break;
7774           case CHAN_SOCKDATA:
7775             pfd_override_throttle(c->u.pfd.pf, 1);
7776             break;
7777         }
7778
7779         /*
7780          * Abandon any buffered data we still wanted to send to this
7781          * channel. Receiving a CHANNEL_CLOSE is an indication that
7782          * the server really wants to get on and _destroy_ this
7783          * channel, and it isn't going to send us any further
7784          * WINDOW_ADJUSTs to permit us to send pending stuff.
7785          */
7786         bufchain_clear(&c->v.v2.outbuffer);
7787
7788         /*
7789          * Send outgoing EOF.
7790          */
7791         sshfwd_write_eof(c);
7792     }
7793
7794     /*
7795      * Now process the actual close.
7796      */
7797     if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7798         c->closes |= CLOSES_RCVD_CLOSE;
7799         ssh2_channel_check_close(c);
7800     }
7801 }
7802
7803 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7804 {
7805     struct ssh_channel *c;
7806
7807     c = ssh2_channel_msg(ssh, pktin);
7808     if (!c)
7809         return;
7810     if (c->type == CHAN_SHARING) {
7811         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7812                                   pktin->body, pktin->length);
7813         return;
7814     }
7815     assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7816     c->remoteid = ssh_pkt_getuint32(pktin);
7817     c->halfopen = FALSE;
7818     c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7819     c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7820
7821     if (c->type == CHAN_SOCKDATA_DORMANT) {
7822         c->type = CHAN_SOCKDATA;
7823         if (c->u.pfd.pf)
7824             pfd_confirm(c->u.pfd.pf);
7825     } else if (c->type == CHAN_ZOMBIE) {
7826         /*
7827          * This case can occur if a local socket error occurred
7828          * between us sending out CHANNEL_OPEN and receiving
7829          * OPEN_CONFIRMATION. In this case, all we can do is
7830          * immediately initiate close proceedings now that we know the
7831          * server's id to put in the close message.
7832          */
7833         ssh2_channel_check_close(c);
7834     } else {
7835         /*
7836          * We never expect to receive OPEN_CONFIRMATION for any
7837          * *other* channel type (since only local-to-remote port
7838          * forwardings cause us to send CHANNEL_OPEN after the main
7839          * channel is live - all other auxiliary channel types are
7840          * initiated from the server end). It's safe to enforce this
7841          * by assertion rather than by ssh_disconnect, because the
7842          * real point is that we never constructed a half-open channel
7843          * structure in the first place with any type other than the
7844          * above.
7845          */
7846         assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7847     }
7848
7849     if (c->pending_eof)
7850         ssh_channel_try_eof(c);        /* in case we had a pending EOF */
7851 }
7852
7853 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7854 {
7855     static const char *const reasons[] = {
7856         "<unknown reason code>",
7857             "Administratively prohibited",
7858             "Connect failed",
7859             "Unknown channel type",
7860             "Resource shortage",
7861     };
7862     unsigned reason_code;
7863     char *reason_string;
7864     int reason_length;
7865     struct ssh_channel *c;
7866
7867     c = ssh2_channel_msg(ssh, pktin);
7868     if (!c)
7869         return;
7870     if (c->type == CHAN_SHARING) {
7871         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7872                                   pktin->body, pktin->length);
7873         return;
7874     }
7875     assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7876
7877     if (c->type == CHAN_SOCKDATA_DORMANT) {
7878         reason_code = ssh_pkt_getuint32(pktin);
7879         if (reason_code >= lenof(reasons))
7880             reason_code = 0; /* ensure reasons[reason_code] in range */
7881         ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7882         logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7883                   reasons[reason_code], reason_length, reason_string);
7884
7885         pfd_close(c->u.pfd.pf);
7886     } else if (c->type == CHAN_ZOMBIE) {
7887         /*
7888          * This case can occur if a local socket error occurred
7889          * between us sending out CHANNEL_OPEN and receiving
7890          * OPEN_FAILURE. In this case, we need do nothing except allow
7891          * the code below to throw the half-open channel away.
7892          */
7893     } else {
7894         /*
7895          * We never expect to receive OPEN_FAILURE for any *other*
7896          * channel type (since only local-to-remote port forwardings
7897          * cause us to send CHANNEL_OPEN after the main channel is
7898          * live - all other auxiliary channel types are initiated from
7899          * the server end). It's safe to enforce this by assertion
7900          * rather than by ssh_disconnect, because the real point is
7901          * that we never constructed a half-open channel structure in
7902          * the first place with any type other than the above.
7903          */
7904         assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7905     }
7906
7907     del234(ssh->channels, c);
7908     sfree(c);
7909 }
7910
7911 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7912 {
7913     char *type;
7914     int typelen, want_reply;
7915     int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7916     struct ssh_channel *c;
7917     struct Packet *pktout;
7918
7919     c = ssh2_channel_msg(ssh, pktin);
7920     if (!c)
7921         return;
7922     if (c->type == CHAN_SHARING) {
7923         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7924                                   pktin->body, pktin->length);
7925         return;
7926     }
7927     ssh_pkt_getstring(pktin, &type, &typelen);
7928     want_reply = ssh2_pkt_getbool(pktin);
7929
7930     if (c->closes & CLOSES_SENT_CLOSE) {
7931         /*
7932          * We don't reply to channel requests after we've sent
7933          * CHANNEL_CLOSE for the channel, because our reply might
7934          * cross in the network with the other side's CHANNEL_CLOSE
7935          * and arrive after they have wound the channel up completely.
7936          */
7937         want_reply = FALSE;
7938     }
7939
7940     /*
7941      * Having got the channel number, we now look at
7942      * the request type string to see if it's something
7943      * we recognise.
7944      */
7945     if (c == ssh->mainchan) {
7946         /*
7947          * We recognise "exit-status" and "exit-signal" on
7948          * the primary channel.
7949          */
7950         if (typelen == 11 &&
7951             !memcmp(type, "exit-status", 11)) {
7952
7953             ssh->exitcode = ssh_pkt_getuint32(pktin);
7954             logeventf(ssh, "Server sent command exit status %d",
7955                       ssh->exitcode);
7956             reply = SSH2_MSG_CHANNEL_SUCCESS;
7957
7958         } else if (typelen == 11 &&
7959                    !memcmp(type, "exit-signal", 11)) {
7960
7961             int is_plausible = TRUE, is_int = FALSE;
7962             char *fmt_sig = "", *fmt_msg = "";
7963             char *msg;
7964             int msglen = 0, core = FALSE;
7965             /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7966              * provide an `int' for the signal, despite its
7967              * having been a `string' in the drafts of RFC 4254 since at
7968              * least 2001. (Fixed in session.c 1.147.) Try to
7969              * infer which we can safely parse it as. */
7970             {
7971                 unsigned char *p = pktin->body +
7972                     pktin->savedpos;
7973                 long len = pktin->length - pktin->savedpos;
7974                 unsigned long num = GET_32BIT(p); /* what is it? */
7975                 /* If it's 0, it hardly matters; assume string */
7976                 if (num == 0) {
7977                     is_int = FALSE;
7978                 } else {
7979                     int maybe_int = FALSE, maybe_str = FALSE;
7980 #define CHECK_HYPOTHESIS(offset, result)                                \
7981                     do                                                  \
7982                     {                                                   \
7983                         int q = toint(offset);                          \
7984                         if (q >= 0 && q+4 <= len) {                     \
7985                             q = toint(q + 4 + GET_32BIT(p+q));          \
7986                             if (q >= 0 && q+4 <= len &&                 \
7987                                 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7988                                 q == len)                               \
7989                                 result = TRUE;                          \
7990                         }                                               \
7991                     } while(0)
7992                     CHECK_HYPOTHESIS(4+1, maybe_int);
7993                     CHECK_HYPOTHESIS(4+num+1, maybe_str);
7994 #undef CHECK_HYPOTHESIS
7995                     if (maybe_int && !maybe_str)
7996                         is_int = TRUE;
7997                     else if (!maybe_int && maybe_str)
7998                         is_int = FALSE;
7999                     else
8000                         /* Crikey. Either or neither. Panic. */
8001                         is_plausible = FALSE;
8002                 }
8003             }
8004             ssh->exitcode = 128;       /* means `unknown signal' */
8005             if (is_plausible) {
8006                 if (is_int) {
8007                     /* Old non-standard OpenSSH. */
8008                     int signum = ssh_pkt_getuint32(pktin);
8009                     fmt_sig = dupprintf(" %d", signum);
8010                     ssh->exitcode = 128 + signum;
8011                 } else {
8012                     /* As per RFC 4254. */
8013                     char *sig;
8014                     int siglen;
8015                     ssh_pkt_getstring(pktin, &sig, &siglen);
8016                     /* Signal name isn't supposed to be blank, but
8017                      * let's cope gracefully if it is. */
8018                     if (siglen) {
8019                         fmt_sig = dupprintf(" \"%.*s\"",
8020                                             siglen, sig);
8021                     }
8022
8023                     /*
8024                      * Really hideous method of translating the
8025                      * signal description back into a locally
8026                      * meaningful number.
8027                      */
8028
8029                     if (0)
8030                         ;
8031 #define TRANSLATE_SIGNAL(s) \
8032     else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8033         ssh->exitcode = 128 + SIG ## s
8034 #ifdef SIGABRT
8035                     TRANSLATE_SIGNAL(ABRT);
8036 #endif
8037 #ifdef SIGALRM
8038                     TRANSLATE_SIGNAL(ALRM);
8039 #endif
8040 #ifdef SIGFPE
8041                     TRANSLATE_SIGNAL(FPE);
8042 #endif
8043 #ifdef SIGHUP
8044                     TRANSLATE_SIGNAL(HUP);
8045 #endif
8046 #ifdef SIGILL
8047                     TRANSLATE_SIGNAL(ILL);
8048 #endif
8049 #ifdef SIGINT
8050                     TRANSLATE_SIGNAL(INT);
8051 #endif
8052 #ifdef SIGKILL
8053                     TRANSLATE_SIGNAL(KILL);
8054 #endif
8055 #ifdef SIGPIPE
8056                     TRANSLATE_SIGNAL(PIPE);
8057 #endif
8058 #ifdef SIGQUIT
8059                     TRANSLATE_SIGNAL(QUIT);
8060 #endif
8061 #ifdef SIGSEGV
8062                     TRANSLATE_SIGNAL(SEGV);
8063 #endif
8064 #ifdef SIGTERM
8065                     TRANSLATE_SIGNAL(TERM);
8066 #endif
8067 #ifdef SIGUSR1
8068                     TRANSLATE_SIGNAL(USR1);
8069 #endif
8070 #ifdef SIGUSR2
8071                     TRANSLATE_SIGNAL(USR2);
8072 #endif
8073 #undef TRANSLATE_SIGNAL
8074                     else
8075                         ssh->exitcode = 128;
8076                 }
8077                 core = ssh2_pkt_getbool(pktin);
8078                 ssh_pkt_getstring(pktin, &msg, &msglen);
8079                 if (msglen) {
8080                     fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8081                 }
8082                 /* ignore lang tag */
8083             } /* else don't attempt to parse */
8084             logeventf(ssh, "Server exited on signal%s%s%s",
8085                       fmt_sig, core ? " (core dumped)" : "",
8086                       fmt_msg);
8087             if (*fmt_sig) sfree(fmt_sig);
8088             if (*fmt_msg) sfree(fmt_msg);
8089             reply = SSH2_MSG_CHANNEL_SUCCESS;
8090
8091         }
8092     } else {
8093         /*
8094          * This is a channel request we don't know
8095          * about, so we now either ignore the request
8096          * or respond with CHANNEL_FAILURE, depending
8097          * on want_reply.
8098          */
8099         reply = SSH2_MSG_CHANNEL_FAILURE;
8100     }
8101     if (want_reply) {
8102         pktout = ssh2_pkt_init(reply);
8103         ssh2_pkt_adduint32(pktout, c->remoteid);
8104         ssh2_pkt_send(ssh, pktout);
8105     }
8106 }
8107
8108 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8109 {
8110     char *type;
8111     int typelen, want_reply;
8112     struct Packet *pktout;
8113
8114     ssh_pkt_getstring(pktin, &type, &typelen);
8115     want_reply = ssh2_pkt_getbool(pktin);
8116
8117     /*
8118      * We currently don't support any global requests
8119      * at all, so we either ignore the request or
8120      * respond with REQUEST_FAILURE, depending on
8121      * want_reply.
8122      */
8123     if (want_reply) {
8124         pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8125         ssh2_pkt_send(ssh, pktout);
8126     }
8127 }
8128
8129 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8130                                                 void *share_cs,
8131                                                 void *share_chan)
8132 {
8133     struct X11FakeAuth *auth;
8134
8135     /*
8136      * Make up a new set of fake X11 auth data, and add it to the tree
8137      * of currently valid ones with an indication of the sharing
8138      * context that it's relevant to.
8139      */
8140     auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8141     auth->share_cs = share_cs;
8142     auth->share_chan = share_chan;
8143
8144     return auth;
8145 }
8146
8147 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8148 {
8149     del234(ssh->x11authtree, auth);
8150     x11_free_fake_auth(auth);
8151 }
8152
8153 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8154 {
8155     char *type;
8156     int typelen;
8157     char *peeraddr;
8158     int peeraddrlen;
8159     int peerport;
8160     char *error = NULL;
8161     struct ssh_channel *c;
8162     unsigned remid, winsize, pktsize;
8163     unsigned our_winsize_override = 0;
8164     struct Packet *pktout;
8165
8166     ssh_pkt_getstring(pktin, &type, &typelen);
8167     c = snew(struct ssh_channel);
8168     c->ssh = ssh;
8169
8170     remid = ssh_pkt_getuint32(pktin);
8171     winsize = ssh_pkt_getuint32(pktin);
8172     pktsize = ssh_pkt_getuint32(pktin);
8173
8174     if (typelen == 3 && !memcmp(type, "x11", 3)) {
8175         char *addrstr;
8176
8177         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8178         addrstr = snewn(peeraddrlen+1, char);
8179         memcpy(addrstr, peeraddr, peeraddrlen);
8180         addrstr[peeraddrlen] = '\0';
8181         peerport = ssh_pkt_getuint32(pktin);
8182
8183         logeventf(ssh, "Received X11 connect request from %s:%d",
8184                   addrstr, peerport);
8185
8186         if (!ssh->X11_fwd_enabled && !ssh->connshare)
8187             error = "X11 forwarding is not enabled";
8188         else {
8189             c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8190                                       addrstr, peerport);
8191             c->type = CHAN_X11;
8192             c->u.x11.initial = TRUE;
8193
8194             /*
8195              * If we are a connection-sharing upstream, then we should
8196              * initially present a very small window, adequate to take
8197              * the X11 initial authorisation packet but not much more.
8198              * Downstream will then present us a larger window (by
8199              * fiat of the connection-sharing protocol) and we can
8200              * guarantee to send a positive-valued WINDOW_ADJUST.
8201              */
8202             if (ssh->connshare)
8203                 our_winsize_override = 128;
8204
8205             logevent("Opened X11 forward channel");
8206         }
8207
8208         sfree(addrstr);
8209     } else if (typelen == 15 &&
8210                !memcmp(type, "forwarded-tcpip", 15)) {
8211         struct ssh_rportfwd pf, *realpf;
8212         char *shost;
8213         int shostlen;
8214         ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8215         pf.shost = dupprintf("%.*s", shostlen, shost);
8216         pf.sport = ssh_pkt_getuint32(pktin);
8217         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8218         peerport = ssh_pkt_getuint32(pktin);
8219         realpf = find234(ssh->rportfwds, &pf, NULL);
8220         logeventf(ssh, "Received remote port %s:%d open request "
8221                   "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8222         sfree(pf.shost);
8223
8224         if (realpf == NULL) {
8225             error = "Remote port is not recognised";
8226         } else {
8227             char *err;
8228
8229             if (realpf->share_ctx) {
8230                 /*
8231                  * This port forwarding is on behalf of a
8232                  * connection-sharing downstream, so abandon our own
8233                  * channel-open procedure and just pass the message on
8234                  * to sshshare.c.
8235                  */
8236                 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8237                                           pktin->body, pktin->length);
8238                 sfree(c);
8239                 return;
8240             }
8241
8242             err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8243                               c, ssh->conf, realpf->pfrec->addressfamily);
8244             logeventf(ssh, "Attempting to forward remote port to "
8245                       "%s:%d", realpf->dhost, realpf->dport);
8246             if (err != NULL) {
8247                 logeventf(ssh, "Port open failed: %s", err);
8248                 sfree(err);
8249                 error = "Port open failed";
8250             } else {
8251                 logevent("Forwarded port opened successfully");
8252                 c->type = CHAN_SOCKDATA;
8253             }
8254         }
8255     } else if (typelen == 22 &&
8256                !memcmp(type, "auth-agent@openssh.com", 22)) {
8257         if (!ssh->agentfwd_enabled)
8258             error = "Agent forwarding is not enabled";
8259         else {
8260             c->type = CHAN_AGENT;       /* identify channel type */
8261             c->u.a.lensofar = 0;
8262             c->u.a.message = NULL;
8263             c->u.a.outstanding_requests = 0;
8264         }
8265     } else {
8266         error = "Unsupported channel type requested";
8267     }
8268
8269     c->remoteid = remid;
8270     c->halfopen = FALSE;
8271     if (error) {
8272         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8273         ssh2_pkt_adduint32(pktout, c->remoteid);
8274         ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8275         ssh2_pkt_addstring(pktout, error);
8276         ssh2_pkt_addstring(pktout, "en");       /* language tag */
8277         ssh2_pkt_send(ssh, pktout);
8278         logeventf(ssh, "Rejected channel open: %s", error);
8279         sfree(c);
8280     } else {
8281         ssh2_channel_init(c);
8282         c->v.v2.remwindow = winsize;
8283         c->v.v2.remmaxpkt = pktsize;
8284         if (our_winsize_override) {
8285             c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8286                 our_winsize_override;
8287         }
8288         add234(ssh->channels, c);
8289         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8290         ssh2_pkt_adduint32(pktout, c->remoteid);
8291         ssh2_pkt_adduint32(pktout, c->localid);
8292         ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8293         ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
8294         ssh2_pkt_send(ssh, pktout);
8295     }
8296 }
8297
8298 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8299                                  void *share_cs, void *share_chan,
8300                                  const char *peer_addr, int peer_port,
8301                                  int endian, int protomajor, int protominor,
8302                                  const void *initial_data, int initial_len)
8303 {
8304     /*
8305      * This function is called when we've just discovered that an X
8306      * forwarding channel on which we'd been handling the initial auth
8307      * ourselves turns out to be destined for a connection-sharing
8308      * downstream. So we turn the channel into a CHAN_SHARING, meaning
8309      * that we completely stop tracking windows and buffering data and
8310      * just pass more or less unmodified SSH messages back and forth.
8311      */
8312     c->type = CHAN_SHARING;
8313     c->u.sharing.ctx = share_cs;
8314     share_setup_x11_channel(share_cs, share_chan,
8315                             c->localid, c->remoteid, c->v.v2.remwindow,
8316                             c->v.v2.remmaxpkt, c->v.v2.locwindow,
8317                             peer_addr, peer_port, endian,
8318                             protomajor, protominor,
8319                             initial_data, initial_len);
8320 }
8321
8322 void sshfwd_x11_is_local(struct ssh_channel *c)
8323 {
8324     /*
8325      * This function is called when we've just discovered that an X
8326      * forwarding channel is _not_ destined for a connection-sharing
8327      * downstream but we're going to handle it ourselves. We stop
8328      * presenting a cautiously small window and go into ordinary data
8329      * exchange mode.
8330      */
8331     c->u.x11.initial = FALSE;
8332     ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8333 }
8334
8335 /*
8336  * Buffer banner messages for later display at some convenient point,
8337  * if we're going to display them.
8338  */
8339 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8340 {
8341     /* Arbitrary limit to prevent unbounded inflation of buffer */
8342     if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8343         bufchain_size(&ssh->banner) <= 131072) {
8344         char *banner = NULL;
8345         int size = 0;
8346         ssh_pkt_getstring(pktin, &banner, &size);
8347         if (banner)
8348             bufchain_add(&ssh->banner, banner, size);
8349     }
8350 }
8351
8352 /* Helper function to deal with sending tty modes for "pty-req" */
8353 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8354 {
8355     struct Packet *pktout = (struct Packet *)data;
8356     int i = 0;
8357     unsigned int arg = 0;
8358     while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8359     if (i == lenof(ssh_ttymodes)) return;
8360     switch (ssh_ttymodes[i].type) {
8361       case TTY_OP_CHAR:
8362         arg = ssh_tty_parse_specchar(val);
8363         break;
8364       case TTY_OP_BOOL:
8365         arg = ssh_tty_parse_boolean(val);
8366         break;
8367     }
8368     ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8369     ssh2_pkt_adduint32(pktout, arg);
8370 }
8371
8372 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8373                            void *ctx)
8374 {
8375     struct ssh2_setup_x11_state {
8376         int crLine;
8377     };
8378     Ssh ssh = c->ssh;
8379     struct Packet *pktout;
8380     crStateP(ssh2_setup_x11_state, ctx);
8381
8382     crBeginState;
8383
8384     logevent("Requesting X11 forwarding");
8385     pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8386                                ssh2_setup_x11, s);
8387     ssh2_pkt_addbool(pktout, 0);               /* many connections */
8388     ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8389     ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8390     ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8391     ssh2_pkt_send(ssh, pktout);
8392
8393     /* Wait to be called back with either a response packet, or NULL
8394      * meaning clean up and free our data */
8395     crReturnV;
8396
8397     if (pktin) {
8398         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8399             logevent("X11 forwarding enabled");
8400             ssh->X11_fwd_enabled = TRUE;
8401         } else
8402             logevent("X11 forwarding refused");
8403     }
8404
8405     crFinishFreeV;
8406 }
8407
8408 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8409                                    void *ctx)
8410 {
8411     struct ssh2_setup_agent_state {
8412         int crLine;
8413     };
8414     Ssh ssh = c->ssh;
8415     struct Packet *pktout;
8416     crStateP(ssh2_setup_agent_state, ctx);
8417
8418     crBeginState;
8419
8420     logevent("Requesting OpenSSH-style agent forwarding");
8421     pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8422                                ssh2_setup_agent, s);
8423     ssh2_pkt_send(ssh, pktout);
8424
8425     /* Wait to be called back with either a response packet, or NULL
8426      * meaning clean up and free our data */
8427     crReturnV;
8428
8429     if (pktin) {
8430         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8431             logevent("Agent forwarding enabled");
8432             ssh->agentfwd_enabled = TRUE;
8433         } else
8434             logevent("Agent forwarding refused");
8435     }
8436
8437     crFinishFreeV;
8438 }
8439
8440 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8441                                  void *ctx)
8442 {
8443     struct ssh2_setup_pty_state {
8444         int crLine;
8445     };
8446     Ssh ssh = c->ssh;
8447     struct Packet *pktout;
8448     crStateP(ssh2_setup_pty_state, ctx);
8449
8450     crBeginState;
8451
8452     /* Unpick the terminal-speed string. */
8453     /* XXX perhaps we should allow no speeds to be sent. */
8454     ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8455     sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8456     /* Build the pty request. */
8457     pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8458                                ssh2_setup_pty, s);
8459     ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8460     ssh2_pkt_adduint32(pktout, ssh->term_width);
8461     ssh2_pkt_adduint32(pktout, ssh->term_height);
8462     ssh2_pkt_adduint32(pktout, 0);             /* pixel width */
8463     ssh2_pkt_adduint32(pktout, 0);             /* pixel height */
8464     ssh2_pkt_addstring_start(pktout);
8465     parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8466     ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8467     ssh2_pkt_adduint32(pktout, ssh->ispeed);
8468     ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8469     ssh2_pkt_adduint32(pktout, ssh->ospeed);
8470     ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8471     ssh2_pkt_send(ssh, pktout);
8472     ssh->state = SSH_STATE_INTERMED;
8473
8474     /* Wait to be called back with either a response packet, or NULL
8475      * meaning clean up and free our data */
8476     crReturnV;
8477
8478     if (pktin) {
8479         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8480             logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8481                       ssh->ospeed, ssh->ispeed);
8482             ssh->got_pty = TRUE;
8483         } else {
8484             c_write_str(ssh, "Server refused to allocate pty\r\n");
8485             ssh->editing = ssh->echoing = 1;
8486         }
8487     }
8488
8489     crFinishFreeV;
8490 }
8491
8492 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8493                            void *ctx)
8494 {
8495     struct ssh2_setup_env_state {
8496         int crLine;
8497         int num_env, env_left, env_ok;
8498     };
8499     Ssh ssh = c->ssh;
8500     struct Packet *pktout;
8501     crStateP(ssh2_setup_env_state, ctx);
8502
8503     crBeginState;
8504
8505     /*
8506      * Send environment variables.
8507      * 
8508      * Simplest thing here is to send all the requests at once, and
8509      * then wait for a whole bunch of successes or failures.
8510      */
8511     s->num_env = 0;
8512     {
8513         char *key, *val;
8514
8515         for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8516              val != NULL;
8517              val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8518             pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8519             ssh2_pkt_addstring(pktout, key);
8520             ssh2_pkt_addstring(pktout, val);
8521             ssh2_pkt_send(ssh, pktout);
8522
8523             s->num_env++;
8524         }
8525         if (s->num_env)
8526             logeventf(ssh, "Sent %d environment variables", s->num_env);
8527     }
8528
8529     if (s->num_env) {
8530         s->env_ok = 0;
8531         s->env_left = s->num_env;
8532
8533         while (s->env_left > 0) {
8534             /* Wait to be called back with either a response packet,
8535              * or NULL meaning clean up and free our data */
8536             crReturnV;
8537             if (!pktin) goto out;
8538             if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8539                 s->env_ok++;
8540             s->env_left--;
8541         }
8542
8543         if (s->env_ok == s->num_env) {
8544             logevent("All environment variables successfully set");
8545         } else if (s->env_ok == 0) {
8546             logevent("All environment variables refused");
8547             c_write_str(ssh, "Server refused to set environment variables\r\n");
8548         } else {
8549             logeventf(ssh, "%d environment variables refused",
8550                       s->num_env - s->env_ok);
8551             c_write_str(ssh, "Server refused to set all environment variables\r\n");
8552         }
8553     }
8554   out:;
8555     crFinishFreeV;
8556 }
8557
8558 /*
8559  * Handle the SSH-2 userauth and connection layers.
8560  */
8561 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8562 {
8563     do_ssh2_authconn(ssh, NULL, 0, pktin);
8564 }
8565
8566 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8567                                    void *ctx)
8568 {
8569     if (pktin)
8570         do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8571 }
8572
8573 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8574                              struct Packet *pktin)
8575 {
8576     struct do_ssh2_authconn_state {
8577         int crLine;
8578         enum {
8579             AUTH_TYPE_NONE,
8580                 AUTH_TYPE_PUBLICKEY,
8581                 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8582                 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8583                 AUTH_TYPE_PASSWORD,
8584                 AUTH_TYPE_GSSAPI,      /* always QUIET */
8585                 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8586                 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8587         } type;
8588         int done_service_req;
8589         int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8590         int tried_pubkey_config, done_agent;
8591 #ifndef NO_GSSAPI
8592         int can_gssapi;
8593         int tried_gssapi;
8594 #endif
8595         int kbd_inter_refused;
8596         int we_are_in, userauth_success;
8597         prompts_t *cur_prompt;
8598         int num_prompts;
8599         char *username;
8600         char *password;
8601         int got_username;
8602         void *publickey_blob;
8603         int publickey_bloblen;
8604         int publickey_encrypted;
8605         char *publickey_algorithm;
8606         char *publickey_comment;
8607         unsigned char agent_request[5], *agent_response, *agentp;
8608         int agent_responselen;
8609         unsigned char *pkblob_in_agent;
8610         int keyi, nkeys;
8611         char *pkblob, *alg, *commentp;
8612         int pklen, alglen, commentlen;
8613         int siglen, retlen, len;
8614         char *q, *agentreq, *ret;
8615         int try_send;
8616         struct Packet *pktout;
8617         Filename *keyfile;
8618 #ifndef NO_GSSAPI
8619         struct ssh_gss_library *gsslib;
8620         Ssh_gss_ctx gss_ctx;
8621         Ssh_gss_buf gss_buf;
8622         Ssh_gss_buf gss_rcvtok, gss_sndtok;
8623         Ssh_gss_name gss_srv_name;
8624         Ssh_gss_stat gss_stat;
8625 #endif
8626     };
8627     crState(do_ssh2_authconn_state);
8628
8629     crBeginState;
8630
8631     /* Register as a handler for all the messages this coroutine handles. */
8632     ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8633     ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8634     ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8635     ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8636     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8637     ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8638     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8639     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8640     ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8641     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8642     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8643     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8644     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8645     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8646     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8647     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8648     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8649     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8650     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8651     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8652     
8653     s->done_service_req = FALSE;
8654     s->we_are_in = s->userauth_success = FALSE;
8655     s->agent_response = NULL;
8656 #ifndef NO_GSSAPI
8657     s->tried_gssapi = FALSE;
8658 #endif
8659
8660     if (!ssh->bare_connection) {
8661         if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8662             /*
8663              * Request userauth protocol, and await a response to it.
8664              */
8665             s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8666             ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8667             ssh2_pkt_send(ssh, s->pktout);
8668             crWaitUntilV(pktin);
8669             if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8670                 s->done_service_req = TRUE;
8671         }
8672         if (!s->done_service_req) {
8673             /*
8674              * Request connection protocol directly, without authentication.
8675              */
8676             s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8677             ssh2_pkt_addstring(s->pktout, "ssh-connection");
8678             ssh2_pkt_send(ssh, s->pktout);
8679             crWaitUntilV(pktin);
8680             if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8681                 s->we_are_in = TRUE; /* no auth required */
8682             } else {
8683                 bombout(("Server refused service request"));
8684                 crStopV;
8685             }
8686         }
8687     } else {
8688         s->we_are_in = TRUE;
8689     }
8690
8691     /* Arrange to be able to deal with any BANNERs that come in.
8692      * (We do this now as packets may come in during the next bit.) */
8693     bufchain_init(&ssh->banner);
8694     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8695         ssh2_msg_userauth_banner;
8696
8697     /*
8698      * Misc one-time setup for authentication.
8699      */
8700     s->publickey_blob = NULL;
8701     if (!s->we_are_in) {
8702
8703         /*
8704          * Load the public half of any configured public key file
8705          * for later use.
8706          */
8707         s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8708         if (!filename_is_null(s->keyfile)) {
8709             int keytype;
8710             logeventf(ssh, "Reading private key file \"%.150s\"",
8711                       filename_to_str(s->keyfile));
8712             keytype = key_type(s->keyfile);
8713             if (keytype == SSH_KEYTYPE_SSH2) {
8714                 const char *error;
8715                 s->publickey_blob =
8716                     ssh2_userkey_loadpub(s->keyfile,
8717                                          &s->publickey_algorithm,
8718                                          &s->publickey_bloblen, 
8719                                          &s->publickey_comment, &error);
8720                 if (s->publickey_blob) {
8721                     s->publickey_encrypted =
8722                         ssh2_userkey_encrypted(s->keyfile, NULL);
8723                 } else {
8724                     char *msgbuf;
8725                     logeventf(ssh, "Unable to load private key (%s)", 
8726                               error);
8727                     msgbuf = dupprintf("Unable to load private key file "
8728                                        "\"%.150s\" (%s)\r\n",
8729                                        filename_to_str(s->keyfile),
8730                                        error);
8731                     c_write_str(ssh, msgbuf);
8732                     sfree(msgbuf);
8733                 }
8734             } else {
8735                 char *msgbuf;
8736                 logeventf(ssh, "Unable to use this key file (%s)",
8737                           key_type_to_str(keytype));
8738                 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8739                                    " (%s)\r\n",
8740                                    filename_to_str(s->keyfile),
8741                                    key_type_to_str(keytype));
8742                 c_write_str(ssh, msgbuf);
8743                 sfree(msgbuf);
8744                 s->publickey_blob = NULL;
8745             }
8746         }
8747
8748         /*
8749          * Find out about any keys Pageant has (but if there's a
8750          * public key configured, filter out all others).
8751          */
8752         s->nkeys = 0;
8753         s->agent_response = NULL;
8754         s->pkblob_in_agent = NULL;
8755         if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8756
8757             void *r;
8758
8759             logevent("Pageant is running. Requesting keys.");
8760
8761             /* Request the keys held by the agent. */
8762             PUT_32BIT(s->agent_request, 1);
8763             s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8764             if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8765                              ssh_agent_callback, ssh)) {
8766                 do {
8767                     crReturnV;
8768                     if (pktin) {
8769                         bombout(("Unexpected data from server while"
8770                                  " waiting for agent response"));
8771                         crStopV;
8772                     }
8773                 } while (pktin || inlen > 0);
8774                 r = ssh->agent_response;
8775                 s->agent_responselen = ssh->agent_response_len;
8776             }
8777             s->agent_response = (unsigned char *) r;
8778             if (s->agent_response && s->agent_responselen >= 5 &&
8779                 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8780                 int keyi;
8781                 unsigned char *p;
8782                 p = s->agent_response + 5;
8783                 s->nkeys = toint(GET_32BIT(p));
8784
8785                 /*
8786                  * Vet the Pageant response to ensure that the key
8787                  * count and blob lengths make sense.
8788                  */
8789                 if (s->nkeys < 0) {
8790                     logeventf(ssh, "Pageant response contained a negative"
8791                               " key count %d", s->nkeys);
8792                     s->nkeys = 0;
8793                     goto done_agent_query;
8794                 } else {
8795                     unsigned char *q = p + 4;
8796                     int lenleft = s->agent_responselen - 5 - 4;
8797
8798                     for (keyi = 0; keyi < s->nkeys; keyi++) {
8799                         int bloblen, commentlen;
8800                         if (lenleft < 4) {
8801                             logeventf(ssh, "Pageant response was truncated");
8802                             s->nkeys = 0;
8803                             goto done_agent_query;
8804                         }
8805                         bloblen = toint(GET_32BIT(q));
8806                         if (bloblen < 0 || bloblen > lenleft) {
8807                             logeventf(ssh, "Pageant response was truncated");
8808                             s->nkeys = 0;
8809                             goto done_agent_query;
8810                         }
8811                         lenleft -= 4 + bloblen;
8812                         q += 4 + bloblen;
8813                         commentlen = toint(GET_32BIT(q));
8814                         if (commentlen < 0 || commentlen > lenleft) {
8815                             logeventf(ssh, "Pageant response was truncated");
8816                             s->nkeys = 0;
8817                             goto done_agent_query;
8818                         }
8819                         lenleft -= 4 + commentlen;
8820                         q += 4 + commentlen;
8821                     }
8822                 }
8823
8824                 p += 4;
8825                 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8826                 if (s->publickey_blob) {
8827                     /* See if configured key is in agent. */
8828                     for (keyi = 0; keyi < s->nkeys; keyi++) {
8829                         s->pklen = toint(GET_32BIT(p));
8830                         if (s->pklen == s->publickey_bloblen &&
8831                             !memcmp(p+4, s->publickey_blob,
8832                                     s->publickey_bloblen)) {
8833                             logeventf(ssh, "Pageant key #%d matches "
8834                                       "configured key file", keyi);
8835                             s->keyi = keyi;
8836                             s->pkblob_in_agent = p;
8837                             break;
8838                         }
8839                         p += 4 + s->pklen;
8840                         p += toint(GET_32BIT(p)) + 4; /* comment */
8841                     }
8842                     if (!s->pkblob_in_agent) {
8843                         logevent("Configured key file not in Pageant");
8844                         s->nkeys = 0;
8845                     }
8846                 }
8847             } else {
8848                 logevent("Failed to get reply from Pageant");
8849             }
8850           done_agent_query:;
8851         }
8852
8853     }
8854
8855     /*
8856      * We repeat this whole loop, including the username prompt,
8857      * until we manage a successful authentication. If the user
8858      * types the wrong _password_, they can be sent back to the
8859      * beginning to try another username, if this is configured on.
8860      * (If they specify a username in the config, they are never
8861      * asked, even if they do give a wrong password.)
8862      * 
8863      * I think this best serves the needs of
8864      * 
8865      *  - the people who have no configuration, no keys, and just
8866      *    want to try repeated (username,password) pairs until they
8867      *    type both correctly
8868      * 
8869      *  - people who have keys and configuration but occasionally
8870      *    need to fall back to passwords
8871      * 
8872      *  - people with a key held in Pageant, who might not have
8873      *    logged in to a particular machine before; so they want to
8874      *    type a username, and then _either_ their key will be
8875      *    accepted, _or_ they will type a password. If they mistype
8876      *    the username they will want to be able to get back and
8877      *    retype it!
8878      */
8879     s->got_username = FALSE;
8880     while (!s->we_are_in) {
8881         /*
8882          * Get a username.
8883          */
8884         if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8885             /*
8886              * We got a username last time round this loop, and
8887              * with change_username turned off we don't try to get
8888              * it again.
8889              */
8890         } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8891             int ret; /* need not be kept over crReturn */
8892             s->cur_prompt = new_prompts(ssh->frontend);
8893             s->cur_prompt->to_server = TRUE;
8894             s->cur_prompt->name = dupstr("SSH login name");
8895             add_prompt(s->cur_prompt, dupstr("login as: "), TRUE); 
8896             ret = get_userpass_input(s->cur_prompt, NULL, 0);
8897             while (ret < 0) {
8898                 ssh->send_ok = 1;
8899                 crWaitUntilV(!pktin);
8900                 ret = get_userpass_input(s->cur_prompt, in, inlen);
8901                 ssh->send_ok = 0;
8902             }
8903             if (!ret) {
8904                 /*
8905                  * get_userpass_input() failed to get a username.
8906                  * Terminate.
8907                  */
8908                 free_prompts(s->cur_prompt);
8909                 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8910                 crStopV;
8911             }
8912             ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8913             free_prompts(s->cur_prompt);
8914         } else {
8915             char *stuff;
8916             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8917                 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8918                 c_write_str(ssh, stuff);
8919                 sfree(stuff);
8920             }
8921         }
8922         s->got_username = TRUE;
8923
8924         /*
8925          * Send an authentication request using method "none": (a)
8926          * just in case it succeeds, and (b) so that we know what
8927          * authentication methods we can usefully try next.
8928          */
8929         ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8930
8931         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8932         ssh2_pkt_addstring(s->pktout, ssh->username);
8933         ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8934         ssh2_pkt_addstring(s->pktout, "none");    /* method */
8935         ssh2_pkt_send(ssh, s->pktout);
8936         s->type = AUTH_TYPE_NONE;
8937         s->gotit = FALSE;
8938         s->we_are_in = FALSE;
8939
8940         s->tried_pubkey_config = FALSE;
8941         s->kbd_inter_refused = FALSE;
8942
8943         /* Reset agent request state. */
8944         s->done_agent = FALSE;
8945         if (s->agent_response) {
8946             if (s->pkblob_in_agent) {
8947                 s->agentp = s->pkblob_in_agent;
8948             } else {
8949                 s->agentp = s->agent_response + 5 + 4;
8950                 s->keyi = 0;
8951             }
8952         }
8953
8954         while (1) {
8955             char *methods = NULL;
8956             int methlen = 0;
8957
8958             /*
8959              * Wait for the result of the last authentication request.
8960              */
8961             if (!s->gotit)
8962                 crWaitUntilV(pktin);
8963             /*
8964              * Now is a convenient point to spew any banner material
8965              * that we've accumulated. (This should ensure that when
8966              * we exit the auth loop, we haven't any left to deal
8967              * with.)
8968              */
8969             {
8970                 int size = bufchain_size(&ssh->banner);
8971                 /*
8972                  * Don't show the banner if we're operating in
8973                  * non-verbose non-interactive mode. (It's probably
8974                  * a script, which means nobody will read the
8975                  * banner _anyway_, and moreover the printing of
8976                  * the banner will screw up processing on the
8977                  * output of (say) plink.)
8978                  */
8979                 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8980                     char *banner = snewn(size, char);
8981                     bufchain_fetch(&ssh->banner, banner, size);
8982                     c_write_untrusted(ssh, banner, size);
8983                     sfree(banner);
8984                 }
8985                 bufchain_clear(&ssh->banner);
8986             }
8987             if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8988                 logevent("Access granted");
8989                 s->we_are_in = s->userauth_success = TRUE;
8990                 break;
8991             }
8992
8993             if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8994                 bombout(("Strange packet received during authentication: "
8995                          "type %d", pktin->type));
8996                 crStopV;
8997             }
8998
8999             s->gotit = FALSE;
9000
9001             /*
9002              * OK, we're now sitting on a USERAUTH_FAILURE message, so
9003              * we can look at the string in it and know what we can
9004              * helpfully try next.
9005              */
9006             if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9007                 ssh_pkt_getstring(pktin, &methods, &methlen);
9008                 if (!ssh2_pkt_getbool(pktin)) {
9009                     /*
9010                      * We have received an unequivocal Access
9011                      * Denied. This can translate to a variety of
9012                      * messages, or no message at all.
9013                      *
9014                      * For forms of authentication which are attempted
9015                      * implicitly, by which I mean without printing
9016                      * anything in the window indicating that we're
9017                      * trying them, we should never print 'Access
9018                      * denied'.
9019                      *
9020                      * If we do print a message saying that we're
9021                      * attempting some kind of authentication, it's OK
9022                      * to print a followup message saying it failed -
9023                      * but the message may sometimes be more specific
9024                      * than simply 'Access denied'.
9025                      *
9026                      * Additionally, if we'd just tried password
9027                      * authentication, we should break out of this
9028                      * whole loop so as to go back to the username
9029                      * prompt (iff we're configured to allow
9030                      * username change attempts).
9031                      */
9032                     if (s->type == AUTH_TYPE_NONE) {
9033                         /* do nothing */
9034                     } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9035                                s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9036                         if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9037                             c_write_str(ssh, "Server refused our key\r\n");
9038                         logevent("Server refused our key");
9039                     } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9040                         /* This _shouldn't_ happen except by a
9041                          * protocol bug causing client and server to
9042                          * disagree on what is a correct signature. */
9043                         c_write_str(ssh, "Server refused public-key signature"
9044                                     " despite accepting key!\r\n");
9045                         logevent("Server refused public-key signature"
9046                                  " despite accepting key!");
9047                     } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9048                         /* quiet, so no c_write */
9049                         logevent("Server refused keyboard-interactive authentication");
9050                     } else if (s->type==AUTH_TYPE_GSSAPI) {
9051                         /* always quiet, so no c_write */
9052                         /* also, the code down in the GSSAPI block has
9053                          * already logged this in the Event Log */
9054                     } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9055                         logevent("Keyboard-interactive authentication failed");
9056                         c_write_str(ssh, "Access denied\r\n");
9057                     } else {
9058                         assert(s->type == AUTH_TYPE_PASSWORD);
9059                         logevent("Password authentication failed");
9060                         c_write_str(ssh, "Access denied\r\n");
9061
9062                         if (conf_get_int(ssh->conf, CONF_change_username)) {
9063                             /* XXX perhaps we should allow
9064                              * keyboard-interactive to do this too? */
9065                             s->we_are_in = FALSE;
9066                             break;
9067                         }
9068                     }
9069                 } else {
9070                     c_write_str(ssh, "Further authentication required\r\n");
9071                     logevent("Further authentication required");
9072                 }
9073
9074                 s->can_pubkey =
9075                     in_commasep_string("publickey", methods, methlen);
9076                 s->can_passwd =
9077                     in_commasep_string("password", methods, methlen);
9078                 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9079                     in_commasep_string("keyboard-interactive", methods, methlen);
9080 #ifndef NO_GSSAPI
9081                 if (!ssh->gsslibs)
9082                     ssh->gsslibs = ssh_gss_setup(ssh->conf);
9083                 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9084                     in_commasep_string("gssapi-with-mic", methods, methlen) &&
9085                     ssh->gsslibs->nlibraries > 0;
9086 #endif
9087             }
9088
9089             ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9090
9091             if (s->can_pubkey && !s->done_agent && s->nkeys) {
9092
9093                 /*
9094                  * Attempt public-key authentication using a key from Pageant.
9095                  */
9096
9097                 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9098
9099                 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9100
9101                 /* Unpack key from agent response */
9102                 s->pklen = toint(GET_32BIT(s->agentp));
9103                 s->agentp += 4;
9104                 s->pkblob = (char *)s->agentp;
9105                 s->agentp += s->pklen;
9106                 s->alglen = toint(GET_32BIT(s->pkblob));
9107                 s->alg = s->pkblob + 4;
9108                 s->commentlen = toint(GET_32BIT(s->agentp));
9109                 s->agentp += 4;
9110                 s->commentp = (char *)s->agentp;
9111                 s->agentp += s->commentlen;
9112                 /* s->agentp now points at next key, if any */
9113
9114                 /* See if server will accept it */
9115                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9116                 ssh2_pkt_addstring(s->pktout, ssh->username);
9117                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9118                                                     /* service requested */
9119                 ssh2_pkt_addstring(s->pktout, "publickey");
9120                                                     /* method */
9121                 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9122                 ssh2_pkt_addstring_start(s->pktout);
9123                 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9124                 ssh2_pkt_addstring_start(s->pktout);
9125                 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9126                 ssh2_pkt_send(ssh, s->pktout);
9127                 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9128
9129                 crWaitUntilV(pktin);
9130                 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9131
9132                     /* Offer of key refused. */
9133                     s->gotit = TRUE;
9134
9135                 } else {
9136                     
9137                     void *vret;
9138
9139                     if (flags & FLAG_VERBOSE) {
9140                         c_write_str(ssh, "Authenticating with "
9141                                     "public key \"");
9142                         c_write(ssh, s->commentp, s->commentlen);
9143                         c_write_str(ssh, "\" from agent\r\n");
9144                     }
9145
9146                     /*
9147                      * Server is willing to accept the key.
9148                      * Construct a SIGN_REQUEST.
9149                      */
9150                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9151                     ssh2_pkt_addstring(s->pktout, ssh->username);
9152                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
9153                                                         /* service requested */
9154                     ssh2_pkt_addstring(s->pktout, "publickey");
9155                                                         /* method */
9156                     ssh2_pkt_addbool(s->pktout, TRUE);  /* signature included */
9157                     ssh2_pkt_addstring_start(s->pktout);
9158                     ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9159                     ssh2_pkt_addstring_start(s->pktout);
9160                     ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9161
9162                     /* Ask agent for signature. */
9163                     s->siglen = s->pktout->length - 5 + 4 +
9164                         ssh->v2_session_id_len;
9165                     if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9166                         s->siglen -= 4;
9167                     s->len = 1;       /* message type */
9168                     s->len += 4 + s->pklen;     /* key blob */
9169                     s->len += 4 + s->siglen;    /* data to sign */
9170                     s->len += 4;      /* flags */
9171                     s->agentreq = snewn(4 + s->len, char);
9172                     PUT_32BIT(s->agentreq, s->len);
9173                     s->q = s->agentreq + 4;
9174                     *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9175                     PUT_32BIT(s->q, s->pklen);
9176                     s->q += 4;
9177                     memcpy(s->q, s->pkblob, s->pklen);
9178                     s->q += s->pklen;
9179                     PUT_32BIT(s->q, s->siglen);
9180                     s->q += 4;
9181                     /* Now the data to be signed... */
9182                     if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9183                         PUT_32BIT(s->q, ssh->v2_session_id_len);
9184                         s->q += 4;
9185                     }
9186                     memcpy(s->q, ssh->v2_session_id,
9187                            ssh->v2_session_id_len);
9188                     s->q += ssh->v2_session_id_len;
9189                     memcpy(s->q, s->pktout->data + 5,
9190                            s->pktout->length - 5);
9191                     s->q += s->pktout->length - 5;
9192                     /* And finally the (zero) flags word. */
9193                     PUT_32BIT(s->q, 0);
9194                     if (!agent_query(s->agentreq, s->len + 4,
9195                                      &vret, &s->retlen,
9196                                      ssh_agent_callback, ssh)) {
9197                         do {
9198                             crReturnV;
9199                             if (pktin) {
9200                                 bombout(("Unexpected data from server"
9201                                          " while waiting for agent"
9202                                          " response"));
9203                                 crStopV;
9204                             }
9205                         } while (pktin || inlen > 0);
9206                         vret = ssh->agent_response;
9207                         s->retlen = ssh->agent_response_len;
9208                     }
9209                     s->ret = vret;
9210                     sfree(s->agentreq);
9211                     if (s->ret) {
9212                         if (s->retlen >= 9 &&
9213                             s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9214                             GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9215                             logevent("Sending Pageant's response");
9216                             ssh2_add_sigblob(ssh, s->pktout,
9217                                              s->pkblob, s->pklen,
9218                                              s->ret + 9,
9219                                              GET_32BIT(s->ret + 5));
9220                             ssh2_pkt_send(ssh, s->pktout);
9221                             s->type = AUTH_TYPE_PUBLICKEY;
9222                         } else {
9223                             /* FIXME: less drastic response */
9224                             bombout(("Pageant failed to answer challenge"));
9225                             crStopV;
9226                         }
9227                     }
9228                 }
9229
9230                 /* Do we have any keys left to try? */
9231                 if (s->pkblob_in_agent) {
9232                     s->done_agent = TRUE;
9233                     s->tried_pubkey_config = TRUE;
9234                 } else {
9235                     s->keyi++;
9236                     if (s->keyi >= s->nkeys)
9237                         s->done_agent = TRUE;
9238                 }
9239
9240             } else if (s->can_pubkey && s->publickey_blob &&
9241                        !s->tried_pubkey_config) {
9242
9243                 struct ssh2_userkey *key;   /* not live over crReturn */
9244                 char *passphrase;           /* not live over crReturn */
9245
9246                 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9247
9248                 s->tried_pubkey_config = TRUE;
9249
9250                 /*
9251                  * Try the public key supplied in the configuration.
9252                  *
9253                  * First, offer the public blob to see if the server is
9254                  * willing to accept it.
9255                  */
9256                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9257                 ssh2_pkt_addstring(s->pktout, ssh->username);
9258                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9259                                                 /* service requested */
9260                 ssh2_pkt_addstring(s->pktout, "publickey");     /* method */
9261                 ssh2_pkt_addbool(s->pktout, FALSE);
9262                                                 /* no signature included */
9263                 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9264                 ssh2_pkt_addstring_start(s->pktout);
9265                 ssh2_pkt_addstring_data(s->pktout,
9266                                         (char *)s->publickey_blob,
9267                                         s->publickey_bloblen);
9268                 ssh2_pkt_send(ssh, s->pktout);
9269                 logevent("Offered public key");
9270
9271                 crWaitUntilV(pktin);
9272                 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9273                     /* Key refused. Give up. */
9274                     s->gotit = TRUE; /* reconsider message next loop */
9275                     s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9276                     continue; /* process this new message */
9277                 }
9278                 logevent("Offer of public key accepted");
9279
9280                 /*
9281                  * Actually attempt a serious authentication using
9282                  * the key.
9283                  */
9284                 if (flags & FLAG_VERBOSE) {
9285                     c_write_str(ssh, "Authenticating with public key \"");
9286                     c_write_str(ssh, s->publickey_comment);
9287                     c_write_str(ssh, "\"\r\n");
9288                 }
9289                 key = NULL;
9290                 while (!key) {
9291                     const char *error;  /* not live over crReturn */
9292                     if (s->publickey_encrypted) {
9293                         /*
9294                          * Get a passphrase from the user.
9295                          */
9296                         int ret; /* need not be kept over crReturn */
9297                         s->cur_prompt = new_prompts(ssh->frontend);
9298                         s->cur_prompt->to_server = FALSE;
9299                         s->cur_prompt->name = dupstr("SSH key passphrase");
9300                         add_prompt(s->cur_prompt,
9301                                    dupprintf("Passphrase for key \"%.100s\": ",
9302                                              s->publickey_comment),
9303                                    FALSE);
9304                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
9305                         while (ret < 0) {
9306                             ssh->send_ok = 1;
9307                             crWaitUntilV(!pktin);
9308                             ret = get_userpass_input(s->cur_prompt,
9309                                                      in, inlen);
9310                             ssh->send_ok = 0;
9311                         }
9312                         if (!ret) {
9313                             /* Failed to get a passphrase. Terminate. */
9314                             free_prompts(s->cur_prompt);
9315                             ssh_disconnect(ssh, NULL,
9316                                            "Unable to authenticate",
9317                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9318                                            TRUE);
9319                             crStopV;
9320                         }
9321                         passphrase =
9322                             dupstr(s->cur_prompt->prompts[0]->result);
9323                         free_prompts(s->cur_prompt);
9324                     } else {
9325                         passphrase = NULL; /* no passphrase needed */
9326                     }
9327
9328                     /*
9329                      * Try decrypting the key.
9330                      */
9331                     s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9332                     key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9333                     if (passphrase) {
9334                         /* burn the evidence */
9335                         smemclr(passphrase, strlen(passphrase));
9336                         sfree(passphrase);
9337                     }
9338                     if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9339                         if (passphrase &&
9340                             (key == SSH2_WRONG_PASSPHRASE)) {
9341                             c_write_str(ssh, "Wrong passphrase\r\n");
9342                             key = NULL;
9343                             /* and loop again */
9344                         } else {
9345                             c_write_str(ssh, "Unable to load private key (");
9346                             c_write_str(ssh, error);
9347                             c_write_str(ssh, ")\r\n");
9348                             key = NULL;
9349                             break; /* try something else */
9350                         }
9351                     }
9352                 }
9353
9354                 if (key) {
9355                     unsigned char *pkblob, *sigblob, *sigdata;
9356                     int pkblob_len, sigblob_len, sigdata_len;
9357                     int p;
9358
9359                     /*
9360                      * We have loaded the private key and the server
9361                      * has announced that it's willing to accept it.
9362                      * Hallelujah. Generate a signature and send it.
9363                      */
9364                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9365                     ssh2_pkt_addstring(s->pktout, ssh->username);
9366                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
9367                                                     /* service requested */
9368                     ssh2_pkt_addstring(s->pktout, "publickey");
9369                                                     /* method */
9370                     ssh2_pkt_addbool(s->pktout, TRUE);
9371                                                     /* signature follows */
9372                     ssh2_pkt_addstring(s->pktout, key->alg->name);
9373                     pkblob = key->alg->public_blob(key->data,
9374                                                    &pkblob_len);
9375                     ssh2_pkt_addstring_start(s->pktout);
9376                     ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9377                                             pkblob_len);
9378
9379                     /*
9380                      * The data to be signed is:
9381                      *
9382                      *   string  session-id
9383                      *
9384                      * followed by everything so far placed in the
9385                      * outgoing packet.
9386                      */
9387                     sigdata_len = s->pktout->length - 5 + 4 +
9388                         ssh->v2_session_id_len;
9389                     if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9390                         sigdata_len -= 4;
9391                     sigdata = snewn(sigdata_len, unsigned char);
9392                     p = 0;
9393                     if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9394                         PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9395                         p += 4;
9396                     }
9397                     memcpy(sigdata+p, ssh->v2_session_id,
9398                            ssh->v2_session_id_len);
9399                     p += ssh->v2_session_id_len;
9400                     memcpy(sigdata+p, s->pktout->data + 5,
9401                            s->pktout->length - 5);
9402                     p += s->pktout->length - 5;
9403                     assert(p == sigdata_len);
9404                     sigblob = key->alg->sign(key->data, (char *)sigdata,
9405                                              sigdata_len, &sigblob_len);
9406                     ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9407                                      sigblob, sigblob_len);
9408                     sfree(pkblob);
9409                     sfree(sigblob);
9410                     sfree(sigdata);
9411
9412                     ssh2_pkt_send(ssh, s->pktout);
9413                     logevent("Sent public key signature");
9414                     s->type = AUTH_TYPE_PUBLICKEY;
9415                     key->alg->freekey(key->data);
9416                 }
9417
9418 #ifndef NO_GSSAPI
9419             } else if (s->can_gssapi && !s->tried_gssapi) {
9420
9421                 /* GSSAPI Authentication */
9422
9423                 int micoffset, len;
9424                 char *data;
9425                 Ssh_gss_buf mic;
9426                 s->type = AUTH_TYPE_GSSAPI;
9427                 s->tried_gssapi = TRUE;
9428                 s->gotit = TRUE;
9429                 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9430
9431                 /*
9432                  * Pick the highest GSS library on the preference
9433                  * list.
9434                  */
9435                 {
9436                     int i, j;
9437                     s->gsslib = NULL;
9438                     for (i = 0; i < ngsslibs; i++) {
9439                         int want_id = conf_get_int_int(ssh->conf,
9440                                                        CONF_ssh_gsslist, i);
9441                         for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9442                             if (ssh->gsslibs->libraries[j].id == want_id) {
9443                                 s->gsslib = &ssh->gsslibs->libraries[j];
9444                                 goto got_gsslib;   /* double break */
9445                             }
9446                     }
9447                     got_gsslib:
9448                     /*
9449                      * We always expect to have found something in
9450                      * the above loop: we only came here if there
9451                      * was at least one viable GSS library, and the
9452                      * preference list should always mention
9453                      * everything and only change the order.
9454                      */
9455                     assert(s->gsslib);
9456                 }
9457
9458                 if (s->gsslib->gsslogmsg)
9459                     logevent(s->gsslib->gsslogmsg);
9460
9461                 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9462                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9463                 ssh2_pkt_addstring(s->pktout, ssh->username);
9464                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9465                 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9466                 logevent("Attempting GSSAPI authentication");
9467
9468                 /* add mechanism info */
9469                 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9470
9471                 /* number of GSSAPI mechanisms */
9472                 ssh2_pkt_adduint32(s->pktout,1);
9473
9474                 /* length of OID + 2 */
9475                 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9476                 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9477
9478                 /* length of OID */
9479                 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9480
9481                 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9482                                 s->gss_buf.length);
9483                 ssh2_pkt_send(ssh, s->pktout);
9484                 crWaitUntilV(pktin);
9485                 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9486                     logevent("GSSAPI authentication request refused");
9487                     continue;
9488                 }
9489
9490                 /* check returned packet ... */
9491
9492                 ssh_pkt_getstring(pktin, &data, &len);
9493                 s->gss_rcvtok.value = data;
9494                 s->gss_rcvtok.length = len;
9495                 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9496                     ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9497                     ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9498                     memcmp((char *)s->gss_rcvtok.value + 2,
9499                            s->gss_buf.value,s->gss_buf.length) ) {
9500                     logevent("GSSAPI authentication - wrong response from server");
9501                     continue;
9502                 }
9503
9504                 /* now start running */
9505                 s->gss_stat = s->gsslib->import_name(s->gsslib,
9506                                                      ssh->fullhostname,
9507                                                      &s->gss_srv_name);
9508                 if (s->gss_stat != SSH_GSS_OK) {
9509                     if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9510                         logevent("GSSAPI import name failed - Bad service name");
9511                     else
9512                         logevent("GSSAPI import name failed");
9513                     continue;
9514                 }
9515
9516                 /* fetch TGT into GSS engine */
9517                 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9518
9519                 if (s->gss_stat != SSH_GSS_OK) {
9520                     logevent("GSSAPI authentication failed to get credentials");
9521                     s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9522                     continue;
9523                 }
9524
9525                 /* initial tokens are empty */
9526                 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9527                 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9528
9529                 /* now enter the loop */
9530                 do {
9531                     s->gss_stat = s->gsslib->init_sec_context
9532                         (s->gsslib,
9533                          &s->gss_ctx,
9534                          s->gss_srv_name,
9535                          conf_get_int(ssh->conf, CONF_gssapifwd),
9536                          &s->gss_rcvtok,
9537                          &s->gss_sndtok);
9538
9539                     if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9540                         s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9541                         logevent("GSSAPI authentication initialisation failed");
9542
9543                         if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9544                                                       &s->gss_buf) == SSH_GSS_OK) {
9545                             logevent(s->gss_buf.value);
9546                             sfree(s->gss_buf.value);
9547                         }
9548
9549                         break;
9550                     }
9551                     logevent("GSSAPI authentication initialised");
9552
9553                     /* Client and server now exchange tokens until GSSAPI
9554                      * no longer says CONTINUE_NEEDED */
9555
9556                     if (s->gss_sndtok.length != 0) {
9557                         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9558                         ssh_pkt_addstring_start(s->pktout);
9559                         ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9560                         ssh2_pkt_send(ssh, s->pktout);
9561                         s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9562                     }
9563
9564                     if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9565                         crWaitUntilV(pktin);
9566                         if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9567                             logevent("GSSAPI authentication - bad server response");
9568                             s->gss_stat = SSH_GSS_FAILURE;
9569                             break;
9570                         }
9571                         ssh_pkt_getstring(pktin, &data, &len);
9572                         s->gss_rcvtok.value = data;
9573                         s->gss_rcvtok.length = len;
9574                     }
9575                 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9576
9577                 if (s->gss_stat != SSH_GSS_OK) {
9578                     s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9579                     s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9580                     continue;
9581                 }
9582                 logevent("GSSAPI authentication loop finished OK");
9583
9584                 /* Now send the MIC */
9585
9586                 s->pktout = ssh2_pkt_init(0);
9587                 micoffset = s->pktout->length;
9588                 ssh_pkt_addstring_start(s->pktout);
9589                 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9590                 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9591                 ssh_pkt_addstring(s->pktout, ssh->username);
9592                 ssh_pkt_addstring(s->pktout, "ssh-connection");
9593                 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9594
9595                 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9596                 s->gss_buf.length = s->pktout->length - micoffset;
9597
9598                 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9599                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9600                 ssh_pkt_addstring_start(s->pktout);
9601                 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9602                 ssh2_pkt_send(ssh, s->pktout);
9603                 s->gsslib->free_mic(s->gsslib, &mic);
9604
9605                 s->gotit = FALSE;
9606
9607                 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9608                 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9609                 continue;
9610 #endif
9611             } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9612
9613                 /*
9614                  * Keyboard-interactive authentication.
9615                  */
9616
9617                 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9618
9619                 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9620
9621                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9622                 ssh2_pkt_addstring(s->pktout, ssh->username);
9623                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9624                                                         /* service requested */
9625                 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9626                                                         /* method */
9627                 ssh2_pkt_addstring(s->pktout, "");      /* lang */
9628                 ssh2_pkt_addstring(s->pktout, "");      /* submethods */
9629                 ssh2_pkt_send(ssh, s->pktout);
9630                 
9631                 logevent("Attempting keyboard-interactive authentication");
9632
9633                 crWaitUntilV(pktin);
9634                 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9635                     /* Server is not willing to do keyboard-interactive
9636                      * at all (or, bizarrely but legally, accepts the
9637                      * user without actually issuing any prompts).
9638                      * Give up on it entirely. */
9639                     s->gotit = TRUE;
9640                     s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9641                     s->kbd_inter_refused = TRUE; /* don't try it again */
9642                     continue;
9643                 }
9644
9645                 /*
9646                  * Loop while the server continues to send INFO_REQUESTs.
9647                  */
9648                 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9649
9650                     char *name, *inst, *lang;
9651                     int name_len, inst_len, lang_len;
9652                     int i;
9653
9654                     /*
9655                      * We've got a fresh USERAUTH_INFO_REQUEST.
9656                      * Get the preamble and start building a prompt.
9657                      */
9658                     ssh_pkt_getstring(pktin, &name, &name_len);
9659                     ssh_pkt_getstring(pktin, &inst, &inst_len);
9660                     ssh_pkt_getstring(pktin, &lang, &lang_len);
9661                     s->cur_prompt = new_prompts(ssh->frontend);
9662                     s->cur_prompt->to_server = TRUE;
9663
9664                     /*
9665                      * Get any prompt(s) from the packet.
9666                      */
9667                     s->num_prompts = ssh_pkt_getuint32(pktin);
9668                     for (i = 0; i < s->num_prompts; i++) {
9669                         char *prompt;
9670                         int prompt_len;
9671                         int echo;
9672                         static char noprompt[] =
9673                             "<server failed to send prompt>: ";
9674
9675                         ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9676                         echo = ssh2_pkt_getbool(pktin);
9677                         if (!prompt_len) {
9678                             prompt = noprompt;
9679                             prompt_len = lenof(noprompt)-1;
9680                         }
9681                         add_prompt(s->cur_prompt,
9682                                    dupprintf("%.*s", prompt_len, prompt),
9683                                    echo);
9684                     }
9685
9686                     if (name_len) {
9687                         /* FIXME: better prefix to distinguish from
9688                          * local prompts? */
9689                         s->cur_prompt->name =
9690                             dupprintf("SSH server: %.*s", name_len, name);
9691                         s->cur_prompt->name_reqd = TRUE;
9692                     } else {
9693                         s->cur_prompt->name =
9694                             dupstr("SSH server authentication");
9695                         s->cur_prompt->name_reqd = FALSE;
9696                     }
9697                     /* We add a prefix to try to make it clear that a prompt
9698                      * has come from the server.
9699                      * FIXME: ugly to print "Using..." in prompt _every_
9700                      * time round. Can this be done more subtly? */
9701                     /* Special case: for reasons best known to themselves,
9702                      * some servers send k-i requests with no prompts and
9703                      * nothing to display. Keep quiet in this case. */
9704                     if (s->num_prompts || name_len || inst_len) {
9705                         s->cur_prompt->instruction =
9706                             dupprintf("Using keyboard-interactive authentication.%s%.*s",
9707                                       inst_len ? "\n" : "", inst_len, inst);
9708                         s->cur_prompt->instr_reqd = TRUE;
9709                     } else {
9710                         s->cur_prompt->instr_reqd = FALSE;
9711                     }
9712
9713                     /*
9714                      * Display any instructions, and get the user's
9715                      * response(s).
9716                      */
9717                     {
9718                         int ret; /* not live over crReturn */
9719                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
9720                         while (ret < 0) {
9721                             ssh->send_ok = 1;
9722                             crWaitUntilV(!pktin);
9723                             ret = get_userpass_input(s->cur_prompt, in, inlen);
9724                             ssh->send_ok = 0;
9725                         }
9726                         if (!ret) {
9727                             /*
9728                              * Failed to get responses. Terminate.
9729                              */
9730                             free_prompts(s->cur_prompt);
9731                             ssh_disconnect(ssh, NULL, "Unable to authenticate",
9732                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9733                                            TRUE);
9734                             crStopV;
9735                         }
9736                     }
9737
9738                     /*
9739                      * Send the response(s) to the server.
9740                      */
9741                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9742                     ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9743                     for (i=0; i < s->num_prompts; i++) {
9744                         ssh2_pkt_addstring(s->pktout,
9745                                            s->cur_prompt->prompts[i]->result);
9746                     }
9747                     ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9748
9749                     /*
9750                      * Free the prompts structure from this iteration.
9751                      * If there's another, a new one will be allocated
9752                      * when we return to the top of this while loop.
9753                      */
9754                     free_prompts(s->cur_prompt);
9755
9756                     /*
9757                      * Get the next packet in case it's another
9758                      * INFO_REQUEST.
9759                      */
9760                     crWaitUntilV(pktin);
9761
9762                 }
9763
9764                 /*
9765                  * We should have SUCCESS or FAILURE now.
9766                  */
9767                 s->gotit = TRUE;
9768
9769             } else if (s->can_passwd) {
9770
9771                 /*
9772                  * Plain old password authentication.
9773                  */
9774                 int ret; /* not live over crReturn */
9775                 int changereq_first_time; /* not live over crReturn */
9776
9777                 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9778
9779                 s->cur_prompt = new_prompts(ssh->frontend);
9780                 s->cur_prompt->to_server = TRUE;
9781                 s->cur_prompt->name = dupstr("SSH password");
9782                 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9783                                                     ssh->username,
9784                                                     ssh->savedhost),
9785                            FALSE);
9786
9787                 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9788                 while (ret < 0) {
9789                     ssh->send_ok = 1;
9790                     crWaitUntilV(!pktin);
9791                     ret = get_userpass_input(s->cur_prompt, in, inlen);
9792                     ssh->send_ok = 0;
9793                 }
9794                 if (!ret) {
9795                     /*
9796                      * Failed to get responses. Terminate.
9797                      */
9798                     free_prompts(s->cur_prompt);
9799                     ssh_disconnect(ssh, NULL, "Unable to authenticate",
9800                                    SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9801                                    TRUE);
9802                     crStopV;
9803                 }
9804                 /*
9805                  * Squirrel away the password. (We may need it later if
9806                  * asked to change it.)
9807                  */
9808                 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9809                 free_prompts(s->cur_prompt);
9810
9811                 /*
9812                  * Send the password packet.
9813                  *
9814                  * We pad out the password packet to 256 bytes to make
9815                  * it harder for an attacker to find the length of the
9816                  * user's password.
9817                  *
9818                  * Anyone using a password longer than 256 bytes
9819                  * probably doesn't have much to worry about from
9820                  * people who find out how long their password is!
9821                  */
9822                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9823                 ssh2_pkt_addstring(s->pktout, ssh->username);
9824                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9825                                                         /* service requested */
9826                 ssh2_pkt_addstring(s->pktout, "password");
9827                 ssh2_pkt_addbool(s->pktout, FALSE);
9828                 ssh2_pkt_addstring(s->pktout, s->password);
9829                 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9830                 logevent("Sent password");
9831                 s->type = AUTH_TYPE_PASSWORD;
9832
9833                 /*
9834                  * Wait for next packet, in case it's a password change
9835                  * request.
9836                  */
9837                 crWaitUntilV(pktin);
9838                 changereq_first_time = TRUE;
9839
9840                 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9841
9842                     /* 
9843                      * We're being asked for a new password
9844                      * (perhaps not for the first time).
9845                      * Loop until the server accepts it.
9846                      */
9847
9848                     int got_new = FALSE; /* not live over crReturn */
9849                     char *prompt;   /* not live over crReturn */
9850                     int prompt_len; /* not live over crReturn */
9851                     
9852                     {
9853                         char *msg;
9854                         if (changereq_first_time)
9855                             msg = "Server requested password change";
9856                         else
9857                             msg = "Server rejected new password";
9858                         logevent(msg);
9859                         c_write_str(ssh, msg);
9860                         c_write_str(ssh, "\r\n");
9861                     }
9862
9863                     ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9864
9865                     s->cur_prompt = new_prompts(ssh->frontend);
9866                     s->cur_prompt->to_server = TRUE;
9867                     s->cur_prompt->name = dupstr("New SSH password");
9868                     s->cur_prompt->instruction =
9869                         dupprintf("%.*s", prompt_len, prompt);
9870                     s->cur_prompt->instr_reqd = TRUE;
9871                     /*
9872                      * There's no explicit requirement in the protocol
9873                      * for the "old" passwords in the original and
9874                      * password-change messages to be the same, and
9875                      * apparently some Cisco kit supports password change
9876                      * by the user entering a blank password originally
9877                      * and the real password subsequently, so,
9878                      * reluctantly, we prompt for the old password again.
9879                      *
9880                      * (On the other hand, some servers don't even bother
9881                      * to check this field.)
9882                      */
9883                     add_prompt(s->cur_prompt,
9884                                dupstr("Current password (blank for previously entered password): "),
9885                                FALSE);
9886                     add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9887                                FALSE);
9888                     add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9889                                FALSE);
9890
9891                     /*
9892                      * Loop until the user manages to enter the same
9893                      * password twice.
9894                      */
9895                     while (!got_new) {
9896
9897                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
9898                         while (ret < 0) {
9899                             ssh->send_ok = 1;
9900                             crWaitUntilV(!pktin);
9901                             ret = get_userpass_input(s->cur_prompt, in, inlen);
9902                             ssh->send_ok = 0;
9903                         }
9904                         if (!ret) {
9905                             /*
9906                              * Failed to get responses. Terminate.
9907                              */
9908                             /* burn the evidence */
9909                             free_prompts(s->cur_prompt);
9910                             smemclr(s->password, strlen(s->password));
9911                             sfree(s->password);
9912                             ssh_disconnect(ssh, NULL, "Unable to authenticate",
9913                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9914                                            TRUE);
9915                             crStopV;
9916                         }
9917
9918                         /*
9919                          * If the user specified a new original password
9920                          * (IYSWIM), overwrite any previously specified
9921                          * one.
9922                          * (A side effect is that the user doesn't have to
9923                          * re-enter it if they louse up the new password.)
9924                          */
9925                         if (s->cur_prompt->prompts[0]->result[0]) {
9926                             smemclr(s->password, strlen(s->password));
9927                                 /* burn the evidence */
9928                             sfree(s->password);
9929                             s->password =
9930                                 dupstr(s->cur_prompt->prompts[0]->result);
9931                         }
9932
9933                         /*
9934                          * Check the two new passwords match.
9935                          */
9936                         got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9937                                           s->cur_prompt->prompts[2]->result)
9938                                    == 0);
9939                         if (!got_new)
9940                             /* They don't. Silly user. */
9941                             c_write_str(ssh, "Passwords do not match\r\n");
9942
9943                     }
9944
9945                     /*
9946                      * Send the new password (along with the old one).
9947                      * (see above for padding rationale)
9948                      */
9949                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9950                     ssh2_pkt_addstring(s->pktout, ssh->username);
9951                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
9952                                                         /* service requested */
9953                     ssh2_pkt_addstring(s->pktout, "password");
9954                     ssh2_pkt_addbool(s->pktout, TRUE);
9955                     ssh2_pkt_addstring(s->pktout, s->password);
9956                     ssh2_pkt_addstring(s->pktout,
9957                                        s->cur_prompt->prompts[1]->result);
9958                     free_prompts(s->cur_prompt);
9959                     ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9960                     logevent("Sent new password");
9961                     
9962                     /*
9963                      * Now see what the server has to say about it.
9964                      * (If it's CHANGEREQ again, it's not happy with the
9965                      * new password.)
9966                      */
9967                     crWaitUntilV(pktin);
9968                     changereq_first_time = FALSE;
9969
9970                 }
9971
9972                 /*
9973                  * We need to reexamine the current pktin at the top
9974                  * of the loop. Either:
9975                  *  - we weren't asked to change password at all, in
9976                  *    which case it's a SUCCESS or FAILURE with the
9977                  *    usual meaning
9978                  *  - we sent a new password, and the server was
9979                  *    either OK with it (SUCCESS or FAILURE w/partial
9980                  *    success) or unhappy with the _old_ password
9981                  *    (FAILURE w/o partial success)
9982                  * In any of these cases, we go back to the top of
9983                  * the loop and start again.
9984                  */
9985                 s->gotit = TRUE;
9986
9987                 /*
9988                  * We don't need the old password any more, in any
9989                  * case. Burn the evidence.
9990                  */
9991                 smemclr(s->password, strlen(s->password));
9992                 sfree(s->password);
9993
9994             } else {
9995                 char *str = dupprintf("No supported authentication methods available"
9996                                       " (server sent: %.*s)",
9997                                       methlen, methods);
9998
9999                 ssh_disconnect(ssh, str,
10000                                "No supported authentication methods available",
10001                                SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10002                                FALSE);
10003                 sfree(str);
10004
10005                 crStopV;
10006
10007             }
10008
10009         }
10010     }
10011     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10012
10013     /* Clear up various bits and pieces from authentication. */
10014     if (s->publickey_blob) {
10015         sfree(s->publickey_blob);
10016         sfree(s->publickey_comment);
10017     }
10018     if (s->agent_response)
10019         sfree(s->agent_response);
10020
10021     if (s->userauth_success && !ssh->bare_connection) {
10022         /*
10023          * We've just received USERAUTH_SUCCESS, and we haven't sent any
10024          * packets since. Signal the transport layer to consider enacting
10025          * delayed compression.
10026          *
10027          * (Relying on we_are_in is not sufficient, as
10028          * draft-miller-secsh-compression-delayed is quite clear that it
10029          * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10030          * become set for other reasons.)
10031          */
10032         do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10033     }
10034
10035     ssh->channels = newtree234(ssh_channelcmp);
10036
10037     /*
10038      * Set up handlers for some connection protocol messages, so we
10039      * don't have to handle them repeatedly in this coroutine.
10040      */
10041     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10042         ssh2_msg_channel_window_adjust;
10043     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10044         ssh2_msg_global_request;
10045
10046     /*
10047      * Create the main session channel.
10048      */
10049     if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10050         ssh->mainchan = NULL;
10051     } else {
10052         ssh->mainchan = snew(struct ssh_channel);
10053         ssh->mainchan->ssh = ssh;
10054         ssh2_channel_init(ssh->mainchan);
10055
10056         if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10057             /*
10058              * Just start a direct-tcpip channel and use it as the main
10059              * channel.
10060              */
10061             ssh_send_port_open(ssh->mainchan,
10062                                conf_get_str(ssh->conf, CONF_ssh_nc_host),
10063                                conf_get_int(ssh->conf, CONF_ssh_nc_port),
10064                                "main channel");
10065             ssh->ncmode = TRUE;
10066         } else {
10067             s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10068             logevent("Opening session as main channel");
10069             ssh2_pkt_send(ssh, s->pktout);
10070             ssh->ncmode = FALSE;
10071         }
10072         crWaitUntilV(pktin);
10073         if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10074             bombout(("Server refused to open channel"));
10075             crStopV;
10076             /* FIXME: error data comes back in FAILURE packet */
10077         }
10078         if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10079             bombout(("Server's channel confirmation cited wrong channel"));
10080             crStopV;
10081         }
10082         ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10083         ssh->mainchan->halfopen = FALSE;
10084         ssh->mainchan->type = CHAN_MAINSESSION;
10085         ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10086         ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10087         add234(ssh->channels, ssh->mainchan);
10088         update_specials_menu(ssh->frontend);
10089         logevent("Opened main channel");
10090     }
10091
10092     /*
10093      * Now we have a channel, make dispatch table entries for
10094      * general channel-based messages.
10095      */
10096     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10097     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10098         ssh2_msg_channel_data;
10099     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10100     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10101     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10102         ssh2_msg_channel_open_confirmation;
10103     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10104         ssh2_msg_channel_open_failure;
10105     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10106         ssh2_msg_channel_request;
10107     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10108         ssh2_msg_channel_open;
10109     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10110     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10111
10112     /*
10113      * Now the connection protocol is properly up and running, with
10114      * all those dispatch table entries, so it's safe to let
10115      * downstreams start trying to open extra channels through us.
10116      */
10117     if (ssh->connshare)
10118         share_activate(ssh->connshare, ssh->v_s);
10119
10120     if (ssh->mainchan && ssh_is_simple(ssh)) {
10121         /*
10122          * This message indicates to the server that we promise
10123          * not to try to run any other channel in parallel with
10124          * this one, so it's safe for it to advertise a very large
10125          * window and leave the flow control to TCP.
10126          */
10127         s->pktout = ssh2_chanreq_init(ssh->mainchan,
10128                                       "simple@putty.projects.tartarus.org",
10129                                       NULL, NULL);
10130         ssh2_pkt_send(ssh, s->pktout);
10131     }
10132
10133     /*
10134      * Enable port forwardings.
10135      */
10136     ssh_setup_portfwd(ssh, ssh->conf);
10137
10138     if (ssh->mainchan && !ssh->ncmode) {
10139         /*
10140          * Send the CHANNEL_REQUESTS for the main session channel.
10141          * Each one is handled by its own little asynchronous
10142          * co-routine.
10143          */
10144
10145         /* Potentially enable X11 forwarding. */
10146         if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10147             ssh->x11disp =
10148                 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10149                                   ssh->conf);
10150             if (!ssh->x11disp) {
10151                 /* FIXME: return an error message from x11_setup_display */
10152                 logevent("X11 forwarding not enabled: unable to"
10153                          " initialise X display");
10154             } else {
10155                 ssh->x11auth = x11_invent_fake_auth
10156                     (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10157                 ssh->x11auth->disp = ssh->x11disp;
10158
10159                 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10160             }
10161         }
10162
10163         /* Potentially enable agent forwarding. */
10164         if (ssh_agent_forwarding_permitted(ssh))
10165             ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10166
10167         /* Now allocate a pty for the session. */
10168         if (!conf_get_int(ssh->conf, CONF_nopty))
10169             ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10170
10171         /* Send environment variables. */
10172         ssh2_setup_env(ssh->mainchan, NULL, NULL);
10173
10174         /*
10175          * Start a shell or a remote command. We may have to attempt
10176          * this twice if the config data has provided a second choice
10177          * of command.
10178          */
10179         while (1) {
10180             int subsys;
10181             char *cmd;
10182
10183             if (ssh->fallback_cmd) {
10184                 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10185                 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10186             } else {
10187                 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10188                 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10189             }
10190
10191             if (subsys) {
10192                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10193                                               ssh2_response_authconn, NULL);
10194                 ssh2_pkt_addstring(s->pktout, cmd);
10195             } else if (*cmd) {
10196                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10197                                               ssh2_response_authconn, NULL);
10198                 ssh2_pkt_addstring(s->pktout, cmd);
10199             } else {
10200                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10201                                               ssh2_response_authconn, NULL);
10202             }
10203             ssh2_pkt_send(ssh, s->pktout);
10204
10205             crWaitUntilV(pktin);
10206
10207             if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10208                 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10209                     bombout(("Unexpected response to shell/command request:"
10210                              " packet type %d", pktin->type));
10211                     crStopV;
10212                 }
10213                 /*
10214                  * We failed to start the command. If this is the
10215                  * fallback command, we really are finished; if it's
10216                  * not, and if the fallback command exists, try falling
10217                  * back to it before complaining.
10218                  */
10219                 if (!ssh->fallback_cmd &&
10220                     *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10221                     logevent("Primary command failed; attempting fallback");
10222                     ssh->fallback_cmd = TRUE;
10223                     continue;
10224                 }
10225                 bombout(("Server refused to start a shell/command"));
10226                 crStopV;
10227             } else {
10228                 logevent("Started a shell/command");
10229             }
10230             break;
10231         }
10232     } else {
10233         ssh->editing = ssh->echoing = TRUE;
10234     }
10235
10236     ssh->state = SSH_STATE_SESSION;
10237     if (ssh->size_needed)
10238         ssh_size(ssh, ssh->term_width, ssh->term_height);
10239     if (ssh->eof_needed)
10240         ssh_special(ssh, TS_EOF);
10241
10242     /*
10243      * Transfer data!
10244      */
10245     if (ssh->ldisc)
10246         ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
10247     if (ssh->mainchan)
10248         ssh->send_ok = 1;
10249     while (1) {
10250         crReturnV;
10251         s->try_send = FALSE;
10252         if (pktin) {
10253
10254             /*
10255              * _All_ the connection-layer packets we expect to
10256              * receive are now handled by the dispatch table.
10257              * Anything that reaches here must be bogus.
10258              */
10259
10260             bombout(("Strange packet received: type %d", pktin->type));
10261             crStopV;
10262         } else if (ssh->mainchan) {
10263             /*
10264              * We have spare data. Add it to the channel buffer.
10265              */
10266             ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10267             s->try_send = TRUE;
10268         }
10269         if (s->try_send) {
10270             int i;
10271             struct ssh_channel *c;
10272             /*
10273              * Try to send data on all channels if we can.
10274              */
10275             for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10276                 ssh2_try_send_and_unthrottle(ssh, c);
10277         }
10278     }
10279
10280     crFinishV;
10281 }
10282
10283 /*
10284  * Handlers for SSH-2 messages that might arrive at any moment.
10285  */
10286 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10287 {
10288     /* log reason code in disconnect message */
10289     char *buf, *msg;
10290     int reason, msglen;
10291
10292     reason = ssh_pkt_getuint32(pktin);
10293     ssh_pkt_getstring(pktin, &msg, &msglen);
10294
10295     if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10296         buf = dupprintf("Received disconnect message (%s)",
10297                         ssh2_disconnect_reasons[reason]);
10298     } else {
10299         buf = dupprintf("Received disconnect message (unknown"
10300                         " type %d)", reason);
10301     }
10302     logevent(buf);
10303     sfree(buf);
10304     buf = dupprintf("Disconnection message text: %.*s",
10305                     msglen, msg);
10306     logevent(buf);
10307     bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10308              reason,
10309              (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10310              ssh2_disconnect_reasons[reason] : "unknown",
10311              msglen, msg));
10312     sfree(buf);
10313 }
10314
10315 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10316 {
10317     /* log the debug message */
10318     char *msg;
10319     int msglen;
10320
10321     /* XXX maybe we should actually take notice of the return value */
10322     ssh2_pkt_getbool(pktin);
10323     ssh_pkt_getstring(pktin, &msg, &msglen);
10324
10325     logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10326 }
10327
10328 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10329 {
10330     do_ssh2_transport(ssh, NULL, 0, pktin);
10331 }
10332
10333 /*
10334  * Called if we receive a packet that isn't allowed by the protocol.
10335  * This only applies to packets whose meaning PuTTY understands.
10336  * Entirely unknown packets are handled below.
10337  */
10338 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10339 {
10340     char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10341                           ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10342                                         pktin->type));
10343     ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10344     sfree(buf);
10345 }
10346
10347 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10348 {
10349     struct Packet *pktout;
10350     pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10351     ssh2_pkt_adduint32(pktout, pktin->sequence);
10352     /*
10353      * UNIMPLEMENTED messages MUST appear in the same order as the
10354      * messages they respond to. Hence, never queue them.
10355      */
10356     ssh2_pkt_send_noqueue(ssh, pktout);
10357 }
10358
10359 /*
10360  * Handle the top-level SSH-2 protocol.
10361  */
10362 static void ssh2_protocol_setup(Ssh ssh)
10363 {
10364     int i;
10365
10366     /*
10367      * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10368      */
10369     for (i = 0; i < 256; i++)
10370         ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10371
10372     /*
10373      * Initially, we only accept transport messages (and a few generic
10374      * ones).  do_ssh2_authconn will add more when it starts.
10375      * Messages that are understood but not currently acceptable go to
10376      * ssh2_msg_unexpected.
10377      */
10378     ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10379     ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10380     ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10381     ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10382     ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10383     ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10384     ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10385     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10386     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10387     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10388     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10389     ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10390     ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10391     ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10392     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10393     ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10394     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10395     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10396     ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10397     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10398     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10399     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10400     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10401     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10402     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10403     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10404     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10405     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10406     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10407     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10408     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10409     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10410     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10411
10412     /*
10413      * These messages have a special handler from the start.
10414      */
10415     ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10416     ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10417     ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10418 }
10419
10420 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10421 {
10422     int i;
10423
10424     /*
10425      * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10426      */
10427     for (i = 0; i < 256; i++)
10428         ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10429
10430     /*
10431      * Initially, we set all ssh-connection messages to 'unexpected';
10432      * do_ssh2_authconn will fill things in properly. We also handle a
10433      * couple of messages from the transport protocol which aren't
10434      * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10435      * DISCONNECT).
10436      */
10437     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10438     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10439     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10440     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10441     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10442     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10443     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10444     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10445     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10446     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10447     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10448     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10449     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10450     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10451
10452     ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10453
10454     /*
10455      * These messages have a special handler from the start.
10456      */
10457     ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10458     ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10459     ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10460 }
10461
10462 static void ssh2_timer(void *ctx, unsigned long now)
10463 {
10464     Ssh ssh = (Ssh)ctx;
10465
10466     if (ssh->state == SSH_STATE_CLOSED)
10467         return;
10468
10469     if (!ssh->kex_in_progress && !ssh->bare_connection &&
10470         conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10471         now == ssh->next_rekey) {
10472         do_ssh2_transport(ssh, "timeout", -1, NULL);
10473     }
10474 }
10475
10476 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10477                           struct Packet *pktin)
10478 {
10479     unsigned char *in = (unsigned char *)vin;
10480     if (ssh->state == SSH_STATE_CLOSED)
10481         return;
10482
10483     if (pktin) {
10484         ssh->incoming_data_size += pktin->encrypted_len;
10485         if (!ssh->kex_in_progress &&
10486             ssh->max_data_size != 0 &&
10487             ssh->incoming_data_size > ssh->max_data_size)
10488             do_ssh2_transport(ssh, "too much data received", -1, NULL);
10489     }
10490
10491     if (pktin)
10492         ssh->packet_dispatch[pktin->type](ssh, pktin);
10493     else if (!ssh->protocol_initial_phase_done)
10494         do_ssh2_transport(ssh, in, inlen, pktin);
10495     else
10496         do_ssh2_authconn(ssh, in, inlen, pktin);
10497 }
10498
10499 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10500                                           struct Packet *pktin)
10501 {
10502     unsigned char *in = (unsigned char *)vin;
10503     if (ssh->state == SSH_STATE_CLOSED)
10504         return;
10505
10506     if (pktin)
10507         ssh->packet_dispatch[pktin->type](ssh, pktin);
10508     else
10509         do_ssh2_authconn(ssh, in, inlen, pktin);
10510 }
10511
10512 static void ssh_cache_conf_values(Ssh ssh)
10513 {
10514     ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10515 }
10516
10517 /*
10518  * Called to set up the connection.
10519  *
10520  * Returns an error message, or NULL on success.
10521  */
10522 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10523                             Conf *conf, char *host, int port, char **realhost,
10524                             int nodelay, int keepalive)
10525 {
10526     const char *p;
10527     Ssh ssh;
10528
10529     ssh = snew(struct ssh_tag);
10530     ssh->conf = conf_copy(conf);
10531     ssh_cache_conf_values(ssh);
10532     ssh->version = 0;                  /* when not ready yet */
10533     ssh->s = NULL;
10534     ssh->cipher = NULL;
10535     ssh->v1_cipher_ctx = NULL;
10536     ssh->crcda_ctx = NULL;
10537     ssh->cscipher = NULL;
10538     ssh->cs_cipher_ctx = NULL;
10539     ssh->sccipher = NULL;
10540     ssh->sc_cipher_ctx = NULL;
10541     ssh->csmac = NULL;
10542     ssh->cs_mac_ctx = NULL;
10543     ssh->scmac = NULL;
10544     ssh->sc_mac_ctx = NULL;
10545     ssh->cscomp = NULL;
10546     ssh->cs_comp_ctx = NULL;
10547     ssh->sccomp = NULL;
10548     ssh->sc_comp_ctx = NULL;
10549     ssh->kex = NULL;
10550     ssh->kex_ctx = NULL;
10551     ssh->hostkey = NULL;
10552     ssh->hostkey_str = NULL;
10553     ssh->exitcode = -1;
10554     ssh->close_expected = FALSE;
10555     ssh->clean_exit = FALSE;
10556     ssh->state = SSH_STATE_PREPACKET;
10557     ssh->size_needed = FALSE;
10558     ssh->eof_needed = FALSE;
10559     ssh->ldisc = NULL;
10560     ssh->logctx = NULL;
10561     ssh->deferred_send_data = NULL;
10562     ssh->deferred_len = 0;
10563     ssh->deferred_size = 0;
10564     ssh->fallback_cmd = 0;
10565     ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10566     ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10567     ssh->x11disp = NULL;
10568     ssh->x11auth = NULL;
10569     ssh->x11authtree = newtree234(x11_authcmp);
10570     ssh->v1_compressing = FALSE;
10571     ssh->v2_outgoing_sequence = 0;
10572     ssh->ssh1_rdpkt_crstate = 0;
10573     ssh->ssh2_rdpkt_crstate = 0;
10574     ssh->ssh2_bare_rdpkt_crstate = 0;
10575     ssh->ssh_gotdata_crstate = 0;
10576     ssh->do_ssh1_connection_crstate = 0;
10577     ssh->do_ssh_init_state = NULL;
10578     ssh->do_ssh_connection_init_state = NULL;
10579     ssh->do_ssh1_login_state = NULL;
10580     ssh->do_ssh2_transport_state = NULL;
10581     ssh->do_ssh2_authconn_state = NULL;
10582     ssh->v_c = NULL;
10583     ssh->v_s = NULL;
10584     ssh->mainchan = NULL;
10585     ssh->throttled_all = 0;
10586     ssh->v1_stdout_throttling = 0;
10587     ssh->queue = NULL;
10588     ssh->queuelen = ssh->queuesize = 0;
10589     ssh->queueing = FALSE;
10590     ssh->qhead = ssh->qtail = NULL;
10591     ssh->deferred_rekey_reason = NULL;
10592     bufchain_init(&ssh->queued_incoming_data);
10593     ssh->frozen = FALSE;
10594     ssh->username = NULL;
10595     ssh->sent_console_eof = FALSE;
10596     ssh->got_pty = FALSE;
10597     ssh->bare_connection = FALSE;
10598     ssh->attempting_connshare = FALSE;
10599
10600     *backend_handle = ssh;
10601
10602 #ifdef MSCRYPTOAPI
10603     if (crypto_startup() == 0)
10604         return "Microsoft high encryption pack not installed!";
10605 #endif
10606
10607     ssh->frontend = frontend_handle;
10608     ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10609     ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10610
10611     ssh->channels = NULL;
10612     ssh->rportfwds = NULL;
10613     ssh->portfwds = NULL;
10614
10615     ssh->send_ok = 0;
10616     ssh->editing = 0;
10617     ssh->echoing = 0;
10618     ssh->conn_throttle_count = 0;
10619     ssh->overall_bufsize = 0;
10620     ssh->fallback_cmd = 0;
10621
10622     ssh->protocol = NULL;
10623
10624     ssh->protocol_initial_phase_done = FALSE;
10625
10626     ssh->pinger = NULL;
10627
10628     ssh->incoming_data_size = ssh->outgoing_data_size =
10629         ssh->deferred_data_size = 0L;
10630     ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10631                                                       CONF_ssh_rekey_data));
10632     ssh->kex_in_progress = FALSE;
10633
10634 #ifndef NO_GSSAPI
10635     ssh->gsslibs = NULL;
10636 #endif
10637
10638     random_ref(); /* do this now - may be needed by sharing setup code */
10639
10640     p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10641     if (p != NULL) {
10642         random_unref();
10643         return p;
10644     }
10645
10646     return NULL;
10647 }
10648
10649 static void ssh_free(void *handle)
10650 {
10651     Ssh ssh = (Ssh) handle;
10652     struct ssh_channel *c;
10653     struct ssh_rportfwd *pf;
10654     struct X11FakeAuth *auth;
10655
10656     if (ssh->v1_cipher_ctx)
10657         ssh->cipher->free_context(ssh->v1_cipher_ctx);
10658     if (ssh->cs_cipher_ctx)
10659         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10660     if (ssh->sc_cipher_ctx)
10661         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10662     if (ssh->cs_mac_ctx)
10663         ssh->csmac->free_context(ssh->cs_mac_ctx);
10664     if (ssh->sc_mac_ctx)
10665         ssh->scmac->free_context(ssh->sc_mac_ctx);
10666     if (ssh->cs_comp_ctx) {
10667         if (ssh->cscomp)
10668             ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10669         else
10670             zlib_compress_cleanup(ssh->cs_comp_ctx);
10671     }
10672     if (ssh->sc_comp_ctx) {
10673         if (ssh->sccomp)
10674             ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10675         else
10676             zlib_decompress_cleanup(ssh->sc_comp_ctx);
10677     }
10678     if (ssh->kex_ctx)
10679         dh_cleanup(ssh->kex_ctx);
10680     sfree(ssh->savedhost);
10681
10682     while (ssh->queuelen-- > 0)
10683         ssh_free_packet(ssh->queue[ssh->queuelen]);
10684     sfree(ssh->queue);
10685
10686     while (ssh->qhead) {
10687         struct queued_handler *qh = ssh->qhead;
10688         ssh->qhead = qh->next;
10689         sfree(qh);
10690     }
10691     ssh->qhead = ssh->qtail = NULL;
10692
10693     if (ssh->channels) {
10694         while ((c = delpos234(ssh->channels, 0)) != NULL) {
10695             switch (c->type) {
10696               case CHAN_X11:
10697                 if (c->u.x11.xconn != NULL)
10698                     x11_close(c->u.x11.xconn);
10699                 break;
10700               case CHAN_SOCKDATA:
10701               case CHAN_SOCKDATA_DORMANT:
10702                 if (c->u.pfd.pf != NULL)
10703                     pfd_close(c->u.pfd.pf);
10704                 break;
10705             }
10706             if (ssh->version == 2) {
10707                 struct outstanding_channel_request *ocr, *nocr;
10708                 ocr = c->v.v2.chanreq_head;
10709                 while (ocr) {
10710                     ocr->handler(c, NULL, ocr->ctx);
10711                     nocr = ocr->next;
10712                     sfree(ocr);
10713                     ocr = nocr;
10714                 }
10715                 bufchain_clear(&c->v.v2.outbuffer);
10716             }
10717             sfree(c);
10718         }
10719         freetree234(ssh->channels);
10720         ssh->channels = NULL;
10721     }
10722
10723     if (ssh->connshare)
10724         sharestate_free(ssh->connshare);
10725
10726     if (ssh->rportfwds) {
10727         while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10728             free_rportfwd(pf);
10729         freetree234(ssh->rportfwds);
10730         ssh->rportfwds = NULL;
10731     }
10732     sfree(ssh->deferred_send_data);
10733     if (ssh->x11disp)
10734         x11_free_display(ssh->x11disp);
10735     while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10736         x11_free_fake_auth(auth);
10737     freetree234(ssh->x11authtree);
10738     sfree(ssh->do_ssh_init_state);
10739     sfree(ssh->do_ssh1_login_state);
10740     sfree(ssh->do_ssh2_transport_state);
10741     sfree(ssh->do_ssh2_authconn_state);
10742     sfree(ssh->v_c);
10743     sfree(ssh->v_s);
10744     sfree(ssh->fullhostname);
10745     sfree(ssh->hostkey_str);
10746     if (ssh->crcda_ctx) {
10747         crcda_free_context(ssh->crcda_ctx);
10748         ssh->crcda_ctx = NULL;
10749     }
10750     if (ssh->s)
10751         ssh_do_close(ssh, TRUE);
10752     expire_timer_context(ssh);
10753     if (ssh->pinger)
10754         pinger_free(ssh->pinger);
10755     bufchain_clear(&ssh->queued_incoming_data);
10756     sfree(ssh->username);
10757     conf_free(ssh->conf);
10758 #ifndef NO_GSSAPI
10759     if (ssh->gsslibs)
10760         ssh_gss_cleanup(ssh->gsslibs);
10761 #endif
10762     sfree(ssh);
10763
10764     random_unref();
10765 }
10766
10767 /*
10768  * Reconfigure the SSH backend.
10769  */
10770 static void ssh_reconfig(void *handle, Conf *conf)
10771 {
10772     Ssh ssh = (Ssh) handle;
10773     char *rekeying = NULL, rekey_mandatory = FALSE;
10774     unsigned long old_max_data_size;
10775     int i, rekey_time;
10776
10777     pinger_reconfig(ssh->pinger, ssh->conf, conf);
10778     if (ssh->portfwds)
10779         ssh_setup_portfwd(ssh, conf);
10780
10781     rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10782     if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10783         rekey_time != 0) {
10784         unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10785         unsigned long now = GETTICKCOUNT();
10786
10787         if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10788             rekeying = "timeout shortened";
10789         } else {
10790             ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10791         }
10792     }
10793
10794     old_max_data_size = ssh->max_data_size;
10795     ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10796                                                       CONF_ssh_rekey_data));
10797     if (old_max_data_size != ssh->max_data_size &&
10798         ssh->max_data_size != 0) {
10799         if (ssh->outgoing_data_size > ssh->max_data_size ||
10800             ssh->incoming_data_size > ssh->max_data_size)
10801             rekeying = "data limit lowered";
10802     }
10803
10804     if (conf_get_int(ssh->conf, CONF_compression) !=
10805         conf_get_int(conf, CONF_compression)) {
10806         rekeying = "compression setting changed";
10807         rekey_mandatory = TRUE;
10808     }
10809
10810     for (i = 0; i < CIPHER_MAX; i++)
10811         if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10812             conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10813         rekeying = "cipher settings changed";
10814         rekey_mandatory = TRUE;
10815     }
10816     if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10817         conf_get_int(conf, CONF_ssh2_des_cbc)) {
10818         rekeying = "cipher settings changed";
10819         rekey_mandatory = TRUE;
10820     }
10821
10822     conf_free(ssh->conf);
10823     ssh->conf = conf_copy(conf);
10824     ssh_cache_conf_values(ssh);
10825
10826     if (!ssh->bare_connection && rekeying) {
10827         if (!ssh->kex_in_progress) {
10828             do_ssh2_transport(ssh, rekeying, -1, NULL);
10829         } else if (rekey_mandatory) {
10830             ssh->deferred_rekey_reason = rekeying;
10831         }
10832     }
10833 }
10834
10835 /*
10836  * Called to send data down the SSH connection.
10837  */
10838 static int ssh_send(void *handle, char *buf, int len)
10839 {
10840     Ssh ssh = (Ssh) handle;
10841
10842     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10843         return 0;
10844
10845     ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10846
10847     return ssh_sendbuffer(ssh);
10848 }
10849
10850 /*
10851  * Called to query the current amount of buffered stdin data.
10852  */
10853 static int ssh_sendbuffer(void *handle)
10854 {
10855     Ssh ssh = (Ssh) handle;
10856     int override_value;
10857
10858     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10859         return 0;
10860
10861     /*
10862      * If the SSH socket itself has backed up, add the total backup
10863      * size on that to any individual buffer on the stdin channel.
10864      */
10865     override_value = 0;
10866     if (ssh->throttled_all)
10867         override_value = ssh->overall_bufsize;
10868
10869     if (ssh->version == 1) {
10870         return override_value;
10871     } else if (ssh->version == 2) {
10872         if (!ssh->mainchan)
10873             return override_value;
10874         else
10875             return (override_value +
10876                     bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10877     }
10878
10879     return 0;
10880 }
10881
10882 /*
10883  * Called to set the size of the window from SSH's POV.
10884  */
10885 static void ssh_size(void *handle, int width, int height)
10886 {
10887     Ssh ssh = (Ssh) handle;
10888     struct Packet *pktout;
10889
10890     ssh->term_width = width;
10891     ssh->term_height = height;
10892
10893     switch (ssh->state) {
10894       case SSH_STATE_BEFORE_SIZE:
10895       case SSH_STATE_PREPACKET:
10896       case SSH_STATE_CLOSED:
10897         break;                         /* do nothing */
10898       case SSH_STATE_INTERMED:
10899         ssh->size_needed = TRUE;       /* buffer for later */
10900         break;
10901       case SSH_STATE_SESSION:
10902         if (!conf_get_int(ssh->conf, CONF_nopty)) {
10903             if (ssh->version == 1) {
10904                 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10905                             PKT_INT, ssh->term_height,
10906                             PKT_INT, ssh->term_width,
10907                             PKT_INT, 0, PKT_INT, 0, PKT_END);
10908             } else if (ssh->mainchan) {
10909                 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10910                                            NULL, NULL);
10911                 ssh2_pkt_adduint32(pktout, ssh->term_width);
10912                 ssh2_pkt_adduint32(pktout, ssh->term_height);
10913                 ssh2_pkt_adduint32(pktout, 0);
10914                 ssh2_pkt_adduint32(pktout, 0);
10915                 ssh2_pkt_send(ssh, pktout);
10916             }
10917         }
10918         break;
10919     }
10920 }
10921
10922 /*
10923  * Return a list of the special codes that make sense in this
10924  * protocol.
10925  */
10926 static const struct telnet_special *ssh_get_specials(void *handle)
10927 {
10928     static const struct telnet_special ssh1_ignore_special[] = {
10929         {"IGNORE message", TS_NOP}
10930     };
10931     static const struct telnet_special ssh2_ignore_special[] = {
10932         {"IGNORE message", TS_NOP},
10933     };
10934     static const struct telnet_special ssh2_rekey_special[] = {
10935         {"Repeat key exchange", TS_REKEY},
10936     };
10937     static const struct telnet_special ssh2_session_specials[] = {
10938         {NULL, TS_SEP},
10939         {"Break", TS_BRK},
10940         /* These are the signal names defined by RFC 4254.
10941          * They include all the ISO C signals, but are a subset of the POSIX
10942          * required signals. */
10943         {"SIGINT (Interrupt)", TS_SIGINT},
10944         {"SIGTERM (Terminate)", TS_SIGTERM},
10945         {"SIGKILL (Kill)", TS_SIGKILL},
10946         {"SIGQUIT (Quit)", TS_SIGQUIT},
10947         {"SIGHUP (Hangup)", TS_SIGHUP},
10948         {"More signals", TS_SUBMENU},
10949           {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10950           {"SIGFPE",  TS_SIGFPE},  {"SIGILL",  TS_SIGILL},
10951           {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10952           {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10953         {NULL, TS_EXITMENU}
10954     };
10955     static const struct telnet_special specials_end[] = {
10956         {NULL, TS_EXITMENU}
10957     };
10958     /* XXX review this length for any changes: */
10959     static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10960                                               lenof(ssh2_rekey_special) +
10961                                               lenof(ssh2_session_specials) +
10962                                               lenof(specials_end)];
10963     Ssh ssh = (Ssh) handle;
10964     int i = 0;
10965 #define ADD_SPECIALS(name) \
10966     do { \
10967         assert((i + lenof(name)) <= lenof(ssh_specials)); \
10968         memcpy(&ssh_specials[i], name, sizeof name); \
10969         i += lenof(name); \
10970     } while(0)
10971
10972     if (ssh->version == 1) {
10973         /* Don't bother offering IGNORE if we've decided the remote
10974          * won't cope with it, since we wouldn't bother sending it if
10975          * asked anyway. */
10976         if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10977             ADD_SPECIALS(ssh1_ignore_special);
10978     } else if (ssh->version == 2) {
10979         if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10980             ADD_SPECIALS(ssh2_ignore_special);
10981         if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
10982             ADD_SPECIALS(ssh2_rekey_special);
10983         if (ssh->mainchan)
10984             ADD_SPECIALS(ssh2_session_specials);
10985     } /* else we're not ready yet */
10986
10987     if (i) {
10988         ADD_SPECIALS(specials_end);
10989         return ssh_specials;
10990     } else {
10991         return NULL;
10992     }
10993 #undef ADD_SPECIALS
10994 }
10995
10996 /*
10997  * Send special codes. TS_EOF is useful for `plink', so you
10998  * can send an EOF and collect resulting output (e.g. `plink
10999  * hostname sort').
11000  */
11001 static void ssh_special(void *handle, Telnet_Special code)
11002 {
11003     Ssh ssh = (Ssh) handle;
11004     struct Packet *pktout;
11005
11006     if (code == TS_EOF) {
11007         if (ssh->state != SSH_STATE_SESSION) {
11008             /*
11009              * Buffer the EOF in case we are pre-SESSION, so we can
11010              * send it as soon as we reach SESSION.
11011              */
11012             if (code == TS_EOF)
11013                 ssh->eof_needed = TRUE;
11014             return;
11015         }
11016         if (ssh->version == 1) {
11017             send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11018         } else if (ssh->mainchan) {
11019             sshfwd_write_eof(ssh->mainchan);
11020             ssh->send_ok = 0;          /* now stop trying to read from stdin */
11021         }
11022         logevent("Sent EOF message");
11023     } else if (code == TS_PING || code == TS_NOP) {
11024         if (ssh->state == SSH_STATE_CLOSED
11025             || ssh->state == SSH_STATE_PREPACKET) return;
11026         if (ssh->version == 1) {
11027             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11028                 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11029         } else {
11030             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11031                 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11032                 ssh2_pkt_addstring_start(pktout);
11033                 ssh2_pkt_send_noqueue(ssh, pktout);
11034             }
11035         }
11036     } else if (code == TS_REKEY) {
11037         if (!ssh->kex_in_progress && !ssh->bare_connection &&
11038             ssh->version == 2) {
11039             do_ssh2_transport(ssh, "at user request", -1, NULL);
11040         }
11041     } else if (code == TS_BRK) {
11042         if (ssh->state == SSH_STATE_CLOSED
11043             || ssh->state == SSH_STATE_PREPACKET) return;
11044         if (ssh->version == 1) {
11045             logevent("Unable to send BREAK signal in SSH-1");
11046         } else if (ssh->mainchan) {
11047             pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11048             ssh2_pkt_adduint32(pktout, 0);   /* default break length */
11049             ssh2_pkt_send(ssh, pktout);
11050         }
11051     } else {
11052         /* Is is a POSIX signal? */
11053         char *signame = NULL;
11054         if (code == TS_SIGABRT) signame = "ABRT";
11055         if (code == TS_SIGALRM) signame = "ALRM";
11056         if (code == TS_SIGFPE)  signame = "FPE";
11057         if (code == TS_SIGHUP)  signame = "HUP";
11058         if (code == TS_SIGILL)  signame = "ILL";
11059         if (code == TS_SIGINT)  signame = "INT";
11060         if (code == TS_SIGKILL) signame = "KILL";
11061         if (code == TS_SIGPIPE) signame = "PIPE";
11062         if (code == TS_SIGQUIT) signame = "QUIT";
11063         if (code == TS_SIGSEGV) signame = "SEGV";
11064         if (code == TS_SIGTERM) signame = "TERM";
11065         if (code == TS_SIGUSR1) signame = "USR1";
11066         if (code == TS_SIGUSR2) signame = "USR2";
11067         /* The SSH-2 protocol does in principle support arbitrary named
11068          * signals, including signame@domain, but we don't support those. */
11069         if (signame) {
11070             /* It's a signal. */
11071             if (ssh->version == 2 && ssh->mainchan) {
11072                 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11073                 ssh2_pkt_addstring(pktout, signame);
11074                 ssh2_pkt_send(ssh, pktout);
11075                 logeventf(ssh, "Sent signal SIG%s", signame);
11076             }
11077         } else {
11078             /* Never heard of it. Do nothing */
11079         }
11080     }
11081 }
11082
11083 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11084 {
11085     Ssh ssh = (Ssh) handle;
11086     struct ssh_channel *c;
11087     c = snew(struct ssh_channel);
11088
11089     c->ssh = ssh;
11090     ssh2_channel_init(c);
11091     c->halfopen = TRUE;
11092     c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11093     c->u.pfd.pf = pf;
11094     add234(ssh->channels, c);
11095     return c;
11096 }
11097
11098 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11099 {
11100     struct ssh_channel *c;
11101     c = snew(struct ssh_channel);
11102
11103     c->ssh = ssh;
11104     ssh2_channel_init(c);
11105     c->type = CHAN_SHARING;
11106     c->u.sharing.ctx = sharing_ctx;
11107     add234(ssh->channels, c);
11108     return c->localid;
11109 }
11110
11111 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11112 {
11113     struct ssh_channel *c;
11114
11115     c = find234(ssh->channels, &localid, ssh_channelfind);
11116     if (c)
11117         ssh_channel_destroy(c);
11118 }
11119
11120 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11121                                      const void *data, int datalen,
11122                                      const char *additional_log_text)
11123 {
11124     struct Packet *pkt;
11125
11126     pkt = ssh2_pkt_init(type);
11127     pkt->downstream_id = id;
11128     pkt->additional_log_text = additional_log_text;
11129     ssh2_pkt_adddata(pkt, data, datalen);
11130     ssh2_pkt_send(ssh, pkt);
11131 }
11132
11133 /*
11134  * This is called when stdout/stderr (the entity to which
11135  * from_backend sends data) manages to clear some backlog.
11136  */
11137 static void ssh_unthrottle(void *handle, int bufsize)
11138 {
11139     Ssh ssh = (Ssh) handle;
11140     int buflimit;
11141
11142     if (ssh->version == 1) {
11143         if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11144             ssh->v1_stdout_throttling = 0;
11145             ssh_throttle_conn(ssh, -1);
11146         }
11147     } else {
11148         if (ssh->mainchan) {
11149             ssh2_set_window(ssh->mainchan,
11150                             bufsize < ssh->mainchan->v.v2.locmaxwin ?
11151                             ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11152             if (ssh_is_simple(ssh))
11153                 buflimit = 0;
11154             else
11155                 buflimit = ssh->mainchan->v.v2.locmaxwin;
11156             if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11157                 ssh->mainchan->throttling_conn = 0;
11158                 ssh_throttle_conn(ssh, -1);
11159             }
11160         }
11161     }
11162
11163     /*
11164      * Now process any SSH connection data that was stashed in our
11165      * queue while we were frozen.
11166      */
11167     ssh_process_queued_incoming_data(ssh);
11168 }
11169
11170 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11171 {
11172     struct ssh_channel *c = (struct ssh_channel *)channel;
11173     Ssh ssh = c->ssh;
11174     struct Packet *pktout;
11175
11176     logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11177
11178     if (ssh->version == 1) {
11179         send_packet(ssh, SSH1_MSG_PORT_OPEN,
11180                     PKT_INT, c->localid,
11181                     PKT_STR, hostname,
11182                     PKT_INT, port,
11183                     /* PKT_STR, <org:orgport>, */
11184                     PKT_END);
11185     } else {
11186         pktout = ssh2_chanopen_init(c, "direct-tcpip");
11187         {
11188             char *trimmed_host = host_strduptrim(hostname);
11189             ssh2_pkt_addstring(pktout, trimmed_host);
11190             sfree(trimmed_host);
11191         }
11192         ssh2_pkt_adduint32(pktout, port);
11193         /*
11194          * We make up values for the originator data; partly it's
11195          * too much hassle to keep track, and partly I'm not
11196          * convinced the server should be told details like that
11197          * about my local network configuration.
11198          * The "originator IP address" is syntactically a numeric
11199          * IP address, and some servers (e.g., Tectia) get upset
11200          * if it doesn't match this syntax.
11201          */
11202         ssh2_pkt_addstring(pktout, "0.0.0.0");
11203         ssh2_pkt_adduint32(pktout, 0);
11204         ssh2_pkt_send(ssh, pktout);
11205     }
11206 }
11207
11208 static int ssh_connected(void *handle)
11209 {
11210     Ssh ssh = (Ssh) handle;
11211     return ssh->s != NULL;
11212 }
11213
11214 static int ssh_sendok(void *handle)
11215 {
11216     Ssh ssh = (Ssh) handle;
11217     return ssh->send_ok;
11218 }
11219
11220 static int ssh_ldisc(void *handle, int option)
11221 {
11222     Ssh ssh = (Ssh) handle;
11223     if (option == LD_ECHO)
11224         return ssh->echoing;
11225     if (option == LD_EDIT)
11226         return ssh->editing;
11227     return FALSE;
11228 }
11229
11230 static void ssh_provide_ldisc(void *handle, void *ldisc)
11231 {
11232     Ssh ssh = (Ssh) handle;
11233     ssh->ldisc = ldisc;
11234 }
11235
11236 static void ssh_provide_logctx(void *handle, void *logctx)
11237 {
11238     Ssh ssh = (Ssh) handle;
11239     ssh->logctx = logctx;
11240 }
11241
11242 static int ssh_return_exitcode(void *handle)
11243 {
11244     Ssh ssh = (Ssh) handle;
11245     if (ssh->s != NULL)
11246         return -1;
11247     else
11248         return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11249 }
11250
11251 /*
11252  * cfg_info for SSH is the protocol running in this session.
11253  * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11254  * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11255  */
11256 static int ssh_cfg_info(void *handle)
11257 {
11258     Ssh ssh = (Ssh) handle;
11259     if (ssh->version == 0)
11260         return 0; /* don't know yet */
11261     else if (ssh->bare_connection)
11262         return -1;
11263     else
11264         return ssh->version;
11265 }
11266
11267 /*
11268  * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11269  * that fails. This variable is the means by which scp.c can reach
11270  * into the SSH code and find out which one it got.
11271  */
11272 extern int ssh_fallback_cmd(void *handle)
11273 {
11274     Ssh ssh = (Ssh) handle;
11275     return ssh->fallback_cmd;
11276 }
11277
11278 Backend ssh_backend = {
11279     ssh_init,
11280     ssh_free,
11281     ssh_reconfig,
11282     ssh_send,
11283     ssh_sendbuffer,
11284     ssh_size,
11285     ssh_special,
11286     ssh_get_specials,
11287     ssh_connected,
11288     ssh_return_exitcode,
11289     ssh_sendok,
11290     ssh_ldisc,
11291     ssh_provide_ldisc,
11292     ssh_provide_logctx,
11293     ssh_unthrottle,
11294     ssh_cfg_info,
11295     "ssh",
11296     PROT_SSH,
11297     22
11298 };