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