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