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