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