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