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