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