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