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