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