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