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