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