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