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