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