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