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