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