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