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