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