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