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