Commit 711fc5e5 authored by Honfika's avatar Honfika

cleanup: removed unused using, field, local variable names fixed, other small fixes

parent 6493ea87
using System; using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Titanium.Web.Proxy.Examples.Basic.Helpers; using Titanium.Web.Proxy.Examples.Basic.Helpers;
namespace Titanium.Web.Proxy.Examples.Basic namespace Titanium.Web.Proxy.Examples.Basic
......
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Security; using System.Net.Security;
......
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Net; using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using Titanium.Web.Proxy.Helpers; using Titanium.Web.Proxy.Helpers;
using Titanium.Web.Proxy.Helpers.WinHttp; using Titanium.Web.Proxy.Helpers.WinHttp;
......
using System; using System.Text;
using System.Text;
using Titanium.Web.Proxy.Helpers; using Titanium.Web.Proxy.Helpers;
using Titanium.Web.Proxy.Http; using Titanium.Web.Proxy.Http;
......
using System; using System.Text;
using System.Text;
using Titanium.Web.Proxy.Helpers; using Titanium.Web.Proxy.Helpers;
using Titanium.Web.Proxy.Http; using Titanium.Web.Proxy.Http;
......
using System; using System.Collections.Concurrent;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
......
...@@ -35,7 +35,7 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -35,7 +35,7 @@ namespace Titanium.Web.Proxy.Helpers
/// <param name="bufferSize">Size of the buffer.</param> /// <param name="bufferSize">Size of the buffer.</param>
public CustomBufferedStream(Stream baseStream, int bufferSize) public CustomBufferedStream(Stream baseStream, int bufferSize)
{ {
readCallback = new AsyncCallback(ReadCallback); readCallback = ReadCallback;
this.baseStream = baseStream; this.baseStream = baseStream;
streamBuffer = BufferPool.GetBuffer(bufferSize); streamBuffer = BufferPool.GetBuffer(bufferSize);
} }
......
...@@ -3,7 +3,6 @@ using System.Collections.Generic; ...@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Titanium.Web.Proxy.Helpers namespace Titanium.Web.Proxy.Helpers
{ {
......
...@@ -11,7 +11,7 @@ namespace Titanium.Web.Proxy.Helpers ...@@ -11,7 +11,7 @@ namespace Titanium.Web.Proxy.Helpers
/// cache for mono runtime check /// cache for mono runtime check
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
private static Lazy<bool> isRunningOnMono private static readonly Lazy<bool> isRunningOnMono
= new Lazy<bool>(()=> Type.GetType("Mono.Runtime") != null); = new Lazy<bool>(()=> Type.GetType("Mono.Runtime") != null);
/// <summary> /// <summary>
......
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Microsoft.Win32; using Microsoft.Win32;
......
...@@ -62,8 +62,8 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp ...@@ -62,8 +62,8 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp
public AutoProxyFlags Flags; public AutoProxyFlags Flags;
public AutoDetectType AutoDetectFlags; public AutoDetectType AutoDetectFlags;
[MarshalAs(UnmanagedType.LPWStr)] public string AutoConfigUrl; [MarshalAs(UnmanagedType.LPWStr)] public string AutoConfigUrl;
private IntPtr lpvReserved; private readonly IntPtr lpvReserved;
private int dwReserved; private readonly int dwReserved;
public bool AutoLogonIfChallenged; public bool AutoLogonIfChallenged;
} }
......
...@@ -26,7 +26,7 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp ...@@ -26,7 +26,7 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp
public bool AutomaticallyDetectSettings { get; internal set; } public bool AutomaticallyDetectSettings { get; internal set; }
private WebProxy Proxy { get; set; } private WebProxy proxy { get; set; }
public WinHttpWebProxyFinder() public WinHttpWebProxyFinder()
{ {
...@@ -89,26 +89,26 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp ...@@ -89,26 +89,26 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp
return null; return null;
} }
string proxy = proxies[0]; string proxyStr = proxies[0];
int port = 80; int port = 80;
if (proxy.Contains(":")) if (proxyStr.Contains(":"))
{ {
var parts = proxy.Split(new[] { ':' }, 2); var parts = proxyStr.Split(new[] { ':' }, 2);
proxy = parts[0]; proxyStr = parts[0];
port = int.Parse(parts[1]); port = int.Parse(parts[1]);
} }
// TODO: Apply authorization // TODO: Apply authorization
var systemProxy = new ExternalProxy var systemProxy = new ExternalProxy
{ {
HostName = proxy, HostName = proxyStr,
Port = port, Port = port,
}; };
return systemProxy; return systemProxy;
} }
if (Proxy?.IsBypassed(destination) == true) if (proxy?.IsBypassed(destination) == true)
return null; return null;
var protocolType = ProxyInfo.ParseProtocolType(destination.Scheme); var protocolType = ProxyInfo.ParseProtocolType(destination.Scheme);
...@@ -138,7 +138,7 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp ...@@ -138,7 +138,7 @@ namespace Titanium.Web.Proxy.Helpers.WinHttp
AutomaticConfigurationScript = pi.AutoConfigUrl == null ? null : new Uri(pi.AutoConfigUrl); AutomaticConfigurationScript = pi.AutoConfigUrl == null ? null : new Uri(pi.AutoConfigUrl);
BypassLoopback = pi.BypassLoopback; BypassLoopback = pi.BypassLoopback;
BypassOnLocal = pi.BypassOnLocal; BypassOnLocal = pi.BypassOnLocal;
Proxy = new WebProxy(new Uri("http://localhost"), BypassOnLocal, pi.BypassList); proxy = new WebProxy(new Uri("http://localhost"), BypassOnLocal, pi.BypassList);
} }
private ProxyInfo GetProxyInfo() private ProxyInfo GetProxyInfo()
......
...@@ -336,9 +336,9 @@ namespace Titanium.Web.Proxy.Http ...@@ -336,9 +336,9 @@ namespace Titanium.Web.Proxy.Http
{ {
if (RequestHeaders.ContainsKey(name)) if (RequestHeaders.ContainsKey(name))
{ {
return new List<HttpHeader>() { RequestHeaders[name] }; return new List<HttpHeader> { RequestHeaders[name] };
} }
else if (NonUniqueRequestHeaders.ContainsKey(name)) if (NonUniqueRequestHeaders.ContainsKey(name))
{ {
return new List<HttpHeader>(NonUniqueRequestHeaders[name]); return new List<HttpHeader>(NonUniqueRequestHeaders[name]);
} }
...@@ -388,7 +388,7 @@ namespace Titanium.Web.Proxy.Http ...@@ -388,7 +388,7 @@ namespace Titanium.Web.Proxy.Http
RequestHeaders.Remove(newHeader.Name); RequestHeaders.Remove(newHeader.Name);
NonUniqueRequestHeaders.Add(newHeader.Name, NonUniqueRequestHeaders.Add(newHeader.Name,
new List<HttpHeader>() { existing, newHeader }); new List<HttpHeader> { existing, newHeader });
} }
else else
{ {
...@@ -409,7 +409,7 @@ namespace Titanium.Web.Proxy.Http ...@@ -409,7 +409,7 @@ namespace Titanium.Web.Proxy.Http
RequestHeaders.Remove(headerName); RequestHeaders.Remove(headerName);
return true; return true;
} }
else if (NonUniqueRequestHeaders.ContainsKey(headerName)) if (NonUniqueRequestHeaders.ContainsKey(headerName))
{ {
NonUniqueRequestHeaders.Remove(headerName); NonUniqueRequestHeaders.Remove(headerName);
return true; return true;
......
using System; using System;
using System.Linq; using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Text; using System.Text;
using Titanium.Web.Proxy.Extensions; using Titanium.Web.Proxy.Extensions;
using Titanium.Web.Proxy.Models; using Titanium.Web.Proxy.Models;
...@@ -269,9 +268,9 @@ namespace Titanium.Web.Proxy.Http ...@@ -269,9 +268,9 @@ namespace Titanium.Web.Proxy.Http
{ {
if (ResponseHeaders.ContainsKey(name)) if (ResponseHeaders.ContainsKey(name))
{ {
return new List<HttpHeader>() { ResponseHeaders[name] }; return new List<HttpHeader> { ResponseHeaders[name] };
} }
else if (NonUniqueResponseHeaders.ContainsKey(name)) if (NonUniqueResponseHeaders.ContainsKey(name))
{ {
return new List<HttpHeader>(NonUniqueResponseHeaders[name]); return new List<HttpHeader>(NonUniqueResponseHeaders[name]);
} }
...@@ -321,7 +320,7 @@ namespace Titanium.Web.Proxy.Http ...@@ -321,7 +320,7 @@ namespace Titanium.Web.Proxy.Http
ResponseHeaders.Remove(newHeader.Name); ResponseHeaders.Remove(newHeader.Name);
NonUniqueResponseHeaders.Add(newHeader.Name, NonUniqueResponseHeaders.Add(newHeader.Name,
new List<HttpHeader>() { existing, newHeader }); new List<HttpHeader> { existing, newHeader });
} }
else else
{ {
...@@ -342,7 +341,7 @@ namespace Titanium.Web.Proxy.Http ...@@ -342,7 +341,7 @@ namespace Titanium.Web.Proxy.Http
ResponseHeaders.Remove(headerName); ResponseHeaders.Remove(headerName);
return true; return true;
} }
else if (NonUniqueResponseHeaders.ContainsKey(headerName)) if (NonUniqueResponseHeaders.ContainsKey(headerName))
{ {
NonUniqueResponseHeaders.Remove(headerName); NonUniqueResponseHeaders.Remove(headerName);
return true; return true;
......
...@@ -239,8 +239,6 @@ namespace Titanium.Web.Proxy.Network.Certificate ...@@ -239,8 +239,6 @@ namespace Titanium.Web.Proxy.Network.Certificate
typeX509Enrollment.InvokeMember("CertificateFriendlyName", BindingFlags.PutDispProperty, null, x509Enrollment, typeValue); typeX509Enrollment.InvokeMember("CertificateFriendlyName", BindingFlags.PutDispProperty, null, x509Enrollment, typeValue);
} }
var members = typeX509Enrollment.GetMembers();
typeValue[0] = 0; typeValue[0] = 0;
var createCertRequest = typeX509Enrollment.InvokeMember("CreateRequest", BindingFlags.InvokeMethod, null, x509Enrollment, typeValue); var createCertRequest = typeX509Enrollment.InvokeMember("CreateRequest", BindingFlags.InvokeMethod, null, x509Enrollment, typeValue);
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
#endregion #endregion
internal static uint NewContextAttributes = 0; internal static uint NewContextAttributes = 0;
internal static Common.SecurityInteger NewLifeTime = new SecurityInteger(0); internal static SecurityInteger NewLifeTime = new SecurityInteger(0);
#region internal constants #region internal constants
internal const int StandardContextAttributes = ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_CONNECTION; internal const int StandardContextAttributes = ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_CONNECTION;
...@@ -34,7 +34,7 @@ ...@@ -34,7 +34,7 @@
} }
[Flags] [Flags]
internal enum NtlmFlags : int internal enum NtlmFlags
{ {
// The client sets this flag to indicate that it supports Unicode strings. // The client sets this flag to indicate that it supports Unicode strings.
NegotiateUnicode = 0x00000001, NegotiateUnicode = 0x00000001,
...@@ -161,18 +161,18 @@ ...@@ -161,18 +161,18 @@
{ {
ulVersion = (int)SecurityBufferType.SECBUFFER_VERSION; ulVersion = (int)SecurityBufferType.SECBUFFER_VERSION;
cBuffers = 1; cBuffers = 1;
Common.SecurityBuffer ThisSecBuffer = new Common.SecurityBuffer(bufferSize); SecurityBuffer thisSecBuffer = new SecurityBuffer(bufferSize);
pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(ThisSecBuffer)); pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(thisSecBuffer));
Marshal.StructureToPtr(ThisSecBuffer, pBuffers, false); Marshal.StructureToPtr(thisSecBuffer, pBuffers, false);
} }
internal SecurityBufferDesciption(byte[] secBufferBytes) internal SecurityBufferDesciption(byte[] secBufferBytes)
{ {
ulVersion = (int)SecurityBufferType.SECBUFFER_VERSION; ulVersion = (int)SecurityBufferType.SECBUFFER_VERSION;
cBuffers = 1; cBuffers = 1;
Common.SecurityBuffer ThisSecBuffer = new Common.SecurityBuffer(secBufferBytes); SecurityBuffer thisSecBuffer = new SecurityBuffer(secBufferBytes);
pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(ThisSecBuffer)); pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(thisSecBuffer));
Marshal.StructureToPtr(ThisSecBuffer, pBuffers, false); Marshal.StructureToPtr(thisSecBuffer, pBuffers, false);
} }
public void Dispose() public void Dispose()
...@@ -181,12 +181,12 @@ ...@@ -181,12 +181,12 @@
{ {
if (cBuffers == 1) if (cBuffers == 1)
{ {
Common.SecurityBuffer ThisSecBuffer = (Common.SecurityBuffer)Marshal.PtrToStructure(pBuffers, typeof(Common.SecurityBuffer)); SecurityBuffer thisSecBuffer = (SecurityBuffer)Marshal.PtrToStructure(pBuffers, typeof(SecurityBuffer));
ThisSecBuffer.Dispose(); thisSecBuffer.Dispose();
} }
else else
{ {
for (int Index = 0; Index < cBuffers; Index++) for (int index = 0; index < cBuffers; index++)
{ {
//The bits were written out the following order: //The bits were written out the following order:
//int cbBuffer; //int cbBuffer;
...@@ -194,9 +194,9 @@ ...@@ -194,9 +194,9 @@
//pvBuffer; //pvBuffer;
//What we need to do here is to grab a hold of the pvBuffer allocate by the individual //What we need to do here is to grab a hold of the pvBuffer allocate by the individual
//SecBuffer and release it... //SecBuffer and release it...
int CurrentOffset = Index * Marshal.SizeOf(typeof(Buffer)); int currentOffset = index * Marshal.SizeOf(typeof(Buffer));
IntPtr SecBufferpvBuffer = Marshal.ReadIntPtr(pBuffers, CurrentOffset + Marshal.SizeOf(typeof(int)) + Marshal.SizeOf(typeof(int))); IntPtr secBufferpvBuffer = Marshal.ReadIntPtr(pBuffers, currentOffset + Marshal.SizeOf(typeof(int)) + Marshal.SizeOf(typeof(int)));
Marshal.FreeHGlobal(SecBufferpvBuffer); Marshal.FreeHGlobal(secBufferpvBuffer);
} }
} }
...@@ -207,7 +207,7 @@ ...@@ -207,7 +207,7 @@
internal byte[] GetBytes() internal byte[] GetBytes()
{ {
byte[] Buffer = null; byte[] buffer = null;
if (pBuffers == IntPtr.Zero) if (pBuffers == IntPtr.Zero)
{ {
...@@ -216,32 +216,32 @@ ...@@ -216,32 +216,32 @@
if (cBuffers == 1) if (cBuffers == 1)
{ {
Common.SecurityBuffer ThisSecBuffer = (Common.SecurityBuffer)Marshal.PtrToStructure(pBuffers, typeof(Common.SecurityBuffer)); SecurityBuffer thisSecBuffer = (SecurityBuffer)Marshal.PtrToStructure(pBuffers, typeof(SecurityBuffer));
if (ThisSecBuffer.cbBuffer > 0) if (thisSecBuffer.cbBuffer > 0)
{ {
Buffer = new byte[ThisSecBuffer.cbBuffer]; buffer = new byte[thisSecBuffer.cbBuffer];
Marshal.Copy(ThisSecBuffer.pvBuffer, Buffer, 0, ThisSecBuffer.cbBuffer); Marshal.Copy(thisSecBuffer.pvBuffer, buffer, 0, thisSecBuffer.cbBuffer);
} }
} }
else else
{ {
int BytesToAllocate = 0; int bytesToAllocate = 0;
for (int Index = 0; Index < cBuffers; Index++) for (int index = 0; index < cBuffers; index++)
{ {
//The bits were written out the following order: //The bits were written out the following order:
//int cbBuffer; //int cbBuffer;
//int BufferType; //int BufferType;
//pvBuffer; //pvBuffer;
//What we need to do here calculate the total number of bytes we need to copy... //What we need to do here calculate the total number of bytes we need to copy...
int CurrentOffset = Index * Marshal.SizeOf(typeof(Buffer)); int currentOffset = index * Marshal.SizeOf(typeof(Buffer));
BytesToAllocate += Marshal.ReadInt32(pBuffers, CurrentOffset); bytesToAllocate += Marshal.ReadInt32(pBuffers, currentOffset);
} }
Buffer = new byte[BytesToAllocate]; buffer = new byte[bytesToAllocate];
for (int Index = 0, BufferIndex = 0; Index < cBuffers; Index++) for (int index = 0, bufferIndex = 0; index < cBuffers; index++)
{ {
//The bits were written out the following order: //The bits were written out the following order:
//int cbBuffer; //int cbBuffer;
...@@ -249,15 +249,15 @@ ...@@ -249,15 +249,15 @@
//pvBuffer; //pvBuffer;
//Now iterate over the individual buffers and put them together into a //Now iterate over the individual buffers and put them together into a
//byte array... //byte array...
int CurrentOffset = Index * Marshal.SizeOf(typeof(Buffer)); int currentOffset = index * Marshal.SizeOf(typeof(Buffer));
int BytesToCopy = Marshal.ReadInt32(pBuffers, CurrentOffset); int bytesToCopy = Marshal.ReadInt32(pBuffers, currentOffset);
IntPtr SecBufferpvBuffer = Marshal.ReadIntPtr(pBuffers, CurrentOffset + Marshal.SizeOf(typeof(int)) + Marshal.SizeOf(typeof(int))); IntPtr secBufferpvBuffer = Marshal.ReadIntPtr(pBuffers, currentOffset + Marshal.SizeOf(typeof(int)) + Marshal.SizeOf(typeof(int)));
Marshal.Copy(SecBufferpvBuffer, Buffer, BufferIndex, BytesToCopy); Marshal.Copy(secBufferpvBuffer, buffer, bufferIndex, bytesToCopy);
BufferIndex += BytesToCopy; bufferIndex += bytesToCopy;
} }
} }
return (Buffer); return (buffer);
} }
} }
#endregion #endregion
......
...@@ -39,45 +39,39 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -39,45 +39,39 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
unsafe private static byte[] GetUShortBytes (byte *bytes) unsafe private static byte[] GetUShortBytes (byte *bytes)
{ {
if (BitConverter.IsLittleEndian) if (BitConverter.IsLittleEndian)
{ {
return new byte[] { bytes[0], bytes[1] }; return new[] { bytes[0], bytes[1] };
}
else
{
return new byte[] { bytes[1], bytes[0] };
} }
return new[] { bytes[1], bytes[0] };
} }
unsafe private static byte[] GetUIntBytes (byte *bytes) unsafe private static byte[] GetUIntBytes (byte *bytes)
{ {
if (BitConverter.IsLittleEndian) if (BitConverter.IsLittleEndian)
{
return new byte[] { bytes[0], bytes[1], bytes[2], bytes[3] };
}
else
{ {
return new byte[] { bytes[3], bytes[2], bytes[1], bytes[0] }; return new[] { bytes[0], bytes[1], bytes[2], bytes[3] };
} }
return new[] { bytes[3], bytes[2], bytes[1], bytes[0] };
} }
unsafe private static byte[] GetULongBytes (byte *bytes) unsafe private static byte[] GetULongBytes (byte *bytes)
{ {
if (BitConverter.IsLittleEndian) if (BitConverter.IsLittleEndian)
{ {
return new byte[] { bytes [0], bytes [1], bytes [2], bytes [3], return new[] { bytes [0], bytes [1], bytes [2], bytes [3],
bytes [4], bytes [5], bytes [6], bytes [7] }; bytes [4], bytes [5], bytes [6], bytes [7] };
} }
else
{ return new[] { bytes [7], bytes [6], bytes [5], bytes [4],
return new byte[] { bytes [7], bytes [6], bytes [5], bytes [4], bytes [3], bytes [2], bytes [1], bytes [0] };
bytes [3], bytes [2], bytes [1], bytes [0] };
}
} }
unsafe internal static byte[] GetBytes (bool value) internal static byte[] GetBytes (bool value)
{ {
return new byte [] { value ? (byte)1 : (byte)0 }; return new[] { value ? (byte)1 : (byte)0 };
} }
unsafe internal static byte[] GetBytes (char value) unsafe internal static byte[] GetBytes (char value)
...@@ -168,7 +162,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -168,7 +162,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
} }
} }
unsafe internal static bool ToBoolean (byte[] value, int startIndex) internal static bool ToBoolean (byte[] value, int startIndex)
{ {
return value [startIndex] != 0; return value [startIndex] != 0;
} }
......
...@@ -40,11 +40,11 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -40,11 +40,11 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
internal class Message internal class Message
{ {
static private byte[] header = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 }; static private readonly byte[] header = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 };
internal Message (byte[] message) internal Message (byte[] message)
{ {
_type = 3; type = 3;
Decode (message); Decode (message);
} }
...@@ -66,16 +66,11 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -66,16 +66,11 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
private set; private set;
} }
private int _type; private readonly int type;
private Common.NtlmFlags _flags;
internal Common.NtlmFlags Flags internal Common.NtlmFlags Flags { get; set; }
{
get { return _flags; }
set { _flags = value; }
}
// methods // methods
private void Decode (byte[] message) private void Decode (byte[] message)
{ {
//base.Decode (message); //base.Decode (message);
...@@ -110,28 +105,25 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -110,28 +105,25 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
Flags = (Common.NtlmFlags)0x8201; Flags = (Common.NtlmFlags)0x8201;
} }
int dom_len = LittleEndian.ToUInt16 (message, 28); int domLen = LittleEndian.ToUInt16 (message, 28);
int dom_off = LittleEndian.ToUInt16 (message, 32); int domOff = LittleEndian.ToUInt16 (message, 32);
this.Domain = DecodeString (message, dom_off, dom_len); Domain = DecodeString (message, domOff, domLen);
int user_len = LittleEndian.ToUInt16 (message, 36); int userLen = LittleEndian.ToUInt16 (message, 36);
int user_off = LittleEndian.ToUInt16 (message, 40); int userOff = LittleEndian.ToUInt16 (message, 40);
this.Username = DecodeString (message, user_off, user_len); Username = DecodeString (message, userOff, userLen);
} }
string DecodeString (byte[] buffer, int offset, int len) string DecodeString (byte[] buffer, int offset, int len)
{ {
if ((Flags & Common.NtlmFlags.NegotiateUnicode) != 0) if ((Flags & Common.NtlmFlags.NegotiateUnicode) != 0)
{ {
return Encoding.Unicode.GetString(buffer, offset, len); return Encoding.Unicode.GetString(buffer, offset, len);
} }
else return Encoding.ASCII.GetString(buffer, offset, len);
{ }
return Encoding.ASCII.GetString(buffer, offset, len);
}
}
protected bool CheckHeader(byte[] message) protected bool CheckHeader(byte[] message)
{ {
...@@ -140,7 +132,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -140,7 +132,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
if (message[i] != header[i]) if (message[i] != header[i])
return false; return false;
} }
return (LittleEndian.ToUInt32(message, 8) == _type); return (LittleEndian.ToUInt32(message, 8) == type);
} }
} }
......
...@@ -9,10 +9,10 @@ ...@@ -9,10 +9,10 @@
{ {
internal State() internal State()
{ {
this.Credentials = new Common.SecurityHandle(0); Credentials = new Common.SecurityHandle(0);
this.Context = new Common.SecurityHandle(0); Context = new Common.SecurityHandle(0);
this.LastSeen = DateTime.Now; LastSeen = DateTime.Now;
} }
/// <summary> /// <summary>
...@@ -32,13 +32,13 @@ ...@@ -32,13 +32,13 @@
internal void ResetHandles() internal void ResetHandles()
{ {
this.Credentials.Reset(); Credentials.Reset();
this.Context.Reset(); Context.Reset();
} }
internal void UpdatePresence() internal void UpdatePresence()
{ {
this.LastSeen = DateTime.Now; LastSeen = DateTime.Now;
} }
} }
} }
...@@ -16,7 +16,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -16,7 +16,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
/// <summary> /// <summary>
/// Keep track of auth states for reuse in final challenge response /// Keep track of auth states for reuse in final challenge response
/// </summary> /// </summary>
private static IDictionary<Guid, State> authStates private static readonly IDictionary<Guid, State> authStates
= new ConcurrentDictionary<Guid, State>(); = new ConcurrentDictionary<Guid, State>();
...@@ -27,10 +27,10 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -27,10 +27,10 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
/// <param name="authScheme"></param> /// <param name="authScheme"></param>
/// <param name="requestId"></param> /// <param name="requestId"></param>
/// <returns></returns> /// <returns></returns>
internal static byte[] AcquireInitialSecurityToken(string hostname, internal static byte[] AcquireInitialSecurityToken(string hostname,
string authScheme, Guid requestId) string authScheme, Guid requestId)
{ {
byte[] token = null; byte[] token;
//null for initial call //null for initial call
SecurityBufferDesciption serverToken SecurityBufferDesciption serverToken
...@@ -53,7 +53,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -53,7 +53,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
IntPtr.Zero, IntPtr.Zero,
0, 0,
IntPtr.Zero, IntPtr.Zero,
ref state.Credentials, ref state.Credentials,
ref NewLifeTime); ref NewLifeTime);
if (result != SuccessfulResult) if (result != SuccessfulResult)
...@@ -70,9 +70,9 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -70,9 +70,9 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
SecurityNativeDataRepresentation, SecurityNativeDataRepresentation,
ref serverToken, ref serverToken,
0, 0,
out state.Context, out state.Context,
out clientToken, out clientToken,
out NewContextAttributes, out NewContextAttributes,
out NewLifeTime); out NewLifeTime);
...@@ -101,10 +101,10 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -101,10 +101,10 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
/// <param name="serverChallenge"></param> /// <param name="serverChallenge"></param>
/// <param name="requestId"></param> /// <param name="requestId"></param>
/// <returns></returns> /// <returns></returns>
internal static byte[] AcquireFinalSecurityToken(string hostname, internal static byte[] AcquireFinalSecurityToken(string hostname,
byte[] serverChallenge, Guid requestId) byte[] serverChallenge, Guid requestId)
{ {
byte[] token = null; byte[] token;
//user server challenge //user server challenge
SecurityBufferDesciption serverToken SecurityBufferDesciption serverToken
...@@ -140,7 +140,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -140,7 +140,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
// Client challenge issue operation failed. // Client challenge issue operation failed.
return null; return null;
} }
authStates.Remove(requestId); authStates.Remove(requestId);
token = clientToken.GetBytes(); token = clientToken.GetBytes();
} }
...@@ -152,7 +152,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -152,7 +152,7 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
return token; return token;
} }
/// <summary> /// <summary>
/// Clear any hanging states /// Clear any hanging states
/// </summary> /// </summary>
...@@ -177,46 +177,46 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security ...@@ -177,46 +177,46 @@ namespace Titanium.Web.Proxy.Network.WinAuth.Security
#region Native calls to secur32.dll #region Native calls to secur32.dll
[DllImport("secur32.dll", SetLastError = true)] [DllImport("secur32.dll", SetLastError = true)]
static extern int InitializeSecurityContext(ref SecurityHandle phCredential,//PCredHandle static extern int InitializeSecurityContext(ref SecurityHandle phCredential, //PCredHandle
IntPtr phContext, //PCtxtHandle IntPtr phContext, //PCtxtHandle
string pszTargetName, string pszTargetName,
int fContextReq, int fContextReq,
int Reserved1, int reserved1,
int TargetDataRep, int targetDataRep,
ref SecurityBufferDesciption pInput, //PSecBufferDesc SecBufferDesc ref SecurityBufferDesciption pInput, //PSecBufferDesc SecBufferDesc
int Reserved2, int reserved2,
out SecurityHandle phNewContext, //PCtxtHandle out SecurityHandle phNewContext, //PCtxtHandle
out SecurityBufferDesciption pOutput, //PSecBufferDesc SecBufferDesc out SecurityBufferDesciption pOutput, //PSecBufferDesc SecBufferDesc
out uint pfContextAttr, //managed ulong == 64 bits!!! out uint pfContextAttr, //managed ulong == 64 bits!!!
out SecurityInteger ptsExpiry); //PTimeStamp out SecurityInteger ptsExpiry); //PTimeStamp
[DllImport("secur32", CharSet = CharSet.Auto, SetLastError = true)] [DllImport("secur32", CharSet = CharSet.Auto, SetLastError = true)]
static extern int InitializeSecurityContext(ref SecurityHandle phCredential,//PCredHandle static extern int InitializeSecurityContext(ref SecurityHandle phCredential, //PCredHandle
ref SecurityHandle phContext, //PCtxtHandle ref SecurityHandle phContext, //PCtxtHandle
string pszTargetName, string pszTargetName,
int fContextReq, int fContextReq,
int Reserved1, int reserved1,
int TargetDataRep, int targetDataRep,
ref SecurityBufferDesciption SecBufferDesc, //PSecBufferDesc SecBufferDesc ref SecurityBufferDesciption secBufferDesc, //PSecBufferDesc SecBufferDesc
int Reserved2, int reserved2,
out SecurityHandle phNewContext, //PCtxtHandle out SecurityHandle phNewContext, //PCtxtHandle
out SecurityBufferDesciption pOutput, //PSecBufferDesc SecBufferDesc out SecurityBufferDesciption pOutput, //PSecBufferDesc SecBufferDesc
out uint pfContextAttr, //managed ulong == 64 bits!!! out uint pfContextAttr, //managed ulong == 64 bits!!!
out SecurityInteger ptsExpiry); //PTimeStamp out SecurityInteger ptsExpiry); //PTimeStamp
[DllImport("secur32.dll", CharSet = CharSet.Auto, SetLastError = false)] [DllImport("secur32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern int AcquireCredentialsHandle( private static extern int AcquireCredentialsHandle(
string pszPrincipal, //SEC_CHAR* string pszPrincipal, //SEC_CHAR*
string pszPackage, //SEC_CHAR* //"Kerberos","NTLM","Negotiative" string pszPackage, //SEC_CHAR* //"Kerberos","NTLM","Negotiative"
int fCredentialUse, int fCredentialUse,
IntPtr PAuthenticationID, //_LUID AuthenticationID,//pvLogonID, //PLUID IntPtr pAuthenticationId, //_LUID AuthenticationID,//pvLogonID, //PLUID
IntPtr pAuthData, //PVOID IntPtr pAuthData, //PVOID
int pGetKeyFn, //SEC_GET_KEY_FN int pGetKeyFn, //SEC_GET_KEY_FN
IntPtr pvGetKeyArgument, //PVOID IntPtr pvGetKeyArgument, //PVOID
ref Common.SecurityHandle phCredential, //SecHandle //PCtxtHandle ref ref SecurityHandle phCredential, //SecHandle //PCtxtHandle ref
ref Common.SecurityInteger ptsExpiry); //PTimeStamp //TimeStamp ref ref SecurityInteger ptsExpiry); //PTimeStamp //TimeStamp ref
#endregion #endregion
} }
} }
...@@ -67,9 +67,7 @@ namespace Titanium.Web.Proxy ...@@ -67,9 +67,7 @@ namespace Titanium.Web.Proxy
/// <summary> /// <summary>
/// Set firefox to use default system proxy /// Set firefox to use default system proxy
/// </summary> /// </summary>
private FireFoxProxySettingsManager firefoxProxySettingsManager private readonly FireFoxProxySettingsManager firefoxProxySettingsManager = new FireFoxProxySettingsManager();
= new FireFoxProxySettingsManager();
/// <summary> /// <summary>
/// Buffer size used throughout this proxy /// Buffer size used throughout this proxy
...@@ -263,7 +261,6 @@ namespace Titanium.Web.Proxy ...@@ -263,7 +261,6 @@ namespace Titanium.Web.Proxy
/// </summary> /// </summary>
public int ClientConnectionCount => clientConnectionCount; public int ClientConnectionCount => clientConnectionCount;
/// <summary> /// <summary>
/// Total number of active server connections /// Total number of active server connections
/// </summary> /// </summary>
......
...@@ -5,30 +5,28 @@ using System.Threading.Tasks; ...@@ -5,30 +5,28 @@ using System.Threading.Tasks;
using Titanium.Web.Proxy.EventArguments; using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Models; using Titanium.Web.Proxy.Models;
using Titanium.Web.Proxy.Network.WinAuth; using Titanium.Web.Proxy.Network.WinAuth;
using Titanium.Web.Proxy.Extensions;
using Titanium.Web.Proxy.Helpers;
namespace Titanium.Web.Proxy namespace Titanium.Web.Proxy
{ {
public partial class ProxyServer public partial class ProxyServer
{ {
//possible header names //possible header names
private static List<string> authHeaderNames private static readonly List<string> authHeaderNames = new List<string>
= new List<string>() { {
"WWW-Authenticate", "WWW-Authenticate",
//IIS 6.0 messed up names below //IIS 6.0 messed up names below
"WWWAuthenticate", "WWWAuthenticate",
"NTLMAuthorization", "NTLMAuthorization",
"NegotiateAuthorization", "NegotiateAuthorization",
"KerberosAuthorization" "KerberosAuthorization"
}; };
private static List<string> authSchemes private static readonly List<string> authSchemes = new List<string>
= new List<string>() { {
"NTLM", "NTLM",
"Negotiate", "Negotiate",
"Kerberos" "Kerberos"
}; };
/// <summary> /// <summary>
/// Handle windows NTLM authentication /// Handle windows NTLM authentication
...@@ -48,19 +46,18 @@ namespace Titanium.Web.Proxy ...@@ -48,19 +46,18 @@ namespace Titanium.Web.Proxy
var header = args.WebSession.Response var header = args.WebSession.Response
.NonUniqueResponseHeaders .NonUniqueResponseHeaders
.FirstOrDefault(x => .FirstOrDefault(x =>
authHeaderNames.Any(y => x.Key.Equals(y, StringComparison.OrdinalIgnoreCase))); authHeaderNames.Any(y => x.Key.Equals(y, StringComparison.OrdinalIgnoreCase)));
if (!header.Equals(new KeyValuePair<string, List<HttpHeader>>())) if (!header.Equals(new KeyValuePair<string, List<HttpHeader>>()))
{ {
headerName = header.Key; headerName = header.Key;
} }
if (headerName != null) if (headerName != null)
{ {
authHeader = args.WebSession.Response authHeader = args.WebSession.Response
.NonUniqueResponseHeaders[headerName] .NonUniqueResponseHeaders[headerName]
.Where(x => authSchemes.Any(y => x.Value.StartsWith(y, StringComparison.OrdinalIgnoreCase))) .FirstOrDefault(x => authSchemes.Any(y => x.Value.StartsWith(y, StringComparison.OrdinalIgnoreCase)));
.FirstOrDefault();
} }
//check in unique headers //check in unique headers
...@@ -70,7 +67,7 @@ namespace Titanium.Web.Proxy ...@@ -70,7 +67,7 @@ namespace Titanium.Web.Proxy
var uHeader = args.WebSession.Response var uHeader = args.WebSession.Response
.ResponseHeaders .ResponseHeaders
.FirstOrDefault(x => .FirstOrDefault(x =>
authHeaderNames.Any(y => x.Key.Equals(y, StringComparison.OrdinalIgnoreCase))); authHeaderNames.Any(y => x.Key.Equals(y, StringComparison.OrdinalIgnoreCase)));
if (!uHeader.Equals(new KeyValuePair<string, HttpHeader>())) if (!uHeader.Equals(new KeyValuePair<string, HttpHeader>()))
{ {
...@@ -80,8 +77,9 @@ namespace Titanium.Web.Proxy ...@@ -80,8 +77,9 @@ namespace Titanium.Web.Proxy
if (headerName != null) if (headerName != null)
{ {
authHeader = authSchemes.Any(x => args.WebSession.Response authHeader = authSchemes.Any(x => args.WebSession.Response
.ResponseHeaders[headerName].Value.StartsWith(x, StringComparison.OrdinalIgnoreCase)) ? .ResponseHeaders[headerName].Value.StartsWith(x, StringComparison.OrdinalIgnoreCase))
args.WebSession.Response.ResponseHeaders[headerName] : null; ? args.WebSession.Response.ResponseHeaders[headerName]
: null;
} }
} }
...@@ -101,7 +99,7 @@ namespace Titanium.Web.Proxy ...@@ -101,7 +99,7 @@ namespace Titanium.Web.Proxy
var clientToken = WinAuthHandler.GetInitialAuthToken(args.WebSession.Request.Host, scheme, args.Id); var clientToken = WinAuthHandler.GetInitialAuthToken(args.WebSession.Request.Host, scheme, args.Id);
var auth = new HttpHeader("Authorization", string.Concat(scheme, clientToken)); var auth = new HttpHeader("Authorization", string.Concat(scheme, clientToken));
//replace existing authorization header if any //replace existing authorization header if any
if (args.WebSession.Request.RequestHeaders.ContainsKey("Authorization")) if (args.WebSession.Request.RequestHeaders.ContainsKey("Authorization"))
{ {
...@@ -113,17 +111,17 @@ namespace Titanium.Web.Proxy ...@@ -113,17 +111,17 @@ namespace Titanium.Web.Proxy
} }
//don't need to send body for Authorization request //don't need to send body for Authorization request
if(args.WebSession.Request.HasBody) if (args.WebSession.Request.HasBody)
{ {
args.WebSession.Request.ContentLength = 0; args.WebSession.Request.ContentLength = 0;
} }
} }
//challenge value will start with any of the scheme selected //challenge value will start with any of the scheme selected
else else
{ {
scheme = authSchemes.FirstOrDefault(x => authHeader.Value.StartsWith(x, StringComparison.OrdinalIgnoreCase) scheme = authSchemes.FirstOrDefault(x => authHeader.Value.StartsWith(x, StringComparison.OrdinalIgnoreCase)
&& authHeader.Value.Length > x.Length + 1); && authHeader.Value.Length > x.Length + 1);
var serverToken = authHeader.Value.Substring(scheme.Length + 1); var serverToken = authHeader.Value.Substring(scheme.Length + 1);
var clientToken = WinAuthHandler.GetFinalAuthToken(args.WebSession.Request.Host, serverToken, args.Id); var clientToken = WinAuthHandler.GetFinalAuthToken(args.WebSession.Request.Host, serverToken, args.Id);
...@@ -135,10 +133,10 @@ namespace Titanium.Web.Proxy ...@@ -135,10 +133,10 @@ namespace Titanium.Web.Proxy
//send body for final auth request //send body for final auth request
if (args.WebSession.Request.HasBody) if (args.WebSession.Request.HasBody)
{ {
args.WebSession.Request.ContentLength args.WebSession.Request.ContentLength
= args.WebSession.Request.RequestBody.Length; = args.WebSession.Request.RequestBody.Length;
} }
} }
//Need to revisit this. //Need to revisit this.
...@@ -158,5 +156,4 @@ namespace Titanium.Web.Proxy ...@@ -158,5 +156,4 @@ namespace Titanium.Web.Proxy
} }
} }
} }
\ 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