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