View Full Version : [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.
hmm... throw a copy my way :)
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.
I not well know this (RSA and other), but maybe this link will usefull for you
http://www.koders.com/csharp/fid657BDE835FA0FC732E9C14336ADC50968CDC310A.aspx
Idea, look the source of DecryptValue method and implement in loginserver. Also the sorcecode avalible for the mono package
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.
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.
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
I was trying to merge Mono http://svn.myrealbox.com/source/trunk/mcs/class/Mono.Security/Mono.Security.Cryptography/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
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?
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.
Yeah, I do encrypt the public key as original :)
So I read many docs about RSA encryption and all says that
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
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
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:
// 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));
Yes!! :) Finally I've made it!!
Have you decrypted the RSA in C#, share how you did it, cause I still have yet to reliably do it.
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. :)
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
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.
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
new ClientThread(stream, rsaPrivateParams, rsaPublicParams, scrambledModulus);
but constructor for ClientThread looks like
public ClientThread(NetworkStream conn, RSAParameters rsaPublic, RSAParameters rsaPrivate, byte[] scrambled)
Private->Public :)
and here is RequestAuthLogin
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);
}
}
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!
Rikimaru
04.03.2006, 02:18
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.
... was it not posted, eh? Use ur brain :)
FlyDragon
06.03.2006, 09:04
Heya, did u guys worked on off (lineage2.com) login server encryption (non blowfish based)?
If so, any results? Thx.
no, it's blowfish I do not know what is in OFF server.....
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)
I'm still have a problems with RSA decription, all tests havn't any realy result, help to me please
my decrypt 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);
}
}
here is complete code for the method
/// <summary>
/// Create new instance of RequestAuthLogin.
/// </summary>
/// <param name="rawPacket">Packet to decrypt.</param>
/// <param name="_key">RSA Private Key</param>
public RequestAuthLogin(byte[] rawPacket, RSAParameters _key)
{
try
{
RSAManaged RSADecryptor = new RSAManaged();
RSADecryptor.ImportParameters(_key);
byte[] _tmp = new byte[0x80];
Array.Copy(rawPacket, 1, _tmp, 0, _tmp.Length);
byte[] decrypted = RSADecryptor.DecryptValue(_tmp);
char[] chr = new char[1] {'\x00'};
char[] tmpChar;
tmpChar = new char[decrypted.Length];
decrypted.CopyTo(tmpChar, 0);
_user = new System.String(tmpChar, 0x2, 14).Trim(chr);
_user = _user.ToLower();
_password = new System.String(tmpChar, 0x11, 16).Trim(chr);
if (Config.DEBUG) Console.WriteLine("[RequestLoginAuth] :: username: '" + _user + "' password: '" + _password + "'\n");
}
catch (CryptographicException e)
{
SupportClass.ErrorLog(e.Message);
}
}
navy, answer me on icq - 203833915:)
I solved this problem, my login server works with old and with new auth protocol.
As you can see, I solved this problem almost 2 month ago ;) . And now I have complete LoginServer and part of GameServer, and they normaly works with c3-c4 client. But now I have not time for farther work. Main thing now is a client engine on gameserv... I try to understand khow it works in java ;) but I do not know java :D
how do you know decryption key?
what are the stats off th c server i wan to help i the sql mod inplandet?
i'm not really sure either :\
but at least i'm started some work on implementing mssql for the other version of the open source for l2c#
havent really got time to go design a more complete version...
if u wish to have a copy of it..
i could always upload it and let u guys have a go at it...
since i'm sure there's tons of people who has time on their hands :)
-out