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