Repository navigation
Expand file tree
/
Copy pathIPBanGUI.ps1
More file actions
5427 lines (4888 loc) · 257 KB
/
Copy pathIPBanGUI.ps1
File metadata and controls
5427 lines (4888 loc) · 257 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
param(
[switch]$tray,
[switch]$minimized,
[switch]$show
)
# ==============================================================================
# IPBan Manager & Control Center (GUI)
# Повнофункціональний графічний інтерфейс для керування DigitalRuby IPBan Free
# ==============================================================================
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.Windows.Forms.Application]::EnableVisualStyles()
# ------------------------------------------------------------------------------
# Захист від автозапуску в сторонніх сесіях:
# Видаляємо застарілий глобальний автозапуск із HKLM (залишаємо тільки в HKCU користувача)
# ------------------------------------------------------------------------------
try {
$hklmRun = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
if (Test-Path $hklmRun) {
Remove-ItemProperty -Path $hklmRun -Name "IPBanControlCenter" -ErrorAction SilentlyContinue
}
} catch {}
# ------------------------------------------------------------------------------
# Захист від повторного запуску (Single Instance):
# Якщо програма вже відкрита — активуємо вікно та тихо виходимо
# ------------------------------------------------------------------------------
$script:AppMutex = $null
$mutexCreated = $false
try {
$script:AppMutex = New-Object System.Threading.Mutex($true, "Local\IPBanGUI_ControlCenter_Instance", [ref]$mutexCreated)
if (-not $mutexCreated) {
try {
$user32 = Add-Type -MemberDefinition @'
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
'@ -Name "User32SingleInstance" -Namespace "Win32" -PassThru -ErrorAction SilentlyContinue
if ($user32) {
# 1. Відновлення за збереженим хендлом з реєстру (активує навіть якщо вікно сховане у трей)
try {
$regU = "HKCU:\SOFTWARE\IPBanControlCenter"
if (Test-Path $regU) {
$hVal = (Get-ItemProperty -Path $regU -Name "WindowHandle" -ErrorAction SilentlyContinue).WindowHandle
if ($hVal) {
$savedH = [IntPtr]$hVal
[Win32.User32SingleInstance]::ShowWindow($savedH, 9) | Out-Null
[Win32.User32SingleInstance]::SetForegroundWindow($savedH) | Out-Null
}
}
} catch {}
Get-Process | Where-Object { $_.MainWindowTitle -like "IPBan*Control Center*" -and $_.Id -ne $PID } | ForEach-Object {
[Win32.User32SingleInstance]::ShowWindow($_.MainWindowHandle, 9)
[Win32.User32SingleInstance]::SetForegroundWindow($_.MainWindowHandle)
}
}
} catch {}
exit 0
}
} catch {}
# ------------------------------------------------------------------------------
# Глобальні змінні та стан
# ------------------------------------------------------------------------------
$script:AppVersion = "v2.2.5"
$script:DefaultInstallPath = "C:\Program Files\IPBan"
$script:CurrentInstallPath = $script:DefaultInstallPath
$script:ServiceName = "IPBan"
$script:LocalZipBackup = $null
$script:AppContext = $null
# Визначення режиму запуску (у системний трей за замовчуванням чи у вікно)
$regStartInTray = 1
try {
$regU = "HKCU:\SOFTWARE\IPBanControlCenter"
if (Test-Path $regU) {
$val = (Get-ItemProperty -Path $regU -Name "StartInTray" -ErrorAction SilentlyContinue).StartInTray
if ($null -ne $val) { $regStartInTray = [int]$val }
}
} catch {}
$script:StartInTray = ($tray -or $minimized -or ($regStartInTray -ne 0)) -and (-not $show)
$script:IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$script:AutoRefreshTimer = $null
$script:LastBannedIPs = @()
$script:TrayIcon = $null
$script:TrayMenu = $null
$script:CurrentTrayState = ""
$script:PreviousBannedCount = -1
$script:AlertActive = $false
$script:AlertResetTimer = $null
$script:TrayMonitorTimer = $null
$script:IsExiting = $false
$script:ManualBanTimes = @{}
$script:CurrentBanTimeSetting = "01:00:00:00"
$script:ReportedAbuseIPs = New-Object 'System.Collections.Generic.HashSet[string]'
function Send-AbuseIPDBReport([string]$ip, [string]$comment = "Brute-force attack detected by IPBan") {
try {
$regAbuse = "HKCU:\SOFTWARE\IPBanControlCenter\AbuseIPDB"
if (-not (Test-Path $regAbuse)) { return }
$p = Get-ItemProperty -Path $regAbuse -ErrorAction SilentlyContinue
if (-not $p -or [int]$p.AutoReport -ne 1 -or [string]::IsNullOrWhiteSpace($p.ApiKey)) { return }
if (-not $ip -or $script:ReportedAbuseIPs.Contains($ip)) { return }
[void]$script:ReportedAbuseIPs.Add($ip)
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls13
$headers = @{
"Key" = $p.ApiKey.Trim()
"Accept" = "application/json"
}
$body = @{
ip = $ip
categories = "18,22" # 18: Brute-Force, 22: SSH/RDP/Server exploit
comment = $comment
}
Invoke-RestMethod -Uri "https://api.abuseipdb.com/api/v2/report" -Method Post -Headers $headers -Body $body -TimeoutSec 10 -ErrorAction SilentlyContinue | Out-Null
} catch {}
}
# Підтримка читання бази ipban.sqlite через вбудований у Windows winsqlite3.dll
$script:HasWinSqlite = (Test-Path "$env:windir\System32\winsqlite3.dll")
if ($script:HasWinSqlite -and -not ([System.Management.Automation.PSTypeName]'IPBanSqlite').Type) {
try {
$csSqlite = @'
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
public class IPBanSqlite {
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_open16", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern int sqlite3_open16(string filename, out IntPtr db);
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_prepare16_v2", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern int sqlite3_prepare16_v2(IntPtr db, string zSql, int nByte, out IntPtr ppStmt, IntPtr pzTail);
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_step", CallingConvention = CallingConvention.Cdecl)]
private static extern int sqlite3_step(IntPtr pStmt);
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_column_text16", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr sqlite3_column_text16(IntPtr pStmt, int iCol);
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_column_int64", CallingConvention = CallingConvention.Cdecl)]
private static extern long sqlite3_column_int64(IntPtr pStmt, int iCol);
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_finalize", CallingConvention = CallingConvention.Cdecl)]
private static extern int sqlite3_finalize(IntPtr pStmt);
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_close", CallingConvention = CallingConvention.Cdecl)]
private static extern int sqlite3_close(IntPtr db);
[DllImport("winsqlite3.dll", EntryPoint = "sqlite3_busy_timeout", CallingConvention = CallingConvention.Cdecl)]
private static extern int sqlite3_busy_timeout(IntPtr db, int ms);
private const int SQLITE_ROW = 100;
private const int SQLITE_OK = 0;
public static Dictionary<string, long[]> ReadBanDates(string dbPath) {
var dict = new Dictionary<string, long[]>(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(dbPath) || !System.IO.File.Exists(dbPath)) return dict;
IntPtr db = IntPtr.Zero;
if (sqlite3_open16(dbPath, out db) != SQLITE_OK || db == IntPtr.Zero) return dict;
try {
sqlite3_busy_timeout(db, 2000);
IntPtr stmt = IntPtr.Zero;
string sql = "SELECT IPAddressText, BanDate, BanEndDate FROM IPAddresses WHERE BanDate IS NOT NULL AND BanDate > 0";
int rc = sqlite3_prepare16_v2(db, sql, -1, out stmt, IntPtr.Zero);
if (rc != SQLITE_OK || stmt == IntPtr.Zero) {
sql = "SELECT IPAddressText, BanDate, 0 FROM IPAddresses WHERE BanDate IS NOT NULL AND BanDate > 0";
rc = sqlite3_prepare16_v2(db, sql, -1, out stmt, IntPtr.Zero);
}
if (rc == SQLITE_OK && stmt != IntPtr.Zero) {
try {
while (sqlite3_step(stmt) == SQLITE_ROW) {
IntPtr ptr = sqlite3_column_text16(stmt, 0);
string ip = Marshal.PtrToStringUni(ptr);
long banDate = sqlite3_column_int64(stmt, 1);
long banEndDate = sqlite3_column_int64(stmt, 2);
if (!string.IsNullOrEmpty(ip)) {
dict[ip] = new long[] { banDate, banEndDate };
}
}
} finally {
sqlite3_finalize(stmt);
}
}
} catch {}
finally {
sqlite3_close(db);
}
return dict;
}
}
'@
Add-Type -TypeDefinition $csSqlite -ErrorAction SilentlyContinue
} catch {}
}
# ------------------------------------------------------------------------------
# Локалізація (Multi-Language: UA / EN)
# ------------------------------------------------------------------------------
$script:I18N = @{
"UA" = @{
"AppTitle" = "IPBan Manager & Control Center"
"HeaderTitle" = "IPBan Control Center"
"HeaderSubtitle" = "Автоматичний захист від Brute-Force атак (RDP, SSH, SQL)"
"StatusChecking" = "Перевірка..."
"StatusRunning" = "ЗАПУЩЕНО"
"StatusStopped" = "ЗУПИНЕНО"
"StatusNotInstalled" = "НЕ ВСТАНОВЛЕНО"
"BtnStart" = "Запустити"
"BtnStop" = "Зупинити"
"BtnRestart" = "Рестарт"
"BtnRefresh" = "Оновити"
"LangToggle" = "English"
"PathLabel" = "Папка IPBan:"
"BtnBrowse" = "Огляд..."
"BtnOpenFolder" = "Відкрити папку"
"BtnOpenConfig" = "Відкрити конфіг"
"TabBanned" = " Заблоковані IP "
"TabStats" = " 📊 Статистика "
"TabSettings" = " Налаштування "
"TabLists" = " Білий / Чорний списки "
"TabLogs" = " Журнал та аудит "
"TabSetup" = " Інсталяція та Сервіс "
"Search" = "Пошук:"
"Filter" = "Фільтр:"
"FilterBanned" = "⛔ Тільки локальні блокування"
"FilterWhitelist" = "⚪ Тільки білий список"
"FilterBlacklist" = "🏴 Чорний список (Blacklist)"
"FilterAllRules" = "📋 Всі правила IPBan"
"BtnUnbanSelected" = "Розблокувати обрані"
"BtnManualBan" = "Заблокувати вручну..."
"BtnUnbanAll" = "Очистити блокування"
"BtnExport" = "Експорт..."
"ColIndex" = "#"
"ColIP" = "IP-адреса (Whois)"
"ColCountry" = "Країна"
"ColBanTime" = "Час блокування"
"ColUnbanTime" = "Час розблокування"
"BanPermanent" = "— (Назавжди)"
"BanActive" = "Активне"
"BanTimeUnknown" = "— (Час не зафіксовано)"
"BanPerConfig" = "За конфігом"
"WhitelistNote" = "— (Білий список)"
"BlacklistNote" = "— (Чорний список)"
"CardTotalBanned" = "Локально заблоковано"
"CardUniqueCountries" = "Країн-джерел атак"
"CardTopCountry" = "Головна країна атак"
"CardPeakHour" = "Піковий час атак"
"GbCountryStats" = "Топ країн за локальними атаками"
"GbTimeStats" = "Розподіл локальних атак за часом доби (24 години)"
"ColStatsRank" = "#"
"ColStatsCountry" = "Країна"
"ColStatsCount" = "Заблоковано IP"
"ColStatsShare" = "Частка"
"ColStatsBar" = "Активність"
"ColHour" = "Часовий проміжок"
"ColHourAttacks" = "Кількість подій"
"ColHourBar" = "Рівень активності"
"BtnRefreshStats" = "Оновити статистику"
"PeakNotice" = "[!] Пік локальних атак: {0}:00 - {1}:00 ({2} спроб)"
"NoActiveBans" = "Локальних блокувань немає"
"ResolvingCountry" = "🌐 Визначення..."
"LocalNetwork" = "Локальна мережа"
"UnknownCountry" = "Невідомо"
"StatusActive" = "🟢 Активно"
"StatusDisabled" = "⚪ Вимкнено"
"LblNoBans" = "🟢 Локальних блокувань немає (0 IP-адрес) | Білий список: {0} | Чорний список: {1}"
"LblBansCount" = "⛔ Локально заблоковано: {0} IP (Відображено: {1}) | Чорний список: {2} | Білий список: {3}"
"LblWhiteCount" = "⚪ У білому списку брандмауера: {0} IP (Відображено: {1}) | Локально заблоковано: {2}"
"LblBlackCount" = "🏴 У чорному списку (Blacklist): {0} IP (Відображено: {1}) | Локально заблоковано: {2}"
"LblAllRulesCount" = "📋 Всього записів IPBan у брандмауері: {0} | Відображено: {1}"
"GbGeneral" = "Правила виявлення та блокування"
"LblFailedAttempts" = "Поріг невдалих спроб входу (FailedLoginAttemptsBeforeBan):"
"LblBanTime" = "Час блокування (BanTime, формат Дні:Год:Хв:Сек):"
"LblExpireTime" = "Час життя невдалих спроб до скидання (ExpireTime):"
"LblCycleTime" = "Інтервал циклу перевірки та бану (CycleTime):"
"GbBehavior" = "Додаткова поведінка та очищення"
"ChkClearOnRestart" = "Очищати всі заблоковані IP при перезапуску служби (ClearBannedIPAddressesOnRestart)"
"ChkClearOnSuccess" = "Скидати лічильник невдалих спроб при успішному вході (ClearFailedLoginsOnSuccessfulLogin)"
"ChkProcessInternal" = "Обробляти та блокувати внутрішні локальні IP-адреси (ProcessInternalIPAddresses)"
"ChkResetUnbanned" = "Скидати лічильник після розблокування IP (ResetFailedLoginCountForUnbannedIPAddresses)"
"ChkStartInTray" = "Запускати програму згорнутою у системний трей (Start in tray)"
"GbMonitoring" = "Моніторинг сервісів та протоколів (Event Viewer & Logs)"
"LblMonitoringDesc" = "Контроль та виявлення атак на сервіси Windows за конфігурацією IPBan:"
"StatusEnabled" = "Включено"
"StatusDisabledService" = "Вимкнено"
"GbAbuseIPDB" = "Хмарна база загроз AbuseIPDB (Threat Intelligence)"
"LblAbuseApiKey" = "API Ключ AbuseIPDB (Key):"
"LblAbuseConfidence" = "Поріг впевненості (Confidence Score, %):"
"LblAbuseLimit" = "Кількість IP для завантаження (Limit):"
"ChkAbuseAutoReport" = "Автоматично надсилати репорти про атаки в AbuseIPDB (за замовчуванням: ВИМКНЕНО)"
"BtnFetchAbuse" = "📥 Завантажити чорний список з AbuseIPDB"
"BtnCheckUpdate" = "Перевірити оновлення"
"UpdateChecking" = "Перевірка нових версій на GitHub..."
"UpdateLatest" = "У вас встановлена найновіша версія ({0}). Оновлень немає."
"UpdateAvailableTitle" = "Доступна нова версія {0}!"
"UpdateAvailableMsg" = "Вийшла нова версія IPBan Control Center: {0}`n`nПоточна версія: {1}`n`nБажаєте відкрити сторінку релізу та завантажити оновлення зараз?"
"BtnSaveConfig" = "Зберегти налаштування у файл"
"BtnReloadConfig" = "Скинути до значень файлу"
"BtnRestoreBak" = "Відновити з бекапу (.bak)"
"GbWhitelist" = "Білий список (Whitelist - ніколи не блокувати)"
"LblWhiteDesc" = "Введіть IP-адреси або підмережі CIDR через кому або з нового рядка:"
"BtnAddLocalIP" = "+ Додати мою локальну IP"
"BtnAddPublicIP" = "+ Додати мою зовнішню WAN IP"
"GbBlacklist" = "Чорний список (Blacklist - перманентно блокувати)"
"LblBlackDesc" = "Введіть IP-адреси або підмережі CIDR для постійного блокування:"
"BtnSaveLists" = "Зберегти Білий та Чорний списки у конфігурацію"
"RbIPBanLog" = "Лог IPBan (logfile.txt)"
"RbEventLog" = "Спроби входу Windows (Security 4625)"
"BtnRefreshLog" = "Оновити журнал"
"ChkAutoRefresh" = "Авто (кожні 5 сек)"
"BtnClearLog" = "Очистити logfile.txt"
"ChkWordWrap" = "Перенос рядків"
"ColTime" = "Час"
"ColUser" = "Користувач"
"ColLogonType" = "Тип входу"
"ColWorkstation" = "Робоча станція"
"ColStatus" = "Статус"
"MiCopyIP" = "Копіювати IP"
"MiUnban" = "Розблокувати"
"MiWhitelist" = "Додати до Білого списку (Whitelist)"
"MiEventBan" = "Заблокувати цей IP"
"MiEventWhite" = "Додати цей IP до Whitelist"
"MiEventCopy" = "Копіювати IP-адресу"
"GbSysStatus" = "Стан компонентів системи"
"BtnBrowseZip" = "Обрати ZIP-архів..."
"GbInstallActions" = "Керування встановленням та налаштуванням"
"BtnSetupAudit" = "Увімкнути аудит безпеки Windows (AuditPol)"
"LblAuditHint" = "(Обов'язково для виявлення невдалих спроб входу RDP/Windows)"
"BtnInstallLocal" = "Встановити IPBan з локального архіву"
"BtnInstallWeb" = "Завантажити та встановити найновішу з GitHub"
"BtnUninstallService" = "Повністю видалити службу IPBan"
"GbLinks" = "Корисні посилання та документація"
"LlGithub" = "Офіційний репозиторій DigitalRuby/IPBan на GitHub"
"LlWiki" = "Документація налаштувань та конфігурації (Wiki)"
"StatusReady" = "Готово"
"AdminYes" = "Адміністратор"
"AdminNo" = "Без прав адміністратора"
"TrayTitle" = "🛡 IPBan Control Center"
"TrayStatusChecking" = "Статус: Перевірка..."
"TrayBannedCount" = "Заблоковано IP: {0}"
"TrayStart" = "▶ Запустити службу"
"TrayStop" = "⏹ Зупинити службу"
"TrayRestart" = "🔄 Перезапустити службу"
"TrayRefresh" = "📋 Оновити дані"
"TrayShow" = "🪟 Відкрити вікно програми"
"TrayExit" = "❌ Вихід з програми"
"SvcRunning" = "Служба Windows (IPBan): Працює (Running)"
"SvcStopped" = "Служба Windows (IPBan): Зупинена (Stopped)"
"SvcNotInstalled" = "Служба Windows (IPBan): Не знайдена в системі"
"PromptInstallTitle" = "Майстер налаштувань IPBan"
"PromptInstallText" = "Службу захисту IPBan ще не встановлено на цьому комп'ютері.`n`nВідкрито розділ «Інсталяція та Сервіс».`nДля захисту сервера від підбору паролів (RDP, SSH, SMB тощо) необхідно встановити службу IPBan.`n`nБажаєте завантажити та встановити найновішу версію IPBan прямо зараз з офіційного GitHub?"
"StatusLogUpdated" = "Лог IPBan оновлено ({0} останніх рядків)"
"StatusPollingEvents" = "Опитування журналу безпеки Windows (Event 4625)..."
"StatusEventsLoaded" = "Отримано невдалих спроб входу: {0}"
"StatusEventsError" = "Помилка читання журналу подій: {0}"
"LogReadError" = "Не вдалося прочитати лог-файл: {0}"
"LogNotFound" = "Файл логу не знайдено за шляхом: {0}`n`nЛоги з'являться після запуску служби IPBan."
"StatusServiceRestarting" = "Перезапуск служби IPBan..."
"StatusServiceRestarted" = "Службу IPBan успішно перезапущено!"
"StatusServiceRestartError" = "Помилка перезапуску служби"
"StatusServiceStarting" = "Запуск служби IPBan..."
"StatusServiceStarted" = "Службу IPBan запущено!"
"StatusServiceStopping" = "Зупинка служби IPBan..."
"StatusServiceStopped" = "Службу IPBan зупинено!"
"StatusLogCleared" = "Лог-файл успішно очищено"
"StatusAuditConfiguring" = "Налаштування Windows Audit Policy..."
"StatusGettingPublicIP" = "Отримання зовнішньої публічної IP-адреси..."
"StatusAbuseDownloaded" = "AbuseIPDB: Завантажено {0} шкідливих IP-адрес"
"StatusConfigSaved" = "Налаштування успішно збережено у {0}"
"StatusConfigLoaded" = "Налаштування завантажено з {0}"
"StatusConfigNotFound" = "Файл конфігурації не знайдено: {0}"
"StatusInstallLocal" = "Встановлення IPBan з локального архіву..."
"StatusInstallWeb" = "Завантаження та встановлення IPBan з GitHub..."
"StatusRulesLoading" = "Завантаження правил брандмауера IPBan..."
"StatusRulesRefreshed" = "Правила оновлено. Локальних блокувань: {0} | Білий список: {1} | Чорний список: {2}"
}
"EN" = @{
"AppTitle" = "IPBan Manager & Control Center"
"HeaderTitle" = "IPBan Control Center"
"HeaderSubtitle" = "Automated Brute-Force Attack Protection (RDP, SSH, SQL)"
"StatusChecking" = "Checking..."
"StatusRunning" = "RUNNING"
"StatusStopped" = "STOPPED"
"StatusNotInstalled" = "NOT INSTALLED"
"BtnStart" = "Start"
"BtnStop" = "Stop"
"BtnRestart" = "Restart"
"BtnRefresh" = "Refresh"
"LangToggle" = "Українська"
"PathLabel" = "IPBan Folder:"
"BtnBrowse" = "Browse..."
"BtnOpenFolder" = "Open Folder"
"BtnOpenConfig" = "Open Config"
"TabBanned" = " Banned IPs "
"TabStats" = " 📊 Analytics "
"TabSettings" = " Settings "
"TabLists" = " White / Black Lists "
"TabLogs" = " Logs & Audit "
"TabSetup" = " Installation & Service "
"Search" = "Search:"
"Filter" = "Filter:"
"FilterBanned" = "⛔ Local Bans Only"
"FilterWhitelist" = "⚪ Whitelist Only"
"FilterBlacklist" = "🏴 Blacklist Only"
"FilterAllRules" = "📋 All IPBan Rules"
"BtnUnbanSelected" = "Unban Selected"
"BtnManualBan" = "Manual Ban..."
"BtnUnbanAll" = "Clear Local Bans"
"BtnExport" = "Export..."
"ColIndex" = "#"
"ColIP" = "IP Address (Whois)"
"ColCountry" = "Country"
"ColBanTime" = "Ban Date & Time"
"ColUnbanTime" = "Unban Date & Time"
"BanPermanent" = "— (Permanent)"
"BanActive" = "Active"
"BanTimeUnknown" = "— (Time not recorded)"
"BanPerConfig" = "Per config"
"WhitelistNote" = "— (Whitelist)"
"BlacklistNote" = "— (Blacklist)"
"CardTotalBanned" = "Locally Blocked IPs"
"CardUniqueCountries" = "Unique Countries"
"CardTopCountry" = "Top Attack Country"
"CardPeakHour" = "Peak Attack Hours"
"GbCountryStats" = "Top Attacking Countries (Local)"
"GbTimeStats" = "24-Hour Local Attack Distribution"
"ColStatsRank" = "#"
"ColStatsCountry" = "Country"
"ColStatsCount" = "Blocked IPs"
"ColStatsShare" = "Share"
"ColStatsBar" = "Activity"
"ColHour" = "Time Window"
"ColHourAttacks" = "Event Count"
"ColHourBar" = "Activity Level"
"BtnRefreshStats" = "Refresh Analytics"
"PeakNotice" = "[!] Peak local attacks: {0}:00 - {1}:00 ({2} attempts)"
"NoActiveBans" = "No local bans"
"ResolvingCountry" = "🌐 Resolving..."
"LocalNetwork" = "Local Network"
"UnknownCountry" = "Unknown"
"StatusActive" = "🟢 Active"
"StatusDisabled" = "⚪ Disabled"
"LblNoBans" = "🟢 No local bans (0 IP addresses) | Whitelist: {0} | Blacklist: {1}"
"LblBansCount" = "⛔ Locally blocked: {0} IPs (Showing: {1}) | Blacklist: {2} | Whitelist: {3}"
"LblWhiteCount" = "⚪ Firewall whitelist: {0} IPs (Showing: {1}) | Locally blocked: {2}"
"LblBlackCount" = "🏴 Firewall blacklist: {0} IPs (Showing: {1}) | Locally blocked: {2}"
"LblAllRulesCount" = "📋 Total IPBan records in firewall: {0} | Showing: {1}"
"GbGeneral" = "Detection and Blocking Rules"
"LblFailedAttempts" = "Failed login attempts threshold (FailedLoginAttemptsBeforeBan):"
"LblBanTime" = "Ban duration (BanTime, format Days:Hours:Min:Sec):"
"LblExpireTime" = "Failed attempt expiration window (ExpireTime):"
"LblCycleTime" = "Cycle checking interval (CycleTime):"
"GbBehavior" = "Additional Behavior and Cleanup"
"ChkClearOnRestart" = "Clear all banned IPs on service restart (ClearBannedIPAddressesOnRestart)"
"ChkClearOnSuccess" = "Reset failed attempts counter on successful login (ClearFailedLoginsOnSuccessfulLogin)"
"ChkProcessInternal" = "Process and ban internal/local IP addresses (ProcessInternalIPAddresses)"
"ChkResetUnbanned" = "Reset counter after unbanning an IP (ResetFailedLoginCountForUnbannedIPAddresses)"
"ChkStartInTray" = "Start application minimized to system tray"
"GbMonitoring" = "Service & Protocol Monitoring (Event Viewer & Logs)"
"LblMonitoringDesc" = "Detection and attack prevention across Windows services per IPBan config:"
"StatusEnabled" = "Enabled"
"StatusDisabledService" = "Disabled"
"GbAbuseIPDB" = "AbuseIPDB Cloud Threat Intelligence"
"LblAbuseApiKey" = "AbuseIPDB API Key:"
"LblAbuseConfidence" = "Confidence Score (%):"
"LblAbuseLimit" = "Download IP Limit:"
"ChkAbuseAutoReport" = "Automatically report attack attempts to AbuseIPDB (Default: DISABLED)"
"BtnFetchAbuse" = "📥 Download Blacklist from AbuseIPDB"
"BtnCheckUpdate" = "Check for Updates"
"UpdateChecking" = "Checking for new versions on GitHub..."
"UpdateLatest" = "You have the latest version ({0}). No updates available."
"UpdateAvailableTitle" = "New version {0} is available!"
"UpdateAvailableMsg" = "A newer version of IPBan Control Center is available: {0}`n`nCurrent version: {1}`n`nWould you like to open the release page and download the update now?"
"BtnSaveConfig" = "Save Settings to File"
"BtnReloadConfig" = "Reset to File Values"
"BtnRestoreBak" = "Restore from Backup (.bak)"
"GbWhitelist" = "Whitelist (Never ban these addresses)"
"LblWhiteDesc" = "Enter IP addresses or CIDR subnets separated by comma or new lines:"
"BtnAddLocalIP" = "+ Add My Local IP"
"BtnAddPublicIP" = "+ Add My Public WAN IP"
"GbBlacklist" = "Blacklist (Permanently block these addresses)"
"LblBlackDesc" = "Enter IP addresses or CIDR subnets to permanently block:"
"BtnSaveLists" = "Save Whitelist & Blacklist to Configuration"
"RbIPBanLog" = "IPBan Log (logfile.txt)"
"RbEventLog" = "Windows Logon Attempts (Security 4625)"
"BtnRefreshLog" = "Refresh Log"
"ChkAutoRefresh" = "Auto (every 5 sec)"
"BtnClearLog" = "Clear logfile.txt"
"ChkWordWrap" = "Word Wrap"
"ColTime" = "Time"
"ColUser" = "User"
"ColLogonType" = "Logon Type"
"ColWorkstation" = "Workstation"
"ColStatus" = "Status"
"MiCopyIP" = "Copy IP"
"MiUnban" = "Unban"
"MiWhitelist" = "Add to Whitelist"
"MiEventBan" = "Ban This IP"
"MiEventWhite" = "Add This IP to Whitelist"
"MiEventCopy" = "Copy IP Address"
"GbSysStatus" = "System Components Status"
"BtnBrowseZip" = "Choose ZIP Archive..."
"GbInstallActions" = "Installation and Maintenance Controls"
"BtnSetupAudit" = "Enable Windows Security Audit (AuditPol)"
"LblAuditHint" = "(Required to detect failed RDP/Windows login attempts)"
"BtnInstallLocal" = "Install IPBan from Local Archive"
"BtnInstallWeb" = "Download and Install Latest from GitHub"
"BtnUninstallService" = "Completely Remove IPBan Service"
"GbLinks" = "Useful Links & Documentation"
"LlGithub" = "Official DigitalRuby/IPBan Repository on GitHub"
"LlWiki" = "Configuration and Settings Documentation (Wiki)"
"StatusReady" = "Ready"
"AdminYes" = "Administrator"
"AdminNo" = "Standard User (Non-Admin)"
"TrayTitle" = "🛡 IPBan Control Center"
"TrayStatusChecking" = "Status: Checking..."
"TrayBannedCount" = "Banned IPs: {0}"
"TrayStart" = "▶ Start Service"
"TrayStop" = "⏹ Stop Service"
"TrayRestart" = "🔄 Restart Service"
"TrayRefresh" = "📋 Refresh Data"
"TrayShow" = "🪟 Open Control Center"
"TrayExit" = "❌ Exit Application"
"SvcRunning" = "Windows Service (IPBan): Running"
"SvcStopped" = "Windows Service (IPBan): Stopped"
"SvcNotInstalled" = "Windows Service (IPBan): Not found in system"
"PromptInstallTitle" = "IPBan Setup Wizard"
"PromptInstallText" = "The IPBan protection service is not yet installed on this computer.`n`nOpened the 'Installation & Service' section.`nTo protect this server from brute-force password attacks (RDP, SSH, SMB, etc.), the IPBan service must be installed.`n`nWould you like to download and install the latest IPBan release from GitHub right now?"
"StatusLogUpdated" = "IPBan log updated (last {0} lines)"
"StatusPollingEvents" = "Querying Windows Security log (Event 4625)..."
"StatusEventsLoaded" = "Received failed login attempts: {0}"
"StatusEventsError" = "Error reading event log: {0}"
"LogReadError" = "Failed to read log file: {0}"
"LogNotFound" = "Log file not found at: {0}`n`nLogs will appear after starting IPBan service."
"StatusServiceRestarting" = "Restarting IPBan service..."
"StatusServiceRestarted" = "IPBan service successfully restarted!"
"StatusServiceRestartError" = "Failed to restart IPBan service"
"StatusServiceStarting" = "Starting IPBan service..."
"StatusServiceStarted" = "IPBan service started!"
"StatusServiceStopping" = "Stopping IPBan service..."
"StatusServiceStopped" = "IPBan service stopped!"
"StatusLogCleared" = "Log file successfully cleared"
"StatusAuditConfiguring" = "Configuring Windows Audit Policy..."
"StatusGettingPublicIP" = "Retrieving external public IP address..."
"StatusAbuseDownloaded" = "AbuseIPDB: Downloaded {0} malicious IP addresses"
"StatusConfigSaved" = "Settings successfully saved to {0}"
"StatusConfigLoaded" = "Settings loaded from {0}"
"StatusConfigNotFound" = "Configuration file not found: {0}"
"StatusInstallLocal" = "Installing IPBan from local archive..."
"StatusInstallWeb" = "Downloading and installing IPBan from GitHub..."
"StatusRulesLoading" = "Loading IPBan firewall rules..."
"StatusRulesRefreshed" = "Rules refreshed. Local bans: {0} | Whitelist: {1} | Blacklist: {2}"
}
}
# Визначення поточної мови (реєстр або культура ОС)
$regKeyLang = "HKCU:\Software\IPBanControlCenter"
$savedLang = $null
try {
if (Test-Path $regKeyLang) {
$savedLang = (Get-ItemProperty -Path $regKeyLang -Name "Language" -ErrorAction SilentlyContinue).Language
}
} catch {}
if ($savedLang -in @("UA", "EN")) {
$script:CurrentLang = $savedLang
} else {
$uiCulture = [System.Globalization.CultureInfo]::CurrentUICulture.TwoLetterISOLanguageName.ToLower()
if ($uiCulture -in @("uk", "ru", "be")) {
$script:CurrentLang = "UA"
} else {
$script:CurrentLang = "EN"
}
}
function T([string]$key) {
if ($script:I18N[$script:CurrentLang].ContainsKey($key)) {
return $script:I18N[$script:CurrentLang][$key]
}
if ($script:I18N["EN"].ContainsKey($key)) {
return $script:I18N["EN"][$key]
}
return $key
}
# Підключення P/Invoke для коректного вивільнення дескрипторів іконок
if (-not ([System.Management.Automation.PSTypeName]'NativeMethods').Type) {
$nativeCode = @"
using System;
using System.Runtime.InteropServices;
public class NativeMethods {
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool DestroyIcon(IntPtr handle);
}
"@
Add-Type -TypeDefinition $nativeCode -ErrorAction SilentlyContinue
}
# Генератор динамічних іконок для системного трею (Працює, Не працює, Алерт)
function Get-AppTrayIcon([string]$state) {
$bmp = New-Object System.Drawing.Bitmap 32, 32
$g = [System.Drawing.Graphics]::FromImage($bmp)
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
$g.Clear([System.Drawing.Color]::Transparent)
$rect = New-Object System.Drawing.Rectangle 1, 1, 29, 29
switch ($state) {
"Running" {
# 🟢 Працює: Зелений щит/коло з білою галочкою
$brush = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(22, 163, 74))
$g.FillEllipse($brush, $rect)
$brush.Dispose()
$pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::White, 3.5)
$pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
$pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
$g.DrawLine($pen, 8, 16, 13, 21)
$g.DrawLine($pen, 13, 21, 23, 10)
$pen.Dispose()
}
"Alert" {
# 🟠 Алерт: Помаранчевий/бурштиновий з білим знаком оклику (!)
$brush = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(234, 88, 12))
$g.FillEllipse($brush, $rect)
$brush.Dispose()
$pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::White, 3.5)
$pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
$pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
$g.DrawLine($pen, 15, 7, 15, 17)
$pen.Dispose()
$brushWhite = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::White)
$g.FillEllipse($brushWhite, 13, 21, 5, 5)
$brushWhite.Dispose()
}
default {
# 🔴 Не працює: Червоне коло з білим хрестиком (X)
$brush = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(220, 38, 38))
$g.FillEllipse($brush, $rect)
$brush.Dispose()
$pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::White, 3.5)
$pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
$pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
$g.DrawLine($pen, 9, 9, 21, 21)
$g.DrawLine($pen, 21, 9, 9, 21)
$pen.Dispose()
}
}
$g.Dispose()
$hIcon = $bmp.GetHicon()
$ico = [System.Drawing.Icon]::FromHandle($hIcon)
$clone = $ico.Clone()
$ico.Dispose()
[NativeMethods]::DestroyIcon($hIcon) | Out-Null
$bmp.Dispose()
return $clone
}
function Enable-DoubleBuffering($control) {
if (-not $control) { return }
try {
$prop = [System.Windows.Forms.Control].GetProperty("DoubleBuffered", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance)
if ($prop) { $prop.SetValue($control, $true, $null) }
} catch {}
}
# Допоміжна функція створення згладжених кнопок та бейджів (Rounded Buttons)
function Set-SmoothButton {
param(
[Parameter(Mandatory=$true)]
[System.Windows.Forms.Control]$control,
[int]$radius = 7,
[System.Drawing.Color]$borderColor = [System.Drawing.Color]::Empty
)
if ($control -is [System.Windows.Forms.ButtonBase]) {
$control.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat
$control.FlatAppearance.BorderSize = 0
$control.Cursor = [System.Windows.Forms.Cursors]::Hand
}
$rVal = if ($radius -gt 0) { $radius } else { 7 }
$bColorVal = $borderColor
$updateRegion = {
param($s, $e)
try {
$curR = if ($rVal -gt 0) { $rVal } else { 7 }
$d = [int]($curR * 2)
if ($s -and $s.Width -gt $d -and $s.Height -gt $d) {
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
$r = $s.ClientRectangle
if ($r.Width -gt $d -and $r.Height -gt $d) {
$path.AddArc($r.X, $r.Y, $d, $d, 180, 90)
$path.AddArc(($r.Right - $d), $r.Y, $d, $d, 270, 90)
$path.AddArc(($r.Right - $d), ($r.Bottom - $d), $d, $d, 0, 90)
$path.AddArc($r.X, ($r.Bottom - $d), $d, $d, 90, 90)
$path.CloseFigure()
$s.Region = New-Object System.Drawing.Region($path)
}
$path.Dispose()
}
} catch {}
}.GetNewClosure()
$control.Add_Resize($updateRegion)
& $updateRegion $control $null
if (-not $bColorVal.IsEmpty) {
$paintBorder = {
param($s, $e)
try {
$curR = if ($rVal -gt 0) { $rVal } else { 7 }
$d = [int]($curR * 2)
if ($s -and $s.Width -gt $d -and $s.Height -gt $d) {
$e.Graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
$r = New-Object System.Drawing.Rectangle 0, 0, ($s.Width - 1), ($s.Height - 1)
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
$path.AddArc($r.X, $r.Y, $d, $d, 180, 90)
$path.AddArc(($r.Right - $d), $r.Y, $d, $d, 270, 90)
$path.AddArc(($r.Right - $d), ($r.Bottom - $d), $d, $d, 0, 90)
$path.AddArc($r.X, ($r.Bottom - $d), $d, $d, 90, 90)
$path.CloseFigure()
$pen = New-Object System.Drawing.Pen($bColorVal, 1)
$e.Graphics.DrawPath($pen, $path)
$pen.Dispose()
$path.Dispose()
}
} catch {}
}.GetNewClosure()
$control.Add_Paint($paintBorder)
}
}
function Find-LocalIPBanZip {
if ($script:LocalZipBackup -and (Test-Path $script:LocalZipBackup)) {
return $script:LocalZipBackup
}
$candidates = @(
$PSScriptRoot,
(Get-Location).Path,
[System.IO.Path]::Combine($env:USERPROFILE, "Downloads"),
"C:\Downloads",
"C:\Temp",
"C:\"
)
if (Test-Path "D:\") {
$candidates += @("D:\Downloads", "D:\Temp", "D:\")
}
foreach ($dir in $candidates) {
if ($dir -and (Test-Path $dir)) {
$zip = Get-ChildItem -Path $dir -Filter "*IPBan*.zip" -File -ErrorAction SilentlyContinue | Select-Object -First 1
if ($zip) {
return $zip.FullName
}
}
}
return $null
}
function Get-IPBanPath {
if ($txtInstallPath -and -not [string]::IsNullOrWhiteSpace($txtInstallPath.Text)) {
$p = $txtInstallPath.Text.Trim()
if (Test-Path "$p\DigitalRuby.IPBan.exe") {
$script:CurrentInstallPath = $p
return $p
}
}
if (Test-Path "$script:CurrentInstallPath\DigitalRuby.IPBan.exe") {
return $script:CurrentInstallPath
}
if (Test-Path "C:\Program Files\IPBan\DigitalRuby.IPBan.exe") {
$script:CurrentInstallPath = "C:\Program Files\IPBan"
return $script:CurrentInstallPath
}
if (Test-Path "C:\IPBan\DigitalRuby.IPBan.exe") {
$script:CurrentInstallPath = "C:\IPBan"
return $script:CurrentInstallPath
}
if ($txtInstallPath -and -not [string]::IsNullOrWhiteSpace($txtInstallPath.Text)) {
return $txtInstallPath.Text.Trim()
}
return $script:CurrentInstallPath
}
function Get-IPBanConfigFile {
$path = Get-IPBanPath
if (Test-Path "$path\ipban.config") {
return "$path\ipban.config"
}
if (Test-Path "$path\ipban.override.config") {
return "$path\ipban.override.config"
}
return "$path\ipban.config"
}
function Get-IPBanServiceStatus {
try {
$svc = Get-Service -Name $script:ServiceName -ErrorAction SilentlyContinue
if ($null -eq $svc) { return "NotInstalled" }
return $svc.Status.ToString()
} catch {
return "NotInstalled"
}
}
function Expand-ZipArchiveSafe {
param(
[Parameter(Mandatory=$true)]
[string]$zipPath,
[Parameter(Mandatory=$true)]
[string]$destDir
)
if (-not (Test-Path $destDir)) {
New-Item -ItemType Directory -Path $destDir -Force | Out-Null
}
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archive = [System.IO.Compression.ZipFile]::OpenRead($zipPath)
try {
foreach ($entry in $archive.Entries) {
$destFile = [System.IO.Path]::Combine($destDir, $entry.FullName)
if ($entry.FullName.EndsWith("/") -or $entry.FullName.EndsWith("\")) {
if (-not (Test-Path $destFile)) {
New-Item -ItemType Directory -Path $destFile -Force | Out-Null
}
} else {
$parentDir = [System.IO.Path]::GetDirectoryName($destFile)
if (-not (Test-Path $parentDir)) {
New-Item -ItemType Directory -Path $parentDir -Force | Out-Null
}
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $destFile, $true)
}
}
} finally {
$archive.Dispose()
}
}
function Install-IPBanFromArchive {
param(
[Parameter(Mandatory=$true)]
[string]$zipPath,
[Parameter(Mandatory=$true)]
[string]$destPath,
[System.Windows.Forms.Label]$progressLabel = $null,
[System.Windows.Forms.Label]$detailsLabel = $null
)
# 1. Резервне копіювання конфігурації
$tempBackup = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), "ipban_cfg_backup")
if (Test-Path $destPath) {
if (-not (Test-Path $tempBackup)) { New-Item -ItemType Directory -Path $tempBackup -Force | Out-Null }
foreach ($cfg in @("ipban.config", "ipban.override.config", "ipban.sqlite", "nlog.config")) {
$srcFile = Join-Path $destPath $cfg
if (Test-Path $srcFile) {
Copy-Item -Path $srcFile -Destination $tempBackup -Force
}
}
}
# 2. Зупинка та видалення старої служби
if (Get-Service $script:ServiceName -ErrorAction SilentlyContinue) {
if ($detailsLabel) { $detailsLabel.Text = "Зупинка попередньої служби IPBan..."; [System.Windows.Forms.Application]::DoEvents() }
try { Stop-Service $script:ServiceName -Force } catch {}
& sc.exe delete $script:ServiceName
Start-Sleep -Seconds 1
}
# 3. Розпакування файлів
if ($detailsLabel) { $detailsLabel.Text = "Розпакування файлів у $destPath..."; [System.Windows.Forms.Application]::DoEvents() }
Expand-ZipArchiveSafe -zipPath $zipPath -destDir $destPath
# 4. Відновлення конфігурації
if (Test-Path $tempBackup) {
foreach ($cfg in @("ipban.config", "ipban.override.config", "ipban.sqlite", "nlog.config")) {
$bakFile = Join-Path $tempBackup $cfg
if (Test-Path $bakFile) {
Copy-Item -Path $bakFile -Destination $destPath -Force
}
}
Remove-Item $tempBackup -Recurse -Force -ErrorAction SilentlyContinue
}
# 5. Налаштування аудиту безпеки
if ($detailsLabel) { $detailsLabel.Text = "Налаштування аудиту входу Windows (AuditPol)..."; [System.Windows.Forms.Application]::DoEvents() }
& auditpol.exe /set /category:"{69979849-797A-11D9-BED3-505054503030}" /success:enable /failure:enable
& auditpol.exe /set /category:"{69979850-797A-11D9-BED3-505054503030}" /success:enable /failure:enable
# 6. Створення та запуск служби Windows
if ($detailsLabel) { $detailsLabel.Text = "Створення та запуск служби Windows..."; [System.Windows.Forms.Application]::DoEvents() }
$exePath = Join-Path $destPath "DigitalRuby.IPBan.exe"
if (-not (Test-Path $exePath)) {
throw "Не знайдено файл DigitalRuby.IPBan.exe у $destPath після розпакування!"
}
& sc.exe create $script:ServiceName binPath= "`"$exePath`"" start= auto
& sc.exe failure $script:ServiceName reset= 86400 actions= restart/60000/restart/60000/restart/60000 | Out-Null
Start-Sleep -Seconds 1
Start-Service $script:ServiceName
}
function Get-FirewallBannedIPs {
$results = @()
try {
$fw = New-Object -ComObject HNetCfg.FwPolicy2
foreach ($rule in $fw.Rules) {
if ($rule.Name -like "IPBan*") {
# Якщо правило блокування IPBan було вимкнено - автоматично відновлюємо активність
if (-not $rule.Enabled -and $rule.Action -eq 0 -and $rule.Name -notlike "*Whitelist*") {
try { $rule.Enabled = $true } catch {}
}
# Вимкнені правила не блокують трафік і не повинні показуватися як активні блокування
if (-not $rule.Enabled) { continue }
$ips = $rule.RemoteAddresses -split ","
foreach ($ip in $ips) {
$trim = $ip.Trim()
if (-not $trim -or $trim -eq "*") { continue }
# Нормалізація діапазону X.X.X.X-X.X.X.X до одного IP
if ($trim -match '^([^-\s]+)-\1$') {
$trim = $matches[1].Trim()
}
# Пропуск dummy/broadcast адрес Windows Firewall
if ($trim -like "255.255.255.255*" -or $trim -like "*-255.255.255.255" -or $trim -eq "255.255.255.255") {
continue
}
$cleanIp = $trim.Replace("/255.255.255.255", "").Replace("/32", "")
if ($cleanIp -eq "255.255.255.255" -or $cleanIp -like "255.255.255.255*") {
continue
}
$isWhite = ($rule.Action -ne 0) -or ($rule.Name -like "*Whitelist*")
$isBlacklist = (-not $isWhite) -and ($rule.Name -like "*Blacklist*")
$actionType = if ($isWhite) { "Allow" } elseif ($isBlacklist) { "Blacklist" } else { "Block" }
$actionLabel = if ($isWhite) { "⚪ Дозволено (Whitelist)" } elseif ($isBlacklist) { "🏴 Чорний список (Blacklist)" } else { "⛔ Локальне блокування" }
$results += [PSCustomObject]@{
IPAddress = $cleanIp
RuleName = $rule.Name
ActionType = $actionType
ActionLabel = $actionLabel
Enabled = $rule.Enabled
}
}
}
}
} catch {
try {
$rules = Get-NetFirewallRule -Name "IPBan*" -ErrorAction SilentlyContinue
foreach ($r in $rules) {
if (-not $r.Enabled -and $r.Action -eq "Block" -and $r.Name -notlike "*Whitelist*") {
try { Enable-NetFirewallRule -Name $r.Name -ErrorAction SilentlyContinue } catch {}
}
if (-not $r.Enabled) { continue }
$filters = Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $r -ErrorAction SilentlyContinue
foreach ($f in $filters) {
foreach ($ip in $f.RemoteAddress) {
$trim = $ip.Trim()
if (-not $trim -or $trim -eq "*") { continue }
if ($trim -match '^([^-\s]+)-\1$') {
$trim = $matches[1].Trim()
}
if ($trim -like "255.255.255.255*" -or $trim -like "*-255.255.255.255" -or $trim -eq "255.255.255.255") {
continue
}
$cleanIp = $trim.Replace("/255.255.255.255", "").Replace("/32", "")
if ($cleanIp -eq "255.255.255.255" -or $cleanIp -like "255.255.255.255*") {
continue
}
$isWhite = ($r.Action -ne "Block") -or ($r.Name -like "*Whitelist*")
$isBlacklist = (-not $isWhite) -and ($r.Name -like "*Blacklist*")
$actionType = if ($isWhite) { "Allow" } elseif ($isBlacklist) { "Blacklist" } else { "Block" }
$actionLabel = if ($isWhite) { "⚪ Дозволено (Whitelist)" } elseif ($isBlacklist) { "🏴 Чорний список (Blacklist)" } else { "⛔ Локальне блокування" }
$results += [PSCustomObject]@{
IPAddress = $cleanIp
RuleName = $r.Name
ActionType = $actionType
ActionLabel = $actionLabel
Enabled = $r.Enabled
}
}
}
}
} catch {}
}
return ,$results