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