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