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