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