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