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