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