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