Commit 990b7412 authored by justcoding121's avatar justcoding121 Committed by justcoding121

cleanup

parent 6b42b1b4
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
......
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
</configuration>
</configuration>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy.Test
{
public class Program
{
static ProxyTestController controller = new ProxyTestController();
private static readonly ProxyTestController Controller = new ProxyTestController();
public static void Main(string[] args)
{
//On Console exit make sure we also exit the proxy
NativeMethods.handler = new NativeMethods.ConsoleEventDelegate(ConsoleEventCallback);
NativeMethods.SetConsoleCtrlHandler(NativeMethods.handler, true);
NativeMethods.Handler = ConsoleEventCallback;
NativeMethods.SetConsoleCtrlHandler(NativeMethods.Handler, true);
Console.Write("Do you want to monitor HTTPS? (Y/N):");
if (Console.ReadLine().Trim().ToLower() == "y")
var readLine = Console.ReadLine();
if (readLine != null && readLine.Trim().ToLower() == "y")
{
controller.EnableSSL = true;
Controller.EnableSsl = true;
}
Console.Write("Do you want to set this as a System Proxy? (Y/N):");
if (Console.ReadLine().Trim().ToLower() == "y")
var line = Console.ReadLine();
if (line != null && line.Trim().ToLower() == "y")
{
controller.SetAsSystemProxy = true;
Controller.SetAsSystemProxy = true;
}
//Start proxy controller
controller.StartProxy();
Controller.StartProxy();
Console.WriteLine("Hit any key to exit..");
Console.WriteLine();
Console.Read();
controller.Stop();
Controller.Stop();
}
static bool ConsoleEventCallback(int eventType)
private static bool ConsoleEventCallback(int eventType)
{
if (eventType == 2)
{
try
{
controller.Stop();
Controller.Stop();
}
catch
{
// ignored
}
catch { }
}
return false;
}
}
internal static class NativeMethods
{
// Keeps it from getting garbage collected
internal static ConsoleEventDelegate Handler;
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
// Pinvoke
internal delegate bool ConsoleEventDelegate(int eventType);
// Keeps it from getting garbage collected
internal static ConsoleEventDelegate handler;
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -17,9 +17,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("33a2109d-0312-4c94-aa51-fbb2a83e63ab")]
// Version information for an assembly consists of the following four values:
......@@ -32,5 +34,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy.Test
{
public partial class ProxyTestController
public class ProxyTestController
{
public int ListeningPort { get; set; }
public bool EnableSSL { get; set; }
public bool EnableSsl { get; set; }
public bool SetAsSystemProxy { get; set; }
public void StartProxy()
{
ProxyServer.BeforeRequest += OnRequest;
ProxyServer.BeforeResponse += OnResponse;
ProxyServer.EnableSSL = EnableSSL;
ProxyServer.EnableSsl = EnableSsl;
ProxyServer.SetAsSystemProxy = SetAsSystemProxy;
......@@ -40,9 +27,9 @@ namespace Titanium.Web.Proxy.Test
ProxyServer.ListeningPort = ProxyServer.ListeningPort;
Console.WriteLine(String.Format("Proxy listening on local machine port: {0} ", ProxyServer.ListeningPort));
Console.WriteLine("Proxy listening on local machine port: {0} ", ProxyServer.ListeningPort);
}
public void Stop()
{
ProxyServer.BeforeRequest -= OnRequest;
......@@ -52,13 +39,11 @@ namespace Titanium.Web.Proxy.Test
}
//Test On Request, intecept requests
//Read browser URL send back to proxy by the injection script in OnResponse event
public void OnRequest(object sender, SessionEventArgs e)
{
Console.WriteLine(e.RequestURL);
Console.WriteLine(e.RequestUrl);
////read request headers
//var requestHeaders = e.RequestHeaders;
......@@ -82,7 +67,6 @@ namespace Titanium.Web.Proxy.Test
//{
// e.Ok("<!DOCTYPE html><html><body><h1>Website Blocked</h1><p>Blocked by titanium web proxy.</p></body></html>");
//}
}
//Test script injection
......@@ -112,9 +96,6 @@ namespace Titanium.Web.Proxy.Test
// e.SetResponseBodyString(modified);
// }
//}
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Titanium.Web.Proxy.Exceptions
{
public class BodyNotFoundException : Exception
{
public BodyNotFoundException(string message)
:base(message)
: base(message)
{
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net;
using System.Text;
namespace Titanium.Web.Proxy.Extensions
......@@ -24,9 +21,12 @@ namespace Titanium.Web.Proxy.Extensions
}
}
}
catch { }
catch
{
// ignored
}
return Encoding.GetEncoding("ISO-8859-1");
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net;
using System.Text;
namespace Titanium.Web.Proxy.Extensions
......@@ -11,8 +8,7 @@ namespace Titanium.Web.Proxy.Extensions
public static Encoding GetEncoding(this HttpWebResponse response)
{
if (string.IsNullOrEmpty(response.CharacterSet)) return Encoding.GetEncoding("ISO-8859-1");
else
return Encoding.GetEncoding(response.CharacterSet);
return Encoding.GetEncoding(response.CharacterSet);
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text;
namespace Titanium.Web.Proxy.Extensions
{
public static class StreamHelper
{
private const int DEFAULT_BUFFER_SIZE = 8192; // +32767
public static void CopyToAsync(this Stream input, string initialData, Stream output, int bufferSize)
{
var bytes = Encoding.ASCII.GetBytes(initialData);
output.Write(bytes,0, bytes.Length);
CopyToAsync(input, output, bufferSize);
output.Write(bytes, 0, bytes.Length);
CopyToAsync(input, output, bufferSize);
}
//http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-write
......@@ -25,15 +21,14 @@ namespace Titanium.Web.Proxy.Extensions
if (!input.CanRead) throw new InvalidOperationException("input must be open for reading");
if (!output.CanWrite) throw new InvalidOperationException("output must be open for writing");
byte[][] buf = { new byte[bufferSize], new byte[bufferSize] };
int[] bufl = { 0, 0 };
int bufno = 0;
IAsyncResult read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
byte[][] buf = {new byte[bufferSize], new byte[bufferSize]};
int[] bufl = {0, 0};
var bufno = 0;
var read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
IAsyncResult write = null;
while (true)
{
// wait for the read operation to complete
read.AsyncWaitHandle.WaitOne();
bufl[bufno] = input.EndRead(read);
......@@ -62,7 +57,6 @@ namespace Titanium.Web.Proxy.Extensions
// A little speedier than using a ternary expression.
bufno ^= 1; // bufno = ( bufno == 0 ? 1 : 0 ) ;
read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
}
// wait for the final in-flight write operation, if one exists, to complete
......@@ -75,9 +69,11 @@ namespace Titanium.Web.Proxy.Extensions
output.Flush();
}
catch { }
catch
{
// ignored
}
// return to the caller ;
return;
}
}
}
}
\ No newline at end of file
......@@ -8,10 +8,10 @@ namespace Titanium.Web.Proxy.Helpers
{
public class CertificateManager : IDisposable
{
private const string CERT_CREATE_FORMAT =
private const string CertCreateFormat =
"-ss {0} -n \"CN={1}, O={2}\" -sky {3} -cy {4} -m 120 -a sha256 -eku 1.3.6.1.5.5.7.3.1 -b {5:MM/dd/yyyy} {6}";
private readonly IDictionary<string, X509Certificate2> certificateCache;
private readonly IDictionary<string, X509Certificate2> _certificateCache;
public string Issuer { get; private set; }
public string RootCertificateName { get; private set; }
......@@ -27,7 +27,7 @@ namespace Titanium.Web.Proxy.Helpers
MyStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
RootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
certificateCache = new Dictionary<string, X509Certificate2>();
_certificateCache = new Dictionary<string, X509Certificate2>();
}
/// <summary>
......@@ -69,8 +69,9 @@ namespace Titanium.Web.Proxy.Helpers
}
protected virtual X509Certificate2 CreateCertificate(X509Store store, string certificateName)
{
if (certificateCache.ContainsKey(certificateName))
return certificateCache[certificateName];
if (_certificateCache.ContainsKey(certificateName))
return _certificateCache[certificateName];
lock (store)
{
......@@ -80,7 +81,7 @@ namespace Titanium.Web.Proxy.Helpers
store.Open(OpenFlags.ReadWrite);
string certificateSubject = string.Format("CN={0}, O={1}", certificateName, Issuer);
X509Certificate2Collection certificates =
var certificates =
FindCertificates(store, certificateSubject);
if (certificates != null)
......@@ -102,8 +103,8 @@ namespace Titanium.Web.Proxy.Helpers
finally
{
store.Close();
if (certificate != null && !certificateCache.ContainsKey(certificateName))
certificateCache.Add(certificateName, certificate);
if (certificate != null && !_certificateCache.ContainsKey(certificateName))
_certificateCache.Add(certificateName, certificate);
}
}
}
......@@ -151,9 +152,9 @@ namespace Titanium.Web.Proxy.Helpers
{
store.Close();
if (certificates == null &&
certificateCache.ContainsKey(certificateName))
_certificateCache.ContainsKey(certificateName))
{
certificateCache.Remove(certificateName);
_certificateCache.Remove(certificateName);
}
}
}
......@@ -164,7 +165,7 @@ namespace Titanium.Web.Proxy.Helpers
bool isRootCertificate =
(certificateName == RootCertificateName);
string certCreatArgs = string.Format(CERT_CREATE_FORMAT,
string certCreatArgs = string.Format(CertCreateFormat,
store.Name, certificateName, Issuer,
isRootCertificate ? "signature" : "exchange",
isRootCertificate ? "authority" : "end", DateTime.Now,
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Diagnostics.CodeAnalysis;
using Ionic.Zlib;
namespace Titanium.Web.Proxy.Helpers
{
public class CompressionHelper
{
private static readonly int BUFFER_SIZE = 8192;
private const int BufferSize = 8192;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressZlib(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream())
using (var ms = new MemoryStream())
{
using (Ionic.Zlib.ZlibStream zip = new Ionic.Zlib.ZlibStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
using (var zip = new ZlibStream(ms, CompressionMode.Compress, true))
{
zip.Write(bytes, 0, bytes.Length);
}
......@@ -26,13 +22,12 @@ namespace Titanium.Web.Proxy.Helpers
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressDeflate(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream())
using (var ms = new MemoryStream())
{
using (Ionic.Zlib.DeflateStream zip = new Ionic.Zlib.DeflateStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
using (var zip = new DeflateStream(ms, CompressionMode.Compress, true))
{
zip.Write(bytes, 0, bytes.Length);
}
......@@ -41,32 +36,31 @@ namespace Titanium.Web.Proxy.Helpers
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] CompressGzip(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream())
using (var ms = new MemoryStream())
{
using (Ionic.Zlib.GZipStream zip = new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(bytes, 0, bytes.Length);
}
return ms.ToArray();
}
}
public static byte[] DecompressGzip(Stream input)
{
using (var decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
using (
var decompressor = new System.IO.Compression.GZipStream(input,
System.IO.Compression.CompressionMode.Decompress))
{
var buffer = new byte[BufferSize];
int read = 0;
var buffer = new byte[BUFFER_SIZE];
using (MemoryStream output = new MemoryStream())
using (var output = new MemoryStream())
{
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
......@@ -78,13 +72,13 @@ namespace Titanium.Web.Proxy.Helpers
public static byte[] DecompressDeflate(Stream input)
{
using (Ionic.Zlib.DeflateStream decompressor = new Ionic.Zlib.DeflateStream(input, Ionic.Zlib.CompressionMode.Decompress))
using (var decompressor = new DeflateStream(input, CompressionMode.Decompress))
{
int read = 0;
var buffer = new byte[BUFFER_SIZE];
var buffer = new byte[BufferSize];
using (MemoryStream output = new MemoryStream())
using (var output = new MemoryStream())
{
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
......@@ -93,15 +87,16 @@ namespace Titanium.Web.Proxy.Helpers
}
}
}
public static byte[] DecompressZlib(Stream input)
{
using (Ionic.Zlib.ZlibStream decompressor = new Ionic.Zlib.ZlibStream(input, Ionic.Zlib.CompressionMode.Decompress))
using (var decompressor = new ZlibStream(input, CompressionMode.Decompress))
{
int read = 0;
var buffer = new byte[BUFFER_SIZE];
var buffer = new byte[BufferSize];
using (MemoryStream output = new MemoryStream())
using (var output = new MemoryStream())
{
int read;
while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
......@@ -111,4 +106,4 @@ namespace Titanium.Web.Proxy.Helpers
}
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Text;
namespace Titanium.Web.Proxy.Helpers
{
internal class CustomBinaryReader : BinaryReader
{
internal CustomBinaryReader(Stream stream, Encoding encoding)
: base(stream, encoding)
{
}
internal string ReadLine()
{
char[] buf = new char[1];
StringBuilder readBuffer = new StringBuilder();
var buf = new char[1];
var readBuffer = new StringBuilder();
try
{
var charsRead = 0;
char lastChar = new char();
var lastChar = new char();
while ((charsRead = base.Read(buf, 0, 1)) > 0)
while ((Read(buf, 0, 1)) > 0)
{
if (lastChar == '\r' && buf[0] == '\n')
{
return readBuffer.Remove(readBuffer.Length - 1, 1).ToString();
}
else
if (buf[0] == '\0')
{
return readBuffer.ToString();
}
else
readBuffer.Append(buf[0]);
if (buf[0] == '\0')
{
return readBuffer.ToString();
}
readBuffer.Append(buf[0]);
lastChar = buf[0];
}
return readBuffer.ToString();
}
catch (IOException)
{
{
return readBuffer.ToString();
}
catch (Exception)
{
throw;
}
}
internal List<string> ReadAllLines()
{
string tmpLine = null;
List<string> requestLines = new List<string>();
while (!String.IsNullOrEmpty(tmpLine = ReadLine()))
string tmpLine;
var requestLines = new List<string>();
while (!string.IsNullOrEmpty(tmpLine = ReadLine()))
{
requestLines.Add(tmpLine);
}
return requestLines;
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Titanium.Web.Proxy.Helpers
......@@ -12,21 +9,23 @@ namespace Titanium.Web.Proxy.Helpers
{
try
{
DirectoryInfo[] myProfileDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
string myFFPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFFPrefFile))
var myProfileDirectory =
new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
"\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
var myFfPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFfPrefFile))
{
// We have a pref file so let''s make sure it has the proxy setting
StreamReader myReader = new StreamReader(myFFPrefFile);
string myPrefContents = myReader.ReadToEnd();
var myReader = new StreamReader(myFfPrefFile);
var myPrefContents = myReader.ReadToEnd();
myReader.Close();
if (myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);"))
{
// Add the proxy enable line and write it back to the file
myPrefContents = myPrefContents.Replace("user_pref(\"network.proxy.type\", 0);", "");
File.Delete(myFFPrefFile);
File.WriteAllText(myFFPrefFile, myPrefContents);
File.Delete(myFfPrefFile);
File.WriteAllText(myFfPrefFile, myPrefContents);
}
}
}
......@@ -35,25 +34,28 @@ namespace Titanium.Web.Proxy.Helpers
// Only exception should be a read/write error because the user opened up FireFox so they can be ignored.
}
}
public static void RemoveFirefox()
{
try
{
DirectoryInfo[] myProfileDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
string myFFPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFFPrefFile))
var myProfileDirectory =
new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
"\\Mozilla\\Firefox\\Profiles\\").GetDirectories("*.default");
var myFfPrefFile = myProfileDirectory[0].FullName + "\\prefs.js";
if (File.Exists(myFfPrefFile))
{
// We have a pref file so let''s make sure it has the proxy setting
StreamReader myReader = new StreamReader(myFFPrefFile);
string myPrefContents = myReader.ReadToEnd();
var myReader = new StreamReader(myFfPrefFile);
var myPrefContents = myReader.ReadToEnd();
myReader.Close();
if (!myPrefContents.Contains("user_pref(\"network.proxy.type\", 0);"))
{
// Add the proxy enable line and write it back to the file
myPrefContents = myPrefContents + "\n\r" + "user_pref(\"network.proxy.type\", 0);";
File.Delete(myFFPrefFile);
File.WriteAllText(myFFPrefFile, myPrefContents);
File.Delete(myFfPrefFile);
File.WriteAllText(myFfPrefFile, myPrefContents);
}
}
}
......@@ -63,4 +65,4 @@ namespace Titanium.Web.Proxy.Helpers
}
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Configuration;
using System.Reflection;
using System.Text;
namespace Titanium.Web.Proxy.Helpers
{
......@@ -11,25 +8,24 @@ namespace Titanium.Web.Proxy.Helpers
{
//Fix bug in .Net 4.0 HttpWebRequest (don't use this for 4.5 and above)
//http://stackoverflow.com/questions/856885/httpwebrequest-to-url-with-dot-at-the-end
public static void URLPeriodFix()
public static void UrlPeriodFix()
{
MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
var getSyntax = typeof (UriParser).GetMethod("GetSyntax", BindingFlags.Static | BindingFlags.NonPublic);
var flagsField = typeof (UriParser).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
if (getSyntax != null && flagsField != null)
{
foreach (string scheme in new[] { "http", "https" })
foreach (var scheme in new[] {"http", "https"})
{
UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { scheme });
var parser = (UriParser) getSyntax.Invoke(null, new object[] {scheme});
if (parser != null)
{
int flagsValue = (int)flagsField.GetValue(parser);
var flagsValue = (int) flagsField.GetValue(parser);
if ((flagsValue & 0x1000000) != 0)
flagsField.SetValue(parser, flagsValue & ~0x1000000);
}
}
}
}
// Enable/disable useUnsafeHeaderParsing.
......@@ -37,31 +33,32 @@ namespace Titanium.Web.Proxy.Helpers
public static bool ToggleAllowUnsafeHeaderParsing(bool enable)
{
//Get the assembly that contains the internal class
Assembly assembly = Assembly.GetAssembly(typeof(SettingsSection));
var assembly = Assembly.GetAssembly(typeof (SettingsSection));
if (assembly != null)
{
//Use the assembly in order to get the internal type for the internal class
Type settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
var settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
if (settingsSectionType != null)
{
//Use the internal static property to get an instance of the internal settings class.
//If the static instance isn't created already invoking the property will create it for us.
object anInstance = settingsSectionType.InvokeMember("Section",
BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
var anInstance = settingsSectionType.InvokeMember("Section",
BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null,
new object[] {});
if (anInstance != null)
{
//Locate the private bool field that tells the framework if unsafe header parsing is allowed
FieldInfo aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
var aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing",
BindingFlags.NonPublic | BindingFlags.Instance);
if (aUseUnsafeHeaderParsing != null)
{
aUseUnsafeHeaderParsing.SetValue(anInstance, enable);
return true;
}
}
}
}
return false;
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Titanium.Web.Proxy.Helpers
{
internal static class NativeMethods
{
[DllImport("wininet.dll")]
internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer,
int dwBufferLength);
}
public static class SystemProxyHelper
{
public const int InternetOptionSettingsChanged = 39;
public const int InternetOptionRefresh = 37;
private static object _prevProxyServer;
private static object _prevProxyEnable;
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
static object prevProxyServer;
static object prevProxyEnable;
public static void EnableProxyHTTP(string hostname, int port)
public static void EnableProxyHttp(string hostname, int port)
{
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
prevProxyEnable = reg.GetValue("ProxyEnable");
prevProxyServer = reg.GetValue("ProxyServer");
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";");
refresh();
var reg = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (reg != null)
{
_prevProxyEnable = reg.GetValue("ProxyEnable");
_prevProxyServer = reg.GetValue("ProxyServer");
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";");
}
Refresh();
}
public static void EnableProxyHTTPS(string hostname, int port)
public static void EnableProxyHttps(string hostname, int port)
{
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";https=" + hostname + ":" + port);
refresh();
var reg = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (reg != null)
{
reg.SetValue("ProxyEnable", 1);
reg.SetValue("ProxyServer", "http=" + hostname + ":" + port + ";https=" + hostname + ":" + port);
}
Refresh();
}
public static void DisableAllProxy()
{
RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
reg.SetValue("ProxyEnable", prevProxyEnable);
if (prevProxyServer != null)
reg.SetValue("ProxyServer", prevProxyServer);
refresh();
var reg = Registry.CurrentUser.OpenSubKey(
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (reg != null)
{
reg.SetValue("ProxyEnable", _prevProxyEnable);
if (_prevProxyServer != null)
reg.SetValue("ProxyServer", _prevProxyServer);
}
Refresh();
}
private static void refresh()
private static void Refresh()
{
settingsReturn = NativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = NativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionSettingsChanged, IntPtr.Zero,0);
NativeMethods.InternetSetOption(IntPtr.Zero, InternetOptionRefresh, IntPtr.Zero, 0);
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net.Security;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Titanium.Web.Proxy.Extensions;
using Titanium.Web.Proxy.Models;
......@@ -15,9 +14,9 @@ namespace Titanium.Web.Proxy.Helpers
public class TcpHelper
{
private static readonly int BUFFER_SIZE = 8192;
private static readonly String[] colonSpaceSplit = new string[] { ": " };
public static void SendRaw(Stream clientStream, string httpCmd, List<HttpHeader> requestHeaders, string hostName, int tunnelPort, bool isHttps)
public static void SendRaw(Stream clientStream, string httpCmd, List<HttpHeader> requestHeaders, string hostName,
int tunnelPort, bool isHttps)
{
StringBuilder sb = null;
if (httpCmd != null || requestHeaders != null)
......@@ -29,23 +28,22 @@ namespace Titanium.Web.Proxy.Helpers
sb.Append(Environment.NewLine);
}
if (requestHeaders != null)
for (int i = 0; i < requestHeaders.Count; i++)
{
var header = requestHeaders[i].ToString();
sb.Append(header);
sb.Append(Environment.NewLine);
}
foreach (var header in requestHeaders.Select(t => t.ToString()))
{
sb.Append(header);
sb.Append(Environment.NewLine);
}
sb.Append(Environment.NewLine);
}
System.Net.Sockets.TcpClient tunnelClient = null;
TcpClient tunnelClient = null;
Stream tunnelStream = null;
try
{
tunnelClient = new System.Net.Sockets.TcpClient(hostName, tunnelPort);
tunnelStream = tunnelClient.GetStream() as Stream;
tunnelClient = new TcpClient(hostName, tunnelPort);
tunnelStream = tunnelClient.GetStream();
if (isHttps)
{
......@@ -60,12 +58,15 @@ namespace Titanium.Web.Proxy.Helpers
{
if (sslStream != null)
sslStream.Dispose();
throw;
}
}
var sendRelay = Task.Factory.StartNew(() => {
if(sb!=null)
var sendRelay = Task.Factory.StartNew(() =>
{
if (sb != null)
clientStream.CopyToAsync(sb.ToString(), tunnelStream, BUFFER_SIZE);
else
clientStream.CopyToAsync(tunnelStream, BUFFER_SIZE);
......@@ -89,7 +90,5 @@ namespace Titanium.Web.Proxy.Helpers
throw;
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Titanium.Web.Proxy.Models
{
public class HttpHeader
{
public string Name { get; set; }
public string Value { get; set; }
public HttpHeader(string name, string value)
{
if (string.IsNullOrEmpty(name)) throw new Exception("Name cannot be null");
this.Name = name.Trim();
this.Value = value.Trim();
Name = name.Trim();
Value = value.Trim();
}
public string Name { get; set; }
public string Value { get; set; }
public override string ToString()
{
return String.Format("{0}: {1}", this.Name, this.Value);
return string.Format("{0}: {1}", Name, Value);
}
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Titanium.Web.Proxy.Properties")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
......@@ -17,9 +17,11 @@ using System.Runtime.InteropServices;
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5036e0b7-a0d0-4070-8eb0-72c129dee9b3")]
// Version information for an assembly consists of the following four values:
......@@ -29,5 +31,6 @@ using System.Runtime.InteropServices;
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Helpers;
using System.Text;
namespace Titanium.Web.Proxy
{
/// <summary>
/// Proxy Server Main class
/// Proxy Server Main class
/// </summary>
public partial class ProxyServer
{
private static readonly int BUFFER_SIZE = 8192;
private static readonly char[] semiSplit = new char[] { ';' };
private static readonly char[] SemiSplit = {';'};
private static readonly String[] colonSpaceSplit = new string[] { ": " };
private static readonly char[] spaceSplit = new char[] { ' ' };
private static readonly string[] ColonSpaceSplit = {": "};
private static readonly char[] SpaceSplit = {' '};
private static readonly Regex cookieSplitRegEx = new Regex(@",(?! )");
private static readonly Regex CookieSplitRegEx = new Regex(@",(?! )");
private static readonly byte[] chunkTrail = Encoding.ASCII.GetBytes(Environment.NewLine);
private static readonly byte[] ChunkEnd = Encoding.ASCII.GetBytes(0.ToString("x2") + Environment.NewLine + Environment.NewLine);
private static readonly byte[] ChunkTrail = Encoding.ASCII.GetBytes(Environment.NewLine);
private static object certificateAccessLock = new object();
private static readonly byte[] ChunkEnd =
Encoding.ASCII.GetBytes(0.ToString("x2") + Environment.NewLine + Environment.NewLine);
private static TcpListener listener;
private static CertificateManager CertManager { get; set; }
private static TcpListener _listener;
public static List<string> ExcludedHttpsHostNameRegex = new List<string>();
public static event EventHandler<SessionEventArgs> BeforeRequest;
public static event EventHandler<SessionEventArgs> BeforeResponse;
public static string RootCertificateName { get; set; }
public static bool EnableSSL { get; set; }
public static bool SetAsSystemProxy { get; set; }
public static Int32 ListeningPort { get; set; }
public static IPAddress ListeningIpAddress { get; set; }
static ProxyServer()
{
CertManager = new CertificateManager("Titanium",
......@@ -61,74 +45,89 @@ namespace Titanium.Web.Proxy
Initialize();
}
private static CertificateManager CertManager { get; set; }
public static string RootCertificateName { get; set; }
public static bool EnableSsl { get; set; }
public static bool SetAsSystemProxy { get; set; }
public static int ListeningPort { get; set; }
public static IPAddress ListeningIpAddress { get; set; }
public static event EventHandler<SessionEventArgs> BeforeRequest;
public static event EventHandler<SessionEventArgs> BeforeResponse;
public static void Initialize()
{
System.Net.ServicePointManager.Expect100Continue = false;
System.Net.WebRequest.DefaultWebProxy = null;
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.DnsRefreshTimeout = 3 * 60 * 1000;//3 minutes
ServicePointManager.MaxServicePointIdleTime = 3 * 60 * 1000;
ServicePointManager.Expect100Continue = false;
WebRequest.DefaultWebProxy = null;
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.DnsRefreshTimeout = 3*60*1000; //3 minutes
ServicePointManager.MaxServicePointIdleTime = 3*60*1000;
//HttpWebRequest certificate validation callback
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None) return true;
else
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None) return true;
return false;
};
};
//Fix a bug in .NET 4.0
NetFrameworkHelper.URLPeriodFix();
NetFrameworkHelper.UrlPeriodFix();
//useUnsafeHeaderParsing
NetFrameworkHelper.ToggleAllowUnsafeHeaderParsing(true);
}
public static bool Start()
{
listener = new TcpListener(ListeningIpAddress, ListeningPort);
listener.Start();
_listener = new TcpListener(ListeningIpAddress, ListeningPort);
_listener.Start();
ListeningPort = ((IPEndPoint)listener.LocalEndpoint).Port;
ListeningPort = ((IPEndPoint) _listener.LocalEndpoint).Port;
// accept clients asynchronously
listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
_listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
if (SetAsSystemProxy)
{
SystemProxyHelper.EnableProxyHTTP(ListeningIpAddress == IPAddress.Any ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort);
SystemProxyHelper.EnableProxyHttp(
Equals(ListeningIpAddress, IPAddress.Any) ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort);
FireFoxHelper.AddFirefox();
if (EnableSSL)
if (EnableSsl)
{
RootCertificateName = RootCertificateName == null ? "Titanium_Proxy_Test_Root" : RootCertificateName;
RootCertificateName = RootCertificateName ?? "Titanium_Proxy_Test_Root";
bool certTrusted = CertManager.CreateTrustedRootCertificate();
var certTrusted = CertManager.CreateTrustedRootCertificate();
//If certificate was trusted by the machine
if (certTrusted)
{
SystemProxyHelper.EnableProxyHTTPS(ListeningIpAddress == IPAddress.Any ? "127.0.0.1" : ListeningIpAddress.ToString(), ListeningPort);
SystemProxyHelper.EnableProxyHttps(
Equals(ListeningIpAddress, IPAddress.Any) ? "127.0.0.1" : ListeningIpAddress.ToString(),
ListeningPort);
}
}
}
return true;
}
private static void OnAcceptConnection(IAsyncResult asyn)
{
{
try
{
// Get the listener that handles the client request.
listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
_listener.BeginAcceptTcpClient(OnAcceptConnection, _listener);
TcpClient client = listener.EndAcceptTcpClient(asyn);
var client = _listener.EndAcceptTcpClient(asyn);
Task.Factory.StartNew(() => HandleClient(client));
}
catch { }
catch
{
// ignored
}
}
......@@ -140,9 +139,8 @@ namespace Titanium.Web.Proxy
FireFoxHelper.RemoveFirefox();
}
listener.Stop();
_listener.Stop();
CertManager.Dispose();
}
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DotNetZip" version="1.9.3" targetFramework="net40-Client" />
</packages>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment