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