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