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