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