Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
1628 lines (1417 loc) · 61.7 KB
/
Copy pathProgram.cs
File metadata and controls
1628 lines (1417 loc) · 61.7 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
namespace ParentalControl
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "--service")
{
ServiceBase.Run(new ParentalControlService());
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ManagerForm());
}
}
// ============================================
// AUDIT LOGGER - Layer 7: Windows Event Log
// ============================================
public static class AuditLogger
{
private const string SourceName = "ParentalControl";
private const string LogName = "Application";
static AuditLogger()
{
try
{
if (!EventLog.SourceExists(SourceName))
EventLog.CreateEventSource(SourceName, LogName);
}
catch { /* Requires admin; silently skip if already exists */ }
}
public static void Log(string message, EventLogEntryType type = EventLogEntryType.Information)
{
try
{
EventLog.WriteEntry(SourceName, message, type, 1001);
}
catch { /* Never crash because of logging */ }
}
public static void LogBlock(string domain, string reason)
=> Log($"BLOCKED: {domain} | Reason: {reason}", EventLogEntryType.Warning);
public static void LogBypassAttempt(string detail)
=> Log($"BYPASS ATTEMPT: {detail}", EventLogEntryType.Error);
}
// ============================================
// BROWSER EXTENSION BLOCKER - Layer 4.5
// Disables all extensions in Chrome, Firefox, Edge, Opera, etc.
// ============================================
public static class BrowserExtensionBlocker
{
private static readonly object LockObj = new object();
// Common browser paths
private static readonly Dictionary<string, string> BrowserExtensionPaths = new Dictionary<string, string>
{
// Chrome/Chromium family
{ "chrome", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Google\Chrome\User Data") },
{ "chromium", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Chromium\User Data") },
{ "edge", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\Edge\User Data") },
{ "opera", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Opera Software\Opera Stable") },
{ "brave", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"BraveSoftware\Brave-Browser\User Data") },
{ "vivaldi", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Vivaldi\User Data") },
// Firefox
{ "firefox", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Mozilla\Firefox") },
};
public static void DisableAllExtensions()
{
lock (LockObj)
{
try
{
// Disable Chrome-based browsers
DisableChromeExtensions();
// Disable Firefox extensions
DisableFirefoxExtensions();
// Block extension install policies
BlockExtensionInstallation();
AuditLogger.Log("All browser extensions disabled/blocked");
}
catch (Exception ex)
{
AuditLogger.Log($"Error disabling extensions: {ex.Message}", EventLogEntryType.Warning);
}
}
}
private static void DisableChromeExtensions()
{
foreach (var browserPath in BrowserExtensionPaths.Where(x => x.Key != "firefox"))
{
try
{
if (!Directory.Exists(browserPath.Value)) continue;
var extensionsPath = Path.Combine(browserPath.Value, "Extensions");
if (Directory.Exists(extensionsPath))
{
// Disable each extension by modifying manifest.json
foreach (var extDir in Directory.GetDirectories(extensionsPath))
{
DisableChromeExtension(extDir);
}
}
// Also check for extensions in profile folders
var profiles = Directory.GetDirectories(browserPath.Value).Where(d => d.Contains("Profile") || d.Contains("Default"));
foreach (var profileDir in profiles)
{
var profileExtDir = Path.Combine(profileDir, "Extensions");
if (Directory.Exists(profileExtDir))
{
foreach (var extDir in Directory.GetDirectories(profileExtDir))
{
DisableChromeExtension(extDir);
}
}
}
}
catch { }
}
}
private static void DisableChromeExtension(string extensionDir)
{
try
{
var manifestPath = Path.Combine(extensionDir, "manifest.json");
if (!File.Exists(manifestPath)) return;
// Read manifest
var manifest = File.ReadAllText(manifestPath);
// Check if already disabled
if (manifest.Contains("\"disabled\": true")) return;
// Parse JSON and add disabled flag
using var doc = JsonDocument.Parse(manifest);
var options = new JsonSerializerOptions { WriteIndented = true };
var root = doc.RootElement;
// Create modified manifest with disabled flag
var modified = manifest;
if (!modified.Contains("\"disabled\""))
{
modified = modified.Replace("}", ",\"disabled\": true}", 1);
}
File.WriteAllText(manifestPath, modified);
AuditLogger.Log($"Disabled extension: {Path.GetFileName(extensionDir)}", EventLogEntryType.Information);
}
catch { }
}
private static void DisableFirefoxExtensions()
{
try
{
var firefoxProfilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
@"Mozilla\Firefox\Profiles");
if (!Directory.Exists(firefoxProfilePath)) return;
foreach (var profileDir in Directory.GetDirectories(firefoxProfilePath))
{
var extensionsJsonPath = Path.Combine(profileDir, "extensions.json");
if (!File.Exists(extensionsJsonPath)) continue;
try
{
var content = File.ReadAllText(extensionsJsonPath);
using var doc = JsonDocument.Parse(content);
var root = doc.RootElement;
// Disable all extensions in Firefox by modifying extensions.json
if (root.TryGetProperty("addons", out var addons))
{
var modified = content;
// Replace enabled:true with enabled:false
modified = System.Text.RegularExpressions.Regex.Replace(
modified,
"\"enabled\"\\s*:\\s*true",
"\"enabled\": false");
File.WriteAllText(extensionsJsonPath, modified);
AuditLogger.Log($"Disabled Firefox extensions in profile: {Path.GetFileName(profileDir)}", EventLogEntryType.Information);
}
}
catch { }
}
}
catch { }
}
private static void BlockExtensionInstallation()
{
try
{
// Chrome/Edge Group Policy to block extension installation
var regPath = @"Software\Policies\Google\Chrome";
using var key = Registry.CurrentUser.CreateSubKey(regPath);
if (key != null)
{
key.SetValue("ExtensionInstallBlocklist", new string[] { "*" }, RegistryValueKind.MultiString);
key.SetValue("ExtensionInstallAllowlist", "", RegistryValueKind.String);
AuditLogger.Log("Chrome extension installation policy enforced");
}
// Microsoft Edge policy
regPath = @"Software\Policies\Microsoft\Edge";
using var edgeKey = Registry.CurrentUser.CreateSubKey(regPath);
if (edgeKey != null)
{
edgeKey.SetValue("ExtensionInstallBlocklist", new string[] { "*" }, RegistryValueKind.MultiString);
edgeKey.SetValue("ExtensionInstallAllowlist", "", RegistryValueKind.String);
AuditLogger.Log("Edge extension installation policy enforced");
}
// Firefox about:config settings (requires automation)
BlockFirefoxExtensionInstall();
}
catch { }
}
private static void BlockFirefoxExtensionInstall()
{
try
{
var firefoxProfilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
@"Mozilla\Firefox\Profiles");
if (!Directory.Exists(firefoxProfilePath)) return;
foreach (var profileDir in Directory.GetDirectories(firefoxProfilePath))
{
var prefsPath = Path.Combine(profileDir, "prefs.js");
if (!File.Exists(prefsPath)) continue;
try
{
var content = File.ReadAllText(prefsPath);
// Add prefs to block extension installation
if (!content.Contains("extensions.autoDisableScopes"))
{
var newPrefs = content + "\nuser_pref(\"extensions.autoDisableScopes\", 15);\n";
newPrefs += "user_pref(\"extensions.update.autoUpdateDefault\", false);\n";
newPrefs += "user_pref(\"extensions.update.enabled\", false);\n";
File.WriteAllText(prefsPath, newPrefs);
AuditLogger.Log($"Firefox extension blocking enabled for profile: {Path.GetFileName(profileDir)}");
}
}
catch { }
}
}
catch { }
}
public static IEnumerable<string> GetInstalledExtensions()
{
var extensions = new List<string>();
try
{
// Scan Chrome extensions
foreach (var browserPath in BrowserExtensionPaths.Where(x => x.Key != "firefox"))
{
if (!Directory.Exists(browserPath.Value)) continue;
var extensionsPath = Path.Combine(browserPath.Value, "Extensions");
if (Directory.Exists(extensionsPath))
{
foreach (var extDir in Directory.GetDirectories(extensionsPath))
{
var manifestPath = Path.Combine(extDir, "manifest.json");
if (File.Exists(manifestPath))
{
try
{
var manifest = File.ReadAllText(manifestPath);
if (manifest.Contains("\"name\""))
{
var name = System.Text.RegularExpressions.Regex.Match(manifest, "\"name\"\\s*:\\s*\"([^\"]+)\"");
if (name.Success)
extensions.Add($"{browserPath.Key}: {name.Groups[1].Value}");
}
}
catch { }
}
}
}
}
}
catch { }
return extensions;
}
public static void MonitorAndDisableExtensions()
{
// This runs periodically to catch newly installed extensions
DisableAllExtensions();
}
}
// ============================================
// VIDEO DETECTOR - Layer 2: Network Interception
// Detects all movie/video file formats
// ============================================
public static class VideoDetector
{
// Common video file magic bytes/signatures
private static readonly Dictionary<byte[], string> VideoMagicBytes = new Dictionary<byte[], string>
{
{ new byte[] { 0x66, 0x74, 0x79, 0x70 }, "mp4/m4v" }, // ftyp (MP4)
{ new byte[] { 0x52, 0x49, 0x46, 0x46 }, "avi" }, // RIFF (AVI/WAV)
{ new byte[] { 0x1A, 0x45, 0xDF, 0xA3 }, "mkv" }, // MKV header
{ new byte[] { 0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70 }, "mov" }, // MOV
{ new byte[] { 0xFF, 0xD8, 0xFF }, "jpg" }, // JPEG (sometimes in video)
{ new byte[] { 0x47, 0x49, 0x46 }, "gif" }, // GIF
{ new byte[] { 0x50, 0x4B, 0x03, 0x04 }, "flv" }, // FLV (Flash)
{ new byte[] { 0x42, 0x4D }, "bmp" }, // BMP
{ new byte[] { 0x89, 0x50, 0x4E, 0x47 }, "png" } // PNG
};
// Comprehensive list of all video/movie file extensions
private static readonly HashSet<string> VideoExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
// MPEG/MP4 family
".mp4", ".m4v", ".m4a", ".mov", ".3gp", ".3g2", ".mj2", ".ismv", ".isma",
// AVI/RIFF family
".avi", ".divx", ".dv",
// Matroska family
".mkv", ".mka", ".mk3d", ".mks",
// Flash Video
".flv", ".f4v", ".f4a",
// Windows Media
".wmv", ".wma", ".asf",
// Ogg/Vorbis
".ogv", ".ogg", ".oga",
// WebM
".webm",
// MPEG
".mpg", ".mpeg", ".m1v", ".m2v", ".m2p", ".mpa", ".mpe",
// MPEG-TS
".ts", ".mts", ".m2ts", ".m2ts",
// Other video formats
".rm", ".rmvb", ".ra", // RealMedia
".vob", ".ifo", // DVD
".swf", // Shockwave Flash
".qt", // QuickTime
".amv", // AnyVideo
".xpl", ".xpml", // Playlist formats
".mxf", // MXF (professional)
".ivf", // IVF (VP8/VP9)
".flc", ".fli", // Autodesk Animator
".nsv", // NullSoft Video
".roq", // ROQ (game video)
".svi", // Samsung Video
".yuv", // Raw video
".y4m", // Raw YUV4MPEG2
".mvk", ".mlv", // Magic Lantern
".mpl", // MPEG Playlist
".m3u", ".m3u8", // Playlist (often video)
".m4b", // Protected audio (sometimes video)
".asx", ".wvx", ".wax", // Windows playlists
".avs" // AVS Script
};
// Video MIME types
private static readonly HashSet<string> VideoMimeTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"video/mp4", "video/m4v", "video/x-m4v", "audio/mp4", "audio/m4a",
"video/quicktime", "video/x-quicktime",
"video/x-msvideo", "video/avi", "video/x-avi",
"video/x-matroska", "audio/x-matroska",
"video/x-flv", "video/x-flash-video", "application/x-flash-video",
"video/x-ms-wmv", "audio/x-ms-wma", "video/x-ms-asf",
"video/ogg", "application/ogg", "audio/ogg",
"video/webm", "audio/webm",
"video/mpeg", "video/x-mpeg", "audio/mpeg",
"video/mp2t", "video/x-mp2t", "video/x-mpegts",
"application/x-mpegURL", "application/vnd.apple.mpegurl",
"video/x-vnd.rn-realvideo", "audio/x-vnd.rn-realaudio",
"video/x-vobis", "video/dvd",
"application/x-shockwave-flash",
"video/x-raw",
"video/x-dv",
"video/x-mxf",
"video/x-ms-wvx",
"application/x-mplayer2"
};
public static bool IsVideoFile(string url, string contentType, byte[] contentStart)
{
// Check by extension
try
{
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
var path = uri.LocalPath;
var ext = Path.GetExtension(path).ToLower();
if (VideoExtensions.Contains(ext))
return true;
}
catch { }
// Check by content-type header
if (!string.IsNullOrEmpty(contentType))
{
var ct = contentType.ToLower();
foreach (var mimeType in VideoMimeTypes)
{
if (ct.Contains(mimeType) || ct.StartsWith("video/") || ct.StartsWith("audio/"))
return true;
}
}
// Check by magic bytes
if (contentStart != null && contentStart.Length >= 4)
{
foreach (var magic in VideoMagicBytes.Keys)
{
if (contentStart.Length >= magic.Length)
{
bool match = true;
for (int i = 0; i < magic.Length; i++)
{
if (contentStart[i] != magic[i])
{
match = false;
break;
}
}
if (match) return true;
}
}
}
return false;
}
public static bool IsLikelyVideoFile(string url)
{
try
{
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
var path = uri.LocalPath;
var ext = Path.GetExtension(path).ToLower();
return VideoExtensions.Contains(ext);
}
catch { }
return false;
}
public static IEnumerable<string> GetAllBlockedExtensions() => VideoExtensions;
}
// ============================================
// HTTP PROXY SERVER - Layer 2.5: Traffic Interception
// Intercepts HTTP traffic and blocks video downloads
// ============================================
public static class HttpProxyServer
{
private static TcpListener _listener;
private static bool _isRunning;
private static readonly int ProxyPort = 8080;
private static readonly HttpClient _httpClient = new HttpClient(new SocketsHttpHandler
{
AutomaticDecompression = System.Net.DecompressionMethods.All
})
{ Timeout = TimeSpan.FromSeconds(10) };
public static void Start()
{
if (_isRunning) return;
try
{
_listener = new TcpListener(IPAddress.Loopback, ProxyPort);
_listener.Start();
_isRunning = true;
AuditLogger.Log($"HTTP Proxy started on port {ProxyPort} - blocking all video formats");
Task.Run(AcceptClientsAsync);
// Set system proxy
SetSystemProxy($"127.0.0.1:{ProxyPort}");
}
catch (Exception ex)
{
AuditLogger.Log($"Failed to start proxy: {ex.Message}", EventLogEntryType.Error);
}
}
public static void Stop()
{
_isRunning = false;
_listener?.Stop();
_listener = null;
ClearSystemProxy();
AuditLogger.Log("HTTP Proxy stopped");
}
private static async Task AcceptClientsAsync()
{
while (_isRunning)
{
try
{
var client = await _listener.AcceptTcpClientAsync();
_ = HandleClientAsync(client);
}
catch when (!_isRunning) { break; }
catch (Exception ex)
{
AuditLogger.Log($"Proxy error: {ex.Message}", EventLogEntryType.Warning);
}
}
}
private static async Task HandleClientAsync(TcpClient client)
{
try
{
using (client)
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream, Encoding.ASCII))
{
// Read request line
var requestLine = await reader.ReadLineAsync();
if (string.IsNullOrEmpty(requestLine)) return;
var parts = requestLine.Split(' ');
if (parts.Length < 3) return;
var method = parts[0];
var url = parts[1];
var host = "";
// Read headers to get Host
string headerLine;
while ((headerLine = await reader.ReadLineAsync()) != null)
{
if (string.IsNullOrEmpty(headerLine)) break;
if (headerLine.StartsWith("Host: ", StringComparison.OrdinalIgnoreCase))
host = headerLine.Substring(6).Trim();
}
// Construct full URL
if (!url.StartsWith("http"))
url = "http://" + host + url;
// Check if it's a video file
if (VideoDetector.IsLikelyVideoFile(url))
{
// Block the request
var blockMessage = $"HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: 57\r\n\r\nVideo downloads are blocked by Parental Control.";
var response = Encoding.ASCII.GetBytes(blockMessage);
await stream.WriteAsync(response, 0, response.Length);
await stream.FlushAsync();
AuditLogger.LogBlock(url, "Video file download blocked by proxy");
return;
}
// For other requests, forward to destination (CONNECT method for HTTPS)
if (method.Equals("CONNECT", StringComparison.OrdinalIgnoreCase))
{
await HandleHttpsConnectAsync(stream, url);
}
else
{
await ForwardHttpRequestAsync(stream, requestLine, url);
}
}
}
catch { }
}
private static async Task HandleHttpsConnectAsync(NetworkStream stream, string url)
{
try
{
var hostPort = url.Split(':');
var host = hostPort[0];
var port = hostPort.Length > 1 ? int.Parse(hostPort[1]) : 443;
using (var remote = new TcpClient())
{
await remote.ConnectAsync(host, port);
// Send 200 Connection Established
var response = Encoding.ASCII.GetBytes("HTTP/1.1 200 Connection Established\r\n\r\n");
await stream.WriteAsync(response, 0, response.Length);
await stream.FlushAsync();
// Tunnel data (passthrough for HTTPS - can't inspect encrypted content)
var remoteStream = remote.GetStream();
_ = CopyStreamAsync(stream, remoteStream);
_ = CopyStreamAsync(remoteStream, stream);
}
}
catch { }
}
private static async Task ForwardHttpRequestAsync(NetworkStream stream, string requestLine, string url)
{
try
{
var request = new HttpRequestMessage(new HttpMethod(requestLine.Split(' ')[0]), url);
var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);
// Check if response is a video file
var contentType = response.Content.Headers.ContentType?.ToString() ?? "";
var contentLength = response.Content.Headers.ContentLength ?? 0;
if (contentLength > 0)
{
var contentStart = new byte[Math.Min(512, (int)contentLength)];
var content = await response.Content.ReadAsStreamAsync();
await content.ReadAsync(contentStart, 0, contentStart.Length);
if (VideoDetector.IsVideoFile(url, contentType, contentStart))
{
// Block it
var blockResponse = "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: 57\r\n\r\nVideo downloads are blocked by Parental Control.";
var blockBytes = Encoding.ASCII.GetBytes(blockResponse);
await stream.WriteAsync(blockBytes, 0, blockBytes.Length);
AuditLogger.LogBlock(url, "Video file download blocked by proxy (content check)");
return;
}
}
// Forward response
var statusLine = $"HTTP/{response.Version.Major}.{response.Version.Minor} {(int)response.StatusCode} {response.ReasonPhrase}\r\n";
var headerBytes = Encoding.ASCII.GetBytes(statusLine);
await stream.WriteAsync(headerBytes, 0, headerBytes.Length);
foreach (var header in response.Headers)
{
var headerLine = $"{header.Key}: {string.Join(", ", header.Value)}\r\n";
await stream.WriteAsync(Encoding.ASCII.GetBytes(headerLine), 0, headerLine.Length);
}
await stream.WriteAsync(Encoding.ASCII.GetBytes("\r\n"), 0, 2);
await stream.FlushAsync();
await response.Content.CopyToAsync(stream);
}
catch { }
}
private static async Task CopyStreamAsync(NetworkStream source, NetworkStream destination)
{
var buffer = new byte[4096];
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await destination.WriteAsync(buffer, 0, bytesRead);
}
}
private static void SetSystemProxy(string proxy)
{
try
{
var regPath = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings";
Registry.SetValue(regPath, "ProxyServer", proxy);
Registry.SetValue(regPath, "ProxyEnable", 1);
AuditLogger.Log($"System proxy configured: {proxy}");
}
catch { }
}
private static void ClearSystemProxy()
{
try
{
var regPath = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings";
Registry.SetValue(regPath, "ProxyEnable", 0);
}
catch { }
}
}
// ============================================
// DNS ENFORCER - Layer 1 (DISABLED FOR OFFICE USE)
// Kept for compatibility but does not modify DNS
// ============================================
public static class DnsEnforcer
{
public static void EnforceDns()
{
// DNS enforcement disabled for office environment
// Blocking is handled by hosts file + keyword filtering
}
public static bool IsDnsEnforced()
{
return false;
}
}
// ============================================
// VPN / BYPASS PROCESS BLOCKER - Layer 5
// ============================================
public static class ProcessBlocker
{
private static readonly HashSet<string> BlockedProcesses = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
// Browsers that bypass filters
"brave", "brave browser",
"tor", "torbrowser", "firefox-esr",
// VPN clients
"protonvpn", "nordvpn", "expressvpn", "surfshark",
"windscribe", "mullvadvpn", "privatevpn", "ipvanish",
"cyberghost", "purevpn", "hotspotshield", "tunnelbear",
"openvpn", "openvpn-gui",
// Proxy tools
"psiphon", "psiphon3",
"ultrasurf", "freegate",
"lantern",
"i2p", "i2pdesktop",
// Tor-based
"vidalia", "obfs4proxy",
// Generic bypass tools
"shadowsocks", "v2ray", "clash", "xray"
};
public static void KillBlockedProcesses()
{
foreach (var name in BlockedProcesses)
{
try
{
foreach (var proc in Process.GetProcessesByName(name))
{
proc.Kill();
AuditLogger.LogBypassAttempt($"Killed process: {name} (PID {proc.Id})");
}
}
catch { }
}
}
public static IEnumerable<string> GetRunningBlockedProcesses()
{
var running = new List<string>();
foreach (var name in BlockedProcesses)
{
if (Process.GetProcessesByName(name).Any())
running.Add(name);
}
return running;
}
}
// ============================================
// CLOUDFLARE DOMAIN CATEGORIZER - Layer 3
// Checks unknown domains against Cloudflare Radar
// ============================================
public static class CloudflareCategorizer
{
private static readonly HttpClient Http = new HttpClient
{
Timeout = TimeSpan.FromSeconds(3)
};
// Categories Cloudflare assigns to adult/explicit content
private static readonly HashSet<string> BlockedCategories = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Adult Themes", "Nudity", "Pornography", "Sexuality",
"Dating", "Gambling", "Violence", "Weapons",
"Proxy/Anonymizer", "Malware", "Phishing"
};
// Simple in-memory cache so we don't re-query the same domain
private static readonly Dictionary<string, bool> Cache = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private static readonly object CacheLock = new object();
public static async Task<bool> IsDomainBlockedAsync(string domain)
{
lock (CacheLock)
{
if (Cache.TryGetValue(domain, out var cached)) return cached;
}
try
{
// Cloudflare Radar public domain categorization (no API key required)
var url = $"https://radar.cloudflare.com/api/v0/domains/categorization/{Uri.EscapeDataString(domain)}";
var response = await Http.GetStringAsync(url);
using var doc = JsonDocument.Parse(response);
var root = doc.RootElement;
if (root.TryGetProperty("result", out var result) &&
result.TryGetProperty("categories", out var cats))
{
foreach (var cat in cats.EnumerateArray())
{
var catName = cat.GetProperty("name").GetString() ?? "";
if (BlockedCategories.Contains(catName))
{
lock (CacheLock) Cache[domain] = true;
AuditLogger.LogBlock(domain, $"Cloudflare category: {catName}");
return true;
}
}
}
lock (CacheLock) Cache[domain] = false;
return false;
}
catch
{
// If API is unreachable, fail safe (don't block on timeout)
return false;
}
}
}
// ============================================
// BLOCKING ENGINE - Core Logic (upgraded)
// ============================================
public static class BlockingEngine
{
public static readonly HashSet<string> HardcodedBlocks = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
// Major adult sites
"pornhub.com", "www.pornhub.com",
"xvideos.com", "www.xvideos.com",
"xnxx.com", "www.xnxx.com",
"redtube.com", "www.redtube.com",
"youporn.com", "www.youporn.com",
"tube8.com", "www.tube8.com",
"spankbang.com", "www.spankbang.com",
"xhamster.com", "www.xhamster.com",
"beeg.com", "www.beeg.com",
"txxx.com", "www.txxx.com",
"hqporner.com", "www.hqporner.com",
"porntrex.com", "www.porntrex.com",
// Live cam sites
"chaturbate.com", "www.chaturbate.com",
"livejasmin.com", "www.livejasmin.com",
"stripchat.com", "www.stripchat.com",
"cam4.com", "www.cam4.com",
"bongacams.com", "www.bongacams.com",
"myfreecams.com", "www.myfreecams.com",
"streamate.com", "www.streamate.com",
"camsoda.com", "www.camsoda.com",
// Subscription sites
"onlyfans.com", "www.onlyfans.com",
"fansly.com", "www.fansly.com",
// Image/forum sites
"4chan.org", "www.4chan.org", "boards.4chan.org",
"8chan.moe", "www.8chan.moe",
"rule34.xxx", "www.rule34.xxx",
"gelbooru.com", "www.gelbooru.com",
"danbooru.donmai.us",
"e621.net", "www.e621.net",
// Gambling sites
"bet365.com", "www.bet365.com",
"888casino.com", "www.888casino.com",
"pokerstars.com", "www.pokerstars.com",
"draftkings.com", "www.draftkings.com",
"fanduel.com", "www.fanduel.com",
// Gore/shock sites
"bestgore.com", "www.bestgore.com",
"liveleak.com", "www.liveleak.com",
"kaotic.com", "www.kaotic.com",
// Proxy/VPN bypass sites
"hidemyass.com", "www.hidemyass.com",
"kproxy.com", "www.kproxy.com",
"hide.me", "www.hide.me",
"proxysite.com", "www.proxysite.com",
"vpnbook.com", "www.vpnbook.com",
"filterbypass.me", "www.filterbypass.me",
// Torrent sites
"piratebay.org", "www.piratebay.org", "thepiratebay.info", "www.thepiratebay.info",
"1337x.to", "www.1337x.to",
"rarbg.to", "www.rarbg.to",
"kickass.to", "www.kickass.to",
"torrentleech.org", "www.torrentleech.org",
"torrentz.eu", "www.torrentz.eu",
"torrentz2.eu", "www.torrentz2.eu",
"limetorrents.info", "www.limetorrents.info",
"torrentfunk.com", "www.torrentfunk.com",
"torrentkitty.tv", "www.torrentkitty.tv",
"torrenthound.com", "www.torrenthound.com",
"yts.mx", "www.yts.mx",
"torrentgalaxy.to", "www.torrentgalaxy.to",
"isohunt.to", "www.isohunt.to",
"skytorrents.in", "www.skytorrents.in",
"torrentdownload.info", "www.torrentdownload.info",
// DoH endpoints used by Brave/Chrome to bypass DNS filtering
"dns.cloudflare.com",
"dns.google",
"chrome.cloudflare-dns.com",
"doh.opendns.com",
"mozilla.cloudflare-dns.com",
"dns.quad9.net"
};
private static readonly HashSet<string> BlockedKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"porn", "xxx", "sex", "nude", "adult", "cam", "hentai", "nsfw",
"livecam", "webcam", "erotic", "playboy", "hustler", "penthouse",
"brazzers", "bangbros", "naughty", "milf", "escort",
"hookup", "casino", "poker", "slots", "betting",
"gore", "shock", "proxy", "vpn", "unblock", "bypass", "torrent", "piratebay"
};
private static HashSet<string> CustomBlocks = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private static HashSet<string> Whitelist = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private static readonly string DataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"ParentalControl");
private static readonly string CustomBlocksFile;
private static readonly string WhitelistFile;
private static readonly string PasswordFile;
private static string AdminPasswordHash;
static BlockingEngine()
{
CustomBlocksFile = Path.Combine(DataDir, "custom_blocks.txt");
WhitelistFile = Path.Combine(DataDir, "whitelist.txt");
PasswordFile = Path.Combine(DataDir, "admin.pwd");
// Hardcoded admin password - cannot be changed
AdminPasswordHash = HashPassword("n0Zone2017");
LoadCustomBlocks();
LoadWhitelist();
}
public static bool IsBlocked(string domain)
{