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