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