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