]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - ssh.c
Fix another bignum formatting problem. This one hit Diffie-Hellmann
[PuTTY_svn.git] / ssh.c
1 #include <windows.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdarg.h>
5 #include <assert.h>
6
7 #include "putty.h"
8 #include "tree234.h"
9 #include "ssh.h"
10
11 #ifndef FALSE
12 #define FALSE 0
13 #endif
14 #ifndef TRUE
15 #define TRUE 1
16 #endif
17
18 #define logevent(s) { logevent(s); \
19                       if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20                       fprintf(stderr, "%s\n", s); }
21
22 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, sk_close(s), \
23                        s = NULL, connection_fatal msg )
24
25 #define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
26 #define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
27 #define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
28 #define SSH1_CMSG_USER                            4    /* 0x4 */
29 #define SSH1_CMSG_AUTH_RSA                        6    /* 0x6 */
30 #define SSH1_SMSG_AUTH_RSA_CHALLENGE              7    /* 0x7 */
31 #define SSH1_CMSG_AUTH_RSA_RESPONSE               8    /* 0x8 */
32 #define SSH1_CMSG_AUTH_PASSWORD                   9    /* 0x9 */
33 #define SSH1_CMSG_REQUEST_PTY                     10   /* 0xa */
34 #define SSH1_CMSG_WINDOW_SIZE                     11   /* 0xb */
35 #define SSH1_CMSG_EXEC_SHELL                      12   /* 0xc */
36 #define SSH1_CMSG_EXEC_CMD                        13   /* 0xd */
37 #define SSH1_SMSG_SUCCESS                         14   /* 0xe */
38 #define SSH1_SMSG_FAILURE                         15   /* 0xf */
39 #define SSH1_CMSG_STDIN_DATA                      16   /* 0x10 */
40 #define SSH1_SMSG_STDOUT_DATA                     17   /* 0x11 */
41 #define SSH1_SMSG_STDERR_DATA                     18   /* 0x12 */
42 #define SSH1_CMSG_EOF                             19   /* 0x13 */
43 #define SSH1_SMSG_EXIT_STATUS                     20   /* 0x14 */
44 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21   /* 0x15 */
45 #define SSH1_MSG_CHANNEL_OPEN_FAILURE             22   /* 0x16 */
46 #define SSH1_MSG_CHANNEL_DATA                     23   /* 0x17 */
47 #define SSH1_MSG_CHANNEL_CLOSE                    24   /* 0x18 */
48 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25   /* 0x19 */
49 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30   /* 0x1e */
50 #define SSH1_SMSG_AGENT_OPEN                      31   /* 0x1f */
51 #define SSH1_CMSG_EXIT_CONFIRMATION               33   /* 0x21 */
52 #define SSH1_MSG_IGNORE                           32   /* 0x20 */
53 #define SSH1_MSG_DEBUG                            36   /* 0x24 */
54 #define SSH1_CMSG_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     while (b[0] > 1 && b[b[0]] == 0) b[0]--;
853     return b;
854 }
855
856 static int do_ssh_init(unsigned char c) {
857     static char *vsp;
858     static char version[10];
859     static char vstring[80];
860     static char vlog[sizeof(vstring)+20];
861     static int i;
862
863     crBegin;
864
865     /* Search for the string "SSH-" in the input. */
866     i = 0;
867     while (1) {
868         static const int transS[] = { 1, 2, 2, 1 };
869         static const int transH[] = { 0, 0, 3, 0 };
870         static const int transminus[] = { 0, 0, 0, -1 };
871         if (c == 'S') i = transS[i];
872         else if (c == 'H') i = transH[i];
873         else if (c == '-') i = transminus[i];
874         else i = 0;
875         if (i < 0)
876             break;
877         crReturn(1);                   /* get another character */
878     }
879
880     strcpy(vstring, "SSH-");
881     vsp = vstring+4;
882     i = 0;
883     while (1) {
884         crReturn(1);                   /* get another char */
885         if (vsp < vstring+sizeof(vstring)-1)
886             *vsp++ = c;
887         if (i >= 0) {
888             if (c == '-') {
889                 version[i] = '\0';
890                 i = -1;
891             } else if (i < sizeof(version)-1)
892                 version[i++] = c;
893         }
894         else if (c == '\n')
895             break;
896     }
897
898     rdpkt2_state.incoming_sequence = 0;
899
900     *vsp = 0;
901     sprintf(vlog, "Server version: %s", vstring);
902     vlog[strcspn(vlog, "\r\n")] = '\0';
903     logevent(vlog);
904
905     /*
906      * Server version "1.99" means we can choose whether we use v1
907      * or v2 protocol. Choice is based on cfg.sshprot.
908      */
909     if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
910         /*
911          * This is a v2 server. Begin v2 protocol.
912          */
913         char *verstring = "SSH-2.0-PuTTY";
914         SHA_Init(&exhash);
915         /*
916          * Hash our version string and their version string.
917          */
918         sha_string(&exhash, verstring, strlen(verstring));
919         sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
920         sprintf(vstring, "%s\n", verstring);
921         sprintf(vlog, "We claim version: %s", verstring);
922         logevent(vlog);
923         logevent("Using SSH protocol version 2");
924         sk_write(s, vstring, strlen(vstring));
925         ssh_protocol = ssh2_protocol;
926         ssh_version = 2;
927         s_rdpkt = ssh2_rdpkt;
928     } else {
929         /*
930          * This is a v1 server. Begin v1 protocol.
931          */
932         sprintf(vstring, "SSH-%s-PuTTY\n",
933                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
934         sprintf(vlog, "We claim version: %s", vstring);
935         vlog[strcspn(vlog, "\r\n")] = '\0';
936         logevent(vlog);
937         logevent("Using SSH protocol version 1");
938         sk_write(s, vstring, strlen(vstring));
939         ssh_protocol = ssh1_protocol;
940         ssh_version = 1;
941         s_rdpkt = ssh1_rdpkt;
942     }
943
944     crFinish(0);
945 }
946
947 static void ssh_gotdata(unsigned char *data, int datalen)
948 {
949     crBegin;
950
951     /*
952      * To begin with, feed the characters one by one to the
953      * protocol initialisation / selection function do_ssh_init().
954      * When that returns 0, we're done with the initial greeting
955      * exchange and can move on to packet discipline.
956      */
957     while (1) {
958         int ret;
959         if (datalen == 0)
960             crReturnV;                 /* more data please */
961         ret = do_ssh_init(*data);
962         data++; datalen--;
963         if (ret == 0)
964             break;
965     }
966
967     /*
968      * We emerge from that loop when the initial negotiation is
969      * over and we have selected an s_rdpkt function. Now pass
970      * everything to s_rdpkt, and then pass the resulting packets
971      * to the proper protocol handler.
972      */
973     if (datalen == 0)
974         crReturnV;
975     while (1) {
976         while (datalen > 0) {
977             if ( s_rdpkt(&data, &datalen) == 0 ) {
978                 ssh_protocol(NULL, 0, 1);
979                 if (ssh_state == SSH_STATE_CLOSED) {
980                     return;
981                 }
982             }
983         }
984         crReturnV;
985     }
986     crFinishV;
987 }
988
989 static int ssh_receive(Socket s, int urgent, char *data, int len) {
990     if (!len) {
991         /* Connection has closed. */
992         sk_close(s);
993         s = NULL;
994         return 0;
995     }
996     ssh_gotdata (data, len);
997     if (ssh_state == SSH_STATE_CLOSED) {
998         if (s) {
999             sk_close(s);
1000             s = NULL;
1001         }
1002         return 0;
1003     }
1004     return 1;
1005 }
1006
1007 /*
1008  * Connect to specified host and port.
1009  * Returns an error message, or NULL on success.
1010  * Also places the canonical host name into `realhost'.
1011  */
1012 static char *connect_to_host(char *host, int port, char **realhost)
1013 {
1014     SockAddr addr;
1015     char *err;
1016 #ifdef FWHACK
1017     char *FWhost;
1018     int FWport;
1019 #endif
1020
1021     savedhost = malloc(1+strlen(host));
1022     if (!savedhost)
1023         fatalbox("Out of memory");
1024     strcpy(savedhost, host);
1025
1026     if (port < 0)
1027         port = 22;                     /* default ssh port */
1028     savedport = port;
1029
1030 #ifdef FWHACK
1031     FWhost = host;
1032     FWport = port;
1033     host = FWSTR;
1034     port = 23;
1035 #endif
1036
1037     /*
1038      * Try to find host.
1039      */
1040     addr = sk_namelookup(host, realhost);
1041     if ( (err = sk_addr_error(addr)) )
1042         return err;
1043
1044 #ifdef FWHACK
1045     *realhost = FWhost;
1046 #endif
1047
1048     /*
1049      * Open socket.
1050      */
1051     s = sk_new(addr, port, ssh_receive);
1052     if ( (err = sk_socket_error(s)) )
1053         return err;
1054
1055 #ifdef FWHACK
1056     sk_write(s, "connect ", 8);
1057     sk_write(s, FWhost, strlen(FWhost));
1058     {
1059         char buf[20];
1060         sprintf(buf, " %d\n", FWport);
1061         sk_write(s, buf, strlen(buf));
1062     }
1063 #endif
1064
1065     return NULL;
1066 }
1067
1068 /*
1069  * Handle the key exchange and user authentication phases.
1070  */
1071 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1072 {
1073     int i, j, len;
1074     unsigned char *rsabuf, *keystr1, *keystr2;
1075     unsigned char cookie[8];
1076     struct RSAKey servkey, hostkey;
1077     struct MD5Context md5c;
1078     static unsigned long supported_ciphers_mask, supported_auths_mask;
1079     static int tried_publickey;
1080     static unsigned char session_id[16];
1081     int cipher_type;
1082     static char username[100];
1083
1084     crBegin;
1085
1086     if (!ispkt) crWaitUntil(ispkt);
1087
1088     if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1089         bombout(("Public key packet not received"));
1090         crReturn(0);
1091     }
1092
1093     logevent("Received public keys");
1094
1095     memcpy(cookie, pktin.body, 8);
1096
1097     i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1098     j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1099
1100     /*
1101      * Log the host key fingerprint.
1102      */
1103     {
1104         char logmsg[80];
1105         logevent("Host key fingerprint is:");
1106         strcpy(logmsg, "      ");
1107         hostkey.comment = NULL;
1108         rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1109                         &hostkey);
1110         logevent(logmsg);
1111     }
1112
1113     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1114     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1115
1116     MD5Init(&md5c);
1117     MD5Update(&md5c, keystr2, hostkey.bytes);
1118     MD5Update(&md5c, keystr1, servkey.bytes);
1119     MD5Update(&md5c, pktin.body, 8);
1120     MD5Final(session_id, &md5c);
1121
1122     for (i=0; i<32; i++)
1123         session_key[i] = random_byte();
1124
1125     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1126
1127     rsabuf = malloc(len);
1128     if (!rsabuf)
1129         fatalbox("Out of memory");
1130
1131     /*
1132      * Verify the host key.
1133      */
1134     {
1135         /*
1136          * First format the key into a string.
1137          */
1138         int len = rsastr_len(&hostkey);
1139         char fingerprint[100];
1140         char *keystr = malloc(len);
1141         if (!keystr)
1142             fatalbox("Out of memory");
1143         rsastr_fmt(keystr, &hostkey);
1144         rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
1145         verify_ssh_host_key(savedhost, savedport, "rsa", keystr, fingerprint);
1146         free(keystr);
1147     }
1148
1149     for (i=0; i<32; i++) {
1150         rsabuf[i] = session_key[i];
1151         if (i < 16)
1152             rsabuf[i] ^= session_id[i];
1153     }
1154
1155     if (hostkey.bytes > servkey.bytes) {
1156         rsaencrypt(rsabuf, 32, &servkey);
1157         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1158     } else {
1159         rsaencrypt(rsabuf, 32, &hostkey);
1160         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1161     }
1162
1163     logevent("Encrypted session key");
1164
1165     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1166                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
1167                   SSH_CIPHER_3DES;
1168     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1169         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1170         cipher_type = SSH_CIPHER_3DES;
1171     }
1172     switch (cipher_type) {
1173       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1174       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1175       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1176     }
1177
1178     send_packet(SSH1_CMSG_SESSION_KEY,
1179                 PKT_CHAR, cipher_type,
1180                 PKT_DATA, cookie, 8,
1181                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1182                 PKT_DATA, rsabuf, len,
1183                 PKT_INT, 0,
1184                 PKT_END);
1185
1186     logevent("Trying to enable encryption...");
1187
1188     free(rsabuf);
1189
1190     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1191              cipher_type == SSH_CIPHER_DES ? &ssh_des :
1192              &ssh_3des;
1193     cipher->sesskey(session_key);
1194
1195     crWaitUntil(ispkt);
1196
1197     if (pktin.type != SSH1_SMSG_SUCCESS) {
1198         bombout(("Encryption not successfully enabled"));
1199         crReturn(0);
1200     }
1201
1202     logevent("Successfully started encryption");
1203
1204     fflush(stdout);
1205     {
1206         static int pos = 0;
1207         static char c;
1208         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1209             c_write("login as: ", 10);
1210             ssh_send_ok = 1;
1211             while (pos >= 0) {
1212                 crWaitUntil(!ispkt);
1213                 while (inlen--) switch (c = *in++) {
1214                   case 10: case 13:
1215                     username[pos] = 0;
1216                     pos = -1;
1217                     break;
1218                   case 8: case 127:
1219                     if (pos > 0) {
1220                         c_write("\b \b", 3);
1221                         pos--;
1222                     }
1223                     break;
1224                   case 21: case 27:
1225                     while (pos > 0) {
1226                         c_write("\b \b", 3);
1227                         pos--;
1228                     }
1229                     break;
1230                   case 3: case 4:
1231                     random_save_seed();
1232                     exit(0);
1233                     break;
1234                   default:
1235                     if (((c >= ' ' && c <= '~') ||
1236                          ((unsigned char)c >= 160)) && pos < 40) {
1237                         username[pos++] = c;
1238                         c_write(&c, 1);
1239                     }
1240                     break;
1241                 }
1242             }
1243             c_write("\r\n", 2);
1244             username[strcspn(username, "\n\r")] = '\0';
1245         } else {
1246             char stuff[200];
1247             strncpy(username, cfg.username, 99);
1248             username[99] = '\0';
1249             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
1250                 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1251                 c_write(stuff, strlen(stuff));
1252             }
1253         }
1254
1255         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1256         {
1257             char userlog[20+sizeof(username)];
1258             sprintf(userlog, "Sent username \"%s\"", username);
1259             logevent(userlog);
1260         }
1261     }
1262
1263     crWaitUntil(ispkt);
1264
1265     tried_publickey = 0;
1266
1267     while (pktin.type == SSH1_SMSG_FAILURE) {
1268         static char password[100];
1269         static char prompt[200];
1270         static int pos;
1271         static char c;
1272         static int pwpkt_type;
1273         /*
1274          * Show password prompt, having first obtained it via a TIS
1275          * or CryptoCard exchange if we're doing TIS or CryptoCard
1276          * authentication.
1277          */
1278         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1279         if (agent_exists()) {
1280             /*
1281              * Attempt RSA authentication using Pageant.
1282              */
1283             static unsigned char request[5], *response, *p;
1284             static int responselen;
1285             static int i, nkeys;
1286             static int authed = FALSE;
1287             void *r;
1288
1289             logevent("Pageant is running. Requesting keys.");
1290
1291             /* Request the keys held by the agent. */
1292             PUT_32BIT(request, 1);
1293             request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1294             agent_query(request, 5, &r, &responselen);
1295             response = (unsigned char *)r;
1296             if (response) {
1297                 p = response + 5;
1298                 nkeys = GET_32BIT(p); p += 4;
1299                 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1300                     logevent(buf); }
1301                 for (i = 0; i < nkeys; i++) {
1302                     static struct RSAKey key;
1303                     static Bignum challenge;
1304                     static char *commentp;
1305                     static int commentlen;
1306
1307                     { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1308                         logevent(buf); }
1309                     p += 4;
1310                     p += ssh1_read_bignum(p, &key.exponent);
1311                     p += ssh1_read_bignum(p, &key.modulus);
1312                     commentlen = GET_32BIT(p); p += 4;
1313                     commentp = p; p += commentlen;
1314                     send_packet(SSH1_CMSG_AUTH_RSA,
1315                                 PKT_BIGNUM, key.modulus, PKT_END);
1316                     crWaitUntil(ispkt);
1317                     if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1318                         logevent("Key refused");
1319                         continue;
1320                     }
1321                     logevent("Received RSA challenge");
1322                     ssh1_read_bignum(pktin.body, &challenge);
1323                     {
1324                         char *agentreq, *q, *ret;
1325                         int len, retlen;
1326                         len = 1 + 4;   /* message type, bit count */
1327                         len += ssh1_bignum_length(key.exponent);
1328                         len += ssh1_bignum_length(key.modulus);
1329                         len += ssh1_bignum_length(challenge);
1330                         len += 16;     /* session id */
1331                         len += 4;      /* response format */
1332                         agentreq = malloc(4 + len);
1333                         PUT_32BIT(agentreq, len);
1334                         q = agentreq + 4;
1335                         *q++ = SSH_AGENTC_RSA_CHALLENGE;
1336                         PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1337                         q += 4;
1338                         q += ssh1_write_bignum(q, key.exponent);
1339                         q += ssh1_write_bignum(q, key.modulus);
1340                         q += ssh1_write_bignum(q, challenge);
1341                         memcpy(q, session_id, 16); q += 16;
1342                         PUT_32BIT(q, 1);   /* response format */
1343                         agent_query(agentreq, len+4, &ret, &retlen);
1344                         free(agentreq);
1345                         if (ret) {
1346                             if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1347                                 logevent("Sending Pageant's response");
1348                                 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1349                                             PKT_DATA, ret+5, 16, PKT_END);
1350                                 free(ret);
1351                                 crWaitUntil(ispkt);
1352                                 if (pktin.type == SSH1_SMSG_SUCCESS) {
1353                                     logevent("Pageant's response accepted");
1354                                     if (flags & FLAG_VERBOSE) {
1355                                         c_write("Authenticated using RSA key \"",
1356                                                 29);
1357                                         c_write(commentp, commentlen);
1358                                         c_write("\" from agent\r\n", 14);
1359                                     }
1360                                     authed = TRUE;
1361                                 } else
1362                                     logevent("Pageant's response not accepted");
1363                             } else {
1364                                 logevent("Pageant failed to answer challenge");
1365                                 free(ret);
1366                             }
1367                         } else {
1368                             logevent("No reply received from Pageant");
1369                         }
1370                     }
1371                     freebn(key.exponent);
1372                     freebn(key.modulus);
1373                     freebn(challenge);
1374                     if (authed)
1375                         break;
1376                 }
1377             }
1378             if (authed)
1379                 break;
1380         }
1381         if (*cfg.keyfile && !tried_publickey)
1382             pwpkt_type = SSH1_CMSG_AUTH_RSA;
1383
1384         if (pktin.type == SSH1_SMSG_FAILURE &&
1385             cfg.try_tis_auth &&
1386             (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1387             pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1388             logevent("Requested TIS authentication");
1389             send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1390             crWaitUntil(ispkt);
1391             if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1392                 logevent("TIS authentication declined");
1393                 if (flags & FLAG_INTERACTIVE)
1394                     c_write("TIS authentication refused.\r\n", 29);
1395             } else {
1396                 int challengelen = ((pktin.body[0] << 24) |
1397                                     (pktin.body[1] << 16) |
1398                                     (pktin.body[2] << 8) |
1399                                     (pktin.body[3]));
1400                 logevent("Received TIS challenge");
1401                 if (challengelen > sizeof(prompt)-1)
1402                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1403                 memcpy(prompt, pktin.body+4, challengelen);
1404                 prompt[challengelen] = '\0';
1405             }
1406         }
1407         if (pktin.type == SSH1_SMSG_FAILURE &&
1408             cfg.try_tis_auth &&
1409             (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1410             pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1411             logevent("Requested CryptoCard authentication");
1412             send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1413             crWaitUntil(ispkt);
1414             if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1415                 logevent("CryptoCard authentication declined");
1416                 c_write("CryptoCard authentication refused.\r\n", 29);
1417             } else {
1418                 int challengelen = ((pktin.body[0] << 24) |
1419                                     (pktin.body[1] << 16) |
1420                                     (pktin.body[2] << 8) |
1421                                     (pktin.body[3]));
1422                 logevent("Received CryptoCard challenge");
1423                 if (challengelen > sizeof(prompt)-1)
1424                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1425                 memcpy(prompt, pktin.body+4, challengelen);
1426                 strncpy(prompt + challengelen, "\r\nResponse : ",
1427                         sizeof(prompt)-challengelen);
1428                 prompt[sizeof(prompt)-1] = '\0';
1429             }
1430         }
1431         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1432             sprintf(prompt, "%.90s@%.90s's password: ",
1433                     username, savedhost);
1434         }
1435         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1436             char *comment = NULL;
1437             if (flags & FLAG_VERBOSE)
1438                 c_write("Trying public key authentication.\r\n", 35);
1439             if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1440                 if (flags & FLAG_VERBOSE)
1441                     c_write("No passphrase required.\r\n", 25);
1442                 goto tryauth;
1443             }
1444             sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1445             free(comment);
1446         }
1447
1448         if (ssh_get_password) {
1449             if (!ssh_get_password(prompt, password, sizeof(password))) {
1450                 /*
1451                  * get_password failed to get a password (for
1452                  * example because one was supplied on the command
1453                  * line which has already failed to work).
1454                  * Terminate.
1455                  */
1456                 logevent("No more passwords to try");
1457                 ssh_state = SSH_STATE_CLOSED;
1458                 crReturn(1);
1459             }
1460         } else {
1461             c_write(prompt, strlen(prompt));
1462             pos = 0;
1463             ssh_send_ok = 1;
1464             while (pos >= 0) {
1465                 crWaitUntil(!ispkt);
1466                 while (inlen--) switch (c = *in++) {
1467                   case 10: case 13:
1468                     password[pos] = 0;
1469                     pos = -1;
1470                     break;
1471                   case 8: case 127:
1472                     if (pos > 0)
1473                         pos--;
1474                     break;
1475                   case 21: case 27:
1476                     pos = 0;
1477                     break;
1478                   case 3: case 4:
1479                     random_save_seed();
1480                     exit(0);
1481                     break;
1482                   default:
1483                     if (((c >= ' ' && c <= '~') ||
1484                          ((unsigned char)c >= 160)) && pos < sizeof(password))
1485                         password[pos++] = c;
1486                     break;
1487                 }
1488             }
1489             c_write("\r\n", 2);
1490         }
1491
1492         tryauth:
1493         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1494             /*
1495              * Try public key authentication with the specified
1496              * key file.
1497              */
1498             static struct RSAKey pubkey;
1499             static Bignum challenge, response;
1500             static int i;
1501             static unsigned char buffer[32];
1502
1503             tried_publickey = 1;
1504             i = loadrsakey(cfg.keyfile, &pubkey, NULL, password);
1505             if (i == 0) {
1506                 c_write("Couldn't load public key from ", 30);
1507                 c_write(cfg.keyfile, strlen(cfg.keyfile));
1508                 c_write(".\r\n", 3);
1509                 continue;              /* go and try password */
1510             }
1511             if (i == -1) {
1512                 c_write("Wrong passphrase.\r\n", 19);
1513                 tried_publickey = 0;
1514                 continue;              /* try again */
1515             }
1516
1517             /*
1518              * Send a public key attempt.
1519              */
1520             send_packet(SSH1_CMSG_AUTH_RSA,
1521                         PKT_BIGNUM, pubkey.modulus, PKT_END);
1522
1523             crWaitUntil(ispkt);
1524             if (pktin.type == SSH1_SMSG_FAILURE) {
1525                 c_write("Server refused our public key.\r\n", 32);
1526                 continue;              /* go and try password */
1527             }
1528             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1529                 bombout(("Bizarre response to offer of public key"));
1530                 crReturn(0);
1531             }
1532             ssh1_read_bignum(pktin.body, &challenge);
1533             response = rsadecrypt(challenge, &pubkey);
1534             freebn(pubkey.private_exponent);   /* burn the evidence */
1535
1536             for (i = 0; i < 32; i += 2) {
1537                 buffer[i] = response[16-i/2] >> 8;
1538                 buffer[i+1] = response[16-i/2] & 0xFF;
1539             }
1540
1541             MD5Init(&md5c);
1542             MD5Update(&md5c, buffer, 32);
1543             MD5Update(&md5c, session_id, 16);
1544             MD5Final(buffer, &md5c);
1545
1546             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1547                         PKT_DATA, buffer, 16, PKT_END);
1548
1549             crWaitUntil(ispkt);
1550             if (pktin.type == SSH1_SMSG_FAILURE) {
1551                 if (flags & FLAG_VERBOSE)
1552                     c_write("Failed to authenticate with our public key.\r\n",
1553                             45);
1554                 continue;              /* go and try password */
1555             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1556                 bombout(("Bizarre response to RSA authentication response"));
1557                 crReturn(0);
1558             }
1559
1560             break;                     /* we're through! */
1561         } else {
1562             send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1563         }
1564         logevent("Sent password");
1565         memset(password, 0, strlen(password));
1566         crWaitUntil(ispkt);
1567         if (pktin.type == SSH1_SMSG_FAILURE) {
1568             if (flags & FLAG_VERBOSE)
1569                 c_write("Access denied\r\n", 15);
1570             logevent("Authentication refused");
1571         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1572             logevent("Received disconnect request");
1573             ssh_state = SSH_STATE_CLOSED;
1574             crReturn(1);
1575         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1576             bombout(("Strange packet received, type %d", pktin.type));
1577             crReturn(0);
1578         }
1579     }
1580
1581     logevent("Authentication successful");
1582
1583     crFinish(1);
1584 }
1585
1586 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1587     crBegin;
1588
1589     random_init();
1590
1591     while (!do_ssh1_login(in, inlen, ispkt)) {
1592         crReturnV;
1593     }
1594     if (ssh_state == SSH_STATE_CLOSED)
1595         crReturnV;
1596
1597     if (cfg.agentfwd && agent_exists()) {
1598         logevent("Requesting agent forwarding");
1599         send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1600         do { crReturnV; } while (!ispkt);
1601         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1602             bombout(("Protocol confusion"));
1603             crReturnV;
1604         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1605             logevent("Agent forwarding refused");
1606         } else
1607             logevent("Agent forwarding enabled");
1608     }
1609
1610     if (!cfg.nopty) {
1611         send_packet(SSH1_CMSG_REQUEST_PTY,
1612                     PKT_STR, cfg.termtype,
1613                     PKT_INT, rows, PKT_INT, cols,
1614                     PKT_INT, 0, PKT_INT, 0,
1615                     PKT_CHAR, 0,
1616                     PKT_END);
1617         ssh_state = SSH_STATE_INTERMED;
1618         do { crReturnV; } while (!ispkt);
1619         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1620             bombout(("Protocol confusion"));
1621             crReturnV;
1622         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1623             c_write("Server refused to allocate pty\r\n", 32);
1624         }
1625         logevent("Allocated pty");
1626     }
1627
1628     if (*cfg.remote_cmd)
1629         send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1630     else
1631         send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1632     logevent("Started session");
1633
1634     ssh_state = SSH_STATE_SESSION;
1635     if (size_needed)
1636         ssh_size();
1637
1638     ssh_send_ok = 1;
1639     ssh_channels = newtree234(ssh_channelcmp);
1640     begin_session();
1641     while (1) {
1642         crReturnV;
1643         if (ispkt) {
1644             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1645                 pktin.type == SSH1_SMSG_STDERR_DATA) {
1646                 long len = GET_32BIT(pktin.body);
1647                 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
1648                              pktin.body+4, len);
1649             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1650                 ssh_state = SSH_STATE_CLOSED;
1651                 logevent("Received disconnect request");
1652                 crReturnV;
1653             } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1654                 /* Remote side is trying to open a channel to talk to our
1655                  * agent. Give them back a local channel number. */
1656                 unsigned i = 1;
1657                 struct ssh_channel *c;
1658                 enum234 e;
1659                 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1660                     if (c->localid > i)
1661                         break;         /* found a free number */
1662                     i = c->localid + 1;
1663                 }
1664                 c = malloc(sizeof(struct ssh_channel));
1665                 c->remoteid = GET_32BIT(pktin.body);
1666                 c->localid = i;
1667                 c->closes = 0;
1668                 c->type = SSH1_SMSG_AGENT_OPEN;   /* identify channel type */
1669                 c->u.a.lensofar = 0;
1670                 add234(ssh_channels, c);
1671                 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1672                             PKT_INT, c->remoteid, PKT_INT, c->localid,
1673                             PKT_END);
1674             } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1675                        pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1676                 /* Remote side closes a channel. */
1677                 unsigned i = GET_32BIT(pktin.body);
1678                 struct ssh_channel *c;
1679                 c = find234(ssh_channels, &i, ssh_channelfind);
1680                 if (c) {
1681                     int closetype;
1682                     closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1683                     send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1684                     c->closes |= closetype;
1685                     if (c->closes == 3) {
1686                         del234(ssh_channels, c);
1687                         free(c);
1688                     }
1689                 }
1690             } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1691                 /* Data sent down one of our channels. */
1692                 int i = GET_32BIT(pktin.body);
1693                 int len = GET_32BIT(pktin.body+4);
1694                 unsigned char *p = pktin.body+8;
1695                 struct ssh_channel *c;
1696                 c = find234(ssh_channels, &i, ssh_channelfind);
1697                 if (c) {
1698                     switch(c->type) {
1699                       case SSH1_SMSG_AGENT_OPEN:
1700                         /* Data for an agent message. Buffer it. */
1701                         while (len > 0) {
1702                             if (c->u.a.lensofar < 4) {
1703                                 int l = min(4 - c->u.a.lensofar, len);
1704                                 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1705                                 p += l; len -= l; c->u.a.lensofar += l;
1706                             }
1707                             if (c->u.a.lensofar == 4) {
1708                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1709                                 c->u.a.message = malloc(c->u.a.totallen);
1710                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
1711                             }
1712                             if (c->u.a.lensofar >= 4 && len > 0) {
1713                                 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1714                                 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1715                                 p += l; len -= l; c->u.a.lensofar += l;
1716                             }
1717                             if (c->u.a.lensofar == c->u.a.totallen) {
1718                                 void *reply, *sentreply;
1719                                 int replylen;
1720                                 agent_query(c->u.a.message, c->u.a.totallen,
1721                                             &reply, &replylen);
1722                                 if (reply)
1723                                     sentreply = reply;
1724                                 else {
1725                                     /* Fake SSH_AGENT_FAILURE. */
1726                                     sentreply = "\0\0\0\1\5";
1727                                     replylen = 5;
1728                                 }
1729                                 send_packet(SSH1_MSG_CHANNEL_DATA,
1730                                             PKT_INT, c->remoteid,
1731                                             PKT_INT, replylen,
1732                                             PKT_DATA, sentreply, replylen,
1733                                             PKT_END);
1734                                 if (reply)
1735                                     free(reply);
1736                                 free(c->u.a.message);
1737                                 c->u.a.lensofar = 0;
1738                             }
1739                         }
1740                         break;
1741                     }
1742                 }                
1743             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1744                 /* may be from EXEC_SHELL on some servers */
1745             } else if (pktin.type == SSH1_SMSG_FAILURE) {
1746                 /* may be from EXEC_SHELL on some servers
1747                  * if no pty is available or in other odd cases. Ignore */
1748             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1749                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1750             } else {
1751                 bombout(("Strange packet received: type %d", pktin.type));
1752                 crReturnV;
1753             }
1754         } else {
1755             while (inlen > 0) {
1756                 int len = min(inlen, 512);
1757                 send_packet(SSH1_CMSG_STDIN_DATA,
1758                             PKT_INT, len, PKT_DATA, in, len, PKT_END);
1759                 in += len;
1760                 inlen -= len;
1761             }
1762         }
1763     }
1764
1765     crFinishV;
1766 }
1767
1768 /*
1769  * Utility routine for decoding comma-separated strings in KEXINIT.
1770  */
1771 static int in_commasep_string(char *needle, char *haystack, int haylen) {
1772     int needlen = strlen(needle);
1773     while (1) {
1774         /*
1775          * Is it at the start of the string?
1776          */
1777         if (haylen >= needlen &&       /* haystack is long enough */
1778             !memcmp(needle, haystack, needlen) &&    /* initial match */
1779             (haylen == needlen || haystack[needlen] == ',')
1780                                        /* either , or EOS follows */
1781             )
1782             return 1;
1783         /*
1784          * If not, search for the next comma and resume after that.
1785          * If no comma found, terminate.
1786          */
1787         while (haylen > 0 && *haystack != ',')
1788             haylen--, haystack++;
1789         if (haylen == 0)
1790             return 0;
1791         haylen--, haystack++;          /* skip over comma itself */
1792     }
1793 }
1794
1795 /*
1796  * SSH2 key creation method.
1797  */
1798 static void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1799     SHA_State s;
1800     /* First 20 bytes. */
1801     SHA_Init(&s);
1802     sha_mpint(&s, K);
1803     SHA_Bytes(&s, H, 20);
1804     SHA_Bytes(&s, &chr, 1);
1805     SHA_Bytes(&s, H, 20);
1806     SHA_Final(&s, keyspace);
1807     /* Next 20 bytes. */
1808     SHA_Init(&s);
1809     sha_mpint(&s, K);
1810     SHA_Bytes(&s, H, 20);
1811     SHA_Bytes(&s, keyspace, 20);
1812     SHA_Final(&s, keyspace+20);
1813 }
1814
1815 /*
1816  * Handle the SSH2 transport layer.
1817  */
1818 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1819 {
1820     static int i, len;
1821     static char *str;
1822     static Bignum e, f, K;
1823     static const struct ssh_mac **maclist;
1824     static int nmacs;
1825     static const struct ssh_cipher *cscipher_tobe = NULL;
1826     static const struct ssh_cipher *sccipher_tobe = NULL;
1827     static const struct ssh_mac *csmac_tobe = NULL;
1828     static const struct ssh_mac *scmac_tobe = NULL;
1829     static const struct ssh_compress *cscomp_tobe = NULL;
1830     static const struct ssh_compress *sccomp_tobe = NULL;
1831     static char *hostkeydata, *sigdata, *keystr, *fingerprint;
1832     static int hostkeylen, siglen;
1833     static unsigned char exchange_hash[20];
1834     static unsigned char keyspace[40];
1835     static const struct ssh_cipher *preferred_cipher;
1836
1837     crBegin;
1838     random_init();
1839
1840     /*
1841      * Set up the preferred cipher.
1842      */
1843     if (cfg.cipher == CIPHER_BLOWFISH) {
1844         preferred_cipher = &ssh_blowfish_ssh2;
1845     } else if (cfg.cipher == CIPHER_DES) {
1846         logevent("Single DES not supported in SSH2; using 3DES");
1847         preferred_cipher = &ssh_3des_ssh2;
1848     } else if (cfg.cipher == CIPHER_3DES) {
1849         preferred_cipher = &ssh_3des_ssh2;
1850     } else {
1851         /* Shouldn't happen, but we do want to initialise to _something_. */
1852         preferred_cipher = &ssh_3des_ssh2;
1853     }
1854
1855     /*
1856      * Be prepared to work around the buggy MAC problem.
1857      */
1858     if (cfg.buggymac)
1859         maclist = buggymacs, nmacs = lenof(buggymacs);
1860     else
1861         maclist = macs, nmacs = lenof(macs);
1862
1863     begin_key_exchange:
1864     /*
1865      * Construct and send our key exchange packet.
1866      */
1867     ssh2_pkt_init(SSH2_MSG_KEXINIT);
1868     for (i = 0; i < 16; i++)
1869         ssh2_pkt_addbyte((unsigned char)random_byte());
1870     /* List key exchange algorithms. */
1871     ssh2_pkt_addstring_start();
1872     for (i = 0; i < lenof(kex_algs); i++) {
1873         ssh2_pkt_addstring_str(kex_algs[i]->name);
1874         if (i < lenof(kex_algs)-1)
1875             ssh2_pkt_addstring_str(",");
1876     }
1877     /* List server host key algorithms. */
1878     ssh2_pkt_addstring_start();
1879     for (i = 0; i < lenof(hostkey_algs); i++) {
1880         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1881         if (i < lenof(hostkey_algs)-1)
1882             ssh2_pkt_addstring_str(",");
1883     }
1884     /* List client->server encryption algorithms. */
1885     ssh2_pkt_addstring_start();
1886     for (i = 0; i < lenof(ciphers)+1; i++) {
1887         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
1888         ssh2_pkt_addstring_str(c->name);
1889         if (i < lenof(ciphers))
1890             ssh2_pkt_addstring_str(",");
1891     }
1892     /* List server->client encryption algorithms. */
1893     ssh2_pkt_addstring_start();
1894     for (i = 0; i < lenof(ciphers)+1; i++) {
1895         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
1896         ssh2_pkt_addstring_str(c->name);
1897         if (i < lenof(ciphers))
1898             ssh2_pkt_addstring_str(",");
1899     }
1900     /* List client->server MAC algorithms. */
1901     ssh2_pkt_addstring_start();
1902     for (i = 0; i < nmacs; i++) {
1903         ssh2_pkt_addstring_str(maclist[i]->name);
1904         if (i < nmacs-1)
1905             ssh2_pkt_addstring_str(",");
1906     }
1907     /* List server->client MAC algorithms. */
1908     ssh2_pkt_addstring_start();
1909     for (i = 0; i < nmacs; i++) {
1910         ssh2_pkt_addstring_str(maclist[i]->name);
1911         if (i < nmacs-1)
1912             ssh2_pkt_addstring_str(",");
1913     }
1914     /* List client->server compression algorithms. */
1915     ssh2_pkt_addstring_start();
1916     for (i = 0; i < lenof(compressions); i++) {
1917         ssh2_pkt_addstring_str(compressions[i]->name);
1918         if (i < lenof(compressions)-1)
1919             ssh2_pkt_addstring_str(",");
1920     }
1921     /* List server->client compression algorithms. */
1922     ssh2_pkt_addstring_start();
1923     for (i = 0; i < lenof(compressions); i++) {
1924         ssh2_pkt_addstring_str(compressions[i]->name);
1925         if (i < lenof(compressions)-1)
1926             ssh2_pkt_addstring_str(",");
1927     }
1928     /* List client->server languages. Empty list. */
1929     ssh2_pkt_addstring_start();
1930     /* List server->client languages. Empty list. */
1931     ssh2_pkt_addstring_start();
1932     /* First KEX packet does _not_ follow, because we're not that brave. */
1933     ssh2_pkt_addbool(FALSE);
1934     /* Reserved. */
1935     ssh2_pkt_adduint32(0);
1936     sha_string(&exhash, pktout.data+5, pktout.length-5);
1937     ssh2_pkt_send();
1938
1939     if (!ispkt) crWaitUntil(ispkt);
1940     sha_string(&exhash, pktin.data+5, pktin.length-5);
1941
1942     /*
1943      * Now examine the other side's KEXINIT to see what we're up
1944      * to.
1945      */
1946     if (pktin.type != SSH2_MSG_KEXINIT) {
1947         bombout(("expected key exchange packet from server"));
1948         crReturn(0);
1949     }
1950     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1951     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1952     pktin.savedpos += 16;              /* skip garbage cookie */
1953     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
1954     for (i = 0; i < lenof(kex_algs); i++) {
1955         if (in_commasep_string(kex_algs[i]->name, str, len)) {
1956             kex = kex_algs[i];
1957             break;
1958         }
1959     }
1960     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
1961     for (i = 0; i < lenof(hostkey_algs); i++) {
1962         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1963             hostkey = hostkey_algs[i];
1964             break;
1965         }
1966     }
1967     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
1968     for (i = 0; i < lenof(ciphers)+1; i++) {
1969         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
1970         if (in_commasep_string(c->name, str, len)) {
1971             cscipher_tobe = c;
1972             break;
1973         }
1974     }
1975     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
1976     for (i = 0; i < lenof(ciphers)+1; i++) {
1977         const struct ssh_cipher *c = i==0 ? preferred_cipher : ciphers[i-1];
1978         if (in_commasep_string(c->name, str, len)) {
1979             sccipher_tobe = c;
1980             break;
1981         }
1982     }
1983     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
1984     for (i = 0; i < nmacs; i++) {
1985         if (in_commasep_string(maclist[i]->name, str, len)) {
1986             csmac_tobe = maclist[i];
1987             break;
1988         }
1989     }
1990     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
1991     for (i = 0; i < nmacs; i++) {
1992         if (in_commasep_string(maclist[i]->name, str, len)) {
1993             scmac_tobe = maclist[i];
1994             break;
1995         }
1996     }
1997     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
1998     for (i = 0; i < lenof(compressions); i++) {
1999         if (in_commasep_string(compressions[i]->name, str, len)) {
2000             cscomp_tobe = compressions[i];
2001             break;
2002         }
2003     }
2004     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
2005     for (i = 0; i < lenof(compressions); i++) {
2006         if (in_commasep_string(compressions[i]->name, str, len)) {
2007             sccomp_tobe = compressions[i];
2008             break;
2009         }
2010     }
2011
2012     /*
2013      * Currently we only support Diffie-Hellman and DSS, so let's
2014      * bomb out if those aren't selected.
2015      */
2016     if (kex != &ssh_diffiehellman || hostkey != &ssh_dss) {
2017         bombout(("internal fault: chaos in SSH 2 transport layer"));
2018         crReturn(0);
2019     }
2020
2021     /*
2022      * Now we begin the fun. Generate and send e for Diffie-Hellman.
2023      */
2024     e = dh_create_e();
2025     ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
2026     ssh2_pkt_addmp(e);
2027     ssh2_pkt_send();
2028
2029     crWaitUntil(ispkt);
2030     if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
2031         bombout(("expected key exchange packet from server"));
2032         crReturn(0);
2033     }
2034     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2035     f = ssh2_pkt_getmp();
2036     ssh2_pkt_getstring(&sigdata, &siglen);
2037
2038     K = dh_find_K(f);
2039
2040     sha_string(&exhash, hostkeydata, hostkeylen);
2041     sha_mpint(&exhash, e);
2042     sha_mpint(&exhash, f);
2043     sha_mpint(&exhash, K);
2044     SHA_Final(&exhash, exchange_hash);
2045
2046 #if 0
2047     debug(("Exchange hash is:\r\n"));
2048     for (i = 0; i < 20; i++)
2049         debug((" %02x", exchange_hash[i]));
2050     debug(("\r\n"));
2051 #endif
2052
2053     hostkey->setkey(hostkeydata, hostkeylen);
2054     if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20)) {
2055         bombout(("Server failed host key check"));
2056         crReturn(0);
2057     }
2058
2059     /*
2060      * Expect SSH2_MSG_NEWKEYS from server.
2061      */
2062     crWaitUntil(ispkt);
2063     if (pktin.type != SSH2_MSG_NEWKEYS) {
2064         bombout(("expected new-keys packet from server"));
2065         crReturn(0);
2066     }
2067
2068     /*
2069      * Authenticate remote host: verify host key. (We've already
2070      * checked the signature of the exchange hash.)
2071      */
2072     keystr = hostkey->fmtkey();
2073     fingerprint = hostkey->fingerprint();
2074     verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
2075                         keystr, fingerprint);
2076     logevent("Host key fingerprint is:");
2077     logevent(fingerprint);
2078     free(fingerprint);
2079     free(keystr);
2080
2081     /*
2082      * Send SSH2_MSG_NEWKEYS.
2083      */
2084     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2085     ssh2_pkt_send();
2086
2087     /*
2088      * Create and initialise session keys.
2089      */
2090     cscipher = cscipher_tobe;
2091     sccipher = sccipher_tobe;
2092     csmac = csmac_tobe;
2093     scmac = scmac_tobe;
2094     cscomp = cscomp_tobe;
2095     sccomp = sccomp_tobe;
2096     /*
2097      * Set IVs after keys.
2098      */
2099     ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
2100     ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
2101     ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
2102     ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
2103     ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
2104     ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2105
2106     /*
2107      * Now we're encrypting. Begin returning 1 to the protocol main
2108      * function so that other things can run on top of the
2109      * transport. If we ever see a KEXINIT, we must go back to the
2110      * start.
2111      */
2112     do {
2113         crReturn(1);
2114     } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2115     goto begin_key_exchange;
2116
2117     crFinish(1);
2118 }
2119
2120 /*
2121  * Handle the SSH2 userauth and connection layers.
2122  */
2123 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2124 {
2125     static unsigned long remote_winsize;
2126     static unsigned long remote_maxpkt;
2127
2128     crBegin;
2129
2130     /*
2131      * Request userauth protocol, and await a response to it.
2132      */
2133     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2134     ssh2_pkt_addstring("ssh-userauth");
2135     ssh2_pkt_send();
2136     crWaitUntilV(ispkt);
2137     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2138         bombout(("Server refused user authentication protocol"));
2139         crReturnV;
2140     }
2141
2142     /*
2143      * FIXME: currently we support only password authentication.
2144      * (This places us technically in violation of the SSH2 spec.
2145      * We must fix this.)
2146      */
2147     while (1) {
2148         /*
2149          * Get a username and a password.
2150          */
2151         static char username[100];
2152         static char password[100];
2153         static int pos = 0;
2154         static char c;
2155
2156         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2157             c_write("login as: ", 10);
2158             ssh_send_ok = 1;
2159             while (pos >= 0) {
2160                 crWaitUntilV(!ispkt);
2161                 while (inlen--) switch (c = *in++) {
2162                   case 10: case 13:
2163                     username[pos] = 0;
2164                     pos = -1;
2165                     break;
2166                   case 8: case 127:
2167                     if (pos > 0) {
2168                         c_write("\b \b", 3);
2169                         pos--;
2170                     }
2171                     break;
2172                   case 21: case 27:
2173                     while (pos > 0) {
2174                         c_write("\b \b", 3);
2175                         pos--;
2176                     }
2177                     break;
2178                   case 3: case 4:
2179                     random_save_seed();
2180                     exit(0);
2181                     break;
2182                   default:
2183                     if (((c >= ' ' && c <= '~') ||
2184                          ((unsigned char)c >= 160)) && pos < 40) {
2185                         username[pos++] = c;
2186                         c_write(&c, 1);
2187                     }
2188                     break;
2189                 }
2190             }
2191             c_write("\r\n", 2);
2192             username[strcspn(username, "\n\r")] = '\0';
2193         } else {
2194             char stuff[200];
2195             strncpy(username, cfg.username, 99);
2196             username[99] = '\0';
2197             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2198                 sprintf(stuff, "Using username \"%s\".\r\n", username);
2199                 c_write(stuff, strlen(stuff));
2200             }
2201         }
2202
2203         if (ssh_get_password) {
2204             char prompt[200];
2205             sprintf(prompt, "%.90s@%.90s's password: ", username, savedhost);
2206             if (!ssh_get_password(prompt, password, sizeof(password))) {
2207                 /*
2208                  * get_password failed to get a password (for
2209                  * example because one was supplied on the command
2210                  * line which has already failed to work).
2211                  * Terminate.
2212                  */
2213                 logevent("No more passwords to try");
2214                 ssh_state = SSH_STATE_CLOSED;
2215                 crReturnV;
2216             }
2217         } else {
2218             c_write("password: ", 10);
2219             ssh_send_ok = 1;
2220
2221             pos = 0;
2222             while (pos >= 0) {
2223                 crWaitUntilV(!ispkt);
2224                 while (inlen--) switch (c = *in++) {
2225                   case 10: case 13:
2226                     password[pos] = 0;
2227                     pos = -1;
2228                     break;
2229                   case 8: case 127:
2230                     if (pos > 0)
2231                         pos--;
2232                     break;
2233                   case 21: case 27:
2234                     pos = 0;
2235                     break;
2236                   case 3: case 4:
2237                     random_save_seed();
2238                     exit(0);
2239                     break;
2240                   default:
2241                     if (((c >= ' ' && c <= '~') ||
2242                          ((unsigned char)c >= 160)) && pos < 40)
2243                         password[pos++] = c;
2244                     break;
2245                 }
2246             }
2247             c_write("\r\n", 2);
2248         }
2249
2250         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2251         ssh2_pkt_addstring(username);
2252         ssh2_pkt_addstring("ssh-connection");   /* service requested */
2253         ssh2_pkt_addstring("password");
2254         ssh2_pkt_addbool(FALSE);
2255         ssh2_pkt_addstring(password);
2256         ssh2_pkt_send();
2257
2258         crWaitUntilV(ispkt);
2259         if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2260             c_write("Access denied\r\n", 15);
2261             logevent("Authentication refused");
2262         } else
2263             break;
2264     }
2265
2266     /*
2267      * Now we're authenticated for the connection protocol. The
2268      * connection protocol will automatically have started at this
2269      * point; there's no need to send SERVICE_REQUEST.
2270      */
2271
2272     /*
2273      * So now create a channel with a session in it.
2274      */
2275     mainchan = malloc(sizeof(struct ssh_channel));
2276     mainchan->localid = 100;           /* as good as any */
2277     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2278     ssh2_pkt_addstring("session");
2279     ssh2_pkt_adduint32(mainchan->localid);
2280     ssh2_pkt_adduint32(0x8000UL);  /* our window size */
2281     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
2282     ssh2_pkt_send();
2283     crWaitUntilV(ispkt);
2284     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2285         bombout(("Server refused to open a session"));
2286         crReturnV;
2287         /* FIXME: error data comes back in FAILURE packet */
2288     }
2289     if (ssh2_pkt_getuint32() != mainchan->localid) {
2290         bombout(("Server's channel confirmation cited wrong channel"));
2291         crReturnV;
2292     }
2293     mainchan->remoteid = ssh2_pkt_getuint32();
2294     mainchan->u.v2.remwindow = ssh2_pkt_getuint32();
2295     mainchan->u.v2.remmaxpkt = ssh2_pkt_getuint32();
2296     mainchan->u.v2.outbuffer = NULL;
2297     mainchan->u.v2.outbuflen = mainchan->u.v2.outbufsize = 0;
2298     logevent("Opened channel for session");
2299
2300     /*
2301      * Now allocate a pty for the session.
2302      */
2303     if (!cfg.nopty) {
2304         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2305         ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2306         ssh2_pkt_addstring("pty-req");
2307         ssh2_pkt_addbool(1);           /* want reply */
2308         ssh2_pkt_addstring(cfg.termtype);
2309         ssh2_pkt_adduint32(cols);
2310         ssh2_pkt_adduint32(rows);
2311         ssh2_pkt_adduint32(0);         /* pixel width */
2312         ssh2_pkt_adduint32(0);         /* pixel height */
2313         ssh2_pkt_addstring_start();
2314         ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2315         ssh2_pkt_send();
2316         ssh_state = SSH_STATE_INTERMED;
2317
2318         do {
2319             crWaitUntilV(ispkt);
2320             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2321                 /* FIXME: be able to handle other channels here */
2322                 if (ssh2_pkt_getuint32() != mainchan->localid)
2323                     continue;          /* wrong channel */
2324                 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2325             }
2326         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2327
2328         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2329             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2330                 bombout(("Server got confused by pty request"));
2331                 crReturnV;
2332             }
2333             c_write("Server refused to allocate pty\r\n", 32);
2334         } else {
2335             logevent("Allocated pty");
2336         }
2337     }
2338
2339     /*
2340      * Start a shell or a remote command.
2341      */
2342     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2343     ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2344     if (*cfg.remote_cmd) {
2345         ssh2_pkt_addstring("exec");
2346         ssh2_pkt_addbool(1);           /* want reply */
2347         ssh2_pkt_addstring(cfg.remote_cmd);
2348     } else {
2349         ssh2_pkt_addstring("shell");
2350         ssh2_pkt_addbool(1);           /* want reply */
2351     }
2352     ssh2_pkt_send();
2353     do {
2354         crWaitUntilV(ispkt);
2355         if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2356             /* FIXME: be able to handle other channels here */
2357             if (ssh2_pkt_getuint32() != mainchan->localid)
2358                 continue;          /* wrong channel */
2359             mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2360         }
2361     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2362     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2363         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2364             bombout(("Server got confused by shell/command request"));
2365             crReturnV;
2366         }
2367         bombout(("Server refused to start a shell/command"));
2368         crReturnV;
2369     } else {
2370         logevent("Started a shell/command");
2371     }
2372
2373     ssh_state = SSH_STATE_SESSION;
2374     if (size_needed)
2375         ssh_size();
2376
2377     /*
2378      * Transfer data!
2379      */
2380     ssh_send_ok = 1;
2381     begin_session();
2382     while (1) {
2383         static int try_send;
2384         crReturnV;
2385         try_send = FALSE;
2386         if (ispkt) {
2387             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2388                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2389                 char *data;
2390                 int length;
2391                 /* FIXME: be able to handle other channels here */
2392                 if (ssh2_pkt_getuint32() != mainchan->localid)
2393                     continue;          /* wrong channel */
2394                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2395                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2396                     continue;          /* extended but not stderr */
2397                 ssh2_pkt_getstring(&data, &length);
2398                 if (data) {
2399                     from_backend(pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA,
2400                                  data, length);
2401                     /*
2402                      * Enlarge the window again at the remote side,
2403                      * just in case it ever runs down and they fail
2404                      * to send us any more data.
2405                      */
2406                     ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2407                     ssh2_pkt_adduint32(mainchan->remoteid);
2408                     ssh2_pkt_adduint32(length);
2409                     ssh2_pkt_send();
2410                 }
2411             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2412                 ssh_state = SSH_STATE_CLOSED;
2413                 logevent("Received disconnect message");
2414                 crReturnV;
2415             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2416                 continue;              /* exit status et al; ignore (FIXME?) */
2417             } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2418                 continue;              /* remote sends EOF; ignore */
2419             } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2420                 /* FIXME: be able to handle other channels here */
2421                 if (ssh2_pkt_getuint32() != mainchan->localid)
2422                     continue;          /* wrong channel */
2423                 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2424                 ssh2_pkt_adduint32(mainchan->remoteid);
2425                 ssh2_pkt_send();
2426                 /* FIXME: mark the channel as closed */
2427                 if (1 /* FIXME: "all channels are closed" */) {
2428                     logevent("All channels closed. Disconnecting");
2429                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2430                     ssh2_pkt_send();
2431                     ssh_state = SSH_STATE_CLOSED;
2432                     crReturnV;
2433                 }
2434                 continue;              /* remote sends close; ignore (FIXME) */
2435             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2436                 /* FIXME: be able to handle other channels here */
2437                 if (ssh2_pkt_getuint32() != mainchan->localid)
2438                     continue;          /* wrong channel */
2439                 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2440                 try_send = TRUE;
2441             } else {
2442                 bombout(("Strange packet received: type %d", pktin.type));
2443                 crReturnV;
2444             }
2445         } else {
2446             /*
2447              * We have spare data. Add it to the channel buffer.
2448              */
2449             if (mainchan->u.v2.outbufsize <
2450                 mainchan->u.v2.outbuflen + inlen) {
2451                 mainchan->u.v2.outbufsize =
2452                     mainchan->u.v2.outbuflen + inlen + 1024;
2453                 mainchan->u.v2.outbuffer = srealloc(mainchan->u.v2.outbuffer,
2454                                                     mainchan->u.v2.outbufsize);
2455             }
2456             memcpy(mainchan->u.v2.outbuffer + mainchan->u.v2.outbuflen,
2457                    in, inlen);
2458             mainchan->u.v2.outbuflen += inlen;
2459             try_send = TRUE;
2460         }
2461         if (try_send) {
2462             /*
2463              * Try to send data on the channel if we can. (FIXME:
2464              * on _all_ channels.)
2465              */
2466             while (mainchan->u.v2.remwindow > 0 &&
2467                    mainchan->u.v2.outbuflen > 0) {
2468                 unsigned len = mainchan->u.v2.remwindow;
2469                 if (len > mainchan->u.v2.outbuflen)
2470                     len = mainchan->u.v2.outbuflen;
2471                 if (len > mainchan->u.v2.remmaxpkt)
2472                     len = mainchan->u.v2.remmaxpkt;
2473                 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2474                 ssh2_pkt_adduint32(mainchan->remoteid);
2475                 ssh2_pkt_addstring_start();
2476                 ssh2_pkt_addstring_data(mainchan->u.v2.outbuffer, len);
2477                 ssh2_pkt_send();
2478                 mainchan->u.v2.outbuflen -= len;
2479                 memmove(mainchan->u.v2.outbuffer, mainchan->u.v2.outbuffer+len,
2480                         mainchan->u.v2.outbuflen);
2481                 mainchan->u.v2.remwindow -= len;
2482             }
2483         }
2484     }
2485
2486     crFinishV;
2487 }
2488
2489 /*
2490  * Handle the top-level SSH2 protocol.
2491  */
2492 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2493 {
2494     if (do_ssh2_transport(in, inlen, ispkt) == 0)
2495         return;
2496     do_ssh2_authconn(in, inlen, ispkt);
2497 }
2498
2499 /*
2500  * Called to set up the connection.
2501  *
2502  * Returns an error message, or NULL on success.
2503  */
2504 static char *ssh_init (char *host, int port, char **realhost) {
2505     char *p;
2506         
2507 #ifdef MSCRYPTOAPI
2508     if(crypto_startup() == 0)
2509         return "Microsoft high encryption pack not installed!";
2510 #endif
2511
2512     ssh_send_ok = 0;
2513
2514     p = connect_to_host(host, port, realhost);
2515     if (p != NULL)
2516         return p;
2517
2518     return NULL;
2519 }
2520
2521 /*
2522  * Called to send data down the Telnet connection.
2523  */
2524 static void ssh_send (char *buf, int len) {
2525     if (s == NULL)
2526         return;
2527
2528     ssh_protocol(buf, len, 0);
2529 }
2530
2531 /*
2532  * Called to set the size of the window from SSH's POV.
2533  */
2534 static void ssh_size(void) {
2535     switch (ssh_state) {
2536       case SSH_STATE_BEFORE_SIZE:
2537       case SSH_STATE_CLOSED:
2538         break;                         /* do nothing */
2539       case SSH_STATE_INTERMED:
2540         size_needed = TRUE;            /* buffer for later */
2541         break;
2542       case SSH_STATE_SESSION:
2543         if (!cfg.nopty) {
2544             if (ssh_version == 1) {
2545                 send_packet(SSH1_CMSG_WINDOW_SIZE,
2546                             PKT_INT, rows, PKT_INT, cols,
2547                             PKT_INT, 0, PKT_INT, 0, PKT_END);
2548             } else {
2549                 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2550                 ssh2_pkt_adduint32(mainchan->remoteid);
2551                 ssh2_pkt_addstring("window-change");
2552                 ssh2_pkt_addbool(0);
2553                 ssh2_pkt_adduint32(cols);
2554                 ssh2_pkt_adduint32(rows);
2555                 ssh2_pkt_adduint32(0);
2556                 ssh2_pkt_adduint32(0);
2557                 ssh2_pkt_send();
2558             }
2559         }
2560     }
2561 }
2562
2563 /*
2564  * Send Telnet special codes. TS_EOF is useful for `plink', so you
2565  * can send an EOF and collect resulting output (e.g. `plink
2566  * hostname sort').
2567  */
2568 static void ssh_special (Telnet_Special code) {
2569     if (code == TS_EOF) {
2570         if (ssh_version == 1) {
2571             send_packet(SSH1_CMSG_EOF, PKT_END);
2572         } else {
2573             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2574             ssh2_pkt_adduint32(mainchan->remoteid);
2575             ssh2_pkt_send();
2576         }
2577         logevent("Sent EOF message");
2578     } else if (code == TS_PING) {
2579         if (ssh_version == 1) {
2580             send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
2581         } else {
2582             ssh2_pkt_init(SSH2_MSG_IGNORE);
2583             ssh2_pkt_addstring_start();
2584             ssh2_pkt_send();
2585         }
2586     } else {
2587         /* do nothing */
2588     }
2589 }
2590
2591 static Socket ssh_socket(void) { return s; }
2592
2593 static int ssh_sendok(void) { return ssh_send_ok; }
2594
2595 Backend ssh_backend = {
2596     ssh_init,
2597     ssh_send,
2598     ssh_size,
2599     ssh_special,
2600     ssh_socket,
2601     ssh_sendok,
2602     22
2603 };