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