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