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