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