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