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