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