Skip to content

Commit

Permalink
Make this not suck, return public key, and actually sign data
Browse files Browse the repository at this point in the history
  • Loading branch information
jonbarrow committed Jun 30, 2023
1 parent 9b9333e commit 67406a7
Show file tree
Hide file tree
Showing 3 changed files with 192 additions and 63 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -399,4 +399,6 @@ FodyWeavers.xsd

# custom
bin
obj
obj
*.pem
.env
3 changes: 3 additions & 0 deletions PKHaX.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="dotenv.net" Version="3.1.2" />
<PackageReference Include="System.Resources.Extensions" Version="6.0.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="PKHeX.Core" Version="22.6.1" />
Expand Down
248 changes: 186 additions & 62 deletions server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,99 +3,223 @@
using System.Text;
using System.Net;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Collections.Generic;
using PKHeX.Core;
using dotenv.net;

namespace PKHaX {
class Server {
public static HttpListener listener;

public static string protocol = "http";
public static int port = 80;

public static byte[] ILLEGAL_POKEMON_MAGIC = new byte[] { 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0A };
public static string protocol = "http";
public static int port = 9000;
public static byte[] EXPECTED_CERTIFICATE_ID = new byte[] { 0xFF, 0xFF };
public static byte[] INVALID_CERTIFICATE_ID_RESPONSE = new byte[] { 0x02 };
public static byte[] ILLEGAL_POKEMON_RESPONSE = new byte[] { 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0A };
public static byte[] LEGAL_POKEMON_MAGIC = new byte[] { 0x00, 0x00, 0x01,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69, 0x6B, 0xF7, 0xCD, 0x45, 0xBC,
0x69, 0xE0, 0xB9, 0x14, 0x8A, 0xC9, 0x35, 0x56, 0x4B, 0xE8, 0x3D, 0x29,
0x9A, 0xF5, 0xCB, 0xEB, 0x2A, 0x14, 0x8D, 0x96, 0x1C, 0x42, 0x09, 0x7D,
0xED, 0xEB, 0xA7, 0x00, 0xEE, 0xA4, 0x0D, 0x65, 0x26, 0x3C, 0xDE, 0x47,
0x83, 0x64, 0x90, 0xE1, 0xA7, 0x11, 0x4C, 0xDA, 0x12, 0x64, 0x97, 0xA8,
0xED, 0x9F, 0xC8, 0xFE, 0x12, 0x65, 0x78, 0xB2, 0x60, 0x86, 0xE0, 0x02,
0x28, 0xC4, 0x5A, 0x17, 0x7B, 0xE4, 0xBF, 0xA3, 0x10, 0x51, 0x18, 0x9E,
0x9A, 0xEB, 0xEC, 0x63
};
public static RSA RSA_KEY_PAIR = RSA.Create();

public static Dictionary<string, Dictionary<string, Func<HttpListenerRequest, byte[]>>> REQUEST_HANDLERS = new Dictionary<string, Dictionary<string, Func<HttpListenerRequest, byte[]>>>();

public static async Task HandleIncomingConnections() {
while (true) {
HttpListenerContext ctx = await listener.GetContextAsync();

HttpListenerRequest req = ctx.Request;
HttpListenerResponse resp = ctx.Response;
HttpListenerRequest request = ctx.Request;
HttpListenerResponse response = ctx.Response;

resp.StatusCode = 404;
response.StatusCode = 404;

if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/validator/v1/validate")) {
MemoryStream ms = new MemoryStream();
req.InputStream.CopyTo(ms);
if (REQUEST_HANDLERS.ContainsKey(request.HttpMethod)) {
Dictionary<string, Func<HttpListenerRequest, byte[]>> methodHandlers = REQUEST_HANDLERS[request.HttpMethod];

byte[] body = ms.ToArray();
if (methodHandlers.ContainsKey(request.Url.AbsolutePath)) {
Func<HttpListenerRequest, byte[]> handler = methodHandlers[request.Url.AbsolutePath];
byte [] responseData = handler(request);

byte[] serviceToken = new byte[0x58];
byte[] unknown = new byte[0xA7];
byte[] encryptedPkm = new byte[0xE8];
response.ContentLength64 = responseData.LongLength;
response.StatusCode = 200;

Array.Copy(body, 0, serviceToken, 0, 0x58);
Array.Copy(body, 0x58, unknown, 0, 0xA7);
Array.Copy(body, 0x58 + 0xA7, encryptedPkm, 0, 0xE8);
await response.OutputStream.WriteAsync(responseData, 0, responseData.Length);
}
}

var pkm = new PK6(encryptedPkm);
var la = new LegalityAnalysis(pkm);
response.Close();
}
}

byte[] responseData;
public static byte[] ValidatorV1Validate(HttpListenerRequest req) {
MemoryStream ms = new MemoryStream();
req.InputStream.CopyTo(ms);

if (la.Valid) {
responseData = new byte[0x107];
Array.Copy(LEGAL_POKEMON_MAGIC, 0, responseData, 0, LEGAL_POKEMON_MAGIC.Length);
Array.Copy(POKEMON_SIG, 0, responseData, LEGAL_POKEMON_MAGIC.Length, POKEMON_SIG.Length);
byte[] body = ms.ToArray();

// Real server sends back an RSA-256 signature here
// after the magic
byte[] serviceToken = new byte[0x58];
byte[] unknown = new byte[0xA7];
byte[] encryptedPokemon = new byte[0xE8];

// We do not have the private key, and the public key
// is requested one time when making a new save and
// stored in the save file, making it risky to patch
int serviceTokenOffset = 0;
int unknownOffset = serviceTokenOffset + serviceToken.Length;
int encryptedPokemonOffset = unknownOffset + unknown.Length;

// Leaving signature as all null bytes for now
} else {
responseData = new byte[0x07];
Array.Copy(ILLEGAL_POKEMON_MAGIC, 0, responseData, 0, ILLEGAL_POKEMON_MAGIC.Length);
}
Array.Copy(body, serviceTokenOffset, serviceToken, 0, serviceToken.Length);
Array.Copy(body, unknownOffset, unknown, 0, unknown.Length);
Array.Copy(body, encryptedPokemonOffset, encryptedPokemon, 0, encryptedPokemon.Length);

// TODO - VERIFY SERVICE TOKEN

byte[] certificateID = new byte[0x2];

Array.Copy(unknown, 0, certificateID, 0, certificateID.Length);

if (!certificateID.SequenceEqual(EXPECTED_CERTIFICATE_ID)) {
return INVALID_CERTIFICATE_ID_RESPONSE;
}

PK6 pokemon = new PK6(encryptedPokemon);
LegalityAnalysis legalityAnalysis = new LegalityAnalysis(pokemon);

if (!legalityAnalysis.Valid) {
return ILLEGAL_POKEMON_RESPONSE;
}

HashAlgorithmName algorithm = HashAlgorithmName.SHA256;
RSASignaturePadding padding = RSASignaturePadding.Pkcs1;

// * WE DON'T ACTUALLY KNOW WHAT DATA THIS SIGNATURE IS OVER!
// * LEAVING IT LIKE THIS FOR NOW UNTIL WE FIND IT
byte[] signature = RSA_KEY_PAIR.SignData(encryptedPokemon, 0, encryptedPokemon.Length, algorithm, padding);
byte[] responseData = new byte[LEGAL_POKEMON_MAGIC.Length + signature.Length];

Array.Copy(LEGAL_POKEMON_MAGIC, 0, responseData, 0, LEGAL_POKEMON_MAGIC.Length);
Array.Copy(signature, 0, responseData, LEGAL_POKEMON_MAGIC.Length, signature.Length);

return responseData;
}

public static byte[] ValidatorV1PublicKey(HttpListenerRequest req) {
// TODO - VERIFY SERVICE TOKEN

// TODO - Is there a better way to do this? I'm new to c# 💀
byte[] publicKeyBytes = RSA_KEY_PAIR.ExportRSAPublicKey();
string publicKeyBase64String = System.Convert.ToBase64String(publicKeyBytes);
byte[] publicKeyBase64Bytes = Encoding.ASCII.GetBytes(publicKeyBase64String);

byte[] responseData = new byte[EXPECTED_CERTIFICATE_ID.Length + publicKeyBase64Bytes.Length];

Array.Copy(EXPECTED_CERTIFICATE_ID, 0, responseData, 0, EXPECTED_CERTIFICATE_ID.Length);
Array.Copy(publicKeyBase64Bytes, 0, responseData, EXPECTED_CERTIFICATE_ID.Length, publicKeyBase64Bytes.Length);

return responseData;
}

public static void ImportRSAKey() {
string privateKeyPath = System.Environment.GetEnvironmentVariable("PKHAX_PRIVATE_KEY_PATH");

if (String.IsNullOrEmpty(privateKeyPath)) {
Console.WriteLine("PKHAX_PRIVATE_KEY_PATH is not set. Set PKHAX_PRIVATE_KEY_PATH to the path of your RSA 2048 private key PEM");
System.Environment.Exit(1);
}

resp.ContentLength64 = responseData.LongLength;
resp.StatusCode = 200;
if (!File.Exists(privateKeyPath)) {
Console.WriteLine("File {0} does not exist. Set PKHAX_PRIVATE_KEY_PATH to the path of your RSA 2048 private key PEM", privateKeyPath);
System.Environment.Exit(1);
}

try {
string privateKeyText = File.ReadAllText(privateKeyPath);

RSA_KEY_PAIR.ImportFromPem(privateKeyText);
} catch (System.Exception) {
Console.WriteLine("Invalid RSA private key PEM");
throw;
}

// * RSA keys can only be 2048
if (RSA_KEY_PAIR.KeySize != 2048) {
Console.WriteLine("Invalid RSA key size. Expected 2048, got {0}", RSA_KEY_PAIR.KeySize);
System.Environment.Exit(1);
}

// * Dirty check to see if the key pair really contains a private key
// TODO - Better way to do this?
try {
RSA_KEY_PAIR.ExportRSAPrivateKey();
} catch (System.Exception) {
Console.WriteLine("RSA key provided is not a private key. Please provide an RSA 2048 private key");
throw;
}
}

public static void CreateRequestHandlers() {
Dictionary<string, Func<HttpListenerRequest, byte[]>> POSTHandlers = new Dictionary<string, Func<HttpListenerRequest, byte[]>>();

POSTHandlers.Add("/validator/v1/validate", ValidatorV1Validate);
POSTHandlers.Add("/validator/v1/public_key", ValidatorV1PublicKey);

REQUEST_HANDLERS.Add("POST", POSTHandlers);
}

public static void CheckEnvironmentVariables() {
CheckPortEnvironmentVariable();
CheckCertificateIDEnvironmentVariable();
}

await resp.OutputStream.WriteAsync(responseData, 0, responseData.Length);
public static void CheckPortEnvironmentVariable() {
string customPortString = System.Environment.GetEnvironmentVariable("PKHAX_PORT");

if (!String.IsNullOrEmpty(customPortString)) {
if (Int32.TryParse(customPortString, out int customPort)) {
port = customPort;
} else {
Console.WriteLine("{0} is not a valid number. Using default port {1}", customPortString, port);
}
} else {
Console.WriteLine("No port set. Using default port {0}", port);
}
}

public static void CheckCertificateIDEnvironmentVariable() {
string customCertificateIDString = System.Environment.GetEnvironmentVariable("PKHAX_CERTIFICATE_ID");

if (!String.IsNullOrEmpty(customCertificateIDString)) {
int hexLength = customCertificateIDString.Length;

if (hexLength != 4) {
Console.WriteLine("Invalid certificate ID. Certificate IDs must be set as exactly 2 bytes represented as 4 hex characters (ex, ABCD), got {0}", customCertificateIDString);
System.Environment.Exit(1);
}

resp.Close();
byte[] bytes = new byte[hexLength / 2];
for (int i = 0; i < hexLength; i += 2) {
string chunk = customCertificateIDString.Substring(i, 2);

try {
bytes[i / 2] = Convert.ToByte(chunk, 16);
} catch (System.Exception) {
Console.WriteLine("Invalid certificate ID. Chunk {0} is not valid hex. Certificate IDs must be set as exactly 2 bytes represented as 4 hex characters (ex, ABCD)", chunk);
System.Environment.Exit(1);
}
}

EXPECTED_CERTIFICATE_ID = bytes;

Console.WriteLine("Using certificate ID {0}", Convert.ToHexString(bytes));
} else {
Console.WriteLine("No certificate ID set. Using default ID {0}", Convert.ToHexString(EXPECTED_CERTIFICATE_ID));
}
}

public static void Main(string[] args) {
DotEnv.Load();

ImportRSAKey();
CreateRequestHandlers();
CheckEnvironmentVariables();

// TODO - It would be nice to display the current PKHeX version at startup

string prefix = string.Format("{0}://*:{1}/", protocol, port);

listener = new HttpListener();
Expand Down

0 comments on commit 67406a7

Please sign in to comment.