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