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