]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Note legacy status of putty.iss.
[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     }
3958
3959     /*
3960      * If we get here (i.e. we left the above while loop via 'break'
3961      * rather than 'return'), that means we've determined that the
3962      * input buffer for the agent forwarding connection doesn't
3963      * contain a complete request.
3964      *
3965      * So if there's potentially more data to come, we can return now,
3966      * and wait for the remote client to send it. But if the remote
3967      * has sent EOF, it would be a mistake to do that, because we'd be
3968      * waiting a long time. So this is the moment to check for EOF,
3969      * and respond appropriately.
3970      */
3971     if (c->closes & CLOSES_RCVD_EOF)
3972         sshfwd_write_eof(c);
3973 }
3974
3975 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3976 {
3977     struct ssh_channel *c = (struct ssh_channel *)cv;
3978
3979     ssh_agentf_got_response(c, reply, replylen);
3980     sfree(reply);
3981
3982     /*
3983      * Now try to extract and send further messages from the channel's
3984      * input-side buffer.
3985      */
3986     ssh_agentf_try_forward(c);
3987 }
3988
3989 /*
3990  * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3991  * non-NULL, otherwise just close the connection. `client_reason' == NULL
3992  * => log `wire_reason'.
3993  */
3994 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3995                            const char *wire_reason,
3996                            int code, int clean_exit)
3997 {
3998     char *error;
3999     if (!client_reason)
4000         client_reason = wire_reason;
4001     if (client_reason)
4002         error = dupprintf("Disconnected: %s", client_reason);
4003     else
4004         error = dupstr("Disconnected");
4005     if (wire_reason) {
4006         if (ssh->version == 1) {
4007             send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
4008                         PKT_END);
4009         } else if (ssh->version == 2) {
4010             struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4011             ssh2_pkt_adduint32(pktout, code);
4012             ssh2_pkt_addstring(pktout, wire_reason);
4013             ssh2_pkt_addstring(pktout, "en");   /* language tag */
4014             ssh2_pkt_send_noqueue(ssh, pktout);
4015         }
4016     }
4017     ssh->close_expected = TRUE;
4018     ssh->clean_exit = clean_exit;
4019     ssh_closing((Plug)ssh, error, 0, 0);
4020     sfree(error);
4021 }
4022
4023 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
4024                                const struct ssh_signkey *ssh2keytype,
4025                                void *ssh2keydata)
4026 {
4027     if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
4028         return -1;                     /* no manual keys configured */
4029     }
4030
4031     if (fingerprint) {
4032         /*
4033          * The fingerprint string we've been given will have things
4034          * like 'ssh-rsa 2048' at the front of it. Strip those off and
4035          * narrow down to just the colon-separated hex block at the
4036          * end of the string.
4037          */
4038         const char *p = strrchr(fingerprint, ' ');
4039         fingerprint = p ? p+1 : fingerprint;
4040         /* Quick sanity checks, including making sure it's in lowercase */
4041         assert(strlen(fingerprint) == 16*3 - 1);
4042         assert(fingerprint[2] == ':');
4043         assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
4044
4045         if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
4046                                  fingerprint))
4047             return 1;                  /* success */
4048     }
4049
4050     if (ssh2keydata) {
4051         /*
4052          * Construct the base64-encoded public key blob and see if
4053          * that's listed.
4054          */
4055         unsigned char *binblob;
4056         char *base64blob;
4057         int binlen, atoms, i;
4058         binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
4059         atoms = (binlen + 2) / 3;
4060         base64blob = snewn(atoms * 4 + 1, char);
4061         for (i = 0; i < atoms; i++)
4062             base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
4063         base64blob[atoms * 4] = '\0';
4064         sfree(binblob);
4065         if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
4066                                  base64blob)) {
4067             sfree(base64blob);
4068             return 1;                  /* success */
4069         }
4070         sfree(base64blob);
4071     }
4072
4073     return 0;
4074 }
4075
4076 /*
4077  * Handle the key exchange and user authentication phases.
4078  */
4079 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
4080                          struct Packet *pktin)
4081 {
4082     int i, j, ret;
4083     unsigned char cookie[8], *ptr;
4084     struct MD5Context md5c;
4085     struct do_ssh1_login_state {
4086         int crLine;
4087         int len;
4088         unsigned char *rsabuf;
4089         const unsigned char *keystr1, *keystr2;
4090         unsigned long supported_ciphers_mask, supported_auths_mask;
4091         int tried_publickey, tried_agent;
4092         int tis_auth_refused, ccard_auth_refused;
4093         unsigned char session_id[16];
4094         int cipher_type;
4095         void *publickey_blob;
4096         int publickey_bloblen;
4097         char *publickey_comment;
4098         int privatekey_available, privatekey_encrypted;
4099         prompts_t *cur_prompt;
4100         char c;
4101         int pwpkt_type;
4102         unsigned char request[5], *response, *p;
4103         int responselen;
4104         int keyi, nkeys;
4105         int authed;
4106         struct RSAKey key;
4107         Bignum challenge;
4108         char *commentp;
4109         int commentlen;
4110         int dlgret;
4111         Filename *keyfile;
4112         struct RSAKey servkey, hostkey;
4113     };
4114     crState(do_ssh1_login_state);
4115
4116     crBeginState;
4117
4118     if (!pktin)
4119         crWaitUntil(pktin);
4120
4121     if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
4122         bombout(("Public key packet not received"));
4123         crStop(0);
4124     }
4125
4126     logevent("Received public keys");
4127
4128     ptr = ssh_pkt_getdata(pktin, 8);
4129     if (!ptr) {
4130         bombout(("SSH-1 public key packet stopped before random cookie"));
4131         crStop(0);
4132     }
4133     memcpy(cookie, ptr, 8);
4134
4135     if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4136         !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) { 
4137         bombout(("Failed to read SSH-1 public keys from public key packet"));
4138         crStop(0);
4139     }
4140
4141     /*
4142      * Log the host key fingerprint.
4143      */
4144     {
4145         char logmsg[80];
4146         logevent("Host key fingerprint is:");
4147         strcpy(logmsg, "      ");
4148         s->hostkey.comment = NULL;
4149         rsa_fingerprint(logmsg + strlen(logmsg),
4150                         sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4151         logevent(logmsg);
4152     }
4153
4154     ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4155     s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4156     s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4157     if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4158         s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4159
4160     ssh->v1_local_protoflags =
4161         ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4162     ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4163
4164     MD5Init(&md5c);
4165     MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4166     MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4167     MD5Update(&md5c, cookie, 8);
4168     MD5Final(s->session_id, &md5c);
4169
4170     for (i = 0; i < 32; i++)
4171         ssh->session_key[i] = random_byte();
4172
4173     /*
4174      * Verify that the `bits' and `bytes' parameters match.
4175      */
4176     if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4177         s->servkey.bits > s->servkey.bytes * 8) {
4178         bombout(("SSH-1 public keys were badly formatted"));
4179         crStop(0);
4180     }
4181
4182     s->len = (s->hostkey.bytes > s->servkey.bytes ?
4183               s->hostkey.bytes : s->servkey.bytes);
4184
4185     s->rsabuf = snewn(s->len, unsigned char);
4186
4187     /*
4188      * Verify the host key.
4189      */
4190     {
4191         /*
4192          * First format the key into a string.
4193          */
4194         int len = rsastr_len(&s->hostkey);
4195         char fingerprint[100];
4196         char *keystr = snewn(len, char);
4197         rsastr_fmt(keystr, &s->hostkey);
4198         rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4199
4200         /* First check against manually configured host keys. */
4201         s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4202         if (s->dlgret == 0) {          /* did not match */
4203             bombout(("Host key did not appear in manually configured list"));
4204             sfree(keystr);
4205             crStop(0);
4206         } else if (s->dlgret < 0) { /* none configured; use standard handling */
4207             ssh_set_frozen(ssh, 1);
4208             s->dlgret = verify_ssh_host_key(ssh->frontend,
4209                                             ssh->savedhost, ssh->savedport,
4210                                             "rsa", keystr, fingerprint,
4211                                             ssh_dialog_callback, ssh);
4212             sfree(keystr);
4213 #ifdef FUZZING
4214             s->dlgret = 1;
4215 #endif
4216             if (s->dlgret < 0) {
4217                 do {
4218                     crReturn(0);
4219                     if (pktin) {
4220                         bombout(("Unexpected data from server while waiting"
4221                                  " for user host key response"));
4222                         crStop(0);
4223                     }
4224                 } while (pktin || inlen > 0);
4225                 s->dlgret = ssh->user_response;
4226             }
4227             ssh_set_frozen(ssh, 0);
4228
4229             if (s->dlgret == 0) {
4230                 ssh_disconnect(ssh, "User aborted at host key verification",
4231                                NULL, 0, TRUE);
4232                 crStop(0);
4233             }
4234         } else {
4235             sfree(keystr);
4236         }
4237     }
4238
4239     for (i = 0; i < 32; i++) {
4240         s->rsabuf[i] = ssh->session_key[i];
4241         if (i < 16)
4242             s->rsabuf[i] ^= s->session_id[i];
4243     }
4244
4245     if (s->hostkey.bytes > s->servkey.bytes) {
4246         ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4247         if (ret)
4248             ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4249     } else {
4250         ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4251         if (ret)
4252             ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4253     }
4254     if (!ret) {
4255         bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4256         crStop(0);      
4257     }
4258
4259     logevent("Encrypted session key");
4260
4261     {
4262         int cipher_chosen = 0, warn = 0;
4263         const char *cipher_string = NULL;
4264         int i;
4265         for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4266             int next_cipher = conf_get_int_int(ssh->conf,
4267                                                CONF_ssh_cipherlist, i);
4268             if (next_cipher == CIPHER_WARN) {
4269                 /* If/when we choose a cipher, warn about it */
4270                 warn = 1;
4271             } else if (next_cipher == CIPHER_AES) {
4272                 /* XXX Probably don't need to mention this. */
4273                 logevent("AES not supported in SSH-1, skipping");
4274             } else {
4275                 switch (next_cipher) {
4276                   case CIPHER_3DES:     s->cipher_type = SSH_CIPHER_3DES;
4277                                         cipher_string = "3DES"; break;
4278                   case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4279                                         cipher_string = "Blowfish"; break;
4280                   case CIPHER_DES:      s->cipher_type = SSH_CIPHER_DES;
4281                                         cipher_string = "single-DES"; break;
4282                 }
4283                 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4284                     cipher_chosen = 1;
4285             }
4286         }
4287         if (!cipher_chosen) {
4288             if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4289                 bombout(("Server violates SSH-1 protocol by not "
4290                          "supporting 3DES encryption"));
4291             else
4292                 /* shouldn't happen */
4293                 bombout(("No supported ciphers found"));
4294             crStop(0);
4295         }
4296
4297         /* Warn about chosen cipher if necessary. */
4298         if (warn) {
4299             ssh_set_frozen(ssh, 1);
4300             s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4301                                ssh_dialog_callback, ssh);
4302             if (s->dlgret < 0) {
4303                 do {
4304                     crReturn(0);
4305                     if (pktin) {
4306                         bombout(("Unexpected data from server while waiting"
4307                                  " for user response"));
4308                         crStop(0);
4309                     }
4310                 } while (pktin || inlen > 0);
4311                 s->dlgret = ssh->user_response;
4312             }
4313             ssh_set_frozen(ssh, 0);
4314             if (s->dlgret == 0) {
4315                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4316                                0, TRUE);
4317                 crStop(0);
4318             }
4319         }
4320     }
4321
4322     switch (s->cipher_type) {
4323       case SSH_CIPHER_3DES:
4324         logevent("Using 3DES encryption");
4325         break;
4326       case SSH_CIPHER_DES:
4327         logevent("Using single-DES encryption");
4328         break;
4329       case SSH_CIPHER_BLOWFISH:
4330         logevent("Using Blowfish encryption");
4331         break;
4332     }
4333
4334     send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4335                 PKT_CHAR, s->cipher_type,
4336                 PKT_DATA, cookie, 8,
4337                 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4338                 PKT_DATA, s->rsabuf, s->len,
4339                 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4340
4341     logevent("Trying to enable encryption...");
4342
4343     sfree(s->rsabuf);
4344
4345     ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4346                    s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4347                    &ssh_3des);
4348     ssh->v1_cipher_ctx = ssh->cipher->make_context();
4349     ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4350     logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4351
4352     ssh->crcda_ctx = crcda_make_context();
4353     logevent("Installing CRC compensation attack detector");
4354
4355     if (s->servkey.modulus) {
4356         sfree(s->servkey.modulus);
4357         s->servkey.modulus = NULL;
4358     }
4359     if (s->servkey.exponent) {
4360         sfree(s->servkey.exponent);
4361         s->servkey.exponent = NULL;
4362     }
4363     if (s->hostkey.modulus) {
4364         sfree(s->hostkey.modulus);
4365         s->hostkey.modulus = NULL;
4366     }
4367     if (s->hostkey.exponent) {
4368         sfree(s->hostkey.exponent);
4369         s->hostkey.exponent = NULL;
4370     }
4371     crWaitUntil(pktin);
4372
4373     if (pktin->type != SSH1_SMSG_SUCCESS) {
4374         bombout(("Encryption not successfully enabled"));
4375         crStop(0);
4376     }
4377
4378     logevent("Successfully started encryption");
4379
4380     fflush(stdout); /* FIXME eh? */
4381     {
4382         if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4383             int ret; /* need not be kept over crReturn */
4384             s->cur_prompt = new_prompts(ssh->frontend);
4385             s->cur_prompt->to_server = TRUE;
4386             s->cur_prompt->name = dupstr("SSH login name");
4387             add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4388             ret = get_userpass_input(s->cur_prompt, NULL, 0);
4389             while (ret < 0) {
4390                 ssh->send_ok = 1;
4391                 crWaitUntil(!pktin);
4392                 ret = get_userpass_input(s->cur_prompt, in, inlen);
4393                 ssh->send_ok = 0;
4394             }
4395             if (!ret) {
4396                 /*
4397                  * Failed to get a username. Terminate.
4398                  */
4399                 free_prompts(s->cur_prompt);
4400                 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4401                 crStop(0);
4402             }
4403             ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4404             free_prompts(s->cur_prompt);
4405         }
4406
4407         send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4408         {
4409             char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4410             logevent(userlog);
4411             if (flags & FLAG_INTERACTIVE &&
4412                 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4413                 c_write_str(ssh, userlog);
4414                 c_write_str(ssh, "\r\n");
4415             }
4416             sfree(userlog);
4417         }
4418     }
4419
4420     crWaitUntil(pktin);
4421
4422     if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4423         /* We must not attempt PK auth. Pretend we've already tried it. */
4424         s->tried_publickey = s->tried_agent = 1;
4425     } else {
4426         s->tried_publickey = s->tried_agent = 0;
4427     }
4428     s->tis_auth_refused = s->ccard_auth_refused = 0;
4429     /*
4430      * Load the public half of any configured keyfile for later use.
4431      */
4432     s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4433     if (!filename_is_null(s->keyfile)) {
4434         int keytype;
4435         logeventf(ssh, "Reading key file \"%.150s\"",
4436                   filename_to_str(s->keyfile));
4437         keytype = key_type(s->keyfile);
4438         if (keytype == SSH_KEYTYPE_SSH1 ||
4439             keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4440             const char *error;
4441             if (rsakey_pubblob(s->keyfile,
4442                                &s->publickey_blob, &s->publickey_bloblen,
4443                                &s->publickey_comment, &error)) {
4444                 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4445                 if (!s->privatekey_available)
4446                     logeventf(ssh, "Key file contains public key only");
4447                 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4448                                                            NULL);
4449             } else {
4450                 char *msgbuf;
4451                 logeventf(ssh, "Unable to load key (%s)", error);
4452                 msgbuf = dupprintf("Unable to load key file "
4453                                    "\"%.150s\" (%s)\r\n",
4454                                    filename_to_str(s->keyfile),
4455                                    error);
4456                 c_write_str(ssh, msgbuf);
4457                 sfree(msgbuf);
4458                 s->publickey_blob = NULL;
4459             }
4460         } else {
4461             char *msgbuf;
4462             logeventf(ssh, "Unable to use this key file (%s)",
4463                       key_type_to_str(keytype));
4464             msgbuf = dupprintf("Unable to use key file \"%.150s\""
4465                                " (%s)\r\n",
4466                                filename_to_str(s->keyfile),
4467                                key_type_to_str(keytype));
4468             c_write_str(ssh, msgbuf);
4469             sfree(msgbuf);
4470             s->publickey_blob = NULL;
4471         }
4472     } else
4473         s->publickey_blob = NULL;
4474
4475     while (pktin->type == SSH1_SMSG_FAILURE) {
4476         s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4477
4478         if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4479             /*
4480              * Attempt RSA authentication using Pageant.
4481              */
4482             void *r;
4483
4484             s->authed = FALSE;
4485             s->tried_agent = 1;
4486             logevent("Pageant is running. Requesting keys.");
4487
4488             /* Request the keys held by the agent. */
4489             PUT_32BIT(s->request, 1);
4490             s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4491             ssh->auth_agent_query = agent_query(
4492                 s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
4493             if (ssh->auth_agent_query) {
4494                 do {
4495                     crReturn(0);
4496                     if (pktin) {
4497                         bombout(("Unexpected data from server while waiting"
4498                                  " for agent response"));
4499                         crStop(0);
4500                     }
4501                 } while (pktin || inlen > 0);
4502                 r = ssh->agent_response;
4503                 s->responselen = ssh->agent_response_len;
4504             }
4505             s->response = (unsigned char *) r;
4506             if (s->response && s->responselen >= 5 &&
4507                 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4508                 s->p = s->response + 5;
4509                 s->nkeys = toint(GET_32BIT(s->p));
4510                 if (s->nkeys < 0) {
4511                     logeventf(ssh, "Pageant reported negative key count %d",
4512                               s->nkeys);
4513                     s->nkeys = 0;
4514                 }
4515                 s->p += 4;
4516                 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4517                 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4518                     unsigned char *pkblob = s->p;
4519                     s->p += 4;
4520                     {
4521                         int n, ok = FALSE;
4522                         do {           /* do while (0) to make breaking easy */
4523                             n = ssh1_read_bignum
4524                                 (s->p, toint(s->responselen-(s->p-s->response)),
4525                                  &s->key.exponent);
4526                             if (n < 0)
4527                                 break;
4528                             s->p += n;
4529                             n = ssh1_read_bignum
4530                                 (s->p, toint(s->responselen-(s->p-s->response)),
4531                                  &s->key.modulus);
4532                             if (n < 0)
4533                                 break;
4534                             s->p += n;
4535                             if (s->responselen - (s->p-s->response) < 4)
4536                                 break;
4537                             s->commentlen = toint(GET_32BIT(s->p));
4538                             s->p += 4;
4539                             if (s->commentlen < 0 ||
4540                                 toint(s->responselen - (s->p-s->response)) <
4541                                 s->commentlen)
4542                                 break;
4543                             s->commentp = (char *)s->p;
4544                             s->p += s->commentlen;
4545                             ok = TRUE;
4546                         } while (0);
4547                         if (!ok) {
4548                             logevent("Pageant key list packet was truncated");
4549                             break;
4550                         }
4551                     }
4552                     if (s->publickey_blob) {
4553                         if (!memcmp(pkblob, s->publickey_blob,
4554                                     s->publickey_bloblen)) {
4555                             logeventf(ssh, "Pageant key #%d matches "
4556                                       "configured key file", s->keyi);
4557                             s->tried_publickey = 1;
4558                         } else
4559                             /* Skip non-configured key */
4560                             continue;
4561                     }
4562                     logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4563                     send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4564                                 PKT_BIGNUM, s->key.modulus, PKT_END);
4565                     crWaitUntil(pktin);
4566                     if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4567                         logevent("Key refused");
4568                         continue;
4569                     }
4570                     logevent("Received RSA challenge");
4571                     if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4572                         bombout(("Server's RSA challenge was badly formatted"));
4573                         crStop(0);
4574                     }
4575
4576                     {
4577                         char *agentreq, *q, *ret;
4578                         void *vret;
4579                         int len, retlen;
4580                         len = 1 + 4;   /* message type, bit count */
4581                         len += ssh1_bignum_length(s->key.exponent);
4582                         len += ssh1_bignum_length(s->key.modulus);
4583                         len += ssh1_bignum_length(s->challenge);
4584                         len += 16;     /* session id */
4585                         len += 4;      /* response format */
4586                         agentreq = snewn(4 + len, char);
4587                         PUT_32BIT(agentreq, len);
4588                         q = agentreq + 4;
4589                         *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4590                         PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4591                         q += 4;
4592                         q += ssh1_write_bignum(q, s->key.exponent);
4593                         q += ssh1_write_bignum(q, s->key.modulus);
4594                         q += ssh1_write_bignum(q, s->challenge);
4595                         memcpy(q, s->session_id, 16);
4596                         q += 16;
4597                         PUT_32BIT(q, 1);        /* response format */
4598                         ssh->auth_agent_query = agent_query(
4599                             agentreq, len + 4, &vret, &retlen,
4600                             ssh_agent_callback, ssh);
4601                         if (ssh->auth_agent_query) {
4602                             sfree(agentreq);
4603                             do {
4604                                 crReturn(0);
4605                                 if (pktin) {
4606                                     bombout(("Unexpected data from server"
4607                                              " while waiting for agent"
4608                                              " response"));
4609                                     crStop(0);
4610                                 }
4611                             } while (pktin || inlen > 0);
4612                             vret = ssh->agent_response;
4613                             retlen = ssh->agent_response_len;
4614                         } else
4615                             sfree(agentreq);
4616                         ret = vret;
4617                         if (ret) {
4618                             if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4619                                 logevent("Sending Pageant's response");
4620                                 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4621                                             PKT_DATA, ret + 5, 16,
4622                                             PKT_END);
4623                                 sfree(ret);
4624                                 crWaitUntil(pktin);
4625                                 if (pktin->type == SSH1_SMSG_SUCCESS) {
4626                                     logevent
4627                                         ("Pageant's response accepted");
4628                                     if (flags & FLAG_VERBOSE) {
4629                                         c_write_str(ssh, "Authenticated using"
4630                                                     " RSA key \"");
4631                                         c_write(ssh, s->commentp,
4632                                                 s->commentlen);
4633                                         c_write_str(ssh, "\" from agent\r\n");
4634                                     }
4635                                     s->authed = TRUE;
4636                                 } else
4637                                     logevent
4638                                         ("Pageant's response not accepted");
4639                             } else {
4640                                 logevent
4641                                     ("Pageant failed to answer challenge");
4642                                 sfree(ret);
4643                             }
4644                         } else {
4645                             logevent("No reply received from Pageant");
4646                         }
4647                     }
4648                     freebn(s->key.exponent);
4649                     freebn(s->key.modulus);
4650                     freebn(s->challenge);
4651                     if (s->authed)
4652                         break;
4653                 }
4654                 sfree(s->response);
4655                 if (s->publickey_blob && !s->tried_publickey)
4656                     logevent("Configured key file not in Pageant");
4657             } else {
4658                 logevent("Failed to get reply from Pageant");
4659             }
4660             if (s->authed)
4661                 break;
4662         }
4663         if (s->publickey_blob && s->privatekey_available &&
4664             !s->tried_publickey) {
4665             /*
4666              * Try public key authentication with the specified
4667              * key file.
4668              */
4669             int got_passphrase; /* need not be kept over crReturn */
4670             if (flags & FLAG_VERBOSE)
4671                 c_write_str(ssh, "Trying public key authentication.\r\n");
4672             s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4673             logeventf(ssh, "Trying public key \"%s\"",
4674                       filename_to_str(s->keyfile));
4675             s->tried_publickey = 1;
4676             got_passphrase = FALSE;
4677             while (!got_passphrase) {
4678                 /*
4679                  * Get a passphrase, if necessary.
4680                  */
4681                 char *passphrase = NULL;    /* only written after crReturn */
4682                 const char *error;
4683                 if (!s->privatekey_encrypted) {
4684                     if (flags & FLAG_VERBOSE)
4685                         c_write_str(ssh, "No passphrase required.\r\n");
4686                     passphrase = NULL;
4687                 } else {
4688                     int ret; /* need not be kept over crReturn */
4689                     s->cur_prompt = new_prompts(ssh->frontend);
4690                     s->cur_prompt->to_server = FALSE;
4691                     s->cur_prompt->name = dupstr("SSH key passphrase");
4692                     add_prompt(s->cur_prompt,
4693                                dupprintf("Passphrase for key \"%.100s\": ",
4694                                          s->publickey_comment), FALSE);
4695                     ret = get_userpass_input(s->cur_prompt, NULL, 0);
4696                     while (ret < 0) {
4697                         ssh->send_ok = 1;
4698                         crWaitUntil(!pktin);
4699                         ret = get_userpass_input(s->cur_prompt, in, inlen);
4700                         ssh->send_ok = 0;
4701                     }
4702                     if (!ret) {
4703                         /* Failed to get a passphrase. Terminate. */
4704                         free_prompts(s->cur_prompt);
4705                         ssh_disconnect(ssh, NULL, "Unable to authenticate",
4706                                        0, TRUE);
4707                         crStop(0);
4708                     }
4709                     passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4710                     free_prompts(s->cur_prompt);
4711                 }
4712                 /*
4713                  * Try decrypting key with passphrase.
4714                  */
4715                 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4716                 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4717                                  &error);
4718                 if (passphrase) {
4719                     smemclr(passphrase, strlen(passphrase));
4720                     sfree(passphrase);
4721                 }
4722                 if (ret == 1) {
4723                     /* Correct passphrase. */
4724                     got_passphrase = TRUE;
4725                 } else if (ret == 0) {
4726                     c_write_str(ssh, "Couldn't load private key from ");
4727                     c_write_str(ssh, filename_to_str(s->keyfile));
4728                     c_write_str(ssh, " (");
4729                     c_write_str(ssh, error);
4730                     c_write_str(ssh, ").\r\n");
4731                     got_passphrase = FALSE;
4732                     break;             /* go and try something else */
4733                 } else if (ret == -1) {
4734                     c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4735                     got_passphrase = FALSE;
4736                     /* and try again */
4737                 } else {
4738                     assert(0 && "unexpected return from loadrsakey()");
4739                     got_passphrase = FALSE;   /* placate optimisers */
4740                 }
4741             }
4742
4743             if (got_passphrase) {
4744
4745                 /*
4746                  * Send a public key attempt.
4747                  */
4748                 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4749                             PKT_BIGNUM, s->key.modulus, PKT_END);
4750
4751                 crWaitUntil(pktin);
4752                 if (pktin->type == SSH1_SMSG_FAILURE) {
4753                     c_write_str(ssh, "Server refused our public key.\r\n");
4754                     continue;          /* go and try something else */
4755                 }
4756                 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4757                     bombout(("Bizarre response to offer of public key"));
4758                     crStop(0);
4759                 }
4760
4761                 {
4762                     int i;
4763                     unsigned char buffer[32];
4764                     Bignum challenge, response;
4765
4766                     if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4767                         bombout(("Server's RSA challenge was badly formatted"));
4768                         crStop(0);
4769                     }
4770                     response = rsadecrypt(challenge, &s->key);
4771                     freebn(s->key.private_exponent);/* burn the evidence */
4772
4773                     for (i = 0; i < 32; i++) {
4774                         buffer[i] = bignum_byte(response, 31 - i);
4775                     }
4776
4777                     MD5Init(&md5c);
4778                     MD5Update(&md5c, buffer, 32);
4779                     MD5Update(&md5c, s->session_id, 16);
4780                     MD5Final(buffer, &md5c);
4781
4782                     send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4783                                 PKT_DATA, buffer, 16, PKT_END);
4784
4785                     freebn(challenge);
4786                     freebn(response);
4787                 }
4788
4789                 crWaitUntil(pktin);
4790                 if (pktin->type == SSH1_SMSG_FAILURE) {
4791                     if (flags & FLAG_VERBOSE)
4792                         c_write_str(ssh, "Failed to authenticate with"
4793                                     " our public key.\r\n");
4794                     continue;          /* go and try something else */
4795                 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4796                     bombout(("Bizarre response to RSA authentication response"));
4797                     crStop(0);
4798                 }
4799
4800                 break;                 /* we're through! */
4801             }
4802
4803         }
4804
4805         /*
4806          * Otherwise, try various forms of password-like authentication.
4807          */
4808         s->cur_prompt = new_prompts(ssh->frontend);
4809
4810         if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4811             (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4812             !s->tis_auth_refused) {
4813             s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4814             logevent("Requested TIS authentication");
4815             send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4816             crWaitUntil(pktin);
4817             if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4818                 logevent("TIS authentication declined");
4819                 if (flags & FLAG_INTERACTIVE)
4820                     c_write_str(ssh, "TIS authentication refused.\r\n");
4821                 s->tis_auth_refused = 1;
4822                 continue;
4823             } else {
4824                 char *challenge;
4825                 int challengelen;
4826                 char *instr_suf, *prompt;
4827
4828                 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4829                 if (!challenge) {
4830                     bombout(("TIS challenge packet was badly formed"));
4831                     crStop(0);
4832                 }
4833                 logevent("Received TIS challenge");
4834                 s->cur_prompt->to_server = TRUE;
4835                 s->cur_prompt->name = dupstr("SSH TIS authentication");
4836                 /* Prompt heuristic comes from OpenSSH */
4837                 if (memchr(challenge, '\n', challengelen)) {
4838                     instr_suf = dupstr("");
4839                     prompt = dupprintf("%.*s", challengelen, challenge);
4840                 } else {
4841                     instr_suf = dupprintf("%.*s", challengelen, challenge);
4842                     prompt = dupstr("Response: ");
4843                 }
4844                 s->cur_prompt->instruction =
4845                     dupprintf("Using TIS authentication.%s%s",
4846                               (*instr_suf) ? "\n" : "",
4847                               instr_suf);
4848                 s->cur_prompt->instr_reqd = TRUE;
4849                 add_prompt(s->cur_prompt, prompt, FALSE);
4850                 sfree(instr_suf);
4851             }
4852         }
4853         if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4854             (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4855             !s->ccard_auth_refused) {
4856             s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4857             logevent("Requested CryptoCard authentication");
4858             send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4859             crWaitUntil(pktin);
4860             if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4861                 logevent("CryptoCard authentication declined");
4862                 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4863                 s->ccard_auth_refused = 1;
4864                 continue;
4865             } else {
4866                 char *challenge;
4867                 int challengelen;
4868                 char *instr_suf, *prompt;
4869
4870                 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4871                 if (!challenge) {
4872                     bombout(("CryptoCard challenge packet was badly formed"));
4873                     crStop(0);
4874                 }
4875                 logevent("Received CryptoCard challenge");
4876                 s->cur_prompt->to_server = TRUE;
4877                 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4878                 s->cur_prompt->name_reqd = FALSE;
4879                 /* Prompt heuristic comes from OpenSSH */
4880                 if (memchr(challenge, '\n', challengelen)) {
4881                     instr_suf = dupstr("");
4882                     prompt = dupprintf("%.*s", challengelen, challenge);
4883                 } else {
4884                     instr_suf = dupprintf("%.*s", challengelen, challenge);
4885                     prompt = dupstr("Response: ");
4886                 }
4887                 s->cur_prompt->instruction =
4888                     dupprintf("Using CryptoCard authentication.%s%s",
4889                               (*instr_suf) ? "\n" : "",
4890                               instr_suf);
4891                 s->cur_prompt->instr_reqd = TRUE;
4892                 add_prompt(s->cur_prompt, prompt, FALSE);
4893                 sfree(instr_suf);
4894             }
4895         }
4896         if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4897             if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4898                 bombout(("No supported authentication methods available"));
4899                 crStop(0);
4900             }
4901             s->cur_prompt->to_server = TRUE;
4902             s->cur_prompt->name = dupstr("SSH password");
4903             add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4904                                                 ssh->username, ssh->savedhost),
4905                        FALSE);
4906         }
4907
4908         /*
4909          * Show password prompt, having first obtained it via a TIS
4910          * or CryptoCard exchange if we're doing TIS or CryptoCard
4911          * authentication.
4912          */
4913         {
4914             int ret; /* need not be kept over crReturn */
4915             ret = get_userpass_input(s->cur_prompt, NULL, 0);
4916             while (ret < 0) {
4917                 ssh->send_ok = 1;
4918                 crWaitUntil(!pktin);
4919                 ret = get_userpass_input(s->cur_prompt, in, inlen);
4920                 ssh->send_ok = 0;
4921             }
4922             if (!ret) {
4923                 /*
4924                  * Failed to get a password (for example
4925                  * because one was supplied on the command line
4926                  * which has already failed to work). Terminate.
4927                  */
4928                 free_prompts(s->cur_prompt);
4929                 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4930                 crStop(0);
4931             }
4932         }
4933
4934         if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4935             /*
4936              * Defence against traffic analysis: we send a
4937              * whole bunch of packets containing strings of
4938              * different lengths. One of these strings is the
4939              * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4940              * The others are all random data in
4941              * SSH1_MSG_IGNORE packets. This way a passive
4942              * listener can't tell which is the password, and
4943              * hence can't deduce the password length.
4944              * 
4945              * Anybody with a password length greater than 16
4946              * bytes is going to have enough entropy in their
4947              * password that a listener won't find it _that_
4948              * much help to know how long it is. So what we'll
4949              * do is:
4950              * 
4951              *  - if password length < 16, we send 15 packets
4952              *    containing string lengths 1 through 15
4953              * 
4954              *  - otherwise, we let N be the nearest multiple
4955              *    of 8 below the password length, and send 8
4956              *    packets containing string lengths N through
4957              *    N+7. This won't obscure the order of
4958              *    magnitude of the password length, but it will
4959              *    introduce a bit of extra uncertainty.
4960              * 
4961              * A few servers can't deal with SSH1_MSG_IGNORE, at
4962              * least in this context. For these servers, we need
4963              * an alternative defence. We make use of the fact
4964              * that the password is interpreted as a C string:
4965              * so we can append a NUL, then some random data.
4966              * 
4967              * A few servers can deal with neither SSH1_MSG_IGNORE
4968              * here _nor_ a padded password string.
4969              * For these servers we are left with no defences
4970              * against password length sniffing.
4971              */
4972             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4973                 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4974                 /*
4975                  * The server can deal with SSH1_MSG_IGNORE, so
4976                  * we can use the primary defence.
4977                  */
4978                 int bottom, top, pwlen, i;
4979                 char *randomstr;
4980
4981                 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4982                 if (pwlen < 16) {
4983                     bottom = 0;    /* zero length passwords are OK! :-) */
4984                     top = 15;
4985                 } else {
4986                     bottom = pwlen & ~7;
4987                     top = bottom + 7;
4988                 }
4989
4990                 assert(pwlen >= bottom && pwlen <= top);
4991
4992                 randomstr = snewn(top + 1, char);
4993
4994                 for (i = bottom; i <= top; i++) {
4995                     if (i == pwlen) {
4996                         defer_packet(ssh, s->pwpkt_type,
4997                                      PKT_STR,s->cur_prompt->prompts[0]->result,
4998                                      PKT_END);
4999                     } else {
5000                         for (j = 0; j < i; j++) {
5001                             do {
5002                                 randomstr[j] = random_byte();
5003                             } while (randomstr[j] == '\0');
5004                         }
5005                         randomstr[i] = '\0';
5006                         defer_packet(ssh, SSH1_MSG_IGNORE,
5007                                      PKT_STR, randomstr, PKT_END);
5008                     }
5009                 }
5010                 logevent("Sending password with camouflage packets");
5011                 ssh_pkt_defersend(ssh);
5012                 sfree(randomstr);
5013             } 
5014             else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
5015                 /*
5016                  * The server can't deal with SSH1_MSG_IGNORE
5017                  * but can deal with padded passwords, so we
5018                  * can use the secondary defence.
5019                  */
5020                 char string[64];
5021                 char *ss;
5022                 int len;
5023
5024                 len = strlen(s->cur_prompt->prompts[0]->result);
5025                 if (len < sizeof(string)) {
5026                     ss = string;
5027                     strcpy(string, s->cur_prompt->prompts[0]->result);
5028                     len++;             /* cover the zero byte */
5029                     while (len < sizeof(string)) {
5030                         string[len++] = (char) random_byte();
5031                     }
5032                 } else {
5033                     ss = s->cur_prompt->prompts[0]->result;
5034                 }
5035                 logevent("Sending length-padded password");
5036                 send_packet(ssh, s->pwpkt_type,
5037                             PKT_INT, len, PKT_DATA, ss, len,
5038                             PKT_END);
5039             } else {
5040                 /*
5041                  * The server is believed unable to cope with
5042                  * any of our password camouflage methods.
5043                  */
5044                 int len;
5045                 len = strlen(s->cur_prompt->prompts[0]->result);
5046                 logevent("Sending unpadded password");
5047                 send_packet(ssh, s->pwpkt_type,
5048                             PKT_INT, len,
5049                             PKT_DATA, s->cur_prompt->prompts[0]->result, len,
5050                             PKT_END);
5051             }
5052         } else {
5053             send_packet(ssh, s->pwpkt_type,
5054                         PKT_STR, s->cur_prompt->prompts[0]->result,
5055                         PKT_END);
5056         }
5057         logevent("Sent password");
5058         free_prompts(s->cur_prompt);
5059         crWaitUntil(pktin);
5060         if (pktin->type == SSH1_SMSG_FAILURE) {
5061             if (flags & FLAG_VERBOSE)
5062                 c_write_str(ssh, "Access denied\r\n");
5063             logevent("Authentication refused");
5064         } else if (pktin->type != SSH1_SMSG_SUCCESS) {
5065             bombout(("Strange packet received, type %d", pktin->type));
5066             crStop(0);
5067         }
5068     }
5069
5070     /* Clear up */
5071     if (s->publickey_blob) {
5072         sfree(s->publickey_blob);
5073         sfree(s->publickey_comment);
5074     }
5075
5076     logevent("Authentication successful");
5077
5078     crFinish(1);
5079 }
5080
5081 static void ssh_channel_try_eof(struct ssh_channel *c)
5082 {
5083     Ssh ssh = c->ssh;
5084     assert(c->pending_eof);          /* precondition for calling us */
5085     if (c->halfopen)
5086         return;                 /* can't close: not even opened yet */
5087     if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
5088         return;              /* can't send EOF: pending outgoing data */
5089
5090     c->pending_eof = FALSE;            /* we're about to send it */
5091     if (ssh->version == 1) {
5092         send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5093                     PKT_END);
5094         c->closes |= CLOSES_SENT_EOF;
5095     } else {
5096         struct Packet *pktout;
5097         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5098         ssh2_pkt_adduint32(pktout, c->remoteid);
5099         ssh2_pkt_send(ssh, pktout);
5100         c->closes |= CLOSES_SENT_EOF;
5101         ssh2_channel_check_close(c);
5102     }
5103 }
5104
5105 Conf *sshfwd_get_conf(struct ssh_channel *c)
5106 {
5107     Ssh ssh = c->ssh;
5108     return ssh->conf;
5109 }
5110
5111 void sshfwd_write_eof(struct ssh_channel *c)
5112 {
5113     Ssh ssh = c->ssh;
5114
5115     if (ssh->state == SSH_STATE_CLOSED)
5116         return;
5117
5118     if (c->closes & CLOSES_SENT_EOF)
5119         return;
5120
5121     c->pending_eof = TRUE;
5122     ssh_channel_try_eof(c);
5123 }
5124
5125 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
5126 {
5127     Ssh ssh = c->ssh;
5128     char *reason;
5129
5130     if (ssh->state == SSH_STATE_CLOSED)
5131         return;
5132
5133     reason = dupprintf("due to local error: %s", err);
5134     ssh_channel_close_local(c, reason);
5135     sfree(reason);
5136     c->pending_eof = FALSE;   /* this will confuse a zombie channel */
5137
5138     ssh2_channel_check_close(c);
5139 }
5140
5141 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5142 {
5143     Ssh ssh = c->ssh;
5144
5145     if (ssh->state == SSH_STATE_CLOSED)
5146         return 0;
5147
5148     return ssh_send_channel_data(c, buf, len);
5149 }
5150
5151 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5152 {
5153     Ssh ssh = c->ssh;
5154
5155     if (ssh->state == SSH_STATE_CLOSED)
5156         return;
5157
5158     ssh_channel_unthrottle(c, bufsize);
5159 }
5160
5161 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5162 {
5163     struct queued_handler *qh = ssh->qhead;
5164
5165     assert(qh != NULL);
5166
5167     assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5168
5169     if (qh->msg1 > 0) {
5170         assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5171         ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5172     }
5173     if (qh->msg2 > 0) {
5174         assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5175         ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5176     }
5177
5178     if (qh->next) {
5179         ssh->qhead = qh->next;
5180
5181         if (ssh->qhead->msg1 > 0) {
5182             ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5183             ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5184         }
5185         if (ssh->qhead->msg2 > 0) {
5186             ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5187             ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5188         }
5189     } else {
5190         ssh->qhead = ssh->qtail = NULL;
5191     }
5192
5193     qh->handler(ssh, pktin, qh->ctx);
5194
5195     sfree(qh);
5196 }
5197
5198 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5199                               chandler_fn_t handler, void *ctx)
5200 {
5201     struct queued_handler *qh;
5202
5203     qh = snew(struct queued_handler);
5204     qh->msg1 = msg1;
5205     qh->msg2 = msg2;
5206     qh->handler = handler;
5207     qh->ctx = ctx;
5208     qh->next = NULL;
5209
5210     if (ssh->qtail == NULL) {
5211         ssh->qhead = qh;
5212
5213         if (qh->msg1 > 0) {
5214             ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5215             ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5216         }
5217         if (qh->msg2 > 0) {
5218             ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5219             ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5220         }
5221     } else {
5222         ssh->qtail->next = qh;
5223     }
5224     ssh->qtail = qh;
5225 }
5226
5227 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5228 {
5229     struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5230
5231     if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5232                         SSH2_MSG_REQUEST_SUCCESS)) {
5233         logeventf(ssh, "Remote port forwarding from %s enabled",
5234                   pf->sportdesc);
5235     } else {
5236         logeventf(ssh, "Remote port forwarding from %s refused",
5237                   pf->sportdesc);
5238
5239         rpf = del234(ssh->rportfwds, pf);
5240         assert(rpf == pf);
5241         pf->pfrec->remote = NULL;
5242         free_rportfwd(pf);
5243     }
5244 }
5245
5246 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5247                                void *share_ctx)
5248 {
5249     struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5250     pf->dhost = NULL;
5251     pf->dport = 0;
5252     pf->share_ctx = share_ctx;
5253     pf->shost = dupstr(shost);
5254     pf->sport = sport;
5255     pf->sportdesc = NULL;
5256     if (!ssh->rportfwds) {
5257         assert(ssh->version == 2);
5258         ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5259     }
5260     if (add234(ssh->rportfwds, pf) != pf) {
5261         sfree(pf->shost);
5262         sfree(pf);
5263         return FALSE;
5264     }
5265     return TRUE;
5266 }
5267
5268 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5269                                                 void *ctx)
5270 {
5271     share_got_pkt_from_server(ctx, pktin->type,
5272                               pktin->body, pktin->length);
5273 }
5274
5275 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5276 {
5277     ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5278                       ssh_sharing_global_request_response, share_ctx);
5279 }
5280
5281 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5282 {
5283     struct ssh_portfwd *epf;
5284     int i;
5285     char *key, *val;
5286
5287     if (!ssh->portfwds) {
5288         ssh->portfwds = newtree234(ssh_portcmp);
5289     } else {
5290         /*
5291          * Go through the existing port forwardings and tag them
5292          * with status==DESTROY. Any that we want to keep will be
5293          * re-enabled (status==KEEP) as we go through the
5294          * configuration and find out which bits are the same as
5295          * they were before.
5296          */
5297         struct ssh_portfwd *epf;
5298         int i;
5299         for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5300             epf->status = DESTROY;
5301     }
5302
5303     for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5304          val != NULL;
5305          val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5306         char *kp, *kp2, *vp, *vp2;
5307         char address_family, type;
5308         int sport,dport,sserv,dserv;
5309         char *sports, *dports, *saddr, *host;
5310
5311         kp = key;
5312
5313         address_family = 'A';
5314         type = 'L';
5315         if (*kp == 'A' || *kp == '4' || *kp == '6')
5316             address_family = *kp++;
5317         if (*kp == 'L' || *kp == 'R')
5318             type = *kp++;
5319
5320         if ((kp2 = host_strchr(kp, ':')) != NULL) {
5321             /*
5322              * There's a colon in the middle of the source port
5323              * string, which means that the part before it is
5324              * actually a source address.
5325              */
5326             char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5327             saddr = host_strduptrim(saddr_tmp);
5328             sfree(saddr_tmp);
5329             sports = kp2+1;
5330         } else {
5331             saddr = NULL;
5332             sports = kp;
5333         }
5334         sport = atoi(sports);
5335         sserv = 0;
5336         if (sport == 0) {
5337             sserv = 1;
5338             sport = net_service_lookup(sports);
5339             if (!sport) {
5340                 logeventf(ssh, "Service lookup failed for source"
5341                           " port \"%s\"", sports);
5342             }
5343         }
5344
5345         if (type == 'L' && !strcmp(val, "D")) {
5346             /* dynamic forwarding */
5347             host = NULL;
5348             dports = NULL;
5349             dport = -1;
5350             dserv = 0;
5351             type = 'D';
5352         } else {
5353             /* ordinary forwarding */
5354             vp = val;
5355             vp2 = vp + host_strcspn(vp, ":");
5356             host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5357             if (*vp2)
5358                 vp2++;
5359             dports = vp2;
5360             dport = atoi(dports);
5361             dserv = 0;
5362             if (dport == 0) {
5363                 dserv = 1;
5364                 dport = net_service_lookup(dports);
5365                 if (!dport) {
5366                     logeventf(ssh, "Service lookup failed for destination"
5367                               " port \"%s\"", dports);
5368                 }
5369             }
5370         }
5371
5372         if (sport && dport) {
5373             /* Set up a description of the source port. */
5374             struct ssh_portfwd *pfrec, *epfrec;
5375
5376             pfrec = snew(struct ssh_portfwd);
5377             pfrec->type = type;
5378             pfrec->saddr = saddr;
5379             pfrec->sserv = sserv ? dupstr(sports) : NULL;
5380             pfrec->sport = sport;
5381             pfrec->daddr = host;
5382             pfrec->dserv = dserv ? dupstr(dports) : NULL;
5383             pfrec->dport = dport;
5384             pfrec->local = NULL;
5385             pfrec->remote = NULL;
5386             pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5387                                     address_family == '6' ? ADDRTYPE_IPV6 :
5388                                     ADDRTYPE_UNSPEC);
5389
5390             epfrec = add234(ssh->portfwds, pfrec);
5391             if (epfrec != pfrec) {
5392                 if (epfrec->status == DESTROY) {
5393                     /*
5394                      * We already have a port forwarding up and running
5395                      * with precisely these parameters. Hence, no need
5396                      * to do anything; simply re-tag the existing one
5397                      * as KEEP.
5398                      */
5399                     epfrec->status = KEEP;
5400                 }
5401                 /*
5402                  * Anything else indicates that there was a duplicate
5403                  * in our input, which we'll silently ignore.
5404                  */
5405                 free_portfwd(pfrec);
5406             } else {
5407                 pfrec->status = CREATE;
5408             }
5409         } else {
5410             sfree(saddr);
5411             sfree(host);
5412         }
5413     }
5414
5415     /*
5416      * Now go through and destroy any port forwardings which were
5417      * not re-enabled.
5418      */
5419     for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5420         if (epf->status == DESTROY) {
5421             char *message;
5422
5423             message = dupprintf("%s port forwarding from %s%s%d",
5424                                 epf->type == 'L' ? "local" :
5425                                 epf->type == 'R' ? "remote" : "dynamic",
5426                                 epf->saddr ? epf->saddr : "",
5427                                 epf->saddr ? ":" : "",
5428                                 epf->sport);
5429
5430             if (epf->type != 'D') {
5431                 char *msg2 = dupprintf("%s to %s:%d", message,
5432                                        epf->daddr, epf->dport);
5433                 sfree(message);
5434                 message = msg2;
5435             }
5436
5437             logeventf(ssh, "Cancelling %s", message);
5438             sfree(message);
5439
5440             /* epf->remote or epf->local may be NULL if setting up a
5441              * forwarding failed. */
5442             if (epf->remote) {
5443                 struct ssh_rportfwd *rpf = epf->remote;
5444                 struct Packet *pktout;
5445
5446                 /*
5447                  * Cancel the port forwarding at the server
5448                  * end.
5449                  */
5450                 if (ssh->version == 1) {
5451                     /*
5452                      * We cannot cancel listening ports on the
5453                      * server side in SSH-1! There's no message
5454                      * to support it. Instead, we simply remove
5455                      * the rportfwd record from the local end
5456                      * so that any connections the server tries
5457                      * to make on it are rejected.
5458                      */
5459                 } else {
5460                     pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5461                     ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5462                     ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5463                     if (epf->saddr) {
5464                         ssh2_pkt_addstring(pktout, epf->saddr);
5465                     } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5466                         /* XXX: rport_acceptall may not represent
5467                          * what was used to open the original connection,
5468                          * since it's reconfigurable. */
5469                         ssh2_pkt_addstring(pktout, "");
5470                     } else {
5471                         ssh2_pkt_addstring(pktout, "localhost");
5472                     }
5473                     ssh2_pkt_adduint32(pktout, epf->sport);
5474                     ssh2_pkt_send(ssh, pktout);
5475                 }
5476
5477                 del234(ssh->rportfwds, rpf);
5478                 free_rportfwd(rpf);
5479             } else if (epf->local) {
5480                 pfl_terminate(epf->local);
5481             }
5482
5483             delpos234(ssh->portfwds, i);
5484             free_portfwd(epf);
5485             i--;                       /* so we don't skip one in the list */
5486         }
5487
5488     /*
5489      * And finally, set up any new port forwardings (status==CREATE).
5490      */
5491     for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5492         if (epf->status == CREATE) {
5493             char *sportdesc, *dportdesc;
5494             sportdesc = dupprintf("%s%s%s%s%d%s",
5495                                   epf->saddr ? epf->saddr : "",
5496                                   epf->saddr ? ":" : "",
5497                                   epf->sserv ? epf->sserv : "",
5498                                   epf->sserv ? "(" : "",
5499                                   epf->sport,
5500                                   epf->sserv ? ")" : "");
5501             if (epf->type == 'D') {
5502                 dportdesc = NULL;
5503             } else {
5504                 dportdesc = dupprintf("%s:%s%s%d%s",
5505                                       epf->daddr,
5506                                       epf->dserv ? epf->dserv : "",
5507                                       epf->dserv ? "(" : "",
5508                                       epf->dport,
5509                                       epf->dserv ? ")" : "");
5510             }
5511
5512             if (epf->type == 'L') {
5513                 char *err = pfl_listen(epf->daddr, epf->dport,
5514                                        epf->saddr, epf->sport,
5515                                        ssh, conf, &epf->local,
5516                                        epf->addressfamily);
5517
5518                 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5519                           epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5520                           epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5521                           sportdesc, dportdesc,
5522                           err ? " failed: " : "", err ? err : "");
5523                 if (err)
5524                     sfree(err);
5525             } else if (epf->type == 'D') {
5526                 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5527                                        ssh, conf, &epf->local,
5528                                        epf->addressfamily);
5529
5530                 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5531                           epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5532                           epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5533                           sportdesc,
5534                           err ? " failed: " : "", err ? err : "");
5535
5536                 if (err)
5537                     sfree(err);
5538             } else {
5539                 struct ssh_rportfwd *pf;
5540
5541                 /*
5542                  * Ensure the remote port forwardings tree exists.
5543                  */
5544                 if (!ssh->rportfwds) {
5545                     if (ssh->version == 1)
5546                         ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5547                     else
5548                         ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5549                 }
5550
5551                 pf = snew(struct ssh_rportfwd);
5552                 pf->share_ctx = NULL;
5553                 pf->dhost = dupstr(epf->daddr);
5554                 pf->dport = epf->dport;
5555                 if (epf->saddr) {
5556                     pf->shost = dupstr(epf->saddr);
5557                 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5558                     pf->shost = dupstr("");
5559                 } else {
5560                     pf->shost = dupstr("localhost");
5561                 }
5562                 pf->sport = epf->sport;
5563                 if (add234(ssh->rportfwds, pf) != pf) {
5564                     logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5565                               epf->daddr, epf->dport);
5566                     sfree(pf);
5567                 } else {
5568                     logeventf(ssh, "Requesting remote port %s"
5569                               " forward to %s", sportdesc, dportdesc);
5570
5571                     pf->sportdesc = sportdesc;
5572                     sportdesc = NULL;
5573                     epf->remote = pf;
5574                     pf->pfrec = epf;
5575
5576                     if (ssh->version == 1) {
5577                         send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5578                                     PKT_INT, epf->sport,
5579                                     PKT_STR, epf->daddr,
5580                                     PKT_INT, epf->dport,
5581                                     PKT_END);
5582                         ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5583                                           SSH1_SMSG_FAILURE,
5584                                           ssh_rportfwd_succfail, pf);
5585                     } else {
5586                         struct Packet *pktout;
5587                         pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5588                         ssh2_pkt_addstring(pktout, "tcpip-forward");
5589                         ssh2_pkt_addbool(pktout, 1);/* want reply */
5590                         ssh2_pkt_addstring(pktout, pf->shost);
5591                         ssh2_pkt_adduint32(pktout, pf->sport);
5592                         ssh2_pkt_send(ssh, pktout);
5593
5594                         ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5595                                           SSH2_MSG_REQUEST_FAILURE,
5596                                           ssh_rportfwd_succfail, pf);
5597                     }
5598                 }
5599             }
5600             sfree(sportdesc);
5601             sfree(dportdesc);
5602         }
5603 }
5604
5605 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5606 {
5607     char *string;
5608     int stringlen, bufsize;
5609
5610     ssh_pkt_getstring(pktin, &string, &stringlen);
5611     if (string == NULL) {
5612         bombout(("Incoming terminal data packet was badly formed"));
5613         return;
5614     }
5615
5616     bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5617                            string, stringlen);
5618     if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5619         ssh->v1_stdout_throttling = 1;
5620         ssh_throttle_conn(ssh, +1);
5621     }
5622 }
5623
5624 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5625 {
5626     /* Remote side is trying to open a channel to talk to our
5627      * X-Server. Give them back a local channel number. */
5628     struct ssh_channel *c;
5629     int remoteid = ssh_pkt_getuint32(pktin);
5630
5631     logevent("Received X11 connect request");
5632     /* Refuse if X11 forwarding is disabled. */
5633     if (!ssh->X11_fwd_enabled) {
5634         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5635                     PKT_INT, remoteid, PKT_END);
5636         logevent("Rejected X11 connect request");
5637     } else {
5638         c = snew(struct ssh_channel);
5639         c->ssh = ssh;
5640
5641         ssh_channel_init(c);
5642         c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5643         c->remoteid = remoteid;
5644         c->halfopen = FALSE;
5645         c->type = CHAN_X11;     /* identify channel type */
5646         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5647                     PKT_INT, c->remoteid, PKT_INT,
5648                     c->localid, PKT_END);
5649         logevent("Opened X11 forward channel");
5650     }
5651 }
5652
5653 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5654 {
5655     /* Remote side is trying to open a channel to talk to our
5656      * agent. Give them back a local channel number. */
5657     struct ssh_channel *c;
5658     int remoteid = ssh_pkt_getuint32(pktin);
5659
5660     /* Refuse if agent forwarding is disabled. */
5661     if (!ssh->agentfwd_enabled) {
5662         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5663                     PKT_INT, remoteid, PKT_END);
5664     } else {
5665         c = snew(struct ssh_channel);
5666         c->ssh = ssh;
5667         ssh_channel_init(c);
5668         c->remoteid = remoteid;
5669         c->halfopen = FALSE;
5670         c->type = CHAN_AGENT;   /* identify channel type */
5671         c->u.a.pending = NULL;
5672         bufchain_init(&c->u.a.inbuffer);
5673         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5674                     PKT_INT, c->remoteid, PKT_INT, c->localid,
5675                     PKT_END);
5676     }
5677 }
5678
5679 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5680 {
5681     /* Remote side is trying to open a channel to talk to a
5682      * forwarded port. Give them back a local channel number. */
5683     struct ssh_rportfwd pf, *pfp;
5684     int remoteid;
5685     int hostsize, port;
5686     char *host;
5687     char *err;
5688
5689     remoteid = ssh_pkt_getuint32(pktin);
5690     ssh_pkt_getstring(pktin, &host, &hostsize);
5691     port = ssh_pkt_getuint32(pktin);
5692
5693     pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5694     pf.dport = port;
5695     pfp = find234(ssh->rportfwds, &pf, NULL);
5696
5697     if (pfp == NULL) {
5698         logeventf(ssh, "Rejected remote port open request for %s:%d",
5699                   pf.dhost, port);
5700         send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5701                     PKT_INT, remoteid, PKT_END);
5702     } else {
5703         struct ssh_channel *c = snew(struct ssh_channel);
5704         c->ssh = ssh;
5705
5706         logeventf(ssh, "Received remote port open request for %s:%d",
5707                   pf.dhost, port);
5708         err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5709                           c, ssh->conf, pfp->pfrec->addressfamily);
5710         if (err != NULL) {
5711             logeventf(ssh, "Port open failed: %s", err);
5712             sfree(err);
5713             sfree(c);
5714             send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5715                         PKT_INT, remoteid, PKT_END);
5716         } else {
5717             ssh_channel_init(c);
5718             c->remoteid = remoteid;
5719             c->halfopen = FALSE;
5720             c->type = CHAN_SOCKDATA;    /* identify channel type */
5721             send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5722                         PKT_INT, c->remoteid, PKT_INT,
5723                         c->localid, PKT_END);
5724             logevent("Forwarded port opened successfully");
5725         }
5726     }
5727
5728     sfree(pf.dhost);
5729 }
5730
5731 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5732 {
5733     struct ssh_channel *c;
5734
5735     c = ssh_channel_msg(ssh, pktin);
5736     if (c && c->type == CHAN_SOCKDATA) {
5737         c->remoteid = ssh_pkt_getuint32(pktin);
5738         c->halfopen = FALSE;
5739         c->throttling_conn = 0;
5740         pfd_confirm(c->u.pfd.pf);
5741     }
5742
5743     if (c && c->pending_eof) {
5744         /*
5745          * We have a pending close on this channel,
5746          * which we decided on before the server acked
5747          * the channel open. So now we know the
5748          * remoteid, we can close it again.
5749          */
5750         ssh_channel_try_eof(c);
5751     }
5752 }
5753
5754 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5755 {
5756     struct ssh_channel *c;
5757
5758     c = ssh_channel_msg(ssh, pktin);
5759     if (c && c->type == CHAN_SOCKDATA) {
5760         logevent("Forwarded connection refused by server");
5761         pfd_close(c->u.pfd.pf);
5762         del234(ssh->channels, c);
5763         sfree(c);
5764     }
5765 }
5766
5767 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5768 {
5769     /* Remote side closes a channel. */
5770     struct ssh_channel *c;
5771
5772     c = ssh_channel_msg(ssh, pktin);
5773     if (c) {
5774
5775         if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
5776             /*
5777              * Received CHANNEL_CLOSE, which we translate into
5778              * outgoing EOF.
5779              */
5780             ssh_channel_got_eof(c);
5781         }
5782
5783         if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5784             !(c->closes & CLOSES_RCVD_CLOSE)) {
5785
5786             if (!(c->closes & CLOSES_SENT_EOF)) {
5787                 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
5788                          " for which we never sent CHANNEL_CLOSE\n",
5789                          c->localid));
5790             }
5791
5792             c->closes |= CLOSES_RCVD_CLOSE;
5793         }
5794
5795         if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5796             !(c->closes & CLOSES_SENT_CLOSE)) {
5797             send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5798                         PKT_INT, c->remoteid, PKT_END);
5799             c->closes |= CLOSES_SENT_CLOSE;
5800         }
5801
5802         if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5803             ssh_channel_destroy(c);
5804     }
5805 }
5806
5807 /*
5808  * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5809  */
5810 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5811                                   int length)
5812 {
5813     bufchain_add(&c->u.a.inbuffer, data, length);
5814     ssh_agentf_try_forward(c);
5815
5816     /*
5817      * We exert back-pressure on an agent forwarding client if and
5818      * only if we're waiting for the response to an asynchronous agent
5819      * request. This prevents the client running out of window while
5820      * receiving the _first_ message, but means that if any message
5821      * takes time to process, the client will be discouraged from
5822      * sending an endless stream of further ones after it.
5823      */
5824     return (c->u.a.pending ? bufchain_size(&c->u.a.inbuffer) : 0);
5825 }
5826
5827 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5828                             char *data,  int length)
5829 {
5830     switch (c->type) {
5831       case CHAN_MAINSESSION:
5832         return from_backend(c->ssh->frontend, is_stderr, data, length);
5833       case CHAN_X11:
5834         return x11_send(c->u.x11.xconn, data, length);
5835       case CHAN_SOCKDATA:
5836         return pfd_send(c->u.pfd.pf, data, length);
5837       case CHAN_AGENT:
5838         return ssh_agent_channel_data(c, data, length);
5839     }
5840     return 0;
5841 }
5842
5843 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5844 {
5845     /* Data sent down one of our channels. */
5846     char *p;
5847     int len;
5848     struct ssh_channel *c;
5849
5850     c = ssh_channel_msg(ssh, pktin);
5851     ssh_pkt_getstring(pktin, &p, &len);
5852
5853     if (c) {
5854         int bufsize = ssh_channel_data(c, FALSE, p, len);
5855         if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5856             c->throttling_conn = 1;
5857             ssh_throttle_conn(ssh, +1);
5858         }
5859     }
5860 }
5861
5862 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5863 {
5864     ssh->exitcode = ssh_pkt_getuint32(pktin);
5865     logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5866     send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5867     /*
5868      * In case `helpful' firewalls or proxies tack
5869      * extra human-readable text on the end of the
5870      * session which we might mistake for another
5871      * encrypted packet, we close the session once
5872      * we've sent EXIT_CONFIRMATION.
5873      */
5874     ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5875 }
5876
5877 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5878 static void ssh1_send_ttymode(void *data,
5879                               const struct ssh_ttymode *mode, char *val)
5880 {
5881     struct Packet *pktout = (struct Packet *)data;
5882     unsigned int arg = 0;
5883
5884     switch (mode->type) {
5885       case TTY_OP_CHAR:
5886         arg = ssh_tty_parse_specchar(val);
5887         break;
5888       case TTY_OP_BOOL:
5889         arg = ssh_tty_parse_boolean(val);
5890         break;
5891     }
5892     ssh2_pkt_addbyte(pktout, mode->opcode);
5893     ssh2_pkt_addbyte(pktout, arg);
5894 }
5895
5896 int ssh_agent_forwarding_permitted(Ssh ssh)
5897 {
5898     return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5899 }
5900
5901 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5902                                struct Packet *pktin)
5903 {
5904     crBegin(ssh->do_ssh1_connection_crstate);
5905
5906     ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] = 
5907         ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5908         ssh1_smsg_stdout_stderr_data;
5909
5910     ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5911         ssh1_msg_channel_open_confirmation;
5912     ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5913         ssh1_msg_channel_open_failure;
5914     ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5915         ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5916         ssh1_msg_channel_close;
5917     ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5918     ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5919
5920     if (ssh_agent_forwarding_permitted(ssh)) {
5921         logevent("Requesting agent forwarding");
5922         send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5923         do {
5924             crReturnV;
5925         } while (!pktin);
5926         if (pktin->type != SSH1_SMSG_SUCCESS
5927             && pktin->type != SSH1_SMSG_FAILURE) {
5928             bombout(("Protocol confusion"));
5929             crStopV;
5930         } else if (pktin->type == SSH1_SMSG_FAILURE) {
5931             logevent("Agent forwarding refused");
5932         } else {
5933             logevent("Agent forwarding enabled");
5934             ssh->agentfwd_enabled = TRUE;
5935             ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5936         }
5937     }
5938
5939     if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5940         ssh->x11disp =
5941             x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5942                               ssh->conf);
5943         if (!ssh->x11disp) {
5944             /* FIXME: return an error message from x11_setup_display */
5945             logevent("X11 forwarding not enabled: unable to"
5946                      " initialise X display");
5947         } else {
5948             ssh->x11auth = x11_invent_fake_auth
5949                 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5950             ssh->x11auth->disp = ssh->x11disp;
5951
5952             logevent("Requesting X11 forwarding");
5953             if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5954                 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5955                             PKT_STR, ssh->x11auth->protoname,
5956                             PKT_STR, ssh->x11auth->datastring,
5957                             PKT_INT, ssh->x11disp->screennum,
5958                             PKT_END);
5959             } else {
5960                 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5961                             PKT_STR, ssh->x11auth->protoname,
5962                             PKT_STR, ssh->x11auth->datastring,
5963                             PKT_END);
5964             }
5965             do {
5966                 crReturnV;
5967             } while (!pktin);
5968             if (pktin->type != SSH1_SMSG_SUCCESS
5969                 && pktin->type != SSH1_SMSG_FAILURE) {
5970                 bombout(("Protocol confusion"));
5971                 crStopV;
5972             } else if (pktin->type == SSH1_SMSG_FAILURE) {
5973                 logevent("X11 forwarding refused");
5974             } else {
5975                 logevent("X11 forwarding enabled");
5976                 ssh->X11_fwd_enabled = TRUE;
5977                 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5978             }
5979         }
5980     }
5981
5982     ssh_setup_portfwd(ssh, ssh->conf);
5983     ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5984
5985     if (!conf_get_int(ssh->conf, CONF_nopty)) {
5986         struct Packet *pkt;
5987         /* Unpick the terminal-speed string. */
5988         /* XXX perhaps we should allow no speeds to be sent. */
5989         ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5990         sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5991         /* Send the pty request. */
5992         pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5993         ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5994         ssh_pkt_adduint32(pkt, ssh->term_height);
5995         ssh_pkt_adduint32(pkt, ssh->term_width);
5996         ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5997         ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5998         parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5999         ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
6000         ssh_pkt_adduint32(pkt, ssh->ispeed);
6001         ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
6002         ssh_pkt_adduint32(pkt, ssh->ospeed);
6003         ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
6004         s_wrpkt(ssh, pkt);
6005         ssh->state = SSH_STATE_INTERMED;
6006         do {
6007             crReturnV;
6008         } while (!pktin);
6009         if (pktin->type != SSH1_SMSG_SUCCESS
6010             && pktin->type != SSH1_SMSG_FAILURE) {
6011             bombout(("Protocol confusion"));
6012             crStopV;
6013         } else if (pktin->type == SSH1_SMSG_FAILURE) {
6014             c_write_str(ssh, "Server refused to allocate pty\r\n");
6015             ssh->editing = ssh->echoing = 1;
6016         } else {
6017             logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6018                       ssh->ospeed, ssh->ispeed);
6019             ssh->got_pty = TRUE;
6020         }
6021     } else {
6022         ssh->editing = ssh->echoing = 1;
6023     }
6024
6025     if (conf_get_int(ssh->conf, CONF_compression)) {
6026         send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
6027         do {
6028             crReturnV;
6029         } while (!pktin);
6030         if (pktin->type != SSH1_SMSG_SUCCESS
6031             && pktin->type != SSH1_SMSG_FAILURE) {
6032             bombout(("Protocol confusion"));
6033             crStopV;
6034         } else if (pktin->type == SSH1_SMSG_FAILURE) {
6035             c_write_str(ssh, "Server refused to compress\r\n");
6036         }
6037         logevent("Started compression");
6038         ssh->v1_compressing = TRUE;
6039         ssh->cs_comp_ctx = zlib_compress_init();
6040         logevent("Initialised zlib (RFC1950) compression");
6041         ssh->sc_comp_ctx = zlib_decompress_init();
6042         logevent("Initialised zlib (RFC1950) decompression");
6043     }
6044
6045     /*
6046      * Start the shell or command.
6047      * 
6048      * Special case: if the first-choice command is an SSH-2
6049      * subsystem (hence not usable here) and the second choice
6050      * exists, we fall straight back to that.
6051      */
6052     {
6053         char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6054         
6055         if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6056             conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6057             cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6058             ssh->fallback_cmd = TRUE;
6059         }
6060         if (*cmd)
6061             send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6062         else
6063             send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6064         logevent("Started session");
6065     }
6066
6067     ssh->state = SSH_STATE_SESSION;
6068     if (ssh->size_needed)
6069         ssh_size(ssh, ssh->term_width, ssh->term_height);
6070     if (ssh->eof_needed)
6071         ssh_special(ssh, TS_EOF);
6072
6073     if (ssh->ldisc)
6074         ldisc_echoedit_update(ssh->ldisc);  /* cause ldisc to notice changes */
6075     ssh->send_ok = 1;
6076     ssh->channels = newtree234(ssh_channelcmp);
6077     while (1) {
6078
6079         /*
6080          * By this point, most incoming packets are already being
6081          * handled by the dispatch table, and we need only pay
6082          * attention to the unusual ones.
6083          */
6084
6085         crReturnV;
6086         if (pktin) {
6087             if (pktin->type == SSH1_SMSG_SUCCESS) {
6088                 /* may be from EXEC_SHELL on some servers */
6089             } else if (pktin->type == SSH1_SMSG_FAILURE) {
6090                 /* may be from EXEC_SHELL on some servers
6091                  * if no pty is available or in other odd cases. Ignore */
6092             } else {
6093                 bombout(("Strange packet received: type %d", pktin->type));
6094                 crStopV;
6095             }
6096         } else {
6097             while (inlen > 0) {
6098                 int len = min(inlen, 512);
6099                 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6100                             PKT_INT, len, PKT_DATA, in, len,
6101                             PKT_END);
6102                 in += len;
6103                 inlen -= len;
6104             }
6105         }
6106     }
6107
6108     crFinishV;
6109 }
6110
6111 /*
6112  * Handle the top-level SSH-2 protocol.
6113  */
6114 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6115 {
6116     char *msg;
6117     int msglen;
6118
6119     ssh_pkt_getstring(pktin, &msg, &msglen);
6120     logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6121 }
6122
6123 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6124 {
6125     /* log reason code in disconnect message */
6126     char *msg;
6127     int msglen;
6128
6129     ssh_pkt_getstring(pktin, &msg, &msglen);
6130     bombout(("Server sent disconnect message:\n\"%.*s\"",
6131              msglen, NULLTOEMPTY(msg)));
6132 }
6133
6134 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6135 {
6136     /* Do nothing, because we're ignoring it! Duhh. */
6137 }
6138
6139 static void ssh1_protocol_setup(Ssh ssh)
6140 {
6141     int i;
6142
6143     /*
6144      * Most messages are handled by the coroutines.
6145      */
6146     for (i = 0; i < 256; i++)
6147         ssh->packet_dispatch[i] = NULL;
6148
6149     /*
6150      * These special message types we install handlers for.
6151      */
6152     ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6153     ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6154     ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6155 }
6156
6157 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6158                           struct Packet *pktin)
6159 {
6160     const unsigned char *in = (const unsigned char *)vin;
6161     if (ssh->state == SSH_STATE_CLOSED)
6162         return;
6163
6164     if (pktin && ssh->packet_dispatch[pktin->type]) {
6165         ssh->packet_dispatch[pktin->type](ssh, pktin);
6166         return;
6167     }
6168
6169     if (!ssh->protocol_initial_phase_done) {
6170         if (do_ssh1_login(ssh, in, inlen, pktin))
6171             ssh->protocol_initial_phase_done = TRUE;
6172         else
6173             return;
6174     }
6175
6176     do_ssh1_connection(ssh, in, inlen, pktin);
6177 }
6178
6179 /*
6180  * Utility routines for decoding comma-separated strings in KEXINIT.
6181  */
6182 static int first_in_commasep_string(char const *needle, char const *haystack,
6183                                     int haylen)
6184 {
6185     int needlen;
6186     if (!needle || !haystack)          /* protect against null pointers */
6187         return 0;
6188     needlen = strlen(needle);
6189
6190     if (haylen >= needlen &&       /* haystack is long enough */
6191         !memcmp(needle, haystack, needlen) &&   /* initial match */
6192         (haylen == needlen || haystack[needlen] == ',')
6193         /* either , or EOS follows */
6194         )
6195         return 1;
6196     return 0;
6197 }
6198
6199 static int in_commasep_string(char const *needle, char const *haystack,
6200                               int haylen)
6201 {
6202     char *p;
6203
6204     if (!needle || !haystack)          /* protect against null pointers */
6205         return 0;
6206     /*
6207      * Is it at the start of the string?
6208      */
6209     if (first_in_commasep_string(needle, haystack, haylen))
6210         return 1;
6211     /*
6212      * If not, search for the next comma and resume after that.
6213      * If no comma found, terminate.
6214      */
6215     p = memchr(haystack, ',', haylen);
6216     if (!p) return 0;
6217     /* + 1 to skip over comma */
6218     return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6219 }
6220
6221 /*
6222  * Add a value to the comma-separated string at the end of the packet.
6223  */
6224 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6225 {
6226     if (pkt->length - pkt->savedpos > 0)
6227         ssh_pkt_addstring_str(pkt, ",");
6228     ssh_pkt_addstring_str(pkt, data);
6229 }
6230
6231
6232 /*
6233  * SSH-2 key derivation (RFC 4253 section 7.2).
6234  */
6235 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6236                                  char chr, int keylen)
6237 {
6238     const struct ssh_hash *h = ssh->kex->hash;
6239     int keylen_padded;
6240     unsigned char *key;
6241     void *s, *s2;
6242
6243     if (keylen == 0)
6244         return NULL;
6245
6246     /* Round up to the next multiple of hash length. */
6247     keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6248
6249     key = snewn(keylen_padded, unsigned char);
6250
6251     /* First hlen bytes. */
6252     s = h->init();
6253     if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6254         hash_mpint(h, s, K);
6255     h->bytes(s, H, h->hlen);
6256     h->bytes(s, &chr, 1);
6257     h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6258     h->final(s, key);
6259
6260     /* Subsequent blocks of hlen bytes. */
6261     if (keylen_padded > h->hlen) {
6262         int offset;
6263
6264         s = h->init();
6265         if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6266             hash_mpint(h, s, K);
6267         h->bytes(s, H, h->hlen);
6268
6269         for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6270             h->bytes(s, key + offset - h->hlen, h->hlen);
6271             s2 = h->copy(s);
6272             h->final(s2, key + offset);
6273         }
6274
6275         h->free(s);
6276     }
6277
6278     /* Now clear any extra bytes of key material beyond the length
6279      * we're officially returning, because the caller won't know to
6280      * smemclr those. */
6281     if (keylen_padded > keylen)
6282         smemclr(key + keylen, keylen_padded - keylen);
6283
6284     return key;
6285 }
6286
6287 /*
6288  * Structure for constructing KEXINIT algorithm lists.
6289  */
6290 #define MAXKEXLIST 16
6291 struct kexinit_algorithm {
6292     const char *name;
6293     union {
6294         struct {
6295             const struct ssh_kex *kex;
6296             int warn;
6297         } kex;
6298         struct {
6299             const struct ssh_signkey *hostkey;
6300             int warn;
6301         } hk;
6302         struct {
6303             const struct ssh2_cipher *cipher;
6304             int warn;
6305         } cipher;
6306         struct {
6307             const struct ssh_mac *mac;
6308             int etm;
6309         } mac;
6310         const struct ssh_compress *comp;
6311     } u;
6312 };
6313
6314 /*
6315  * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6316  * If the algorithm is already in the list, return a pointer to its
6317  * entry, otherwise return an entry from the end of the list.
6318  * This assumes that every time a particular name is passed in, it
6319  * comes from the same string constant.  If this isn't true, this
6320  * function may need to be rewritten to use strcmp() instead.
6321  */
6322 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6323                                                      *list, const char *name)
6324 {
6325     int i;
6326
6327     for (i = 0; i < MAXKEXLIST; i++)
6328         if (list[i].name == NULL || list[i].name == name) {
6329             list[i].name = name;
6330             return &list[i];
6331         }
6332     assert(!"No space in KEXINIT list");
6333     return NULL;
6334 }
6335
6336 /*
6337  * Handle the SSH-2 transport layer.
6338  */
6339 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6340                              struct Packet *pktin)
6341 {
6342     const unsigned char *in = (const unsigned char *)vin;
6343     enum kexlist {
6344         KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6345         KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6346         NKEXLIST
6347     };
6348     const char * kexlist_descr[NKEXLIST] = {
6349         "key exchange algorithm", "host key algorithm",
6350         "client-to-server cipher", "server-to-client cipher",
6351         "client-to-server MAC", "server-to-client MAC",
6352         "client-to-server compression method",
6353         "server-to-client compression method" };
6354     struct do_ssh2_transport_state {
6355         int crLine;
6356         int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6357         Bignum p, g, e, f, K;
6358         void *our_kexinit;
6359         int our_kexinitlen;
6360         int kex_init_value, kex_reply_value;
6361         const struct ssh_mac *const *maclist;
6362         int nmacs;
6363         const struct ssh2_cipher *cscipher_tobe;
6364         const struct ssh2_cipher *sccipher_tobe;
6365         const struct ssh_mac *csmac_tobe;
6366         const struct ssh_mac *scmac_tobe;
6367         int csmac_etm_tobe, scmac_etm_tobe;
6368         const struct ssh_compress *cscomp_tobe;
6369         const struct ssh_compress *sccomp_tobe;
6370         char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6371         int hostkeylen, siglen, rsakeylen;
6372         void *hkey;                    /* actual host key */
6373         void *rsakey;                  /* for RSA kex */
6374         void *eckey;                   /* for ECDH kex */
6375         unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6376         int n_preferred_kex;
6377         const struct ssh_kexes *preferred_kex[KEX_MAX];
6378         int n_preferred_hk;
6379         int preferred_hk[HK_MAX];
6380         int n_preferred_ciphers;
6381         const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6382         const struct ssh_compress *preferred_comp;
6383         int userauth_succeeded;     /* for delayed compression */
6384         int pending_compression;
6385         int got_session_id, activated_authconn;
6386         struct Packet *pktout;
6387         int dlgret;
6388         int guessok;
6389         int ignorepkt;
6390         struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6391     };
6392     crState(do_ssh2_transport_state);
6393
6394     assert(!ssh->bare_connection);
6395     assert(ssh->version == 2);
6396
6397     crBeginState;
6398
6399     s->cscipher_tobe = s->sccipher_tobe = NULL;
6400     s->csmac_tobe = s->scmac_tobe = NULL;
6401     s->cscomp_tobe = s->sccomp_tobe = NULL;
6402
6403     s->got_session_id = s->activated_authconn = FALSE;
6404     s->userauth_succeeded = FALSE;
6405     s->pending_compression = FALSE;
6406
6407     /*
6408      * Be prepared to work around the buggy MAC problem.
6409      */
6410     if (ssh->remote_bugs & BUG_SSH2_HMAC)
6411         s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6412     else
6413         s->maclist = macs, s->nmacs = lenof(macs);
6414
6415   begin_key_exchange:
6416     ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6417     {
6418         int i, j, k, warn;
6419         struct kexinit_algorithm *alg;
6420
6421         /*
6422          * Set up the preferred key exchange. (NULL => warn below here)
6423          */
6424         s->n_preferred_kex = 0;
6425         for (i = 0; i < KEX_MAX; i++) {
6426             switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6427               case KEX_DHGEX:
6428                 s->preferred_kex[s->n_preferred_kex++] =
6429                     &ssh_diffiehellman_gex;
6430                 break;
6431               case KEX_DHGROUP14:
6432                 s->preferred_kex[s->n_preferred_kex++] =
6433                     &ssh_diffiehellman_group14;
6434                 break;
6435               case KEX_DHGROUP1:
6436                 s->preferred_kex[s->n_preferred_kex++] =
6437                     &ssh_diffiehellman_group1;
6438                 break;
6439               case KEX_RSA:
6440                 s->preferred_kex[s->n_preferred_kex++] =
6441                     &ssh_rsa_kex;
6442                 break;
6443               case KEX_ECDH:
6444                 s->preferred_kex[s->n_preferred_kex++] =
6445                     &ssh_ecdh_kex;
6446                 break;
6447               case KEX_WARN:
6448                 /* Flag for later. Don't bother if it's the last in
6449                  * the list. */
6450                 if (i < KEX_MAX - 1) {
6451                     s->preferred_kex[s->n_preferred_kex++] = NULL;
6452                 }
6453                 break;
6454             }
6455         }
6456
6457         /*
6458          * Set up the preferred host key types. These are just the ids
6459          * in the enum in putty.h, so 'warn below here' is indicated
6460          * by HK_WARN.
6461          */
6462         s->n_preferred_hk = 0;
6463         for (i = 0; i < HK_MAX; i++) {
6464             int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6465             /* As above, don't bother with HK_WARN if it's last in the
6466              * list */
6467             if (id != HK_WARN || i < HK_MAX - 1)
6468                 s->preferred_hk[s->n_preferred_hk++] = id;
6469         }
6470
6471         /*
6472          * Set up the preferred ciphers. (NULL => warn below here)
6473          */
6474         s->n_preferred_ciphers = 0;
6475         for (i = 0; i < CIPHER_MAX; i++) {
6476             switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6477               case CIPHER_BLOWFISH:
6478                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6479                 break;
6480               case CIPHER_DES:
6481                 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6482                     s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6483                 }
6484                 break;
6485               case CIPHER_3DES:
6486                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6487                 break;
6488               case CIPHER_AES:
6489                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6490                 break;
6491               case CIPHER_ARCFOUR:
6492                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6493                 break;
6494               case CIPHER_CHACHA20:
6495                 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6496                 break;
6497               case CIPHER_WARN:
6498                 /* Flag for later. Don't bother if it's the last in
6499                  * the list. */
6500                 if (i < CIPHER_MAX - 1) {
6501                     s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6502                 }
6503                 break;
6504             }
6505         }
6506
6507         /*
6508          * Set up preferred compression.
6509          */
6510         if (conf_get_int(ssh->conf, CONF_compression))
6511             s->preferred_comp = &ssh_zlib;
6512         else
6513             s->preferred_comp = &ssh_comp_none;
6514
6515         /*
6516          * Enable queueing of outgoing auth- or connection-layer
6517          * packets while we are in the middle of a key exchange.
6518          */
6519         ssh->queueing = TRUE;
6520
6521         /*
6522          * Flag that KEX is in progress.
6523          */
6524         ssh->kex_in_progress = TRUE;
6525
6526         for (i = 0; i < NKEXLIST; i++)
6527             for (j = 0; j < MAXKEXLIST; j++)
6528                 s->kexlists[i][j].name = NULL;
6529         /* List key exchange algorithms. */
6530         warn = FALSE;
6531         for (i = 0; i < s->n_preferred_kex; i++) {
6532             const struct ssh_kexes *k = s->preferred_kex[i];
6533             if (!k) warn = TRUE;
6534             else for (j = 0; j < k->nkexes; j++) {
6535                 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6536                                           k->list[j]->name);
6537                 alg->u.kex.kex = k->list[j];
6538                 alg->u.kex.warn = warn;
6539             }
6540         }
6541         /* List server host key algorithms. */
6542         if (!s->got_session_id) {
6543             /*
6544              * In the first key exchange, we list all the algorithms
6545              * we're prepared to cope with, but prefer those algorithms
6546              * for which we have a host key for this host.
6547              *
6548              * If the host key algorithm is below the warning
6549              * threshold, we warn even if we did already have a key
6550              * for it, on the basis that if the user has just
6551              * reconfigured that host key type to be warned about,
6552              * they surely _do_ want to be alerted that a server
6553              * they're actually connecting to is using it.
6554              */
6555             warn = FALSE;
6556             for (i = 0; i < s->n_preferred_hk; i++) {
6557                 if (s->preferred_hk[i] == HK_WARN)
6558                     warn = TRUE;
6559                 for (j = 0; j < lenof(hostkey_algs); j++) {
6560                     if (hostkey_algs[j].id != s->preferred_hk[i])
6561                         continue;
6562                     if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6563                                           hostkey_algs[j].alg->keytype)) {
6564                         alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6565                                                   hostkey_algs[j].alg->name);
6566                         alg->u.hk.hostkey = hostkey_algs[j].alg;
6567                         alg->u.hk.warn = warn;
6568                     }
6569                 }
6570             }
6571             warn = FALSE;
6572             for (i = 0; i < s->n_preferred_hk; i++) {
6573                 if (s->preferred_hk[i] == HK_WARN)
6574                     warn = TRUE;
6575                 for (j = 0; j < lenof(hostkey_algs); j++) {
6576                     if (hostkey_algs[j].id != s->preferred_hk[i])
6577                         continue;
6578                     alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6579                                               hostkey_algs[j].alg->name);
6580                     alg->u.hk.hostkey = hostkey_algs[j].alg;
6581                     alg->u.hk.warn = warn;
6582                 }
6583             }
6584         } else {
6585             /*
6586              * In subsequent key exchanges, we list only the kex
6587              * algorithm that was selected in the first key exchange,
6588              * so that we keep getting the same host key and hence
6589              * don't have to interrupt the user's session to ask for
6590              * reverification.
6591              */
6592             assert(ssh->kex);
6593             alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6594                                       ssh->hostkey->name);
6595             alg->u.hk.hostkey = ssh->hostkey;
6596             alg->u.hk.warn = FALSE;
6597         }
6598         /* List encryption algorithms (client->server then server->client). */
6599         for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6600             warn = FALSE;
6601 #ifdef FUZZING
6602             alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6603             alg->u.cipher.cipher = NULL;
6604             alg->u.cipher.warn = warn;
6605 #endif /* FUZZING */
6606             for (i = 0; i < s->n_preferred_ciphers; i++) {
6607                 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6608                 if (!c) warn = TRUE;
6609                 else for (j = 0; j < c->nciphers; j++) {
6610                     alg = ssh2_kexinit_addalg(s->kexlists[k],
6611                                               c->list[j]->name);
6612                     alg->u.cipher.cipher = c->list[j];
6613                     alg->u.cipher.warn = warn;
6614                 }
6615             }
6616         }
6617         /* List MAC algorithms (client->server then server->client). */
6618         for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6619 #ifdef FUZZING
6620             alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6621             alg->u.mac.mac = NULL;
6622             alg->u.mac.etm = FALSE;
6623 #endif /* FUZZING */
6624             for (i = 0; i < s->nmacs; i++) {
6625                 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6626                 alg->u.mac.mac = s->maclist[i];
6627                 alg->u.mac.etm = FALSE;
6628             }
6629             for (i = 0; i < s->nmacs; i++)
6630                 /* For each MAC, there may also be an ETM version,
6631                  * which we list second. */
6632                 if (s->maclist[i]->etm_name) {
6633                     alg = ssh2_kexinit_addalg(s->kexlists[j],
6634                                               s->maclist[i]->etm_name);
6635                     alg->u.mac.mac = s->maclist[i];
6636                     alg->u.mac.etm = TRUE;
6637                 }
6638         }
6639         /* List client->server compression algorithms,
6640          * then server->client compression algorithms. (We use the
6641          * same set twice.) */
6642         for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6643             assert(lenof(compressions) > 1);
6644             /* Prefer non-delayed versions */
6645             alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6646             alg->u.comp = s->preferred_comp;
6647             /* We don't even list delayed versions of algorithms until
6648              * they're allowed to be used, to avoid a race. See the end of
6649              * this function. */
6650             if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6651                 alg = ssh2_kexinit_addalg(s->kexlists[j],
6652                                           s->preferred_comp->delayed_name);
6653                 alg->u.comp = s->preferred_comp;
6654             }
6655             for (i = 0; i < lenof(compressions); i++) {
6656                 const struct ssh_compress *c = compressions[i];
6657                 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6658                 alg->u.comp = c;
6659                 if (s->userauth_succeeded && c->delayed_name) {
6660                     alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6661                     alg->u.comp = c;
6662                 }
6663             }
6664         }
6665         /*
6666          * Construct and send our key exchange packet.
6667          */
6668         s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6669         for (i = 0; i < 16; i++)
6670             ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6671         for (i = 0; i < NKEXLIST; i++) {
6672             ssh2_pkt_addstring_start(s->pktout);
6673             for (j = 0; j < MAXKEXLIST; j++) {
6674                 if (s->kexlists[i][j].name == NULL) break;
6675                 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6676             }
6677         }
6678         /* List client->server languages. Empty list. */
6679         ssh2_pkt_addstring_start(s->pktout);
6680         /* List server->client languages. Empty list. */
6681         ssh2_pkt_addstring_start(s->pktout);
6682         /* First KEX packet does _not_ follow, because we're not that brave. */
6683         ssh2_pkt_addbool(s->pktout, FALSE);
6684         /* Reserved. */
6685         ssh2_pkt_adduint32(s->pktout, 0);
6686     }
6687
6688     s->our_kexinitlen = s->pktout->length - 5;
6689     s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6690     memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen); 
6691
6692     ssh2_pkt_send_noqueue(ssh, s->pktout);
6693
6694     if (!pktin)
6695         crWaitUntilV(pktin);
6696
6697     /*
6698      * Now examine the other side's KEXINIT to see what we're up
6699      * to.
6700      */
6701     {
6702         char *str;
6703         int i, j, len;
6704
6705         if (pktin->type != SSH2_MSG_KEXINIT) {
6706             bombout(("expected key exchange packet from server"));
6707             crStopV;
6708         }
6709         ssh->kex = NULL;
6710         ssh->hostkey = NULL;
6711         s->cscipher_tobe = NULL;
6712         s->sccipher_tobe = NULL;
6713         s->csmac_tobe = NULL;
6714         s->scmac_tobe = NULL;
6715         s->cscomp_tobe = NULL;
6716         s->sccomp_tobe = NULL;
6717         s->warn_kex = s->warn_hk = FALSE;
6718         s->warn_cscipher = s->warn_sccipher = FALSE;
6719
6720         pktin->savedpos += 16;          /* skip garbage cookie */
6721
6722         s->guessok = FALSE;
6723         for (i = 0; i < NKEXLIST; i++) {
6724             ssh_pkt_getstring(pktin, &str, &len);
6725             if (!str) {
6726                 bombout(("KEXINIT packet was incomplete"));
6727                 crStopV;
6728             }
6729
6730             /* If we've already selected a cipher which requires a
6731              * particular MAC, then just select that, and don't even
6732              * bother looking through the server's KEXINIT string for
6733              * MACs. */
6734             if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6735                 s->cscipher_tobe->required_mac) {
6736                 s->csmac_tobe = s->cscipher_tobe->required_mac;
6737                 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6738                 goto matched;
6739             }
6740             if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6741                 s->sccipher_tobe->required_mac) {
6742                 s->scmac_tobe = s->sccipher_tobe->required_mac;
6743                 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6744                 goto matched;
6745             }
6746
6747             for (j = 0; j < MAXKEXLIST; j++) {
6748                 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6749                 if (alg->name == NULL) break;
6750                 if (in_commasep_string(alg->name, str, len)) {
6751                     /* We've found a matching algorithm. */
6752                     if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6753                         /* Check if we might need to ignore first kex pkt */
6754                         if (j != 0 ||
6755                             !first_in_commasep_string(alg->name, str, len))
6756                             s->guessok = FALSE;
6757                     }
6758                     if (i == KEXLIST_KEX) {
6759                         ssh->kex = alg->u.kex.kex;
6760                         s->warn_kex = alg->u.kex.warn;
6761                     } else if (i == KEXLIST_HOSTKEY) {
6762                         ssh->hostkey = alg->u.hk.hostkey;
6763                         s->warn_hk = alg->u.hk.warn;
6764                     } else if (i == KEXLIST_CSCIPHER) {
6765                         s->cscipher_tobe = alg->u.cipher.cipher;
6766                         s->warn_cscipher = alg->u.cipher.warn;
6767                     } else if (i == KEXLIST_SCCIPHER) {
6768                         s->sccipher_tobe = alg->u.cipher.cipher;
6769                         s->warn_sccipher = alg->u.cipher.warn;
6770                     } else if (i == KEXLIST_CSMAC) {
6771                         s->csmac_tobe = alg->u.mac.mac;
6772                         s->csmac_etm_tobe = alg->u.mac.etm;
6773                     } else if (i == KEXLIST_SCMAC) {
6774                         s->scmac_tobe = alg->u.mac.mac;
6775                         s->scmac_etm_tobe = alg->u.mac.etm;
6776                     } else if (i == KEXLIST_CSCOMP) {
6777                         s->cscomp_tobe = alg->u.comp;
6778                     } else if (i == KEXLIST_SCCOMP) {
6779                         s->sccomp_tobe = alg->u.comp;
6780                     }
6781                     goto matched;
6782                 }
6783                 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6784                     in_commasep_string(alg->u.comp->delayed_name, str, len))
6785                     s->pending_compression = TRUE;  /* try this later */
6786             }
6787             bombout(("Couldn't agree a %s (available: %.*s)",
6788                      kexlist_descr[i], len, str));
6789             crStopV;
6790           matched:;
6791
6792             if (i == KEXLIST_HOSTKEY) {
6793                 int j;
6794
6795                 /*
6796                  * In addition to deciding which host key we're
6797                  * actually going to use, we should make a list of the
6798                  * host keys offered by the server which we _don't_
6799                  * have cached. These will be offered as cross-
6800                  * certification options by ssh_get_specials.
6801                  *
6802                  * We also count the key we're currently using for KEX
6803                  * as one we've already got, because by the time this
6804                  * menu becomes visible, it will be.
6805                  */
6806                 ssh->n_uncert_hostkeys = 0;
6807
6808                 for (j = 0; j < lenof(hostkey_algs); j++) {
6809                     if (hostkey_algs[j].alg != ssh->hostkey &&
6810                         in_commasep_string(hostkey_algs[j].alg->name,
6811                                            str, len) &&
6812                         !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6813                                            hostkey_algs[j].alg->keytype)) {
6814                         ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6815                     }
6816                 }
6817             }
6818         }
6819
6820         if (s->pending_compression) {
6821             logevent("Server supports delayed compression; "
6822                      "will try this later");
6823         }
6824         ssh_pkt_getstring(pktin, &str, &len);  /* client->server language */
6825         ssh_pkt_getstring(pktin, &str, &len);  /* server->client language */
6826         s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6827
6828         ssh->exhash = ssh->kex->hash->init();
6829         hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6830         hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6831         hash_string(ssh->kex->hash, ssh->exhash,
6832             s->our_kexinit, s->our_kexinitlen);
6833         sfree(s->our_kexinit);
6834         /* Include the type byte in the hash of server's KEXINIT */
6835         hash_string(ssh->kex->hash, ssh->exhash,
6836                     pktin->body - 1, pktin->length + 1);
6837
6838         if (s->warn_kex) {
6839             ssh_set_frozen(ssh, 1);
6840             s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6841                                ssh->kex->name,
6842                                ssh_dialog_callback, ssh);
6843             if (s->dlgret < 0) {
6844                 do {
6845                     crReturnV;
6846                     if (pktin) {
6847                         bombout(("Unexpected data from server while"
6848                                  " waiting for user response"));
6849                         crStopV;
6850                     }
6851                 } while (pktin || inlen > 0);
6852                 s->dlgret = ssh->user_response;
6853             }
6854             ssh_set_frozen(ssh, 0);
6855             if (s->dlgret == 0) {
6856                 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6857                                0, TRUE);
6858                 crStopV;
6859             }
6860         }
6861
6862         if (s->warn_hk) {
6863             int j, k;
6864             char *betteralgs;
6865
6866             ssh_set_frozen(ssh, 1);
6867
6868             /*
6869              * Change warning box wording depending on why we chose a
6870              * warning-level host key algorithm. If it's because
6871              * that's all we have *cached*, use the askhk mechanism,
6872              * and list the host keys we could usefully cross-certify.
6873              * Otherwise, use askalg for the standard wording.
6874              */
6875             betteralgs = NULL;
6876             for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6877                 const struct ssh_signkey_with_user_pref_id *hktype =
6878                     &hostkey_algs[ssh->uncert_hostkeys[j]];
6879                 int better = FALSE;
6880                 for (k = 0; k < HK_MAX; k++) {
6881                     int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6882                     if (id == HK_WARN) {
6883                         break;
6884                     } else if (id == hktype->id) {
6885                         better = TRUE;
6886                         break;
6887                     }
6888                 }
6889                 if (better) {
6890                     if (betteralgs) {
6891                         char *old_ba = betteralgs;
6892                         betteralgs = dupcat(betteralgs, ",",
6893                                             hktype->alg->name,
6894                                             (const char *)NULL);
6895                         sfree(old_ba);
6896                     } else {
6897                         betteralgs = dupstr(hktype->alg->name);
6898                     }
6899                 }
6900             }
6901             if (betteralgs) {
6902                 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6903                                   betteralgs, ssh_dialog_callback, ssh);
6904                 sfree(betteralgs);
6905             } else {
6906                 s->dlgret = askalg(ssh->frontend, "host key type",
6907                                    ssh->hostkey->name,
6908                                    ssh_dialog_callback, ssh);
6909             }
6910             if (s->dlgret < 0) {
6911                 do {
6912                     crReturnV;
6913                     if (pktin) {
6914                         bombout(("Unexpected data from server while"
6915                                  " waiting for user response"));
6916                         crStopV;
6917                     }
6918                 } while (pktin || inlen > 0);
6919                 s->dlgret = ssh->user_response;
6920             }
6921             ssh_set_frozen(ssh, 0);
6922             if (s->dlgret == 0) {
6923                 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6924                                0, TRUE);
6925                 crStopV;
6926             }
6927         }
6928
6929         if (s->warn_cscipher) {
6930             ssh_set_frozen(ssh, 1);
6931             s->dlgret = askalg(ssh->frontend,
6932                                "client-to-server cipher",
6933                                s->cscipher_tobe->name,
6934                                ssh_dialog_callback, ssh);
6935             if (s->dlgret < 0) {
6936                 do {
6937                     crReturnV;
6938                     if (pktin) {
6939                         bombout(("Unexpected data from server while"
6940                                  " waiting for user response"));
6941                         crStopV;
6942                     }
6943                 } while (pktin || inlen > 0);
6944                 s->dlgret = ssh->user_response;
6945             }
6946             ssh_set_frozen(ssh, 0);
6947             if (s->dlgret == 0) {
6948                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6949                                0, TRUE);
6950                 crStopV;
6951             }
6952         }
6953
6954         if (s->warn_sccipher) {
6955             ssh_set_frozen(ssh, 1);
6956             s->dlgret = askalg(ssh->frontend,
6957                                "server-to-client cipher",
6958                                s->sccipher_tobe->name,
6959                                ssh_dialog_callback, ssh);
6960             if (s->dlgret < 0) {
6961                 do {
6962                     crReturnV;
6963                     if (pktin) {
6964                         bombout(("Unexpected data from server while"
6965                                  " waiting for user response"));
6966                         crStopV;
6967                     }
6968                 } while (pktin || inlen > 0);
6969                 s->dlgret = ssh->user_response;
6970             }
6971             ssh_set_frozen(ssh, 0);
6972             if (s->dlgret == 0) {
6973                 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6974                                0, TRUE);
6975                 crStopV;
6976             }
6977         }
6978
6979         if (s->ignorepkt) /* first_kex_packet_follows */
6980             crWaitUntilV(pktin);                /* Ignore packet */
6981     }
6982
6983     if (ssh->kex->main_type == KEXTYPE_DH) {
6984         /*
6985          * Work out the number of bits of key we will need from the
6986          * key exchange. We start with the maximum key length of
6987          * either cipher...
6988          */
6989         {
6990             int csbits, scbits;
6991
6992             csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6993             scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6994             s->nbits = (csbits > scbits ? csbits : scbits);
6995         }
6996         /* The keys only have hlen-bit entropy, since they're based on
6997          * a hash. So cap the key size at hlen bits. */
6998         if (s->nbits > ssh->kex->hash->hlen * 8)
6999             s->nbits = ssh->kex->hash->hlen * 8;
7000
7001         /*
7002          * If we're doing Diffie-Hellman group exchange, start by
7003          * requesting a group.
7004          */
7005         if (dh_is_gex(ssh->kex)) {
7006             logevent("Doing Diffie-Hellman group exchange");
7007             ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
7008             /*
7009              * Work out how big a DH group we will need to allow that
7010              * much data.
7011              */
7012             s->pbits = 512 << ((s->nbits - 1) / 64);
7013             if (s->pbits < DH_MIN_SIZE)
7014                 s->pbits = DH_MIN_SIZE;
7015             if (s->pbits > DH_MAX_SIZE)
7016                 s->pbits = DH_MAX_SIZE;
7017             if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
7018                 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
7019                 ssh2_pkt_adduint32(s->pktout, s->pbits);
7020             } else {
7021                 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
7022                 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
7023                 ssh2_pkt_adduint32(s->pktout, s->pbits);
7024                 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
7025             }
7026             ssh2_pkt_send_noqueue(ssh, s->pktout);
7027
7028             crWaitUntilV(pktin);
7029             if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
7030                 bombout(("expected key exchange group packet from server"));
7031                 crStopV;
7032             }
7033             s->p = ssh2_pkt_getmp(pktin);
7034             s->g = ssh2_pkt_getmp(pktin);
7035             if (!s->p || !s->g) {
7036                 bombout(("unable to read mp-ints from incoming group packet"));
7037                 crStopV;
7038             }
7039             ssh->kex_ctx = dh_setup_gex(s->p, s->g);
7040             s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
7041             s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
7042         } else {
7043             ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
7044             ssh->kex_ctx = dh_setup_group(ssh->kex);
7045             s->kex_init_value = SSH2_MSG_KEXDH_INIT;
7046             s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
7047             logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
7048                       ssh->kex->groupname);
7049         }
7050
7051         logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
7052                   ssh->kex->hash->text_name);
7053         /*
7054          * Now generate and send e for Diffie-Hellman.
7055          */
7056         set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7057         s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7058         s->pktout = ssh2_pkt_init(s->kex_init_value);
7059         ssh2_pkt_addmp(s->pktout, s->e);
7060         ssh2_pkt_send_noqueue(ssh, s->pktout);
7061
7062         set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7063         crWaitUntilV(pktin);
7064         if (pktin->type != s->kex_reply_value) {
7065             bombout(("expected key exchange reply packet from server"));
7066             crStopV;
7067         }
7068         set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7069         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7070         if (!s->hostkeydata) {
7071             bombout(("unable to parse key exchange reply packet"));
7072             crStopV;
7073         }
7074         s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7075                                        s->hostkeydata, s->hostkeylen);
7076         s->f = ssh2_pkt_getmp(pktin);
7077         if (!s->f) {
7078             bombout(("unable to parse key exchange reply packet"));
7079             crStopV;
7080         }
7081         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7082         if (!s->sigdata) {
7083             bombout(("unable to parse key exchange reply packet"));
7084             crStopV;
7085         }
7086
7087         {
7088             const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7089             if (err) {
7090                 bombout(("key exchange reply failed validation: %s", err));
7091                 crStopV;
7092             }
7093         }
7094         s->K = dh_find_K(ssh->kex_ctx, s->f);
7095
7096         /* We assume everything from now on will be quick, and it might
7097          * involve user interaction. */
7098         set_busy_status(ssh->frontend, BUSY_NOT);
7099
7100         hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7101         if (dh_is_gex(ssh->kex)) {
7102             if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7103                 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7104             hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7105             if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7106                 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7107             hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7108             hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7109         }
7110         hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7111         hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7112
7113         dh_cleanup(ssh->kex_ctx);
7114         freebn(s->f);
7115         if (dh_is_gex(ssh->kex)) {
7116             freebn(s->g);
7117             freebn(s->p);
7118         }
7119     } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7120
7121         logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7122                   ssh_ecdhkex_curve_textname(ssh->kex),
7123                   ssh->kex->hash->text_name);
7124         ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7125
7126         s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7127         if (!s->eckey) {
7128             bombout(("Unable to generate key for ECDH"));
7129             crStopV;
7130         }
7131
7132         {
7133             char *publicPoint;
7134             int publicPointLength;
7135             publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7136             if (!publicPoint) {
7137                 ssh_ecdhkex_freekey(s->eckey);
7138                 bombout(("Unable to encode public key for ECDH"));
7139                 crStopV;
7140             }
7141             s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7142             ssh2_pkt_addstring_start(s->pktout);
7143             ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7144             sfree(publicPoint);
7145         }
7146
7147         ssh2_pkt_send_noqueue(ssh, s->pktout);
7148
7149         crWaitUntilV(pktin);
7150         if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7151             ssh_ecdhkex_freekey(s->eckey);
7152             bombout(("expected ECDH reply packet from server"));
7153             crStopV;
7154         }
7155
7156         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7157         if (!s->hostkeydata) {
7158             bombout(("unable to parse ECDH reply packet"));
7159             crStopV;
7160         }
7161         hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7162         s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7163                                        s->hostkeydata, s->hostkeylen);
7164
7165         {
7166             char *publicPoint;
7167             int publicPointLength;
7168             publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7169             if (!publicPoint) {
7170                 ssh_ecdhkex_freekey(s->eckey);
7171                 bombout(("Unable to encode public key for ECDH hash"));
7172                 crStopV;
7173             }
7174             hash_string(ssh->kex->hash, ssh->exhash,
7175                         publicPoint, publicPointLength);
7176             sfree(publicPoint);
7177         }
7178
7179         {
7180             char *keydata;
7181             int keylen;
7182             ssh_pkt_getstring(pktin, &keydata, &keylen);
7183             if (!keydata) {
7184                 bombout(("unable to parse ECDH reply packet"));
7185                 crStopV;
7186             }
7187             hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7188             s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7189             if (!s->K) {
7190                 ssh_ecdhkex_freekey(s->eckey);
7191                 bombout(("point received in ECDH was not valid"));
7192                 crStopV;
7193             }
7194         }
7195
7196         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7197         if (!s->sigdata) {
7198             bombout(("unable to parse key exchange reply packet"));
7199             crStopV;
7200         }
7201
7202         ssh_ecdhkex_freekey(s->eckey);
7203     } else {
7204         logeventf(ssh, "Doing RSA key exchange with hash %s",
7205                   ssh->kex->hash->text_name);
7206         ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7207         /*
7208          * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7209          * from the server.
7210          */
7211         crWaitUntilV(pktin);
7212         if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7213             bombout(("expected RSA public key packet from server"));
7214             crStopV;
7215         }
7216
7217         ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7218         if (!s->hostkeydata) {
7219             bombout(("unable to parse RSA public key packet"));
7220             crStopV;
7221         }
7222         hash_string(ssh->kex->hash, ssh->exhash,
7223                     s->hostkeydata, s->hostkeylen);
7224         s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7225                                        s->hostkeydata, s->hostkeylen);
7226
7227         {
7228             char *keydata;
7229             ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7230             if (!keydata) {
7231                 bombout(("unable to parse RSA public key packet"));
7232                 crStopV;
7233             }
7234             s->rsakeydata = snewn(s->rsakeylen, char);
7235             memcpy(s->rsakeydata, keydata, s->rsakeylen);
7236         }
7237
7238         s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7239         if (!s->rsakey) {
7240             sfree(s->rsakeydata);
7241             bombout(("unable to parse RSA public key from server"));
7242             crStopV;
7243         }
7244
7245         hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7246
7247         /*
7248          * Next, set up a shared secret K, of precisely KLEN -
7249          * 2*HLEN - 49 bits, where KLEN is the bit length of the
7250          * RSA key modulus and HLEN is the bit length of the hash
7251          * we're using.
7252          */
7253         {
7254             int klen = ssh_rsakex_klen(s->rsakey);
7255             int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7256             int i, byte = 0;
7257             unsigned char *kstr1, *kstr2, *outstr;
7258             int kstr1len, kstr2len, outstrlen;
7259
7260             s->K = bn_power_2(nbits - 1);
7261
7262             for (i = 0; i < nbits; i++) {
7263                 if ((i & 7) == 0) {
7264                     byte = random_byte();
7265                 }
7266                 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7267             }
7268
7269             /*
7270              * Encode this as an mpint.
7271              */
7272             kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7273             kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7274             PUT_32BIT(kstr2, kstr1len);
7275             memcpy(kstr2 + 4, kstr1, kstr1len);
7276
7277             /*
7278              * Encrypt it with the given RSA key.
7279              */
7280             outstrlen = (klen + 7) / 8;
7281             outstr = snewn(outstrlen, unsigned char);
7282             ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7283                                outstr, outstrlen, s->rsakey);
7284
7285             /*
7286              * And send it off in a return packet.
7287              */
7288             s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7289             ssh2_pkt_addstring_start(s->pktout);
7290             ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7291             ssh2_pkt_send_noqueue(ssh, s->pktout);
7292
7293             hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7294
7295             sfree(kstr2);
7296             sfree(kstr1);
7297             sfree(outstr);
7298         }
7299
7300         ssh_rsakex_freekey(s->rsakey);
7301
7302         crWaitUntilV(pktin);
7303         if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7304             sfree(s->rsakeydata);
7305             bombout(("expected signature packet from server"));
7306             crStopV;
7307         }
7308
7309         ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7310         if (!s->sigdata) {
7311             bombout(("unable to parse signature packet"));
7312             crStopV;
7313         }
7314
7315         sfree(s->rsakeydata);
7316     }
7317
7318     hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7319     assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7320     ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7321
7322     ssh->kex_ctx = NULL;
7323
7324 #if 0
7325     debug(("Exchange hash is:\n"));
7326     dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7327 #endif
7328
7329     if (!s->hkey) {
7330         bombout(("Server's host key is invalid"));
7331         crStopV;
7332     }
7333
7334     if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7335                                  (char *)s->exchange_hash,
7336                                  ssh->kex->hash->hlen)) {
7337 #ifndef FUZZING
7338         bombout(("Server's host key did not match the signature supplied"));
7339         crStopV;
7340 #endif
7341     }
7342
7343     s->keystr = ssh->hostkey->fmtkey(s->hkey);
7344     if (!s->got_session_id) {
7345         /*
7346          * Make a note of any other host key formats that are available.
7347          */
7348         {
7349             int i, j, nkeys = 0;
7350             char *list = NULL;
7351             for (i = 0; i < lenof(hostkey_algs); i++) {
7352                 if (hostkey_algs[i].alg == ssh->hostkey)
7353                     continue;
7354
7355                 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7356                     if (ssh->uncert_hostkeys[j] == i)
7357                         break;
7358
7359                 if (j < ssh->n_uncert_hostkeys) {
7360                     char *newlist;
7361                     if (list)
7362                         newlist = dupprintf("%s/%s", list,
7363                                             hostkey_algs[i].alg->name);
7364                     else
7365                         newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7366                     sfree(list);
7367                     list = newlist;
7368                     nkeys++;
7369                 }
7370             }
7371             if (list) {
7372                 logeventf(ssh,
7373                           "Server also has %s host key%s, but we "
7374                           "don't know %s", list,
7375                           nkeys > 1 ? "s" : "",
7376                           nkeys > 1 ? "any of them" : "it");
7377                 sfree(list);
7378             }
7379         }
7380
7381         /*
7382          * Authenticate remote host: verify host key. (We've already
7383          * checked the signature of the exchange hash.)
7384          */
7385         s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7386         logevent("Host key fingerprint is:");
7387         logevent(s->fingerprint);
7388         /* First check against manually configured host keys. */
7389         s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7390                                                ssh->hostkey, s->hkey);
7391         if (s->dlgret == 0) {          /* did not match */
7392             bombout(("Host key did not appear in manually configured list"));
7393             crStopV;
7394         } else if (s->dlgret < 0) { /* none configured; use standard handling */
7395             ssh_set_frozen(ssh, 1);
7396             s->dlgret = verify_ssh_host_key(ssh->frontend,
7397                                             ssh->savedhost, ssh->savedport,
7398                                             ssh->hostkey->keytype, s->keystr,
7399                                             s->fingerprint,
7400                                             ssh_dialog_callback, ssh);
7401 #ifdef FUZZING
7402             s->dlgret = 1;
7403 #endif
7404             if (s->dlgret < 0) {
7405                 do {
7406                     crReturnV;
7407                     if (pktin) {
7408                         bombout(("Unexpected data from server while waiting"
7409                                  " for user host key response"));
7410                         crStopV;
7411                     }
7412                 } while (pktin || inlen > 0);
7413                 s->dlgret = ssh->user_response;
7414             }
7415             ssh_set_frozen(ssh, 0);
7416             if (s->dlgret == 0) {
7417                 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7418                                0, TRUE);
7419                 crStopV;
7420             }
7421         }
7422         sfree(s->fingerprint);
7423         /*
7424          * Save this host key, to check against the one presented in
7425          * subsequent rekeys.
7426          */
7427         ssh->hostkey_str = s->keystr;
7428     } else if (ssh->cross_certifying) {
7429         s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7430         logevent("Storing additional host key for this host:");
7431         logevent(s->fingerprint);
7432         sfree(s->fingerprint);
7433         store_host_key(ssh->savedhost, ssh->savedport,
7434                        ssh->hostkey->keytype, s->keystr);
7435         ssh->cross_certifying = FALSE;
7436         /*
7437          * Don't forget to store the new key as the one we'll be
7438          * re-checking in future normal rekeys.
7439          */
7440         ssh->hostkey_str = s->keystr;
7441     } else {
7442         /*
7443          * In a rekey, we never present an interactive host key
7444          * verification request to the user. Instead, we simply
7445          * enforce that the key we're seeing this time is identical to
7446          * the one we saw before.
7447          */
7448         if (strcmp(ssh->hostkey_str, s->keystr)) {
7449 #ifndef FUZZING
7450             bombout(("Host key was different in repeat key exchange"));
7451             crStopV;
7452 #endif
7453         }
7454         sfree(s->keystr);
7455     }
7456     ssh->hostkey->freekey(s->hkey);
7457
7458     /*
7459      * The exchange hash from the very first key exchange is also
7460      * the session id, used in session key construction and
7461      * authentication.
7462      */
7463     if (!s->got_session_id) {
7464         assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7465         memcpy(ssh->v2_session_id, s->exchange_hash,
7466                sizeof(s->exchange_hash));
7467         ssh->v2_session_id_len = ssh->kex->hash->hlen;
7468         assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7469         s->got_session_id = TRUE;
7470     }
7471
7472     /*
7473      * Send SSH2_MSG_NEWKEYS.
7474      */
7475     s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7476     ssh2_pkt_send_noqueue(ssh, s->pktout);
7477     ssh->outgoing_data_size = 0;       /* start counting from here */
7478
7479     /*
7480      * We've sent client NEWKEYS, so create and initialise
7481      * client-to-server session keys.
7482      */
7483     if (ssh->cs_cipher_ctx)
7484         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7485     ssh->cscipher = s->cscipher_tobe;
7486     if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7487
7488     if (ssh->cs_mac_ctx)
7489         ssh->csmac->free_context(ssh->cs_mac_ctx);
7490     ssh->csmac = s->csmac_tobe;
7491     ssh->csmac_etm = s->csmac_etm_tobe;
7492     if (ssh->csmac)
7493         ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7494
7495     if (ssh->cs_comp_ctx)
7496         ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7497     ssh->cscomp = s->cscomp_tobe;
7498     ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7499
7500     /*
7501      * Set IVs on client-to-server keys. Here we use the exchange
7502      * hash from the _first_ key exchange.
7503      */
7504     if (ssh->cscipher) {
7505         unsigned char *key;
7506
7507         key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7508                          ssh->cscipher->padded_keybytes);
7509         ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7510         smemclr(key, ssh->cscipher->padded_keybytes);
7511         sfree(key);
7512
7513         key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7514                          ssh->cscipher->blksize);
7515         ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7516         smemclr(key, ssh->cscipher->blksize);
7517         sfree(key);
7518     }
7519     if (ssh->csmac) {
7520         unsigned char *key;
7521
7522         key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7523                          ssh->csmac->keylen);
7524         ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7525         smemclr(key, ssh->csmac->keylen);
7526         sfree(key);
7527     }
7528
7529     if (ssh->cscipher)
7530         logeventf(ssh, "Initialised %.200s client->server encryption",
7531                   ssh->cscipher->text_name);
7532     if (ssh->csmac)
7533         logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7534                   ssh->csmac->text_name,
7535                   ssh->csmac_etm ? " (in ETM mode)" : "",
7536                   ssh->cscipher->required_mac ? " (required by cipher)" : "");
7537     if (ssh->cscomp->text_name)
7538         logeventf(ssh, "Initialised %s compression",
7539                   ssh->cscomp->text_name);
7540
7541     /*
7542      * Now our end of the key exchange is complete, we can send all
7543      * our queued higher-layer packets.
7544      */
7545     ssh->queueing = FALSE;
7546     ssh2_pkt_queuesend(ssh);
7547
7548     /*
7549      * Expect SSH2_MSG_NEWKEYS from server.
7550      */
7551     crWaitUntilV(pktin);
7552     if (pktin->type != SSH2_MSG_NEWKEYS) {
7553         bombout(("expected new-keys packet from server"));
7554         crStopV;
7555     }
7556     ssh->incoming_data_size = 0;       /* start counting from here */
7557
7558     /*
7559      * We've seen server NEWKEYS, so create and initialise
7560      * server-to-client session keys.
7561      */
7562     if (ssh->sc_cipher_ctx)
7563         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7564     if (s->sccipher_tobe) {
7565         ssh->sccipher = s->sccipher_tobe;
7566         ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7567     }
7568
7569     if (ssh->sc_mac_ctx)
7570         ssh->scmac->free_context(ssh->sc_mac_ctx);
7571     if (s->scmac_tobe) {
7572         ssh->scmac = s->scmac_tobe;
7573         ssh->scmac_etm = s->scmac_etm_tobe;
7574         ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7575     }
7576
7577     if (ssh->sc_comp_ctx)
7578         ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7579     ssh->sccomp = s->sccomp_tobe;
7580     ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7581
7582     /*
7583      * Set IVs on server-to-client keys. Here we use the exchange
7584      * hash from the _first_ key exchange.
7585      */
7586     if (ssh->sccipher) {
7587         unsigned char *key;
7588
7589         key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7590                          ssh->sccipher->padded_keybytes);
7591         ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7592         smemclr(key, ssh->sccipher->padded_keybytes);
7593         sfree(key);
7594
7595         key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7596                          ssh->sccipher->blksize);
7597         ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7598         smemclr(key, ssh->sccipher->blksize);
7599         sfree(key);
7600     }
7601     if (ssh->scmac) {
7602         unsigned char *key;
7603
7604         key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7605                          ssh->scmac->keylen);
7606         ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7607         smemclr(key, ssh->scmac->keylen);
7608         sfree(key);
7609     }
7610     if (ssh->sccipher)
7611         logeventf(ssh, "Initialised %.200s server->client encryption",
7612                   ssh->sccipher->text_name);
7613     if (ssh->scmac)
7614         logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7615                   ssh->scmac->text_name,
7616                   ssh->scmac_etm ? " (in ETM mode)" : "",
7617                   ssh->sccipher->required_mac ? " (required by cipher)" : "");
7618     if (ssh->sccomp->text_name)
7619         logeventf(ssh, "Initialised %s decompression",
7620                   ssh->sccomp->text_name);
7621
7622     /*
7623      * Free shared secret.
7624      */
7625     freebn(s->K);
7626
7627     /*
7628      * Update the specials menu to list the remaining uncertified host
7629      * keys.
7630      */
7631     update_specials_menu(ssh->frontend);
7632
7633     /*
7634      * Key exchange is over. Loop straight back round if we have a
7635      * deferred rekey reason.
7636      */
7637     if (ssh->deferred_rekey_reason) {
7638         logevent(ssh->deferred_rekey_reason);
7639         pktin = NULL;
7640         ssh->deferred_rekey_reason = NULL;
7641         goto begin_key_exchange;
7642     }
7643
7644     /*
7645      * Otherwise, schedule a timer for our next rekey.
7646      */
7647     ssh->kex_in_progress = FALSE;
7648     ssh->last_rekey = GETTICKCOUNT();
7649     if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7650         ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7651                                          ssh2_timer, ssh);
7652
7653     /*
7654      * Now we're encrypting. Begin returning 1 to the protocol main
7655      * function so that other things can run on top of the
7656      * transport. If we ever see a KEXINIT, we must go back to the
7657      * start.
7658      * 
7659      * We _also_ go back to the start if we see pktin==NULL and
7660      * inlen negative, because this is a special signal meaning
7661      * `initiate client-driven rekey', and `in' contains a message
7662      * giving the reason for the rekey.
7663      *
7664      * inlen==-1 means always initiate a rekey;
7665      * inlen==-2 means that userauth has completed successfully and
7666      *   we should consider rekeying (for delayed compression).
7667      */
7668     while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7669              (!pktin && inlen < 0))) {
7670         wait_for_rekey:
7671         if (!ssh->protocol_initial_phase_done) {
7672             ssh->protocol_initial_phase_done = TRUE;
7673             /*
7674              * Allow authconn to initialise itself.
7675              */
7676             do_ssh2_authconn(ssh, NULL, 0, NULL);
7677         }
7678         crReturnV;
7679     }
7680     if (pktin) {
7681         logevent("Server initiated key re-exchange");
7682     } else {
7683         if (inlen == -2) {
7684             /* 
7685              * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7686              * delayed compression, if it's available.
7687              *
7688              * draft-miller-secsh-compression-delayed-00 says that you
7689              * negotiate delayed compression in the first key exchange, and
7690              * both sides start compressing when the server has sent
7691              * USERAUTH_SUCCESS. This has a race condition -- the server
7692              * can't know when the client has seen it, and thus which incoming
7693              * packets it should treat as compressed.
7694              *
7695              * Instead, we do the initial key exchange without offering the
7696              * delayed methods, but note if the server offers them; when we
7697              * get here, if a delayed method was available that was higher
7698              * on our list than what we got, we initiate a rekey in which we
7699              * _do_ list the delayed methods (and hopefully get it as a
7700              * result). Subsequent rekeys will do the same.
7701              */
7702             assert(!s->userauth_succeeded); /* should only happen once */
7703             s->userauth_succeeded = TRUE;
7704             if (!s->pending_compression)
7705                 /* Can't see any point rekeying. */
7706                 goto wait_for_rekey;       /* this is utterly horrid */
7707             /* else fall through to rekey... */
7708             s->pending_compression = FALSE;
7709         }
7710         /*
7711          * Now we've decided to rekey.
7712          *
7713          * Special case: if the server bug is set that doesn't
7714          * allow rekeying, we give a different log message and
7715          * continue waiting. (If such a server _initiates_ a rekey,
7716          * we process it anyway!)
7717          */
7718         if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7719             logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7720                       (char *)in);
7721             /* Reset the counters, so that at least this message doesn't
7722              * hit the event log _too_ often. */
7723             ssh->outgoing_data_size = 0;
7724             ssh->incoming_data_size = 0;
7725             if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7726                 ssh->next_rekey =
7727                     schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7728                                    ssh2_timer, ssh);
7729             }
7730             goto wait_for_rekey;       /* this is still utterly horrid */
7731         } else {
7732             logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7733         }
7734     }
7735     goto begin_key_exchange;
7736
7737     crFinishV;
7738 }
7739
7740 /*
7741  * Send data on an SSH channel.  In SSH-2, this involves buffering it
7742  * first.
7743  */
7744 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7745                                    int len)
7746 {
7747     if (c->ssh->version == 2) {
7748         bufchain_add(&c->v.v2.outbuffer, buf, len);
7749         return ssh2_try_send(c);
7750     } else {
7751         send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7752                     PKT_INT, c->remoteid,
7753                     PKT_INT, len,
7754                     PKT_DATA, buf, len,
7755                     PKT_END);
7756         /*
7757          * In SSH-1 we can return 0 here - implying that channels are
7758          * never individually throttled - because the only
7759          * circumstance that can cause throttling will be the whole
7760          * SSH connection backing up, in which case _everything_ will
7761          * be throttled as a whole.
7762          */
7763         return 0;
7764     }
7765 }
7766
7767 /*
7768  * Attempt to send data on an SSH-2 channel.
7769  */
7770 static int ssh2_try_send(struct ssh_channel *c)
7771 {
7772     Ssh ssh = c->ssh;
7773     struct Packet *pktout;
7774     int ret;
7775
7776     while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7777         int len;
7778         void *data;
7779         bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7780         if ((unsigned)len > c->v.v2.remwindow)
7781             len = c->v.v2.remwindow;
7782         if ((unsigned)len > c->v.v2.remmaxpkt)
7783             len = c->v.v2.remmaxpkt;
7784         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7785         ssh2_pkt_adduint32(pktout, c->remoteid);
7786         ssh2_pkt_addstring_start(pktout);
7787         ssh2_pkt_addstring_data(pktout, data, len);
7788         ssh2_pkt_send(ssh, pktout);
7789         bufchain_consume(&c->v.v2.outbuffer, len);
7790         c->v.v2.remwindow -= len;
7791     }
7792
7793     /*
7794      * After having sent as much data as we can, return the amount
7795      * still buffered.
7796      */
7797     ret = bufchain_size(&c->v.v2.outbuffer);
7798
7799     /*
7800      * And if there's no data pending but we need to send an EOF, send
7801      * it.
7802      */
7803     if (!ret && c->pending_eof)
7804         ssh_channel_try_eof(c);
7805
7806     return ret;
7807 }
7808
7809 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7810 {
7811     int bufsize;
7812     if (c->closes & CLOSES_SENT_EOF)
7813         return;                   /* don't send on channels we've EOFed */
7814     bufsize = ssh2_try_send(c);
7815     if (bufsize == 0) {
7816         switch (c->type) {
7817           case CHAN_MAINSESSION:
7818             /* stdin need not receive an unthrottle
7819              * notification since it will be polled */
7820             break;
7821           case CHAN_X11:
7822             x11_unthrottle(c->u.x11.xconn);
7823             break;
7824           case CHAN_AGENT:
7825             /* Now that we've successfully sent all the outgoing
7826              * replies we had, try to process more incoming data. */
7827             ssh_agentf_try_forward(c);
7828             break;
7829           case CHAN_SOCKDATA:
7830             pfd_unthrottle(c->u.pfd.pf);
7831             break;
7832         }
7833     }
7834 }
7835
7836 static int ssh_is_simple(Ssh ssh)
7837 {
7838     /*
7839      * We use the 'simple' variant of the SSH protocol if we're asked
7840      * to, except not if we're also doing connection-sharing (either
7841      * tunnelling our packets over an upstream or expecting to be
7842      * tunnelled over ourselves), since then the assumption that we
7843      * have only one channel to worry about is not true after all.
7844      */
7845     return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7846             !ssh->bare_connection && !ssh->connshare);
7847 }
7848
7849 /*
7850  * Set up most of a new ssh_channel.
7851  */
7852 static void ssh_channel_init(struct ssh_channel *c)
7853 {
7854     Ssh ssh = c->ssh;
7855     c->localid = alloc_channel_id(ssh);
7856     c->closes = 0;
7857     c->pending_eof = FALSE;
7858     c->throttling_conn = FALSE;
7859     if (ssh->version == 2) {
7860         c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7861             ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7862         c->v.v2.chanreq_head = NULL;
7863         c->v.v2.throttle_state = UNTHROTTLED;
7864         bufchain_init(&c->v.v2.outbuffer);
7865     }
7866     add234(ssh->channels, c);
7867 }
7868
7869 /*
7870  * Construct the common parts of a CHANNEL_OPEN.
7871  */
7872 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7873                                          const char *type)
7874 {
7875     struct Packet *pktout;
7876
7877     pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7878     ssh2_pkt_addstring(pktout, type);
7879     ssh2_pkt_adduint32(pktout, c->localid);
7880     ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7881     ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
7882     return pktout;
7883 }
7884
7885 /*
7886  * CHANNEL_FAILURE doesn't come with any indication of what message
7887  * caused it, so we have to keep track of the outstanding
7888  * CHANNEL_REQUESTs ourselves.
7889  */
7890 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7891                                        cchandler_fn_t handler, void *ctx)
7892 {
7893     struct outstanding_channel_request *ocr =
7894         snew(struct outstanding_channel_request);
7895
7896     assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7897     ocr->handler = handler;
7898     ocr->ctx = ctx;
7899     ocr->next = NULL;
7900     if (!c->v.v2.chanreq_head)
7901         c->v.v2.chanreq_head = ocr;
7902     else
7903         c->v.v2.chanreq_tail->next = ocr;
7904     c->v.v2.chanreq_tail = ocr;
7905 }
7906
7907 /*
7908  * Construct the common parts of a CHANNEL_REQUEST.  If handler is not
7909  * NULL then a reply will be requested and the handler will be called
7910  * when it arrives.  The returned packet is ready to have any
7911  * request-specific data added and be sent.  Note that if a handler is
7912  * provided, it's essential that the request actually be sent.
7913  *
7914  * The handler will usually be passed the response packet in pktin. If
7915  * pktin is NULL, this means that no reply will ever be forthcoming
7916  * (e.g. because the entire connection is being destroyed, or because
7917  * the server initiated channel closure before we saw the response)
7918  * and the handler should free any storage it's holding.
7919  */
7920 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7921                                         const char *type,
7922                                         cchandler_fn_t handler, void *ctx)
7923 {
7924     struct Packet *pktout;
7925
7926     assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7927     pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7928     ssh2_pkt_adduint32(pktout, c->remoteid);
7929     ssh2_pkt_addstring(pktout, type);
7930     ssh2_pkt_addbool(pktout, handler != NULL);
7931     if (handler != NULL)
7932         ssh2_queue_chanreq_handler(c, handler, ctx);
7933     return pktout;
7934 }
7935
7936 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7937 {
7938     Ssh ssh = c->ssh;
7939     int buflimit;
7940
7941     if (ssh->version == 1) {
7942         buflimit = SSH1_BUFFER_LIMIT;
7943     } else {
7944         if (ssh_is_simple(ssh))
7945             buflimit = 0;
7946         else
7947             buflimit = c->v.v2.locmaxwin;
7948         if (bufsize < buflimit)
7949             ssh2_set_window(c, buflimit - bufsize);
7950     }
7951     if (c->throttling_conn && bufsize <= buflimit) {
7952         c->throttling_conn = 0;
7953         ssh_throttle_conn(ssh, -1);
7954     }
7955 }
7956
7957 /*
7958  * Potentially enlarge the window on an SSH-2 channel.
7959  */
7960 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7961                                         void *);
7962 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7963 {
7964     Ssh ssh = c->ssh;
7965
7966     /*
7967      * Never send WINDOW_ADJUST for a channel that the remote side has
7968      * already sent EOF on; there's no point, since it won't be
7969      * sending any more data anyway. Ditto if _we've_ already sent
7970      * CLOSE.
7971      */
7972     if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7973         return;
7974
7975     /*
7976      * Also, never widen the window for an X11 channel when we're
7977      * still waiting to see its initial auth and may yet hand it off
7978      * to a downstream.
7979      */
7980     if (c->type == CHAN_X11 && c->u.x11.initial)
7981         return;
7982
7983     /*
7984      * If the remote end has a habit of ignoring maxpkt, limit the
7985      * window so that it has no choice (assuming it doesn't ignore the
7986      * window as well).
7987      */
7988     if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7989         newwin = OUR_V2_MAXPKT;
7990
7991     /*
7992      * Only send a WINDOW_ADJUST if there's significantly more window
7993      * available than the other end thinks there is.  This saves us
7994      * sending a WINDOW_ADJUST for every character in a shell session.
7995      *
7996      * "Significant" is arbitrarily defined as half the window size.
7997      */
7998     if (newwin / 2 >= c->v.v2.locwindow) {
7999         struct Packet *pktout;
8000         unsigned *up;
8001
8002         /*
8003          * In order to keep track of how much window the client
8004          * actually has available, we'd like it to acknowledge each
8005          * WINDOW_ADJUST.  We can't do that directly, so we accompany
8006          * it with a CHANNEL_REQUEST that has to be acknowledged.
8007          *
8008          * This is only necessary if we're opening the window wide.
8009          * If we're not, then throughput is being constrained by
8010          * something other than the maximum window size anyway.
8011          */
8012         if (newwin == c->v.v2.locmaxwin &&
8013             !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
8014             up = snew(unsigned);
8015             *up = newwin - c->v.v2.locwindow;
8016             pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
8017                                        ssh2_handle_winadj_response, up);
8018             ssh2_pkt_send(ssh, pktout);
8019
8020             if (c->v.v2.throttle_state != UNTHROTTLED)
8021                 c->v.v2.throttle_state = UNTHROTTLING;
8022         } else {
8023             /* Pretend the WINDOW_ADJUST was acked immediately. */
8024             c->v.v2.remlocwin = newwin;
8025             c->v.v2.throttle_state = THROTTLED;
8026         }
8027         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
8028         ssh2_pkt_adduint32(pktout, c->remoteid);
8029         ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
8030         ssh2_pkt_send(ssh, pktout);
8031         c->v.v2.locwindow = newwin;
8032     }
8033 }
8034
8035 /*
8036  * Find the channel associated with a message.  If there's no channel,
8037  * or it's not properly open, make a noise about it and return NULL.
8038  * If the channel is shared, pass the message on to downstream and
8039  * also return NULL (meaning the caller should ignore this message).
8040  */
8041 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
8042 {
8043     unsigned localid = ssh_pkt_getuint32(pktin);
8044     struct ssh_channel *c;
8045     int halfopen_ok;
8046
8047     /* Is this message OK on a half-open connection? */
8048     if (ssh->version == 1)
8049         halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
8050                        pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
8051     else
8052         halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
8053                        pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
8054     c = find234(ssh->channels, &localid, ssh_channelfind);
8055     if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
8056         char *buf = dupprintf("Received %s for %s channel %u",
8057                               ssh_pkt_type(ssh, pktin->type),
8058                               !c ? "nonexistent" :
8059                               c->halfopen ? "half-open" : "open",
8060                               localid);
8061         ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
8062         sfree(buf);
8063         return NULL;
8064     }
8065     if (c->type == CHAN_SHARING) {
8066         share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8067                                   pktin->body, pktin->length);
8068         return NULL;
8069     }
8070     return c;
8071 }
8072
8073 static void ssh2_handle_winadj_response(struct ssh_channel *c,
8074                                         struct Packet *pktin, void *ctx)
8075 {
8076     unsigned *sizep = ctx;
8077
8078     /*
8079      * Winadj responses should always be failures. However, at least
8080      * one server ("boks_sshd") is known to return SUCCESS for channel
8081      * requests it's never heard of, such as "winadj@putty". Raised
8082      * with foxt.com as bug 090916-090424, but for the sake of a quiet
8083      * life, we don't worry about what kind of response we got.
8084      */
8085
8086     c->v.v2.remlocwin += *sizep;
8087     sfree(sizep);
8088     /*
8089      * winadj messages are only sent when the window is fully open, so
8090      * if we get an ack of one, we know any pending unthrottle is
8091      * complete.
8092      */
8093     if (c->v.v2.throttle_state == UNTHROTTLING)
8094         c->v.v2.throttle_state = UNTHROTTLED;
8095 }
8096
8097 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8098 {
8099     struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
8100     struct outstanding_channel_request *ocr;
8101
8102     if (!c) return;
8103     ocr = c->v.v2.chanreq_head;
8104     if (!ocr) {
8105         ssh2_msg_unexpected(ssh, pktin);
8106         return;
8107     }
8108     ocr->handler(c, pktin, ocr->ctx);
8109     c->v.v2.chanreq_head = ocr->next;
8110     sfree(ocr);
8111     /*
8112      * We may now initiate channel-closing procedures, if that
8113      * CHANNEL_REQUEST was the last thing outstanding before we send
8114      * CHANNEL_CLOSE.
8115      */
8116     ssh2_channel_check_close(c);
8117 }
8118
8119 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8120 {
8121     struct ssh_channel *c;
8122     c = ssh_channel_msg(ssh, pktin);
8123     if (!c)
8124         return;
8125     if (!(c->closes & CLOSES_SENT_EOF)) {
8126         c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8127         ssh2_try_send_and_unthrottle(ssh, c);
8128     }
8129 }
8130
8131 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8132 {
8133     char *data;
8134     int length;
8135     unsigned ext_type = 0; /* 0 means not extended */
8136     struct ssh_channel *c;
8137     c = ssh_channel_msg(ssh, pktin);
8138     if (!c)
8139         return;
8140     if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
8141         ext_type = ssh_pkt_getuint32(pktin);
8142     ssh_pkt_getstring(pktin, &data, &length);
8143     if (data) {
8144         int bufsize;
8145         c->v.v2.locwindow -= length;
8146         c->v.v2.remlocwin -= length;
8147         if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
8148             length = 0; /* Don't do anything with unknown extended data. */
8149         bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
8150                                    data, length);
8151         /*
8152          * If it looks like the remote end hit the end of its window,
8153          * and we didn't want it to do that, think about using a
8154          * larger window.
8155          */
8156         if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8157             c->v.v2.locmaxwin < 0x40000000)
8158             c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8159         /*
8160          * If we are not buffering too much data,
8161          * enlarge the window again at the remote side.
8162          * If we are buffering too much, we may still
8163          * need to adjust the window if the server's
8164          * sent excess data.
8165          */
8166         if (bufsize < c->v.v2.locmaxwin)
8167             ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8168         /*
8169          * If we're either buffering way too much data, or if we're
8170          * buffering anything at all and we're in "simple" mode,
8171          * throttle the whole channel.
8172          */
8173         if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8174             && !c->throttling_conn) {
8175             c->throttling_conn = 1;
8176             ssh_throttle_conn(ssh, +1);
8177         }
8178     }
8179 }
8180
8181 static void ssh_check_termination(Ssh ssh)
8182 {
8183     if (ssh->version == 2 &&
8184         !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8185         (ssh->channels && count234(ssh->channels) == 0) &&
8186         !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8187         /*
8188          * We used to send SSH_MSG_DISCONNECT here, because I'd
8189          * believed that _every_ conforming SSH-2 connection had to
8190          * end with a disconnect being sent by at least one side;
8191          * apparently I was wrong and it's perfectly OK to
8192          * unceremoniously slam the connection shut when you're done,
8193          * and indeed OpenSSH feels this is more polite than sending a
8194          * DISCONNECT. So now we don't.
8195          */
8196         ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8197     }
8198 }
8199
8200 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8201                                       const char *peerinfo)
8202 {
8203     if (peerinfo)
8204         logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8205                   id, peerinfo);
8206     else
8207         logeventf(ssh, "Connection sharing downstream #%u connected", id);
8208 }
8209
8210 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8211 {
8212     logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8213     ssh_check_termination(ssh);
8214 }
8215
8216 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8217 {
8218     va_list ap;
8219     char *buf;
8220
8221     va_start(ap, logfmt);
8222     buf = dupvprintf(logfmt, ap);
8223     va_end(ap);
8224     if (id)
8225         logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8226     else
8227         logeventf(ssh, "Connection sharing: %s", buf);
8228     sfree(buf);
8229 }
8230
8231 /*
8232  * Close any local socket and free any local resources associated with
8233  * a channel.  This converts the channel into a CHAN_ZOMBIE.
8234  */
8235 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
8236 {
8237     Ssh ssh = c->ssh;
8238     char const *msg = NULL;
8239
8240     switch (c->type) {
8241       case CHAN_MAINSESSION:
8242         ssh->mainchan = NULL;
8243         update_specials_menu(ssh->frontend);
8244         break;
8245       case CHAN_X11:
8246         assert(c->u.x11.xconn != NULL);
8247         x11_close(c->u.x11.xconn);
8248         msg = "Forwarded X11 connection terminated";
8249         break;
8250       case CHAN_AGENT:
8251         if (c->u.a.pending)
8252             agent_cancel_query(c->u.a.pending);
8253         bufchain_clear(&c->u.a.inbuffer);
8254         msg = "Agent-forwarding connection closed";
8255         break;
8256       case CHAN_SOCKDATA:
8257         assert(c->u.pfd.pf != NULL);
8258         pfd_close(c->u.pfd.pf);
8259         msg = "Forwarded port closed";
8260         break;
8261     }
8262     c->type = CHAN_ZOMBIE;
8263     if (msg != NULL) {
8264         if (reason != NULL)
8265             logeventf(ssh, "%s %s", msg, reason);
8266         else
8267             logevent(msg);
8268     }
8269 }
8270
8271 static void ssh_channel_destroy(struct ssh_channel *c)
8272 {
8273     Ssh ssh = c->ssh;
8274
8275     ssh_channel_close_local(c, NULL);
8276
8277     del234(ssh->channels, c);
8278     if (ssh->version == 2) {
8279         bufchain_clear(&c->v.v2.outbuffer);
8280         assert(c->v.v2.chanreq_head == NULL);
8281     }
8282     sfree(c);
8283
8284     /*
8285      * If that was the last channel left open, we might need to
8286      * terminate.
8287      */
8288     ssh_check_termination(ssh);
8289 }
8290
8291 static void ssh2_channel_check_close(struct ssh_channel *c)
8292 {
8293     Ssh ssh = c->ssh;
8294     struct Packet *pktout;
8295
8296     assert(ssh->version == 2);
8297     if (c->halfopen) {
8298         /*
8299          * If we've sent out our own CHANNEL_OPEN but not yet seen
8300          * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8301          * it's too early to be sending close messages of any kind.
8302          */
8303         return;
8304     }
8305
8306     if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8307          c->type == CHAN_ZOMBIE) &&
8308         !c->v.v2.chanreq_head &&
8309         !(c->closes & CLOSES_SENT_CLOSE)) {
8310         /*
8311          * We have both sent and received EOF (or the channel is a
8312          * zombie), and we have no outstanding channel requests, which
8313          * means the channel is in final wind-up. But we haven't sent
8314          * CLOSE, so let's do so now.
8315          */
8316         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8317         ssh2_pkt_adduint32(pktout, c->remoteid);
8318         ssh2_pkt_send(ssh, pktout);
8319         c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8320     }
8321
8322     if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8323         assert(c->v.v2.chanreq_head == NULL);
8324         /*
8325          * We have both sent and received CLOSE, which means we're
8326          * completely done with the channel.
8327          */
8328         ssh_channel_destroy(c);
8329     }
8330 }
8331
8332 static void ssh_channel_got_eof(struct ssh_channel *c)
8333 {
8334     if (c->closes & CLOSES_RCVD_EOF)
8335         return;                        /* already seen EOF */
8336     c->closes |= CLOSES_RCVD_EOF;
8337
8338     if (c->type == CHAN_X11) {
8339         assert(c->u.x11.xconn != NULL);
8340         x11_send_eof(c->u.x11.xconn);
8341     } else if (c->type == CHAN_AGENT) {
8342         /* Just call try_forward, which will respond to the EOF now if
8343          * appropriate, or wait until the queue of outstanding
8344          * requests is dealt with if not */
8345         ssh_agentf_try_forward(c);
8346     } else if (c->type == CHAN_SOCKDATA) {
8347         assert(c->u.pfd.pf != NULL);
8348         pfd_send_eof(c->u.pfd.pf);
8349     } else if (c->type == CHAN_MAINSESSION) {
8350         Ssh ssh = c->ssh;
8351
8352         if (!ssh->sent_console_eof &&
8353             (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8354             /*
8355              * Either from_backend_eof told us that the front end
8356              * wants us to close the outgoing side of the connection
8357              * as soon as we see EOF from the far end, or else we've
8358              * unilaterally decided to do that because we've allocated
8359              * a remote pty and hence EOF isn't a particularly
8360              * meaningful concept.
8361              */
8362             sshfwd_write_eof(c);
8363         }
8364         ssh->sent_console_eof = TRUE;
8365     }
8366 }
8367
8368 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8369 {
8370     struct ssh_channel *c;
8371
8372     c = ssh_channel_msg(ssh, pktin);
8373     if (!c)
8374         return;
8375     ssh_channel_got_eof(c);
8376     ssh2_channel_check_close(c);
8377 }
8378
8379 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8380 {
8381     struct ssh_channel *c;
8382
8383     c = ssh_channel_msg(ssh, pktin);
8384     if (!c)
8385         return;
8386
8387     /*
8388      * When we receive CLOSE on a channel, we assume it comes with an
8389      * implied EOF if we haven't seen EOF yet.
8390      */
8391     ssh_channel_got_eof(c);
8392
8393     if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8394         /*
8395          * It also means we stop expecting to see replies to any
8396          * outstanding channel requests, so clean those up too.
8397          * (ssh_chanreq_init will enforce by assertion that we don't
8398          * subsequently put anything back on this list.)
8399          */
8400         while (c->v.v2.chanreq_head) {
8401             struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8402             ocr->handler(c, NULL, ocr->ctx);
8403             c->v.v2.chanreq_head = ocr->next;
8404             sfree(ocr);
8405         }
8406     }
8407
8408     /*
8409      * And we also send an outgoing EOF, if we haven't already, on the
8410      * assumption that CLOSE is a pretty forceful announcement that
8411      * the remote side is doing away with the entire channel. (If it
8412      * had wanted to send us EOF and continue receiving data from us,
8413      * it would have just sent CHANNEL_EOF.)
8414      */
8415     if (!(c->closes & CLOSES_SENT_EOF)) {
8416         /*
8417          * Make sure we don't read any more from whatever our local
8418          * data source is for this channel.
8419          */
8420         switch (c->type) {
8421           case CHAN_MAINSESSION:
8422             ssh->send_ok = 0;     /* stop trying to read from stdin */
8423             break;
8424           case CHAN_X11:
8425             x11_override_throttle(c->u.x11.xconn, 1);
8426             break;
8427           case CHAN_SOCKDATA:
8428             pfd_override_throttle(c->u.pfd.pf, 1);
8429             break;
8430         }
8431
8432         /*
8433          * Abandon any buffered data we still wanted to send to this
8434          * channel. Receiving a CHANNEL_CLOSE is an indication that
8435          * the server really wants to get on and _destroy_ this
8436          * channel, and it isn't going to send us any further
8437          * WINDOW_ADJUSTs to permit us to send pending stuff.
8438          */
8439         bufchain_clear(&c->v.v2.outbuffer);
8440
8441         /*
8442          * Send outgoing EOF.
8443          */
8444         sshfwd_write_eof(c);
8445     }
8446
8447     /*
8448      * Now process the actual close.
8449      */
8450     if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8451         c->closes |= CLOSES_RCVD_CLOSE;
8452         ssh2_channel_check_close(c);
8453     }
8454 }
8455
8456 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8457 {
8458     struct ssh_channel *c;
8459
8460     c = ssh_channel_msg(ssh, pktin);
8461     if (!c)
8462         return;
8463     assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8464     c->remoteid = ssh_pkt_getuint32(pktin);
8465     c->halfopen = FALSE;
8466     c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8467     c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8468
8469     if (c->type == CHAN_SOCKDATA) {
8470         assert(c->u.pfd.pf != NULL);
8471         pfd_confirm(c->u.pfd.pf);
8472     } else if (c->type == CHAN_ZOMBIE) {
8473         /*
8474          * This case can occur if a local socket error occurred
8475          * between us sending out CHANNEL_OPEN and receiving
8476          * OPEN_CONFIRMATION. In this case, all we can do is
8477          * immediately initiate close proceedings now that we know the
8478          * server's id to put in the close message.
8479          */
8480         ssh2_channel_check_close(c);
8481     } else {
8482         /*
8483          * We never expect to receive OPEN_CONFIRMATION for any
8484          * *other* channel type (since only local-to-remote port
8485          * forwardings cause us to send CHANNEL_OPEN after the main
8486          * channel is live - all other auxiliary channel types are
8487          * initiated from the server end). It's safe to enforce this
8488          * by assertion rather than by ssh_disconnect, because the
8489          * real point is that we never constructed a half-open channel
8490          * structure in the first place with any type other than the
8491          * above.
8492          */
8493         assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8494     }
8495
8496     if (c->pending_eof)
8497         ssh_channel_try_eof(c);        /* in case we had a pending EOF */
8498 }
8499
8500 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8501 {
8502     static const char *const reasons[] = {
8503         "<unknown reason code>",
8504             "Administratively prohibited",
8505             "Connect failed",
8506             "Unknown channel type",
8507             "Resource shortage",
8508     };
8509     unsigned reason_code;
8510     char *reason_string;
8511     int reason_length;
8512     struct ssh_channel *c;
8513
8514     c = ssh_channel_msg(ssh, pktin);
8515     if (!c)
8516         return;
8517     assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8518
8519     if (c->type == CHAN_SOCKDATA) {
8520         reason_code = ssh_pkt_getuint32(pktin);
8521         if (reason_code >= lenof(reasons))
8522             reason_code = 0; /* ensure reasons[reason_code] in range */
8523         ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8524         logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8525                   reasons[reason_code], reason_length,
8526                   NULLTOEMPTY(reason_string));
8527
8528         pfd_close(c->u.pfd.pf);
8529     } else if (c->type == CHAN_ZOMBIE) {
8530         /*
8531          * This case can occur if a local socket error occurred
8532          * between us sending out CHANNEL_OPEN and receiving
8533          * OPEN_FAILURE. In this case, we need do nothing except allow
8534          * the code below to throw the half-open channel away.
8535          */
8536     } else {
8537         /*
8538          * We never expect to receive OPEN_FAILURE for any *other*
8539          * channel type (since only local-to-remote port forwardings
8540          * cause us to send CHANNEL_OPEN after the main channel is
8541          * live - all other auxiliary channel types are initiated from
8542          * the server end). It's safe to enforce this by assertion
8543          * rather than by ssh_disconnect, because the real point is
8544          * that we never constructed a half-open channel structure in
8545          * the first place with any type other than the above.
8546          */
8547         assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8548     }
8549
8550     del234(ssh->channels, c);
8551     sfree(c);
8552 }
8553
8554 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8555 {
8556     char *type;
8557     int typelen, want_reply;
8558     int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8559     struct ssh_channel *c;
8560     struct Packet *pktout;
8561
8562     c = ssh_channel_msg(ssh, pktin);
8563     if (!c)
8564         return;
8565     ssh_pkt_getstring(pktin, &type, &typelen);
8566     want_reply = ssh2_pkt_getbool(pktin);
8567
8568     if (c->closes & CLOSES_SENT_CLOSE) {
8569         /*
8570          * We don't reply to channel requests after we've sent
8571          * CHANNEL_CLOSE for the channel, because our reply might
8572          * cross in the network with the other side's CHANNEL_CLOSE
8573          * and arrive after they have wound the channel up completely.
8574          */
8575         want_reply = FALSE;
8576     }
8577
8578     /*
8579      * Having got the channel number, we now look at
8580      * the request type string to see if it's something
8581      * we recognise.
8582      */
8583     if (c == ssh->mainchan) {
8584         /*
8585          * We recognise "exit-status" and "exit-signal" on
8586          * the primary channel.
8587          */
8588         if (typelen == 11 &&
8589             !memcmp(type, "exit-status", 11)) {
8590
8591             ssh->exitcode = ssh_pkt_getuint32(pktin);
8592             logeventf(ssh, "Server sent command exit status %d",
8593                       ssh->exitcode);
8594             reply = SSH2_MSG_CHANNEL_SUCCESS;
8595
8596         } else if (typelen == 11 &&
8597                    !memcmp(type, "exit-signal", 11)) {
8598
8599             int is_plausible = TRUE, is_int = FALSE;
8600             char *fmt_sig = NULL, *fmt_msg = NULL;
8601             char *msg;
8602             int msglen = 0, core = FALSE;
8603             /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8604              * provide an `int' for the signal, despite its
8605              * having been a `string' in the drafts of RFC 4254 since at
8606              * least 2001. (Fixed in session.c 1.147.) Try to
8607              * infer which we can safely parse it as. */
8608             {
8609                 unsigned char *p = pktin->body +
8610                     pktin->savedpos;
8611                 long len = pktin->length - pktin->savedpos;
8612                 unsigned long num = GET_32BIT(p); /* what is it? */
8613                 /* If it's 0, it hardly matters; assume string */
8614                 if (num == 0) {
8615                     is_int = FALSE;
8616                 } else {
8617                     int maybe_int = FALSE, maybe_str = FALSE;
8618 #define CHECK_HYPOTHESIS(offset, result)                                \
8619                     do                                                  \
8620                     {                                                   \
8621                         int q = toint(offset);                          \
8622                         if (q >= 0 && q+4 <= len) {                     \
8623                             q = toint(q + 4 + GET_32BIT(p+q));          \
8624                             if (q >= 0 && q+4 <= len &&                 \
8625                                 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8626                                 q == len)                               \
8627                                 result = TRUE;                          \
8628                         }                                               \
8629                     } while(0)
8630                     CHECK_HYPOTHESIS(4+1, maybe_int);
8631                     CHECK_HYPOTHESIS(4+num+1, maybe_str);
8632 #undef CHECK_HYPOTHESIS
8633                     if (maybe_int && !maybe_str)
8634                         is_int = TRUE;
8635                     else if (!maybe_int && maybe_str)
8636                         is_int = FALSE;
8637                     else
8638                         /* Crikey. Either or neither. Panic. */
8639                         is_plausible = FALSE;
8640                 }
8641             }
8642             ssh->exitcode = 128;       /* means `unknown signal' */
8643             if (is_plausible) {
8644                 if (is_int) {
8645                     /* Old non-standard OpenSSH. */
8646                     int signum = ssh_pkt_getuint32(pktin);
8647                     fmt_sig = dupprintf(" %d", signum);
8648                     ssh->exitcode = 128 + signum;
8649                 } else {
8650                     /* As per RFC 4254. */
8651                     char *sig;
8652                     int siglen;
8653                     ssh_pkt_getstring(pktin, &sig, &siglen);
8654                     /* Signal name isn't supposed to be blank, but
8655                      * let's cope gracefully if it is. */
8656                     if (siglen) {
8657                         fmt_sig = dupprintf(" \"%.*s\"",
8658                                             siglen, sig);
8659                     }
8660
8661                     /*
8662                      * Really hideous method of translating the
8663                      * signal description back into a locally
8664                      * meaningful number.
8665                      */
8666
8667                     if (0)
8668                         ;
8669 #define TRANSLATE_SIGNAL(s) \
8670     else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8671         ssh->exitcode = 128 + SIG ## s
8672 #ifdef SIGABRT
8673                     TRANSLATE_SIGNAL(ABRT);
8674 #endif
8675 #ifdef SIGALRM
8676                     TRANSLATE_SIGNAL(ALRM);
8677 #endif
8678 #ifdef SIGFPE
8679                     TRANSLATE_SIGNAL(FPE);
8680 #endif
8681 #ifdef SIGHUP
8682                     TRANSLATE_SIGNAL(HUP);
8683 #endif
8684 #ifdef SIGILL
8685                     TRANSLATE_SIGNAL(ILL);
8686 #endif
8687 #ifdef SIGINT
8688                     TRANSLATE_SIGNAL(INT);
8689 #endif
8690 #ifdef SIGKILL
8691                     TRANSLATE_SIGNAL(KILL);
8692 #endif
8693 #ifdef SIGPIPE
8694                     TRANSLATE_SIGNAL(PIPE);
8695 #endif
8696 #ifdef SIGQUIT
8697                     TRANSLATE_SIGNAL(QUIT);
8698 #endif
8699 #ifdef SIGSEGV
8700                     TRANSLATE_SIGNAL(SEGV);
8701 #endif
8702 #ifdef SIGTERM
8703                     TRANSLATE_SIGNAL(TERM);
8704 #endif
8705 #ifdef SIGUSR1
8706                     TRANSLATE_SIGNAL(USR1);
8707 #endif
8708 #ifdef SIGUSR2
8709                     TRANSLATE_SIGNAL(USR2);
8710 #endif
8711 #undef TRANSLATE_SIGNAL
8712                     else
8713                         ssh->exitcode = 128;
8714                 }
8715                 core = ssh2_pkt_getbool(pktin);
8716                 ssh_pkt_getstring(pktin, &msg, &msglen);
8717                 if (msglen) {
8718                     fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8719                 }
8720                 /* ignore lang tag */
8721             } /* else don't attempt to parse */
8722             logeventf(ssh, "Server exited on signal%s%s%s",
8723                       fmt_sig ? fmt_sig : "",
8724                       core ? " (core dumped)" : "",
8725                       fmt_msg ? fmt_msg : "");
8726             sfree(fmt_sig);
8727             sfree(fmt_msg);
8728             reply = SSH2_MSG_CHANNEL_SUCCESS;
8729
8730         }
8731     } else {
8732         /*
8733          * This is a channel request we don't know
8734          * about, so we now either ignore the request
8735          * or respond with CHANNEL_FAILURE, depending
8736          * on want_reply.
8737          */
8738         reply = SSH2_MSG_CHANNEL_FAILURE;
8739     }
8740     if (want_reply) {
8741         pktout = ssh2_pkt_init(reply);
8742         ssh2_pkt_adduint32(pktout, c->remoteid);
8743         ssh2_pkt_send(ssh, pktout);
8744     }
8745 }
8746
8747 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8748 {
8749     char *type;
8750     int typelen, want_reply;
8751     struct Packet *pktout;
8752
8753     ssh_pkt_getstring(pktin, &type, &typelen);
8754     want_reply = ssh2_pkt_getbool(pktin);
8755
8756     /*
8757      * We currently don't support any global requests
8758      * at all, so we either ignore the request or
8759      * respond with REQUEST_FAILURE, depending on
8760      * want_reply.
8761      */
8762     if (want_reply) {
8763         pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8764         ssh2_pkt_send(ssh, pktout);
8765     }
8766 }
8767
8768 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8769                                                 void *share_cs,
8770                                                 void *share_chan)
8771 {
8772     struct X11FakeAuth *auth;
8773
8774     /*
8775      * Make up a new set of fake X11 auth data, and add it to the tree
8776      * of currently valid ones with an indication of the sharing
8777      * context that it's relevant to.
8778      */
8779     auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8780     auth->share_cs = share_cs;
8781     auth->share_chan = share_chan;
8782
8783     return auth;
8784 }
8785
8786 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8787 {
8788     del234(ssh->x11authtree, auth);
8789     x11_free_fake_auth(auth);
8790 }
8791
8792 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8793 {
8794     char *type;
8795     int typelen;
8796     char *peeraddr;
8797     int peeraddrlen;
8798     int peerport;
8799     const char *error = NULL;
8800     struct ssh_channel *c;
8801     unsigned remid, winsize, pktsize;
8802     unsigned our_winsize_override = 0;
8803     struct Packet *pktout;
8804
8805     ssh_pkt_getstring(pktin, &type, &typelen);
8806     c = snew(struct ssh_channel);
8807     c->ssh = ssh;
8808
8809     remid = ssh_pkt_getuint32(pktin);
8810     winsize = ssh_pkt_getuint32(pktin);
8811     pktsize = ssh_pkt_getuint32(pktin);
8812
8813     if (typelen == 3 && !memcmp(type, "x11", 3)) {
8814         char *addrstr;
8815
8816         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8817         addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8818         peerport = ssh_pkt_getuint32(pktin);
8819
8820         logeventf(ssh, "Received X11 connect request from %s:%d",
8821                   addrstr, peerport);
8822
8823         if (!ssh->X11_fwd_enabled && !ssh->connshare)
8824             error = "X11 forwarding is not enabled";
8825         else {
8826             c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8827                                       addrstr, peerport);
8828             c->type = CHAN_X11;
8829             c->u.x11.initial = TRUE;
8830
8831             /*
8832              * If we are a connection-sharing upstream, then we should
8833              * initially present a very small window, adequate to take
8834              * the X11 initial authorisation packet but not much more.
8835              * Downstream will then present us a larger window (by
8836              * fiat of the connection-sharing protocol) and we can
8837              * guarantee to send a positive-valued WINDOW_ADJUST.
8838              */
8839             if (ssh->connshare)
8840                 our_winsize_override = 128;
8841
8842             logevent("Opened X11 forward channel");
8843         }
8844
8845         sfree(addrstr);
8846     } else if (typelen == 15 &&
8847                !memcmp(type, "forwarded-tcpip", 15)) {
8848         struct ssh_rportfwd pf, *realpf;
8849         char *shost;
8850         int shostlen;
8851         ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8852         pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8853         pf.sport = ssh_pkt_getuint32(pktin);
8854         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8855         peerport = ssh_pkt_getuint32(pktin);
8856         realpf = find234(ssh->rportfwds, &pf, NULL);
8857         logeventf(ssh, "Received remote port %s:%d open request "
8858                   "from %.*s:%d", pf.shost, pf.sport,
8859                   peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8860         sfree(pf.shost);
8861
8862         if (realpf == NULL) {
8863             error = "Remote port is not recognised";
8864         } else {
8865             char *err;
8866
8867             if (realpf->share_ctx) {
8868                 /*
8869                  * This port forwarding is on behalf of a
8870                  * connection-sharing downstream, so abandon our own
8871                  * channel-open procedure and just pass the message on
8872                  * to sshshare.c.
8873                  */
8874                 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8875                                           pktin->body, pktin->length);
8876                 sfree(c);
8877                 return;
8878             }
8879
8880             err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8881                               c, ssh->conf, realpf->pfrec->addressfamily);
8882             logeventf(ssh, "Attempting to forward remote port to "
8883                       "%s:%d", realpf->dhost, realpf->dport);
8884             if (err != NULL) {
8885                 logeventf(ssh, "Port open failed: %s", err);
8886                 sfree(err);
8887                 error = "Port open failed";
8888             } else {
8889                 logevent("Forwarded port opened successfully");
8890                 c->type = CHAN_SOCKDATA;
8891             }
8892         }
8893     } else if (typelen == 22 &&
8894                !memcmp(type, "auth-agent@openssh.com", 22)) {
8895         if (!ssh->agentfwd_enabled)
8896             error = "Agent forwarding is not enabled";
8897         else {
8898             c->type = CHAN_AGENT;       /* identify channel type */
8899             bufchain_init(&c->u.a.inbuffer);
8900             c->u.a.pending = NULL;
8901         }
8902     } else {
8903         error = "Unsupported channel type requested";
8904     }
8905
8906     c->remoteid = remid;
8907     c->halfopen = FALSE;
8908     if (error) {
8909         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8910         ssh2_pkt_adduint32(pktout, c->remoteid);
8911         ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8912         ssh2_pkt_addstring(pktout, error);
8913         ssh2_pkt_addstring(pktout, "en");       /* language tag */
8914         ssh2_pkt_send(ssh, pktout);
8915         logeventf(ssh, "Rejected channel open: %s", error);
8916         sfree(c);
8917     } else {
8918         ssh_channel_init(c);
8919         c->v.v2.remwindow = winsize;
8920         c->v.v2.remmaxpkt = pktsize;
8921         if (our_winsize_override) {
8922             c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8923                 our_winsize_override;
8924         }
8925         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8926         ssh2_pkt_adduint32(pktout, c->remoteid);
8927         ssh2_pkt_adduint32(pktout, c->localid);
8928         ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8929         ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
8930         ssh2_pkt_send(ssh, pktout);
8931     }
8932 }
8933
8934 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8935                                  void *share_cs, void *share_chan,
8936                                  const char *peer_addr, int peer_port,
8937                                  int endian, int protomajor, int protominor,
8938                                  const void *initial_data, int initial_len)
8939 {
8940     /*
8941      * This function is called when we've just discovered that an X
8942      * forwarding channel on which we'd been handling the initial auth
8943      * ourselves turns out to be destined for a connection-sharing
8944      * downstream. So we turn the channel into a CHAN_SHARING, meaning
8945      * that we completely stop tracking windows and buffering data and
8946      * just pass more or less unmodified SSH messages back and forth.
8947      */
8948     c->type = CHAN_SHARING;
8949     c->u.sharing.ctx = share_cs;
8950     share_setup_x11_channel(share_cs, share_chan,
8951                             c->localid, c->remoteid, c->v.v2.remwindow,
8952                             c->v.v2.remmaxpkt, c->v.v2.locwindow,
8953                             peer_addr, peer_port, endian,
8954                             protomajor, protominor,
8955                             initial_data, initial_len);
8956 }
8957
8958 void sshfwd_x11_is_local(struct ssh_channel *c)
8959 {
8960     /*
8961      * This function is called when we've just discovered that an X
8962      * forwarding channel is _not_ destined for a connection-sharing
8963      * downstream but we're going to handle it ourselves. We stop
8964      * presenting a cautiously small window and go into ordinary data
8965      * exchange mode.
8966      */
8967     c->u.x11.initial = FALSE;
8968     ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8969 }
8970
8971 /*
8972  * Buffer banner messages for later display at some convenient point,
8973  * if we're going to display them.
8974  */
8975 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8976 {
8977     /* Arbitrary limit to prevent unbounded inflation of buffer */
8978     if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8979         bufchain_size(&ssh->banner) <= 131072) {
8980         char *banner = NULL;
8981         int size = 0;
8982         ssh_pkt_getstring(pktin, &banner, &size);
8983         if (banner)
8984             bufchain_add(&ssh->banner, banner, size);
8985     }
8986 }
8987
8988 /* Helper function to deal with sending tty modes for "pty-req" */
8989 static void ssh2_send_ttymode(void *data,
8990                               const struct ssh_ttymode *mode, char *val)
8991 {
8992     struct Packet *pktout = (struct Packet *)data;
8993     unsigned int arg = 0;
8994
8995     switch (mode->type) {
8996       case TTY_OP_CHAR:
8997         arg = ssh_tty_parse_specchar(val);
8998         break;
8999       case TTY_OP_BOOL:
9000         arg = ssh_tty_parse_boolean(val);
9001         break;
9002     }
9003     ssh2_pkt_addbyte(pktout, mode->opcode);
9004     ssh2_pkt_adduint32(pktout, arg);
9005 }
9006
9007 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
9008                            void *ctx)
9009 {
9010     struct ssh2_setup_x11_state {
9011         int crLine;
9012     };
9013     Ssh ssh = c->ssh;
9014     struct Packet *pktout;
9015     crStateP(ssh2_setup_x11_state, ctx);
9016
9017     crBeginState;
9018
9019     logevent("Requesting X11 forwarding");
9020     pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
9021                                ssh2_setup_x11, s);
9022     ssh2_pkt_addbool(pktout, 0);               /* many connections */
9023     ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
9024     ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
9025     ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
9026     ssh2_pkt_send(ssh, pktout);
9027
9028     /* Wait to be called back with either a response packet, or NULL
9029      * meaning clean up and free our data */
9030     crReturnV;
9031
9032     if (pktin) {
9033         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9034             logevent("X11 forwarding enabled");
9035             ssh->X11_fwd_enabled = TRUE;
9036         } else
9037             logevent("X11 forwarding refused");
9038     }
9039
9040     crFinishFreeV;
9041 }
9042
9043 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
9044                                    void *ctx)
9045 {
9046     struct ssh2_setup_agent_state {
9047         int crLine;
9048     };
9049     Ssh ssh = c->ssh;
9050     struct Packet *pktout;
9051     crStateP(ssh2_setup_agent_state, ctx);
9052
9053     crBeginState;
9054
9055     logevent("Requesting OpenSSH-style agent forwarding");
9056     pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9057                                ssh2_setup_agent, s);
9058     ssh2_pkt_send(ssh, pktout);
9059
9060     /* Wait to be called back with either a response packet, or NULL
9061      * meaning clean up and free our data */
9062     crReturnV;
9063
9064     if (pktin) {
9065         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9066             logevent("Agent forwarding enabled");
9067             ssh->agentfwd_enabled = TRUE;
9068         } else
9069             logevent("Agent forwarding refused");
9070     }
9071
9072     crFinishFreeV;
9073 }
9074
9075 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9076                                  void *ctx)
9077 {
9078     struct ssh2_setup_pty_state {
9079         int crLine;
9080     };
9081     Ssh ssh = c->ssh;
9082     struct Packet *pktout;
9083     crStateP(ssh2_setup_pty_state, ctx);
9084
9085     crBeginState;
9086
9087     /* Unpick the terminal-speed string. */
9088     /* XXX perhaps we should allow no speeds to be sent. */
9089     ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9090     sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9091     /* Build the pty request. */
9092     pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9093                                ssh2_setup_pty, s);
9094     ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9095     ssh2_pkt_adduint32(pktout, ssh->term_width);
9096     ssh2_pkt_adduint32(pktout, ssh->term_height);
9097     ssh2_pkt_adduint32(pktout, 0);             /* pixel width */
9098     ssh2_pkt_adduint32(pktout, 0);             /* pixel height */
9099     ssh2_pkt_addstring_start(pktout);
9100     parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9101     ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9102     ssh2_pkt_adduint32(pktout, ssh->ispeed);
9103     ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9104     ssh2_pkt_adduint32(pktout, ssh->ospeed);
9105     ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9106     ssh2_pkt_send(ssh, pktout);
9107     ssh->state = SSH_STATE_INTERMED;
9108
9109     /* Wait to be called back with either a response packet, or NULL
9110      * meaning clean up and free our data */
9111     crReturnV;
9112
9113     if (pktin) {
9114         if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9115             logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9116                       ssh->ospeed, ssh->ispeed);
9117             ssh->got_pty = TRUE;
9118         } else {
9119             c_write_str(ssh, "Server refused to allocate pty\r\n");
9120             ssh->editing = ssh->echoing = 1;
9121         }
9122     }
9123
9124     crFinishFreeV;
9125 }
9126
9127 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9128                            void *ctx)
9129 {
9130     struct ssh2_setup_env_state {
9131         int crLine;
9132         int num_env, env_left, env_ok;
9133     };
9134     Ssh ssh = c->ssh;
9135     struct Packet *pktout;
9136     crStateP(ssh2_setup_env_state, ctx);
9137
9138     crBeginState;
9139
9140     /*
9141      * Send environment variables.
9142      * 
9143      * Simplest thing here is to send all the requests at once, and
9144      * then wait for a whole bunch of successes or failures.
9145      */
9146     s->num_env = 0;
9147     {
9148         char *key, *val;
9149
9150         for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9151              val != NULL;
9152              val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9153             pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9154             ssh2_pkt_addstring(pktout, key);
9155             ssh2_pkt_addstring(pktout, val);
9156             ssh2_pkt_send(ssh, pktout);
9157
9158             s->num_env++;
9159         }
9160         if (s->num_env)
9161             logeventf(ssh, "Sent %d environment variables", s->num_env);
9162     }
9163
9164     if (s->num_env) {
9165         s->env_ok = 0;
9166         s->env_left = s->num_env;
9167
9168         while (s->env_left > 0) {
9169             /* Wait to be called back with either a response packet,
9170              * or NULL meaning clean up and free our data */
9171             crReturnV;
9172             if (!pktin) goto out;
9173             if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9174                 s->env_ok++;
9175             s->env_left--;
9176         }
9177
9178         if (s->env_ok == s->num_env) {
9179             logevent("All environment variables successfully set");
9180         } else if (s->env_ok == 0) {
9181             logevent("All environment variables refused");
9182             c_write_str(ssh, "Server refused to set environment variables\r\n");
9183         } else {
9184             logeventf(ssh, "%d environment variables refused",
9185                       s->num_env - s->env_ok);
9186             c_write_str(ssh, "Server refused to set all environment variables\r\n");
9187         }
9188     }
9189   out:;
9190     crFinishFreeV;
9191 }
9192
9193 /*
9194  * Handle the SSH-2 userauth and connection layers.
9195  */
9196 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9197 {
9198     do_ssh2_authconn(ssh, NULL, 0, pktin);
9199 }
9200
9201 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9202                                    void *ctx)
9203 {
9204     if (pktin)
9205         do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9206 }
9207
9208 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9209                              struct Packet *pktin)
9210 {
9211     struct do_ssh2_authconn_state {
9212         int crLine;
9213         enum {
9214             AUTH_TYPE_NONE,
9215                 AUTH_TYPE_PUBLICKEY,
9216                 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9217                 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9218                 AUTH_TYPE_PASSWORD,
9219                 AUTH_TYPE_GSSAPI,      /* always QUIET */
9220                 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9221                 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9222         } type;
9223         int done_service_req;
9224         int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9225         int tried_pubkey_config, done_agent;
9226 #ifndef NO_GSSAPI
9227         int can_gssapi;
9228         int tried_gssapi;
9229 #endif
9230         int kbd_inter_refused;
9231         int we_are_in, userauth_success;
9232         prompts_t *cur_prompt;
9233         int num_prompts;
9234         char *username;
9235         char *password;
9236         int got_username;
9237         void *publickey_blob;
9238         int publickey_bloblen;
9239         int privatekey_available, privatekey_encrypted;
9240         char *publickey_algorithm;
9241         char *publickey_comment;
9242         unsigned char agent_request[5], *agent_response, *agentp;
9243         int agent_responselen;
9244         unsigned char *pkblob_in_agent;
9245         int keyi, nkeys;
9246         char *pkblob, *alg, *commentp;
9247         int pklen, alglen, commentlen;
9248         int siglen, retlen, len;
9249         char *q, *agentreq, *ret;
9250         struct Packet *pktout;
9251         Filename *keyfile;
9252 #ifndef NO_GSSAPI
9253         struct ssh_gss_library *gsslib;
9254         Ssh_gss_ctx gss_ctx;
9255         Ssh_gss_buf gss_buf;
9256         Ssh_gss_buf gss_rcvtok, gss_sndtok;
9257         Ssh_gss_name gss_srv_name;
9258         Ssh_gss_stat gss_stat;
9259 #endif
9260     };
9261     crState(do_ssh2_authconn_state);
9262
9263     crBeginState;
9264
9265     /* Register as a handler for all the messages this coroutine handles. */
9266     ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9267     ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9268     ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9269     ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9270     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9271     ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9272     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9273     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9274     ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9275     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9276     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9277     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9278     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9279     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9280     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9281     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9282     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9283     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9284     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9285     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9286     
9287     s->done_service_req = FALSE;
9288     s->we_are_in = s->userauth_success = FALSE;
9289     s->agent_response = NULL;
9290 #ifndef NO_GSSAPI
9291     s->tried_gssapi = FALSE;
9292 #endif
9293
9294     if (!ssh->bare_connection) {
9295         if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9296             /*
9297              * Request userauth protocol, and await a response to it.
9298              */
9299             s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9300             ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9301             ssh2_pkt_send(ssh, s->pktout);
9302             crWaitUntilV(pktin);
9303             if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9304                 s->done_service_req = TRUE;
9305         }
9306         if (!s->done_service_req) {
9307             /*
9308              * Request connection protocol directly, without authentication.
9309              */
9310             s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9311             ssh2_pkt_addstring(s->pktout, "ssh-connection");
9312             ssh2_pkt_send(ssh, s->pktout);
9313             crWaitUntilV(pktin);
9314             if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9315                 s->we_are_in = TRUE; /* no auth required */
9316             } else {
9317                 bombout(("Server refused service request"));
9318                 crStopV;
9319             }
9320         }
9321     } else {
9322         s->we_are_in = TRUE;
9323     }
9324
9325     /* Arrange to be able to deal with any BANNERs that come in.
9326      * (We do this now as packets may come in during the next bit.) */
9327     bufchain_init(&ssh->banner);
9328     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9329         ssh2_msg_userauth_banner;
9330
9331     /*
9332      * Misc one-time setup for authentication.
9333      */
9334     s->publickey_blob = NULL;
9335     if (!s->we_are_in) {
9336
9337         /*
9338          * Load the public half of any configured public key file
9339          * for later use.
9340          */
9341         s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9342         if (!filename_is_null(s->keyfile)) {
9343             int keytype;
9344             logeventf(ssh, "Reading key file \"%.150s\"",
9345                       filename_to_str(s->keyfile));
9346             keytype = key_type(s->keyfile);
9347             if (keytype == SSH_KEYTYPE_SSH2 ||
9348                 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9349                 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9350                 const char *error;
9351                 s->publickey_blob =
9352                     ssh2_userkey_loadpub(s->keyfile,
9353                                          &s->publickey_algorithm,
9354                                          &s->publickey_bloblen, 
9355                                          &s->publickey_comment, &error);
9356                 if (s->publickey_blob) {
9357                     s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9358                     if (!s->privatekey_available)
9359                         logeventf(ssh, "Key file contains public key only");
9360                     s->privatekey_encrypted =
9361                         ssh2_userkey_encrypted(s->keyfile, NULL);
9362                 } else {
9363                     char *msgbuf;
9364                     logeventf(ssh, "Unable to load key (%s)", 
9365                               error);
9366                     msgbuf = dupprintf("Unable to load key file "
9367                                        "\"%.150s\" (%s)\r\n",
9368                                        filename_to_str(s->keyfile),
9369                                        error);
9370                     c_write_str(ssh, msgbuf);
9371                     sfree(msgbuf);
9372                 }
9373             } else {
9374                 char *msgbuf;
9375                 logeventf(ssh, "Unable to use this key file (%s)",
9376                           key_type_to_str(keytype));
9377                 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9378                                    " (%s)\r\n",
9379                                    filename_to_str(s->keyfile),
9380                                    key_type_to_str(keytype));
9381                 c_write_str(ssh, msgbuf);
9382                 sfree(msgbuf);
9383                 s->publickey_blob = NULL;
9384             }
9385         }
9386
9387         /*
9388          * Find out about any keys Pageant has (but if there's a
9389          * public key configured, filter out all others).
9390          */
9391         s->nkeys = 0;
9392         s->agent_response = NULL;
9393         s->pkblob_in_agent = NULL;
9394         if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9395
9396             void *r;
9397
9398             logevent("Pageant is running. Requesting keys.");
9399
9400             /* Request the keys held by the agent. */
9401             PUT_32BIT(s->agent_request, 1);
9402             s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9403             ssh->auth_agent_query = agent_query(
9404                 s->agent_request, 5, &r, &s->agent_responselen,
9405                 ssh_agent_callback, ssh);
9406             if (ssh->auth_agent_query) {
9407                 do {
9408                     crReturnV;
9409                     if (pktin) {
9410                         bombout(("Unexpected data from server while"
9411                                  " waiting for agent response"));
9412                         crStopV;
9413                     }
9414                 } while (pktin || inlen > 0);
9415                 r = ssh->agent_response;
9416                 s->agent_responselen = ssh->agent_response_len;
9417             }
9418             s->agent_response = (unsigned char *) r;
9419             if (s->agent_response && s->agent_responselen >= 5 &&
9420                 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9421                 int keyi;
9422                 unsigned char *p;
9423                 p = s->agent_response + 5;
9424                 s->nkeys = toint(GET_32BIT(p));
9425
9426                 /*
9427                  * Vet the Pageant response to ensure that the key
9428                  * count and blob lengths make sense.
9429                  */
9430                 if (s->nkeys < 0) {
9431                     logeventf(ssh, "Pageant response contained a negative"
9432                               " key count %d", s->nkeys);
9433                     s->nkeys = 0;
9434                     goto done_agent_query;
9435                 } else {
9436                     unsigned char *q = p + 4;
9437                     int lenleft = s->agent_responselen - 5 - 4;
9438
9439                     for (keyi = 0; keyi < s->nkeys; keyi++) {
9440                         int bloblen, commentlen;
9441                         if (lenleft < 4) {
9442                             logeventf(ssh, "Pageant response was truncated");
9443                             s->nkeys = 0;
9444                             goto done_agent_query;
9445                         }
9446                         bloblen = toint(GET_32BIT(q));
9447                         if (bloblen < 0 || bloblen > lenleft) {
9448                             logeventf(ssh, "Pageant response was truncated");
9449                             s->nkeys = 0;
9450                             goto done_agent_query;
9451                         }
9452                         lenleft -= 4 + bloblen;
9453                         q += 4 + bloblen;
9454                         commentlen = toint(GET_32BIT(q));
9455                         if (commentlen < 0 || commentlen > lenleft) {
9456                             logeventf(ssh, "Pageant response was truncated");
9457                             s->nkeys = 0;
9458                             goto done_agent_query;
9459                         }
9460                         lenleft -= 4 + commentlen;
9461                         q += 4 + commentlen;
9462                     }
9463                 }
9464
9465                 p += 4;
9466                 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9467                 if (s->publickey_blob) {
9468                     /* See if configured key is in agent. */
9469                     for (keyi = 0; keyi < s->nkeys; keyi++) {
9470                         s->pklen = toint(GET_32BIT(p));
9471                         if (s->pklen == s->publickey_bloblen &&
9472                             !memcmp(p+4, s->publickey_blob,
9473                                     s->publickey_bloblen)) {
9474                             logeventf(ssh, "Pageant key #%d matches "
9475                                       "configured key file", keyi);
9476                             s->keyi = keyi;
9477                             s->pkblob_in_agent = p;
9478                             break;
9479                         }
9480                         p += 4 + s->pklen;
9481                         p += toint(GET_32BIT(p)) + 4; /* comment */
9482                     }
9483                     if (!s->pkblob_in_agent) {
9484                         logevent("Configured key file not in Pageant");
9485                         s->nkeys = 0;
9486                     }
9487                 }
9488             } else {
9489                 logevent("Failed to get reply from Pageant");
9490             }
9491           done_agent_query:;
9492         }
9493
9494     }
9495
9496     /*
9497      * We repeat this whole loop, including the username prompt,
9498      * until we manage a successful authentication. If the user
9499      * types the wrong _password_, they can be sent back to the
9500      * beginning to try another username, if this is configured on.
9501      * (If they specify a username in the config, they are never
9502      * asked, even if they do give a wrong password.)
9503      * 
9504      * I think this best serves the needs of
9505      * 
9506      *  - the people who have no configuration, no keys, and just
9507      *    want to try repeated (username,password) pairs until they
9508      *    type both correctly
9509      * 
9510      *  - people who have keys and configuration but occasionally
9511      *    need to fall back to passwords
9512      * 
9513      *  - people with a key held in Pageant, who might not have
9514      *    logged in to a particular machine before; so they want to
9515      *    type a username, and then _either_ their key will be
9516      *    accepted, _or_ they will type a password. If they mistype
9517      *    the username they will want to be able to get back and
9518      *    retype it!
9519      */
9520     s->got_username = FALSE;
9521     while (!s->we_are_in) {
9522         /*
9523          * Get a username.
9524          */
9525         if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9526             /*
9527              * We got a username last time round this loop, and
9528              * with change_username turned off we don't try to get
9529              * it again.
9530              */
9531         } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9532             int ret; /* need not be kept over crReturn */
9533             s->cur_prompt = new_prompts(ssh->frontend);
9534             s->cur_prompt->to_server = TRUE;
9535             s->cur_prompt->name = dupstr("SSH login name");
9536             add_prompt(s->cur_prompt, dupstr("login as: "), TRUE); 
9537             ret = get_userpass_input(s->cur_prompt, NULL, 0);
9538             while (ret < 0) {
9539                 ssh->send_ok = 1;
9540                 crWaitUntilV(!pktin);
9541                 ret = get_userpass_input(s->cur_prompt, in, inlen);
9542                 ssh->send_ok = 0;
9543             }
9544             if (!ret) {
9545                 /*
9546                  * get_userpass_input() failed to get a username.
9547                  * Terminate.
9548                  */
9549                 free_prompts(s->cur_prompt);
9550                 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9551                 crStopV;
9552             }
9553             ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9554             free_prompts(s->cur_prompt);
9555         } else {
9556             char *stuff;
9557             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9558                 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9559                 c_write_str(ssh, stuff);
9560                 sfree(stuff);
9561             }
9562         }
9563         s->got_username = TRUE;
9564
9565         /*
9566          * Send an authentication request using method "none": (a)
9567          * just in case it succeeds, and (b) so that we know what
9568          * authentication methods we can usefully try next.
9569          */
9570         ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9571
9572         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9573         ssh2_pkt_addstring(s->pktout, ssh->username);
9574         ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9575         ssh2_pkt_addstring(s->pktout, "none");    /* method */
9576         ssh2_pkt_send(ssh, s->pktout);
9577         s->type = AUTH_TYPE_NONE;
9578         s->gotit = FALSE;
9579         s->we_are_in = FALSE;
9580
9581         s->tried_pubkey_config = FALSE;
9582         s->kbd_inter_refused = FALSE;
9583
9584         /* Reset agent request state. */
9585         s->done_agent = FALSE;
9586         if (s->agent_response) {
9587             if (s->pkblob_in_agent) {
9588                 s->agentp = s->pkblob_in_agent;
9589             } else {
9590                 s->agentp = s->agent_response + 5 + 4;
9591                 s->keyi = 0;
9592             }
9593         }
9594
9595         while (1) {
9596             char *methods = NULL;
9597             int methlen = 0;
9598
9599             /*
9600              * Wait for the result of the last authentication request.
9601              */
9602             if (!s->gotit)
9603                 crWaitUntilV(pktin);
9604             /*
9605              * Now is a convenient point to spew any banner material
9606              * that we've accumulated. (This should ensure that when
9607              * we exit the auth loop, we haven't any left to deal
9608              * with.)
9609              */
9610             {
9611                 int size = bufchain_size(&ssh->banner);
9612                 /*
9613                  * Don't show the banner if we're operating in
9614                  * non-verbose non-interactive mode. (It's probably
9615                  * a script, which means nobody will read the
9616                  * banner _anyway_, and moreover the printing of
9617                  * the banner will screw up processing on the
9618                  * output of (say) plink.)
9619                  */
9620                 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9621                     char *banner = snewn(size, char);
9622                     bufchain_fetch(&ssh->banner, banner, size);
9623                     c_write_untrusted(ssh, banner, size);
9624                     sfree(banner);
9625                 }
9626                 bufchain_clear(&ssh->banner);
9627             }
9628             if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9629                 logevent("Access granted");
9630                 s->we_are_in = s->userauth_success = TRUE;
9631                 break;
9632             }
9633
9634             if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9635                 bombout(("Strange packet received during authentication: "
9636                          "type %d", pktin->type));
9637                 crStopV;
9638             }
9639
9640             s->gotit = FALSE;
9641
9642             /*
9643              * OK, we're now sitting on a USERAUTH_FAILURE message, so
9644              * we can look at the string in it and know what we can
9645              * helpfully try next.
9646              */
9647             if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9648                 ssh_pkt_getstring(pktin, &methods, &methlen);
9649                 if (!ssh2_pkt_getbool(pktin)) {
9650                     /*
9651                      * We have received an unequivocal Access
9652                      * Denied. This can translate to a variety of
9653                      * messages, or no message at all.
9654                      *
9655                      * For forms of authentication which are attempted
9656                      * implicitly, by which I mean without printing
9657                      * anything in the window indicating that we're
9658                      * trying them, we should never print 'Access
9659                      * denied'.
9660                      *
9661                      * If we do print a message saying that we're
9662                      * attempting some kind of authentication, it's OK
9663                      * to print a followup message saying it failed -
9664                      * but the message may sometimes be more specific
9665                      * than simply 'Access denied'.
9666                      *
9667                      * Additionally, if we'd just tried password
9668                      * authentication, we should break out of this
9669                      * whole loop so as to go back to the username
9670                      * prompt (iff we're configured to allow
9671                      * username change attempts).
9672                      */
9673                     if (s->type == AUTH_TYPE_NONE) {
9674                         /* do nothing */
9675                     } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9676                                s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9677                         if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9678                             c_write_str(ssh, "Server refused our key\r\n");
9679                         logevent("Server refused our key");
9680                     } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9681                         /* This _shouldn't_ happen except by a
9682                          * protocol bug causing client and server to
9683                          * disagree on what is a correct signature. */
9684                         c_write_str(ssh, "Server refused public-key signature"
9685                                     " despite accepting key!\r\n");
9686                         logevent("Server refused public-key signature"
9687                                  " despite accepting key!");
9688                     } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9689                         /* quiet, so no c_write */
9690                         logevent("Server refused keyboard-interactive authentication");
9691                     } else if (s->type==AUTH_TYPE_GSSAPI) {
9692                         /* always quiet, so no c_write */
9693                         /* also, the code down in the GSSAPI block has
9694                          * already logged this in the Event Log */
9695                     } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9696                         logevent("Keyboard-interactive authentication failed");
9697                         c_write_str(ssh, "Access denied\r\n");
9698                     } else {
9699                         assert(s->type == AUTH_TYPE_PASSWORD);
9700                         logevent("Password authentication failed");
9701                         c_write_str(ssh, "Access denied\r\n");
9702
9703                         if (conf_get_int(ssh->conf, CONF_change_username)) {
9704                             /* XXX perhaps we should allow
9705                              * keyboard-interactive to do this too? */
9706                             s->we_are_in = FALSE;
9707                             break;
9708                         }
9709                     }
9710                 } else {
9711                     c_write_str(ssh, "Further authentication required\r\n");
9712                     logevent("Further authentication required");
9713                 }
9714
9715                 s->can_pubkey =
9716                     in_commasep_string("publickey", methods, methlen);
9717                 s->can_passwd =
9718                     in_commasep_string("password", methods, methlen);
9719                 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9720                     in_commasep_string("keyboard-interactive", methods, methlen);
9721 #ifndef NO_GSSAPI
9722                 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9723                     in_commasep_string("gssapi-with-mic", methods, methlen)) {
9724                     /* Try loading the GSS libraries and see if we
9725                      * have any. */
9726                     if (!ssh->gsslibs)
9727                         ssh->gsslibs = ssh_gss_setup(ssh->conf);
9728                     s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9729                 } else {
9730                     /* No point in even bothering to try to load the
9731                      * GSS libraries, if the user configuration and
9732                      * server aren't both prepared to attempt GSSAPI
9733                      * auth in the first place. */
9734                     s->can_gssapi = FALSE;
9735                 }
9736 #endif
9737             }
9738
9739             ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9740
9741             if (s->can_pubkey && !s->done_agent && s->nkeys) {
9742
9743                 /*
9744                  * Attempt public-key authentication using a key from Pageant.
9745                  */
9746
9747                 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9748
9749                 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9750
9751                 /* Unpack key from agent response */
9752                 s->pklen = toint(GET_32BIT(s->agentp));
9753                 s->agentp += 4;
9754                 s->pkblob = (char *)s->agentp;
9755                 s->agentp += s->pklen;
9756                 s->alglen = toint(GET_32BIT(s->pkblob));
9757                 s->alg = s->pkblob + 4;
9758                 s->commentlen = toint(GET_32BIT(s->agentp));
9759                 s->agentp += 4;
9760                 s->commentp = (char *)s->agentp;
9761                 s->agentp += s->commentlen;
9762                 /* s->agentp now points at next key, if any */
9763
9764                 /* See if server will accept it */
9765                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9766                 ssh2_pkt_addstring(s->pktout, ssh->username);
9767                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9768                                                     /* service requested */
9769                 ssh2_pkt_addstring(s->pktout, "publickey");
9770                                                     /* method */
9771                 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9772                 ssh2_pkt_addstring_start(s->pktout);
9773                 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9774                 ssh2_pkt_addstring_start(s->pktout);
9775                 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9776                 ssh2_pkt_send(ssh, s->pktout);
9777                 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9778
9779                 crWaitUntilV(pktin);
9780                 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9781
9782                     /* Offer of key refused. */
9783                     s->gotit = TRUE;
9784
9785                 } else {
9786                     
9787                     void *vret;
9788
9789                     if (flags & FLAG_VERBOSE) {
9790                         c_write_str(ssh, "Authenticating with "
9791                                     "public key \"");
9792                         c_write(ssh, s->commentp, s->commentlen);
9793                         c_write_str(ssh, "\" from agent\r\n");
9794                     }
9795
9796                     /*
9797                      * Server is willing to accept the key.
9798                      * Construct a SIGN_REQUEST.
9799                      */
9800                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9801                     ssh2_pkt_addstring(s->pktout, ssh->username);
9802                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
9803                                                         /* service requested */
9804                     ssh2_pkt_addstring(s->pktout, "publickey");
9805                                                         /* method */
9806                     ssh2_pkt_addbool(s->pktout, TRUE);  /* signature included */
9807                     ssh2_pkt_addstring_start(s->pktout);
9808                     ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9809                     ssh2_pkt_addstring_start(s->pktout);
9810                     ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9811
9812                     /* Ask agent for signature. */
9813                     s->siglen = s->pktout->length - 5 + 4 +
9814                         ssh->v2_session_id_len;
9815                     if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9816                         s->siglen -= 4;
9817                     s->len = 1;       /* message type */
9818                     s->len += 4 + s->pklen;     /* key blob */
9819                     s->len += 4 + s->siglen;    /* data to sign */
9820                     s->len += 4;      /* flags */
9821                     s->agentreq = snewn(4 + s->len, char);
9822                     PUT_32BIT(s->agentreq, s->len);
9823                     s->q = s->agentreq + 4;
9824                     *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9825                     PUT_32BIT(s->q, s->pklen);
9826                     s->q += 4;
9827                     memcpy(s->q, s->pkblob, s->pklen);
9828                     s->q += s->pklen;
9829                     PUT_32BIT(s->q, s->siglen);
9830                     s->q += 4;
9831                     /* Now the data to be signed... */
9832                     if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9833                         PUT_32BIT(s->q, ssh->v2_session_id_len);
9834                         s->q += 4;
9835                     }
9836                     memcpy(s->q, ssh->v2_session_id,
9837                            ssh->v2_session_id_len);
9838                     s->q += ssh->v2_session_id_len;
9839                     memcpy(s->q, s->pktout->data + 5,
9840                            s->pktout->length - 5);
9841                     s->q += s->pktout->length - 5;
9842                     /* And finally the (zero) flags word. */
9843                     PUT_32BIT(s->q, 0);
9844                     ssh->auth_agent_query = agent_query(
9845                         s->agentreq, s->len + 4, &vret, &s->retlen,
9846                         ssh_agent_callback, ssh);
9847                     if (ssh->auth_agent_query) {
9848                         do {
9849                             crReturnV;
9850                             if (pktin) {
9851                                 bombout(("Unexpected data from server"
9852                                          " while waiting for agent"
9853                                          " response"));
9854                                 crStopV;
9855                             }
9856                         } while (pktin || inlen > 0);
9857                         vret = ssh->agent_response;
9858                         s->retlen = ssh->agent_response_len;
9859                     }
9860                     s->ret = vret;
9861                     sfree(s->agentreq);
9862                     if (s->ret) {
9863                         if (s->retlen >= 9 &&
9864                             s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9865                             GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9866                             logevent("Sending Pageant's response");
9867                             ssh2_add_sigblob(ssh, s->pktout,
9868                                              s->pkblob, s->pklen,
9869                                              s->ret + 9,
9870                                              GET_32BIT(s->ret + 5));
9871                             ssh2_pkt_send(ssh, s->pktout);
9872                             s->type = AUTH_TYPE_PUBLICKEY;
9873                         } else {
9874                             /* FIXME: less drastic response */
9875                             bombout(("Pageant failed to answer challenge"));
9876                             crStopV;
9877                         }
9878                     }
9879                 }
9880
9881                 /* Do we have any keys left to try? */
9882                 if (s->pkblob_in_agent) {
9883                     s->done_agent = TRUE;
9884                     s->tried_pubkey_config = TRUE;
9885                 } else {
9886                     s->keyi++;
9887                     if (s->keyi >= s->nkeys)
9888                         s->done_agent = TRUE;
9889                 }
9890
9891             } else if (s->can_pubkey && s->publickey_blob &&
9892                        s->privatekey_available && !s->tried_pubkey_config) {
9893
9894                 struct ssh2_userkey *key;   /* not live over crReturn */
9895                 char *passphrase;           /* not live over crReturn */
9896
9897                 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9898
9899                 s->tried_pubkey_config = TRUE;
9900
9901                 /*
9902                  * Try the public key supplied in the configuration.
9903                  *
9904                  * First, offer the public blob to see if the server is
9905                  * willing to accept it.
9906                  */
9907                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9908                 ssh2_pkt_addstring(s->pktout, ssh->username);
9909                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9910                                                 /* service requested */
9911                 ssh2_pkt_addstring(s->pktout, "publickey");     /* method */
9912                 ssh2_pkt_addbool(s->pktout, FALSE);
9913                                                 /* no signature included */
9914                 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9915                 ssh2_pkt_addstring_start(s->pktout);
9916                 ssh2_pkt_addstring_data(s->pktout,
9917                                         (char *)s->publickey_blob,
9918                                         s->publickey_bloblen);
9919                 ssh2_pkt_send(ssh, s->pktout);
9920                 logevent("Offered public key");
9921
9922                 crWaitUntilV(pktin);
9923                 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9924                     /* Key refused. Give up. */
9925                     s->gotit = TRUE; /* reconsider message next loop */
9926                     s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9927                     continue; /* process this new message */
9928                 }
9929                 logevent("Offer of public key accepted");
9930
9931                 /*
9932                  * Actually attempt a serious authentication using
9933                  * the key.
9934                  */
9935                 if (flags & FLAG_VERBOSE) {
9936                     c_write_str(ssh, "Authenticating with public key \"");
9937                     c_write_str(ssh, s->publickey_comment);
9938                     c_write_str(ssh, "\"\r\n");
9939                 }
9940                 key = NULL;
9941                 while (!key) {
9942                     const char *error;  /* not live over crReturn */
9943                     if (s->privatekey_encrypted) {
9944                         /*
9945                          * Get a passphrase from the user.
9946                          */
9947                         int ret; /* need not be kept over crReturn */
9948                         s->cur_prompt = new_prompts(ssh->frontend);
9949                         s->cur_prompt->to_server = FALSE;
9950                         s->cur_prompt->name = dupstr("SSH key passphrase");
9951                         add_prompt(s->cur_prompt,
9952                                    dupprintf("Passphrase for key \"%.100s\": ",
9953                                              s->publickey_comment),
9954                                    FALSE);
9955                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
9956                         while (ret < 0) {
9957                             ssh->send_ok = 1;
9958                             crWaitUntilV(!pktin);
9959                             ret = get_userpass_input(s->cur_prompt,
9960                                                      in, inlen);
9961                             ssh->send_ok = 0;
9962                         }
9963                         if (!ret) {
9964                             /* Failed to get a passphrase. Terminate. */
9965                             free_prompts(s->cur_prompt);
9966                             ssh_disconnect(ssh, NULL,
9967                                            "Unable to authenticate",
9968                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9969                                            TRUE);
9970                             crStopV;
9971                         }
9972                         passphrase =
9973                             dupstr(s->cur_prompt->prompts[0]->result);
9974                         free_prompts(s->cur_prompt);
9975                     } else {
9976                         passphrase = NULL; /* no passphrase needed */
9977                     }
9978
9979                     /*
9980                      * Try decrypting the key.
9981                      */
9982                     s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9983                     key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9984                     if (passphrase) {
9985                         /* burn the evidence */
9986                         smemclr(passphrase, strlen(passphrase));
9987                         sfree(passphrase);
9988                     }
9989                     if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9990                         if (passphrase &&
9991                             (key == SSH2_WRONG_PASSPHRASE)) {
9992                             c_write_str(ssh, "Wrong passphrase\r\n");
9993                             key = NULL;
9994                             /* and loop again */
9995                         } else {
9996                             c_write_str(ssh, "Unable to load private key (");
9997                             c_write_str(ssh, error);
9998                             c_write_str(ssh, ")\r\n");
9999                             key = NULL;
10000                             break; /* try something else */
10001                         }
10002                     }
10003                 }
10004
10005                 if (key) {
10006                     unsigned char *pkblob, *sigblob, *sigdata;
10007                     int pkblob_len, sigblob_len, sigdata_len;
10008                     int p;
10009
10010                     /*
10011                      * We have loaded the private key and the server
10012                      * has announced that it's willing to accept it.
10013                      * Hallelujah. Generate a signature and send it.
10014                      */
10015                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10016                     ssh2_pkt_addstring(s->pktout, ssh->username);
10017                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
10018                                                     /* service requested */
10019                     ssh2_pkt_addstring(s->pktout, "publickey");
10020                                                     /* method */
10021                     ssh2_pkt_addbool(s->pktout, TRUE);
10022                                                     /* signature follows */
10023                     ssh2_pkt_addstring(s->pktout, key->alg->name);
10024                     pkblob = key->alg->public_blob(key->data,
10025                                                    &pkblob_len);
10026                     ssh2_pkt_addstring_start(s->pktout);
10027                     ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
10028                                             pkblob_len);
10029
10030                     /*
10031                      * The data to be signed is:
10032                      *
10033                      *   string  session-id
10034                      *
10035                      * followed by everything so far placed in the
10036                      * outgoing packet.
10037                      */
10038                     sigdata_len = s->pktout->length - 5 + 4 +
10039                         ssh->v2_session_id_len;
10040                     if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
10041                         sigdata_len -= 4;
10042                     sigdata = snewn(sigdata_len, unsigned char);
10043                     p = 0;
10044                     if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
10045                         PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
10046                         p += 4;
10047                     }
10048                     memcpy(sigdata+p, ssh->v2_session_id,
10049                            ssh->v2_session_id_len);
10050                     p += ssh->v2_session_id_len;
10051                     memcpy(sigdata+p, s->pktout->data + 5,
10052                            s->pktout->length - 5);
10053                     p += s->pktout->length - 5;
10054                     assert(p == sigdata_len);
10055                     sigblob = key->alg->sign(key->data, (char *)sigdata,
10056                                              sigdata_len, &sigblob_len);
10057                     ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10058                                      sigblob, sigblob_len);
10059                     sfree(pkblob);
10060                     sfree(sigblob);
10061                     sfree(sigdata);
10062
10063                     ssh2_pkt_send(ssh, s->pktout);
10064                     logevent("Sent public key signature");
10065                     s->type = AUTH_TYPE_PUBLICKEY;
10066                     key->alg->freekey(key->data);
10067                     sfree(key->comment);
10068                     sfree(key);
10069                 }
10070
10071 #ifndef NO_GSSAPI
10072             } else if (s->can_gssapi && !s->tried_gssapi) {
10073
10074                 /* GSSAPI Authentication */
10075
10076                 int micoffset, len;
10077                 char *data;
10078                 Ssh_gss_buf mic;
10079                 s->type = AUTH_TYPE_GSSAPI;
10080                 s->tried_gssapi = TRUE;
10081                 s->gotit = TRUE;
10082                 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10083
10084                 /*
10085                  * Pick the highest GSS library on the preference
10086                  * list.
10087                  */
10088                 {
10089                     int i, j;
10090                     s->gsslib = NULL;
10091                     for (i = 0; i < ngsslibs; i++) {
10092                         int want_id = conf_get_int_int(ssh->conf,
10093                                                        CONF_ssh_gsslist, i);
10094                         for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10095                             if (ssh->gsslibs->libraries[j].id == want_id) {
10096                                 s->gsslib = &ssh->gsslibs->libraries[j];
10097                                 goto got_gsslib;   /* double break */
10098                             }
10099                     }
10100                     got_gsslib:
10101                     /*
10102                      * We always expect to have found something in
10103                      * the above loop: we only came here if there
10104                      * was at least one viable GSS library, and the
10105                      * preference list should always mention
10106                      * everything and only change the order.
10107                      */
10108                     assert(s->gsslib);
10109                 }
10110
10111                 if (s->gsslib->gsslogmsg)
10112                     logevent(s->gsslib->gsslogmsg);
10113
10114                 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10115                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10116                 ssh2_pkt_addstring(s->pktout, ssh->username);
10117                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10118                 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10119                 logevent("Attempting GSSAPI authentication");
10120
10121                 /* add mechanism info */
10122                 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10123
10124                 /* number of GSSAPI mechanisms */
10125                 ssh2_pkt_adduint32(s->pktout,1);
10126
10127                 /* length of OID + 2 */
10128                 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10129                 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10130
10131                 /* length of OID */
10132                 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10133
10134                 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10135                                 s->gss_buf.length);
10136                 ssh2_pkt_send(ssh, s->pktout);
10137                 crWaitUntilV(pktin);
10138                 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10139                     logevent("GSSAPI authentication request refused");
10140                     continue;
10141                 }
10142
10143                 /* check returned packet ... */
10144
10145                 ssh_pkt_getstring(pktin, &data, &len);
10146                 s->gss_rcvtok.value = data;
10147                 s->gss_rcvtok.length = len;
10148                 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10149                     ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10150                     ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10151                     memcmp((char *)s->gss_rcvtok.value + 2,
10152                            s->gss_buf.value,s->gss_buf.length) ) {
10153                     logevent("GSSAPI authentication - wrong response from server");
10154                     continue;
10155                 }
10156
10157                 /* now start running */
10158                 s->gss_stat = s->gsslib->import_name(s->gsslib,
10159                                                      ssh->fullhostname,
10160                                                      &s->gss_srv_name);
10161                 if (s->gss_stat != SSH_GSS_OK) {
10162                     if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10163                         logevent("GSSAPI import name failed - Bad service name");
10164                     else
10165                         logevent("GSSAPI import name failed");
10166                     continue;
10167                 }
10168
10169                 /* fetch TGT into GSS engine */
10170                 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10171
10172                 if (s->gss_stat != SSH_GSS_OK) {
10173                     logevent("GSSAPI authentication failed to get credentials");
10174                     s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10175                     continue;
10176                 }
10177
10178                 /* initial tokens are empty */
10179                 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10180                 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10181
10182                 /* now enter the loop */
10183                 do {
10184                     s->gss_stat = s->gsslib->init_sec_context
10185                         (s->gsslib,
10186                          &s->gss_ctx,
10187                          s->gss_srv_name,
10188                          conf_get_int(ssh->conf, CONF_gssapifwd),
10189                          &s->gss_rcvtok,
10190                          &s->gss_sndtok);
10191
10192                     if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10193                         s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10194                         logevent("GSSAPI authentication initialisation failed");
10195
10196                         if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10197                                                       &s->gss_buf) == SSH_GSS_OK) {
10198                             logevent(s->gss_buf.value);
10199                             sfree(s->gss_buf.value);
10200                         }
10201
10202                         break;
10203                     }
10204                     logevent("GSSAPI authentication initialised");
10205
10206                     /* Client and server now exchange tokens until GSSAPI
10207                      * no longer says CONTINUE_NEEDED */
10208
10209                     if (s->gss_sndtok.length != 0) {
10210                         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10211                         ssh_pkt_addstring_start(s->pktout);
10212                         ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10213                         ssh2_pkt_send(ssh, s->pktout);
10214                         s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10215                     }
10216
10217                     if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10218                         crWaitUntilV(pktin);
10219                         if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10220                             logevent("GSSAPI authentication - bad server response");
10221                             s->gss_stat = SSH_GSS_FAILURE;
10222                             break;
10223                         }
10224                         ssh_pkt_getstring(pktin, &data, &len);
10225                         s->gss_rcvtok.value = data;
10226                         s->gss_rcvtok.length = len;
10227                     }
10228                 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10229
10230                 if (s->gss_stat != SSH_GSS_OK) {
10231                     s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10232                     s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10233                     continue;
10234                 }
10235                 logevent("GSSAPI authentication loop finished OK");
10236
10237                 /* Now send the MIC */
10238
10239                 s->pktout = ssh2_pkt_init(0);
10240                 micoffset = s->pktout->length;
10241                 ssh_pkt_addstring_start(s->pktout);
10242                 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10243                 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10244                 ssh_pkt_addstring(s->pktout, ssh->username);
10245                 ssh_pkt_addstring(s->pktout, "ssh-connection");
10246                 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10247
10248                 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10249                 s->gss_buf.length = s->pktout->length - micoffset;
10250
10251                 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10252                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10253                 ssh_pkt_addstring_start(s->pktout);
10254                 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10255                 ssh2_pkt_send(ssh, s->pktout);
10256                 s->gsslib->free_mic(s->gsslib, &mic);
10257
10258                 s->gotit = FALSE;
10259
10260                 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10261                 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10262                 continue;
10263 #endif
10264             } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10265
10266                 /*
10267                  * Keyboard-interactive authentication.
10268                  */
10269
10270                 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10271
10272                 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10273
10274                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10275                 ssh2_pkt_addstring(s->pktout, ssh->username);
10276                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10277                                                         /* service requested */
10278                 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10279                                                         /* method */
10280                 ssh2_pkt_addstring(s->pktout, "");      /* lang */
10281                 ssh2_pkt_addstring(s->pktout, "");      /* submethods */
10282                 ssh2_pkt_send(ssh, s->pktout);
10283                 
10284                 logevent("Attempting keyboard-interactive authentication");
10285
10286                 crWaitUntilV(pktin);
10287                 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10288                     /* Server is not willing to do keyboard-interactive
10289                      * at all (or, bizarrely but legally, accepts the
10290                      * user without actually issuing any prompts).
10291                      * Give up on it entirely. */
10292                     s->gotit = TRUE;
10293                     s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10294                     s->kbd_inter_refused = TRUE; /* don't try it again */
10295                     continue;
10296                 }
10297
10298                 /*
10299                  * Loop while the server continues to send INFO_REQUESTs.
10300                  */
10301                 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10302
10303                     char *name, *inst, *lang;
10304                     int name_len, inst_len, lang_len;
10305                     int i;
10306
10307                     /*
10308                      * We've got a fresh USERAUTH_INFO_REQUEST.
10309                      * Get the preamble and start building a prompt.
10310                      */
10311                     ssh_pkt_getstring(pktin, &name, &name_len);
10312                     ssh_pkt_getstring(pktin, &inst, &inst_len);
10313                     ssh_pkt_getstring(pktin, &lang, &lang_len);
10314                     s->cur_prompt = new_prompts(ssh->frontend);
10315                     s->cur_prompt->to_server = TRUE;
10316
10317                     /*
10318                      * Get any prompt(s) from the packet.
10319                      */
10320                     s->num_prompts = ssh_pkt_getuint32(pktin);
10321                     for (i = 0; i < s->num_prompts; i++) {
10322                         char *prompt;
10323                         int prompt_len;
10324                         int echo;
10325                         static char noprompt[] =
10326                             "<server failed to send prompt>: ";
10327
10328                         ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10329                         echo = ssh2_pkt_getbool(pktin);
10330                         if (!prompt_len) {
10331                             prompt = noprompt;
10332                             prompt_len = lenof(noprompt)-1;
10333                         }
10334                         add_prompt(s->cur_prompt,
10335                                    dupprintf("%.*s", prompt_len, prompt),
10336                                    echo);
10337                     }
10338
10339                     if (name_len) {
10340                         /* FIXME: better prefix to distinguish from
10341                          * local prompts? */
10342                         s->cur_prompt->name =
10343                             dupprintf("SSH server: %.*s", name_len, name);
10344                         s->cur_prompt->name_reqd = TRUE;
10345                     } else {
10346                         s->cur_prompt->name =
10347                             dupstr("SSH server authentication");
10348                         s->cur_prompt->name_reqd = FALSE;
10349                     }
10350                     /* We add a prefix to try to make it clear that a prompt
10351                      * has come from the server.
10352                      * FIXME: ugly to print "Using..." in prompt _every_
10353                      * time round. Can this be done more subtly? */
10354                     /* Special case: for reasons best known to themselves,
10355                      * some servers send k-i requests with no prompts and
10356                      * nothing to display. Keep quiet in this case. */
10357                     if (s->num_prompts || name_len || inst_len) {
10358                         s->cur_prompt->instruction =
10359                             dupprintf("Using keyboard-interactive authentication.%s%.*s",
10360                                       inst_len ? "\n" : "", inst_len, inst);
10361                         s->cur_prompt->instr_reqd = TRUE;
10362                     } else {
10363                         s->cur_prompt->instr_reqd = FALSE;
10364                     }
10365
10366                     /*
10367                      * Display any instructions, and get the user's
10368                      * response(s).
10369                      */
10370                     {
10371                         int ret; /* not live over crReturn */
10372                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
10373                         while (ret < 0) {
10374                             ssh->send_ok = 1;
10375                             crWaitUntilV(!pktin);
10376                             ret = get_userpass_input(s->cur_prompt, in, inlen);
10377                             ssh->send_ok = 0;
10378                         }
10379                         if (!ret) {
10380                             /*
10381                              * Failed to get responses. Terminate.
10382                              */
10383                             free_prompts(s->cur_prompt);
10384                             ssh_disconnect(ssh, NULL, "Unable to authenticate",
10385                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10386                                            TRUE);
10387                             crStopV;
10388                         }
10389                     }
10390
10391                     /*
10392                      * Send the response(s) to the server.
10393                      */
10394                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10395                     ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10396                     for (i=0; i < s->num_prompts; i++) {
10397                         ssh2_pkt_addstring(s->pktout,
10398                                            s->cur_prompt->prompts[i]->result);
10399                     }
10400                     ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10401
10402                     /*
10403                      * Free the prompts structure from this iteration.
10404                      * If there's another, a new one will be allocated
10405                      * when we return to the top of this while loop.
10406                      */
10407                     free_prompts(s->cur_prompt);
10408
10409                     /*
10410                      * Get the next packet in case it's another
10411                      * INFO_REQUEST.
10412                      */
10413                     crWaitUntilV(pktin);
10414
10415                 }
10416
10417                 /*
10418                  * We should have SUCCESS or FAILURE now.
10419                  */
10420                 s->gotit = TRUE;
10421
10422             } else if (s->can_passwd) {
10423
10424                 /*
10425                  * Plain old password authentication.
10426                  */
10427                 int ret; /* not live over crReturn */
10428                 int changereq_first_time; /* not live over crReturn */
10429
10430                 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10431
10432                 s->cur_prompt = new_prompts(ssh->frontend);
10433                 s->cur_prompt->to_server = TRUE;
10434                 s->cur_prompt->name = dupstr("SSH password");
10435                 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10436                                                     ssh->username,
10437                                                     ssh->savedhost),
10438                            FALSE);
10439
10440                 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10441                 while (ret < 0) {
10442                     ssh->send_ok = 1;
10443                     crWaitUntilV(!pktin);
10444                     ret = get_userpass_input(s->cur_prompt, in, inlen);
10445                     ssh->send_ok = 0;
10446                 }
10447                 if (!ret) {
10448                     /*
10449                      * Failed to get responses. Terminate.
10450                      */
10451                     free_prompts(s->cur_prompt);
10452                     ssh_disconnect(ssh, NULL, "Unable to authenticate",
10453                                    SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10454                                    TRUE);
10455                     crStopV;
10456                 }
10457                 /*
10458                  * Squirrel away the password. (We may need it later if
10459                  * asked to change it.)
10460                  */
10461                 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10462                 free_prompts(s->cur_prompt);
10463
10464                 /*
10465                  * Send the password packet.
10466                  *
10467                  * We pad out the password packet to 256 bytes to make
10468                  * it harder for an attacker to find the length of the
10469                  * user's password.
10470                  *
10471                  * Anyone using a password longer than 256 bytes
10472                  * probably doesn't have much to worry about from
10473                  * people who find out how long their password is!
10474                  */
10475                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10476                 ssh2_pkt_addstring(s->pktout, ssh->username);
10477                 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10478                                                         /* service requested */
10479                 ssh2_pkt_addstring(s->pktout, "password");
10480                 ssh2_pkt_addbool(s->pktout, FALSE);
10481                 ssh2_pkt_addstring(s->pktout, s->password);
10482                 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10483                 logevent("Sent password");
10484                 s->type = AUTH_TYPE_PASSWORD;
10485
10486                 /*
10487                  * Wait for next packet, in case it's a password change
10488                  * request.
10489                  */
10490                 crWaitUntilV(pktin);
10491                 changereq_first_time = TRUE;
10492
10493                 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10494
10495                     /* 
10496                      * We're being asked for a new password
10497                      * (perhaps not for the first time).
10498                      * Loop until the server accepts it.
10499                      */
10500
10501                     int got_new = FALSE; /* not live over crReturn */
10502                     char *prompt;   /* not live over crReturn */
10503                     int prompt_len; /* not live over crReturn */
10504                     
10505                     {
10506                         const char *msg;
10507                         if (changereq_first_time)
10508                             msg = "Server requested password change";
10509                         else
10510                             msg = "Server rejected new password";
10511                         logevent(msg);
10512                         c_write_str(ssh, msg);
10513                         c_write_str(ssh, "\r\n");
10514                     }
10515
10516                     ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10517
10518                     s->cur_prompt = new_prompts(ssh->frontend);
10519                     s->cur_prompt->to_server = TRUE;
10520                     s->cur_prompt->name = dupstr("New SSH password");
10521                     s->cur_prompt->instruction =
10522                         dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10523                     s->cur_prompt->instr_reqd = TRUE;
10524                     /*
10525                      * There's no explicit requirement in the protocol
10526                      * for the "old" passwords in the original and
10527                      * password-change messages to be the same, and
10528                      * apparently some Cisco kit supports password change
10529                      * by the user entering a blank password originally
10530                      * and the real password subsequently, so,
10531                      * reluctantly, we prompt for the old password again.
10532                      *
10533                      * (On the other hand, some servers don't even bother
10534                      * to check this field.)
10535                      */
10536                     add_prompt(s->cur_prompt,
10537                                dupstr("Current password (blank for previously entered password): "),
10538                                FALSE);
10539                     add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10540                                FALSE);
10541                     add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10542                                FALSE);
10543
10544                     /*
10545                      * Loop until the user manages to enter the same
10546                      * password twice.
10547                      */
10548                     while (!got_new) {
10549
10550                         ret = get_userpass_input(s->cur_prompt, NULL, 0);
10551                         while (ret < 0) {
10552                             ssh->send_ok = 1;
10553                             crWaitUntilV(!pktin);
10554                             ret = get_userpass_input(s->cur_prompt, in, inlen);
10555                             ssh->send_ok = 0;
10556                         }
10557                         if (!ret) {
10558                             /*
10559                              * Failed to get responses. Terminate.
10560                              */
10561                             /* burn the evidence */
10562                             free_prompts(s->cur_prompt);
10563                             smemclr(s->password, strlen(s->password));
10564                             sfree(s->password);
10565                             ssh_disconnect(ssh, NULL, "Unable to authenticate",
10566                                            SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10567                                            TRUE);
10568                             crStopV;
10569                         }
10570
10571                         /*
10572                          * If the user specified a new original password
10573                          * (IYSWIM), overwrite any previously specified
10574                          * one.
10575                          * (A side effect is that the user doesn't have to
10576                          * re-enter it if they louse up the new password.)
10577                          */
10578                         if (s->cur_prompt->prompts[0]->result[0]) {
10579                             smemclr(s->password, strlen(s->password));
10580                                 /* burn the evidence */
10581                             sfree(s->password);
10582                             s->password =
10583                                 dupstr(s->cur_prompt->prompts[0]->result);
10584                         }
10585
10586                         /*
10587                          * Check the two new passwords match.
10588                          */
10589                         got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10590                                           s->cur_prompt->prompts[2]->result)
10591                                    == 0);
10592                         if (!got_new)
10593                             /* They don't. Silly user. */
10594                             c_write_str(ssh, "Passwords do not match\r\n");
10595
10596                     }
10597
10598                     /*
10599                      * Send the new password (along with the old one).
10600                      * (see above for padding rationale)
10601                      */
10602                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10603                     ssh2_pkt_addstring(s->pktout, ssh->username);
10604                     ssh2_pkt_addstring(s->pktout, "ssh-connection");
10605                                                         /* service requested */
10606                     ssh2_pkt_addstring(s->pktout, "password");
10607                     ssh2_pkt_addbool(s->pktout, TRUE);
10608                     ssh2_pkt_addstring(s->pktout, s->password);
10609                     ssh2_pkt_addstring(s->pktout,
10610                                        s->cur_prompt->prompts[1]->result);
10611                     free_prompts(s->cur_prompt);
10612                     ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10613                     logevent("Sent new password");
10614                     
10615                     /*
10616                      * Now see what the server has to say about it.
10617                      * (If it's CHANGEREQ again, it's not happy with the
10618                      * new password.)
10619                      */
10620                     crWaitUntilV(pktin);
10621                     changereq_first_time = FALSE;
10622
10623                 }
10624
10625                 /*
10626                  * We need to reexamine the current pktin at the top
10627                  * of the loop. Either:
10628                  *  - we weren't asked to change password at all, in
10629                  *    which case it's a SUCCESS or FAILURE with the
10630                  *    usual meaning
10631                  *  - we sent a new password, and the server was
10632                  *    either OK with it (SUCCESS or FAILURE w/partial
10633                  *    success) or unhappy with the _old_ password
10634                  *    (FAILURE w/o partial success)
10635                  * In any of these cases, we go back to the top of
10636                  * the loop and start again.
10637                  */
10638                 s->gotit = TRUE;
10639
10640                 /*
10641                  * We don't need the old password any more, in any
10642                  * case. Burn the evidence.
10643                  */
10644                 smemclr(s->password, strlen(s->password));
10645                 sfree(s->password);
10646
10647             } else {
10648                 char *str = dupprintf("No supported authentication methods available"
10649                                       " (server sent: %.*s)",
10650                                       methlen, methods);
10651
10652                 ssh_disconnect(ssh, str,
10653                                "No supported authentication methods available",
10654                                SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10655                                FALSE);
10656                 sfree(str);
10657
10658                 crStopV;
10659
10660             }
10661
10662         }
10663     }
10664     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10665
10666     /* Clear up various bits and pieces from authentication. */
10667     if (s->publickey_blob) {
10668         sfree(s->publickey_algorithm);
10669         sfree(s->publickey_blob);
10670         sfree(s->publickey_comment);
10671     }
10672     if (s->agent_response)
10673         sfree(s->agent_response);
10674
10675     if (s->userauth_success && !ssh->bare_connection) {
10676         /*
10677          * We've just received USERAUTH_SUCCESS, and we haven't sent any
10678          * packets since. Signal the transport layer to consider enacting
10679          * delayed compression.
10680          *
10681          * (Relying on we_are_in is not sufficient, as
10682          * draft-miller-secsh-compression-delayed is quite clear that it
10683          * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10684          * become set for other reasons.)
10685          */
10686         do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10687     }
10688
10689     ssh->channels = newtree234(ssh_channelcmp);
10690
10691     /*
10692      * Set up handlers for some connection protocol messages, so we
10693      * don't have to handle them repeatedly in this coroutine.
10694      */
10695     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10696         ssh2_msg_channel_window_adjust;
10697     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10698         ssh2_msg_global_request;
10699
10700     /*
10701      * Create the main session channel.
10702      */
10703     if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10704         ssh->mainchan = NULL;
10705     } else {
10706         ssh->mainchan = snew(struct ssh_channel);
10707         ssh->mainchan->ssh = ssh;
10708         ssh_channel_init(ssh->mainchan);
10709
10710         if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10711             /*
10712              * Just start a direct-tcpip channel and use it as the main
10713              * channel.
10714              */
10715             ssh_send_port_open(ssh->mainchan,
10716                                conf_get_str(ssh->conf, CONF_ssh_nc_host),
10717                                conf_get_int(ssh->conf, CONF_ssh_nc_port),
10718                                "main channel");
10719             ssh->ncmode = TRUE;
10720         } else {
10721             s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10722             logevent("Opening session as main channel");
10723             ssh2_pkt_send(ssh, s->pktout);
10724             ssh->ncmode = FALSE;
10725         }
10726         crWaitUntilV(pktin);
10727         if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10728             bombout(("Server refused to open channel"));
10729             crStopV;
10730             /* FIXME: error data comes back in FAILURE packet */
10731         }
10732         if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10733             bombout(("Server's channel confirmation cited wrong channel"));
10734             crStopV;
10735         }
10736         ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10737         ssh->mainchan->halfopen = FALSE;
10738         ssh->mainchan->type = CHAN_MAINSESSION;
10739         ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10740         ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10741         update_specials_menu(ssh->frontend);
10742         logevent("Opened main channel");
10743     }
10744
10745     /*
10746      * Now we have a channel, make dispatch table entries for
10747      * general channel-based messages.
10748      */
10749     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10750     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10751         ssh2_msg_channel_data;
10752     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10753     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10754     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10755         ssh2_msg_channel_open_confirmation;
10756     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10757         ssh2_msg_channel_open_failure;
10758     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10759         ssh2_msg_channel_request;
10760     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10761         ssh2_msg_channel_open;
10762     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10763     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10764
10765     /*
10766      * Now the connection protocol is properly up and running, with
10767      * all those dispatch table entries, so it's safe to let
10768      * downstreams start trying to open extra channels through us.
10769      */
10770     if (ssh->connshare)
10771         share_activate(ssh->connshare, ssh->v_s);
10772
10773     if (ssh->mainchan && ssh_is_simple(ssh)) {
10774         /*
10775          * This message indicates to the server that we promise
10776          * not to try to run any other channel in parallel with
10777          * this one, so it's safe for it to advertise a very large
10778          * window and leave the flow control to TCP.
10779          */
10780         s->pktout = ssh2_chanreq_init(ssh->mainchan,
10781                                       "simple@putty.projects.tartarus.org",
10782                                       NULL, NULL);
10783         ssh2_pkt_send(ssh, s->pktout);
10784     }
10785
10786     /*
10787      * Enable port forwardings.
10788      */
10789     ssh_setup_portfwd(ssh, ssh->conf);
10790
10791     if (ssh->mainchan && !ssh->ncmode) {
10792         /*
10793          * Send the CHANNEL_REQUESTS for the main session channel.
10794          * Each one is handled by its own little asynchronous
10795          * co-routine.
10796          */
10797
10798         /* Potentially enable X11 forwarding. */
10799         if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10800             ssh->x11disp =
10801                 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10802                                   ssh->conf);
10803             if (!ssh->x11disp) {
10804                 /* FIXME: return an error message from x11_setup_display */
10805                 logevent("X11 forwarding not enabled: unable to"
10806                          " initialise X display");
10807             } else {
10808                 ssh->x11auth = x11_invent_fake_auth
10809                     (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10810                 ssh->x11auth->disp = ssh->x11disp;
10811
10812                 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10813             }
10814         }
10815
10816         /* Potentially enable agent forwarding. */
10817         if (ssh_agent_forwarding_permitted(ssh))
10818             ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10819
10820         /* Now allocate a pty for the session. */
10821         if (!conf_get_int(ssh->conf, CONF_nopty))
10822             ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10823
10824         /* Send environment variables. */
10825         ssh2_setup_env(ssh->mainchan, NULL, NULL);
10826
10827         /*
10828          * Start a shell or a remote command. We may have to attempt
10829          * this twice if the config data has provided a second choice
10830          * of command.
10831          */
10832         while (1) {
10833             int subsys;
10834             char *cmd;
10835
10836             if (ssh->fallback_cmd) {
10837                 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10838                 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10839             } else {
10840                 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10841                 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10842             }
10843
10844             if (subsys) {
10845                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10846                                               ssh2_response_authconn, NULL);
10847                 ssh2_pkt_addstring(s->pktout, cmd);
10848             } else if (*cmd) {
10849                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10850                                               ssh2_response_authconn, NULL);
10851                 ssh2_pkt_addstring(s->pktout, cmd);
10852             } else {
10853                 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10854                                               ssh2_response_authconn, NULL);
10855             }
10856             ssh2_pkt_send(ssh, s->pktout);
10857
10858             crWaitUntilV(pktin);
10859
10860             if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10861                 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10862                     bombout(("Unexpected response to shell/command request:"
10863                              " packet type %d", pktin->type));
10864                     crStopV;
10865                 }
10866                 /*
10867                  * We failed to start the command. If this is the
10868                  * fallback command, we really are finished; if it's
10869                  * not, and if the fallback command exists, try falling
10870                  * back to it before complaining.
10871                  */
10872                 if (!ssh->fallback_cmd &&
10873                     *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10874                     logevent("Primary command failed; attempting fallback");
10875                     ssh->fallback_cmd = TRUE;
10876                     continue;
10877                 }
10878                 bombout(("Server refused to start a shell/command"));
10879                 crStopV;
10880             } else {
10881                 logevent("Started a shell/command");
10882             }
10883             break;
10884         }
10885     } else {
10886         ssh->editing = ssh->echoing = TRUE;
10887     }
10888
10889     ssh->state = SSH_STATE_SESSION;
10890     if (ssh->size_needed)
10891         ssh_size(ssh, ssh->term_width, ssh->term_height);
10892     if (ssh->eof_needed)
10893         ssh_special(ssh, TS_EOF);
10894
10895     /*
10896      * Transfer data!
10897      */
10898     if (ssh->ldisc)
10899         ldisc_echoedit_update(ssh->ldisc);  /* cause ldisc to notice changes */
10900     if (ssh->mainchan)
10901         ssh->send_ok = 1;
10902     while (1) {
10903         crReturnV;
10904         if (pktin) {
10905
10906             /*
10907              * _All_ the connection-layer packets we expect to
10908              * receive are now handled by the dispatch table.
10909              * Anything that reaches here must be bogus.
10910              */
10911
10912             bombout(("Strange packet received: type %d", pktin->type));
10913             crStopV;
10914         } else if (ssh->mainchan) {
10915             /*
10916              * We have spare data. Add it to the channel buffer.
10917              */
10918             ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10919         }
10920     }
10921
10922     crFinishV;
10923 }
10924
10925 /*
10926  * Handlers for SSH-2 messages that might arrive at any moment.
10927  */
10928 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10929 {
10930     /* log reason code in disconnect message */
10931     char *buf, *msg;
10932     int reason, msglen;
10933
10934     reason = ssh_pkt_getuint32(pktin);
10935     ssh_pkt_getstring(pktin, &msg, &msglen);
10936
10937     if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10938         buf = dupprintf("Received disconnect message (%s)",
10939                         ssh2_disconnect_reasons[reason]);
10940     } else {
10941         buf = dupprintf("Received disconnect message (unknown"
10942                         " type %d)", reason);
10943     }
10944     logevent(buf);
10945     sfree(buf);
10946     buf = dupprintf("Disconnection message text: %.*s",
10947                     msglen, NULLTOEMPTY(msg));
10948     logevent(buf);
10949     bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10950              reason,
10951              (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10952              ssh2_disconnect_reasons[reason] : "unknown",
10953              msglen, NULLTOEMPTY(msg)));
10954     sfree(buf);
10955 }
10956
10957 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10958 {
10959     /* log the debug message */
10960     char *msg;
10961     int msglen;
10962
10963     /* XXX maybe we should actually take notice of the return value */
10964     ssh2_pkt_getbool(pktin);
10965     ssh_pkt_getstring(pktin, &msg, &msglen);
10966
10967     logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10968 }
10969
10970 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10971 {
10972     do_ssh2_transport(ssh, NULL, 0, pktin);
10973 }
10974
10975 /*
10976  * Called if we receive a packet that isn't allowed by the protocol.
10977  * This only applies to packets whose meaning PuTTY understands.
10978  * Entirely unknown packets are handled below.
10979  */
10980 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10981 {
10982     char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10983                           ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10984                                         pktin->type));
10985     ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10986     sfree(buf);
10987 }
10988
10989 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10990 {
10991     struct Packet *pktout;
10992     pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10993     ssh2_pkt_adduint32(pktout, pktin->sequence);
10994     /*
10995      * UNIMPLEMENTED messages MUST appear in the same order as the
10996      * messages they respond to. Hence, never queue them.
10997      */
10998     ssh2_pkt_send_noqueue(ssh, pktout);
10999 }
11000
11001 /*
11002  * Handle the top-level SSH-2 protocol.
11003  */
11004 static void ssh2_protocol_setup(Ssh ssh)
11005 {
11006     int i;
11007
11008     /*
11009      * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11010      */
11011     for (i = 0; i < 256; i++)
11012         ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11013
11014     /*
11015      * Initially, we only accept transport messages (and a few generic
11016      * ones).  do_ssh2_authconn will add more when it starts.
11017      * Messages that are understood but not currently acceptable go to
11018      * ssh2_msg_unexpected.
11019      */
11020     ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11021     ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
11022     ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
11023     ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
11024     ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
11025     ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
11026     ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
11027     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
11028     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
11029     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
11030     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
11031     ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
11032     ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
11033     ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
11034     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
11035     ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
11036     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
11037     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
11038     ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
11039     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11040     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11041     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11042     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11043     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11044     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11045     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11046     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11047     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11048     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11049     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11050     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11051     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11052     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11053
11054     /*
11055      * These messages have a special handler from the start.
11056      */
11057     ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11058     ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11059     ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11060 }
11061
11062 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11063 {
11064     int i;
11065
11066     /*
11067      * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11068      */
11069     for (i = 0; i < 256; i++)
11070         ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11071
11072     /*
11073      * Initially, we set all ssh-connection messages to 'unexpected';
11074      * do_ssh2_authconn will fill things in properly. We also handle a
11075      * couple of messages from the transport protocol which aren't
11076      * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11077      * DISCONNECT).
11078      */
11079     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11080     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11081     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11082     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11083     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11084     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11085     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11086     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11087     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11088     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11089     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11090     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11091     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11092     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11093
11094     ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11095
11096     /*
11097      * These messages have a special handler from the start.
11098      */
11099     ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11100     ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11101     ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11102 }
11103
11104 static void ssh2_timer(void *ctx, unsigned long now)
11105 {
11106     Ssh ssh = (Ssh)ctx;
11107
11108     if (ssh->state == SSH_STATE_CLOSED)
11109         return;
11110
11111     if (!ssh->kex_in_progress && !ssh->bare_connection &&
11112         conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11113         now == ssh->next_rekey) {
11114         do_ssh2_transport(ssh, "timeout", -1, NULL);
11115     }
11116 }
11117
11118 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11119                           struct Packet *pktin)
11120 {
11121     const unsigned char *in = (const unsigned char *)vin;
11122     if (ssh->state == SSH_STATE_CLOSED)
11123         return;
11124
11125     if (pktin) {
11126         ssh->incoming_data_size += pktin->encrypted_len;
11127         if (!ssh->kex_in_progress &&
11128             ssh->max_data_size != 0 &&
11129             ssh->incoming_data_size > ssh->max_data_size)
11130             do_ssh2_transport(ssh, "too much data received", -1, NULL);
11131     }
11132
11133     if (pktin)
11134         ssh->packet_dispatch[pktin->type](ssh, pktin);
11135     else if (!ssh->protocol_initial_phase_done)
11136         do_ssh2_transport(ssh, in, inlen, pktin);
11137     else
11138         do_ssh2_authconn(ssh, in, inlen, pktin);
11139 }
11140
11141 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11142                                           struct Packet *pktin)
11143 {
11144     const unsigned char *in = (const unsigned char *)vin;
11145     if (ssh->state == SSH_STATE_CLOSED)
11146         return;
11147
11148     if (pktin)
11149         ssh->packet_dispatch[pktin->type](ssh, pktin);
11150     else
11151         do_ssh2_authconn(ssh, in, inlen, pktin);
11152 }
11153
11154 static void ssh_cache_conf_values(Ssh ssh)
11155 {
11156     ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11157 }
11158
11159 /*
11160  * Called to set up the connection.
11161  *
11162  * Returns an error message, or NULL on success.
11163  */
11164 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11165                             Conf *conf,
11166                             const char *host, int port, char **realhost,
11167                             int nodelay, int keepalive)
11168 {
11169     const char *p;
11170     Ssh ssh;
11171
11172     ssh = snew(struct ssh_tag);
11173     ssh->conf = conf_copy(conf);
11174     ssh_cache_conf_values(ssh);
11175     ssh->version = 0;                  /* when not ready yet */
11176     ssh->s = NULL;
11177     ssh->cipher = NULL;
11178     ssh->v1_cipher_ctx = NULL;
11179     ssh->crcda_ctx = NULL;
11180     ssh->cscipher = NULL;
11181     ssh->cs_cipher_ctx = NULL;
11182     ssh->sccipher = NULL;
11183     ssh->sc_cipher_ctx = NULL;
11184     ssh->csmac = NULL;
11185     ssh->cs_mac_ctx = NULL;
11186     ssh->scmac = NULL;
11187     ssh->sc_mac_ctx = NULL;
11188     ssh->cscomp = NULL;
11189     ssh->cs_comp_ctx = NULL;
11190     ssh->sccomp = NULL;
11191     ssh->sc_comp_ctx = NULL;
11192     ssh->kex = NULL;
11193     ssh->kex_ctx = NULL;
11194     ssh->hostkey = NULL;
11195     ssh->hostkey_str = NULL;
11196     ssh->exitcode = -1;
11197     ssh->close_expected = FALSE;
11198     ssh->clean_exit = FALSE;
11199     ssh->state = SSH_STATE_PREPACKET;
11200     ssh->size_needed = FALSE;
11201     ssh->eof_needed = FALSE;
11202     ssh->ldisc = NULL;
11203     ssh->logctx = NULL;
11204     ssh->deferred_send_data = NULL;
11205     ssh->deferred_len = 0;
11206     ssh->deferred_size = 0;
11207     ssh->fallback_cmd = 0;
11208     ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11209     ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11210     ssh->x11disp = NULL;
11211     ssh->x11auth = NULL;
11212     ssh->x11authtree = newtree234(x11_authcmp);
11213     ssh->v1_compressing = FALSE;
11214     ssh->v2_outgoing_sequence = 0;
11215     ssh->ssh1_rdpkt_crstate = 0;
11216     ssh->ssh2_rdpkt_crstate = 0;
11217     ssh->ssh2_bare_rdpkt_crstate = 0;
11218     ssh->ssh_gotdata_crstate = 0;
11219     ssh->do_ssh1_connection_crstate = 0;
11220     ssh->do_ssh_init_state = NULL;
11221     ssh->do_ssh_connection_init_state = NULL;
11222     ssh->do_ssh1_login_state = NULL;
11223     ssh->do_ssh2_transport_state = NULL;
11224     ssh->do_ssh2_authconn_state = NULL;
11225     ssh->v_c = NULL;
11226     ssh->v_s = NULL;
11227     ssh->mainchan = NULL;
11228     ssh->throttled_all = 0;
11229     ssh->v1_stdout_throttling = 0;
11230     ssh->queue = NULL;
11231     ssh->queuelen = ssh->queuesize = 0;
11232     ssh->queueing = FALSE;
11233     ssh->qhead = ssh->qtail = NULL;
11234     ssh->deferred_rekey_reason = NULL;
11235     bufchain_init(&ssh->queued_incoming_data);
11236     ssh->frozen = FALSE;
11237     ssh->username = NULL;
11238     ssh->sent_console_eof = FALSE;
11239     ssh->got_pty = FALSE;
11240     ssh->bare_connection = FALSE;
11241     ssh->X11_fwd_enabled = FALSE;
11242     ssh->connshare = NULL;
11243     ssh->attempting_connshare = FALSE;
11244     ssh->session_started = FALSE;
11245     ssh->specials = NULL;
11246     ssh->n_uncert_hostkeys = 0;
11247     ssh->cross_certifying = FALSE;
11248
11249     *backend_handle = ssh;
11250
11251 #ifdef MSCRYPTOAPI
11252     if (crypto_startup() == 0)
11253         return "Microsoft high encryption pack not installed!";
11254 #endif
11255
11256     ssh->frontend = frontend_handle;
11257     ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11258     ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11259
11260     ssh->channels = NULL;
11261     ssh->rportfwds = NULL;
11262     ssh->portfwds = NULL;
11263
11264     ssh->send_ok = 0;
11265     ssh->editing = 0;
11266     ssh->echoing = 0;
11267     ssh->conn_throttle_count = 0;
11268     ssh->overall_bufsize = 0;
11269     ssh->fallback_cmd = 0;
11270
11271     ssh->protocol = NULL;
11272
11273     ssh->protocol_initial_phase_done = FALSE;
11274
11275     ssh->pinger = NULL;
11276
11277     ssh->incoming_data_size = ssh->outgoing_data_size =
11278         ssh->deferred_data_size = 0L;
11279     ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11280                                                       CONF_ssh_rekey_data));
11281     ssh->kex_in_progress = FALSE;
11282
11283     ssh->auth_agent_query = NULL;
11284
11285 #ifndef NO_GSSAPI
11286     ssh->gsslibs = NULL;
11287 #endif
11288
11289     random_ref(); /* do this now - may be needed by sharing setup code */
11290
11291     p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11292     if (p != NULL) {
11293         random_unref();
11294         return p;
11295     }
11296
11297     return NULL;
11298 }
11299
11300 static void ssh_free(void *handle)
11301 {
11302     Ssh ssh = (Ssh) handle;
11303     struct ssh_channel *c;
11304     struct ssh_rportfwd *pf;
11305     struct X11FakeAuth *auth;
11306
11307     if (ssh->v1_cipher_ctx)
11308         ssh->cipher->free_context(ssh->v1_cipher_ctx);
11309     if (ssh->cs_cipher_ctx)
11310         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11311     if (ssh->sc_cipher_ctx)
11312         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11313     if (ssh->cs_mac_ctx)
11314         ssh->csmac->free_context(ssh->cs_mac_ctx);
11315     if (ssh->sc_mac_ctx)
11316         ssh->scmac->free_context(ssh->sc_mac_ctx);
11317     if (ssh->cs_comp_ctx) {
11318         if (ssh->cscomp)
11319             ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11320         else
11321             zlib_compress_cleanup(ssh->cs_comp_ctx);
11322     }
11323     if (ssh->sc_comp_ctx) {
11324         if (ssh->sccomp)
11325             ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11326         else
11327             zlib_decompress_cleanup(ssh->sc_comp_ctx);
11328     }
11329     if (ssh->kex_ctx)
11330         dh_cleanup(ssh->kex_ctx);
11331     sfree(ssh->savedhost);
11332
11333     while (ssh->queuelen-- > 0)
11334         ssh_free_packet(ssh->queue[ssh->queuelen]);
11335     sfree(ssh->queue);
11336
11337     while (ssh->qhead) {
11338         struct queued_handler *qh = ssh->qhead;
11339         ssh->qhead = qh->next;
11340         sfree(qh);
11341     }
11342     ssh->qhead = ssh->qtail = NULL;
11343
11344     if (ssh->channels) {
11345         while ((c = delpos234(ssh->channels, 0)) != NULL) {
11346             ssh_channel_close_local(c, NULL);
11347             if (ssh->version == 2) {
11348                 struct outstanding_channel_request *ocr, *nocr;
11349                 ocr = c->v.v2.chanreq_head;
11350                 while (ocr) {
11351                     ocr->handler(c, NULL, ocr->ctx);
11352                     nocr = ocr->next;
11353                     sfree(ocr);
11354                     ocr = nocr;
11355                 }
11356                 bufchain_clear(&c->v.v2.outbuffer);
11357             }
11358             sfree(c);
11359         }
11360         freetree234(ssh->channels);
11361         ssh->channels = NULL;
11362     }
11363
11364     if (ssh->connshare)
11365         sharestate_free(ssh->connshare);
11366
11367     if (ssh->rportfwds) {
11368         while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11369             free_rportfwd(pf);
11370         freetree234(ssh->rportfwds);
11371         ssh->rportfwds = NULL;
11372     }
11373     sfree(ssh->deferred_send_data);
11374     if (ssh->x11disp)
11375         x11_free_display(ssh->x11disp);
11376     while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11377         x11_free_fake_auth(auth);
11378     freetree234(ssh->x11authtree);
11379     sfree(ssh->do_ssh_init_state);
11380     sfree(ssh->do_ssh1_login_state);
11381     sfree(ssh->do_ssh2_transport_state);
11382     sfree(ssh->do_ssh2_authconn_state);
11383     sfree(ssh->v_c);
11384     sfree(ssh->v_s);
11385     sfree(ssh->fullhostname);
11386     sfree(ssh->hostkey_str);
11387     sfree(ssh->specials);
11388     if (ssh->crcda_ctx) {
11389         crcda_free_context(ssh->crcda_ctx);
11390         ssh->crcda_ctx = NULL;
11391     }
11392     if (ssh->s)
11393         ssh_do_close(ssh, TRUE);
11394     expire_timer_context(ssh);
11395     if (ssh->pinger)
11396         pinger_free(ssh->pinger);
11397     bufchain_clear(&ssh->queued_incoming_data);
11398     sfree(ssh->username);
11399     conf_free(ssh->conf);
11400
11401     if (ssh->auth_agent_query)
11402         agent_cancel_query(ssh->auth_agent_query);
11403
11404 #ifndef NO_GSSAPI
11405     if (ssh->gsslibs)
11406         ssh_gss_cleanup(ssh->gsslibs);
11407 #endif
11408     sfree(ssh);
11409
11410     random_unref();
11411 }
11412
11413 /*
11414  * Reconfigure the SSH backend.
11415  */
11416 static void ssh_reconfig(void *handle, Conf *conf)
11417 {
11418     Ssh ssh = (Ssh) handle;
11419     const char *rekeying = NULL;
11420     int rekey_mandatory = FALSE;
11421     unsigned long old_max_data_size;
11422     int i, rekey_time;
11423
11424     pinger_reconfig(ssh->pinger, ssh->conf, conf);
11425     if (ssh->portfwds)
11426         ssh_setup_portfwd(ssh, conf);
11427
11428     rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11429     if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11430         rekey_time != 0) {
11431         unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11432         unsigned long now = GETTICKCOUNT();
11433
11434         if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11435             rekeying = "timeout shortened";
11436         } else {
11437             ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11438         }
11439     }
11440
11441     old_max_data_size = ssh->max_data_size;
11442     ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11443                                                       CONF_ssh_rekey_data));
11444     if (old_max_data_size != ssh->max_data_size &&
11445         ssh->max_data_size != 0) {
11446         if (ssh->outgoing_data_size > ssh->max_data_size ||
11447             ssh->incoming_data_size > ssh->max_data_size)
11448             rekeying = "data limit lowered";
11449     }
11450
11451     if (conf_get_int(ssh->conf, CONF_compression) !=
11452         conf_get_int(conf, CONF_compression)) {
11453         rekeying = "compression setting changed";
11454         rekey_mandatory = TRUE;
11455     }
11456
11457     for (i = 0; i < CIPHER_MAX; i++)
11458         if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11459             conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11460         rekeying = "cipher settings changed";
11461         rekey_mandatory = TRUE;
11462     }
11463     if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11464         conf_get_int(conf, CONF_ssh2_des_cbc)) {
11465         rekeying = "cipher settings changed";
11466         rekey_mandatory = TRUE;
11467     }
11468
11469     conf_free(ssh->conf);
11470     ssh->conf = conf_copy(conf);
11471     ssh_cache_conf_values(ssh);
11472
11473     if (!ssh->bare_connection && rekeying) {
11474         if (!ssh->kex_in_progress) {
11475             do_ssh2_transport(ssh, rekeying, -1, NULL);
11476         } else if (rekey_mandatory) {
11477             ssh->deferred_rekey_reason = rekeying;
11478         }
11479     }
11480 }
11481
11482 /*
11483  * Called to send data down the SSH connection.
11484  */
11485 static int ssh_send(void *handle, const char *buf, int len)
11486 {
11487     Ssh ssh = (Ssh) handle;
11488
11489     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11490         return 0;
11491
11492     ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11493
11494     return ssh_sendbuffer(ssh);
11495 }
11496
11497 /*
11498  * Called to query the current amount of buffered stdin data.
11499  */
11500 static int ssh_sendbuffer(void *handle)
11501 {
11502     Ssh ssh = (Ssh) handle;
11503     int override_value;
11504
11505     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11506         return 0;
11507
11508     /*
11509      * If the SSH socket itself has backed up, add the total backup
11510      * size on that to any individual buffer on the stdin channel.
11511      */
11512     override_value = 0;
11513     if (ssh->throttled_all)
11514         override_value = ssh->overall_bufsize;
11515
11516     if (ssh->version == 1) {
11517         return override_value;
11518     } else if (ssh->version == 2) {
11519         if (!ssh->mainchan)
11520             return override_value;
11521         else
11522             return (override_value +
11523                     bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11524     }
11525
11526     return 0;
11527 }
11528
11529 /*
11530  * Called to set the size of the window from SSH's POV.
11531  */
11532 static void ssh_size(void *handle, int width, int height)
11533 {
11534     Ssh ssh = (Ssh) handle;
11535     struct Packet *pktout;
11536
11537     ssh->term_width = width;
11538     ssh->term_height = height;
11539
11540     switch (ssh->state) {
11541       case SSH_STATE_BEFORE_SIZE:
11542       case SSH_STATE_PREPACKET:
11543       case SSH_STATE_CLOSED:
11544         break;                         /* do nothing */
11545       case SSH_STATE_INTERMED:
11546         ssh->size_needed = TRUE;       /* buffer for later */
11547         break;
11548       case SSH_STATE_SESSION:
11549         if (!conf_get_int(ssh->conf, CONF_nopty)) {
11550             if (ssh->version == 1) {
11551                 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11552                             PKT_INT, ssh->term_height,
11553                             PKT_INT, ssh->term_width,
11554                             PKT_INT, 0, PKT_INT, 0, PKT_END);
11555             } else if (ssh->mainchan) {
11556                 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11557                                            NULL, NULL);
11558                 ssh2_pkt_adduint32(pktout, ssh->term_width);
11559                 ssh2_pkt_adduint32(pktout, ssh->term_height);
11560                 ssh2_pkt_adduint32(pktout, 0);
11561                 ssh2_pkt_adduint32(pktout, 0);
11562                 ssh2_pkt_send(ssh, pktout);
11563             }
11564         }
11565         break;
11566     }
11567 }
11568
11569 /*
11570  * Return a list of the special codes that make sense in this
11571  * protocol.
11572  */
11573 static const struct telnet_special *ssh_get_specials(void *handle)
11574 {
11575     static const struct telnet_special ssh1_ignore_special[] = {
11576         {"IGNORE message", TS_NOP}
11577     };
11578     static const struct telnet_special ssh2_ignore_special[] = {
11579         {"IGNORE message", TS_NOP},
11580     };
11581     static const struct telnet_special ssh2_rekey_special[] = {
11582         {"Repeat key exchange", TS_REKEY},
11583     };
11584     static const struct telnet_special ssh2_session_specials[] = {
11585         {NULL, TS_SEP},
11586         {"Break", TS_BRK},
11587         /* These are the signal names defined by RFC 4254.
11588          * They include all the ISO C signals, but are a subset of the POSIX
11589          * required signals. */
11590         {"SIGINT (Interrupt)", TS_SIGINT},
11591         {"SIGTERM (Terminate)", TS_SIGTERM},
11592         {"SIGKILL (Kill)", TS_SIGKILL},
11593         {"SIGQUIT (Quit)", TS_SIGQUIT},
11594         {"SIGHUP (Hangup)", TS_SIGHUP},
11595         {"More signals", TS_SUBMENU},
11596           {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11597           {"SIGFPE",  TS_SIGFPE},  {"SIGILL",  TS_SIGILL},
11598           {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11599           {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11600         {NULL, TS_EXITMENU}
11601     };
11602     static const struct telnet_special specials_end[] = {
11603         {NULL, TS_EXITMENU}
11604     };
11605
11606     struct telnet_special *specials = NULL;
11607     int nspecials = 0, specialsize = 0;
11608
11609     Ssh ssh = (Ssh) handle;
11610
11611     sfree(ssh->specials);
11612
11613 #define ADD_SPECIALS(name) do                                           \
11614     {                                                                   \
11615         int len = lenof(name);                                          \
11616         if (nspecials + len > specialsize) {                            \
11617             specialsize = (nspecials + len) * 5 / 4 + 32;               \
11618             specials = sresize(specials, specialsize, struct telnet_special); \
11619         }                                                               \
11620         memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11621         nspecials += len;                                               \
11622     } while (0)
11623
11624     if (ssh->version == 1) {
11625         /* Don't bother offering IGNORE if we've decided the remote
11626          * won't cope with it, since we wouldn't bother sending it if
11627          * asked anyway. */
11628         if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11629             ADD_SPECIALS(ssh1_ignore_special);
11630     } else if (ssh->version == 2) {
11631         if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11632             ADD_SPECIALS(ssh2_ignore_special);
11633         if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11634             ADD_SPECIALS(ssh2_rekey_special);
11635         if (ssh->mainchan)
11636             ADD_SPECIALS(ssh2_session_specials);
11637
11638         if (ssh->n_uncert_hostkeys) {
11639             static const struct telnet_special uncert_start[] = {
11640                 {NULL, TS_SEP},
11641                 {"Cache new host key type", TS_SUBMENU},
11642             };
11643             static const struct telnet_special uncert_end[] = {
11644                 {NULL, TS_EXITMENU},
11645             };
11646             int i;
11647
11648             ADD_SPECIALS(uncert_start);
11649             for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11650                 struct telnet_special uncert[1];
11651                 const struct ssh_signkey *alg =
11652                     hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11653                 uncert[0].name = alg->name;
11654                 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11655                 ADD_SPECIALS(uncert);
11656             }
11657             ADD_SPECIALS(uncert_end);
11658         }
11659     } /* else we're not ready yet */
11660
11661     if (nspecials)
11662         ADD_SPECIALS(specials_end);
11663
11664     ssh->specials = specials;
11665
11666     if (nspecials) {
11667         return specials;
11668     } else {
11669         return NULL;
11670     }
11671 #undef ADD_SPECIALS
11672 }
11673
11674 /*
11675  * Send special codes. TS_EOF is useful for `plink', so you
11676  * can send an EOF and collect resulting output (e.g. `plink
11677  * hostname sort').
11678  */
11679 static void ssh_special(void *handle, Telnet_Special code)
11680 {
11681     Ssh ssh = (Ssh) handle;
11682     struct Packet *pktout;
11683
11684     if (code == TS_EOF) {
11685         if (ssh->state != SSH_STATE_SESSION) {
11686             /*
11687              * Buffer the EOF in case we are pre-SESSION, so we can
11688              * send it as soon as we reach SESSION.
11689              */
11690             if (code == TS_EOF)
11691                 ssh->eof_needed = TRUE;
11692             return;
11693         }
11694         if (ssh->version == 1) {
11695             send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11696         } else if (ssh->mainchan) {
11697             sshfwd_write_eof(ssh->mainchan);
11698             ssh->send_ok = 0;          /* now stop trying to read from stdin */
11699         }
11700         logevent("Sent EOF message");
11701     } else if (code == TS_PING || code == TS_NOP) {
11702         if (ssh->state == SSH_STATE_CLOSED
11703             || ssh->state == SSH_STATE_PREPACKET) return;
11704         if (ssh->version == 1) {
11705             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11706                 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11707         } else {
11708             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11709                 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11710                 ssh2_pkt_addstring_start(pktout);
11711                 ssh2_pkt_send_noqueue(ssh, pktout);
11712             }
11713         }
11714     } else if (code == TS_REKEY) {
11715         if (!ssh->kex_in_progress && !ssh->bare_connection &&
11716             ssh->version == 2) {
11717             do_ssh2_transport(ssh, "at user request", -1, NULL);
11718         }
11719     } else if (code >= TS_LOCALSTART) {
11720         ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11721         ssh->cross_certifying = TRUE;
11722         if (!ssh->kex_in_progress && !ssh->bare_connection &&
11723             ssh->version == 2) {
11724             do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11725         }
11726     } else if (code == TS_BRK) {
11727         if (ssh->state == SSH_STATE_CLOSED
11728             || ssh->state == SSH_STATE_PREPACKET) return;
11729         if (ssh->version == 1) {
11730             logevent("Unable to send BREAK signal in SSH-1");
11731         } else if (ssh->mainchan) {
11732             pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11733             ssh2_pkt_adduint32(pktout, 0);   /* default break length */
11734             ssh2_pkt_send(ssh, pktout);
11735         }
11736     } else {
11737         /* Is is a POSIX signal? */
11738         const char *signame = NULL;
11739         if (code == TS_SIGABRT) signame = "ABRT";
11740         if (code == TS_SIGALRM) signame = "ALRM";
11741         if (code == TS_SIGFPE)  signame = "FPE";
11742         if (code == TS_SIGHUP)  signame = "HUP";
11743         if (code == TS_SIGILL)  signame = "ILL";
11744         if (code == TS_SIGINT)  signame = "INT";
11745         if (code == TS_SIGKILL) signame = "KILL";
11746         if (code == TS_SIGPIPE) signame = "PIPE";
11747         if (code == TS_SIGQUIT) signame = "QUIT";
11748         if (code == TS_SIGSEGV) signame = "SEGV";
11749         if (code == TS_SIGTERM) signame = "TERM";
11750         if (code == TS_SIGUSR1) signame = "USR1";
11751         if (code == TS_SIGUSR2) signame = "USR2";
11752         /* The SSH-2 protocol does in principle support arbitrary named
11753          * signals, including signame@domain, but we don't support those. */
11754         if (signame) {
11755             /* It's a signal. */
11756             if (ssh->version == 2 && ssh->mainchan) {
11757                 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11758                 ssh2_pkt_addstring(pktout, signame);
11759                 ssh2_pkt_send(ssh, pktout);
11760                 logeventf(ssh, "Sent signal SIG%s", signame);
11761             }
11762         } else {
11763             /* Never heard of it. Do nothing */
11764         }
11765     }
11766 }
11767
11768 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11769 {
11770     Ssh ssh = (Ssh) handle;
11771     struct ssh_channel *c;
11772     c = snew(struct ssh_channel);
11773
11774     c->ssh = ssh;
11775     ssh_channel_init(c);
11776     c->halfopen = TRUE;
11777     c->type = CHAN_SOCKDATA;/* identify channel type */
11778     c->u.pfd.pf = pf;
11779     return c;
11780 }
11781
11782 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11783 {
11784     struct ssh_channel *c;
11785     c = snew(struct ssh_channel);
11786
11787     c->ssh = ssh;
11788     ssh_channel_init(c);
11789     c->type = CHAN_SHARING;
11790     c->u.sharing.ctx = sharing_ctx;
11791     return c->localid;
11792 }
11793
11794 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11795 {
11796     struct ssh_channel *c;
11797
11798     c = find234(ssh->channels, &localid, ssh_channelfind);
11799     if (c)
11800         ssh_channel_destroy(c);
11801 }
11802
11803 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11804                                      const void *data, int datalen,
11805                                      const char *additional_log_text)
11806 {
11807     struct Packet *pkt;
11808
11809     pkt = ssh2_pkt_init(type);
11810     pkt->downstream_id = id;
11811     pkt->additional_log_text = additional_log_text;
11812     ssh2_pkt_adddata(pkt, data, datalen);
11813     ssh2_pkt_send(ssh, pkt);
11814 }
11815
11816 /*
11817  * This is called when stdout/stderr (the entity to which
11818  * from_backend sends data) manages to clear some backlog.
11819  */
11820 static void ssh_unthrottle(void *handle, int bufsize)
11821 {
11822     Ssh ssh = (Ssh) handle;
11823
11824     if (ssh->version == 1) {
11825         if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11826             ssh->v1_stdout_throttling = 0;
11827             ssh_throttle_conn(ssh, -1);
11828         }
11829     } else {
11830         if (ssh->mainchan)
11831             ssh_channel_unthrottle(ssh->mainchan, bufsize);
11832     }
11833
11834     /*
11835      * Now process any SSH connection data that was stashed in our
11836      * queue while we were frozen.
11837      */
11838     ssh_process_queued_incoming_data(ssh);
11839 }
11840
11841 void ssh_send_port_open(void *channel, const char *hostname, int port,
11842                         const char *org)
11843 {
11844     struct ssh_channel *c = (struct ssh_channel *)channel;
11845     Ssh ssh = c->ssh;
11846     struct Packet *pktout;
11847
11848     logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11849
11850     if (ssh->version == 1) {
11851         send_packet(ssh, SSH1_MSG_PORT_OPEN,
11852                     PKT_INT, c->localid,
11853                     PKT_STR, hostname,
11854                     PKT_INT, port,
11855                     /* PKT_STR, <org:orgport>, */
11856                     PKT_END);
11857     } else {
11858         pktout = ssh2_chanopen_init(c, "direct-tcpip");
11859         {
11860             char *trimmed_host = host_strduptrim(hostname);
11861             ssh2_pkt_addstring(pktout, trimmed_host);
11862             sfree(trimmed_host);
11863         }
11864         ssh2_pkt_adduint32(pktout, port);
11865         /*
11866          * We make up values for the originator data; partly it's
11867          * too much hassle to keep track, and partly I'm not
11868          * convinced the server should be told details like that
11869          * about my local network configuration.
11870          * The "originator IP address" is syntactically a numeric
11871          * IP address, and some servers (e.g., Tectia) get upset
11872          * if it doesn't match this syntax.
11873          */
11874         ssh2_pkt_addstring(pktout, "0.0.0.0");
11875         ssh2_pkt_adduint32(pktout, 0);
11876         ssh2_pkt_send(ssh, pktout);
11877     }
11878 }
11879
11880 static int ssh_connected(void *handle)
11881 {
11882     Ssh ssh = (Ssh) handle;
11883     return ssh->s != NULL;
11884 }
11885
11886 static int ssh_sendok(void *handle)
11887 {
11888     Ssh ssh = (Ssh) handle;
11889     return ssh->send_ok;
11890 }
11891
11892 static int ssh_ldisc(void *handle, int option)
11893 {
11894     Ssh ssh = (Ssh) handle;
11895     if (option == LD_ECHO)
11896         return ssh->echoing;
11897     if (option == LD_EDIT)
11898         return ssh->editing;
11899     return FALSE;
11900 }
11901
11902 static void ssh_provide_ldisc(void *handle, void *ldisc)
11903 {
11904     Ssh ssh = (Ssh) handle;
11905     ssh->ldisc = ldisc;
11906 }
11907
11908 static void ssh_provide_logctx(void *handle, void *logctx)
11909 {
11910     Ssh ssh = (Ssh) handle;
11911     ssh->logctx = logctx;
11912 }
11913
11914 static int ssh_return_exitcode(void *handle)
11915 {
11916     Ssh ssh = (Ssh) handle;
11917     if (ssh->s != NULL)
11918         return -1;
11919     else
11920         return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11921 }
11922
11923 /*
11924  * cfg_info for SSH is the protocol running in this session.
11925  * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11926  * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11927  */
11928 static int ssh_cfg_info(void *handle)
11929 {
11930     Ssh ssh = (Ssh) handle;
11931     if (ssh->version == 0)
11932         return 0; /* don't know yet */
11933     else if (ssh->bare_connection)
11934         return -1;
11935     else
11936         return ssh->version;
11937 }
11938
11939 /*
11940  * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11941  * that fails. This variable is the means by which scp.c can reach
11942  * into the SSH code and find out which one it got.
11943  */
11944 extern int ssh_fallback_cmd(void *handle)
11945 {
11946     Ssh ssh = (Ssh) handle;
11947     return ssh->fallback_cmd;
11948 }
11949
11950 Backend ssh_backend = {
11951     ssh_init,
11952     ssh_free,
11953     ssh_reconfig,
11954     ssh_send,
11955     ssh_sendbuffer,
11956     ssh_size,
11957     ssh_special,
11958     ssh_get_specials,
11959     ssh_connected,
11960     ssh_return_exitcode,
11961     ssh_sendok,
11962     ssh_ldisc,
11963     ssh_provide_ldisc,
11964     ssh_provide_logctx,
11965     ssh_unthrottle,
11966     ssh_cfg_info,
11967     ssh_test_for_upstream,
11968     "ssh",
11969     PROT_SSH,
11970     22
11971 };