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