Skip to content

Commit

Permalink
v2.1.4
Browse files Browse the repository at this point in the history
  • Loading branch information
msasanmh committed Jun 2, 2023
1 parent b52b8b9 commit a1f5615
Show file tree
Hide file tree
Showing 16 changed files with 926 additions and 429 deletions.
9 changes: 9 additions & 0 deletions SecureDNSClient/Audio/Resource1.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions SecureDNSClient/Audio/Resource1.resx
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,7 @@
<data name="Secure_DNS_Online" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>secure-dns-online.wav;System.IO.MemoryStream, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="Warning_Handle_Requests_Exceeded" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>warning-handle-requests-exceeded.wav;System.IO.MemoryStream, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
</root>
Binary file not shown.
946 changes: 604 additions & 342 deletions SecureDNSClient/Forms/FormMain.Designer.cs

Large diffs are not rendered by default.

154 changes: 119 additions & 35 deletions SecureDNSClient/Forms/FormMain.cs

Large diffs are not rendered by default.

3 changes: 0 additions & 3 deletions SecureDNSClient/Forms/FormMain.resx
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,6 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="CustomStatusStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="NotifyIconMain.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>176, 17</value>
</metadata>
Expand Down
17 changes: 14 additions & 3 deletions SecureDNSClient/MsmhTools/HTTPProxyServer/Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ internal static byte[] AppendBytes(byte[] orig, byte[] append)
return ret;
}




/// <summary>
/// Fully read a stream into a byte array.
/// </summary>
Expand Down Expand Up @@ -77,6 +74,20 @@ public static Dictionary<string, string> AddToDict(string key, string? val, Dict
}
}

public static bool IsWin7()
{
bool result = false;
OperatingSystem os = Environment.OSVersion;
Version vs = os.Version;

if (os.Platform == PlatformID.Win32NT)
{
if (vs.Minor == 1 && vs.Major == 6)
result = true;
}

return result;
}

}
}
81 changes: 55 additions & 26 deletions SecureDNSClient/MsmhTools/HTTPProxyServer/HTTPProxyServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@ public void Set(DPIBypass.Mode mode, int firstPartOfDataLength, int fragmentSize
}
}

private static ProxySettings _Settings = new();
internal static ProxySettings _Settings = new();

private static TunnelManager? _TunnelManager;
private static TcpListener? _TcpListener;

private static CancellationTokenSource? _CancelTokenSource;
private static CancellationToken _CancelToken;
private static int _ActiveThreads = 0;
internal static int _ActiveThreads = 0;

public bool IsRunning = false;
private static bool Cancel = false;
Expand All @@ -63,9 +63,14 @@ public void Set(DPIBypass.Mode mode, int firstPartOfDataLength, int fragmentSize
public event EventHandler<EventArgs>? OnChunkDetailsReceived;
private static readonly EventWaitHandle Terminator = new(false, EventResetMode.ManualReset);

private List<string> BlackList = new();

public HTTPProxyServer()
{

// Captive Portal
BlackList.Add("ipv6.msftconnecttest.com:80");
BlackList.Add("detectportal.firefox.com:80");
BlackList.Add("gstatic.com:80");
}

public void Start(IPAddress ipAddress, int port, int maxThreads)
Expand Down Expand Up @@ -108,15 +113,17 @@ public void Stop()
Tunnel.Cancel = true;
_TcpListener.Stop();

//if (_TunnelManager != null)
//{
// var t = _TunnelManager.GetFull().ToList();
// for (int n = 0; n < t.Count; n++)
// {
// var kvp = t[n];
// _TunnelManager.Remove(kvp.Key);
// }
//}
if (_TunnelManager != null)
{
var t = _TunnelManager.GetFull().ToList();
Debug.WriteLine(t.Count);
for (int n = 0; n < t.Count; n++)
{
var kvp = t[n];
if (_TunnelManager.Active(kvp.Key))
_TunnelManager.Remove(kvp.Key);
}
}

IsRunning = _TcpListener.Server.IsBound;
Goodbye();
Expand All @@ -133,13 +140,21 @@ public bool IsDpiActive
get => BypassProgram.DPIBypassMode != DPIBypass.Mode.Disable;
}

public int ActiveRequests
{
get => _ActiveThreads;
}

public int MaxRequests
{
get => _Settings != null ? _Settings.MaxThreads : 0;
}

public Dictionary<int, Tunnel> GetCurrentConnectTunnels()
{
return _TunnelManager != null ? _TunnelManager.GetMetadata() : new Dictionary<int, Tunnel>();
}

#region Setup-Methods

private void Welcome()
{
// Event
Expand All @@ -156,10 +171,6 @@ private void Goodbye()
OnDebugInfoReceived?.Invoke(msgEvent, EventArgs.Empty);
}

#endregion

#region Connection-Handler

private void AcceptConnections()
{
if (Cancel) return;
Expand Down Expand Up @@ -197,13 +208,12 @@ private void AcceptConnections()
}
}
}

private async Task ProcessConnection(TcpClient client)
{
if (Cancel) return;

int connectionId = Environment.CurrentManagedThreadId;
_ActiveThreads++;
Debug.WriteLine($"Active Requests: {_ActiveThreads}");

try
Expand All @@ -212,15 +222,18 @@ private async Task ProcessConnection(TcpClient client)
if (_ActiveThreads >= _Settings.MaxThreads)
{
// Event
string msgEventErr = $"AcceptConnections connection count {_ActiveThreads} exceeds configured max {_Settings.MaxThreads}, waiting";
string msgEventErr = $"AcceptConnections connection count {_ActiveThreads} exceeds configured max {_Settings.MaxThreads}.";
OnErrorOccurred?.Invoke(msgEventErr, EventArgs.Empty);

while (_ActiveThreads >= _Settings.MaxThreads)
{
Task.Delay(100).Wait();
}
// Kill em
client.Dispose();
Debug.WriteLine($"Active Requests2: {_ActiveThreads}");
Task.Delay(100).Wait();
return;
}

_ActiveThreads++;

IPEndPoint? clientIpEndpoint = client.Client.RemoteEndPoint as IPEndPoint;
IPEndPoint? serverIpEndpoint = client.Client.LocalEndPoint as IPEndPoint;

Expand Down Expand Up @@ -248,6 +261,23 @@ private async Task ProcessConnection(TcpClient client)
req.DestIp = serverIp;
req.DestPort = serverPort;

// Block Black List
for (int n = 0; n < BlackList.Count; n++)
{
string website = BlackList[n];
string destWebsite = $"{req.DestHostname}:{req.DestHostPort}";
if (destWebsite == website)
{
// Event
string msgEvent = $"Black list: {req.FullUrl}, request denied.";
OnDebugInfoReceived?.Invoke(msgEvent, EventArgs.Empty);

client.Close();
_ActiveThreads--;
return;
}
}

// Event
OnRequestReceived?.Invoke($"{req.DestHostname}:{req.DestHostPort}", EventArgs.Empty);

Expand Down Expand Up @@ -552,6 +582,5 @@ async Task sendRestResponse(RestResponse resp, NetworkStream ns)
}
}

#endregion
}
}
26 changes: 25 additions & 1 deletion SecureDNSClient/MsmhTools/HTTPProxyServer/HttpMethod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,30 @@ public enum HttpMethod
[EnumMember(Value = "OPTIONS")]
OPTIONS,
[EnumMember(Value = "TRACE")]
TRACE
TRACE,
[EnumMember(Value = "UNKNOWN")]
UNKNOWN
}

public static class GetHttpMethod
{
public static HttpMethod Parse(string method)
{
method = method.Trim().ToLower();
var httpMethod = method switch
{
"get" => HttpMethod.GET,
"head" => HttpMethod.HEAD,
"put" => HttpMethod.PUT,
"post" => HttpMethod.POST,
"delete" => HttpMethod.DELETE,
"patch" => HttpMethod.PATCH,
"connect" => HttpMethod.CONNECT,
"options" => HttpMethod.OPTIONS,
"trace" => HttpMethod.TRACE,
_ => HttpMethod.UNKNOWN,
};
return httpMethod;
}
}
}
29 changes: 15 additions & 14 deletions SecureDNSClient/MsmhTools/HTTPProxyServer/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ public Request(HttpListenerContext ctx, bool readStreamFully)
{
tempKey = WebUtility.UrlDecode(tempKey);
QuerystringEntries = Common.AddToDict(tempKey, null, QuerystringEntries);
}
}
}

if (inVal == 1)
Expand Down Expand Up @@ -383,9 +383,9 @@ public Request(HttpListenerContext ctx, bool readStreamFully)
gzip = xferEncodingHeader.ToLower().Contains("gzip");
deflate = xferEncodingHeader.ToLower().Contains("deflate");
}
if (chunkedXfer
&& Method != HttpMethod.GET

if (chunkedXfer
&& Method != HttpMethod.GET
&& Method != HttpMethod.HEAD)
{
Stream bodyStream = ctx.Request.InputStream;
Expand Down Expand Up @@ -417,7 +417,7 @@ public Request(HttpListenerContext ctx, bool readStreamFully)
Data = new byte[ContentLength];
Buffer.BlockCopy(decodedData, 0, Data, 0, decodedData.Length);
}
}
}
}
else if (ContentLength > 0)
{
Expand All @@ -426,7 +426,7 @@ public Request(HttpListenerContext ctx, bool readStreamFully)
if (Method != HttpMethod.GET && Method != HttpMethod.HEAD)
{
try
{
{
Data = new byte[ContentLength];
Stream bodyStream = ctx.Request.InputStream;
Data = Common.StreamToBytes(bodyStream);
Expand All @@ -440,7 +440,7 @@ public Request(HttpListenerContext ctx, bool readStreamFully)
else
{
Data = null;
DataStream = ctx.Request.InputStream;
DataStream = ctx.Request.InputStream;
}
}
}
Expand Down Expand Up @@ -623,7 +623,7 @@ public static Request FromBytes(byte[] bytes)
if (bytes.Length < 4) throw new ArgumentException("Too few bytes supplied to form a valid HTTP request.");

bool endOfHeader = false;
byte[] headerBytes = new byte[1];
byte[] headerBytes = new byte[1];

Request ret = new();

Expand Down Expand Up @@ -1094,8 +1094,9 @@ private static Request BuildHeaders(byte[] bytes)
// First-Line
string[] requestLine = headers[i].Trim().Trim('\0').Split(' ');
if (requestLine.Length < 3) throw new ArgumentException("Request line does not contain at least three parts (method, raw URL, protocol/version).");

ret.Method = (HttpMethod)Enum.Parse(typeof(HttpMethod), requestLine[0], true);

// (HttpMethod)Enum.Parse(typeof(HttpMethod), requestLine[0], true);
ret.Method = GetHttpMethod.Parse(requestLine[0]);
ret.FullUrl = requestLine[1];
ret.ProtocolVersion = requestLine[2];
ret.RawUrlWithQuery = ret.FullUrl;
Expand Down Expand Up @@ -1127,7 +1128,7 @@ private static Request BuildHeaders(byte[] bytes)
throw new Exception("Unable to parse destination hostname and port.");
}
}
}
}
}
}
else
Expand Down Expand Up @@ -1176,7 +1177,7 @@ private static Request BuildHeaders(byte[] bytes)
List<string> ret = new();

foreach (char c in rawUrlWithoutQuery)
{
{
if ((position == 0) &&
(string.Compare(tempString, "") == 0) &&
(c == '/'))
Expand Down Expand Up @@ -1227,7 +1228,7 @@ private static Request BuildHeaders(byte[] bytes)
if (string.IsNullOrEmpty(query)) return null;

Dictionary<string, string> ret = new();

int inKey = 1;
int inVal = 0;
int position = 0;
Expand Down Expand Up @@ -1271,7 +1272,7 @@ private static Request BuildHeaders(byte[] bytes)
continue;
}
}

if (inVal == 1)
{
if (!string.IsNullOrEmpty(tempVal)) tempVal = WebUtility.UrlEncode(tempVal);
Expand Down
Loading

0 comments on commit a1f5615

Please sign in to comment.