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