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