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