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