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