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