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