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