]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - ssh.c
Bit more robustness when talking to Pageant
[PuTTY_svn.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 #define logevent(s) { logevent(s); \
19                       if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20                       fprintf(stderr, "%s\n", s); }
21
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
23                           (s ? sk_close(s), s = NULL : 0), \
24                           connection_fatal msg )
25
26 #define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
27 #define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
28 #define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
29 #define SSH1_CMSG_USER                            4    /* 0x4 */
30 #define SSH1_CMSG_AUTH_RSA                        6    /* 0x6 */
31 #define SSH1_SMSG_AUTH_RSA_CHALLENGE              7    /* 0x7 */
32 #define SSH1_CMSG_AUTH_RSA_RESPONSE               8    /* 0x8 */
33 #define SSH1_CMSG_AUTH_PASSWORD                   9    /* 0x9 */
34 #define SSH1_CMSG_REQUEST_PTY                     10   /* 0xa */
35 #define SSH1_CMSG_WINDOW_SIZE                     11   /* 0xb */
36 #define SSH1_CMSG_EXEC_SHELL                      12   /* 0xc */
37 #define SSH1_CMSG_EXEC_CMD                        13   /* 0xd */
38 #define SSH1_SMSG_SUCCESS                         14   /* 0xe */
39 #define SSH1_SMSG_FAILURE                         15   /* 0xf */
40 #define SSH1_CMSG_STDIN_DATA                      16   /* 0x10 */
41 #define SSH1_SMSG_STDOUT_DATA                     17   /* 0x11 */
42 #define SSH1_SMSG_STDERR_DATA                     18   /* 0x12 */
43 #define SSH1_CMSG_EOF                             19   /* 0x13 */
44 #define SSH1_SMSG_EXIT_STATUS                     20   /* 0x14 */
45 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21   /* 0x15 */
46 #define SSH1_MSG_CHANNEL_OPEN_FAILURE             22   /* 0x16 */
47 #define SSH1_MSG_CHANNEL_DATA                     23   /* 0x17 */
48 #define SSH1_MSG_CHANNEL_CLOSE                    24   /* 0x18 */
49 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25   /* 0x19 */
50 #define SSH1_SMSG_X11_OPEN                        27   /* 0x1b */
51 #define SSH1_CMSG_PORT_FORWARD_REQUEST            28   /* 0x1c */
52 #define SSH1_MSG_PORT_OPEN                        29   /* 0x1d */
53 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30   /* 0x1e */
54 #define SSH1_SMSG_AGENT_OPEN                      31   /* 0x1f */
55 #define SSH1_MSG_IGNORE                           32   /* 0x20 */
56 #define SSH1_CMSG_EXIT_CONFIRMATION               33   /* 0x21 */
57 #define SSH1_CMSG_X11_REQUEST_FORWARDING          34   /* 0x22 */
58 #define SSH1_CMSG_AUTH_RHOSTS_RSA                 35   /* 0x23 */
59 #define SSH1_MSG_DEBUG                            36   /* 0x24 */
60 #define SSH1_CMSG_REQUEST_COMPRESSION             37   /* 0x25 */
61 #define SSH1_CMSG_AUTH_TIS                        39   /* 0x27 */
62 #define SSH1_SMSG_AUTH_TIS_CHALLENGE              40   /* 0x28 */
63 #define SSH1_CMSG_AUTH_TIS_RESPONSE               41   /* 0x29 */
64 #define SSH1_CMSG_AUTH_CCARD                      70   /* 0x46 */
65 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE            71   /* 0x47 */
66 #define SSH1_CMSG_AUTH_CCARD_RESPONSE             72   /* 0x48 */
67
68 #define SSH1_AUTH_TIS                             5    /* 0x5 */
69 #define SSH1_AUTH_CCARD                           16   /* 0x10 */
70
71 #define SSH2_MSG_DISCONNECT                       1    /* 0x1 */
72 #define SSH2_MSG_IGNORE                           2    /* 0x2 */
73 #define SSH2_MSG_UNIMPLEMENTED                    3    /* 0x3 */
74 #define SSH2_MSG_DEBUG                            4    /* 0x4 */
75 #define SSH2_MSG_SERVICE_REQUEST                  5    /* 0x5 */
76 #define SSH2_MSG_SERVICE_ACCEPT                   6    /* 0x6 */
77 #define SSH2_MSG_KEXINIT                          20   /* 0x14 */
78 #define SSH2_MSG_NEWKEYS                          21   /* 0x15 */
79 #define SSH2_MSG_KEXDH_INIT                       30   /* 0x1e */
80 #define SSH2_MSG_KEXDH_REPLY                      31   /* 0x1f */
81 #define SSH2_MSG_KEX_DH_GEX_REQUEST               30   /* 0x1e */
82 #define SSH2_MSG_KEX_DH_GEX_GROUP                 31   /* 0x1f */
83 #define SSH2_MSG_KEX_DH_GEX_INIT                  32   /* 0x20 */
84 #define SSH2_MSG_KEX_DH_GEX_REPLY                 33   /* 0x21 */
85 #define SSH2_MSG_USERAUTH_REQUEST                 50   /* 0x32 */
86 #define SSH2_MSG_USERAUTH_FAILURE                 51   /* 0x33 */
87 #define SSH2_MSG_USERAUTH_SUCCESS                 52   /* 0x34 */
88 #define SSH2_MSG_USERAUTH_BANNER                  53   /* 0x35 */
89 #define SSH2_MSG_USERAUTH_PK_OK                   60   /* 0x3c */
90 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ        60   /* 0x3c */
91 #define SSH2_MSG_GLOBAL_REQUEST                   80   /* 0x50 */
92 #define SSH2_MSG_REQUEST_SUCCESS                  81   /* 0x51 */
93 #define SSH2_MSG_REQUEST_FAILURE                  82   /* 0x52 */
94 #define SSH2_MSG_CHANNEL_OPEN                     90   /* 0x5a */
95 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION        91   /* 0x5b */
96 #define SSH2_MSG_CHANNEL_OPEN_FAILURE             92   /* 0x5c */
97 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST            93   /* 0x5d */
98 #define SSH2_MSG_CHANNEL_DATA                     94   /* 0x5e */
99 #define SSH2_MSG_CHANNEL_EXTENDED_DATA            95   /* 0x5f */
100 #define SSH2_MSG_CHANNEL_EOF                      96   /* 0x60 */
101 #define SSH2_MSG_CHANNEL_CLOSE                    97   /* 0x61 */
102 #define SSH2_MSG_CHANNEL_REQUEST                  98   /* 0x62 */
103 #define SSH2_MSG_CHANNEL_SUCCESS                  99   /* 0x63 */
104 #define SSH2_MSG_CHANNEL_FAILURE                  100  /* 0x64 */
105
106 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1  /* 0x1 */
107 #define SSH2_DISCONNECT_PROTOCOL_ERROR            2    /* 0x2 */
108 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED       3    /* 0x3 */
109 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4   /* 0x4 */
110 #define SSH2_DISCONNECT_MAC_ERROR                 5    /* 0x5 */
111 #define SSH2_DISCONNECT_COMPRESSION_ERROR         6    /* 0x6 */
112 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE     7    /* 0x7 */
113 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
114 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE   9    /* 0x9 */
115 #define SSH2_DISCONNECT_CONNECTION_LOST           10   /* 0xa */
116 #define SSH2_DISCONNECT_BY_APPLICATION            11   /* 0xb */
117
118 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED     1    /* 0x1 */
119 #define SSH2_OPEN_CONNECT_FAILED                  2    /* 0x2 */
120 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE            3    /* 0x3 */
121 #define SSH2_OPEN_RESOURCE_SHORTAGE               4    /* 0x4 */
122
123 #define SSH2_EXTENDED_DATA_STDERR                 1    /* 0x1 */
124
125 /*
126  * Various remote-bug flags.
127  */
128 #define BUG_CHOKES_ON_SSH1_IGNORE                 1
129 #define BUG_SSH2_HMAC                             2
130
131 #define GET_32BIT(cp) \
132     (((unsigned long)(unsigned char)(cp)[0] << 24) | \
133     ((unsigned long)(unsigned char)(cp)[1] << 16) | \
134     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
135     ((unsigned long)(unsigned char)(cp)[3]))
136
137 #define PUT_32BIT(cp, value) { \
138     (cp)[0] = (unsigned char)((value) >> 24); \
139     (cp)[1] = (unsigned char)((value) >> 16); \
140     (cp)[2] = (unsigned char)((value) >> 8); \
141     (cp)[3] = (unsigned char)(value); }
142
143 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
144
145 /* Coroutine mechanics for the sillier bits of the code */
146 #define crBegin1        static int crLine = 0;
147 #define crBegin2        switch(crLine) { case 0:;
148 #define crBegin         crBegin1; crBegin2;
149 #define crFinish(z)     } crLine = 0; return (z)
150 #define crFinishV       } crLine = 0; return
151 #define crReturn(z)     \
152         do {\
153             crLine=__LINE__; return (z); case __LINE__:;\
154         } while (0)
155 #define crReturnV       \
156         do {\
157             crLine=__LINE__; return; case __LINE__:;\
158         } while (0)
159 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
160 #define crStopV         do{ crLine = 0; return; }while(0)
161 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
162 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
163
164 extern char *x11_init (Socket *, char *, void *);
165 extern void x11_close (Socket);
166 extern void x11_send  (Socket , char *, int);
167 extern void x11_invent_auth(char *, int, char *, int);
168
169 /*
170  * Ciphers for SSH2. We miss out single-DES because it isn't
171  * supported; also 3DES and Blowfish are both done differently from
172  * SSH1. (3DES uses outer chaining; Blowfish has the opposite
173  * endianness and different-sized keys.)
174  */
175 const static struct ssh2_ciphers *ciphers[] = {
176     &ssh2_aes,
177     &ssh2_blowfish,
178     &ssh2_3des,
179 };
180
181 const static struct ssh_kex *kex_algs[] = {
182     &ssh_diffiehellman_gex,
183     &ssh_diffiehellman };
184
185 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
186
187 static void nullmac_key(unsigned char *key) { }
188 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
189 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
190 const static struct ssh_mac ssh_mac_none = {
191     nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
192 };
193 const static struct ssh_mac *macs[] = {
194     &ssh_sha1, &ssh_md5, &ssh_mac_none };
195 const static struct ssh_mac *buggymacs[] = {
196     &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none };
197
198 static void ssh_comp_none_init(void) { }
199 static int ssh_comp_none_block(unsigned char *block, int len,
200                                unsigned char **outblock, int *outlen) {
201     return 0;
202 }
203 static int ssh_comp_none_disable(void) { return 0; }
204 const static struct ssh_compress ssh_comp_none = {
205     "none",
206     ssh_comp_none_init, ssh_comp_none_block,
207     ssh_comp_none_init, ssh_comp_none_block,
208     ssh_comp_none_disable
209 };
210 extern const struct ssh_compress ssh_zlib;
211 const static struct ssh_compress *compressions[] = {
212     &ssh_zlib, &ssh_comp_none };
213
214 enum {                                 /* channel types */
215     CHAN_MAINSESSION,
216     CHAN_X11,
217     CHAN_AGENT,
218 };
219
220 /*
221  * 2-3-4 tree storing channels.
222  */
223 struct ssh_channel {
224     unsigned remoteid, localid;
225     int type;
226     int closes;
227     struct ssh2_data_channel {
228         unsigned char *outbuffer;
229         unsigned outbuflen, outbufsize;
230         unsigned remwindow, remmaxpkt;
231     } v2;
232     union {
233         struct ssh_agent_channel {
234             unsigned char *message;
235             unsigned char msglen[4];
236             int lensofar, totallen;
237         } a;
238         struct ssh_x11_channel {
239             Socket s;
240         } x11;
241     } u;
242 };
243
244 struct Packet {
245     long length;
246     int type;
247     unsigned char *data;
248     unsigned char *body;
249     long savedpos;
250     long maxlen;
251 };
252
253 static SHA_State exhash, exhashbase;
254
255 static Socket s = NULL;
256
257 static unsigned char session_key[32];
258 static int ssh1_compressing;
259 static int ssh_agentfwd_enabled;
260 static int ssh_X11_fwd_enabled;
261 static int ssh_remote_bugs;
262 static const struct ssh_cipher *cipher = NULL;
263 static const struct ssh2_cipher *cscipher = NULL;
264 static const struct ssh2_cipher *sccipher = NULL;
265 static const struct ssh_mac *csmac = NULL;
266 static const struct ssh_mac *scmac = NULL;
267 static const struct ssh_compress *cscomp = NULL;
268 static const struct ssh_compress *sccomp = NULL;
269 static const struct ssh_kex *kex = NULL;
270 static const struct ssh_signkey *hostkey = NULL;
271 static unsigned char ssh2_session_id[20];
272 int (*ssh_get_line)(const char *prompt, char *str, int maxlen,
273                     int is_pw) = NULL;
274
275 static char *savedhost;
276 static int savedport;
277 static int ssh_send_ok;
278 static int ssh_echoing, ssh_editing;
279
280 static tree234 *ssh_channels;           /* indexed by local id */
281 static struct ssh_channel *mainchan;   /* primary session channel */
282
283 static enum {
284     SSH_STATE_PREPACKET,
285     SSH_STATE_BEFORE_SIZE,
286     SSH_STATE_INTERMED,
287     SSH_STATE_SESSION,
288     SSH_STATE_CLOSED
289 } ssh_state = SSH_STATE_PREPACKET;
290
291 static int size_needed = FALSE, eof_needed = FALSE;
292
293 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
294 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
295 static unsigned char *deferred_send_data = NULL;
296 static int deferred_len = 0, deferred_size = 0;
297
298 static int ssh_version;
299 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
300 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
301 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
302 static void ssh_size(void);
303 static void ssh_special (Telnet_Special);
304 static void ssh2_try_send(struct ssh_channel *c);
305 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
306
307 static int (*s_rdpkt)(unsigned char **data, int *datalen);
308
309 static struct rdpkt1_state_tag {
310     long len, pad, biglen, to_read;
311     unsigned long realcrc, gotcrc;
312     unsigned char *p;
313     int i;
314     int chunk;
315 } rdpkt1_state;
316
317 static struct rdpkt2_state_tag {
318     long len, pad, payload, packetlen, maclen;
319     int i;
320     int cipherblk;
321     unsigned long incoming_sequence;
322 } rdpkt2_state;
323
324 static int ssh_channelcmp(void *av, void *bv) {
325     struct ssh_channel *a = (struct ssh_channel *)av;
326     struct ssh_channel *b = (struct ssh_channel *)bv;
327     if (a->localid < b->localid) return -1;
328     if (a->localid > b->localid) return +1;
329     return 0;
330 }
331 static int ssh_channelfind(void *av, void *bv) {
332     unsigned *a = (unsigned *)av;
333     struct ssh_channel *b = (struct ssh_channel *)bv;
334     if (*a < b->localid) return -1;
335     if (*a > b->localid) return +1;
336     return 0;
337 }
338
339 static void c_write (char *buf, int len) {
340     if ((flags & FLAG_STDERR)) {
341         int i;
342         for (i = 0; i < len; i++)
343             if (buf[i] != '\r')
344                 fputc(buf[i], stderr);
345         return;
346     }
347     from_backend(1, buf, len);
348 }
349
350 static void c_write_str (char *buf) {
351     c_write(buf, strlen(buf));
352 }
353
354 /*
355  * Collect incoming data in the incoming packet buffer.
356  * Decipher and verify the packet when it is completely read.
357  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
358  * Update the *data and *datalen variables.
359  * Return the additional nr of bytes needed, or 0 when
360  * a complete packet is available.
361  */
362 static int ssh1_rdpkt(unsigned char **data, int *datalen)
363 {
364     struct rdpkt1_state_tag *st = &rdpkt1_state;
365
366     crBegin;
367
368 next_packet:
369
370     pktin.type = 0;
371     pktin.length = 0;
372
373     for (st->i = st->len = 0; st->i < 4; st->i++) {
374         while ((*datalen) == 0)
375             crReturn(4-st->i);
376         st->len = (st->len << 8) + **data;
377         (*data)++, (*datalen)--;
378     }
379
380 #ifdef FWHACK
381     if (st->len == 0x52656d6f) {        /* "Remo"te server has closed ... */
382         st->len = 0x300;                /* big enough to carry to end */
383     }
384 #endif
385
386     st->pad = 8 - (st->len % 8);
387     st->biglen = st->len + st->pad;
388     pktin.length = st->len - 5;
389
390     if (pktin.maxlen < st->biglen) {
391         pktin.maxlen = st->biglen;
392         pktin.data = (pktin.data == NULL ? smalloc(st->biglen+APIEXTRA) :
393                       srealloc(pktin.data, st->biglen+APIEXTRA));
394         if (!pktin.data)
395             fatalbox("Out of memory");
396     }
397
398     st->to_read = st->biglen;
399     st->p = pktin.data;
400     while (st->to_read > 0) {
401         st->chunk = st->to_read;
402         while ((*datalen) == 0)
403             crReturn(st->to_read);
404         if (st->chunk > (*datalen))
405             st->chunk = (*datalen);
406         memcpy(st->p, *data, st->chunk);
407         *data += st->chunk;
408         *datalen -= st->chunk;
409         st->p += st->chunk;
410         st->to_read -= st->chunk;
411     }
412
413     if (cipher)
414         cipher->decrypt(pktin.data, st->biglen);
415 #if 0
416     debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
417     for (st->i = 0; st->i < st->biglen; st->i++)
418         debug(("  %02x", (unsigned char)pktin.data[st->i]));
419     debug(("\r\n"));
420 #endif
421
422     st->realcrc = crc32(pktin.data, st->biglen-4);
423     st->gotcrc = GET_32BIT(pktin.data+st->biglen-4);
424     if (st->gotcrc != st->realcrc) {
425         bombout(("Incorrect CRC received on packet"));
426         crReturn(0);
427     }
428
429     pktin.body = pktin.data + st->pad + 1;
430
431     if (ssh1_compressing) {
432         unsigned char *decompblk;
433         int decomplen;
434 #if 0
435         int i;
436         debug(("Packet payload pre-decompression:\n"));
437         for (i = -1; i < pktin.length; i++)
438             debug(("  %02x", (unsigned char)pktin.body[i]));
439         debug(("\r\n"));
440 #endif
441         zlib_decompress_block(pktin.body-1, pktin.length+1,
442                               &decompblk, &decomplen);
443
444         if (pktin.maxlen < st->pad + decomplen) {
445             pktin.maxlen = st->pad + decomplen;
446             pktin.data = srealloc(pktin.data, pktin.maxlen+APIEXTRA);
447             pktin.body = pktin.data + st->pad + 1;
448             if (!pktin.data)
449                 fatalbox("Out of memory");
450         }
451
452         memcpy(pktin.body-1, decompblk, decomplen);
453         sfree(decompblk);
454         pktin.length = decomplen-1;
455 #if 0
456         debug(("Packet payload post-decompression:\n"));
457         for (i = -1; i < pktin.length; i++)
458             debug(("  %02x", (unsigned char)pktin.body[i]));
459         debug(("\r\n"));
460 #endif
461     }
462
463     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
464         pktin.type == SSH1_SMSG_STDERR_DATA ||
465         pktin.type == SSH1_MSG_DEBUG ||
466         pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
467         pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
468         long strlen = GET_32BIT(pktin.body);
469         if (strlen + 4 != pktin.length) {
470             bombout(("Received data packet with bogus string length"));
471             crReturn(0);
472         }
473     }
474
475     pktin.type = pktin.body[-1];
476
477     if (pktin.type == SSH1_MSG_DEBUG) {
478         /* log debug message */
479         char buf[80];
480         int strlen = GET_32BIT(pktin.body);
481         strcpy(buf, "Remote: ");
482         if (strlen > 70) strlen = 70;
483         memcpy(buf+8, pktin.body+4, strlen);
484         buf[8+strlen] = '\0';
485         logevent(buf);
486         goto next_packet;
487     } else if (pktin.type == SSH1_MSG_IGNORE) {
488         /* do nothing */
489         goto next_packet;
490     }
491
492     crFinish(0);
493 }
494
495 static int ssh2_rdpkt(unsigned char **data, int *datalen)
496 {
497     struct rdpkt2_state_tag *st = &rdpkt2_state;
498
499     crBegin;
500
501 next_packet:
502     pktin.type = 0;
503     pktin.length = 0;
504     if (sccipher)
505         st->cipherblk = sccipher->blksize;
506     else
507         st->cipherblk = 8;
508     if (st->cipherblk < 8)
509         st->cipherblk = 8;
510
511     if (pktin.maxlen < st->cipherblk) {
512         pktin.maxlen = st->cipherblk;
513         pktin.data = (pktin.data == NULL ? smalloc(st->cipherblk+APIEXTRA) :
514                       srealloc(pktin.data, st->cipherblk+APIEXTRA));
515         if (!pktin.data)
516             fatalbox("Out of memory");
517     }
518
519     /*
520      * Acquire and decrypt the first block of the packet. This will
521      * contain the length and padding details.
522      */
523      for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
524         while ((*datalen) == 0)
525             crReturn(st->cipherblk-st->i);
526         pktin.data[st->i] = *(*data)++;
527         (*datalen)--;
528     }
529 #ifdef FWHACK
530     if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
531         /* FIXME */
532     }
533 #endif
534     if (sccipher)
535         sccipher->decrypt(pktin.data, st->cipherblk);
536
537     /*
538      * Now get the length and padding figures.
539      */
540     st->len = GET_32BIT(pktin.data);
541     st->pad = pktin.data[4];
542
543     /*
544      * This enables us to deduce the payload length.
545      */
546     st->payload = st->len - st->pad - 1;
547
548     pktin.length = st->payload + 5;
549
550     /*
551      * So now we can work out the total packet length.
552      */
553     st->packetlen = st->len + 4;
554     st->maclen = scmac ? scmac->len : 0;
555
556     /*
557      * Adjust memory allocation if packet is too big.
558      */
559     if (pktin.maxlen < st->packetlen+st->maclen) {
560         pktin.maxlen = st->packetlen+st->maclen;
561         pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
562                       srealloc(pktin.data, pktin.maxlen+APIEXTRA));
563         if (!pktin.data)
564             fatalbox("Out of memory");
565     }
566
567     /*
568      * Read and decrypt the remainder of the packet.
569      */
570     for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) {
571         while ((*datalen) == 0)
572             crReturn(st->packetlen + st->maclen - st->i);
573         pktin.data[st->i] = *(*data)++;
574         (*datalen)--;
575     }
576     /* Decrypt everything _except_ the MAC. */
577     if (sccipher)
578         sccipher->decrypt(pktin.data + st->cipherblk,
579                           st->packetlen - st->cipherblk);
580
581 #if 0
582     debug(("Got packet len=%d pad=%d\r\n", st->len, st->pad));
583     for (st->i = 0; st->i < st->packetlen; st->i++)
584         debug(("  %02x", (unsigned char)pktin.data[st->i]));
585     debug(("\r\n"));
586 #endif
587
588     /*
589      * Check the MAC.
590      */
591     if (scmac && !scmac->verify(pktin.data, st->len+4, st->incoming_sequence)) {
592         bombout(("Incorrect MAC received on packet"));
593         crReturn(0);
594     }
595     st->incoming_sequence++;               /* whether or not we MACed */
596
597     /*
598      * Decompress packet payload.
599      */
600     {
601         unsigned char *newpayload;
602         int newlen;
603         if (sccomp && sccomp->decompress(pktin.data+5, pktin.length-5,
604                                          &newpayload, &newlen)) {
605             if (pktin.maxlen < newlen+5) {
606                 pktin.maxlen = newlen+5;
607                 pktin.data = (pktin.data == NULL ? smalloc(pktin.maxlen+APIEXTRA) :
608                               srealloc(pktin.data, pktin.maxlen+APIEXTRA));
609                 if (!pktin.data)
610                     fatalbox("Out of memory");
611             }
612             pktin.length = 5 + newlen;
613             memcpy(pktin.data+5, newpayload, newlen);
614 #if 0
615             debug(("Post-decompression payload:\r\n"));
616             for (st->i = 0; st->i < newlen; st->i++)
617                 debug(("  %02x", (unsigned char)pktin.data[5+st->i]));
618             debug(("\r\n"));
619 #endif
620
621             sfree(newpayload);
622         }
623     }
624
625     pktin.savedpos = 6;
626     pktin.type = pktin.data[5];
627
628     if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
629         goto next_packet;              /* FIXME: print DEBUG message */
630
631     crFinish(0);
632 }
633
634 static void ssh1_pktout_size(int len) {
635     int pad, biglen;
636
637     len += 5;                          /* type and CRC */
638     pad = 8 - (len%8);
639     biglen = len + pad;
640
641     pktout.length = len-5;
642     if (pktout.maxlen < biglen) {
643         pktout.maxlen = biglen;
644 #ifdef MSCRYPTOAPI
645         /* Allocate enough buffer space for extra block
646          * for MS CryptEncrypt() */
647         pktout.data = (pktout.data == NULL ? smalloc(biglen+12) :
648                        srealloc(pktout.data, biglen+12));
649 #else
650         pktout.data = (pktout.data == NULL ? smalloc(biglen+4) :
651                        srealloc(pktout.data, biglen+4));
652 #endif
653         if (!pktout.data)
654             fatalbox("Out of memory");
655     }
656     pktout.body = pktout.data+4+pad+1;
657 }
658
659 static void s_wrpkt_start(int type, int len) {
660     ssh1_pktout_size(len);
661     pktout.type = type;
662 }
663
664 static int s_wrpkt_prepare(void) {
665     int pad, len, biglen, i;
666     unsigned long crc;
667
668     pktout.body[-1] = pktout.type;
669
670 #if 0
671     debug(("Packet payload pre-compression:\n"));
672     for (i = -1; i < pktout.length; i++)
673         debug(("  %02x", (unsigned char)pktout.body[i]));
674     debug(("\r\n"));
675 #endif
676
677     if (ssh1_compressing) {
678         unsigned char *compblk;
679         int complen;
680         zlib_compress_block(pktout.body-1, pktout.length+1,
681                             &compblk, &complen);
682         ssh1_pktout_size(complen-1);
683         memcpy(pktout.body-1, compblk, complen);
684         sfree(compblk);
685 #if 0
686         debug(("Packet payload post-compression:\n"));
687         for (i = -1; i < pktout.length; i++)
688             debug(("  %02x", (unsigned char)pktout.body[i]));
689         debug(("\r\n"));
690 #endif
691     }
692
693     len = pktout.length + 5;           /* type and CRC */
694     pad = 8 - (len%8);
695     biglen = len + pad;
696
697     for (i=0; i<pad; i++)
698         pktout.data[i+4] = random_byte();
699     crc = crc32(pktout.data+4, biglen-4);
700     PUT_32BIT(pktout.data+biglen, crc);
701     PUT_32BIT(pktout.data, len);
702
703 #if 0
704     debug(("Sending packet len=%d\r\n", biglen+4));
705     for (i = 0; i < biglen+4; i++)
706         debug(("  %02x", (unsigned char)pktout.data[i]));
707     debug(("\r\n"));
708 #endif
709     if (cipher)
710         cipher->encrypt(pktout.data+4, biglen);
711
712     return biglen+4;
713 }
714
715 static void s_wrpkt(void) {
716     int len;
717     len = s_wrpkt_prepare();
718     sk_write(s, pktout.data, len);
719 }
720
721 static void s_wrpkt_defer(void) {
722     int len;
723     len = s_wrpkt_prepare();
724     if (deferred_len + len > deferred_size) {
725         deferred_size = deferred_len + len + 128;
726         deferred_send_data = srealloc(deferred_send_data, deferred_size);
727     }
728     memcpy(deferred_send_data+deferred_len, pktout.data, len);
729     deferred_len += len;
730 }
731
732 /*
733  * Construct a packet with the specified contents.
734  */
735 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
736 {
737     unsigned char *p, *argp, argchar;
738     unsigned long argint;
739     int pktlen, argtype, arglen;
740     Bignum bn;
741
742     pktlen = 0;
743     while ((argtype = va_arg(ap1, int)) != PKT_END) {
744         switch (argtype) {
745           case PKT_INT:
746             (void) va_arg(ap1, int);
747             pktlen += 4;
748             break;
749           case PKT_CHAR:
750             (void) va_arg(ap1, char);
751             pktlen++;
752             break;
753           case PKT_DATA:
754             (void) va_arg(ap1, unsigned char *);
755             arglen = va_arg(ap1, int);
756             pktlen += arglen;
757             break;
758           case PKT_STR:
759             argp = va_arg(ap1, unsigned char *);
760             arglen = strlen(argp);
761             pktlen += 4 + arglen;
762             break;
763           case PKT_BIGNUM:
764             bn = va_arg(ap1, Bignum);
765             pktlen += ssh1_bignum_length(bn);
766             break;
767           default:
768             assert(0);
769         }
770     }
771
772     s_wrpkt_start(pkttype, pktlen);
773     p = pktout.body;
774
775     while ((argtype = va_arg(ap2, int)) != PKT_END) {
776         switch (argtype) {
777           case PKT_INT:
778             argint = va_arg(ap2, int);
779             PUT_32BIT(p, argint);
780             p += 4;
781             break;
782           case PKT_CHAR:
783             argchar = va_arg(ap2, unsigned char);
784             *p = argchar;
785             p++;
786             break;
787           case PKT_DATA:
788             argp = va_arg(ap2, unsigned char *);
789             arglen = va_arg(ap2, int);
790             memcpy(p, argp, arglen);
791             p += arglen;
792             break;
793           case PKT_STR:
794             argp = va_arg(ap2, unsigned char *);
795             arglen = strlen(argp);
796             PUT_32BIT(p, arglen);
797             memcpy(p + 4, argp, arglen);
798             p += 4 + arglen;
799             break;
800           case PKT_BIGNUM:
801             bn = va_arg(ap2, Bignum);
802             p += ssh1_write_bignum(p, bn);
803             break;
804         }
805     }
806 }
807
808 static void send_packet(int pkttype, ...) {
809     va_list ap1, ap2;
810     va_start(ap1, pkttype);
811     va_start(ap2, pkttype);
812     construct_packet(pkttype, ap1, ap2);
813     s_wrpkt();
814 }
815
816 static void defer_packet(int pkttype, ...) {
817     va_list ap1, ap2;
818     va_start(ap1, pkttype);
819     va_start(ap2, pkttype);
820     construct_packet(pkttype, ap1, ap2);
821     s_wrpkt_defer();
822 }
823
824 static int ssh_versioncmp(char *a, char *b) {
825     char *ae, *be;
826     unsigned long av, bv;
827
828     av = strtoul(a, &ae, 10);
829     bv = strtoul(b, &be, 10);
830     if (av != bv) return (av < bv ? -1 : +1);
831     if (*ae == '.') ae++;
832     if (*be == '.') be++;
833     av = strtoul(ae, &ae, 10);
834     bv = strtoul(be, &be, 10);
835     if (av != bv) return (av < bv ? -1 : +1);
836     return 0;
837 }
838
839
840 /*
841  * Utility routines for putting an SSH-protocol `string' and
842  * `uint32' into a SHA state.
843  */
844 #include <stdio.h>
845 static void sha_string(SHA_State *s, void *str, int len) {
846     unsigned char lenblk[4];
847     PUT_32BIT(lenblk, len);
848     SHA_Bytes(s, lenblk, 4);
849     SHA_Bytes(s, str, len);
850 }
851
852 static void sha_uint32(SHA_State *s, unsigned i) {
853     unsigned char intblk[4];
854     PUT_32BIT(intblk, i);
855     SHA_Bytes(s, intblk, 4);
856 }
857
858 /*
859  * SSH2 packet construction functions.
860  */
861 static void ssh2_pkt_ensure(int length) {
862     if (pktout.maxlen < length) {
863         pktout.maxlen = length + 256;
864         pktout.data = (pktout.data == NULL ? smalloc(pktout.maxlen+APIEXTRA) :
865                        srealloc(pktout.data, pktout.maxlen+APIEXTRA));
866         if (!pktout.data)
867             fatalbox("Out of memory");
868     }
869 }
870 static void ssh2_pkt_adddata(void *data, int len) {
871     pktout.length += len;
872     ssh2_pkt_ensure(pktout.length);
873     memcpy(pktout.data+pktout.length-len, data, len);
874 }
875 static void ssh2_pkt_addbyte(unsigned char byte) {
876     ssh2_pkt_adddata(&byte, 1);
877 }
878 static void ssh2_pkt_init(int pkt_type) {
879     pktout.length = 5;
880     ssh2_pkt_addbyte((unsigned char)pkt_type);
881 }
882 static void ssh2_pkt_addbool(unsigned char value) {
883     ssh2_pkt_adddata(&value, 1);
884 }
885 static void ssh2_pkt_adduint32(unsigned long value) {
886     unsigned char x[4];
887     PUT_32BIT(x, value);
888     ssh2_pkt_adddata(x, 4);
889 }
890 static void ssh2_pkt_addstring_start(void) {
891     ssh2_pkt_adduint32(0);
892     pktout.savedpos = pktout.length;
893 }
894 static void ssh2_pkt_addstring_str(char *data) {
895     ssh2_pkt_adddata(data, strlen(data));
896     PUT_32BIT(pktout.data + pktout.savedpos - 4,
897               pktout.length - pktout.savedpos);
898 }
899 static void ssh2_pkt_addstring_data(char *data, int len) {
900     ssh2_pkt_adddata(data, len);
901     PUT_32BIT(pktout.data + pktout.savedpos - 4,
902               pktout.length - pktout.savedpos);
903 }
904 static void ssh2_pkt_addstring(char *data) {
905     ssh2_pkt_addstring_start();
906     ssh2_pkt_addstring_str(data);
907 }
908 static char *ssh2_mpint_fmt(Bignum b, int *len) {
909     unsigned char *p;
910     int i, n = (ssh1_bignum_bitcount(b)+7)/8;
911     p = smalloc(n + 1);
912     if (!p)
913         fatalbox("out of memory");
914     p[0] = 0;
915     for (i = 1; i <= n; i++)
916         p[i] = bignum_byte(b, n-i);
917     i = 0;
918     while (i <= n && p[i] == 0 && (p[i+1] & 0x80) == 0)
919         i++;
920     memmove(p, p+i, n+1-i);
921     *len = n+1-i;
922     return p;
923 }
924 static void ssh2_pkt_addmp(Bignum b) {
925     unsigned char *p;
926     int len;
927     p = ssh2_mpint_fmt(b, &len);
928     ssh2_pkt_addstring_start();
929     ssh2_pkt_addstring_data(p, len);
930     sfree(p);
931 }
932
933 /*
934  * Construct an SSH2 final-form packet: compress it, encrypt it,
935  * put the MAC on it. Final packet, ready to be sent, is stored in
936  * pktout.data. Total length is returned.
937  */
938 static int ssh2_pkt_construct(void) {
939     int cipherblk, maclen, padding, i;
940     static unsigned long outgoing_sequence = 0;
941
942     /*
943      * Compress packet payload.
944      */
945 #if 0
946     debug(("Pre-compression payload:\r\n"));
947     for (i = 5; i < pktout.length; i++)
948         debug(("  %02x", (unsigned char)pktout.data[i]));
949     debug(("\r\n"));
950 #endif
951     {
952         unsigned char *newpayload;
953         int newlen;
954         if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
955                                        &newpayload, &newlen)) {
956             pktout.length = 5;
957             ssh2_pkt_adddata(newpayload, newlen);
958             sfree(newpayload);
959         }
960     }
961
962     /*
963      * Add padding. At least four bytes, and must also bring total
964      * length (minus MAC) up to a multiple of the block size.
965      */
966     cipherblk = cscipher ? cscipher->blksize : 8;   /* block size */
967     cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
968     padding = 4;
969     padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
970     maclen = csmac ? csmac->len : 0;
971     ssh2_pkt_ensure(pktout.length + padding + maclen);
972     pktout.data[4] = padding;
973     for (i = 0; i < padding; i++)
974         pktout.data[pktout.length + i] = random_byte();
975     PUT_32BIT(pktout.data, pktout.length + padding - 4);
976     if (csmac)
977         csmac->generate(pktout.data, pktout.length + padding,
978                         outgoing_sequence);
979     outgoing_sequence++;               /* whether or not we MACed */
980
981 #if 0
982     debug(("Sending packet len=%d\r\n", pktout.length+padding));
983     for (i = 0; i < pktout.length+padding; i++)
984         debug(("  %02x", (unsigned char)pktout.data[i]));
985     debug(("\r\n"));
986 #endif
987
988     if (cscipher)
989         cscipher->encrypt(pktout.data, pktout.length + padding);
990
991     /* Ready-to-send packet starts at pktout.data. We return length. */
992     return pktout.length + padding + maclen;
993 }
994
995 /*
996  * Construct and send an SSH2 packet immediately.
997  */
998 static void ssh2_pkt_send(void) {
999     int len = ssh2_pkt_construct();
1000     sk_write(s, pktout.data, len);
1001 }
1002
1003 /*
1004  * Construct an SSH2 packet and add it to a deferred data block.
1005  * Useful for sending multiple packets in a single sk_write() call,
1006  * to prevent a traffic-analysing listener from being able to work
1007  * out the length of any particular packet (such as the password
1008  * packet).
1009  * 
1010  * Note that because SSH2 sequence-numbers its packets, this can
1011  * NOT be used as an m4-style `defer' allowing packets to be
1012  * constructed in one order and sent in another.
1013  */
1014 static void ssh2_pkt_defer(void) {
1015     int len = ssh2_pkt_construct();
1016     if (deferred_len + len > deferred_size) {
1017         deferred_size = deferred_len + len + 128;
1018         deferred_send_data = srealloc(deferred_send_data, deferred_size);
1019     }
1020     memcpy(deferred_send_data+deferred_len, pktout.data, len);
1021     deferred_len += len;
1022 }
1023
1024 /*
1025  * Send the whole deferred data block constructed by
1026  * ssh2_pkt_defer() or SSH1's defer_packet().
1027  */
1028 static void ssh_pkt_defersend(void) {
1029     sk_write(s, deferred_send_data, deferred_len);
1030     deferred_len = deferred_size = 0;
1031     sfree(deferred_send_data);
1032     deferred_send_data = NULL;
1033 }
1034
1035 #if 0
1036 void bndebug(char *string, Bignum b) {
1037     unsigned char *p;
1038     int i, len;
1039     p = ssh2_mpint_fmt(b, &len);
1040     debug(("%s", string));
1041     for (i = 0; i < len; i++)
1042         debug((" %02x", p[i]));
1043     debug(("\r\n"));
1044     sfree(p);
1045 }
1046 #endif
1047
1048 static void sha_mpint(SHA_State *s, Bignum b) {
1049     unsigned char *p;
1050     int len;
1051     p = ssh2_mpint_fmt(b, &len);
1052     sha_string(s, p, len);
1053     sfree(p);
1054 }
1055
1056 /*
1057  * SSH2 packet decode functions.
1058  */
1059 static unsigned long ssh2_pkt_getuint32(void) {
1060     unsigned long value;
1061     if (pktin.length - pktin.savedpos < 4)
1062         return 0;                      /* arrgh, no way to decline (FIXME?) */
1063     value = GET_32BIT(pktin.data+pktin.savedpos);
1064     pktin.savedpos += 4;
1065     return value;
1066 }
1067 static int ssh2_pkt_getbool(void) {
1068     unsigned long value;
1069     if (pktin.length - pktin.savedpos < 1)
1070         return 0;                      /* arrgh, no way to decline (FIXME?) */
1071     value = pktin.data[pktin.savedpos] != 0;
1072     pktin.savedpos++;
1073     return value;
1074 }
1075 static void ssh2_pkt_getstring(char **p, int *length) {
1076     *p = NULL;
1077     if (pktin.length - pktin.savedpos < 4)
1078         return;
1079     *length = GET_32BIT(pktin.data+pktin.savedpos);
1080     pktin.savedpos += 4;
1081     if (pktin.length - pktin.savedpos < *length)
1082         return;
1083     *p = pktin.data+pktin.savedpos;
1084     pktin.savedpos += *length;
1085 }
1086 static Bignum ssh2_pkt_getmp(void) {
1087     char *p;
1088     int length;
1089     Bignum b;
1090
1091     ssh2_pkt_getstring(&p, &length);
1092     if (!p)
1093         return NULL;
1094     if (p[0] & 0x80) {
1095         bombout(("internal error: Can't handle negative mpints"));
1096         return NULL;
1097     }
1098     b = bignum_from_bytes(p, length);
1099     return b;
1100 }
1101
1102 /*
1103  * Examine the remote side's version string and compare it against
1104  * a list of known buggy implementations.
1105  */
1106 static void ssh_detect_bugs(char *vstring) {
1107     char *imp;                         /* pointer to implementation part */
1108     imp = vstring;
1109     imp += strcspn(imp, "-");
1110     imp += strcspn(imp, "-");
1111
1112     ssh_remote_bugs = 0;
1113
1114     if (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1115         !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1116         !strcmp(imp, "1.2.22")) {
1117         /*
1118          * These versions don't support SSH1_MSG_IGNORE, so we have
1119          * to use a different defence against password length
1120          * sniffing.
1121          */
1122         ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1123         logevent("We believe remote version has SSH1 ignore bug");
1124     }
1125
1126     if (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1127         !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1128         !strncmp(imp, "2.1 ", 4)) {
1129         /*
1130          * These versions have the HMAC bug.
1131          */
1132         ssh_remote_bugs |= BUG_SSH2_HMAC;
1133         logevent("We believe remote version has SSH2 HMAC bug");
1134     }
1135 }
1136
1137 static int do_ssh_init(unsigned char c) {
1138     static char *vsp;
1139     static char version[10];
1140     static char vstring[80];
1141     static char vlog[sizeof(vstring)+20];
1142     static int i;
1143
1144     crBegin;
1145
1146     /* Search for the string "SSH-" in the input. */
1147     i = 0;
1148     while (1) {
1149         static const int transS[] = { 1, 2, 2, 1 };
1150         static const int transH[] = { 0, 0, 3, 0 };
1151         static const int transminus[] = { 0, 0, 0, -1 };
1152         if (c == 'S') i = transS[i];
1153         else if (c == 'H') i = transH[i];
1154         else if (c == '-') i = transminus[i];
1155         else i = 0;
1156         if (i < 0)
1157             break;
1158         crReturn(1);                   /* get another character */
1159     }
1160
1161     strcpy(vstring, "SSH-");
1162     vsp = vstring+4;
1163     i = 0;
1164     while (1) {
1165         crReturn(1);                   /* get another char */
1166         if (vsp < vstring+sizeof(vstring)-1)
1167             *vsp++ = c;
1168         if (i >= 0) {
1169             if (c == '-') {
1170                 version[i] = '\0';
1171                 i = -1;
1172             } else if (i < sizeof(version)-1)
1173                 version[i++] = c;
1174         }
1175         else if (c == '\n')
1176             break;
1177     }
1178
1179     ssh_agentfwd_enabled = FALSE;
1180     rdpkt2_state.incoming_sequence = 0;
1181
1182     *vsp = 0;
1183     sprintf(vlog, "Server version: %s", vstring);
1184     ssh_detect_bugs(vstring);
1185     vlog[strcspn(vlog, "\r\n")] = '\0';
1186     logevent(vlog);
1187
1188     /*
1189      * Server version "1.99" means we can choose whether we use v1
1190      * or v2 protocol. Choice is based on cfg.sshprot.
1191      */
1192     if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1193         /*
1194          * This is a v2 server. Begin v2 protocol.
1195          */
1196         char *verstring = "SSH-2.0-PuTTY";
1197         SHA_Init(&exhashbase);
1198         /*
1199          * Hash our version string and their version string.
1200          */
1201         sha_string(&exhashbase, verstring, strlen(verstring));
1202         sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1203         sprintf(vstring, "%s\n", verstring);
1204         sprintf(vlog, "We claim version: %s", verstring);
1205         logevent(vlog);
1206         logevent("Using SSH protocol version 2");
1207         sk_write(s, vstring, strlen(vstring));
1208         ssh_protocol = ssh2_protocol;
1209         ssh_version = 2;
1210         s_rdpkt = ssh2_rdpkt;
1211     } else {
1212         /*
1213          * This is a v1 server. Begin v1 protocol.
1214          */
1215         sprintf(vstring, "SSH-%s-PuTTY\n",
1216                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1217         sprintf(vlog, "We claim version: %s", vstring);
1218         vlog[strcspn(vlog, "\r\n")] = '\0';
1219         logevent(vlog);
1220         logevent("Using SSH protocol version 1");
1221         sk_write(s, vstring, strlen(vstring));
1222         ssh_protocol = ssh1_protocol;
1223         ssh_version = 1;
1224         s_rdpkt = ssh1_rdpkt;
1225     }
1226     ssh_state = SSH_STATE_BEFORE_SIZE;
1227
1228     crFinish(0);
1229 }
1230
1231 static void ssh_gotdata(unsigned char *data, int datalen)
1232 {
1233     crBegin;
1234
1235     /*
1236      * To begin with, feed the characters one by one to the
1237      * protocol initialisation / selection function do_ssh_init().
1238      * When that returns 0, we're done with the initial greeting
1239      * exchange and can move on to packet discipline.
1240      */
1241     while (1) {
1242         int ret;
1243         if (datalen == 0)
1244             crReturnV;                 /* more data please */
1245         ret = do_ssh_init(*data);
1246         data++; datalen--;
1247         if (ret == 0)
1248             break;
1249     }
1250
1251     /*
1252      * We emerge from that loop when the initial negotiation is
1253      * over and we have selected an s_rdpkt function. Now pass
1254      * everything to s_rdpkt, and then pass the resulting packets
1255      * to the proper protocol handler.
1256      */
1257     if (datalen == 0)
1258         crReturnV;
1259     while (1) {
1260         while (datalen > 0) {
1261             if ( s_rdpkt(&data, &datalen) == 0 ) {
1262                 ssh_protocol(NULL, 0, 1);
1263                 if (ssh_state == SSH_STATE_CLOSED) {
1264                     return;
1265                 }
1266             }
1267         }
1268         crReturnV;
1269     }
1270     crFinishV;
1271 }
1272
1273 static int ssh_closing (Plug plug, char *error_msg, int error_code, int calling_back) {
1274     ssh_state = SSH_STATE_CLOSED;
1275     sk_close(s);
1276     s = NULL;
1277     if (error_msg) {
1278         /* A socket error has occurred. */
1279         connection_fatal (error_msg);
1280     } else {
1281         /* Otherwise, the remote side closed the connection normally. */
1282     }
1283     return 0;
1284 }
1285
1286 static int ssh_receive(Plug plug, int urgent, char *data, int len) {
1287     ssh_gotdata (data, len);
1288     if (ssh_state == SSH_STATE_CLOSED) {
1289         if (s) {
1290             sk_close(s);
1291             s = NULL;
1292         }
1293         return 0;
1294     }
1295     return 1;
1296 }
1297
1298 /*
1299  * Connect to specified host and port.
1300  * Returns an error message, or NULL on success.
1301  * Also places the canonical host name into `realhost'.
1302  */
1303 static char *connect_to_host(char *host, int port, char **realhost)
1304 {
1305     static struct plug_function_table fn_table = {
1306         ssh_closing,
1307         ssh_receive
1308     }, *fn_table_ptr = &fn_table;
1309
1310     SockAddr addr;
1311     char *err;
1312 #ifdef FWHACK
1313     char *FWhost;
1314     int FWport;
1315 #endif
1316
1317     savedhost = smalloc(1+strlen(host));
1318     if (!savedhost)
1319         fatalbox("Out of memory");
1320     strcpy(savedhost, host);
1321
1322     if (port < 0)
1323         port = 22;                     /* default ssh port */
1324     savedport = port;
1325
1326 #ifdef FWHACK
1327     FWhost = host;
1328     FWport = port;
1329     host = FWSTR;
1330     port = 23;
1331 #endif
1332
1333     /*
1334      * Try to find host.
1335      */
1336     addr = sk_namelookup(host, realhost);
1337     if ( (err = sk_addr_error(addr)) )
1338         return err;
1339
1340 #ifdef FWHACK
1341     *realhost = FWhost;
1342 #endif
1343
1344     /*
1345      * Open socket.
1346      */
1347     s = sk_new(addr, port, 0, 1, &fn_table_ptr);
1348     if ( (err = sk_socket_error(s)) )
1349         return err;
1350
1351 #ifdef FWHACK
1352     sk_write(s, "connect ", 8);
1353     sk_write(s, FWhost, strlen(FWhost));
1354     {
1355         char buf[20];
1356         sprintf(buf, " %d\n", FWport);
1357         sk_write(s, buf, strlen(buf));
1358     }
1359 #endif
1360
1361     return NULL;
1362 }
1363
1364 /*
1365  * Handle the key exchange and user authentication phases.
1366  */
1367 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1368 {
1369     int i, j, len;
1370     unsigned char *rsabuf, *keystr1, *keystr2;
1371     unsigned char cookie[8];
1372     struct RSAKey servkey, hostkey;
1373     struct MD5Context md5c;
1374     static unsigned long supported_ciphers_mask, supported_auths_mask;
1375     static int tried_publickey;
1376     static unsigned char session_id[16];
1377     int cipher_type;
1378     static char username[100];
1379
1380     crBegin;
1381
1382     if (!ispkt) crWaitUntil(ispkt);
1383
1384     if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1385         bombout(("Public key packet not received"));
1386         crReturn(0);
1387     }
1388
1389     logevent("Received public keys");
1390
1391     memcpy(cookie, pktin.body, 8);
1392
1393     i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1394     j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1395
1396     /*
1397      * Log the host key fingerprint.
1398      */
1399     {
1400         char logmsg[80];
1401         logevent("Host key fingerprint is:");
1402         strcpy(logmsg, "      ");
1403         hostkey.comment = NULL;
1404         rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1405                         &hostkey);
1406         logevent(logmsg);
1407     }
1408
1409     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1410     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1411
1412     MD5Init(&md5c);
1413     MD5Update(&md5c, keystr2, hostkey.bytes);
1414     MD5Update(&md5c, keystr1, servkey.bytes);
1415     MD5Update(&md5c, pktin.body, 8);
1416     MD5Final(session_id, &md5c);
1417
1418     for (i=0; i<32; i++)
1419         session_key[i] = random_byte();
1420
1421     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1422
1423     rsabuf = smalloc(len);
1424     if (!rsabuf)
1425         fatalbox("Out of memory");
1426
1427     /*
1428      * Verify the host key.
1429      */
1430     {
1431         /*
1432          * First format the key into a string.
1433          */
1434         int len = rsastr_len(&hostkey);
1435         char fingerprint[100];
1436         char *keystr = smalloc(len);
1437         if (!keystr)
1438             fatalbox("Out of memory");
1439         rsastr_fmt(keystr, &hostkey);
1440         rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1441         verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1442         sfree(keystr);
1443     }
1444
1445     for (i=0; i<32; i++) {
1446         rsabuf[i] = session_key[i];
1447         if (i < 16)
1448             rsabuf[i] ^= session_id[i];
1449     }
1450
1451     if (hostkey.bytes > servkey.bytes) {
1452         rsaencrypt(rsabuf, 32, &servkey);
1453         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1454     } else {
1455         rsaencrypt(rsabuf, 32, &hostkey);
1456         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1457     }
1458
1459     logevent("Encrypted session key");
1460
1461     switch (cfg.cipher) {
1462       case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH; break;
1463       case CIPHER_DES:      cipher_type = SSH_CIPHER_DES;      break;
1464       case CIPHER_3DES:     cipher_type = SSH_CIPHER_3DES;     break;
1465       case CIPHER_AES:
1466         c_write_str("AES not supported in SSH1, falling back to 3DES\r\n");
1467         cipher_type = SSH_CIPHER_3DES;
1468         break;
1469     }
1470     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1471         c_write_str("Selected cipher not supported, falling back to 3DES\r\n");
1472         cipher_type = SSH_CIPHER_3DES;
1473     }
1474     switch (cipher_type) {
1475       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1476       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1477       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1478     }
1479
1480     send_packet(SSH1_CMSG_SESSION_KEY,
1481                 PKT_CHAR, cipher_type,
1482                 PKT_DATA, cookie, 8,
1483                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1484                 PKT_DATA, rsabuf, len,
1485                 PKT_INT, 0,
1486                 PKT_END);
1487
1488     logevent("Trying to enable encryption...");
1489
1490     sfree(rsabuf);
1491
1492     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1493              cipher_type == SSH_CIPHER_DES ? &ssh_des :
1494              &ssh_3des;
1495     cipher->sesskey(session_key);
1496
1497     crWaitUntil(ispkt);
1498
1499     if (pktin.type != SSH1_SMSG_SUCCESS) {
1500         bombout(("Encryption not successfully enabled"));
1501         crReturn(0);
1502     }
1503
1504     logevent("Successfully started encryption");
1505
1506     fflush(stdout);
1507     {
1508         static int pos = 0;
1509         static char c;
1510         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1511             if (ssh_get_line) {
1512                 if (!ssh_get_line("login as: ",
1513                                   username, sizeof(username), FALSE)) {
1514                     /*
1515                      * get_line failed to get a username.
1516                      * Terminate.
1517                      */
1518                     logevent("No username provided. Abandoning session.");
1519                     ssh_state = SSH_STATE_CLOSED;
1520                     crReturn(1);
1521                 }
1522             } else {
1523                 c_write_str("login as: ");
1524                 ssh_send_ok = 1;
1525                 while (pos >= 0) {
1526                     crWaitUntil(!ispkt);
1527                     while (inlen--) switch (c = *in++) {
1528                       case 10: case 13:
1529                         username[pos] = 0;
1530                         pos = -1;
1531                         break;
1532                       case 8: case 127:
1533                         if (pos > 0) {
1534                             c_write_str("\b \b");
1535                             pos--;
1536                         }
1537                         break;
1538                       case 21: case 27:
1539                         while (pos > 0) {
1540                             c_write_str("\b \b");
1541                             pos--;
1542                         }
1543                         break;
1544                       case 3: case 4:
1545                         random_save_seed();
1546                         exit(0);
1547                         break;
1548                       default:
1549                         if (((c >= ' ' && c <= '~') ||
1550                              ((unsigned char)c >= 160)) && pos < 40) {
1551                             username[pos++] = c;
1552                             c_write(&c, 1);
1553                         }
1554                         break;
1555                     }
1556                 }
1557                 c_write_str("\r\n");
1558                 username[strcspn(username, "\n\r")] = '\0';
1559             }
1560         } else {
1561             strncpy(username, cfg.username, 99);
1562             username[99] = '\0';
1563         }
1564
1565         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1566         {
1567             char userlog[22+sizeof(username)];
1568             sprintf(userlog, "Sent username \"%s\"", username);
1569             logevent(userlog);
1570             if (flags & FLAG_INTERACTIVE &&
1571                 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1572                 strcat(userlog, "\r\n");
1573                 c_write_str(userlog);
1574             }
1575         }
1576     }
1577
1578     crWaitUntil(ispkt);
1579
1580     tried_publickey = 0;
1581
1582     while (pktin.type == SSH1_SMSG_FAILURE) {
1583         static char password[100];
1584         static char prompt[200];
1585         static int pos;
1586         static char c;
1587         static int pwpkt_type;
1588         /*
1589          * Show password prompt, having first obtained it via a TIS
1590          * or CryptoCard exchange if we're doing TIS or CryptoCard
1591          * authentication.
1592          */
1593         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1594         if (agent_exists()) {
1595             /*
1596              * Attempt RSA authentication using Pageant.
1597              */
1598             static unsigned char request[5], *response, *p;
1599             static int responselen;
1600             static int i, nkeys;
1601             static int authed = FALSE;
1602             void *r;
1603
1604             logevent("Pageant is running. Requesting keys.");
1605
1606             /* Request the keys held by the agent. */
1607             PUT_32BIT(request, 1);
1608             request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
1609             agent_query(request, 5, &r, &responselen);
1610             response = (unsigned char *)r;
1611             if (response && responselen >= 5 &&
1612                 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
1613                 p = response + 5;
1614                 nkeys = GET_32BIT(p); p += 4;
1615                 { char buf[64]; sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
1616                     logevent(buf); }
1617                 for (i = 0; i < nkeys; i++) {
1618                     static struct RSAKey key;
1619                     static Bignum challenge;
1620                     static char *commentp;
1621                     static int commentlen;
1622
1623                     { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1624                         logevent(buf); }
1625                     p += 4;
1626                     p += ssh1_read_bignum(p, &key.exponent);
1627                     p += ssh1_read_bignum(p, &key.modulus);
1628                     commentlen = GET_32BIT(p); p += 4;
1629                     commentp = p; p += commentlen;
1630                     send_packet(SSH1_CMSG_AUTH_RSA,
1631                                 PKT_BIGNUM, key.modulus, PKT_END);
1632                     crWaitUntil(ispkt);
1633                     if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1634                         logevent("Key refused");
1635                         continue;
1636                     }
1637                     logevent("Received RSA challenge");
1638                     ssh1_read_bignum(pktin.body, &challenge);
1639                     {
1640                         char *agentreq, *q, *ret;
1641                         int len, retlen;
1642                         len = 1 + 4;   /* message type, bit count */
1643                         len += ssh1_bignum_length(key.exponent);
1644                         len += ssh1_bignum_length(key.modulus);
1645                         len += ssh1_bignum_length(challenge);
1646                         len += 16;     /* session id */
1647                         len += 4;      /* response format */
1648                         agentreq = smalloc(4 + len);
1649                         PUT_32BIT(agentreq, len);
1650                         q = agentreq + 4;
1651                         *q++ = SSH1_AGENTC_RSA_CHALLENGE;
1652                         PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1653                         q += 4;
1654                         q += ssh1_write_bignum(q, key.exponent);
1655                         q += ssh1_write_bignum(q, key.modulus);
1656                         q += ssh1_write_bignum(q, challenge);
1657                         memcpy(q, session_id, 16); q += 16;
1658                         PUT_32BIT(q, 1);   /* response format */
1659                         agent_query(agentreq, len+4, &ret, &retlen);
1660                         sfree(agentreq);
1661                         if (ret) {
1662                             if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
1663                                 logevent("Sending Pageant's response");
1664                                 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1665                                             PKT_DATA, ret+5, 16, PKT_END);
1666                                 sfree(ret);
1667                                 crWaitUntil(ispkt);
1668                                 if (pktin.type == SSH1_SMSG_SUCCESS) {
1669                                     logevent("Pageant's response accepted");
1670                                     if (flags & FLAG_VERBOSE) {
1671                                         c_write_str("Authenticated using RSA key \"");
1672                                         c_write(commentp, commentlen);
1673                                         c_write_str("\" from agent\r\n");
1674                                     }
1675                                     authed = TRUE;
1676                                 } else
1677                                     logevent("Pageant's response not accepted");
1678                             } else {
1679                                 logevent("Pageant failed to answer challenge");
1680                                 sfree(ret);
1681                             }
1682                         } else {
1683                             logevent("No reply received from Pageant");
1684                         }
1685                     }
1686                     freebn(key.exponent);
1687                     freebn(key.modulus);
1688                     freebn(challenge);
1689                     if (authed)
1690                         break;
1691                 }
1692             }
1693             if (authed)
1694                 break;
1695         }
1696         if (*cfg.keyfile && !tried_publickey)
1697             pwpkt_type = SSH1_CMSG_AUTH_RSA;
1698
1699         if (pktin.type == SSH1_SMSG_FAILURE &&
1700             cfg.try_tis_auth &&
1701             (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1702             pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1703             logevent("Requested TIS authentication");
1704             send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1705             crWaitUntil(ispkt);
1706             if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1707                 logevent("TIS authentication declined");
1708                 if (flags & FLAG_INTERACTIVE)
1709                     c_write_str("TIS authentication refused.\r\n");
1710             } else {
1711                 int challengelen = ((pktin.body[0] << 24) |
1712                                     (pktin.body[1] << 16) |
1713                                     (pktin.body[2] << 8) |
1714                                     (pktin.body[3]));
1715                 logevent("Received TIS challenge");
1716                 if (challengelen > sizeof(prompt)-1)
1717                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1718                 memcpy(prompt, pktin.body+4, challengelen);
1719                 prompt[challengelen] = '\0';
1720             }
1721         }
1722         if (pktin.type == SSH1_SMSG_FAILURE &&
1723             cfg.try_tis_auth &&
1724             (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1725             pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1726             logevent("Requested CryptoCard authentication");
1727             send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1728             crWaitUntil(ispkt);
1729             if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1730                 logevent("CryptoCard authentication declined");
1731                 c_write_str("CryptoCard authentication refused.\r\n");
1732             } else {
1733                 int challengelen = ((pktin.body[0] << 24) |
1734                                     (pktin.body[1] << 16) |
1735                                     (pktin.body[2] << 8) |
1736                                     (pktin.body[3]));
1737                 logevent("Received CryptoCard challenge");
1738                 if (challengelen > sizeof(prompt)-1)
1739                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1740                 memcpy(prompt, pktin.body+4, challengelen);
1741                 strncpy(prompt + challengelen, "\r\nResponse : ",
1742                         sizeof(prompt)-challengelen);
1743                 prompt[sizeof(prompt)-1] = '\0';
1744             }
1745         }
1746         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1747             sprintf(prompt, "%.90s@%.90s's password: ",
1748                     username, savedhost);
1749         }
1750         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1751             char *comment = NULL;
1752             if (flags & FLAG_VERBOSE)
1753                 c_write_str("Trying public key authentication.\r\n");
1754             if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1755                 if (flags & FLAG_VERBOSE)
1756                     c_write_str("No passphrase required.\r\n");
1757                 goto tryauth;
1758             }
1759             sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1760             sfree(comment);
1761         }
1762
1763         if (ssh_get_line) {
1764             if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
1765                 /*
1766                  * get_line failed to get a password (for example
1767                  * because one was supplied on the command line
1768                  * which has already failed to work). Terminate.
1769                  */
1770                 logevent("No more passwords to try");
1771                 ssh_state = SSH_STATE_CLOSED;
1772                 crReturn(1);
1773             }
1774         } else {
1775             c_write_str(prompt);
1776             pos = 0;
1777             ssh_send_ok = 1;
1778             while (pos >= 0) {
1779                 crWaitUntil(!ispkt);
1780                 while (inlen--) switch (c = *in++) {
1781                   case 10: case 13:
1782                     password[pos] = 0;
1783                     pos = -1;
1784                     break;
1785                   case 8: case 127:
1786                     if (pos > 0)
1787                         pos--;
1788                     break;
1789                   case 21: case 27:
1790                     pos = 0;
1791                     break;
1792                   case 3: case 4:
1793                     random_save_seed();
1794                     exit(0);
1795                     break;
1796                   default:
1797                     if (((c >= ' ' && c <= '~') ||
1798                          ((unsigned char)c >= 160)) && pos < sizeof(password))
1799                         password[pos++] = c;
1800                     break;
1801                 }
1802             }
1803             c_write_str("\r\n");
1804         }
1805
1806         tryauth:
1807         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1808             /*
1809              * Try public key authentication with the specified
1810              * key file.
1811              */
1812             static struct RSAKey pubkey;
1813             static Bignum challenge, response;
1814             static int i;
1815             static unsigned char buffer[32];
1816
1817             tried_publickey = 1;
1818             i = loadrsakey(cfg.keyfile, &pubkey, password);
1819             if (i == 0) {
1820                 c_write_str("Couldn't load public key from ");
1821                 c_write_str(cfg.keyfile);
1822                 c_write_str(".\r\n");
1823                 continue;              /* go and try password */
1824             }
1825             if (i == -1) {
1826                 c_write_str("Wrong passphrase.\r\n");
1827                 tried_publickey = 0;
1828                 continue;              /* try again */
1829             }
1830
1831             /*
1832              * Send a public key attempt.
1833              */
1834             send_packet(SSH1_CMSG_AUTH_RSA,
1835                         PKT_BIGNUM, pubkey.modulus, PKT_END);
1836
1837             crWaitUntil(ispkt);
1838             if (pktin.type == SSH1_SMSG_FAILURE) {
1839                 c_write_str("Server refused our public key.\r\n");
1840                 continue;              /* go and try password */
1841             }
1842             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1843                 bombout(("Bizarre response to offer of public key"));
1844                 crReturn(0);
1845             }
1846             ssh1_read_bignum(pktin.body, &challenge);
1847             response = rsadecrypt(challenge, &pubkey);
1848             freebn(pubkey.private_exponent);   /* burn the evidence */
1849
1850             for (i = 0; i < 32; i++) {
1851                 buffer[i] = bignum_byte(response, 31-i);
1852             }
1853
1854             MD5Init(&md5c);
1855             MD5Update(&md5c, buffer, 32);
1856             MD5Update(&md5c, session_id, 16);
1857             MD5Final(buffer, &md5c);
1858
1859             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1860                         PKT_DATA, buffer, 16, PKT_END);
1861
1862             crWaitUntil(ispkt);
1863             if (pktin.type == SSH1_SMSG_FAILURE) {
1864                 if (flags & FLAG_VERBOSE)
1865                     c_write_str("Failed to authenticate with our public key.\r\n");
1866                 continue;              /* go and try password */
1867             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1868                 bombout(("Bizarre response to RSA authentication response"));
1869                 crReturn(0);
1870             }
1871
1872             break;                     /* we're through! */
1873         } else {
1874             if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1875                 /*
1876                  * Defence against traffic analysis: we send a
1877                  * whole bunch of packets containing strings of
1878                  * different lengths. One of these strings is the
1879                  * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
1880                  * The others are all random data in
1881                  * SSH1_MSG_IGNORE packets. This way a passive
1882                  * listener can't tell which is the password, and
1883                  * hence can't deduce the password length.
1884                  * 
1885                  * Anybody with a password length greater than 16
1886                  * bytes is going to have enough entropy in their
1887                  * password that a listener won't find it _that_
1888                  * much help to know how long it is. So what we'll
1889                  * do is:
1890                  * 
1891                  *  - if password length < 16, we send 15 packets
1892                  *    containing string lengths 1 through 15
1893                  * 
1894                  *  - otherwise, we let N be the nearest multiple
1895                  *    of 8 below the password length, and send 8
1896                  *    packets containing string lengths N through
1897                  *    N+7. This won't obscure the order of
1898                  *    magnitude of the password length, but it will
1899                  *    introduce a bit of extra uncertainty.
1900                  * 
1901                  * A few servers (the old 1.2.18 through 1.2.22)
1902                  * can't deal with SSH1_MSG_IGNORE. For these
1903                  * servers, we need an alternative defence. We make
1904                  * use of the fact that the password is interpreted
1905                  * as a C string: so we can append a NUL, then some
1906                  * random data.
1907                  */
1908                 if (ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) {
1909                     char string[64];
1910                     char *s;
1911                     int len;
1912
1913                     len = strlen(password);
1914                     if (len < sizeof(string)) {
1915                         s = string;
1916                         strcpy(string, password);
1917                         len++;         /* cover the zero byte */
1918                         while (len < sizeof(string)) {
1919                             string[len++] = (char)random_byte();
1920                         }
1921                     } else {
1922                         s = password;
1923                     }
1924                     send_packet(pwpkt_type, PKT_INT, len,
1925                                 PKT_DATA, s, len, PKT_END);
1926                 } else {
1927                     int bottom, top, pwlen, i;
1928                     char *randomstr;
1929
1930                     pwlen = strlen(password);
1931                     if (pwlen < 16) {
1932                         bottom = 0;    /* zero length passwords are OK! :-) */
1933                         top = 15;
1934                     } else {
1935                         bottom = pwlen &~ 7;
1936                         top = bottom + 7;
1937                     }
1938
1939                     assert(pwlen >= bottom && pwlen <= top);
1940
1941                     randomstr = smalloc(top+1);
1942
1943                     for (i = bottom; i <= top; i++) {
1944                         if (i == pwlen)
1945                             defer_packet(pwpkt_type, PKT_STR, password, PKT_END);
1946                         else {
1947                             for (j = 0; j < i; j++) {
1948                                 do {
1949                                     randomstr[j] = random_byte();
1950                                 } while (randomstr[j] == '\0');
1951                             }
1952                             randomstr[i] = '\0';
1953                             defer_packet(SSH1_MSG_IGNORE,
1954                                          PKT_STR, randomstr, PKT_END);
1955                         }
1956                     }
1957                     ssh_pkt_defersend();
1958                 }
1959             } else {
1960                 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1961             }
1962         }
1963         logevent("Sent password");
1964         memset(password, 0, strlen(password));
1965         crWaitUntil(ispkt);
1966         if (pktin.type == SSH1_SMSG_FAILURE) {
1967             if (flags & FLAG_VERBOSE)
1968                 c_write_str("Access denied\r\n");
1969             logevent("Authentication refused");
1970         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1971             logevent("Received disconnect request");
1972             ssh_state = SSH_STATE_CLOSED;
1973             crReturn(1);
1974         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1975             bombout(("Strange packet received, type %d", pktin.type));
1976             crReturn(0);
1977         }
1978     }
1979
1980     logevent("Authentication successful");
1981
1982     crFinish(1);
1983 }
1984
1985 void sshfwd_close(struct ssh_channel *c) {
1986     if (c && !c->closes) {
1987         if (ssh_version == 1) {
1988             send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1989         } else {
1990             ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1991             ssh2_pkt_adduint32(c->remoteid);
1992             ssh2_pkt_send();
1993         }
1994         c->closes = 1;
1995         if (c->type == CHAN_X11) {
1996             c->u.x11.s = NULL;
1997             logevent("X11 connection terminated");
1998         }
1999     }
2000 }
2001
2002 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
2003     if (ssh_version == 1) {
2004         send_packet(SSH1_MSG_CHANNEL_DATA,
2005                     PKT_INT, c->remoteid,
2006                     PKT_INT, len,
2007                     PKT_DATA, buf, len,
2008                     PKT_END);
2009     } else {
2010         ssh2_add_channel_data(c, buf, len);
2011         ssh2_try_send(c);
2012     }
2013 }
2014
2015 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
2016     crBegin;
2017
2018     random_init();
2019
2020     while (!do_ssh1_login(in, inlen, ispkt)) {
2021         crReturnV;
2022     }
2023     if (ssh_state == SSH_STATE_CLOSED)
2024         crReturnV;
2025
2026     if (cfg.agentfwd && agent_exists()) {
2027         logevent("Requesting agent forwarding");
2028         send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2029         do { crReturnV; } while (!ispkt);
2030         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2031             bombout(("Protocol confusion"));
2032             crReturnV;
2033         } else if (pktin.type == SSH1_SMSG_FAILURE) {
2034             logevent("Agent forwarding refused");
2035         } else {
2036             logevent("Agent forwarding enabled");
2037             ssh_agentfwd_enabled = TRUE;
2038         }
2039     }
2040
2041     if (cfg.x11_forward) {
2042         char proto[20], data[64];
2043         logevent("Requesting X11 forwarding");
2044         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2045         send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING, 
2046                     PKT_STR, proto, PKT_STR, data,
2047                     PKT_INT, 0,
2048                     PKT_END);
2049         do { crReturnV; } while (!ispkt);
2050         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2051             bombout(("Protocol confusion"));
2052             crReturnV;
2053         } else if (pktin.type == SSH1_SMSG_FAILURE) {
2054             logevent("X11 forwarding refused");
2055         } else {
2056             logevent("X11 forwarding enabled");
2057             ssh_X11_fwd_enabled = TRUE;
2058         }
2059     }
2060
2061     if (!cfg.nopty) {
2062         send_packet(SSH1_CMSG_REQUEST_PTY,
2063                     PKT_STR, cfg.termtype,
2064                     PKT_INT, rows, PKT_INT, cols,
2065                     PKT_INT, 0, PKT_INT, 0,
2066                     PKT_CHAR, 0,
2067                     PKT_END);
2068         ssh_state = SSH_STATE_INTERMED;
2069         do { crReturnV; } while (!ispkt);
2070         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2071             bombout(("Protocol confusion"));
2072             crReturnV;
2073         } else if (pktin.type == SSH1_SMSG_FAILURE) {
2074             c_write_str("Server refused to allocate pty\r\n");
2075             ssh_editing = ssh_echoing = 1;
2076         }
2077         logevent("Allocated pty");
2078     } else {
2079         ssh_editing = ssh_echoing = 1;
2080     }
2081
2082     if (cfg.compression) {
2083         send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
2084         do { crReturnV; } while (!ispkt);
2085         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
2086             bombout(("Protocol confusion"));
2087             crReturnV;
2088         } else if (pktin.type == SSH1_SMSG_FAILURE) {
2089             c_write_str("Server refused to compress\r\n");
2090         }
2091         logevent("Started compression");
2092         ssh1_compressing = TRUE;
2093         zlib_compress_init();
2094         zlib_decompress_init();
2095     }
2096
2097     if (*cfg.remote_cmd)
2098         send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
2099     else
2100         send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
2101     logevent("Started session");
2102
2103     ssh_state = SSH_STATE_SESSION;
2104     if (size_needed)
2105         ssh_size();
2106     if (eof_needed)
2107         ssh_special(TS_EOF);
2108
2109     ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
2110     ssh_send_ok = 1;
2111     ssh_channels = newtree234(ssh_channelcmp);
2112     while (1) {
2113         crReturnV;
2114         if (ispkt) {
2115             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
2116                 pktin.type == SSH1_SMSG_STDERR_DATA) {
2117                 long len = GET_32BIT(pktin.body);
2118                 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
2119                              pktin.body+4, len);
2120             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2121                 ssh_state = SSH_STATE_CLOSED;
2122                 logevent("Received disconnect request");
2123                 crReturnV;
2124             } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
2125                 /* Remote side is trying to open a channel to talk to our
2126                  * X-Server. Give them back a local channel number. */
2127                 unsigned i;
2128                 struct ssh_channel *c, *d;
2129                 enum234 e;
2130
2131                 logevent("Received X11 connect request");
2132                 /* Refuse if X11 forwarding is disabled. */
2133                 if (!ssh_X11_fwd_enabled) {
2134                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2135                                 PKT_INT, GET_32BIT(pktin.body),
2136                                 PKT_END);
2137                     logevent("Rejected X11 connect request");
2138                 } else {
2139                     c = smalloc(sizeof(struct ssh_channel));
2140
2141                     if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
2142                       logevent("opening X11 forward connection failed");
2143                       sfree(c);
2144                       send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2145                                   PKT_INT, GET_32BIT(pktin.body),
2146                                   PKT_END);
2147                     } else {
2148                       logevent("opening X11 forward connection succeeded");
2149                       for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
2150                           if (d->localid > i)
2151                               break;     /* found a free number */
2152                           i = d->localid + 1;
2153                       }
2154                       c->remoteid = GET_32BIT(pktin.body);
2155                       c->localid = i;
2156                       c->closes = 0;
2157                       c->type = CHAN_X11;   /* identify channel type */
2158                       add234(ssh_channels, c);
2159                       send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2160                                   PKT_INT, c->remoteid, PKT_INT, c->localid,
2161                                   PKT_END);
2162                       logevent("Opened X11 forward channel");
2163                     }
2164                 }
2165             } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
2166                 /* Remote side is trying to open a channel to talk to our
2167                  * agent. Give them back a local channel number. */
2168                 unsigned i;
2169                 struct ssh_channel *c;
2170                 enum234 e;
2171
2172                 /* Refuse if agent forwarding is disabled. */
2173                 if (!ssh_agentfwd_enabled) {
2174                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
2175                                 PKT_INT, GET_32BIT(pktin.body),
2176                                 PKT_END);
2177                 } else {
2178                     i = 1;
2179                     for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2180                         if (c->localid > i)
2181                             break;     /* found a free number */
2182                         i = c->localid + 1;
2183                     }
2184                     c = smalloc(sizeof(struct ssh_channel));
2185                     c->remoteid = GET_32BIT(pktin.body);
2186                     c->localid = i;
2187                     c->closes = 0;
2188                     c->type = CHAN_AGENT;   /* identify channel type */
2189                     c->u.a.lensofar = 0;
2190                     add234(ssh_channels, c);
2191                     send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2192                                 PKT_INT, c->remoteid, PKT_INT, c->localid,
2193                                 PKT_END);
2194                 }
2195             } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2196                        pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2197                 /* Remote side closes a channel. */
2198                 unsigned i = GET_32BIT(pktin.body);
2199                 struct ssh_channel *c;
2200                 c = find234(ssh_channels, &i, ssh_channelfind);
2201                 if (c) {
2202                     int closetype;
2203                     closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2204                     send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2205                     if ((c->closes == 0) && (c->type == CHAN_X11)) {
2206                         logevent("X11 connection closed");
2207                         assert(c->u.x11.s != NULL);
2208                         x11_close(c->u.x11.s);
2209                         c->u.x11.s = NULL;
2210                     }
2211                     c->closes |= closetype;
2212                     if (c->closes == 3) {
2213                         del234(ssh_channels, c);
2214                         sfree(c);
2215                     }
2216                 }
2217             } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2218                 /* Data sent down one of our channels. */
2219                 int i = GET_32BIT(pktin.body);
2220                 int len = GET_32BIT(pktin.body+4);
2221                 unsigned char *p = pktin.body+8;
2222                 struct ssh_channel *c;
2223                 c = find234(ssh_channels, &i, ssh_channelfind);
2224                 if (c) {
2225                     switch(c->type) {
2226                       case CHAN_X11:
2227                         x11_send(c->u.x11.s, p, len);
2228                         break;
2229                       case CHAN_AGENT:
2230                         /* Data for an agent message. Buffer it. */
2231                         while (len > 0) {
2232                             if (c->u.a.lensofar < 4) {
2233                                 int l = min(4 - c->u.a.lensofar, len);
2234                                 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2235                                 p += l; len -= l; c->u.a.lensofar += l;
2236                             }
2237                             if (c->u.a.lensofar == 4) {
2238                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2239                                 c->u.a.message = smalloc(c->u.a.totallen);
2240                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
2241                             }
2242                             if (c->u.a.lensofar >= 4 && len > 0) {
2243                                 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2244                                 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2245                                 p += l; len -= l; c->u.a.lensofar += l;
2246                             }
2247                             if (c->u.a.lensofar == c->u.a.totallen) {
2248                                 void *reply, *sentreply;
2249                                 int replylen;
2250                                 agent_query(c->u.a.message, c->u.a.totallen,
2251                                             &reply, &replylen);
2252                                 if (reply)
2253                                     sentreply = reply;
2254                                 else {
2255                                     /* Fake SSH_AGENT_FAILURE. */
2256                                     sentreply = "\0\0\0\1\5";
2257                                     replylen = 5;
2258                                 }
2259                                 send_packet(SSH1_MSG_CHANNEL_DATA,
2260                                             PKT_INT, c->remoteid,
2261                                             PKT_INT, replylen,
2262                                             PKT_DATA, sentreply, replylen,
2263                                             PKT_END);
2264                                 if (reply)
2265                                     sfree(reply);
2266                                 sfree(c->u.a.message);
2267                                 c->u.a.lensofar = 0;
2268                             }
2269                         }
2270                         break;
2271                     }
2272                 }                
2273             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2274                 /* may be from EXEC_SHELL on some servers */
2275             } else if (pktin.type == SSH1_SMSG_FAILURE) {
2276                 /* may be from EXEC_SHELL on some servers
2277                  * if no pty is available or in other odd cases. Ignore */
2278             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2279                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2280             } else {
2281                 bombout(("Strange packet received: type %d", pktin.type));
2282                 crReturnV;
2283             }
2284         } else {
2285             while (inlen > 0) {
2286                 int len = min(inlen, 512);
2287                 send_packet(SSH1_CMSG_STDIN_DATA,
2288                             PKT_INT, len, PKT_DATA, in, len, PKT_END);
2289                 in += len;
2290                 inlen -= len;
2291             }
2292         }
2293     }
2294
2295     crFinishV;
2296 }
2297
2298 /*
2299  * Utility routine for decoding comma-separated strings in KEXINIT.
2300  */
2301 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2302     int needlen = strlen(needle);
2303     while (1) {
2304         /*
2305          * Is it at the start of the string?
2306          */
2307         if (haylen >= needlen &&       /* haystack is long enough */
2308             !memcmp(needle, haystack, needlen) &&    /* initial match */
2309             (haylen == needlen || haystack[needlen] == ',')
2310                                        /* either , or EOS follows */
2311             )
2312             return 1;
2313         /*
2314          * If not, search for the next comma and resume after that.
2315          * If no comma found, terminate.
2316          */
2317         while (haylen > 0 && *haystack != ',')
2318             haylen--, haystack++;
2319         if (haylen == 0)
2320             return 0;
2321         haylen--, haystack++;          /* skip over comma itself */
2322     }
2323 }
2324
2325 /*
2326  * SSH2 key creation method.
2327  */
2328 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2329     SHA_State s;
2330     /* First 20 bytes. */
2331     SHA_Init(&s);
2332     sha_mpint(&s, K);
2333     SHA_Bytes(&s, H, 20);
2334     SHA_Bytes(&s, &chr, 1);
2335     SHA_Bytes(&s, sessid, 20);
2336     SHA_Final(&s, keyspace);
2337     /* Next 20 bytes. */
2338     SHA_Init(&s);
2339     sha_mpint(&s, K);
2340     SHA_Bytes(&s, H, 20);
2341     SHA_Bytes(&s, keyspace, 20);
2342     SHA_Final(&s, keyspace+20);
2343 }
2344
2345 /*
2346  * Handle the SSH2 transport layer.
2347  */
2348 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2349 {
2350     static int i, j, len, nbits, pbits;
2351     static char *str;
2352     static Bignum p, g, e, f, K;
2353     static int kex_init_value, kex_reply_value;
2354     static const struct ssh_mac **maclist;
2355     static int nmacs;
2356     static const struct ssh2_cipher *cscipher_tobe = NULL;
2357     static const struct ssh2_cipher *sccipher_tobe = NULL;
2358     static const struct ssh_mac *csmac_tobe = NULL;
2359     static const struct ssh_mac *scmac_tobe = NULL;
2360     static const struct ssh_compress *cscomp_tobe = NULL;
2361     static const struct ssh_compress *sccomp_tobe = NULL;
2362     static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2363     static int hostkeylen, siglen;
2364     static void *hkey;                 /* actual host key */
2365     static unsigned char exchange_hash[20];
2366     static unsigned char keyspace[40];
2367     static const struct ssh2_ciphers *preferred_cipher;
2368     static const struct ssh_compress *preferred_comp;
2369     static int first_kex;
2370
2371     crBegin;
2372     random_init();
2373     first_kex = 1;
2374
2375     /*
2376      * Set up the preferred cipher and compression.
2377      */
2378     if (cfg.cipher == CIPHER_BLOWFISH) {
2379         preferred_cipher = &ssh2_blowfish;
2380     } else if (cfg.cipher == CIPHER_DES) {
2381         logevent("Single DES not supported in SSH2; using 3DES");
2382         preferred_cipher = &ssh2_3des;
2383     } else if (cfg.cipher == CIPHER_3DES) {
2384         preferred_cipher = &ssh2_3des;
2385     } else if (cfg.cipher == CIPHER_AES) {
2386         preferred_cipher = &ssh2_aes;
2387     } else {
2388         /* Shouldn't happen, but we do want to initialise to _something_. */
2389         preferred_cipher = &ssh2_3des;
2390     }
2391     if (cfg.compression)
2392         preferred_comp = &ssh_zlib;
2393     else
2394         preferred_comp = &ssh_comp_none;
2395
2396     /*
2397      * Be prepared to work around the buggy MAC problem.
2398      */
2399     if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
2400         maclist = buggymacs, nmacs = lenof(buggymacs);
2401     else
2402         maclist = macs, nmacs = lenof(macs);
2403
2404     begin_key_exchange:
2405     /*
2406      * Construct and send our key exchange packet.
2407      */
2408     ssh2_pkt_init(SSH2_MSG_KEXINIT);
2409     for (i = 0; i < 16; i++)
2410         ssh2_pkt_addbyte((unsigned char)random_byte());
2411     /* List key exchange algorithms. */
2412     ssh2_pkt_addstring_start();
2413     for (i = 0; i < lenof(kex_algs); i++) {
2414         ssh2_pkt_addstring_str(kex_algs[i]->name);
2415         if (i < lenof(kex_algs)-1)
2416             ssh2_pkt_addstring_str(",");
2417     }
2418     /* List server host key algorithms. */
2419     ssh2_pkt_addstring_start();
2420     for (i = 0; i < lenof(hostkey_algs); i++) {
2421         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2422         if (i < lenof(hostkey_algs)-1)
2423             ssh2_pkt_addstring_str(",");
2424     }
2425     /* List client->server encryption algorithms. */
2426     ssh2_pkt_addstring_start();
2427     for (i = 0; i < lenof(ciphers)+1; i++) {
2428         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2429         for (j = 0; j < c->nciphers; j++) {
2430             ssh2_pkt_addstring_str(c->list[j]->name);
2431             if (i < lenof(ciphers) || j < c->nciphers-1)
2432                 ssh2_pkt_addstring_str(",");
2433         }
2434     }
2435     /* List server->client encryption algorithms. */
2436     ssh2_pkt_addstring_start();
2437     for (i = 0; i < lenof(ciphers)+1; i++) {
2438         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2439         for (j = 0; j < c->nciphers; j++) {
2440             ssh2_pkt_addstring_str(c->list[j]->name);
2441             if (i < lenof(ciphers) || j < c->nciphers-1)
2442                 ssh2_pkt_addstring_str(",");
2443         }
2444     }
2445     /* List client->server MAC algorithms. */
2446     ssh2_pkt_addstring_start();
2447     for (i = 0; i < nmacs; i++) {
2448         ssh2_pkt_addstring_str(maclist[i]->name);
2449         if (i < nmacs-1)
2450             ssh2_pkt_addstring_str(",");
2451     }
2452     /* List server->client MAC algorithms. */
2453     ssh2_pkt_addstring_start();
2454     for (i = 0; i < nmacs; i++) {
2455         ssh2_pkt_addstring_str(maclist[i]->name);
2456         if (i < nmacs-1)
2457             ssh2_pkt_addstring_str(",");
2458     }
2459     /* List client->server compression algorithms. */
2460     ssh2_pkt_addstring_start();
2461     for (i = 0; i < lenof(compressions)+1; i++) {
2462         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2463         ssh2_pkt_addstring_str(c->name);
2464         if (i < lenof(compressions))
2465             ssh2_pkt_addstring_str(",");
2466     }
2467     /* List server->client compression algorithms. */
2468     ssh2_pkt_addstring_start();
2469     for (i = 0; i < lenof(compressions)+1; i++) {
2470         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2471         ssh2_pkt_addstring_str(c->name);
2472         if (i < lenof(compressions))
2473             ssh2_pkt_addstring_str(",");
2474     }
2475     /* List client->server languages. Empty list. */
2476     ssh2_pkt_addstring_start();
2477     /* List server->client languages. Empty list. */
2478     ssh2_pkt_addstring_start();
2479     /* First KEX packet does _not_ follow, because we're not that brave. */
2480     ssh2_pkt_addbool(FALSE);
2481     /* Reserved. */
2482     ssh2_pkt_adduint32(0);
2483
2484     exhash = exhashbase;
2485     sha_string(&exhash, pktout.data+5, pktout.length-5);
2486
2487     ssh2_pkt_send();
2488
2489     if (!ispkt) crWaitUntil(ispkt);
2490     sha_string(&exhash, pktin.data+5, pktin.length-5);
2491
2492     /*
2493      * Now examine the other side's KEXINIT to see what we're up
2494      * to.
2495      */
2496     if (pktin.type != SSH2_MSG_KEXINIT) {
2497         bombout(("expected key exchange packet from server"));
2498         crReturn(0);
2499     }
2500     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2501     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2502     pktin.savedpos += 16;              /* skip garbage cookie */
2503     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
2504     for (i = 0; i < lenof(kex_algs); i++) {
2505         if (in_commasep_string(kex_algs[i]->name, str, len)) {
2506             kex = kex_algs[i];
2507             break;
2508         }
2509     }
2510     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
2511     for (i = 0; i < lenof(hostkey_algs); i++) {
2512         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2513             hostkey = hostkey_algs[i];
2514             break;
2515         }
2516     }
2517     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
2518     for (i = 0; i < lenof(ciphers)+1; i++) {
2519         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2520         for (j = 0; j < c->nciphers; j++) {
2521             if (in_commasep_string(c->list[j]->name, str, len)) {
2522                 cscipher_tobe = c->list[j];
2523                 break;
2524             }
2525         }
2526         if (cscipher_tobe)
2527             break;
2528     }
2529     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
2530     for (i = 0; i < lenof(ciphers)+1; i++) {
2531         const struct ssh2_ciphers *c = i==0 ? preferred_cipher : ciphers[i-1];
2532         for (j = 0; j < c->nciphers; j++) {
2533             if (in_commasep_string(c->list[j]->name, str, len)) {
2534                 sccipher_tobe = c->list[j];
2535                 break;
2536             }
2537         }
2538         if (sccipher_tobe)
2539             break;
2540     }
2541     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
2542     for (i = 0; i < nmacs; i++) {
2543         if (in_commasep_string(maclist[i]->name, str, len)) {
2544             csmac_tobe = maclist[i];
2545             break;
2546         }
2547     }
2548     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
2549     for (i = 0; i < nmacs; i++) {
2550         if (in_commasep_string(maclist[i]->name, str, len)) {
2551             scmac_tobe = maclist[i];
2552             break;
2553         }
2554     }
2555     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
2556     for (i = 0; i < lenof(compressions)+1; i++) {
2557         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2558         if (in_commasep_string(c->name, str, len)) {
2559             cscomp_tobe = c;
2560             break;
2561         }
2562     }
2563     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
2564     for (i = 0; i < lenof(compressions)+1; i++) {
2565         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2566         if (in_commasep_string(c->name, str, len)) {
2567             sccomp_tobe = c;
2568             break;
2569         }
2570     }
2571
2572     /*
2573      * Work out the number of bits of key we will need from the key
2574      * exchange. We start with the maximum key length of either
2575      * cipher...
2576      */
2577     {
2578         int csbits, scbits;
2579
2580         csbits = cscipher_tobe->keylen;
2581         scbits = sccipher_tobe->keylen;
2582         nbits = (csbits > scbits ? csbits : scbits);
2583     }
2584     /* The keys only have 160-bit entropy, since they're based on
2585      * a SHA-1 hash. So cap the key size at 160 bits. */
2586     if (nbits > 160) nbits = 160;
2587
2588     /*
2589      * If we're doing Diffie-Hellman group exchange, start by
2590      * requesting a group.
2591      */
2592     if (kex == &ssh_diffiehellman_gex) {
2593         logevent("Doing Diffie-Hellman group exchange");
2594         /*
2595          * Work out how big a DH group we will need to allow that
2596          * much data.
2597          */
2598         pbits = 512 << ((nbits-1) / 64);
2599         ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
2600         ssh2_pkt_adduint32(pbits);
2601         ssh2_pkt_send();
2602
2603         crWaitUntil(ispkt);
2604         if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
2605             bombout(("expected key exchange group packet from server"));
2606             crReturn(0);
2607         }
2608         p = ssh2_pkt_getmp();
2609         g = ssh2_pkt_getmp();
2610         dh_setup_group(p, g);
2611         kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
2612         kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
2613     } else {
2614         dh_setup_group1();
2615         kex_init_value = SSH2_MSG_KEXDH_INIT;
2616         kex_reply_value = SSH2_MSG_KEXDH_REPLY;
2617     }
2618
2619     logevent("Doing Diffie-Hellman key exchange");
2620     /*
2621      * Now generate and send e for Diffie-Hellman.
2622      */
2623     e = dh_create_e(nbits*2);
2624     ssh2_pkt_init(kex_init_value);
2625     ssh2_pkt_addmp(e);
2626     ssh2_pkt_send();
2627
2628     crWaitUntil(ispkt);
2629     if (pktin.type != kex_reply_value) {
2630         bombout(("expected key exchange reply packet from server"));
2631         crReturn(0);
2632     }
2633     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2634     f = ssh2_pkt_getmp();
2635     ssh2_pkt_getstring(&sigdata, &siglen);
2636
2637     K = dh_find_K(f);
2638
2639     sha_string(&exhash, hostkeydata, hostkeylen);
2640     if (kex == &ssh_diffiehellman_gex) {
2641         sha_uint32(&exhash, pbits);
2642         sha_mpint(&exhash, p);
2643         sha_mpint(&exhash, g);
2644     }
2645     sha_mpint(&exhash, e);
2646     sha_mpint(&exhash, f);
2647     sha_mpint(&exhash, K);
2648     SHA_Final(&exhash, exchange_hash);
2649
2650     dh_cleanup();
2651
2652 #if 0
2653     debug(("Exchange hash is:\r\n"));
2654     for (i = 0; i < 20; i++)
2655         debug((" %02x", exchange_hash[i]));
2656     debug(("\r\n"));
2657 #endif
2658
2659     hkey = hostkey->newkey(hostkeydata, hostkeylen);
2660     if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2661         bombout(("Server failed host key check"));
2662         crReturn(0);
2663     }
2664
2665     /*
2666      * Expect SSH2_MSG_NEWKEYS from server.
2667      */
2668     crWaitUntil(ispkt);
2669     if (pktin.type != SSH2_MSG_NEWKEYS) {
2670         bombout(("expected new-keys packet from server"));
2671         crReturn(0);
2672     }
2673
2674     /*
2675      * Authenticate remote host: verify host key. (We've already
2676      * checked the signature of the exchange hash.)
2677      */
2678     keystr = hostkey->fmtkey(hkey);
2679     fingerprint = hostkey->fingerprint(hkey);
2680     verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2681                         keystr, fingerprint);
2682     if (first_kex) {                /* don't bother logging this in rekeys */
2683         logevent("Host key fingerprint is:");
2684         logevent(fingerprint);
2685     }
2686     sfree(fingerprint);
2687     sfree(keystr);
2688     hostkey->freekey(hkey);
2689
2690     /*
2691      * Send SSH2_MSG_NEWKEYS.
2692      */
2693     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2694     ssh2_pkt_send();
2695
2696     /*
2697      * Create and initialise session keys.
2698      */
2699     cscipher = cscipher_tobe;
2700     sccipher = sccipher_tobe;
2701     csmac = csmac_tobe;
2702     scmac = scmac_tobe;
2703     cscomp = cscomp_tobe;
2704     sccomp = sccomp_tobe;
2705     cscomp->compress_init();
2706     sccomp->decompress_init();
2707     /*
2708      * Set IVs after keys. Here we use the exchange hash from the
2709      * _first_ key exchange.
2710      */
2711     if (first_kex)
2712         memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
2713     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
2714     cscipher->setcskey(keyspace);
2715     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
2716     sccipher->setsckey(keyspace);
2717     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
2718     cscipher->setcsiv(keyspace);
2719     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
2720     sccipher->setsciv(keyspace);
2721     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
2722     csmac->setcskey(keyspace);
2723     ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
2724     scmac->setsckey(keyspace);
2725
2726     /*
2727      * If this is the first key exchange phase, we must pass the
2728      * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2729      * wants to see it but because it will need time to initialise
2730      * itself before it sees an actual packet. In subsequent key
2731      * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2732      * it would only confuse the layer above.
2733      */
2734     if (!first_kex) {
2735         crReturn(0);
2736     }
2737     first_kex = 0;
2738
2739     /*
2740      * Now we're encrypting. Begin returning 1 to the protocol main
2741      * function so that other things can run on top of the
2742      * transport. If we ever see a KEXINIT, we must go back to the
2743      * start.
2744      */
2745     while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2746         crReturn(1);
2747     }
2748     logevent("Server initiated key re-exchange");
2749     goto begin_key_exchange;
2750
2751     crFinish(1);
2752 }
2753
2754 /*
2755  * Add data to an SSH2 channel output buffer.
2756  */
2757 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2758     if (c->v2.outbufsize <
2759         c->v2.outbuflen + len) {
2760         c->v2.outbufsize =
2761             c->v2.outbuflen + len + 1024;
2762         c->v2.outbuffer = srealloc(c->v2.outbuffer,
2763                                    c->v2.outbufsize);
2764     }
2765     memcpy(c->v2.outbuffer + c->v2.outbuflen,
2766            buf, len);
2767     c->v2.outbuflen += len;
2768 }
2769
2770 /*
2771  * Attempt to send data on an SSH2 channel.
2772  */
2773 static void ssh2_try_send(struct ssh_channel *c) {
2774     while (c->v2.remwindow > 0 &&
2775            c->v2.outbuflen > 0) {
2776         unsigned len = c->v2.remwindow;
2777         if (len > c->v2.outbuflen)
2778             len = c->v2.outbuflen;
2779         if (len > c->v2.remmaxpkt)
2780             len = c->v2.remmaxpkt;
2781         ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2782         ssh2_pkt_adduint32(c->remoteid);
2783         ssh2_pkt_addstring_start();
2784         ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2785         ssh2_pkt_send();
2786         c->v2.outbuflen -= len;
2787         memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2788                 c->v2.outbuflen);
2789         c->v2.remwindow -= len;
2790     }
2791 }
2792
2793 /*
2794  * Handle the SSH2 userauth and connection layers.
2795  */
2796 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2797 {
2798     static unsigned long remote_winsize;
2799     static unsigned long remote_maxpkt;
2800     static enum {
2801         AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE, AUTH_PASSWORD
2802     } method;
2803     static enum {
2804         AUTH_TYPE_NONE,
2805         AUTH_TYPE_PUBLICKEY,
2806         AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
2807         AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
2808         AUTH_TYPE_PASSWORD
2809     } type;
2810     static int gotit, need_pw, can_pubkey, can_passwd;
2811     static int tried_pubkey_config, tried_agent;
2812     static int we_are_in;
2813     static char username[100];
2814     static char pwprompt[200];
2815     static char password[100];
2816
2817     crBegin;
2818
2819     /*
2820      * Request userauth protocol, and await a response to it.
2821      */
2822     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2823     ssh2_pkt_addstring("ssh-userauth");
2824     ssh2_pkt_send();
2825     crWaitUntilV(ispkt);
2826     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2827         bombout(("Server refused user authentication protocol"));
2828         crReturnV;
2829     }
2830
2831     /*
2832      * We repeat this whole loop, including the username prompt,
2833      * until we manage a successful authentication. If the user
2834      * types the wrong _password_, they are sent back to the
2835      * beginning to try another username. (If they specify a
2836      * username in the config, they are never asked, even if they
2837      * do give a wrong password.)
2838      * 
2839      * I think this best serves the needs of
2840      * 
2841      *  - the people who have no configuration, no keys, and just
2842      *    want to try repeated (username,password) pairs until they
2843      *    type both correctly
2844      * 
2845      *  - people who have keys and configuration but occasionally
2846      *    need to fall back to passwords
2847      * 
2848      *  - people with a key held in Pageant, who might not have
2849      *    logged in to a particular machine before; so they want to
2850      *    type a username, and then _either_ their key will be
2851      *    accepted, _or_ they will type a password. If they mistype
2852      *    the username they will want to be able to get back and
2853      *    retype it!
2854      */
2855     do {
2856         static int pos;
2857         static char c;
2858
2859         /*
2860          * Get a username.
2861          */
2862         pos = 0;
2863         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2864             if (ssh_get_line) {
2865                 if (!ssh_get_line("login as: ",
2866                                   username, sizeof(username), FALSE)) {
2867                     /*
2868                      * get_line failed to get a username.
2869                      * Terminate.
2870                      */
2871                     logevent("No username provided. Abandoning session.");
2872                     ssh_state = SSH_STATE_CLOSED;
2873                     crReturn(1);
2874                 }
2875             } else {
2876                 c_write_str("login as: ");
2877                 ssh_send_ok = 1;
2878                 while (pos >= 0) {
2879                     crWaitUntilV(!ispkt);
2880                     while (inlen--) switch (c = *in++) {
2881                       case 10: case 13:
2882                         username[pos] = 0;
2883                         pos = -1;
2884                         break;
2885                       case 8: case 127:
2886                         if (pos > 0) {
2887                             c_write_str("\b \b");
2888                             pos--;
2889                         }
2890                         break;
2891                       case 21: case 27:
2892                         while (pos > 0) {
2893                             c_write_str("\b \b");
2894                             pos--;
2895                         }
2896                         break;
2897                       case 3: case 4:
2898                         random_save_seed();
2899                         exit(0);
2900                         break;
2901                       default:
2902                         if (((c >= ' ' && c <= '~') ||
2903                              ((unsigned char)c >= 160)) && pos < 40) {
2904                             username[pos++] = c;
2905                             c_write(&c, 1);
2906                         }
2907                         break;
2908                     }
2909                 }
2910             }
2911             c_write_str("\r\n");
2912             username[strcspn(username, "\n\r")] = '\0';
2913         } else {
2914             char stuff[200];
2915             strncpy(username, cfg.username, 99);
2916             username[99] = '\0';
2917             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2918                 sprintf(stuff, "Using username \"%s\".\r\n", username);
2919                 c_write_str(stuff);
2920             }
2921         }
2922
2923         /*
2924          * Send an authentication request using method "none": (a)
2925          * just in case it succeeds, and (b) so that we know what
2926          * authentication methods we can usefully try next.
2927          */
2928         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2929         ssh2_pkt_addstring(username);
2930         ssh2_pkt_addstring("ssh-connection");   /* service requested */
2931         ssh2_pkt_addstring("none");    /* method */
2932         ssh2_pkt_send();
2933         type = AUTH_TYPE_NONE;
2934         gotit = FALSE;
2935         we_are_in = FALSE;
2936
2937         tried_pubkey_config = FALSE;
2938         tried_agent = FALSE;
2939
2940         while (1) {
2941             /*
2942              * Wait for the result of the last authentication request.
2943              */
2944             if (!gotit)
2945                 crWaitUntilV(ispkt);
2946             while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
2947                 /* FIXME: should support this */
2948                 crWaitUntilV(ispkt);
2949             }
2950             if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
2951                 logevent("Access granted");
2952                 we_are_in = TRUE;
2953                 break;
2954             }
2955
2956             if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
2957                 bombout(("Strange packet received during authentication: type %d",
2958                          pktin.type));
2959             }
2960
2961             gotit = FALSE;
2962
2963             /*
2964              * OK, we're now sitting on a USERAUTH_FAILURE message, so
2965              * we can look at the string in it and know what we can
2966              * helpfully try next.
2967              */
2968             {
2969                 char *methods;
2970                 int methlen;
2971                 ssh2_pkt_getstring(&methods, &methlen);
2972                 if (!ssh2_pkt_getbool()) {
2973                     /*
2974                      * We have received an unequivocal Access
2975                      * Denied. This can translate to a variety of
2976                      * messages:
2977                      * 
2978                      *  - if we'd just tried "none" authentication,
2979                      *    it's not worth printing anything at all
2980                      * 
2981                      *  - if we'd just tried a public key _offer_,
2982                      *    the message should be "Server refused our
2983                      *    key" (or no message at all if the key
2984                      *    came from Pageant)
2985                      * 
2986                      *  - if we'd just tried anything else, the
2987                      *    message really should be "Access denied".
2988                      * 
2989                      * Additionally, if we'd just tried password
2990                      * authentication, we should break out of this
2991                      * whole loop so as to go back to the username
2992                      * prompt.
2993                      */
2994                     if (type == AUTH_TYPE_NONE) {
2995                         /* do nothing */
2996                     } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
2997                                type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
2998                         if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
2999                             c_write_str("Server refused our key\r\n");
3000                         logevent("Server refused public key");
3001                     } else {
3002                         c_write_str("Access denied\r\n");
3003                         logevent("Access denied");
3004                         if (type == AUTH_TYPE_PASSWORD) {
3005                             we_are_in = FALSE;
3006                             break;
3007                         }
3008                     }
3009                 } else {
3010                     c_write_str("Further authentication required\r\n");
3011                     logevent("Further authentication required");
3012                 }
3013
3014                 can_pubkey = in_commasep_string("publickey", methods, methlen);
3015                 can_passwd = in_commasep_string("password", methods, methlen);
3016             }
3017
3018             method = 0;
3019
3020             if (!method && can_pubkey && agent_exists && !tried_agent) {
3021                 /*
3022                  * Attempt public-key authentication using Pageant.
3023                  */
3024                 static unsigned char request[5], *response, *p;
3025                 static int responselen;
3026                 static int i, nkeys;
3027                 static int authed = FALSE;
3028                 void *r;
3029
3030                 tried_agent = TRUE;
3031
3032                 logevent("Pageant is running. Requesting keys.");
3033
3034                 /* Request the keys held by the agent. */
3035                 PUT_32BIT(request, 1);
3036                 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
3037                 agent_query(request, 5, &r, &responselen);
3038                 response = (unsigned char *)r;
3039                 if (response && responselen >= 5 &&
3040                     response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
3041                     p = response + 5;
3042                     nkeys = GET_32BIT(p); p += 4;
3043                     { char buf[64]; sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
3044                         logevent(buf); }
3045                     for (i = 0; i < nkeys; i++) {
3046                         static char *pkblob, *alg, *commentp;
3047                         static int pklen, alglen, commentlen;
3048                         static int siglen, retlen, len;
3049                         static char *q, *agentreq, *ret;
3050
3051                         { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
3052                             logevent(buf); }
3053                         pklen = GET_32BIT(p); p += 4;
3054                         pkblob = p; p += pklen;
3055                         alglen = GET_32BIT(pkblob);
3056                         alg = pkblob + 4;
3057                         commentlen = GET_32BIT(p); p += 4;
3058                         commentp = p; p += commentlen;
3059                         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3060                         ssh2_pkt_addstring(username);
3061                         ssh2_pkt_addstring("ssh-connection");/* service requested */
3062                         ssh2_pkt_addstring("publickey");/* method */
3063                         ssh2_pkt_addbool(FALSE);   /* no signature included */
3064                         ssh2_pkt_addstring_start();
3065                         ssh2_pkt_addstring_data(alg, alglen);
3066                         ssh2_pkt_addstring_start();
3067                         ssh2_pkt_addstring_data(pkblob, pklen);
3068                         ssh2_pkt_send();
3069
3070                         crWaitUntilV(ispkt);
3071                         if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3072                             logevent("Key refused");
3073                             continue;
3074                         }
3075
3076                         c_write_str("Authenticating with public key \"");
3077                         c_write(commentp, commentlen);
3078                         c_write_str("\" from agent\r\n");
3079
3080                         /*
3081                          * Server is willing to accept the key.
3082                          * Construct a SIGN_REQUEST.
3083                          */
3084                         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3085                         ssh2_pkt_addstring(username);
3086                         ssh2_pkt_addstring("ssh-connection");   /* service requested */
3087                         ssh2_pkt_addstring("publickey");    /* method */
3088                         ssh2_pkt_addbool(TRUE);
3089                         ssh2_pkt_addstring_start();
3090                         ssh2_pkt_addstring_data(alg, alglen);
3091                         ssh2_pkt_addstring_start();
3092                         ssh2_pkt_addstring_data(pkblob, pklen);
3093
3094                         siglen = pktout.length - 5 + 4 + 20;
3095                         len = 1;   /* message type */
3096                         len += 4 + pklen;   /* key blob */
3097                         len += 4 + siglen;   /* data to sign */
3098                         len += 4;  /* flags */
3099                         agentreq = smalloc(4 + len);
3100                         PUT_32BIT(agentreq, len);
3101                         q = agentreq + 4;
3102                         *q++ = SSH2_AGENTC_SIGN_REQUEST;
3103                         PUT_32BIT(q, pklen); q += 4;
3104                         memcpy(q, pkblob, pklen); q += pklen;
3105                         PUT_32BIT(q, siglen); q += 4;
3106                         /* Now the data to be signed... */
3107                         PUT_32BIT(q, 20); q += 4;
3108                         memcpy(q, ssh2_session_id, 20); q += 20;
3109                         memcpy(q, pktout.data+5, pktout.length-5);
3110                         q += pktout.length-5;
3111                         /* And finally the (zero) flags word. */
3112                         PUT_32BIT(q, 0);
3113                         agent_query(agentreq, len+4, &ret, &retlen);
3114                         sfree(agentreq);
3115                         if (ret) {
3116                             if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
3117                                 logevent("Sending Pageant's response");
3118                                 ssh2_pkt_addstring_start();
3119                                 ssh2_pkt_addstring_data(ret+9, GET_32BIT(ret+5));
3120                                 ssh2_pkt_send();
3121                                 authed = TRUE;
3122                                 break;
3123                             } else {
3124                                 logevent("Pageant failed to answer challenge");
3125                                 sfree(ret);
3126                             }
3127                         }
3128                     }
3129                     if (authed)
3130                         continue;
3131                 }
3132             }
3133
3134             if (!method && can_pubkey && *cfg.keyfile && !tried_pubkey_config) {
3135                 unsigned char *pub_blob;
3136                 char *algorithm, *comment;
3137                 int pub_blob_len;
3138
3139                 tried_pubkey_config = TRUE;
3140
3141                 /*
3142                  * Try the public key supplied in the configuration.
3143                  *
3144                  * First, offer the public blob to see if the server is
3145                  * willing to accept it.
3146                  */
3147                 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
3148                                                 &pub_blob_len);
3149                 if (pub_blob) {
3150                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3151                     ssh2_pkt_addstring(username);
3152                     ssh2_pkt_addstring("ssh-connection");   /* service requested */
3153                     ssh2_pkt_addstring("publickey");/* method */
3154                     ssh2_pkt_addbool(FALSE);   /* no signature included */
3155                     ssh2_pkt_addstring(algorithm);
3156                     ssh2_pkt_addstring_start();
3157                     ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
3158                     ssh2_pkt_send();
3159                     logevent("Offered public key"); /* FIXME */
3160
3161                     crWaitUntilV(ispkt);
3162                     if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
3163                         gotit = TRUE;
3164                         type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
3165                         continue;              /* key refused; give up on it */
3166                     }
3167
3168                     logevent("Offer of public key accepted");
3169                     /*
3170                      * Actually attempt a serious authentication using
3171                      * the key.
3172                      */
3173                     if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
3174                         sprintf(pwprompt, "Passphrase for key \"%.100s\": ", comment);
3175                         need_pw = TRUE;
3176                     } else {
3177                         need_pw = FALSE;
3178                     }
3179                     c_write_str("Authenticating with public key \"");
3180                     c_write_str(comment);
3181                     c_write_str("\"\r\n");
3182                     method = AUTH_PUBLICKEY_FILE;
3183                 }
3184             }
3185
3186             if (!method && can_passwd) {
3187                 method = AUTH_PASSWORD;
3188                 sprintf(pwprompt, "%.90s@%.90s's password: ", username, savedhost);
3189                 need_pw = TRUE;
3190             }
3191
3192             if (need_pw) {
3193                 if (ssh_get_line) {
3194                     if (!ssh_get_line(pwprompt, password,
3195                                       sizeof(password), TRUE)) {
3196                         /*
3197                          * get_line failed to get a password (for
3198                          * example because one was supplied on the
3199                          * command line which has already failed to
3200                          * work). Terminate.
3201                          */
3202                         logevent("No more passwords to try");
3203                         ssh_state = SSH_STATE_CLOSED;
3204                         crReturnV;
3205                     }
3206                 } else {
3207                     static int pos = 0;
3208                     static char c;
3209
3210                     c_write_str(pwprompt);
3211                     ssh_send_ok = 1;
3212
3213                     pos = 0;
3214                     while (pos >= 0) {
3215                         crWaitUntilV(!ispkt);
3216                         while (inlen--) switch (c = *in++) {
3217                           case 10: case 13:
3218                             password[pos] = 0;
3219                             pos = -1;
3220                             break;
3221                           case 8: case 127:
3222                             if (pos > 0)
3223                                 pos--;
3224                             break;
3225                           case 21: case 27:
3226                             pos = 0;
3227                             break;
3228                           case 3: case 4:
3229                             random_save_seed();
3230                             exit(0);
3231                             break;
3232                           default:
3233                             if (((c >= ' ' && c <= '~') ||
3234                                  ((unsigned char)c >= 160)) && pos < 40)
3235                                 password[pos++] = c;
3236                             break;
3237                         }
3238                     }
3239                     c_write_str("\r\n");
3240                 }
3241             }
3242
3243             if (method == AUTH_PUBLICKEY_FILE) {
3244                 /*
3245                  * We have our passphrase. Now try the actual authentication.
3246                  */
3247                 struct ssh2_userkey *key;
3248
3249                 key = ssh2_load_userkey(cfg.keyfile, password);
3250                 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
3251                     if (key == SSH2_WRONG_PASSPHRASE) {
3252                         c_write_str("Wrong passphrase\r\n");
3253                         tried_pubkey_config = FALSE;
3254                     } else {
3255                         c_write_str("Unable to load private key\r\n");
3256                         tried_pubkey_config = TRUE;
3257                     }
3258                     /* Send a spurious AUTH_NONE to return to the top. */
3259                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3260                     ssh2_pkt_addstring(username);
3261                     ssh2_pkt_addstring("ssh-connection");   /* service requested */
3262                     ssh2_pkt_addstring("none");    /* method */
3263                     ssh2_pkt_send();
3264                     type = AUTH_TYPE_NONE;
3265                 } else {
3266                     unsigned char *blob, *sigdata;
3267                     int blob_len, sigdata_len;
3268
3269                     /*
3270                      * We have loaded the private key and the server
3271                      * has announced that it's willing to accept it.
3272                      * Hallelujah. Generate a signature and send it.
3273                      */
3274                     ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3275                     ssh2_pkt_addstring(username);
3276                     ssh2_pkt_addstring("ssh-connection");   /* service requested */
3277                     ssh2_pkt_addstring("publickey");    /* method */
3278                     ssh2_pkt_addbool(TRUE);
3279                     ssh2_pkt_addstring(key->alg->name);
3280                     blob = key->alg->public_blob(key->data, &blob_len);
3281                     ssh2_pkt_addstring_start();
3282                     ssh2_pkt_addstring_data(blob, blob_len);
3283                     sfree(blob);
3284
3285                     /*
3286                      * The data to be signed is:
3287                      *
3288                      *   string  session-id
3289                      *
3290                      * followed by everything so far placed in the
3291                      * outgoing packet.
3292                      */
3293                     sigdata_len = pktout.length - 5 + 4 + 20;
3294                     sigdata = smalloc(sigdata_len);
3295                     PUT_32BIT(sigdata, 20);
3296                     memcpy(sigdata+4, ssh2_session_id, 20);
3297                     memcpy(sigdata+24, pktout.data+5, pktout.length-5);
3298                     blob = key->alg->sign(key->data, sigdata, sigdata_len, &blob_len);
3299                     ssh2_pkt_addstring_start();
3300                     ssh2_pkt_addstring_data(blob, blob_len);
3301                     sfree(blob);
3302                     sfree(sigdata);
3303
3304                     ssh2_pkt_send();
3305                     type = AUTH_TYPE_PUBLICKEY;
3306                 }
3307             } else if (method == AUTH_PASSWORD) {
3308                 /*
3309                  * We send the password packet lumped tightly together with
3310                  * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
3311                  * string long enough to make the total length of the two
3312                  * packets constant. This should ensure that a passive
3313                  * listener doing traffic analyis can't work out the length
3314                  * of the password.
3315                  *
3316                  * For this to work, we need an assumption about the
3317                  * maximum length of the password packet. I think 256 is
3318                  * pretty conservative. Anyone using a password longer than
3319                  * that probably doesn't have much to worry about from
3320                  * people who find out how long their password is!
3321                  */
3322                 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
3323                 ssh2_pkt_addstring(username);
3324                 ssh2_pkt_addstring("ssh-connection");   /* service requested */
3325                 ssh2_pkt_addstring("password");
3326                 ssh2_pkt_addbool(FALSE);
3327                 ssh2_pkt_addstring(password);
3328                 ssh2_pkt_defer();
3329                 /*
3330                  * We'll include a string that's an exact multiple of the
3331                  * cipher block size. If the cipher is NULL for some
3332                  * reason, we don't do this trick at all because we gain
3333                  * nothing by it.
3334                  */
3335                 if (cscipher) {
3336                     int stringlen, i;
3337
3338                     stringlen = (256 - deferred_len);
3339                     stringlen += cscipher->blksize - 1;
3340                     stringlen -= (stringlen % cscipher->blksize);
3341                     if (cscomp) {
3342                         /*
3343                          * Temporarily disable actual compression,
3344                          * so we can guarantee to get this string
3345                          * exactly the length we want it. The
3346                          * compression-disabling routine should
3347                          * return an integer indicating how many
3348                          * bytes we should adjust our string length
3349                          * by.
3350                          */
3351                         stringlen -= cscomp->disable_compression();
3352                     }
3353                     ssh2_pkt_init(SSH2_MSG_IGNORE);
3354                     ssh2_pkt_addstring_start();
3355                     for (i = 0; i < stringlen; i++) {
3356                         char c = (char)random_byte();
3357                         ssh2_pkt_addstring_data(&c, 1);
3358                     }
3359                     ssh2_pkt_defer();
3360                 }
3361                 ssh_pkt_defersend();
3362                 logevent("Sent password");
3363                 type = AUTH_TYPE_PASSWORD;
3364             } else {
3365                 c_write_str("No supported authentication methods left to try!\r\n");
3366                 logevent("No supported authentications offered. Disconnecting");
3367                 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3368                 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3369                 ssh2_pkt_addstring("No supported authentication methods available");
3370                 ssh2_pkt_addstring("en");   /* language tag */
3371                 ssh2_pkt_send();
3372                 ssh_state = SSH_STATE_CLOSED;
3373                 crReturnV;
3374             }
3375         }
3376     } while (!we_are_in);
3377
3378     /*
3379      * Now we're authenticated for the connection protocol. The
3380      * connection protocol will automatically have started at this
3381      * point; there's no need to send SERVICE_REQUEST.
3382      */
3383
3384     /*
3385      * So now create a channel with a session in it.
3386      */
3387     mainchan = smalloc(sizeof(struct ssh_channel));
3388     mainchan->localid = 100;           /* as good as any */
3389     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
3390     ssh2_pkt_addstring("session");
3391     ssh2_pkt_adduint32(mainchan->localid);
3392     ssh2_pkt_adduint32(0x8000UL);  /* our window size */
3393     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
3394     ssh2_pkt_send();
3395     crWaitUntilV(ispkt);
3396     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
3397         bombout(("Server refused to open a session"));
3398         crReturnV;
3399         /* FIXME: error data comes back in FAILURE packet */
3400     }
3401     if (ssh2_pkt_getuint32() != mainchan->localid) {
3402         bombout(("Server's channel confirmation cited wrong channel"));
3403         crReturnV;
3404     }
3405     mainchan->remoteid = ssh2_pkt_getuint32();
3406     mainchan->type = CHAN_MAINSESSION;
3407     mainchan->closes = 0;
3408     mainchan->v2.remwindow = ssh2_pkt_getuint32();
3409     mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
3410     mainchan->v2.outbuffer = NULL;
3411     mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
3412     ssh_channels = newtree234(ssh_channelcmp);
3413     add234(ssh_channels, mainchan);
3414     logevent("Opened channel for session");
3415
3416     /*
3417      * Potentially enable X11 forwarding.
3418      */
3419     if (cfg.x11_forward) {
3420         char proto[20], data[64];
3421         logevent("Requesting X11 forwarding");
3422         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3423         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3424         ssh2_pkt_adduint32(mainchan->remoteid);
3425         ssh2_pkt_addstring("x11-req");
3426         ssh2_pkt_addbool(1);           /* want reply */
3427         ssh2_pkt_addbool(0);           /* many connections */
3428         ssh2_pkt_addstring(proto);
3429         ssh2_pkt_addstring(data);
3430         ssh2_pkt_adduint32(0);         /* screen number */
3431         ssh2_pkt_send();
3432
3433         do {
3434             crWaitUntilV(ispkt);
3435             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3436                 unsigned i = ssh2_pkt_getuint32();
3437                 struct ssh_channel *c;
3438                 c = find234(ssh_channels, &i, ssh_channelfind);
3439                 if (!c)
3440                     continue;          /* nonexistent channel */
3441                 c->v2.remwindow += ssh2_pkt_getuint32();
3442             }
3443         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3444
3445         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3446             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3447                 bombout(("Server got confused by X11 forwarding request"));
3448                 crReturnV;
3449             }
3450             logevent("X11 forwarding refused");
3451         } else {
3452             logevent("X11 forwarding enabled");
3453             ssh_X11_fwd_enabled = TRUE;
3454         }
3455     }
3456
3457     /*
3458      * Potentially enable agent forwarding.
3459      */
3460     if (cfg.agentfwd && agent_exists()) {
3461         char proto[20], data[64];
3462         logevent("Requesting OpenSSH-style agent forwarding");
3463         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3464         ssh2_pkt_adduint32(mainchan->remoteid);
3465         ssh2_pkt_addstring("auth-agent-req@openssh.com");
3466         ssh2_pkt_addbool(1);           /* want reply */
3467         ssh2_pkt_send();
3468
3469         do {
3470             crWaitUntilV(ispkt);
3471             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3472                 unsigned i = ssh2_pkt_getuint32();
3473                 struct ssh_channel *c;
3474                 c = find234(ssh_channels, &i, ssh_channelfind);
3475                 if (!c)
3476                     continue;          /* nonexistent channel */
3477                 c->v2.remwindow += ssh2_pkt_getuint32();
3478             }
3479         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3480
3481         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3482             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3483                 bombout(("Server got confused by agent forwarding request"));
3484                 crReturnV;
3485             }
3486             logevent("Agent forwarding refused");
3487         } else {
3488             logevent("Agent forwarding enabled");
3489             ssh_agentfwd_enabled = TRUE;
3490         }
3491     }
3492
3493     /*
3494      * Now allocate a pty for the session.
3495      */
3496     if (!cfg.nopty) {
3497         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3498         ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3499         ssh2_pkt_addstring("pty-req");
3500         ssh2_pkt_addbool(1);           /* want reply */
3501         ssh2_pkt_addstring(cfg.termtype);
3502         ssh2_pkt_adduint32(cols);
3503         ssh2_pkt_adduint32(rows);
3504         ssh2_pkt_adduint32(0);         /* pixel width */
3505         ssh2_pkt_adduint32(0);         /* pixel height */
3506         ssh2_pkt_addstring_start();
3507         ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
3508         ssh2_pkt_send();
3509         ssh_state = SSH_STATE_INTERMED;
3510
3511         do {
3512             crWaitUntilV(ispkt);
3513             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3514                 unsigned i = ssh2_pkt_getuint32();
3515                 struct ssh_channel *c;
3516                 c = find234(ssh_channels, &i, ssh_channelfind);
3517                 if (!c)
3518                     continue;          /* nonexistent channel */
3519                 c->v2.remwindow += ssh2_pkt_getuint32();
3520             }
3521         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3522
3523         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3524             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3525                 bombout(("Server got confused by pty request"));
3526                 crReturnV;
3527             }
3528             c_write_str("Server refused to allocate pty\r\n");
3529             ssh_editing = ssh_echoing = 1;
3530         } else {
3531             logevent("Allocated pty");
3532         }
3533     } else {
3534         ssh_editing = ssh_echoing = 1;
3535     }
3536
3537     /*
3538      * Start a shell or a remote command.
3539      */
3540     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3541     ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
3542     if (cfg.ssh_subsys) {
3543         ssh2_pkt_addstring("subsystem");
3544         ssh2_pkt_addbool(1);           /* want reply */
3545         ssh2_pkt_addstring(cfg.remote_cmd);
3546     } else if (*cfg.remote_cmd) {
3547         ssh2_pkt_addstring("exec");
3548         ssh2_pkt_addbool(1);           /* want reply */
3549         ssh2_pkt_addstring(cfg.remote_cmd);
3550     } else {
3551         ssh2_pkt_addstring("shell");
3552         ssh2_pkt_addbool(1);           /* want reply */
3553     }
3554     ssh2_pkt_send();
3555     do {
3556         crWaitUntilV(ispkt);
3557         if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3558             unsigned i = ssh2_pkt_getuint32();
3559             struct ssh_channel *c;
3560             c = find234(ssh_channels, &i, ssh_channelfind);
3561             if (!c)
3562                 continue;              /* nonexistent channel */
3563             c->v2.remwindow += ssh2_pkt_getuint32();
3564         }
3565     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3566     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
3567         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
3568             bombout(("Server got confused by shell/command request"));
3569             crReturnV;
3570         }
3571         bombout(("Server refused to start a shell/command"));
3572         crReturnV;
3573     } else {
3574         logevent("Started a shell/command");
3575     }
3576
3577     ssh_state = SSH_STATE_SESSION;
3578     if (size_needed)
3579         ssh_size();
3580     if (eof_needed)
3581         ssh_special(TS_EOF);
3582
3583     /*
3584      * Transfer data!
3585      */
3586     ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
3587     ssh_send_ok = 1;
3588     while (1) {
3589         static int try_send;
3590         crReturnV;
3591         try_send = FALSE;
3592         if (ispkt) {
3593             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
3594                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
3595                 char *data;
3596                 int length;
3597                 unsigned i = ssh2_pkt_getuint32();
3598                 struct ssh_channel *c;
3599                 c = find234(ssh_channels, &i, ssh_channelfind);
3600                 if (!c)
3601                     continue;          /* nonexistent channel */
3602                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
3603                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
3604                     continue;          /* extended but not stderr */
3605                 ssh2_pkt_getstring(&data, &length);
3606                 if (data) {
3607                     switch (c->type) {
3608                       case CHAN_MAINSESSION:
3609                         from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
3610                                      data, length);
3611                         break;
3612                       case CHAN_X11:
3613                         x11_send(c->u.x11.s, data, length);
3614                         break;
3615                       case CHAN_AGENT:
3616                         while (length > 0) {
3617                             if (c->u.a.lensofar < 4) {
3618                                 int l = min(4 - c->u.a.lensofar, length);
3619                                 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
3620                                 data += l; length -= l; c->u.a.lensofar += l;
3621                             }
3622                             if (c->u.a.lensofar == 4) {
3623                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
3624                                 c->u.a.message = smalloc(c->u.a.totallen);
3625                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
3626                             }
3627                             if (c->u.a.lensofar >= 4 && length > 0) {
3628                                 int l = min(c->u.a.totallen - c->u.a.lensofar,
3629                                             length);
3630                                 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
3631                                 data += l; length -= l; c->u.a.lensofar += l;
3632                             }
3633                             if (c->u.a.lensofar == c->u.a.totallen) {
3634                                 void *reply, *sentreply;
3635                                 int replylen;
3636                                 agent_query(c->u.a.message, c->u.a.totallen,
3637                                             &reply, &replylen);
3638                                 if (reply)
3639                                     sentreply = reply;
3640                                 else {
3641                                     /* Fake SSH_AGENT_FAILURE. */
3642                                     sentreply = "\0\0\0\1\5";
3643                                     replylen = 5;
3644                                 }
3645                                 ssh2_add_channel_data(c, sentreply, replylen);
3646                                 try_send = TRUE;
3647                                 if (reply)
3648                                     sfree(reply);
3649                                 sfree(c->u.a.message);
3650                                 c->u.a.lensofar = 0;
3651                             }
3652                         }
3653                         break;
3654                     }
3655                     /*
3656                      * Enlarge the window again at the remote
3657                      * side, just in case it ever runs down and
3658                      * they fail to send us any more data.
3659                      */
3660                     ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
3661                     ssh2_pkt_adduint32(c->remoteid);
3662                     ssh2_pkt_adduint32(length);
3663                     ssh2_pkt_send();
3664                 }
3665             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
3666                 ssh_state = SSH_STATE_CLOSED;
3667                 logevent("Received disconnect message");
3668                 crReturnV;
3669             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
3670                 continue;              /* exit status et al; ignore (FIXME?) */
3671             } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
3672                 unsigned i = ssh2_pkt_getuint32();
3673                 struct ssh_channel *c;
3674
3675                 c = find234(ssh_channels, &i, ssh_channelfind);
3676                 if (!c)
3677                     continue;          /* nonexistent channel */
3678                 
3679                 if (c->type == CHAN_X11) {
3680                     /*
3681                      * Remote EOF on an X11 channel means we should
3682                      * wrap up and close the channel ourselves.
3683                      */
3684                     x11_close(c->u.x11.s);
3685                     sshfwd_close(c);
3686                 } else if (c->type == CHAN_AGENT) {
3687                     sshfwd_close(c);
3688                 }
3689             } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
3690                 unsigned i = ssh2_pkt_getuint32();
3691                 struct ssh_channel *c;
3692                 enum234 e;
3693
3694                 c = find234(ssh_channels, &i, ssh_channelfind);
3695                 if (!c)
3696                     continue;          /* nonexistent channel */
3697                 if (c->closes == 0) {
3698                     ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3699                     ssh2_pkt_adduint32(c->remoteid);
3700                     ssh2_pkt_send();
3701                 }
3702                 /* Do pre-close processing on the channel. */
3703                 switch (c->type) {
3704                   case CHAN_MAINSESSION:
3705                     break;             /* nothing to see here, move along */
3706                   case CHAN_X11:
3707                     break;
3708                   case CHAN_AGENT:
3709                     break;
3710                 }
3711                 del234(ssh_channels, c);
3712                 sfree(c->v2.outbuffer);
3713                 sfree(c);
3714
3715                 /*
3716                  * See if that was the last channel left open.
3717                  */
3718                 c = first234(ssh_channels, &e);
3719                 if (!c) {
3720                     logevent("All channels closed. Disconnecting");
3721                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3722                     ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
3723                     ssh2_pkt_addstring("All open channels closed");
3724                     ssh2_pkt_addstring("en");   /* language tag */
3725                     ssh2_pkt_send();
3726                     ssh_state = SSH_STATE_CLOSED;
3727                     crReturnV;
3728                 }
3729                 continue;              /* remote sends close; ignore (FIXME) */
3730             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3731                 unsigned i = ssh2_pkt_getuint32();
3732                 struct ssh_channel *c;
3733                 c = find234(ssh_channels, &i, ssh_channelfind);
3734                 if (!c)
3735                     continue;          /* nonexistent channel */
3736                 mainchan->v2.remwindow += ssh2_pkt_getuint32();
3737                 try_send = TRUE;
3738             } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3739                 char *type;
3740                 int typelen;
3741                 char *error = NULL;
3742                 struct ssh_channel *c;
3743                 ssh2_pkt_getstring(&type, &typelen);
3744                 c = smalloc(sizeof(struct ssh_channel));
3745
3746                 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3747                     if (!ssh_X11_fwd_enabled)
3748                         error = "X11 forwarding is not enabled";
3749                     else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3750                         error = "Unable to open an X11 connection";
3751                     } else {
3752                         c->type = CHAN_X11;
3753                     }
3754                 } else if (typelen == 22 &&
3755                            !memcmp(type, "auth-agent@openssh.com", 3)) {
3756                     if (!ssh_agentfwd_enabled)
3757                         error = "Agent forwarding is not enabled";
3758                     else {
3759                         c->type = CHAN_AGENT;   /* identify channel type */
3760                         c->u.a.lensofar = 0;
3761                     }
3762                 } else {
3763                     error = "Unsupported channel type requested";
3764                 }
3765
3766                 c->remoteid = ssh2_pkt_getuint32();
3767                 if (error) {
3768                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3769                     ssh2_pkt_adduint32(c->remoteid);
3770                     ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3771                     ssh2_pkt_addstring(error);
3772                     ssh2_pkt_addstring("en");   /* language tag */
3773                     ssh2_pkt_send();
3774                     sfree(c);
3775                 } else {
3776                     struct ssh_channel *d;
3777                     unsigned i;
3778                     enum234 e;
3779
3780                     for (i=1, d = first234(ssh_channels, &e); d;
3781                          d = next234(&e)) {
3782                         if (d->localid > i)
3783                             break;     /* found a free number */
3784                         i = d->localid + 1;
3785                     }
3786                     c->localid = i;
3787                     c->closes = 0;
3788                     c->v2.remwindow = ssh2_pkt_getuint32();
3789                     c->v2.remmaxpkt = ssh2_pkt_getuint32();
3790                     c->v2.outbuffer = NULL;
3791                     c->v2.outbuflen = c->v2.outbufsize = 0;
3792                     add234(ssh_channels, c);
3793                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3794                     ssh2_pkt_adduint32(c->remoteid);
3795                     ssh2_pkt_adduint32(c->localid);
3796                     ssh2_pkt_adduint32(0x8000UL);  /* our window size */
3797                     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
3798                     ssh2_pkt_send();
3799                 }
3800             } else {
3801                 bombout(("Strange packet received: type %d", pktin.type));
3802                 crReturnV;
3803             }
3804         } else {
3805             /*
3806              * We have spare data. Add it to the channel buffer.
3807              */
3808             ssh2_add_channel_data(mainchan, in, inlen);
3809             try_send = TRUE;
3810         }
3811         if (try_send) {
3812             enum234 e;
3813             struct ssh_channel *c;
3814             /*
3815              * Try to send data on all channels if we can.
3816              */
3817             for (c = first234(ssh_channels, &e); c; c = next234(&e))
3818                 ssh2_try_send(c);
3819         }
3820     }
3821
3822     crFinishV;
3823 }
3824
3825 /*
3826  * Handle the top-level SSH2 protocol.
3827  */
3828 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3829 {
3830     if (do_ssh2_transport(in, inlen, ispkt) == 0)
3831         return;
3832     do_ssh2_authconn(in, inlen, ispkt);
3833 }
3834
3835 /*
3836  * Called to set up the connection.
3837  *
3838  * Returns an error message, or NULL on success.
3839  */
3840 static char *ssh_init (char *host, int port, char **realhost) {
3841     char *p;
3842         
3843 #ifdef MSCRYPTOAPI
3844     if(crypto_startup() == 0)
3845         return "Microsoft high encryption pack not installed!";
3846 #endif
3847
3848     ssh_send_ok = 0;
3849     ssh_editing = 0;
3850     ssh_echoing = 0;
3851
3852     p = connect_to_host(host, port, realhost);
3853     if (p != NULL)
3854         return p;
3855
3856     return NULL;
3857 }
3858
3859 /*
3860  * Called to send data down the Telnet connection.
3861  */
3862 static void ssh_send (char *buf, int len) {
3863     if (s == NULL || ssh_protocol == NULL)
3864         return;
3865
3866     ssh_protocol(buf, len, 0);
3867 }
3868
3869 /*
3870  * Called to set the size of the window from SSH's POV.
3871  */
3872 static void ssh_size(void) {
3873     switch (ssh_state) {
3874       case SSH_STATE_BEFORE_SIZE:
3875       case SSH_STATE_PREPACKET:
3876       case SSH_STATE_CLOSED:
3877         break;                         /* do nothing */
3878       case SSH_STATE_INTERMED:
3879         size_needed = TRUE;            /* buffer for later */
3880         break;
3881       case SSH_STATE_SESSION:
3882         if (!cfg.nopty) {
3883             if (ssh_version == 1) {
3884                 send_packet(SSH1_CMSG_WINDOW_SIZE,
3885                             PKT_INT, rows, PKT_INT, cols,
3886                             PKT_INT, 0, PKT_INT, 0, PKT_END);
3887             } else {
3888                 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3889                 ssh2_pkt_adduint32(mainchan->remoteid);
3890                 ssh2_pkt_addstring("window-change");
3891                 ssh2_pkt_addbool(0);
3892                 ssh2_pkt_adduint32(cols);
3893                 ssh2_pkt_adduint32(rows);
3894                 ssh2_pkt_adduint32(0);
3895                 ssh2_pkt_adduint32(0);
3896                 ssh2_pkt_send();
3897             }
3898         }
3899         break;
3900     }
3901 }
3902
3903 /*
3904  * Send Telnet special codes. TS_EOF is useful for `plink', so you
3905  * can send an EOF and collect resulting output (e.g. `plink
3906  * hostname sort').
3907  */
3908 static void ssh_special (Telnet_Special code) {
3909     if (code == TS_EOF) {
3910         if (ssh_state != SSH_STATE_SESSION) {
3911             /*
3912              * Buffer the EOF in case we are pre-SESSION, so we can
3913              * send it as soon as we reach SESSION.
3914              */
3915             if (code == TS_EOF)
3916                 eof_needed = TRUE;
3917             return;
3918         }
3919         if (ssh_version == 1) {
3920             send_packet(SSH1_CMSG_EOF, PKT_END);
3921         } else {
3922             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3923             ssh2_pkt_adduint32(mainchan->remoteid);
3924             ssh2_pkt_send();
3925         }
3926         logevent("Sent EOF message");
3927     } else if (code == TS_PING) {
3928         if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3929             return;
3930         if (ssh_version == 1) {
3931             send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3932         } else {
3933             ssh2_pkt_init(SSH2_MSG_IGNORE);
3934             ssh2_pkt_addstring_start();
3935             ssh2_pkt_send();
3936         }
3937     } else {
3938         /* do nothing */
3939     }
3940 }
3941
3942 static Socket ssh_socket(void) { return s; }
3943
3944 static int ssh_sendok(void) { return ssh_send_ok; }
3945
3946 static int ssh_ldisc(int option) {
3947     if (option == LD_ECHO) return ssh_echoing;
3948     if (option == LD_EDIT) return ssh_editing;
3949     return FALSE;
3950 }
3951
3952 Backend ssh_backend = {
3953     ssh_init,
3954     ssh_send,
3955     ssh_size,
3956     ssh_special,
3957     ssh_socket,
3958     ssh_sendok,
3959     ssh_ldisc,
3960     22
3961 };