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