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