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