-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
370 lines (320 loc) · 13 KB
/
Copy pathMainForm.cs
File metadata and controls
370 lines (320 loc) · 13 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Security;
using Titanium.Web.Proxy;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Models;
namespace HTTPInterceptor
{
public partial class MainForm : Form
{
private Process? targetProcess;
private List<string> domains = new List<string>();
private bool isRunning = false;
private bool isEnglish = false;
private LogForm? logForm;
private ProxyServer proxyServer = null!;
private ExplicitProxyEndPoint explicitEndPoint = null!;
private CancellationTokenSource? cts;
public MainForm()
{
InitializeComponent();
DetermineLanguage();
LocalizeUI();
this.FormClosing += MainForm_FormClosing;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
private async void MainForm_FormClosing(object? sender, FormClosingEventArgs e)
{
if (isRunning)
{
await StopProxy();
}
logForm?.Close();
}
private void DetermineLanguage()
{
string culture = CultureInfo.CurrentUICulture.Name;
isEnglish = culture.StartsWith("en", StringComparison.OrdinalIgnoreCase);
}
private void LocalizeUI()
{
lblExePath.Text = isEnglish ? "Target Application:" : "目標程式:";
btnBrowse.Text = isEnglish ? "Browse..." : "瀏覽...";
lblTarget.Text = isEnglish ? "Target Address:" : "目標地址:";
lblOrigin.Text = isEnglish ? "Origin Domains:" : "原始域名列表:";
btnControl.Text = isRunning ? (isEnglish ? "Stop" : "停止")
: (isEnglish ? "Start" : "開始");
lblStatus.Text = isEnglish ? $"Proxy Status: {(isRunning ? "Running" : "Stopped")}"
: $"Proxy 狀態: {(isRunning ? "運行中" : "已停止")}";
this.Text = isEnglish ? "Advanced Traffic Management Tool" : "高級流量管理工具";
}
private void btnBrowse_Click(object sender, EventArgs e)
{
using (var dlg = new OpenFileDialog())
{
dlg.Filter = isEnglish ? "Executable Files|*.exe" : "可執行檔|*.exe";
if (dlg.ShowDialog() == DialogResult.OK)
{
txtExePath.Text = dlg.FileName;
}
}
}
private async void btnControl_Click(object sender, EventArgs e)
{
if (isRunning)
{
await StopProxy();
}
else
{
if (!ValidateInputs()) return;
await StartProxy();
}
UpdateUIState();
LocalizeUI();
}
private bool ValidateInputs()
{
if (!File.Exists(txtExePath.Text))
{
MessageBox.Show(isEnglish ? "Please select a valid executable file." : "請選擇有效的可執行檔");
return false;
}
if (!ParseTargetAddress())
{
MessageBox.Show(isEnglish ? "Invalid target address format (e.g., localhost:443)" : "無效的目標地址格式 (正確範例: localhost:443)");
return false;
}
if (txtOriginList.Text == null)
{
MessageBox.Show(isEnglish ? "Domain list cannot be empty." : "域名列表不能為空");
return false;
}
return true;
}
private bool ParseTargetAddress()
{
var parts = txtTarget.Text.Split(':');
return parts.Length == 2 && int.TryParse(parts[1], out _);
}
private async Task StartProxy()
{
try
{
domains = txtOriginList.Text.Split(
new[] { '\n', ',', ' ' },
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries
).ToList();
cts = new CancellationTokenSource();
proxyServer = new ProxyServer();
proxyServer.CertificateManager.EnsureRootCertificate();
proxyServer.ServerCertificateValidationCallback += OnCertificateValidation;
proxyServer.ClientCertificateSelectionCallback += OnCertificateSelection;
proxyServer.BeforeRequest += OnRequest;
proxyServer.BeforeResponse += OnResponse;
explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, 8888, true);
explicitEndPoint.BeforeTunnelConnectRequest += OnBeforeTunnelConnectRequest;
proxyServer.AddEndPoint(explicitEndPoint);
proxyServer.Start();
logForm = new LogForm();
logForm.Show();
StartTargetProcess();
isRunning = true;
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ? "Proxy started." : "Proxy 啟動。"));
}
catch (Exception ex)
{
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ? $"Start Proxy Error: {ex}" : $"Proxy 啟動錯誤: {ex}"));
}
await Task.CompletedTask;
}
private Task OnCertificateValidation(object sender, CertificateValidationEventArgs e)
{
e.IsValid = e.SslPolicyErrors == SslPolicyErrors.None;
return Task.CompletedTask;
}
private Task OnCertificateSelection(object sender, CertificateSelectionEventArgs e)
{
return Task.CompletedTask;
}
private async Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e)
{
e.DecryptSsl = true;
await Task.CompletedTask;
}
private async Task OnRequest(object sender, SessionEventArgs e)
{
try
{
string originalHost = e.HttpClient.Request.RequestUri.Host;
bool shouldRedirect = domains.Any(d =>
originalHost.EndsWith(d.Replace("*.", ""), StringComparison.OrdinalIgnoreCase));
if (shouldRedirect)
{
var targetParts = txtTarget.Text.Split(':');
if (targetParts.Length == 2 && int.TryParse(targetParts[1], out int targetPort))
{
string targetHost = targetParts[0];
var uriBuilder = new UriBuilder(e.HttpClient.Request.RequestUri)
{
Scheme = "https",
Host = targetHost,
Port = targetPort
};
uriBuilder.Path = e.HttpClient.Request.RequestUri.AbsolutePath;
uriBuilder.Query = e.HttpClient.Request.RequestUri.Query;
e.HttpClient.Request.Url = uriBuilder.Uri.ToString();
AddLog($"[{DateTime.Now:HH:mm:ss}] 重定向 {originalHost} -> {targetHost}:{targetPort}");
}
}
}
catch (Exception ex)
{
AddLog($"[{DateTime.Now:HH:mm:ss}] 請求處理錯誤: {ex.Message}");
}
await Task.CompletedTask;
}
private async Task OnResponse(object sender, SessionEventArgs e)
{
try
{
if (e.HttpClient.Response.StatusCode >= 400)
{
string requestBody = string.Empty;
string responseBody = string.Empty;
var method = e.HttpClient.Request.Method.ToUpperInvariant();
if (method is "POST" or "PUT" or "PATCH" && e.HttpClient.Request.HasBody)
{
requestBody = await e.GetRequestBodyAsString();
}
if (e.HttpClient.Response.HasBody)
{
responseBody = await e.GetResponseBodyAsString();
}
AddLog($"[錯誤詳情]\n" +
$"請求URL: {e.HttpClient.Request.Url}\n" +
$"請求頭: {string.Join("\n", e.HttpClient.Request.Headers)}\n" +
$"請求體: {requestBody}\n" +
$"狀態碼: {e.HttpClient.Response.StatusCode}\n" +
$"響應頭: {string.Join("\n", e.HttpClient.Response.Headers)}\n" +
$"響應體: {responseBody}");
}
}
catch (Exception ex)
{
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ?
$"Response error: {ex}" :
$"回應錯誤: {ex}"));
}
await Task.CompletedTask;
}
private void StartTargetProcess()
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = txtExePath.Text,
UseShellExecute = false,
Environment =
{
["HTTP_PROXY"] = "http://127.0.0.1:8888",
["HTTPS_PROXY"] = "http://127.0.0.1:8888",
["NO_PROXY"] = "localhost,127.0.0.1",
["DOTNET_SYSTEM_NET_HTTP_USEPORTINSPN"] = "1",
["DOTNET_SYSTEM_NET_HTTP_USEPROXY"] = "1"
}
};
startInfo.WorkingDirectory = Path.GetDirectoryName(txtExePath.Text)!;
targetProcess = Process.Start(startInfo);
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ? "Target process started." : "目標程式啟動。"));
}
catch (Exception ex)
{
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ?
$"Error starting target process: {ex}" :
$"啟動目標程式錯誤: {ex}"));
}
}
private async Task StopProxy()
{
try
{
cts?.Cancel();
if (proxyServer != null)
{
explicitEndPoint.BeforeTunnelConnectRequest -= OnBeforeTunnelConnectRequest;
proxyServer.BeforeRequest -= OnRequest;
proxyServer.BeforeResponse -= OnResponse;
proxyServer.Stop();
}
if (targetProcess != null && !targetProcess.HasExited)
{
try
{
targetProcess.Kill();
await Task.Run(() => targetProcess.WaitForExit());
targetProcess.Dispose();
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ? "Target process terminated." : "目標程式已結束。"));
}
catch (Exception ex)
{
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ?
$"Error stopping target process: {ex}" :
$"停止目標程式錯誤: {ex}"));
}
}
}
catch (Exception ex)
{
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ?
$"Stop Proxy Error: {ex}" :
$"Proxy 停止錯誤: {ex}"));
}
finally
{
isRunning = false;
AddLog($"[{DateTime.Now:HH:mm:ss}] " + (isEnglish ? "Proxy stopped." : "Proxy 停止。"));
logForm?.Close();
}
}
private void UpdateUIState()
{
btnControl.Text = isRunning ? (isEnglish ? "Stop" : "停止")
: (isEnglish ? "Start" : "開始");
lblStatus.Text = isEnglish ? $"Proxy Status: {(isRunning ? "Running" : "Stopped")}"
: $"Proxy 狀態: {(isRunning ? "運行中" : "已停止")}";
}
private void AddLog(string message)
{
if (logForm != null && !logForm.IsDisposed)
{
logForm.Invoke((Action)(() =>
{
logForm.AppendLog(message);
}));
}
Debug.WriteLine(message);
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
private void lblExePath_Click(object sender, EventArgs e)
{
}
private void txtExePath_TextChanged(object sender, EventArgs e)
{
}
private void lblTarget_Click(object sender, EventArgs e)
{
}
private void lblOrigin_Click(object sender, EventArgs e)
{
}
}
}