]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
a842c4d0411611cec6a21a247501e557326a9dec
[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 : (void)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 = b[0];
873     p = smalloc(n * 2 + 1);
874     if (!p)
875         fatalbox("out of memory");
876     p[0] = 0;
877     for (i = 0; i < n; i++) {
878         p[i*2+1] = (b[n-i] >> 8) & 0xFF;
879         p[i*2+2] = (b[n-i]     ) & 0xFF;
880     }
881     i = 0;
882     while (p[i] == 0 && (p[i+1] & 0x80) == 0)
883         i++;
884     memmove(p, p+i, n*2+1-i);
885     *len = n*2+1-i;
886     return p;
887 }
888 static void ssh2_pkt_addmp(Bignum b) {
889     unsigned char *p;
890     int len;
891     p = ssh2_mpint_fmt(b, &len);
892     ssh2_pkt_addstring_start();
893     ssh2_pkt_addstring_data(p, len);
894     sfree(p);
895 }
896
897 /*
898  * Construct an SSH2 final-form packet: compress it, encrypt it,
899  * put the MAC on it. Final packet, ready to be sent, is stored in
900  * pktout.data. Total length is returned.
901  */
902 static int ssh2_pkt_construct(void) {
903     int cipherblk, maclen, padding, i;
904     static unsigned long outgoing_sequence = 0;
905
906     /*
907      * Compress packet payload.
908      */
909 #if 0
910     debug(("Pre-compression payload:\r\n"));
911     for (i = 5; i < pktout.length; i++)
912         debug(("  %02x", (unsigned char)pktout.data[i]));
913     debug(("\r\n"));
914 #endif
915     {
916         unsigned char *newpayload;
917         int newlen;
918         if (cscomp && cscomp->compress(pktout.data+5, pktout.length-5,
919                                        &newpayload, &newlen)) {
920             pktout.length = 5;
921             ssh2_pkt_adddata(newpayload, newlen);
922             sfree(newpayload);
923         }
924     }
925
926     /*
927      * Add padding. At least four bytes, and must also bring total
928      * length (minus MAC) up to a multiple of the block size.
929      */
930     cipherblk = cipher ? cipher->blksize : 8;   /* block size */
931     cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
932     padding = 4;
933     padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
934     maclen = csmac ? csmac->len : 0;
935     ssh2_pkt_ensure(pktout.length + padding + maclen);
936     pktout.data[4] = padding;
937     for (i = 0; i < padding; i++)
938         pktout.data[pktout.length + i] = random_byte();
939     PUT_32BIT(pktout.data, pktout.length + padding - 4);
940     if (csmac)
941         csmac->generate(pktout.data, pktout.length + padding,
942                         outgoing_sequence);
943     outgoing_sequence++;               /* whether or not we MACed */
944
945 #if 0
946     debug(("Sending packet len=%d\r\n", pktout.length+padding));
947     for (i = 0; i < pktout.length+padding; i++)
948         debug(("  %02x", (unsigned char)pktout.data[i]));
949     debug(("\r\n"));
950 #endif
951
952     if (cscipher)
953         cscipher->encrypt(pktout.data, pktout.length + padding);
954
955     /* Ready-to-send packet starts at pktout.data. We return length. */
956     return pktout.length + padding + maclen;
957 }
958
959 /*
960  * Construct and send an SSH2 packet immediately.
961  */
962 static void ssh2_pkt_send(void) {
963     int len = ssh2_pkt_construct();
964     sk_write(s, pktout.data, len);
965 }
966
967 /*
968  * Construct an SSH2 packet and add it to a deferred data block.
969  * Useful for sending multiple packets in a single sk_write() call,
970  * to prevent a traffic-analysing listener from being able to work
971  * out the length of any particular packet (such as the password
972  * packet).
973  * 
974  * Note that because SSH2 sequence-numbers its packets, this can
975  * NOT be used as an m4-style `defer' allowing packets to be
976  * constructed in one order and sent in another.
977  */
978 static void ssh2_pkt_defer(void) {
979     int len = ssh2_pkt_construct();
980     if (deferred_len + len > deferred_size) {
981         deferred_size = deferred_len + len + 128;
982         deferred_send_data = srealloc(deferred_send_data, deferred_size);
983     }
984     memcpy(deferred_send_data+deferred_len, pktout.data, len);
985     deferred_len += len;
986 }
987
988 /*
989  * Send the whole deferred data block constructed by
990  * ssh2_pkt_defer().
991  */
992 static void ssh2_pkt_defersend(void) {
993     sk_write(s, deferred_send_data, deferred_len);
994     deferred_len = deferred_size = 0;
995     sfree(deferred_send_data);
996     deferred_send_data = NULL;
997 }
998
999 #if 0
1000 void bndebug(char *string, Bignum b) {
1001     unsigned char *p;
1002     int i, len;
1003     p = ssh2_mpint_fmt(b, &len);
1004     debug(("%s", string));
1005     for (i = 0; i < len; i++)
1006         debug((" %02x", p[i]));
1007     debug(("\r\n"));
1008     sfree(p);
1009 }
1010 #endif
1011
1012 static void sha_mpint(SHA_State *s, Bignum b) {
1013     unsigned char *p;
1014     int len;
1015     p = ssh2_mpint_fmt(b, &len);
1016     sha_string(s, p, len);
1017     sfree(p);
1018 }
1019
1020 /*
1021  * SSH2 packet decode functions.
1022  */
1023 static unsigned long ssh2_pkt_getuint32(void) {
1024     unsigned long value;
1025     if (pktin.length - pktin.savedpos < 4)
1026         return 0;                      /* arrgh, no way to decline (FIXME?) */
1027     value = GET_32BIT(pktin.data+pktin.savedpos);
1028     pktin.savedpos += 4;
1029     return value;
1030 }
1031 static void ssh2_pkt_getstring(char **p, int *length) {
1032     *p = NULL;
1033     if (pktin.length - pktin.savedpos < 4)
1034         return;
1035     *length = GET_32BIT(pktin.data+pktin.savedpos);
1036     pktin.savedpos += 4;
1037     if (pktin.length - pktin.savedpos < *length)
1038         return;
1039     *p = pktin.data+pktin.savedpos;
1040     pktin.savedpos += *length;
1041 }
1042 static Bignum ssh2_pkt_getmp(void) {
1043     char *p;
1044     int i, j, length;
1045     Bignum b;
1046
1047     ssh2_pkt_getstring(&p, &length);
1048     if (!p)
1049         return NULL;
1050     if (p[0] & 0x80) {
1051         bombout(("internal error: Can't handle negative mpints"));
1052         return NULL;
1053     }
1054     b = newbn((length+1)/2);
1055     for (i = 0; i < length; i++) {
1056         j = length - 1 - i;
1057         if (j & 1)
1058             b[j/2+1] |= ((unsigned char)p[i]) << 8;
1059         else
1060             b[j/2+1] |= ((unsigned char)p[i]);
1061     }
1062     while (b[0] > 1 && b[b[0]] == 0) b[0]--;
1063     return b;
1064 }
1065
1066 static int do_ssh_init(unsigned char c) {
1067     static char *vsp;
1068     static char version[10];
1069     static char vstring[80];
1070     static char vlog[sizeof(vstring)+20];
1071     static int i;
1072
1073     crBegin;
1074
1075     /* Search for the string "SSH-" in the input. */
1076     i = 0;
1077     while (1) {
1078         static const int transS[] = { 1, 2, 2, 1 };
1079         static const int transH[] = { 0, 0, 3, 0 };
1080         static const int transminus[] = { 0, 0, 0, -1 };
1081         if (c == 'S') i = transS[i];
1082         else if (c == 'H') i = transH[i];
1083         else if (c == '-') i = transminus[i];
1084         else i = 0;
1085         if (i < 0)
1086             break;
1087         crReturn(1);                   /* get another character */
1088     }
1089
1090     strcpy(vstring, "SSH-");
1091     vsp = vstring+4;
1092     i = 0;
1093     while (1) {
1094         crReturn(1);                   /* get another char */
1095         if (vsp < vstring+sizeof(vstring)-1)
1096             *vsp++ = c;
1097         if (i >= 0) {
1098             if (c == '-') {
1099                 version[i] = '\0';
1100                 i = -1;
1101             } else if (i < sizeof(version)-1)
1102                 version[i++] = c;
1103         }
1104         else if (c == '\n')
1105             break;
1106     }
1107
1108     ssh_agentfwd_enabled = FALSE;
1109     rdpkt2_state.incoming_sequence = 0;
1110
1111     *vsp = 0;
1112     sprintf(vlog, "Server version: %s", vstring);
1113     vlog[strcspn(vlog, "\r\n")] = '\0';
1114     logevent(vlog);
1115
1116     /*
1117      * Server version "1.99" means we can choose whether we use v1
1118      * or v2 protocol. Choice is based on cfg.sshprot.
1119      */
1120     if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1121         /*
1122          * This is a v2 server. Begin v2 protocol.
1123          */
1124         char *verstring = "SSH-2.0-PuTTY";
1125         SHA_Init(&exhashbase);
1126         /*
1127          * Hash our version string and their version string.
1128          */
1129         sha_string(&exhashbase, verstring, strlen(verstring));
1130         sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1131         sprintf(vstring, "%s\n", verstring);
1132         sprintf(vlog, "We claim version: %s", verstring);
1133         logevent(vlog);
1134         logevent("Using SSH protocol version 2");
1135         sk_write(s, vstring, strlen(vstring));
1136         ssh_protocol = ssh2_protocol;
1137         ssh_version = 2;
1138         s_rdpkt = ssh2_rdpkt;
1139     } else {
1140         /*
1141          * This is a v1 server. Begin v1 protocol.
1142          */
1143         sprintf(vstring, "SSH-%s-PuTTY\n",
1144                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1145         sprintf(vlog, "We claim version: %s", vstring);
1146         vlog[strcspn(vlog, "\r\n")] = '\0';
1147         logevent(vlog);
1148         logevent("Using SSH protocol version 1");
1149         sk_write(s, vstring, strlen(vstring));
1150         ssh_protocol = ssh1_protocol;
1151         ssh_version = 1;
1152         s_rdpkt = ssh1_rdpkt;
1153     }
1154     ssh_state = SSH_STATE_BEFORE_SIZE;
1155
1156     crFinish(0);
1157 }
1158
1159 static void ssh_gotdata(unsigned char *data, int datalen)
1160 {
1161     crBegin;
1162
1163     /*
1164      * To begin with, feed the characters one by one to the
1165      * protocol initialisation / selection function do_ssh_init().
1166      * When that returns 0, we're done with the initial greeting
1167      * exchange and can move on to packet discipline.
1168      */
1169     while (1) {
1170         int ret;
1171         if (datalen == 0)
1172             crReturnV;                 /* more data please */
1173         ret = do_ssh_init(*data);
1174         data++; datalen--;
1175         if (ret == 0)
1176             break;
1177     }
1178
1179     /*
1180      * We emerge from that loop when the initial negotiation is
1181      * over and we have selected an s_rdpkt function. Now pass
1182      * everything to s_rdpkt, and then pass the resulting packets
1183      * to the proper protocol handler.
1184      */
1185     if (datalen == 0)
1186         crReturnV;
1187     while (1) {
1188         while (datalen > 0) {
1189             if ( s_rdpkt(&data, &datalen) == 0 ) {
1190                 ssh_protocol(NULL, 0, 1);
1191                 if (ssh_state == SSH_STATE_CLOSED) {
1192                     return;
1193                 }
1194             }
1195         }
1196         crReturnV;
1197     }
1198     crFinishV;
1199 }
1200
1201 static int ssh_receive(Socket skt, int urgent, char *data, int len) {
1202     if (urgent==3) {
1203         /* A socket error has occurred. */
1204         ssh_state = SSH_STATE_CLOSED;
1205         sk_close(s);
1206         s = NULL;
1207         connection_fatal(data);
1208         return 0;
1209     } else if (!len) {
1210         /* Connection has closed. */
1211         ssh_state = SSH_STATE_CLOSED;
1212         sk_close(s);
1213         s = NULL;
1214         return 0;
1215     }
1216     ssh_gotdata (data, len);
1217     if (ssh_state == SSH_STATE_CLOSED) {
1218         if (s) {
1219             sk_close(s);
1220             s = NULL;
1221         }
1222         return 0;
1223     }
1224     return 1;
1225 }
1226
1227 /*
1228  * Connect to specified host and port.
1229  * Returns an error message, or NULL on success.
1230  * Also places the canonical host name into `realhost'.
1231  */
1232 static char *connect_to_host(char *host, int port, char **realhost)
1233 {
1234     SockAddr addr;
1235     char *err;
1236 #ifdef FWHACK
1237     char *FWhost;
1238     int FWport;
1239 #endif
1240
1241     savedhost = smalloc(1+strlen(host));
1242     if (!savedhost)
1243         fatalbox("Out of memory");
1244     strcpy(savedhost, host);
1245
1246     if (port < 0)
1247         port = 22;                     /* default ssh port */
1248     savedport = port;
1249
1250 #ifdef FWHACK
1251     FWhost = host;
1252     FWport = port;
1253     host = FWSTR;
1254     port = 23;
1255 #endif
1256
1257     /*
1258      * Try to find host.
1259      */
1260     addr = sk_namelookup(host, realhost);
1261     if ( (err = sk_addr_error(addr)) )
1262         return err;
1263
1264 #ifdef FWHACK
1265     *realhost = FWhost;
1266 #endif
1267
1268     /*
1269      * Open socket.
1270      */
1271     s = sk_new(addr, port, 0, 1, ssh_receive);
1272     if ( (err = sk_socket_error(s)) )
1273         return err;
1274
1275 #ifdef FWHACK
1276     sk_write(s, "connect ", 8);
1277     sk_write(s, FWhost, strlen(FWhost));
1278     {
1279         char buf[20];
1280         sprintf(buf, " %d\n", FWport);
1281         sk_write(s, buf, strlen(buf));
1282     }
1283 #endif
1284
1285     return NULL;
1286 }
1287
1288 /*
1289  * Handle the key exchange and user authentication phases.
1290  */
1291 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1292 {
1293     int i, j, len;
1294     unsigned char *rsabuf, *keystr1, *keystr2;
1295     unsigned char cookie[8];
1296     struct RSAKey servkey, hostkey;
1297     struct MD5Context md5c;
1298     static unsigned long supported_ciphers_mask, supported_auths_mask;
1299     static int tried_publickey;
1300     static unsigned char session_id[16];
1301     int cipher_type;
1302     static char username[100];
1303
1304     crBegin;
1305
1306     if (!ispkt) crWaitUntil(ispkt);
1307
1308     if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1309         bombout(("Public key packet not received"));
1310         crReturn(0);
1311     }
1312
1313     logevent("Received public keys");
1314
1315     memcpy(cookie, pktin.body, 8);
1316
1317     i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1318     j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1319
1320     /*
1321      * Log the host key fingerprint.
1322      */
1323     {
1324         char logmsg[80];
1325         logevent("Host key fingerprint is:");
1326         strcpy(logmsg, "      ");
1327         hostkey.comment = NULL;
1328         rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1329                         &hostkey);
1330         logevent(logmsg);
1331     }
1332
1333     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1334     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1335
1336     MD5Init(&md5c);
1337     MD5Update(&md5c, keystr2, hostkey.bytes);
1338     MD5Update(&md5c, keystr1, servkey.bytes);
1339     MD5Update(&md5c, pktin.body, 8);
1340     MD5Final(session_id, &md5c);
1341
1342     for (i=0; i<32; i++)
1343         session_key[i] = random_byte();
1344
1345     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1346
1347     rsabuf = smalloc(len);
1348     if (!rsabuf)
1349         fatalbox("Out of memory");
1350
1351     /*
1352      * Verify the host key.
1353      */
1354     {
1355         /*
1356          * First format the key into a string.
1357          */
1358         int len = rsastr_len(&hostkey);
1359         char fingerprint[100];
1360         char *keystr = smalloc(len);
1361         if (!keystr)
1362             fatalbox("Out of memory");
1363         rsastr_fmt(keystr, &hostkey);
1364         rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1365         verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1366         sfree(keystr);
1367     }
1368
1369     for (i=0; i<32; i++) {
1370         rsabuf[i] = session_key[i];
1371         if (i < 16)
1372             rsabuf[i] ^= session_id[i];
1373     }
1374
1375     if (hostkey.bytes > servkey.bytes) {
1376         rsaencrypt(rsabuf, 32, &servkey);
1377         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1378     } else {
1379         rsaencrypt(rsabuf, 32, &hostkey);
1380         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1381     }
1382
1383     logevent("Encrypted session key");
1384
1385     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1386                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
1387                   SSH_CIPHER_3DES;
1388     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1389         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1390         cipher_type = SSH_CIPHER_3DES;
1391     }
1392     switch (cipher_type) {
1393       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1394       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1395       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1396     }
1397
1398     send_packet(SSH1_CMSG_SESSION_KEY,
1399                 PKT_CHAR, cipher_type,
1400                 PKT_DATA, cookie, 8,
1401                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1402                 PKT_DATA, rsabuf, len,
1403                 PKT_INT, 0,
1404                 PKT_END);
1405
1406     logevent("Trying to enable encryption...");
1407
1408     sfree(rsabuf);
1409
1410     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1411              cipher_type == SSH_CIPHER_DES ? &ssh_des :
1412              &ssh_3des;
1413     cipher->sesskey(session_key);
1414
1415     crWaitUntil(ispkt);
1416
1417     if (pktin.type != SSH1_SMSG_SUCCESS) {
1418         bombout(("Encryption not successfully enabled"));
1419         crReturn(0);
1420     }
1421
1422     logevent("Successfully started encryption");
1423
1424     fflush(stdout);
1425     {
1426         static int pos = 0;
1427         static char c;
1428         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1429             c_write("login as: ", 10);
1430             ssh_send_ok = 1;
1431             while (pos >= 0) {
1432                 crWaitUntil(!ispkt);
1433                 while (inlen--) switch (c = *in++) {
1434                   case 10: case 13:
1435                     username[pos] = 0;
1436                     pos = -1;
1437                     break;
1438                   case 8: case 127:
1439                     if (pos > 0) {
1440                         c_write("\b \b", 3);
1441                         pos--;
1442                     }
1443                     break;
1444                   case 21: case 27:
1445                     while (pos > 0) {
1446                         c_write("\b \b", 3);
1447                         pos--;
1448                     }
1449                     break;
1450                   case 3: case 4:
1451                     random_save_seed();
1452                     exit(0);
1453                     break;
1454                   default:
1455                     if (((c >= ' ' && c <= '~') ||
1456                          ((unsigned char)c >= 160)) && pos < 40) {
1457                         username[pos++] = c;
1458                         c_write(&c, 1);
1459                     }
1460                     break;
1461                 }
1462             }
1463             c_write("\r\n", 2);
1464             username[strcspn(username, "\n\r")] = '\0';
1465         } else {
1466             strncpy(username, cfg.username, 99);
1467             username[99] = '\0';
1468         }
1469
1470         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1471         {
1472             char userlog[22+sizeof(username)];
1473             sprintf(userlog, "Sent username \"%s\"", username);
1474             logevent(userlog);
1475             if (flags & FLAG_INTERACTIVE &&
1476                 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
1477                 strcat(userlog, "\r\n");
1478                 c_write(userlog, strlen(userlog));
1479             }
1480         }
1481     }
1482
1483     crWaitUntil(ispkt);
1484
1485     tried_publickey = 0;
1486
1487     while (pktin.type == SSH1_SMSG_FAILURE) {
1488         static char password[100];
1489         static char prompt[200];
1490         static int pos;
1491         static char c;
1492         static int pwpkt_type;
1493         /*
1494          * Show password prompt, having first obtained it via a TIS
1495          * or CryptoCard exchange if we're doing TIS or CryptoCard
1496          * authentication.
1497          */
1498         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1499         if (agent_exists()) {
1500             /*
1501              * Attempt RSA authentication using Pageant.
1502              */
1503             static unsigned char request[5], *response, *p;
1504             static int responselen;
1505             static int i, nkeys;
1506             static int authed = FALSE;
1507             void *r;
1508
1509             logevent("Pageant is running. Requesting keys.");
1510
1511             /* Request the keys held by the agent. */
1512             PUT_32BIT(request, 1);
1513             request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1514             agent_query(request, 5, &r, &responselen);
1515             response = (unsigned char *)r;
1516             if (response) {
1517                 p = response + 5;
1518                 nkeys = GET_32BIT(p); p += 4;
1519                 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1520                     logevent(buf); }
1521                 for (i = 0; i < nkeys; i++) {
1522                     static struct RSAKey key;
1523                     static Bignum challenge;
1524                     static char *commentp;
1525                     static int commentlen;
1526
1527                     { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1528                         logevent(buf); }
1529                     p += 4;
1530                     p += ssh1_read_bignum(p, &key.exponent);
1531                     p += ssh1_read_bignum(p, &key.modulus);
1532                     commentlen = GET_32BIT(p); p += 4;
1533                     commentp = p; p += commentlen;
1534                     send_packet(SSH1_CMSG_AUTH_RSA,
1535                                 PKT_BIGNUM, key.modulus, PKT_END);
1536                     crWaitUntil(ispkt);
1537                     if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1538                         logevent("Key refused");
1539                         continue;
1540                     }
1541                     logevent("Received RSA challenge");
1542                     ssh1_read_bignum(pktin.body, &challenge);
1543                     {
1544                         char *agentreq, *q, *ret;
1545                         int len, retlen;
1546                         len = 1 + 4;   /* message type, bit count */
1547                         len += ssh1_bignum_length(key.exponent);
1548                         len += ssh1_bignum_length(key.modulus);
1549                         len += ssh1_bignum_length(challenge);
1550                         len += 16;     /* session id */
1551                         len += 4;      /* response format */
1552                         agentreq = smalloc(4 + len);
1553                         PUT_32BIT(agentreq, len);
1554                         q = agentreq + 4;
1555                         *q++ = SSH_AGENTC_RSA_CHALLENGE;
1556                         PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1557                         q += 4;
1558                         q += ssh1_write_bignum(q, key.exponent);
1559                         q += ssh1_write_bignum(q, key.modulus);
1560                         q += ssh1_write_bignum(q, challenge);
1561                         memcpy(q, session_id, 16); q += 16;
1562                         PUT_32BIT(q, 1);   /* response format */
1563                         agent_query(agentreq, len+4, &ret, &retlen);
1564                         sfree(agentreq);
1565                         if (ret) {
1566                             if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1567                                 logevent("Sending Pageant's response");
1568                                 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1569                                             PKT_DATA, ret+5, 16, PKT_END);
1570                                 sfree(ret);
1571                                 crWaitUntil(ispkt);
1572                                 if (pktin.type == SSH1_SMSG_SUCCESS) {
1573                                     logevent("Pageant's response accepted");
1574                                     if (flags & FLAG_VERBOSE) {
1575                                         c_write("Authenticated using RSA key \"",
1576                                                 29);
1577                                         c_write(commentp, commentlen);
1578                                         c_write("\" from agent\r\n", 14);
1579                                     }
1580                                     authed = TRUE;
1581                                 } else
1582                                     logevent("Pageant's response not accepted");
1583                             } else {
1584                                 logevent("Pageant failed to answer challenge");
1585                                 sfree(ret);
1586                             }
1587                         } else {
1588                             logevent("No reply received from Pageant");
1589                         }
1590                     }
1591                     freebn(key.exponent);
1592                     freebn(key.modulus);
1593                     freebn(challenge);
1594                     if (authed)
1595                         break;
1596                 }
1597             }
1598             if (authed)
1599                 break;
1600         }
1601         if (*cfg.keyfile && !tried_publickey)
1602             pwpkt_type = SSH1_CMSG_AUTH_RSA;
1603
1604         if (pktin.type == SSH1_SMSG_FAILURE &&
1605             cfg.try_tis_auth &&
1606             (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1607             pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1608             logevent("Requested TIS authentication");
1609             send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1610             crWaitUntil(ispkt);
1611             if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1612                 logevent("TIS authentication declined");
1613                 if (flags & FLAG_INTERACTIVE)
1614                     c_write("TIS authentication refused.\r\n", 29);
1615             } else {
1616                 int challengelen = ((pktin.body[0] << 24) |
1617                                     (pktin.body[1] << 16) |
1618                                     (pktin.body[2] << 8) |
1619                                     (pktin.body[3]));
1620                 logevent("Received TIS challenge");
1621                 if (challengelen > sizeof(prompt)-1)
1622                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1623                 memcpy(prompt, pktin.body+4, challengelen);
1624                 prompt[challengelen] = '\0';
1625             }
1626         }
1627         if (pktin.type == SSH1_SMSG_FAILURE &&
1628             cfg.try_tis_auth &&
1629             (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1630             pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1631             logevent("Requested CryptoCard authentication");
1632             send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1633             crWaitUntil(ispkt);
1634             if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1635                 logevent("CryptoCard authentication declined");
1636                 c_write("CryptoCard authentication refused.\r\n", 29);
1637             } else {
1638                 int challengelen = ((pktin.body[0] << 24) |
1639                                     (pktin.body[1] << 16) |
1640                                     (pktin.body[2] << 8) |
1641                                     (pktin.body[3]));
1642                 logevent("Received CryptoCard challenge");
1643                 if (challengelen > sizeof(prompt)-1)
1644                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1645                 memcpy(prompt, pktin.body+4, challengelen);
1646                 strncpy(prompt + challengelen, "\r\nResponse : ",
1647                         sizeof(prompt)-challengelen);
1648                 prompt[sizeof(prompt)-1] = '\0';
1649             }
1650         }
1651         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1652             sprintf(prompt, "%.90s@%.90s's password: ",
1653                     username, savedhost);
1654         }
1655         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1656             char *comment = NULL;
1657             if (flags & FLAG_VERBOSE)
1658                 c_write("Trying public key authentication.\r\n", 35);
1659             if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1660                 if (flags & FLAG_VERBOSE)
1661                     c_write("No passphrase required.\r\n", 25);
1662                 goto tryauth;
1663             }
1664             sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1665             sfree(comment);
1666         }
1667
1668         if (ssh_get_password) {
1669             if (!ssh_get_password(prompt, password, sizeof(password))) {
1670                 /*
1671                  * get_password failed to get a password (for
1672                  * example because one was supplied on the command
1673                  * line which has already failed to work).
1674                  * Terminate.
1675                  */
1676                 logevent("No more passwords to try");
1677                 ssh_state = SSH_STATE_CLOSED;
1678                 crReturn(1);
1679             }
1680         } else {
1681             c_write(prompt, strlen(prompt));
1682             pos = 0;
1683             ssh_send_ok = 1;
1684             while (pos >= 0) {
1685                 crWaitUntil(!ispkt);
1686                 while (inlen--) switch (c = *in++) {
1687                   case 10: case 13:
1688                     password[pos] = 0;
1689                     pos = -1;
1690                     break;
1691                   case 8: case 127:
1692                     if (pos > 0)
1693                         pos--;
1694                     break;
1695                   case 21: case 27:
1696                     pos = 0;
1697                     break;
1698                   case 3: case 4:
1699                     random_save_seed();
1700                     exit(0);
1701                     break;
1702                   default:
1703                     if (((c >= ' ' && c <= '~') ||
1704                          ((unsigned char)c >= 160)) && pos < sizeof(password))
1705                         password[pos++] = c;
1706                     break;
1707                 }
1708             }
1709             c_write("\r\n", 2);
1710         }
1711
1712         tryauth:
1713         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1714             /*
1715              * Try public key authentication with the specified
1716              * key file.
1717              */
1718             static struct RSAKey pubkey;
1719             static Bignum challenge, response;
1720             static int i;
1721             static unsigned char buffer[32];
1722
1723             tried_publickey = 1;
1724             i = loadrsakey(cfg.keyfile, &pubkey, NULL, password);
1725             if (i == 0) {
1726                 c_write("Couldn't load public key from ", 30);
1727                 c_write(cfg.keyfile, strlen(cfg.keyfile));
1728                 c_write(".\r\n", 3);
1729                 continue;              /* go and try password */
1730             }
1731             if (i == -1) {
1732                 c_write("Wrong passphrase.\r\n", 19);
1733                 tried_publickey = 0;
1734                 continue;              /* try again */
1735             }
1736
1737             /*
1738              * Send a public key attempt.
1739              */
1740             send_packet(SSH1_CMSG_AUTH_RSA,
1741                         PKT_BIGNUM, pubkey.modulus, PKT_END);
1742
1743             crWaitUntil(ispkt);
1744             if (pktin.type == SSH1_SMSG_FAILURE) {
1745                 c_write("Server refused our public key.\r\n", 32);
1746                 continue;              /* go and try password */
1747             }
1748             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1749                 bombout(("Bizarre response to offer of public key"));
1750                 crReturn(0);
1751             }
1752             ssh1_read_bignum(pktin.body, &challenge);
1753             response = rsadecrypt(challenge, &pubkey);
1754             freebn(pubkey.private_exponent);   /* burn the evidence */
1755
1756             for (i = 0; i < 32; i += 2) {
1757                 buffer[i] = response[16-i/2] >> 8;
1758                 buffer[i+1] = response[16-i/2] & 0xFF;
1759             }
1760
1761             MD5Init(&md5c);
1762             MD5Update(&md5c, buffer, 32);
1763             MD5Update(&md5c, session_id, 16);
1764             MD5Final(buffer, &md5c);
1765
1766             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1767                         PKT_DATA, buffer, 16, PKT_END);
1768
1769             crWaitUntil(ispkt);
1770             if (pktin.type == SSH1_SMSG_FAILURE) {
1771                 if (flags & FLAG_VERBOSE)
1772                     c_write("Failed to authenticate with our public key.\r\n",
1773                             45);
1774                 continue;              /* go and try password */
1775             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1776                 bombout(("Bizarre response to RSA authentication response"));
1777                 crReturn(0);
1778             }
1779
1780             break;                     /* we're through! */
1781         } else {
1782             send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1783         }
1784         logevent("Sent password");
1785         memset(password, 0, strlen(password));
1786         crWaitUntil(ispkt);
1787         if (pktin.type == SSH1_SMSG_FAILURE) {
1788             if (flags & FLAG_VERBOSE)
1789                 c_write("Access denied\r\n", 15);
1790             logevent("Authentication refused");
1791         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1792             logevent("Received disconnect request");
1793             ssh_state = SSH_STATE_CLOSED;
1794             crReturn(1);
1795         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1796             bombout(("Strange packet received, type %d", pktin.type));
1797             crReturn(0);
1798         }
1799     }
1800
1801     logevent("Authentication successful");
1802
1803     crFinish(1);
1804 }
1805
1806 void sshfwd_close(struct ssh_channel *c) {
1807     if (c) {
1808         if (ssh_version == 1) {
1809             send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END);
1810         } else {
1811             ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
1812             ssh2_pkt_adduint32(c->remoteid);
1813             ssh2_pkt_send();
1814         }
1815         c->closes = 1;
1816         if (c->type == CHAN_X11) {
1817             c->u.x11.s = NULL;
1818             logevent("X11 connection terminated");
1819         }
1820     }
1821 }
1822
1823 void sshfwd_write(struct ssh_channel *c, char *buf, int len) {
1824     if (ssh_version == 1) {
1825         send_packet(SSH1_MSG_CHANNEL_DATA,
1826                     PKT_INT, c->remoteid,
1827                     PKT_INT, len,
1828                     PKT_DATA, buf, len,
1829                     PKT_END);
1830     } else {
1831         ssh2_add_channel_data(c, buf, len);
1832         ssh2_try_send(c);
1833     }
1834 }
1835
1836 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1837     crBegin;
1838
1839     random_init();
1840
1841     while (!do_ssh1_login(in, inlen, ispkt)) {
1842         crReturnV;
1843     }
1844     if (ssh_state == SSH_STATE_CLOSED)
1845         crReturnV;
1846
1847     if (cfg.agentfwd && agent_exists()) {
1848         logevent("Requesting agent forwarding");
1849         send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1850         do { crReturnV; } while (!ispkt);
1851         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1852             bombout(("Protocol confusion"));
1853             crReturnV;
1854         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1855             logevent("Agent forwarding refused");
1856         } else {
1857             logevent("Agent forwarding enabled");
1858             ssh_agentfwd_enabled = TRUE;
1859         }
1860     }
1861
1862     if (cfg.x11_forward) {
1863         char proto[20], data[64];
1864         logevent("Requesting X11 forwarding");
1865         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
1866         send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING, 
1867                     PKT_STR, proto, PKT_STR, data,
1868                     PKT_INT, 0,
1869                     PKT_END);
1870         do { crReturnV; } while (!ispkt);
1871         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1872             bombout(("Protocol confusion"));
1873             crReturnV;
1874         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1875             logevent("X11 forwarding refused");
1876         } else {
1877             logevent("X11 forwarding enabled");
1878             ssh_X11_fwd_enabled = TRUE;
1879         }
1880     }
1881
1882     if (!cfg.nopty) {
1883         send_packet(SSH1_CMSG_REQUEST_PTY,
1884                     PKT_STR, cfg.termtype,
1885                     PKT_INT, rows, PKT_INT, cols,
1886                     PKT_INT, 0, PKT_INT, 0,
1887                     PKT_CHAR, 0,
1888                     PKT_END);
1889         ssh_state = SSH_STATE_INTERMED;
1890         do { crReturnV; } while (!ispkt);
1891         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1892             bombout(("Protocol confusion"));
1893             crReturnV;
1894         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1895             c_write("Server refused to allocate pty\r\n", 32);
1896             ssh_editing = ssh_echoing = 1;
1897         }
1898         logevent("Allocated pty");
1899     } else {
1900         ssh_editing = ssh_echoing = 1;
1901     }
1902
1903     if (cfg.compression) {
1904         send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
1905         do { crReturnV; } while (!ispkt);
1906         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1907             bombout(("Protocol confusion"));
1908             crReturnV;
1909         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1910             c_write("Server refused to compress\r\n", 32);
1911         }
1912         logevent("Started compression");
1913         ssh1_compressing = TRUE;
1914         zlib_compress_init();
1915         zlib_decompress_init();
1916     }
1917
1918     if (*cfg.remote_cmd)
1919         send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1920     else
1921         send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1922     logevent("Started session");
1923
1924     ssh_state = SSH_STATE_SESSION;
1925     if (size_needed)
1926         ssh_size();
1927     if (eof_needed)
1928         ssh_special(TS_EOF);
1929
1930     ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
1931     ssh_send_ok = 1;
1932     ssh_channels = newtree234(ssh_channelcmp);
1933     while (1) {
1934         crReturnV;
1935         if (ispkt) {
1936             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1937                 pktin.type == SSH1_SMSG_STDERR_DATA) {
1938                 long len = GET_32BIT(pktin.body);
1939                 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
1940                              pktin.body+4, len);
1941             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1942                 ssh_state = SSH_STATE_CLOSED;
1943                 logevent("Received disconnect request");
1944                 crReturnV;
1945             } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
1946                 /* Remote side is trying to open a channel to talk to our
1947                  * X-Server. Give them back a local channel number. */
1948                 unsigned i;
1949                 struct ssh_channel *c, *d;
1950                 enum234 e;
1951
1952                 logevent("Received X11 connect request");
1953                 /* Refuse if X11 forwarding is disabled. */
1954                 if (!ssh_X11_fwd_enabled) {
1955                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1956                                 PKT_INT, GET_32BIT(pktin.body),
1957                                 PKT_END);
1958                     logevent("Rejected X11 connect request");
1959                 } else {
1960                     c = smalloc(sizeof(struct ssh_channel));
1961
1962                     if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
1963                       logevent("opening X11 forward connection failed");
1964                       sfree(c);
1965                       send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1966                                   PKT_INT, GET_32BIT(pktin.body),
1967                                   PKT_END);
1968                     } else {
1969                       logevent("opening X11 forward connection succeeded");
1970                       for (i=1, d = first234(ssh_channels, &e); d; d = next234(&e)) {
1971                           if (d->localid > i)
1972                               break;     /* found a free number */
1973                           i = d->localid + 1;
1974                       }
1975                       c->remoteid = GET_32BIT(pktin.body);
1976                       c->localid = i;
1977                       c->closes = 0;
1978                       c->type = CHAN_X11;   /* identify channel type */
1979                       add234(ssh_channels, c);
1980                       send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1981                                   PKT_INT, c->remoteid, PKT_INT, c->localid,
1982                                   PKT_END);
1983                       logevent("Opened X11 forward channel");
1984                     }
1985                 }
1986             } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1987                 /* Remote side is trying to open a channel to talk to our
1988                  * agent. Give them back a local channel number. */
1989                 unsigned i;
1990                 struct ssh_channel *c;
1991                 enum234 e;
1992
1993                 /* Refuse if agent forwarding is disabled. */
1994                 if (!ssh_agentfwd_enabled) {
1995                     send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
1996                                 PKT_INT, GET_32BIT(pktin.body),
1997                                 PKT_END);
1998                 } else {
1999                     i = 1;
2000                     for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
2001                         if (c->localid > i)
2002                             break;     /* found a free number */
2003                         i = c->localid + 1;
2004                     }
2005                     c = smalloc(sizeof(struct ssh_channel));
2006                     c->remoteid = GET_32BIT(pktin.body);
2007                     c->localid = i;
2008                     c->closes = 0;
2009                     c->type = CHAN_AGENT;   /* identify channel type */
2010                     c->u.a.lensofar = 0;
2011                     add234(ssh_channels, c);
2012                     send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
2013                                 PKT_INT, c->remoteid, PKT_INT, c->localid,
2014                                 PKT_END);
2015                 }
2016             } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
2017                        pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
2018                 /* Remote side closes a channel. */
2019                 unsigned i = GET_32BIT(pktin.body);
2020                 struct ssh_channel *c;
2021                 c = find234(ssh_channels, &i, ssh_channelfind);
2022                 if (c) {
2023                     int closetype;
2024                     closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
2025                     send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
2026                     if ((c->closes == 0) && (c->type == CHAN_X11)) {
2027                         logevent("X11 connection closed");
2028                         assert(c->u.x11.s != NULL);
2029                         x11_close(c->u.x11.s);
2030                         c->u.x11.s = NULL;
2031                     }
2032                     c->closes |= closetype;
2033                     if (c->closes == 3) {
2034                         del234(ssh_channels, c);
2035                         sfree(c);
2036                     }
2037                 }
2038             } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
2039                 /* Data sent down one of our channels. */
2040                 int i = GET_32BIT(pktin.body);
2041                 int len = GET_32BIT(pktin.body+4);
2042                 unsigned char *p = pktin.body+8;
2043                 struct ssh_channel *c;
2044                 c = find234(ssh_channels, &i, ssh_channelfind);
2045                 if (c) {
2046                     switch(c->type) {
2047                       case CHAN_X11:
2048                         x11_send(c->u.x11.s, p, len);
2049                         break;
2050                       case CHAN_AGENT:
2051                         /* Data for an agent message. Buffer it. */
2052                         while (len > 0) {
2053                             if (c->u.a.lensofar < 4) {
2054                                 int l = min(4 - c->u.a.lensofar, len);
2055                                 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
2056                                 p += l; len -= l; c->u.a.lensofar += l;
2057                             }
2058                             if (c->u.a.lensofar == 4) {
2059                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
2060                                 c->u.a.message = smalloc(c->u.a.totallen);
2061                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
2062                             }
2063                             if (c->u.a.lensofar >= 4 && len > 0) {
2064                                 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
2065                                 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
2066                                 p += l; len -= l; c->u.a.lensofar += l;
2067                             }
2068                             if (c->u.a.lensofar == c->u.a.totallen) {
2069                                 void *reply, *sentreply;
2070                                 int replylen;
2071                                 agent_query(c->u.a.message, c->u.a.totallen,
2072                                             &reply, &replylen);
2073                                 if (reply)
2074                                     sentreply = reply;
2075                                 else {
2076                                     /* Fake SSH_AGENT_FAILURE. */
2077                                     sentreply = "\0\0\0\1\5";
2078                                     replylen = 5;
2079                                 }
2080                                 send_packet(SSH1_MSG_CHANNEL_DATA,
2081                                             PKT_INT, c->remoteid,
2082                                             PKT_INT, replylen,
2083                                             PKT_DATA, sentreply, replylen,
2084                                             PKT_END);
2085                                 if (reply)
2086                                     sfree(reply);
2087                                 sfree(c->u.a.message);
2088                                 c->u.a.lensofar = 0;
2089                             }
2090                         }
2091                         break;
2092                     }
2093                 }                
2094             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
2095                 /* may be from EXEC_SHELL on some servers */
2096             } else if (pktin.type == SSH1_SMSG_FAILURE) {
2097                 /* may be from EXEC_SHELL on some servers
2098                  * if no pty is available or in other odd cases. Ignore */
2099             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
2100                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
2101             } else {
2102                 bombout(("Strange packet received: type %d", pktin.type));
2103                 crReturnV;
2104             }
2105         } else {
2106             while (inlen > 0) {
2107                 int len = min(inlen, 512);
2108                 send_packet(SSH1_CMSG_STDIN_DATA,
2109                             PKT_INT, len, PKT_DATA, in, len, PKT_END);
2110                 in += len;
2111                 inlen -= len;
2112             }
2113         }
2114     }
2115
2116     crFinishV;
2117 }
2118
2119 /*
2120  * Utility routine for decoding comma-separated strings in KEXINIT.
2121  */
2122 static int in_commasep_string(char *needle, char *haystack, int haylen) {
2123     int needlen = strlen(needle);
2124     while (1) {
2125         /*
2126          * Is it at the start of the string?
2127          */
2128         if (haylen >= needlen &&       /* haystack is long enough */
2129             !memcmp(needle, haystack, needlen) &&    /* initial match */
2130             (haylen == needlen || haystack[needlen] == ',')
2131                                        /* either , or EOS follows */
2132             )
2133             return 1;
2134         /*
2135          * If not, search for the next comma and resume after that.
2136          * If no comma found, terminate.
2137          */
2138         while (haylen > 0 && *haystack != ',')
2139             haylen--, haystack++;
2140         if (haylen == 0)
2141             return 0;
2142         haylen--, haystack++;          /* skip over comma itself */
2143     }
2144 }
2145
2146 /*
2147  * SSH2 key creation method.
2148  */
2149 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr, char *keyspace) {
2150     SHA_State s;
2151     /* First 20 bytes. */
2152     SHA_Init(&s);
2153     sha_mpint(&s, K);
2154     SHA_Bytes(&s, H, 20);
2155     SHA_Bytes(&s, &chr, 1);
2156     SHA_Bytes(&s, sessid, 20);
2157     SHA_Final(&s, keyspace);
2158     /* Next 20 bytes. */
2159     SHA_Init(&s);
2160     sha_mpint(&s, K);
2161     SHA_Bytes(&s, H, 20);
2162     SHA_Bytes(&s, keyspace, 20);
2163     SHA_Final(&s, keyspace+20);
2164 }
2165
2166 /*
2167  * Handle the SSH2 transport layer.
2168  */
2169 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
2170 {
2171     static int i, len;
2172     static char *str;
2173     static Bignum e, f, K;
2174     static const struct ssh_mac **maclist;
2175     static int nmacs;
2176     static const struct ssh_cipher *cscipher_tobe = NULL;
2177     static const struct ssh_cipher *sccipher_tobe = NULL;
2178     static const struct ssh_mac *csmac_tobe = NULL;
2179     static const struct ssh_mac *scmac_tobe = NULL;
2180     static const struct ssh_compress *cscomp_tobe = NULL;
2181     static const struct ssh_compress *sccomp_tobe = NULL;
2182     static char *hostkeydata, *sigdata, *keystr, *fingerprint;
2183     static int hostkeylen, siglen;
2184     static void *hkey;                 /* actual host key */
2185     static unsigned char exchange_hash[20];
2186     static unsigned char first_exchange_hash[20];
2187     static unsigned char keyspace[40];
2188     static const struct ssh_cipher *preferred_cipher;
2189     static const struct ssh_compress *preferred_comp;
2190     static int first_kex;
2191
2192     crBegin;
2193     random_init();
2194     first_kex = 1;
2195
2196     /*
2197      * Set up the preferred cipher and compression.
2198      */
2199     if (cfg.cipher == CIPHER_BLOWFISH) {
2200         preferred_cipher = &ssh_blowfish_ssh2;
2201     } else if (cfg.cipher == CIPHER_DES) {
2202         logevent("Single DES not supported in SSH2; using 3DES");
2203         preferred_cipher = &ssh_3des_ssh2;
2204     } else if (cfg.cipher == CIPHER_3DES) {
2205         preferred_cipher = &ssh_3des_ssh2;
2206     } else {
2207         /* Shouldn't happen, but we do want to initialise to _something_. */
2208         preferred_cipher = &ssh_3des_ssh2;
2209     }
2210     if (cfg.compression)
2211         preferred_comp = &ssh_zlib;
2212     else
2213         preferred_comp = &ssh_comp_none;
2214
2215     /*
2216      * Be prepared to work around the buggy MAC problem.
2217      */
2218     if (cfg.buggymac)
2219         maclist = buggymacs, nmacs = lenof(buggymacs);
2220     else
2221         maclist = macs, nmacs = lenof(macs);
2222
2223     begin_key_exchange:
2224     /*
2225      * Construct and send our key exchange packet.
2226      */
2227     ssh2_pkt_init(SSH2_MSG_KEXINIT);
2228     for (i = 0; i < 16; i++)
2229         ssh2_pkt_addbyte((unsigned char)random_byte());
2230     /* List key exchange algorithms. */
2231     ssh2_pkt_addstring_start();
2232     for (i = 0; i < lenof(kex_algs); i++) {
2233         ssh2_pkt_addstring_str(kex_algs[i]->name);
2234         if (i < lenof(kex_algs)-1)
2235             ssh2_pkt_addstring_str(",");
2236     }
2237     /* List server host key algorithms. */
2238     ssh2_pkt_addstring_start();
2239     for (i = 0; i < lenof(hostkey_algs); i++) {
2240         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
2241         if (i < lenof(hostkey_algs)-1)
2242             ssh2_pkt_addstring_str(",");
2243     }
2244     /* List client->server encryption algorithms. */
2245     ssh2_pkt_addstring_start();
2246     for (i = 0; i < lenof(ciphers)+1; i++) {
2247         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2248         ssh2_pkt_addstring_str(c->name);
2249         if (i < lenof(ciphers))
2250             ssh2_pkt_addstring_str(",");
2251     }
2252     /* List server->client encryption algorithms. */
2253     ssh2_pkt_addstring_start();
2254     for (i = 0; i < lenof(ciphers)+1; i++) {
2255         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2256         ssh2_pkt_addstring_str(c->name);
2257         if (i < lenof(ciphers))
2258             ssh2_pkt_addstring_str(",");
2259     }
2260     /* List client->server MAC algorithms. */
2261     ssh2_pkt_addstring_start();
2262     for (i = 0; i < nmacs; i++) {
2263         ssh2_pkt_addstring_str(maclist[i]->name);
2264         if (i < nmacs-1)
2265             ssh2_pkt_addstring_str(",");
2266     }
2267     /* List server->client MAC algorithms. */
2268     ssh2_pkt_addstring_start();
2269     for (i = 0; i < nmacs; i++) {
2270         ssh2_pkt_addstring_str(maclist[i]->name);
2271         if (i < nmacs-1)
2272             ssh2_pkt_addstring_str(",");
2273     }
2274     /* List client->server compression algorithms. */
2275     ssh2_pkt_addstring_start();
2276     for (i = 0; i < lenof(compressions)+1; i++) {
2277         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2278         ssh2_pkt_addstring_str(c->name);
2279         if (i < lenof(compressions))
2280             ssh2_pkt_addstring_str(",");
2281     }
2282     /* List server->client compression algorithms. */
2283     ssh2_pkt_addstring_start();
2284     for (i = 0; i < lenof(compressions)+1; i++) {
2285         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2286         ssh2_pkt_addstring_str(c->name);
2287         if (i < lenof(compressions))
2288             ssh2_pkt_addstring_str(",");
2289     }
2290     /* List client->server languages. Empty list. */
2291     ssh2_pkt_addstring_start();
2292     /* List server->client languages. Empty list. */
2293     ssh2_pkt_addstring_start();
2294     /* First KEX packet does _not_ follow, because we're not that brave. */
2295     ssh2_pkt_addbool(FALSE);
2296     /* Reserved. */
2297     ssh2_pkt_adduint32(0);
2298
2299     exhash = exhashbase;
2300     sha_string(&exhash, pktout.data+5, pktout.length-5);
2301
2302     ssh2_pkt_send();
2303
2304     if (!ispkt) crWaitUntil(ispkt);
2305     sha_string(&exhash, pktin.data+5, pktin.length-5);
2306
2307     /*
2308      * Now examine the other side's KEXINIT to see what we're up
2309      * to.
2310      */
2311     if (pktin.type != SSH2_MSG_KEXINIT) {
2312         bombout(("expected key exchange packet from server"));
2313         crReturn(0);
2314     }
2315     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
2316     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
2317     pktin.savedpos += 16;              /* skip garbage cookie */
2318     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
2319     for (i = 0; i < lenof(kex_algs); i++) {
2320         if (in_commasep_string(kex_algs[i]->name, str, len)) {
2321             kex = kex_algs[i];
2322             break;
2323         }
2324     }
2325     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
2326     for (i = 0; i < lenof(hostkey_algs); i++) {
2327         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
2328             hostkey = hostkey_algs[i];
2329             break;
2330         }
2331     }
2332     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
2333     for (i = 0; i < lenof(ciphers)+1; i++) {
2334         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2335         if (in_commasep_string(c->name, str, len)) {
2336             cscipher_tobe = c;
2337             break;
2338         }
2339     }
2340     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
2341     for (i = 0; i < lenof(ciphers)+1; i++) {
2342         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
2343         if (in_commasep_string(c->name, str, len)) {
2344             sccipher_tobe = c;
2345             break;
2346         }
2347     }
2348     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
2349     for (i = 0; i < nmacs; i++) {
2350         if (in_commasep_string(maclist[i]->name, str, len)) {
2351             csmac_tobe = maclist[i];
2352             break;
2353         }
2354     }
2355     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
2356     for (i = 0; i < nmacs; i++) {
2357         if (in_commasep_string(maclist[i]->name, str, len)) {
2358             scmac_tobe = maclist[i];
2359             break;
2360         }
2361     }
2362     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
2363     for (i = 0; i < lenof(compressions)+1; i++) {
2364         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2365         if (in_commasep_string(c->name, str, len)) {
2366             cscomp_tobe = c;
2367             break;
2368         }
2369     }
2370     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
2371     for (i = 0; i < lenof(compressions)+1; i++) {
2372         const struct ssh_compress *c = i==0 ? preferred_comp : compressions[i-1];
2373         if (in_commasep_string(c->name, str, len)) {
2374             sccomp_tobe = c;
2375             break;
2376         }
2377     }
2378
2379     /*
2380      * Currently we only support Diffie-Hellman and DSS, so let's
2381      * bomb out if those aren't selected.
2382      */
2383     if (kex != &ssh_diffiehellman || hostkey != &ssh_dss) {
2384         bombout(("internal fault: chaos in SSH 2 transport layer"));
2385         crReturn(0);
2386     }
2387
2388     /*
2389      * Now we begin the fun. Generate and send e for Diffie-Hellman.
2390      */
2391     e = dh_create_e();
2392     ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
2393     ssh2_pkt_addmp(e);
2394     ssh2_pkt_send();
2395
2396     crWaitUntil(ispkt);
2397     if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
2398         bombout(("expected key exchange packet from server"));
2399         crReturn(0);
2400     }
2401     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2402     f = ssh2_pkt_getmp();
2403     ssh2_pkt_getstring(&sigdata, &siglen);
2404
2405     K = dh_find_K(f);
2406
2407     sha_string(&exhash, hostkeydata, hostkeylen);
2408     sha_mpint(&exhash, e);
2409     sha_mpint(&exhash, f);
2410     sha_mpint(&exhash, K);
2411     SHA_Final(&exhash, exchange_hash);
2412
2413 #if 0
2414     debug(("Exchange hash is:\r\n"));
2415     for (i = 0; i < 20; i++)
2416         debug((" %02x", exchange_hash[i]));
2417     debug(("\r\n"));
2418 #endif
2419
2420     hkey = hostkey->newkey(hostkeydata, hostkeylen);
2421     if (!hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
2422         bombout(("Server failed host key check"));
2423         crReturn(0);
2424     }
2425
2426     /*
2427      * Expect SSH2_MSG_NEWKEYS from server.
2428      */
2429     crWaitUntil(ispkt);
2430     if (pktin.type != SSH2_MSG_NEWKEYS) {
2431         bombout(("expected new-keys packet from server"));
2432         crReturn(0);
2433     }
2434
2435     /*
2436      * Authenticate remote host: verify host key. (We've already
2437      * checked the signature of the exchange hash.)
2438      */
2439     keystr = hostkey->fmtkey(hkey);
2440     fingerprint = hostkey->fingerprint(hkey);
2441     verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2442                         keystr, fingerprint);
2443     if (first_kex) {                   /* don't bother logging this in rekeys */
2444         logevent("Host key fingerprint is:");
2445         logevent(fingerprint);
2446     }
2447     sfree(fingerprint);
2448     sfree(keystr);
2449     hostkey->freekey(hkey);
2450
2451     /*
2452      * Send SSH2_MSG_NEWKEYS.
2453      */
2454     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2455     ssh2_pkt_send();
2456
2457     /*
2458      * Create and initialise session keys.
2459      */
2460     cscipher = cscipher_tobe;
2461     sccipher = sccipher_tobe;
2462     csmac = csmac_tobe;
2463     scmac = scmac_tobe;
2464     cscomp = cscomp_tobe;
2465     sccomp = sccomp_tobe;
2466     cscomp->compress_init();
2467     sccomp->decompress_init();
2468     /*
2469      * Set IVs after keys. Here we use the exchange hash from the
2470      * _first_ key exchange.
2471      */
2472     if (first_kex)
2473         memcpy(first_exchange_hash, exchange_hash, sizeof(exchange_hash));
2474     ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'C', keyspace);
2475     cscipher->setcskey(keyspace);
2476     ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'D', keyspace);
2477     sccipher->setsckey(keyspace);
2478     ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'A', keyspace);
2479     cscipher->setcsiv(keyspace);
2480     ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'B', keyspace);
2481     sccipher->setsciv(keyspace);
2482     ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'E', keyspace);
2483     csmac->setcskey(keyspace);
2484     ssh2_mkkey(K, exchange_hash, first_exchange_hash, 'F', keyspace);
2485     scmac->setsckey(keyspace);
2486
2487     /*
2488      * If this is the first key exchange phase, we must pass the
2489      * SSH2_MSG_NEWKEYS packet to the next layer, not because it
2490      * wants to see it but because it will need time to initialise
2491      * itself before it sees an actual packet. In subsequent key
2492      * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
2493      * it would only confuse the layer above.
2494      */
2495     if (!first_kex) {
2496         crReturn(0);
2497     }
2498     first_kex = 0;
2499
2500     /*
2501      * Now we're encrypting. Begin returning 1 to the protocol main
2502      * function so that other things can run on top of the
2503      * transport. If we ever see a KEXINIT, we must go back to the
2504      * start.
2505      */
2506     while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
2507         crReturn(1);
2508     }
2509     logevent("Server initiated key re-exchange");
2510     goto begin_key_exchange;
2511
2512     crFinish(1);
2513 }
2514
2515 /*
2516  * Add data to an SSH2 channel output buffer.
2517  */
2518 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len) {
2519     if (c->v2.outbufsize <
2520         c->v2.outbuflen + len) {
2521         c->v2.outbufsize =
2522             c->v2.outbuflen + len + 1024;
2523         c->v2.outbuffer = srealloc(c->v2.outbuffer,
2524                                    c->v2.outbufsize);
2525     }
2526     memcpy(c->v2.outbuffer + c->v2.outbuflen,
2527            buf, len);
2528     c->v2.outbuflen += len;
2529 }
2530
2531 /*
2532  * Attempt to send data on an SSH2 channel.
2533  */
2534 static void ssh2_try_send(struct ssh_channel *c) {
2535     while (c->v2.remwindow > 0 &&
2536            c->v2.outbuflen > 0) {
2537         unsigned len = c->v2.remwindow;
2538         if (len > c->v2.outbuflen)
2539             len = c->v2.outbuflen;
2540         if (len > c->v2.remmaxpkt)
2541             len = c->v2.remmaxpkt;
2542         ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2543         ssh2_pkt_adduint32(c->remoteid);
2544         ssh2_pkt_addstring_start();
2545         ssh2_pkt_addstring_data(c->v2.outbuffer, len);
2546         ssh2_pkt_send();
2547         c->v2.outbuflen -= len;
2548         memmove(c->v2.outbuffer, c->v2.outbuffer+len,
2549                 c->v2.outbuflen);
2550         c->v2.remwindow -= len;
2551     }
2552 }
2553
2554 /*
2555  * Handle the SSH2 userauth and connection layers.
2556  */
2557 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2558 {
2559     static unsigned long remote_winsize;
2560     static unsigned long remote_maxpkt;
2561
2562     crBegin;
2563
2564     /*
2565      * Request userauth protocol, and await a response to it.
2566      */
2567     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2568     ssh2_pkt_addstring("ssh-userauth");
2569     ssh2_pkt_send();
2570     crWaitUntilV(ispkt);
2571     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2572         bombout(("Server refused user authentication protocol"));
2573         crReturnV;
2574     }
2575
2576     /*
2577      * FIXME: currently we support only password authentication.
2578      * (This places us technically in violation of the SSH2 spec.
2579      * We must fix this.)
2580      */
2581     while (1) {
2582         /*
2583          * Get a username and a password.
2584          */
2585         static char username[100];
2586         static char password[100];
2587         static int pos = 0;
2588         static char c;
2589
2590         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2591             c_write("login as: ", 10);
2592             ssh_send_ok = 1;
2593             while (pos >= 0) {
2594                 crWaitUntilV(!ispkt);
2595                 while (inlen--) switch (c = *in++) {
2596                   case 10: case 13:
2597                     username[pos] = 0;
2598                     pos = -1;
2599                     break;
2600                   case 8: case 127:
2601                     if (pos > 0) {
2602                         c_write("\b \b", 3);
2603                         pos--;
2604                     }
2605                     break;
2606                   case 21: case 27:
2607                     while (pos > 0) {
2608                         c_write("\b \b", 3);
2609                         pos--;
2610                     }
2611                     break;
2612                   case 3: case 4:
2613                     random_save_seed();
2614                     exit(0);
2615                     break;
2616                   default:
2617                     if (((c >= ' ' && c <= '~') ||
2618                          ((unsigned char)c >= 160)) && pos < 40) {
2619                         username[pos++] = c;
2620                         c_write(&c, 1);
2621                     }
2622                     break;
2623                 }
2624             }
2625             c_write("\r\n", 2);
2626             username[strcspn(username, "\n\r")] = '\0';
2627         } else {
2628             char stuff[200];
2629             strncpy(username, cfg.username, 99);
2630             username[99] = '\0';
2631             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2632                 sprintf(stuff, "Using username \"%s\".\r\n", username);
2633                 c_write(stuff, strlen(stuff));
2634             }
2635         }
2636
2637         if (ssh_get_password) {
2638             char prompt[200];
2639             sprintf(prompt, "%.90s@%.90s's password: ", username, savedhost);
2640             if (!ssh_get_password(prompt, password, sizeof(password))) {
2641                 /*
2642                  * get_password failed to get a password (for
2643                  * example because one was supplied on the command
2644                  * line which has already failed to work).
2645                  * Terminate.
2646                  */
2647                 logevent("No more passwords to try");
2648                 ssh_state = SSH_STATE_CLOSED;
2649                 crReturnV;
2650             }
2651         } else {
2652             c_write("password: ", 10);
2653             ssh_send_ok = 1;
2654
2655             pos = 0;
2656             while (pos >= 0) {
2657                 crWaitUntilV(!ispkt);
2658                 while (inlen--) switch (c = *in++) {
2659                   case 10: case 13:
2660                     password[pos] = 0;
2661                     pos = -1;
2662                     break;
2663                   case 8: case 127:
2664                     if (pos > 0)
2665                         pos--;
2666                     break;
2667                   case 21: case 27:
2668                     pos = 0;
2669                     break;
2670                   case 3: case 4:
2671                     random_save_seed();
2672                     exit(0);
2673                     break;
2674                   default:
2675                     if (((c >= ' ' && c <= '~') ||
2676                          ((unsigned char)c >= 160)) && pos < 40)
2677                         password[pos++] = c;
2678                     break;
2679                 }
2680             }
2681             c_write("\r\n", 2);
2682         }
2683
2684         /*
2685          * We send the password packet lumped tightly together with
2686          * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
2687          * string long enough to make the total length of the two
2688          * packets constant. This should ensure that a passive
2689          * listener doing traffic analyis can't work out the length
2690          * of the password.
2691          * 
2692          * For this to work, we need an assumption about the
2693          * maximum length of the password packet. I think 256 is
2694          * pretty conservative. Anyone using a password longer than
2695          * that probably doesn't have much to worry about from
2696          * people who find out how long their password is!
2697          */
2698         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2699         ssh2_pkt_addstring(username);
2700         ssh2_pkt_addstring("ssh-connection");   /* service requested */
2701         ssh2_pkt_addstring("password");
2702         ssh2_pkt_addbool(FALSE);
2703         ssh2_pkt_addstring(password);
2704         ssh2_pkt_defer();
2705         /*
2706          * We'll include a string that's an exact multiple of the
2707          * cipher block size. If the cipher is NULL for some
2708          * reason, we don't do this trick at all because we gain
2709          * nothing by it.
2710          */
2711         if (cscipher) {
2712             int i, j;
2713             ssh2_pkt_init(SSH2_MSG_IGNORE);
2714             ssh2_pkt_addstring_start();
2715             for (i = deferred_len; i <= 256; i += cscipher->blksize) {
2716                 for (j = 0; j < cscipher->blksize; j++) {
2717                     char c = (char)random_byte();
2718                     ssh2_pkt_addstring_data(&c, 1);
2719                 }
2720             }
2721             ssh2_pkt_defer();
2722         }
2723         ssh2_pkt_defersend();
2724
2725         crWaitUntilV(ispkt);
2726         if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2727             c_write("Access denied\r\n", 15);
2728             logevent("Authentication refused");
2729         } else
2730             break;
2731     }
2732
2733     /*
2734      * Now we're authenticated for the connection protocol. The
2735      * connection protocol will automatically have started at this
2736      * point; there's no need to send SERVICE_REQUEST.
2737      */
2738
2739     /*
2740      * So now create a channel with a session in it.
2741      */
2742     mainchan = smalloc(sizeof(struct ssh_channel));
2743     mainchan->localid = 100;           /* as good as any */
2744     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2745     ssh2_pkt_addstring("session");
2746     ssh2_pkt_adduint32(mainchan->localid);
2747     ssh2_pkt_adduint32(0x8000UL);  /* our window size */
2748     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
2749     ssh2_pkt_send();
2750     crWaitUntilV(ispkt);
2751     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2752         bombout(("Server refused to open a session"));
2753         crReturnV;
2754         /* FIXME: error data comes back in FAILURE packet */
2755     }
2756     if (ssh2_pkt_getuint32() != mainchan->localid) {
2757         bombout(("Server's channel confirmation cited wrong channel"));
2758         crReturnV;
2759     }
2760     mainchan->remoteid = ssh2_pkt_getuint32();
2761     mainchan->type = CHAN_MAINSESSION;
2762     mainchan->closes = 0;
2763     mainchan->v2.remwindow = ssh2_pkt_getuint32();
2764     mainchan->v2.remmaxpkt = ssh2_pkt_getuint32();
2765     mainchan->v2.outbuffer = NULL;
2766     mainchan->v2.outbuflen = mainchan->v2.outbufsize = 0;
2767     ssh_channels = newtree234(ssh_channelcmp);
2768     add234(ssh_channels, mainchan);
2769     logevent("Opened channel for session");
2770
2771     /*
2772      * Potentially enable X11 forwarding.
2773      */
2774     if (cfg.x11_forward) {
2775         char proto[20], data[64];
2776         logevent("Requesting X11 forwarding");
2777         x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2778         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2779         ssh2_pkt_adduint32(mainchan->remoteid);
2780         ssh2_pkt_addstring("x11-req");
2781         ssh2_pkt_addbool(1);           /* want reply */
2782         ssh2_pkt_addbool(0);           /* many connections */
2783         ssh2_pkt_addstring(proto);
2784         ssh2_pkt_addstring(data);
2785         ssh2_pkt_adduint32(0);         /* screen number */
2786         ssh2_pkt_send();
2787
2788         do {
2789             crWaitUntilV(ispkt);
2790             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2791                 unsigned i = ssh2_pkt_getuint32();
2792                 struct ssh_channel *c;
2793                 c = find234(ssh_channels, &i, ssh_channelfind);
2794                 if (!c)
2795                     continue;          /* nonexistent channel */
2796                 c->v2.remwindow += ssh2_pkt_getuint32();
2797             }
2798         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2799
2800         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2801             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2802                 bombout(("Server got confused by X11 forwarding request"));
2803                 crReturnV;
2804             }
2805             logevent("X11 forwarding refused");
2806         } else {
2807             logevent("X11 forwarding enabled");
2808             ssh_X11_fwd_enabled = TRUE;
2809         }
2810     }
2811
2812     /*
2813      * Now allocate a pty for the session.
2814      */
2815     if (!cfg.nopty) {
2816         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2817         ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2818         ssh2_pkt_addstring("pty-req");
2819         ssh2_pkt_addbool(1);           /* want reply */
2820         ssh2_pkt_addstring(cfg.termtype);
2821         ssh2_pkt_adduint32(cols);
2822         ssh2_pkt_adduint32(rows);
2823         ssh2_pkt_adduint32(0);         /* pixel width */
2824         ssh2_pkt_adduint32(0);         /* pixel height */
2825         ssh2_pkt_addstring_start();
2826         ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2827         ssh2_pkt_send();
2828         ssh_state = SSH_STATE_INTERMED;
2829
2830         do {
2831             crWaitUntilV(ispkt);
2832             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2833                 unsigned i = ssh2_pkt_getuint32();
2834                 struct ssh_channel *c;
2835                 c = find234(ssh_channels, &i, ssh_channelfind);
2836                 if (!c)
2837                     continue;          /* nonexistent channel */
2838                 c->v2.remwindow += ssh2_pkt_getuint32();
2839             }
2840         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2841
2842         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2843             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2844                 bombout(("Server got confused by pty request"));
2845                 crReturnV;
2846             }
2847             c_write("Server refused to allocate pty\r\n", 32);
2848             ssh_editing = ssh_echoing = 1;
2849         } else {
2850             logevent("Allocated pty");
2851         }
2852     } else {
2853         ssh_editing = ssh_echoing = 1;
2854     }
2855
2856     /*
2857      * Start a shell or a remote command.
2858      */
2859     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2860     ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2861     if (*cfg.remote_cmd) {
2862         ssh2_pkt_addstring("exec");
2863         ssh2_pkt_addbool(1);           /* want reply */
2864         ssh2_pkt_addstring(cfg.remote_cmd);
2865     } else {
2866         ssh2_pkt_addstring("shell");
2867         ssh2_pkt_addbool(1);           /* want reply */
2868     }
2869     ssh2_pkt_send();
2870     do {
2871         crWaitUntilV(ispkt);
2872         if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2873             unsigned i = ssh2_pkt_getuint32();
2874             struct ssh_channel *c;
2875             c = find234(ssh_channels, &i, ssh_channelfind);
2876             if (!c)
2877                 continue;              /* nonexistent channel */
2878             c->v2.remwindow += ssh2_pkt_getuint32();
2879         }
2880     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2881     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2882         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2883             bombout(("Server got confused by shell/command request"));
2884             crReturnV;
2885         }
2886         bombout(("Server refused to start a shell/command"));
2887         crReturnV;
2888     } else {
2889         logevent("Started a shell/command");
2890     }
2891
2892     ssh_state = SSH_STATE_SESSION;
2893     if (size_needed)
2894         ssh_size();
2895     if (eof_needed)
2896         ssh_special(TS_EOF);
2897
2898     /*
2899      * Transfer data!
2900      */
2901     ldisc_send(NULL, 0);               /* cause ldisc to notice changes */
2902     ssh_send_ok = 1;
2903     while (1) {
2904         static int try_send;
2905         crReturnV;
2906         try_send = FALSE;
2907         if (ispkt) {
2908             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2909                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2910                 char *data;
2911                 int length;
2912                 unsigned i = ssh2_pkt_getuint32();
2913                 struct ssh_channel *c;
2914                 c = find234(ssh_channels, &i, ssh_channelfind);
2915                 if (!c)
2916                     continue;          /* nonexistent channel */
2917                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2918                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2919                     continue;          /* extended but not stderr */
2920                 ssh2_pkt_getstring(&data, &length);
2921                 if (data) {
2922                     switch (c->type) {
2923                       case CHAN_MAINSESSION:
2924                         from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
2925                                      data, length);
2926                         break;
2927                       case CHAN_X11:
2928                         x11_send(c->u.x11.s, data, length);
2929                         break;
2930                     }
2931                     /*
2932                      * Enlarge the window again at the remote
2933                      * side, just in case it ever runs down and
2934                      * they fail to send us any more data.
2935                      */
2936                     ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2937                     ssh2_pkt_adduint32(c->remoteid);
2938                     ssh2_pkt_adduint32(length);
2939                     ssh2_pkt_send();
2940                 }
2941             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2942                 ssh_state = SSH_STATE_CLOSED;
2943                 logevent("Received disconnect message");
2944                 crReturnV;
2945             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2946                 continue;              /* exit status et al; ignore (FIXME?) */
2947             } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2948                 unsigned i = ssh2_pkt_getuint32();
2949                 struct ssh_channel *c;
2950
2951                 c = find234(ssh_channels, &i, ssh_channelfind);
2952                 if (!c)
2953                     continue;          /* nonexistent channel */
2954                 
2955                 if (c->type == CHAN_X11) {
2956                     /*
2957                      * Remote EOF on an X11 channel means we should
2958                      * wrap up and close the channel ourselves.
2959                      */
2960                     x11_close(c->u.x11.s);
2961                     sshfwd_close(c);
2962                 }
2963             } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2964                 unsigned i = ssh2_pkt_getuint32();
2965                 struct ssh_channel *c;
2966                 enum234 e;
2967
2968                 c = find234(ssh_channels, &i, ssh_channelfind);
2969                 if (!c)
2970                     continue;          /* nonexistent channel */
2971                 if (c->closes == 0) {
2972                     ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2973                     ssh2_pkt_adduint32(c->remoteid);
2974                     ssh2_pkt_send();
2975                 }
2976                 /* Do pre-close processing on the channel. */
2977                 switch (c->type) {
2978                   case CHAN_MAINSESSION:
2979                     break;             /* nothing to see here, move along */
2980                   case CHAN_X11:
2981                     break;
2982                 }
2983                 del234(ssh_channels, c);
2984                 sfree(c->v2.outbuffer);
2985                 sfree(c);
2986
2987                 /*
2988                  * See if that was the last channel left open.
2989                  */
2990                 c = first234(ssh_channels, &e);
2991                 if (!c) {
2992                     logevent("All channels closed. Disconnecting");
2993                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2994                     ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
2995                     ssh2_pkt_addstring("All open channels closed");
2996                     ssh2_pkt_addstring("en");   /* language tag */
2997                     ssh2_pkt_send();
2998                     ssh_state = SSH_STATE_CLOSED;
2999                     crReturnV;
3000                 }
3001                 continue;              /* remote sends close; ignore (FIXME) */
3002             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
3003                 unsigned i = ssh2_pkt_getuint32();
3004                 struct ssh_channel *c;
3005                 c = find234(ssh_channels, &i, ssh_channelfind);
3006                 if (!c)
3007                     continue;          /* nonexistent channel */
3008                 mainchan->v2.remwindow += ssh2_pkt_getuint32();
3009                 try_send = TRUE;
3010             } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
3011                 char *type;
3012                 int typelen;
3013                 char *error = NULL;
3014                 struct ssh_channel *c;
3015                 ssh2_pkt_getstring(&type, &typelen);
3016                 c = smalloc(sizeof(struct ssh_channel));
3017
3018                 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3019                     if (!ssh_X11_fwd_enabled)
3020                         error = "X11 forwarding is not enabled";
3021                     else if ( x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL ) {
3022                         error = "Unable to open an X11 connection";
3023                     } else {
3024                         c->type = CHAN_X11;
3025                     }
3026                 } else {
3027                     error = "Unsupported channel type requested";
3028                 }
3029
3030                 c->remoteid = ssh2_pkt_getuint32();
3031                 if (error) {
3032                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
3033                     ssh2_pkt_adduint32(c->remoteid);
3034                     ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
3035                     ssh2_pkt_addstring(error);
3036                     ssh2_pkt_addstring("en");   /* language tag */
3037                     ssh2_pkt_send();
3038                     sfree(c);
3039                 } else {
3040                     struct ssh_channel *d;
3041                     unsigned i;
3042                     enum234 e;
3043
3044                     for (i=1, d = first234(ssh_channels, &e); d;
3045                          d = next234(&e)) {
3046                         if (d->localid > i)
3047                             break;     /* found a free number */
3048                         i = d->localid + 1;
3049                     }
3050                     c->localid = i;
3051                     c->closes = 0;
3052                     c->v2.remwindow = ssh2_pkt_getuint32();
3053                     c->v2.remmaxpkt = ssh2_pkt_getuint32();
3054                     c->v2.outbuffer = NULL;
3055                     c->v2.outbuflen = c->v2.outbufsize = 0;
3056                     add234(ssh_channels, c);
3057                     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
3058                     ssh2_pkt_adduint32(c->remoteid);
3059                     ssh2_pkt_adduint32(c->localid);
3060                     ssh2_pkt_adduint32(0x8000UL);  /* our window size */
3061                     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
3062                     ssh2_pkt_send();
3063                 }
3064             } else {
3065                 bombout(("Strange packet received: type %d", pktin.type));
3066                 crReturnV;
3067             }
3068         } else {
3069             /*
3070              * We have spare data. Add it to the channel buffer.
3071              */
3072             ssh2_add_channel_data(mainchan, in, inlen);
3073             try_send = TRUE;
3074         }
3075         if (try_send) {
3076             enum234 e;
3077             struct ssh_channel *c;
3078             /*
3079              * Try to send data on all channels if we can.
3080              */
3081             for (c = first234(ssh_channels, &e); c; c = next234(&e))
3082                 ssh2_try_send(c);
3083         }
3084     }
3085
3086     crFinishV;
3087 }
3088
3089 /*
3090  * Handle the top-level SSH2 protocol.
3091  */
3092 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
3093 {
3094     if (do_ssh2_transport(in, inlen, ispkt) == 0)
3095         return;
3096     do_ssh2_authconn(in, inlen, ispkt);
3097 }
3098
3099 /*
3100  * Called to set up the connection.
3101  *
3102  * Returns an error message, or NULL on success.
3103  */
3104 static char *ssh_init (char *host, int port, char **realhost) {
3105     char *p;
3106         
3107 #ifdef MSCRYPTOAPI
3108     if(crypto_startup() == 0)
3109         return "Microsoft high encryption pack not installed!";
3110 #endif
3111
3112     ssh_send_ok = 0;
3113     ssh_editing = 0;
3114     ssh_echoing = 0;
3115
3116     p = connect_to_host(host, port, realhost);
3117     if (p != NULL)
3118         return p;
3119
3120     return NULL;
3121 }
3122
3123 /*
3124  * Called to send data down the Telnet connection.
3125  */
3126 static void ssh_send (char *buf, int len) {
3127     if (s == NULL || ssh_protocol == NULL)
3128         return;
3129
3130     ssh_protocol(buf, len, 0);
3131 }
3132
3133 /*
3134  * Called to set the size of the window from SSH's POV.
3135  */
3136 static void ssh_size(void) {
3137     switch (ssh_state) {
3138       case SSH_STATE_BEFORE_SIZE:
3139       case SSH_STATE_PREPACKET:
3140       case SSH_STATE_CLOSED:
3141         break;                         /* do nothing */
3142       case SSH_STATE_INTERMED:
3143         size_needed = TRUE;            /* buffer for later */
3144         break;
3145       case SSH_STATE_SESSION:
3146         if (!cfg.nopty) {
3147             if (ssh_version == 1) {
3148                 send_packet(SSH1_CMSG_WINDOW_SIZE,
3149                             PKT_INT, rows, PKT_INT, cols,
3150                             PKT_INT, 0, PKT_INT, 0, PKT_END);
3151             } else {
3152                 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
3153                 ssh2_pkt_adduint32(mainchan->remoteid);
3154                 ssh2_pkt_addstring("window-change");
3155                 ssh2_pkt_addbool(0);
3156                 ssh2_pkt_adduint32(cols);
3157                 ssh2_pkt_adduint32(rows);
3158                 ssh2_pkt_adduint32(0);
3159                 ssh2_pkt_adduint32(0);
3160                 ssh2_pkt_send();
3161             }
3162         }
3163         break;
3164     }
3165 }
3166
3167 /*
3168  * Send Telnet special codes. TS_EOF is useful for `plink', so you
3169  * can send an EOF and collect resulting output (e.g. `plink
3170  * hostname sort').
3171  */
3172 static void ssh_special (Telnet_Special code) {
3173     if (code == TS_EOF) {
3174         if (ssh_state != SSH_STATE_SESSION) {
3175             /*
3176              * Buffer the EOF in case we are pre-SESSION, so we can
3177              * send it as soon as we reach SESSION.
3178              */
3179             if (code == TS_EOF)
3180                 eof_needed = TRUE;
3181             return;
3182         }
3183         if (ssh_version == 1) {
3184             send_packet(SSH1_CMSG_EOF, PKT_END);
3185         } else {
3186             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
3187             ssh2_pkt_adduint32(mainchan->remoteid);
3188             ssh2_pkt_send();
3189         }
3190         logevent("Sent EOF message");
3191     } else if (code == TS_PING) {
3192         if (ssh_state == SSH_STATE_CLOSED || ssh_state == SSH_STATE_PREPACKET)
3193             return;
3194         if (ssh_version == 1) {
3195             send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
3196         } else {
3197             ssh2_pkt_init(SSH2_MSG_IGNORE);
3198             ssh2_pkt_addstring_start();
3199             ssh2_pkt_send();
3200         }
3201     } else {
3202         /* do nothing */
3203     }
3204 }
3205
3206 static Socket ssh_socket(void) { return s; }
3207
3208 static int ssh_sendok(void) { return ssh_send_ok; }
3209
3210 static int ssh_ldisc(int option) {
3211     if (option == LD_ECHO) return ssh_echoing;
3212     if (option == LD_EDIT) return ssh_editing;
3213     return FALSE;
3214 }
3215
3216 Backend ssh_backend = {
3217     ssh_init,
3218     ssh_send,
3219     ssh_size,
3220     ssh_special,
3221     ssh_socket,
3222     ssh_sendok,
3223     ssh_ldisc,
3224     22
3225 };