Repository navigation
Expand file tree
/
Copy pathProxyWorker.cs
More file actions
294 lines (257 loc) · 12 KB
/
Copy pathProxyWorker.cs
File metadata and controls
294 lines (257 loc) · 12 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
using System;
using System.Net;
using System.Net.Quic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Examples.Shared;
using Titanium.Web.Proxy.Models;
using Titanium.Web.Proxy.Network;
using Titanium.Web.Proxy.Options;
namespace Titanium.Web.Proxy.Examples.WindowsService;
/// <summary>
/// Hosts a <see cref="ProxyServer" /> for the lifetime of the Windows Service / generic host process.
/// This replaces the old System.ServiceProcess.ServiceBase-derived ProxyService.
/// </summary>
internal sealed class ProxyWorker : BackgroundService
{
private readonly ProxySettings settings;
private readonly ILogger<ProxyWorker> logger;
private readonly ILoggerFactory loggerFactory;
private ProxyServer? proxyServer;
public ProxyWorker(IOptions<ProxySettings> settings, ILogger<ProxyWorker> logger, ILoggerFactory loggerFactory)
{
this.settings = settings.Value;
this.logger = logger;
this.loggerFactory = loggerFactory;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
if (settings.ListeningPort <= 0 || settings.ListeningPort > 65535)
throw new InvalidOperationException("Invalid listening port");
// We create a fresh ProxyServer instance on every start so a service restart also reloads settings.
proxyServer = new ProxyServer(false)
{
Profile = ProxyProfile.Balanced,
CheckCertificateRevocation = settings.CheckCertificateRevocation,
ConnectionTimeOutSeconds = settings.ConnectionTimeOutSeconds,
Enable100ContinueBehaviour = settings.Enable100ContinueBehaviour,
EnableConnectionPool = settings.EnableConnectionPool,
EnableTcpServerConnectionPrefetch = settings.EnableTcpServerConnectionPrefetch,
EnableWinAuth = settings.EnableWinAuth,
ForwardToUpstreamGateway = settings.ForwardToUpstreamGateway,
MaxCachedConnections = settings.MaxCachedConnections,
ReuseSocket = settings.ReuseSocket,
TcpTimeWaitSeconds = settings.TcpTimeWaitSeconds,
EnableHttp2 = settings.EnableHttp2,
NoDelay = settings.NoDelay
};
proxyServer.CertificateManager.CertificateEngine = Network.CertificateEngine.BouncyCastleFast;
proxyServer.CertificateManager.SaveFakeCertificates = settings.SaveFakeCertificates;
proxyServer.CertificateManager.LeafCertificateKeyAlgorithm = settings.LeafCertificateKeyAlgorithm;
if (settings.TrustRootCertificate || settings.TrustRootCertificateMachine)
{
proxyServer.CertificateManager.EnsureRootCertificate();
proxyServer.CertificateManager.TrustRootCertificate(
machineTrusted: settings.TrustRootCertificateMachine);
logger.LogInformation(
settings.TrustRootCertificateMachine
? "Trusted MITM root in Current User and Local Machine certificate stores (machine install needs elevation)"
: "Trusted MITM root in Current User certificate stores");
}
proxyServer.ThreadPoolWorkerThread = settings.ThreadPoolWorkerThreads < 0
? Environment.ProcessorCount
: settings.ThreadPoolWorkerThreads;
if (settings.ThreadPoolWorkerThreads >= 0 && settings.ThreadPoolWorkerThreads < Environment.ProcessorCount)
logger.LogWarning(
"Worker thread count of {ConfiguredThreads} is below the processor count of {ProcessorCount}. " +
"This may be on purpose.", settings.ThreadPoolWorkerThreads, Environment.ProcessorCount);
var explicitEndPointV4 = new ExplicitProxyEndPoint(IPAddress.Any, settings.ListeningPort, settings.DecryptSsl);
explicitEndPointV4.BeforeTunnelConnectRequest += OnBeforeTunnelConnectRequest;
proxyServer.AddEndPoint(explicitEndPointV4);
ExplicitProxyEndPoint? explicitEndPointV6 = null;
if (settings.EnableIpV6)
{
explicitEndPointV6 =
new ExplicitProxyEndPoint(IPAddress.IPv6Any, settings.ListeningPort, settings.DecryptSsl);
explicitEndPointV6.BeforeTunnelConnectRequest += OnBeforeTunnelConnectRequest;
proxyServer.AddEndPoint(explicitEndPointV6);
}
// HTTP/3 transparent QUIC endpoint (experimental — suppress TWP001 to opt in).
// Requires MsQuic and a supported OS. UDP traffic must be redirected here; see wiki/HTTP-3.md.
#pragma warning disable TWP001
if (settings.EnableHttp3)
{
if (QuicListener.IsSupported)
{
if (settings.QuicListeningPort <= 0 || settings.QuicListeningPort > 65535)
throw new InvalidOperationException("Invalid QUIC listening port");
proxyServer.EnableHttp3 = true;
proxyServer.EnableHttpsSvcbDnsDiscovery = settings.EnableHttpsSvcbDnsDiscovery;
var quicEndPoint = new TransparentQuicProxyEndPoint(IPAddress.Any, settings.QuicListeningPort)
{
// Replace with IOriginalDestinationResolver for real NAT-transparent interception.
ForwardHost = "localhost",
ForwardPort = 443
};
proxyServer.AddEndPoint(quicEndPoint);
logger.LogInformation(
"HTTP/3 QUIC endpoint started on UDP {QuicListeningPort} (SVCB discovery={SvcbDiscovery})",
settings.QuicListeningPort,
settings.EnableHttpsSvcbDnsDiscovery ? "on" : "off");
}
else
{
logger.LogWarning(
"EnableHttp3 is true but QuicListener.IsSupported is false on this platform. " +
"HTTP/3 skipped. Windows requires Windows 11 / Server 2022+.");
}
}
#pragma warning restore TWP001
// Bridge the proxy's diagnostic logging into the host's Serilog pipeline (rolling files + Event Log).
proxyServer.Logging.Enabled = settings.EnableProxyLogging;
proxyServer.Logging.LoggerFactory = loggerFactory;
if (settings.LogRequests)
proxyServer.BeforeResponse += OnBeforeResponse;
try
{
proxyServer.Start();
}
catch (Exception ex) when (IsAddressAlreadyInUse(ex))
{
logger.LogWarning(ex,
"ListeningPort {ListeningPort} unavailable; falling back to ephemeral port 0",
settings.ListeningPort);
proxyServer.RemoveEndPoint(explicitEndPointV4);
if (explicitEndPointV6 != null)
proxyServer.RemoveEndPoint(explicitEndPointV6);
explicitEndPointV4 = new ExplicitProxyEndPoint(IPAddress.Any, 0, settings.DecryptSsl);
explicitEndPointV4.BeforeTunnelConnectRequest += OnBeforeTunnelConnectRequest;
proxyServer.AddEndPoint(explicitEndPointV4);
if (settings.EnableIpV6)
{
explicitEndPointV6 =
new ExplicitProxyEndPoint(IPAddress.IPv6Any, 0, settings.DecryptSsl);
explicitEndPointV6.BeforeTunnelConnectRequest += OnBeforeTunnelConnectRequest;
proxyServer.AddEndPoint(explicitEndPointV6);
}
proxyServer.Start();
}
if (settings.SetAsSystemProxy)
{
var result = proxyServer.TrySetAsSystemProxy(explicitEndPointV4, ProxyProtocolType.AllHttp,
KnownMitmExclusions.CreateSystemProxySettings());
if (result.Succeeded)
{
logger.LogInformation(
"Registered as Windows system proxy on port {ListeningPort} with identity host bypass (cleared on stop)",
explicitEndPointV4.Port);
}
else
{
logger.LogWarning("SetAsSystemProxy failed: {Message}", result.Message);
}
}
logger.LogInformation("Service listening on port {ListeningPort}", explicitEndPointV4.Port);
return base.StartAsync(cancellationToken);
}
private static bool IsAddressAlreadyInUse(Exception ex)
{
for (var cur = ex; cur != null; cur = cur.InnerException)
{
if (cur is System.Net.Sockets.SocketException se &&
(se.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse
|| se.NativeErrorCode is 10048 or 98))
return true;
}
return false;
}
private static Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e)
{
if (KnownMitmExclusions.ShouldDisableSslDecrypt(e.HttpClient.Request.RequestUri.Host))
e.DecryptSsl = false;
return Task.CompletedTask;
}
private Task OnBeforeResponse(object sender, SessionEventArgs e)
{
var request = e.HttpClient.Request;
var response = e.HttpClient.Response;
var statusCode = response?.StatusCode ?? 0;
// Aligned with the Basic/WPF traffic line shape; Information goes to files (Event Log is Warning+).
logger.LogInformation(
"{Method} {Url} → {StatusCode} | client↔proxy: {ClientProtocol} | proxy↔server: {ServerProtocol}",
request.Method,
request.Url,
statusCode,
FormatHttpProtocol(request.HttpVersion),
FormatHttpProtocol(response?.HttpVersion));
return Task.CompletedTask;
}
/// <summary>
/// Formats an HTTP version for brief logs (e.g. HTTP/1.1, HTTP/2, HTTP/3).
/// </summary>
private static string FormatHttpProtocol(Version? version)
{
if (version == null || version.Major == 0)
return "unknown";
if (version.Major >= 2)
return "HTTP/" + version.Major;
return "HTTP/" + version.Major + "." + version.Minor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// The proxy runs its own listener loops; just wait until the host asks us to stop.
try
{
await Task.Delay(Timeout.Infinite, stoppingToken);
}
catch (OperationCanceledException)
{
// expected on shutdown
}
}
public override Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Stopping proxy service...");
if (proxyServer != null && settings.LogRequests)
proxyServer.BeforeResponse -= OnBeforeResponse;
try
{
// Stop restores original system proxy when SetAsSystemProxy was used.
if (proxyServer?.ProxyRunning == true)
proxyServer.Stop();
else if (settings.SetAsSystemProxy)
proxyServer?.RestoreOriginalProxySettings();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Error while stopping proxy; attempting system proxy restore");
try
{
if (settings.SetAsSystemProxy)
proxyServer?.RestoreOriginalProxySettings();
}
catch (Exception restoreEx)
{
logger.LogWarning(restoreEx, "Failed to restore system proxy settings");
}
}
try
{
if ((settings.TrustRootCertificate || settings.TrustRootCertificateMachine) && proxyServer != null)
proxyServer.CertificateManager.RemoveTrustedRootCertificate(
machineTrusted: settings.TrustRootCertificateMachine);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Failed to remove trusted MITM root certificate");
}
// clean up here since we make a new instance every time the service starts
proxyServer?.Dispose();
proxyServer = null;
return base.StopAsync(cancellationToken);
}
}