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