Skip to content

Commit

Permalink
Merge pull request #3 from XKaguya/dev
Browse files Browse the repository at this point in the history
Version 1.0.3
  • Loading branch information
XKaguya authored Feb 27, 2024
2 parents ee7f27b + 40c5711 commit 47f2def
Show file tree
Hide file tree
Showing 15 changed files with 625 additions and 188 deletions.
31 changes: 14 additions & 17 deletions RDPInterceptor/API/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class Logger
static Logger()
{
logRichTextBox = new RichTextBox();

File.WriteAllText(logFilePath, string.Empty);
}

Expand All @@ -36,12 +36,12 @@ public static void SetLogLevel(string level)
LogLevel = level;
}
}

public static void SetLogTarget(RichTextBox richTextBox)
{
logRichTextBox = richTextBox;
}

public static void SetLogBackgroundColor(SolidColorBrush color)
{
logRichTextBox.Background = color;
Expand All @@ -53,9 +53,9 @@ public static void Log(string message)
{
string logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [INFO]: {message}";
LogAddLine(logMessage, Brushes.CornflowerBlue);

WriteLogToFile(logMessage);

if (++logCount > maxLogCount)
{
ClearLogs();
Expand All @@ -69,16 +69,16 @@ public static void Error(string message)
{
string logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [ERROR]: {message}";
LogAddLine(logMessage, Brushes.Red);

WriteLogToFile(logMessage);

if (++logCount > maxLogCount)
{
ClearLogs();
}
}
}

public static void Debug(string message)
{
if (logRichTextBox != null)
Expand All @@ -87,9 +87,9 @@ public static void Debug(string message)
{
string logMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [DEBUG]: {message}";
LogAddLine(logMessage, Brushes.Chocolate);

WriteLogToFile(logMessage);

if (++logCount > maxLogCount)
{
ClearLogs();
Expand All @@ -105,7 +105,7 @@ private static void LogAddLine(string message, SolidColorBrush color)
Paragraph paragraph = new Paragraph(new Run(message));
paragraph.Foreground = color;
logRichTextBox.Document.Blocks.Add(paragraph);

logRichTextBox.ScrollToEnd();
});
}
Expand All @@ -123,10 +123,7 @@ private static void WriteLogToFile(string message)

private static void ClearLogs()
{
logRichTextBox.Dispatcher.Invoke(() =>
{
logRichTextBox.Document.Blocks.Clear();
});
logRichTextBox.Dispatcher.Invoke(() => { logRichTextBox.Document.Blocks.Clear(); });
logCount = 0;
}

Expand All @@ -150,7 +147,7 @@ public static string GetLogs()
}
}
}

return text.ToString();
});

Expand All @@ -160,4 +157,4 @@ public static string GetLogs()
return null;
}
}
}
}
147 changes: 120 additions & 27 deletions RDPInterceptor/API/NetworkInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using WindivertDotnet;

namespace RDPInterceptor.API
{
public class NetworkInterceptor
{
public static CancellationTokenSource CaptureCancellationTokenSource = new();
public static CancellationTokenSource? CaptureCancellationTokenSource = new();

public static bool IpWhitelistMode { get; set; } = true;

Expand All @@ -25,6 +26,8 @@ public class NetworkInterceptor
public static ushort Port { get; set; } = 3389;

private static WinDivert? Divert { get; set; }

private static readonly SemaphoreSlim semaphore = new(1);

private static WinDivertPacket? Packet { get; set; }

Expand All @@ -41,8 +44,16 @@ public static async Task<bool> AddIpIntoList(string Ip)

if (IPAddress.TryParse(Ip, out IpAddr))
{
IpAddrList.Add(IpAddr);
await AddIpIntoWhitelistFile(IpAddr);
if (!IpAddrList.Contains(IpAddr))
{
IpAddrList.Add(IpAddr);
await AddIpIntoWhitelistFile(IpAddr);
}
else
{
Logger.Error($"There's already a {IpAddr}");
return false;
}
}
else
{
Expand All @@ -57,17 +68,36 @@ public static async Task StartCapture(CancellationToken cancellationToken)
{
Logger.Log("Start Interceptor.");

if (cancellationToken.IsCancellationRequested)
{
CaptureCancellationTokenSource = new CancellationTokenSource();
}

try
{
await RunCapture(CaptureCancellationTokenSource.Token);
}
catch (OperationCanceledException e)
{
Logger.Error(e.Message + e.StackTrace);
}
}

private static async Task RunCapture(CancellationToken cancellationToken)
{
var filter = Filter.True.And(f => f.Tcp.DstPort == Port);

Divert = new WinDivert(filter, WinDivertLayer.Network);
Addr = new();
Packet = new();

while (!cancellationToken.IsCancellationRequested)
try
{
if (Divert != null)
while (!cancellationToken.IsCancellationRequested)
{
try
cancellationToken.ThrowIfCancellationRequested();

if (Divert != null)
{
await Divert.RecvAsync(Packet, Addr, cancellationToken);

Expand All @@ -76,21 +106,35 @@ public static async Task StartCapture(CancellationToken cancellationToken)
await Divert.SendAsync(Packet, Addr, cancellationToken);
}
}
catch (OperationCanceledException ex)
{
Logger.Log($"Stop Interceptor.");
}
}
}
catch (OperationCanceledException ex)
{
Logger.Log($"Stop Interceptor.");
}
finally
{
Divert?.Dispose();
Addr?.Dispose();
Packet?.Dispose();
}
}

public static async Task StopCapture()
{
CaptureCancellationTokenSource?.Cancel();

Logger.Log("Capture has now stopped.");
if (CaptureCancellationTokenSource != null)
{
CaptureCancellationTokenSource.Cancel();
await Task.Delay(100);
Logger.Log("Capture has now stopped.");
}
else
{
Logger.Log("Capture is not running.");
}
}


private static unsafe void GetIpAddresses(IPV4Header* header, out IPAddress srcIpAddr, out IPAddress dstIpAddr)
{
IPAddress srcIp = header->SrcAddr;
Expand Down Expand Up @@ -118,13 +162,13 @@ public static async Task<bool> ProcessPacketAsync(WinDivertPacket Packet, WinDiv

if (IpAddrList.Contains(SrcIpAddr))
{
LogConnections(IsLogConnection,$"Incoming RDP Connection from {SrcIpAddr} has been accepted.");
LogConnections(IsLogConnection, $"Incoming RDP Connection from {SrcIpAddr} has been accepted.");
Packet.CalcChecksums(Address);
return true;
}
else if (IpAddrList.Contains(DstIpAddr))
{
LogConnections(IsLogConnection,$"Outgoing RDP Connection to {DstIpAddr} has been accepted.");
LogConnections(IsLogConnection, $"Outgoing RDP Connection to {DstIpAddr} has been accepted.");
Packet.CalcChecksums(Address);
return true;
}
Expand Down Expand Up @@ -152,7 +196,7 @@ private static void LogConnections(bool isLogConnection, string content)
private static async Task LogConnectionAsync(IPAddress srcIpAddr)
{
string logFilePath = "Connectionlist.log";

if (File.Exists(logFilePath))
{
string[] lines = await File.ReadAllLinesAsync(logFilePath);
Expand All @@ -166,33 +210,31 @@ private static async Task LogConnectionAsync(IPAddress srcIpAddr)
FileStream fs = File.Create(logFilePath);
fs.Close();
}

using (StreamWriter writer = File.AppendText(logFilePath))
{
await writer.WriteLineAsync(srcIpAddr.ToString());
}
}

private static readonly SemaphoreSlim semaphore = new(1);

public static async void ReadLinesFromFileAsync()
{
await semaphore.WaitAsync();

string WhitelistFilePath = "Whitelist.txt";

try
{
if (File.Exists(WhitelistFilePath))
{
IPAddress IpAddr;

foreach (string ip in await File.ReadAllLinesAsync(WhitelistFilePath))
{
if (IPAddress.TryParse(ip, out IpAddr))
{
IpAddrList.Add(IpAddr);

Logger.Log($"IP {ip} has been read into whitelist.");
}
else
Expand All @@ -212,7 +254,7 @@ public static async void ReadLinesFromFileAsync()
semaphore.Release();
}
}

public static async Task AddIpIntoWhitelistFile(IPAddress ipAddress)
{
Logger.Debug($"Method AddIpIntoWhitelistFile called.");
Expand All @@ -231,7 +273,6 @@ public static async Task AddIpIntoWhitelistFile(IPAddress ipAddress)
if (Array.Exists(lines, line => line.Equals(ipAddress.ToString())))
{
Logger.Debug($"IP {ipAddress} already in {WhitelistFilePath}");
return;
}
else
{
Expand Down Expand Up @@ -263,7 +304,59 @@ public static async Task AddIpIntoWhitelistFile(IPAddress ipAddress)
semaphore.Release();
}
}
}
}

public static async Task RemoveIpFromList(IPAddress ipAddress)
{
Logger.Debug($"Method RemoveIpFromWhitelist called.");

try
{
if (IpAddrList.Contains(ipAddress))
{
IpAddrList.Remove(ipAddress);
}

string WhitelistFilePath = "Whitelist.txt";

if (File.Exists(WhitelistFilePath))
{
Logger.Debug($"File {WhitelistFilePath} exists. Proceeding...");

await semaphore.WaitAsync();

string[] lines = await File.ReadAllLinesAsync(WhitelistFilePath);

if (lines.Contains(ipAddress.ToString()))
{
List<string> linesList = lines.ToList();
linesList.Remove(ipAddress.ToString());

using (StreamWriter writer = new StreamWriter(WhitelistFilePath, false))
{
foreach (string ip in linesList)
{
await writer.WriteLineAsync(ip);
}
}
}
}
else
{
FileStream fs = File.Create(WhitelistFilePath);
fs.Close();

Logger.Error($"File {WhitelistFilePath} doesn't exist. Now create file {WhitelistFilePath}.");
}
}
catch (Exception e)
{
Logger.Error(e.Message + e.Message);
throw;
}
finally
{
semaphore.Release();
}
}
}
}
Loading

0 comments on commit 47f2def

Please sign in to comment.