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