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