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