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