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