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