This commit is contained in:
lhodges1 2023-09-11 02:30:46 +10:00
parent c694ee02c2
commit da1dca21a1
7 changed files with 97 additions and 84 deletions

View file

@ -1,4 +1,6 @@
using System;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
@ -12,20 +14,26 @@ namespace server
{
public class Helper
{
unsafe public static T BytesToStructure<T>(ref byte[] buffer, int offset)
unsafe public static T BytesToStructure<T>(byte[] buffer, int offset)
{
//int typeSize = Marshal.SizeOf(typeof(T));
int typeSize = buffer.Length - offset;
int typeSize = Marshal.SizeOf(typeof(T));
if (buffer.Length == 0)
return default(T);
IntPtr ptr = Marshal.AllocHGlobal(typeSize);
try
{
Marshal.Copy(buffer, offset, ptr, typeSize);
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
finally
{
T result = (T)Marshal.PtrToStructure(ptr, typeof(T));
Marshal.FreeHGlobal(ptr);
return result;
}
catch(Exception ex)
{
Log.Information(ex.Message);
return default(T);
}
}
@ -39,11 +47,13 @@ namespace server
{
Marshal.StructureToPtr(structure, ptr, true);
Marshal.Copy(ptr, buffer, 0, typeSize);
Marshal.FreeHGlobal(ptr);
return buffer;
}
finally
catch (Exception ex)
{
Marshal.FreeHGlobal(ptr);
Log.Information(ex.Message);
return null;
}
}

View file

@ -57,6 +57,11 @@ namespace server
public int reason;
}
private struct REPORT_RESPONSE
{
public int success;
}
private enum USER_BAN_REASONS
{
HARDWARE_BAN = 10,
@ -90,29 +95,41 @@ namespace server
private PACKET_HEADER GetMessageHeader()
{
return Helper.BytesToStructure<PACKET_HEADER>(ref _buffer, 0);
return Helper.BytesToStructure<PACKET_HEADER>(_buffer, 0);
}
unsafe private PACKET_REQUEST_HEADER GetPacketRequestId()
{
return Helper.BytesToStructure<PACKET_REQUEST_HEADER>(ref _buffer, sizeof(PACKET_HEADER));
return Helper.BytesToStructure<PACKET_REQUEST_HEADER>(_buffer, sizeof(PACKET_HEADER));
}
unsafe private CLIENT_SEND_PACKET_HEADER GetClientSendPacketHeader()
{
return Helper.BytesToStructure<CLIENT_SEND_PACKET_HEADER>(ref _buffer, sizeof(PACKET_HEADER));
return Helper.BytesToStructure<CLIENT_SEND_PACKET_HEADER>(_buffer, sizeof(PACKET_HEADER));
}
unsafe private void HandleReportMessage(int reportId)
{
OPEN_HANDLE_FAILURE_REPORT openHandleFailure =
Helper.BytesToStructure<OPEN_HANDLE_FAILURE_REPORT>(ref _buffer, sizeof(PACKET_HEADER));
Helper.BytesToStructure<OPEN_HANDLE_FAILURE_REPORT>(_buffer, sizeof(PACKET_HEADER));
_logger.Information("Report code: {0}, ProcessID: {1:x}, ThreadId: {2:x}, DesiredAccess{3:x}",
openHandleFailure.ReportCode,
openHandleFailure.ProcessId,
openHandleFailure.ThreadId,
openHandleFailure.DesiredAccess);
BuildReportResponseMessage(1);
}
private void BuildReportResponseMessage(int success)
{
REPORT_RESPONSE response = new REPORT_RESPONSE();
response.success = 1;
byte[] responseBytes = Helper.StructureToBytes<REPORT_RESPONSE>(ref response);
_networkStream.Write(responseBytes, 0, responseBytes.Length);
}
private void HandleClientSendMessage(int clientSendId)
@ -132,19 +149,9 @@ namespace server
{
_logger.Information("Handling client send hardware information");
string moboSerial = Helper.FixedUnsafeBufferToSafeString(
ref _buffer, _bufferSize, sizeof(PACKET_HEADER) + sizeof(CLIENT_SEND_PACKET_HEADER), 32);
PACKET_CLIENT_HARDWARE_INFORMATION info = Helper.BytesToStructure<PACKET_CLIENT_HARDWARE_INFORMATION>(_buffer, sizeof(PACKET_HEADER) + sizeof(CLIENT_SEND_PACKET_HEADER));
if (moboSerial == null)
return;
string driveSerial = Helper.FixedUnsafeBufferToSafeString(
ref _buffer, _bufferSize, sizeof(PACKET_HEADER) + sizeof(CLIENT_SEND_PACKET_HEADER) + 32, 32);
if (driveSerial == null)
return;
_logger.Information("SteamId: {0}, Mobo Serial: {1}, drive serial: {2}", _header.steam64_id, moboSerial, driveSerial);
_logger.Information("SteamId: {0}, Mobo Serial: {1}, drive serial: {2}", _header.steam64_id, info.MotherboardSerialNumber, info.DeviceDriver0Serial);
using (var context = new ModelContext())
{
@ -169,8 +176,8 @@ namespace server
var hardwareConfiguration = new HardwareConfigurationEntity(context)
{
DeviceDrive0Serial = driveSerial,
MotherboardSerial = moboSerial,
DeviceDrive0Serial = info.DeviceDriver0Serial,
MotherboardSerial = info.MotherboardSerialNumber,
User = user
};
@ -203,7 +210,7 @@ namespace server
byte[] responseBytes = Helper.StructureToBytes<SYSTEM_INFORMATION_REQUEST_RESPONSE>(ref response);
_networkStream.Write(responseBytes, 0, Marshal.SizeOf(response));
_networkStream.Write(responseBytes, 0, responseBytes.Length);
}
}
}

View file

@ -40,7 +40,6 @@ namespace server
using (MemoryStream stream = new MemoryStream())
{
while (_stream.DataAvailable)
{
bytesRead = _stream.Read(buffer, 0, buffer.Length);

View file

@ -20,11 +20,13 @@ namespace server
public int PacketSize;
};
[StructLayout(LayoutKind.Sequential)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public unsafe struct PACKET_CLIENT_HARDWARE_INFORMATION
{
public fixed char MotherboardSerialNumber[32];
public fixed char DeviceDriver0Serial[32];
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string MotherboardSerialNumber;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DeviceDriver0Serial;
}
}
@ -80,7 +82,7 @@ namespace server
public fixed char ModuleName[128];
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public unsafe struct OPEN_HANDLE_FAILURE_REPORT
{
public int ReportCode;
@ -88,7 +90,8 @@ namespace server
public uint ProcessId;
public uint ThreadId;
public uint DesiredAccess;
public fixed char ProcessName[64];
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string processName;
}
}

View file

@ -9,39 +9,38 @@ namespace service
{
public class Client
{
private readonly Serilog.ILogger _logger;
private IPEndPoint _ipEndPoint;
private TcpClient _tcpClient;
private NetworkStream _stream;
private byte[] _buffer;
private int _bufferSize;
public Client(ref byte[] buffer, int bufferSize)
public Client(ref byte[] buffer, int bufferSize, Serilog.ILogger logger)
{
_logger = logger;
_ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
_tcpClient = new TcpClient();
_tcpClient.Connect(_ipEndPoint);
_stream = _tcpClient.GetStream();
_buffer = buffer;
_bufferSize = bufferSize;
}
public void SendMessageToServer()
{
_tcpClient.Connect(_ipEndPoint);
NetworkStream stream = _tcpClient.GetStream();
stream.BeginWrite(_buffer, 0, _bufferSize, null, null);
_stream.BeginWrite(_buffer, 0, _bufferSize, null, null);
}
public async Task<byte[]> GetResponseFromServer()
public byte[] GetResponseFromServer()
{
byte[] buffer = new byte[1024];
NetworkStream stream = _tcpClient.GetStream();
using (MemoryStream memoryStream = new MemoryStream())
{
while (stream.DataAvailable)
{
await stream.ReadAsync(buffer, 0, 1024);
memoryStream.Write(buffer, 0, buffer.Length);
}
int bytesRead = _stream.Read(buffer, 0, 1024);
memoryStream.Write(buffer, 0, bytesRead);
return memoryStream.ToArray();
}

View file

@ -6,6 +6,7 @@ using System.Reflection.PortableExecutable;
using System.Net.Sockets;
using System.Net;
using System.Net.Http;
using Serilog;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
#pragma warning disable CS8600
@ -15,28 +16,28 @@ namespace service
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly Serilog.ILogger _logger;
private NamedPipeServerStream _pipeServer;
private byte[] _buffer;
private int _bufferSize;
private static int MAX_BUFFER_SIZE = 60000;
private static int MAX_BUFFER_SIZE = 8192;
public Worker(ILogger<Worker> logger)
public Worker(Serilog.ILogger logger)
{
_logger = logger;
_pipeServer = new NamedPipeServerStream("DonnaACPipe", PipeDirection.InOut, 1);
_pipeServer = new NamedPipeServerStream("DonnaACPipe", PipeDirection.InOut, 1, 0, PipeOptions.Asynchronous);
_bufferSize = MAX_BUFFER_SIZE;
_buffer = new byte[_bufferSize];
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Windows service starting, waiting for client to connect");
_logger.Information("Windows service starting, waiting for client to connect");
// to do: verify whos connecting
_pipeServer.WaitForConnection();
_logger.LogInformation("Client connected to the pipe server");
_logger.Information("Client connected to the pipe server");
while (!stoppingToken.IsCancellationRequested)
{
@ -46,25 +47,35 @@ namespace service
if (numBytesRead > 0)
{
_logger.LogInformation("Message received at pipe server with size: {0}", numBytesRead);
_logger.Information("Message received at pipe server with size: {0}", numBytesRead);
Client message = new Client(ref _buffer, numBytesRead, _logger);
Client message = new Client(ref _buffer, numBytesRead);
message.SendMessageToServer();
byte[] responseMessage = await message.GetResponseFromServer();
_pipeServer.Write(responseMessage, 0, responseMessage.Length);
ThreadPool.QueueUserWorkItem(state => RelayResponseMessage(ref message));
}
}
catch (Exception ex)
{
_logger.LogError("Reading buffer from pipe failed with message: {0}", ex.Message);
_logger.Error("Reading buffer from pipe failed with message: {0}", ex.Message);
}
Array.Clear(_buffer, 0, _bufferSize);
}
}
private void RelayResponseMessage(ref Client message)
{
byte[] responseMessage = message.GetResponseFromServer();
_logger.Information("Sending response message to client with size: {0}", responseMessage.Length);
_pipeServer.Write(responseMessage, 0, responseMessage.Length);
_logger.Information("written to pipe");
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId);
public static uint GetNamedPipeClientProcId(NamedPipeServerStream PipeServer)

View file

@ -12,7 +12,7 @@ global::Pipe::Pipe( LPTSTR PipeName )
0,
NULL,
OPEN_EXISTING,
0,
FILE_FLAG_OVERLAPPED,
NULL
);
@ -49,29 +49,13 @@ void global::Pipe::ReadPipe(PVOID Buffer, SIZE_T Size)
BOOL status = FALSE;
DWORD bytes_read;
do
{
status = ReadFile(
this->pipe_handle,
Buffer,
Size,
&bytes_read,
NULL
);
status = ReadFile(
this->pipe_handle,
Buffer,
Size,
&bytes_read,
NULL
);
LOG_INFO("Bytes read: %d", bytes_read);
if ( bytes_read > Size )
break;
if ( !status && GetLastError() != ERROR_MORE_DATA )
break;
} while ( !status );
if ( !status )
{
LOG_ERROR( "ReadFile failed with status 0x%x", GetLastError() );
return;
}
LOG_INFO( "Bytes read: %d", bytes_read );
}