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