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