-
Notifications
You must be signed in to change notification settings - Fork 14
/
HttpSecureNonHttpServer.cs
228 lines (210 loc) · 6.73 KB
/
HttpSecureNonHttpServer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
using System;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using static WebOne.Program;
namespace WebOne
{
/// <summary>
/// Fake HTTPS Proxy Server for non-HTTP/HTTPS protocols tunneling
/// </summary>
class HttpSecureNonHttpServer
{
Stream ClientStream;
Stream RemoteStream;
X509Certificate2 Certificate = null;
HttpRequest RequestReal;
HttpResponse ResponseReal;
LogWriter Logger;
/// <summary>
/// Start fake HTTPS proxy server emulation for already established NetworkStream.
/// </summary>
public HttpSecureNonHttpServer(HttpRequest Request, HttpResponse Response, bool UseSsl, LogWriter Logger)
{
RequestReal = Request;
ResponseReal = Response;
ClientStream = Request.InputStream;
this.Logger = Logger;
if (UseSsl)
{
if (!ConfigFile.SslEnable) return;
string HostName = RequestReal.RawUrl.Substring(0, RequestReal.RawUrl.IndexOf(":"));
Certificate = CertificateUtil.MakeChainSignedCert("CN=" + HostName, RootCertificate, ConfigFile.SslHashAlgorithm);
}
}
/// <summary>
/// Accept an incoming "connection" by establishing tunnel & start data exchange.
/// </summary>
public void Accept()
{
if (ConfigFile.AllowNonHttpsCONNECT)
{
// Answer that this proxy supports CONNECT method
ResponseReal.ProtocolVersion = new Version(1, 1);
ResponseReal.StatusCode = 200;
ResponseReal.StatusMessage = " Connection established";
ResponseReal.SendHeaders(); //"HTTP/1.1 200 Connection established"
}
else
{
// Reject connection request
string OnlyHTTPS = "This proxy is performing only HTTP and HTTPS tunneling.";
ResponseReal.ProtocolVersion = new Version(1, 1);
ResponseReal.StatusCode = 502;
ResponseReal.ContentType = "text/plain";
ResponseReal.ContentLength64 = OnlyHTTPS.Length;
ResponseReal.SendHeaders();
ResponseReal.OutputStream.Write(System.Text.Encoding.Default.GetBytes(OnlyHTTPS), 0, OnlyHTTPS.Length);
ResponseReal.Close();
Logger.WriteLine("<Not a HTTPS CONNECT, goodbye.");
return;
}
// Detect domain and port
Logger.WriteLine(">Non-HTTP: {0}", RequestReal.RawUrl);
string[] Parts = RequestReal.RawUrl.Split(":");
string Domain; int Port;
if (Parts.Length != 2) throw new Exception("Invalid `domain:port` pair supplied for CONNECT method.");
Domain = Parts[0];
if (!int.TryParse(Parts[1], out Port)) throw new Exception("Invalid port number supplied for CONNECT method.");
// Check for blacklisted URL
if (CheckString(RequestReal.RawUrl, ConfigFile.UrlBlackList))
{
Logger.WriteLine(" Blacklisted target, goodbye.");
return;
}
// Check for URL white list
if (ConfigFile.UrlWhiteList.Count > 0 && !CheckString(ConfigFile.UrlWhiteList.ToArray(), RequestReal.RawUrl))
{
Logger.WriteLine(" Non-allowed target, goodbye.");
return;
}
// Check for redirect
foreach (string SourceTarget in ConfigFile.NonHttpConnectRedirect.Keys)
{
if (RequestReal.RawUrl.Contains(SourceTarget))
{
RequestReal.RawUrl = ConfigFile.NonHttpConnectRedirect[SourceTarget];
Parts = RequestReal.RawUrl.Split(":");
Domain = Parts[0];
Port = int.Parse(Parts[1]);
Logger.WriteLine(" Redirect connection to {0}.", ConfigFile.NonHttpConnectRedirect[SourceTarget]);
}
}
// Perform an SSL/TLS handshake if need
if (Certificate != null)
{
if (!ConfigFile.SslEnable)
{
Logger.WriteLine("<SSL is disabled, goodbye.");
return;
}
SslStream ClientStreamTunnel = new(RequestReal.InputStream, true);
try
{
SslServerAuthenticationOptions ClientStreamTunnelOptions = new();
ClientStreamTunnelOptions.ServerCertificate = Certificate;
ClientStreamTunnelOptions.ClientCertificateRequired = false;
ClientStreamTunnelOptions.CertificateRevocationCheckMode = X509RevocationMode.NoCheck;
ClientStreamTunnelOptions.EnabledSslProtocols = ConfigFile.SslProtocols;
ClientStreamTunnelOptions.CipherSuitesPolicy = ConfigFile.SslCipherSuitesPolicy;
ClientStreamTunnel.AuthenticateAsServer(ClientStreamTunnelOptions);
ClientStream = ClientStreamTunnel;
}
catch (Exception HandshakeEx)
{
string err = HandshakeEx.Message;
if (HandshakeEx.InnerException != null) err = HandshakeEx.InnerException.Message;
Logger.WriteLine("!SSL client handshake failed: {0} ({1})", err, HandshakeEx.HResult);
ClientStream.Close();
return;
}
}
// Establish tunnel
TcpClient TunnelToRemote = new();
try
{
TunnelToRemote.Connect(Domain, Port);
if (Certificate != null)
{
RemoteStream = new SslStream(TunnelToRemote.GetStream(), true);
(RemoteStream as SslStream).AuthenticateAsClient(RequestReal.RawUrl.Substring(0, RequestReal.RawUrl.IndexOf(":")));
Logger.WriteLine(" Secure tunnel established.", RequestReal.RawUrl);
}
else
{
RemoteStream = TunnelToRemote.GetStream();
Logger.WriteLine(" Tunnel established.", RequestReal.RawUrl);
}
}
catch (Exception ex)
{
//An error occured, try to return nice error message, some clients like KVIrc will display it
Logger.WriteLine(" Connection failed: {0}.", ex.Message);
try { new StreamWriter(ClientStream).WriteLine("The proxy server is unable to connect: " + ex.Message); }
catch { };
ClientStream.Close();
return;
}
// Do routing
bool TunnelAlive = true;
try
{
BinaryReader BRclient = new(ClientStream);
BinaryWriter BWclient = new(ClientStream);
BinaryReader BRremote = new(RemoteStream);
BinaryWriter BWremote = new(RemoteStream);
new Task(() =>
{
try
{
while (true)
{
BWremote.Write(BRclient.ReadByte());
}
}
catch { TunnelAlive = false; }
}).Start();
new Task(() =>
{
try
{
while (true)
{
BWclient.Write(BRremote.ReadByte());
}
}
catch { TunnelAlive = false; }
}).Start();
}
catch (Exception ex)
{
Logger.WriteLine(" Tunnel error: {0}. Closing.", ex.ToString());
TunnelAlive = false;
};
// Wait while connecion is alive
while (TunnelAlive)
{
System.Threading.Thread.Sleep(1000);
if (ClientStream is NetworkStream)
{
TunnelAlive = (ClientStream as NetworkStream).Socket.Connected;
}
else if (ClientStream is SslStream)
{
TunnelAlive = (RequestReal.InputStream as NetworkStream).Socket.Connected;
}
};
// All done, close
if (TunnelToRemote.Connected)
{
TunnelToRemote.Close();
Logger.WriteLine(" Connection to {0} closed.", RequestReal.RawUrl);
}
else Logger.WriteLine(" Connection to {0} lost.", RequestReal.RawUrl);
ClientStream.Close();
return;
}
}
}