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