Post Pacific  

Go Back   Post Pacific > Восстановленный архив > Темы без сохранившегося раздела

Notices

 
 
Thread Tools Search this Thread Display Modes
Old 04.12.2005, 10:05   #1
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default [Updated]Maybe somone else can find the problem here.

Well I started porting over a new loginserver with the latest encryption in C#, can decrypt packets fine but for some reason I keep getting bad data errors when attempting to decrypt username/password so I'm posting my mini debug version of the project in hopes that someone can help or at least use the code to share a solution with me.

UPDATE:
Found the problem, client encrypts without padding, the microsoft version of RSA doesn't support unpadded decryption, just throws Not Supported exception, mono on other hand does support raw decryption.

Removed code since its useless for windows development, but it should work on mono (don't have to test), so if anyone wants a copy you can PM me.
Sindol is offline  
Old 05.12.2005, 05:40   #2
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

hmm... throw a copy my way
Digital is offline  
Old 05.12.2005, 11:59   #3
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default Re:

Ok, I re-added the download.

As it stands, I'm thinking about just using a ported BigInteger class with a modPow function to handle decryption but I'm not 100% certain it can handle it, or for that matter how to do it since the documentation on the class is almost non-existant.

I've given up on the username/password decrypting part for now, I just validate any login calls now regardless of credentials and have moved over to working on differant parts of the emulator.

But if anyone does come up with a solution please let me know!

And ignore the sloppy way I handle connections, its just easier to use tcplistener for this little app, my actual version uses a high performance asynchronous I/O callback socket model with thread pooling that can hopefully handle around 4000 connections and Net 2.0 has some interesting new features I wanna look at, the new asynchronous accepts and socket.disconnect in particular.
Sindol is offline  
Old 05.12.2005, 13:22   #4
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

I not well know this (RSA and other), but maybe this link will usefull for you
http://www.koders.com/csharp/fid657B...68CDC310A.aspx
Idea, look the source of DecryptValue method and implement in loginserver. Also the sorcecode avalible for the mono package
navy is offline  
Old 05.12.2005, 15:37   #5
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default Re:

Thanks for the link, unfortunately all that version does is default DecryptValue to use PKCS 1.5 padding, but it looks like I might be able to pull something useful out of the source so it may not be a bust after all.
Sindol is offline  
Old 06.12.2005, 06:14   #6
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default Re

I ended up finally able to decrypt it just using the RSA decryption algorithim t = (c^d) mod m using my own power reduced modulo method.
Sindol is offline  
Old 06.12.2005, 16:33   #7
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

yeah... nice job on it
u could try sonic.net for the connect thread pool
were intending to use it on our own implementation as well
it's pretty good and easy to use
btw... do get to me on irc/icq/msn, i could drop u alot more codes to help ya with the project
Digital is offline  
Old 26.12.2005, 12:39   #8
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

I was trying to merge Mono http://svn.myrealbox.com/source/trun.../RSAManaged.cs with your first ver. of AuthD.... but it doesn't work Something I can't understand. Perhaps on MONO it is also not work
navy is offline  
Old 11.01.2006, 12:41   #9
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

I spend my xmas vacation to find solution decrypt RSA, and find that problem in generation modulus or something like this. Cause all other modifications on incoming packet give same result as in java. And if i understand right, sever must sends modulus and public exponent to client, but it sends only modulus.
So i didn't find solution...Anyone find?
navy is offline  
Old 11.01.2006, 16:28   #10
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default

The public key has to be scrambled before being sent to the client.

It can be scrambled by doing the following:

1. Swap the first 4 bytes with the last 4 bytes
2. Xor first 64 bytes with last 64 bytes
3. Xor bytes 13 - 16 with bytes 52 - 56
4. Xor last 64 bytes with first 64 bytes

I have not had any luck using C#'s RSA functions to decrypt packets tho, but I haven't been working on it too hard as I got frustrated.

Only the public modulus is sent to the client as the client can use whatever exponent it wants to encrypt the packet, the exponent isn't used in the decryption process at all.
Sindol is offline  
Old 12.01.2006, 07:05   #11
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

Yeah, I do encrypt the public key as original

So I read many docs about RSA encryption and all says that

Quote:
The public key is (n, e) and the private key is (n, d)

Encryption: c = m^e mod n
Decryption: m = c^d mod n
navy is offline  
Old 12.01.2006, 10:23   #12
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default

Ya thats correct forumula, the reason that the exponent isnt sent to the client is because 99% of the time, the exponent is either 3 or 65537 (usually this one, represented in byte[] form as 1,0,1), and since the exponent isnt used in decryption, the server could care less what the exponent is, so the client just creates its own, the only really important parts are N (public) and D (private).

The real problem with RSA and C# is that M$ thinks that everything RSA related should be padded, with either PKCS#1 v2 or PKCS#1 v1.5. Lineage 2 doesn't need to pad because the packet is always under 128 in length and there fore, never larger then the key. In Java, you can tell the RSA engine this by using NoPadding options. In C# if you try this (by using a direct crypto stream), C# will complain and either throw an exception or try to use PKCS#1 v1.5 by default, which of course screws up the decryption.

So the only option is to use the formulas yourself to decrypt, which means you'll need access to Big Integers since a 1024 bit RSA key is larger then a double. You can find many free C# versions of a BigInt on the web. Next you'll need a modpow method to perform the math on the BigInt. Last you'll need a method to perform ECB block handling on the encrypted data. The last is actually fairly easy, since the block size is the length of the key, so technically all you need to do is convert the encrypted data from little-endian to big-endian order.

The followin was my attempt at basic RSA encryption and decryption using a Big Integer class found at

http://www.codeproject.com/csharp/biginteger.asp

Code:
using System;

namespace Lineage2.Crypt
{

    public class RSAKeyPair
    {

        private BigInteger publicKey;
        private BigInteger privateKey;
        private BigInteger exponent;

        public BigInteger PublicKey
        {

            get
            {

                return publicKey;

            }
        }

        public BigInteger PrivateKey
        {

            get
            {

                return privateKey;

            }
        }

        public BigInteger Exponent
        {

            get
            {

                return exponent;

            }
        }

        public RSAKeyPair(BigInteger n, BigInteger d, BigInteger e)
        {

            publicKey = n;
            privateKey = d;
            exponent = e;

        }
    }

    public class RSAEngine
    {

        public static RSAKeyPair CreateKey(int lengthMax)
        {

            BigInteger p = FindRan(lengthMax * 4);
            BigInteger q = FindRan(lengthMax * 4);

            BigInteger n = p * q;

            BigInteger one = 1;
            BigInteger m = (p - one) * (q - one);

            BigInteger e = 65537;

            while(m.gcd(e).IntValue() > 1)
            {

                e = e + 2;

            }

            BigInteger d = e.modInverse(m);

            RSAKeyPair keyPair = new RSAKeyPair(n, d, e);

            return keyPair;

        }

        public static byte[] Decrypt(byte[] data, RSAKeyPair keyPair)
        {

            BigInteger encryptedData = new BigInteger(data, data.Length);

            BigInteger decryptedData = encryptedData.modPow(keyPair.PrivateKey, keyPair.PublicKey);

            return decryptedData.getBytes();

        }

        public static byte[] Encrypt(byte[] data, RSAKeyPair keyPair)
        {

            BigInteger decryptedData = new BigInteger(data, data.Length);

            BigInteger encryptedData = decryptedData.modPow(keyPair.Exponent, keyPair.PublicKey);

            return encryptedData.getBytes();

        }

        private static BigInteger FindRan(int lengthKey)
        {

            Random rn = new Random();
            BigInteger rnI = BigInteger.genPseudoPrime(lengthKey, 100, rn);

            return rnI;

        }
    }
}
This will encrypt and decrypt using RSA, but for reasons beyond me, it cannot decrypt packets sent from Lineage 2 client and I could never find out why, but you can take a look at it to see what has to be done to encrypt and decrypt without using M$'s RSACryptoServiceProvider.

Here's an example of how to use it:

Code:
// Byte Converter
System.Text.ASCIIEncoding ByteConverter = new System.Text.ASCIIEncoding();

// Create New Key Pair Using 1024bit strength
RSAKeyPair keyPair = RSAEngine.CreateKey(128);

String dataString = "This is my data to encrypt.";

Byte[] rawData = ByteConverter.GetBytes(dataString);

Byte[] encryptedData = RSAEngine.Encrypt(rawData, keyPair);

Console.WriteLine("Encrypted Data: {0}", ByteConverter.GetString(encryptedData));

Byte[] decryptedData = RSAEngine.Decrypt(encryptedData, keyPair);

Console.WriteLine("Decrypted Data: {0}", ByteConverter.GetString(decryptedData));
Sindol is offline  
Old 19.01.2006, 05:43   #13
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

Yes!! Finally I've made it!!
navy is offline  
Old 19.01.2006, 06:38   #14
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default

Have you decrypted the RSA in C#, share how you did it, cause I still have yet to reliably do it.
Sindol is offline  
Old 19.01.2006, 07:03   #15
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

Yes... it was today about 0.30 AM I use BigInteger class for encripting and dercrypting. For some reason decrypted packet goes shrinked, all leading null-bytes are missing, but I think it not to important... So, now I've changed offsets, and can get login and password. I want to test some other parts where RSA decryption used, and if all fine, I'll share it.
navy is offline  
Old 19.01.2006, 20:31   #16
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

Here complete pack of RSA implemetation taken from Mono. I've just changed thi namespace for my needs. It can be use as normal RSACryptoServiceProvider

This is 7zip archive renamed to *.rar
navy is offline  
Old 19.01.2006, 23:33   #17
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default

Interesting, how are you going about decrypting the packet, are you using the RSAManaged class or just using the BigInteger class.

I tried both and neither method decrypted the packet so I might have used them wrong. I'd like to see the section of code you use to decrypt the packet and get the username and password to see where I'm going wrong.
Sindol is offline  
Old 20.01.2006, 07:26   #18
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

I've found one error in your first AuthD and in my code, that Iappend to it. Here is yours In server.c you ctreate
Code:
				new ClientThread(stream, rsaPrivateParams, rsaPublicParams, scrambledModulus);
but constructor for ClientThread looks like
Code:
		public ClientThread(NetworkStream conn, RSAParameters rsaPublic, RSAParameters rsaPrivate, byte[] scrambled)
Private->Public

and here is RequestAuthLogin
Code:
		public RequestAuthLogin(byte[] rawPacket, RSAParameters rsaPrivateParams)
		{
			try
			{

				Console.WriteLine("[RequestLoginAuth] :: Incoming Packet Length: {0}", rawPacket.Length);
				Console.WriteLine(PrintData(rawPacket, rawPacket.Length));

				Console.WriteLine("\n");

				byte[] decrypted = new byte[0x80];
				Array.Copy(rawPacket, 1, decrypted, 0, decrypted.Length);

				Console.WriteLine("\n");

				RSAManaged rsaDecryptor = new RSAManaged();
				rsaDecryptor.ImportParameters(rsaPrivateParams);

				byte[] result = rsaDecryptor.DecryptValue(decrypted);

				Console.WriteLine("[RequestLoginAuth] :: Decrypted Packet Length: {0}", result.Length);
				Console.WriteLine(PrintData(result, result.Length));

				Console.WriteLine("\n");

				char [] dec = new char [result.Length];
				result.CopyTo(dec,0);

				username = new System.String(dec, 0x02, 14).Trim();
				username = username.ToLower();
				password = new string(dec, 0x11, 16).Trim();

				Console.WriteLine("[RequestLoginAuth] :: username: " + username + " password: " + password + "\n");
			}
			catch(Exception ex)
			{

				Console.WriteLine("[RequestAuthLogin] :: Error Decrypting Login");
				Console.WriteLine("[RequestAuthLogin] :: Error Message:\n");
				Console.WriteLine(ex.Message);

			}
		}
navy is offline  
Old 20.01.2006, 14:02   #19
Sindol
Архивный участник
 
Join Date: Oct 2005
Posts: 21
Default

Well I see where I went wrong, and all is good now, great work!!!!

Just remember though, C# String.Trim doesn't remove null terminators, so you'll probably wanna change:

username = new System.String(dec, 0x02, 14).Trim();
username = username.ToLower();
password = new string(dec, 0x11, 16).Trim();

To:

String trimString = "\0 ";
username = new System.String(dec, 0x02, 4).Trim(trimString.ToCharArray());
username = username.ToLower();
password = new string(dec, 0x11, 16).Trim(trimString.ToCharArray());


I think we're the first people to crack C4 encryption in C#, woot! Though I did it differant, I didn't use RSAManaged at all, I just used BigIntegers to do it, I'm not too concerned with all the extra crap from RSAManaged like keyblinding and what not, to think all that effort looking for a new way to decrypt it and I had it all along except for a tiny little mistake in my code. That'll teach me. But again, good job on all the work!
Sindol is offline  
Old 04.03.2006, 02:18   #20
Rikimaru
Архивный участник
 
Join Date: Sep 2005
Posts: 14
Default

Can any of you post your work with the encryption. I myself am willing to work more on GameServer stuff but i will need that part to start working at all.
Rikimaru is offline  
Old 04.03.2006, 21:10   #21
Livid
Архивный участник
 
Join Date: Apr 2005
Posts: 314
Default

... was it not posted, eh? Use ur brain
Livid is offline  
Old 06.03.2006, 09:04   #22
FlyDragon
Архивный участник
 
Join Date: Mar 2006
Posts: 1
Default

Heya, did u guys worked on off (lineage2.com) login server encryption (non blowfish based)?
If so, any results? Thx.
FlyDragon is offline  
Old 06.03.2006, 13:22   #23
navy
Архивный участник
 
Join Date: Nov 2005
Posts: 41
Default

no, it's blowfish I do not know what is in OFF server.....
navy is offline  
Old 08.03.2006, 13:26   #24
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

http://freepository.com
^ some new free repository that emailed me..
thought it might come in handy for u guys if your ever want to code together or something

(P.S how status so far? :x)
Digital is offline  
Old 11.03.2006, 20:12   #25
BoyStav
Архивный участник
 
Join Date: Mar 2006
Posts: 2
Default

I'm still have a problems with RSA decription, all tests havn't any realy result, help to me please

my decrypt code:

Code:
public RequestAuthLogin(byte[] rawPacket, RSAParameters rsaParameters)
        {
            try
            {
                byte[] toDecrypt = new byte[0x80];
                Array.Copy(rawPacket, 0x01, toDecrypt, 0x00, 0x80);

                RSAManaged rsaManaged = new RSAManaged(1024);

                rsaManaged.ImportParameters(rsaParameters);

                byte[] decripted = rsaManaged.DecryptValue(toDecrypt);

                //Array.Reverse(decripted);

                using (StreamWriter sw = new StreamWriter("TestFile.txt"))
                {
                    for (int i = 0; i < decripted.Length; i++)
                    {
                        sw.WriteLine("\n{0:x2}:", i);
                        sw.WriteLine("Def: {0}", Encoding.Default.GetString(toDecrypt, i, decripted.Length - i));
                        sw.WriteLine("ASCII: {0}", Encoding.ASCII.GetString(toDecrypt, i, decripted.Length - i));
                        sw.WriteLine("UTF8: {0}", Encoding.UTF8.GetString(toDecrypt, i, decripted.Length - i));
                        sw.WriteLine("UNI: {0}", Encoding.BigEndianUnicode.GetString(toDecrypt, i, decripted.Length - i));
                    }
                }
                
                //password = new string(dec, 0x11, 16).Trim(trimString.ToCharArray()); 

                //byte[] decripted = rsaProvider.Decrypt(toDecrypt, false);
                //user = new String(decrypted, 0x62, 14).trim();
                //user = _user.toLowerCase();
                //password = new String(decrypted, 0x70, 16).trim();
            }
            catch(CryptographicException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
BoyStav is offline  
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 20:31.