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