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