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