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