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