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