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