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