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