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