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