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