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