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