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