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