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