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