Repository navigation
Expand file tree
/
Copy pathNetwork_Configuration.ps1
More file actions
5880 lines (5182 loc) · 263 KB
/
Copy pathNetwork_Configuration.ps1
File metadata and controls
5880 lines (5182 loc) · 263 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
# Version: 3.0
#Requires -Version 5.1
# Network Configuration Script
#
# Features:
# - Static IP and DHCP configuration
# - Live Interface Monitoring with real-time event tracking
# - Network connectivity testing (Gateway, DNS, Internet)
# - JSON IP profiles with legacy XML fallback
# - Subnet Calculator with CIDR calculations
# - Interface management and renaming
# - Opt-in logging with IP address masking
# - Data pseudonymization (IP addresses)
# - Privacy & Data Management dashboard
#
# Credits:
# - Subnet Calculator: Inspired by various PowerShell community implementations
# including work from robert-gaines, Jzubia, and other contributors
# Set console colors for better visibility
if ($Host.UI.SupportsVirtualTerminal -or $Host.Name -eq 'ConsoleHost') {
try {
$Host.UI.RawUI.BackgroundColor = 'Black'
$Host.UI.RawUI.ForegroundColor = 'Gray'
Clear-Host
} catch {
Write-Verbose "Console colors could not be set: $_"
}
}
#region File Path Migration (deduplicated)
$script:AppDataDir = Join-Path $env:APPDATA 'Network_Configuration_Script'
if (-not (Test-Path $script:AppDataDir)) {
New-Item -Path $script:AppDataDir -ItemType Directory | Out-Null
}
$script:ConfigFile = 'IPConfiguration.xml'
$script:LogFileName = 'network_config.log'
$script:VersionFile = 'version.txt'
$script:InterfaceFile = 'selected_interface.txt'
$script:ConsentFile = 'gdpr_consent.txt'
$script:ProfilesDirName = 'Profiles'
$script:BackupsDirName = 'Backups'
$script:ConfigPath = Join-Path $script:AppDataDir $script:ConfigFile
$script:LogPath = Join-Path $script:AppDataDir $script:LogFileName
$script:VersionPath = Join-Path $script:AppDataDir $script:VersionFile
$script:InterfacePath = Join-Path $script:AppDataDir $script:InterfaceFile
$script:ConsentPath = Join-Path $script:AppDataDir $script:ConsentFile
$script:ProfilesPath = Join-Path $script:AppDataDir $script:ProfilesDirName
$script:BackupsPath = Join-Path $script:AppDataDir $script:BackupsDirName
foreach ($directory in @($script:ProfilesPath, $script:BackupsPath)) {
if (-not (Test-Path $directory)) {
New-Item -Path $directory -ItemType Directory | Out-Null
}
}
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
foreach ($file in @($script:ConfigFile, $script:LogFileName, $script:VersionFile, $script:InterfaceFile, $script:ConsentFile)) {
$oldScriptPath = Join-Path $scriptDir $file
$oldUserProfilePath = Join-Path $env:USERPROFILE $file
$newPath = Join-Path $script:AppDataDir $file
if ((Test-Path $oldScriptPath) -and -not (Test-Path $newPath)) {
Move-Item -Path $oldScriptPath -Destination $newPath
}
if ((Test-Path $oldUserProfilePath) -and -not (Test-Path $newPath)) {
Move-Item -Path $oldUserProfilePath -Destination $newPath
}
}
# Ensure version.txt reflects the current script version
# Extract version from the header comment (first line: # Version: X.X)
$scriptContent = Get-Content $MyInvocation.MyCommand.Path -TotalCount 1
if ($scriptContent -match '^# Version:\s*(\d+(?:\.\d+){1,3})\s*$') {
$currentScriptVersion = $matches[1]
if (Test-Path $script:VersionPath) {
$savedVersion = (Get-Content $script:VersionPath -ErrorAction SilentlyContinue).Trim()
if ($savedVersion -ne $currentScriptVersion) {
Set-Content -Path $script:VersionPath -Value $currentScriptVersion -Force
}
} else {
Set-Content -Path $script:VersionPath -Value $currentScriptVersion -Force
}
}
#endregion
# Extract version dynamically from the script header before any consent or logging metadata is written
$script:ScriptVersion = "Unknown"
try {
$scriptContent = Get-Content -Path $MyInvocation.MyCommand.Path -TotalCount 5 -ErrorAction SilentlyContinue
$versionLine = $scriptContent | Where-Object { $_ -match "^# Version:" } | Select-Object -First 1
if ($versionLine) {
$script:ScriptVersion = ($versionLine -replace "^# Version:\s*", "").Trim()
}
} catch {
Write-Verbose "Could not extract script version from header: $_"
}
# Check for elevation and re-run as administrator if needed
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Host ""
Write-Host "Administrator privileges are required to change network adapter settings." -ForegroundColor Yellow
Write-Host "A User Account Control prompt will open. Choose Yes to continue." -ForegroundColor Gray
Write-Host ""
try {
$scriptPath = $MyInvocation.MyCommand.Definition
$launchArgs = "-NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`""
Start-Process -FilePath "powershell.exe" -ArgumentList $launchArgs -Verb RunAs -WorkingDirectory $scriptDir -ErrorAction Stop | Out-Null
exit
} catch {
Write-Host "[ERROR] The script was not started as administrator." -ForegroundColor Red
Write-Host "Network configuration changes cannot continue without elevation." -ForegroundColor Yellow
Write-Host "Start PowerShell as Administrator, or rerun the script and accept the UAC prompt." -ForegroundColor Gray
Write-Host ""
Read-Host "Press Enter to exit"
exit 1
}
}
#region Logging Settings
$script:MaxLogSizeMB = 5 # Max log file size (MB) before rotation
$script:MaxLogArchives = 5 # Number of rotated log files to keep
$script:MaxLogAgeDays = 30 # Remove rotated logs older than this many days
$script:MaxBackupArchives = 5 # Number of script/network backup files to keep per backup type
$script:MaxBackupAgeDays = 30 # Remove backups older than this many days
$script:MinLogLevel = "INFO" # Minimum log level to record
$script:LogFile = $script:LogPath
$script:LogLevels = @{
"DEBUG" = 1
"INFO" = 2
"WARN" = 3
"ERROR" = 4
"CRITICAL" = 5
}
#endregion
function Read-YesNo {
param (
[Parameter(Mandatory=$true)]
[string]$Prompt,
[bool]$Default = $false
)
$suffix = if ($Default) { " (Y/n)" } else { " (y/N)" }
while ($true) {
$response = (Read-Host "$Prompt$suffix").Trim().ToLower()
if ([string]::IsNullOrWhiteSpace($response)) {
return $Default
}
switch ($response) {
"y" { return $true }
"yes" { return $true }
"n" { return $false }
"no" { return $false }
default {
Write-Host "Please answer y or n." -ForegroundColor Yellow
}
}
}
}
function Remove-OldFiles {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$Path,
[Parameter(Mandatory=$true)]
[string]$Filter,
[ValidateRange(1,1000)]
[int]$KeepNewest = 5,
[ValidateRange(1,3650)]
[int]$MaxAgeDays = 30
)
if (-not (Test-Path $Path)) { return 0 }
$deletedCount = 0
$cutoff = (Get-Date).AddDays(-$MaxAgeDays)
$files = @(Get-ChildItem -Path $Path -Filter $Filter -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending)
foreach ($oldFile in ($files | Where-Object { $_.LastWriteTime -lt $cutoff })) {
try {
Remove-Item -LiteralPath $oldFile.FullName -Force -ErrorAction Stop
$deletedCount++
} catch {
Write-Verbose "Could not remove old file '$($oldFile.FullName)': $_"
}
}
$remainingFiles = @(Get-ChildItem -Path $Path -Filter $Filter -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending)
foreach ($extraFile in ($remainingFiles | Select-Object -Skip $KeepNewest)) {
try {
Remove-Item -LiteralPath $extraFile.FullName -Force -ErrorAction Stop
$deletedCount++
} catch {
Write-Verbose "Could not remove extra file '$($extraFile.FullName)': $_"
}
}
return $deletedCount
}
function Remove-LocalItemSafe {
param (
[Parameter(Mandatory=$true)]
[string]$Path,
[string]$DisplayName = $null,
[switch]$Recurse
)
if (-not (Test-Path $Path)) { return $false }
if ([string]::IsNullOrWhiteSpace($DisplayName)) {
$DisplayName = Split-Path $Path -Leaf
}
try {
if ($Recurse) {
Remove-Item -LiteralPath $Path -Recurse -Force -ErrorAction Stop
} else {
Remove-Item -LiteralPath $Path -Force -ErrorAction Stop
}
Write-Host " [OK] Deleted $DisplayName" -ForegroundColor Green
return $true
} catch {
Write-Host " [WARN] Could not delete ${DisplayName}: $_" -ForegroundColor Yellow
return $false
}
}
#region Privacy Controls
$script:LoggingConsent = $false
$script:PseudonymizeData = $true # Always pseudonymize IP addresses by default
# Function to check and request GDPR consent
function Get-GDPRConsent {
if (Test-Path $script:ConsentPath) {
try {
$consentData = Get-Content $script:ConsentPath -Raw | ConvertFrom-Json
if ($consentData.LoggingConsent -isnot [bool]) {
throw 'Stored logging consent must be a JSON boolean; request explicit consent again.'
}
$script:LoggingConsent = $consentData.LoggingConsent
# Existing consent files may contain false; current consent always promises masked logs.
$script:PseudonymizeData = $true
return
} catch {
# Invalid consent file, request new consent (will continue to show privacy notice)
Write-Verbose "Consent file is invalid or corrupted: $_"
}
}
# Show privacy notice
Clear-Host
Write-Host "===========================================================================" -ForegroundColor Cyan
Write-Host " PRIVACY NOTICE (GDPR) " -ForegroundColor Cyan
Write-Host "===========================================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "This script can collect the following data for troubleshooting purposes:" -ForegroundColor Yellow
Write-Host ""
Write-Host " - Network interface names (e.g., 'Ethernet', 'Wi-Fi')" -ForegroundColor White
Write-Host " - IP addresses (pseudonymized: 192.168.1.xxx)" -ForegroundColor White
Write-Host " - Subnet masks and gateway addresses (pseudonymized)" -ForegroundColor White
Write-Host " - DNS server addresses (pseudonymized)" -ForegroundColor White
Write-Host " - Saved profiles and backups may contain full IP settings" -ForegroundColor White
Write-Host " - Script actions and errors" -ForegroundColor White
Write-Host " - Timestamps of operations" -ForegroundColor White
Write-Host ""
Write-Host "Data Protection:" -ForegroundColor Green
Write-Host " [OK] Logs, profiles, and backups are stored locally" -ForegroundColor Gray
Write-Host " - MAC vendor lookup sends a MAC prefix to api.macvendors.com" -ForegroundColor Gray
Write-Host " - Checking for updates downloads the script from GitHub" -ForegroundColor Gray
Write-Host " [OK] IP addresses are pseudonymized (last octet hidden)" -ForegroundColor Gray
Write-Host " [OK] You can delete logs or all local data at any time" -ForegroundColor Gray
Write-Host " [OK] Logs are stored in: $script:AppDataDir" -ForegroundColor Gray
Write-Host ""
Write-Host "Your Rights:" -ForegroundColor Green
Write-Host " - Right to access your data (view logs)" -ForegroundColor Gray
Write-Host " - Right to delete your data (clear all logs)" -ForegroundColor Gray
Write-Host " - Right to withdraw consent at any time" -ForegroundColor Gray
Write-Host ""
Write-Host "Note: Logging helps diagnose network configuration issues." -ForegroundColor DarkGray
Write-Host " The script will function normally if you decline." -ForegroundColor DarkGray
Write-Host ""
if (Read-YesNo -Prompt "Do you consent to logging with data pseudonymization?" -Default $false) {
$script:LoggingConsent = $true
$consentData = @{
LoggingConsent = $true
PseudonymizeData = $true
ConsentDate = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
Version = $script:ScriptVersion
}
$consentData | ConvertTo-Json | Set-Content -Path $script:ConsentPath -Encoding UTF8
Write-Host ""
Write-Host "[OK] Thank you. Logging enabled with data pseudonymization." -ForegroundColor Green
Write-Host " You can manage your data via the 'Privacy & Data' menu option." -ForegroundColor Gray
} else {
$script:LoggingConsent = $false
$consentData = @{
LoggingConsent = $false
PseudonymizeData = $true
ConsentDate = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
Version = $script:ScriptVersion
}
$consentData | ConvertTo-Json | Set-Content -Path $script:ConsentPath -Encoding UTF8
Write-Host ""
Write-Host "[OK] Logging disabled. The script will function normally." -ForegroundColor Yellow
}
Write-Host ""
Start-Sleep -Seconds 2
}
# Function to pseudonymize IP addresses (GDPR data minimization)
function Hide-IPAddress {
param ([string]$IPAddress)
if (-not $script:PseudonymizeData -or [string]::IsNullOrWhiteSpace($IPAddress)) {
return $IPAddress
}
# Hide last octet of IPv4 addresses
if ($IPAddress -match '^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}$') {
return $IPAddress -replace '^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}$', '${1}xxx'
}
# Expand compressed IPv6 before masking the host half of the address.
$parsedAddress = $null
if ([System.Net.IPAddress]::TryParse($IPAddress, [ref]$parsedAddress) -and
$parsedAddress.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) {
$bytes = $parsedAddress.GetAddressBytes()
$networkPart = for ($i = 0; $i -lt 8; $i += 2) {
'{0:x}' -f (([int]$bytes[$i] -shl 8) -bor [int]$bytes[$i + 1])
}
return "$(($networkPart -join ':')):xxxx:xxxx:xxxx:xxxx"
}
return $IPAddress
}
# Function to show GDPR data management menu
function Show-GDPRMenu {
Clear-Host
Write-Host "===========================================================================" -ForegroundColor Cyan
Write-Host " PRIVACY & DATA MANAGEMENT " -ForegroundColor Cyan
Write-Host "===========================================================================" -ForegroundColor Cyan
Write-Host ""
$consentStatus = if ($script:LoggingConsent) { "Enabled" } else { "Disabled" }
$pseudoStatus = if ($script:PseudonymizeData) { "Enabled" } else { "Disabled" }
Write-Host "Current Settings:" -ForegroundColor Yellow
Write-Host " Logging: $consentStatus" -ForegroundColor White
Write-Host " Data Pseudonymization: $pseudoStatus" -ForegroundColor White
Write-Host " Data Location: $script:AppDataDir" -ForegroundColor Gray
Write-Host " Log Retention: $script:MaxLogArchives archive(s), $script:MaxLogAgeDays day(s)" -ForegroundColor Gray
Write-Host " Backup Retention: $script:MaxBackupArchives per type, $script:MaxBackupAgeDays day(s)" -ForegroundColor Gray
Write-Host ""
Write-Host "Options:" -ForegroundColor Cyan
Write-Host " [1] View Privacy Notice" -ForegroundColor White
Write-Host " [2] Query Logs" -ForegroundColor White
Write-Host " [3] Delete Logs Only" -ForegroundColor White
Write-Host " [4] Delete All Local Data" -ForegroundColor Yellow
Write-Host " [5] Change Logging Consent" -ForegroundColor White
Write-Host " [6] Export Data (Data Portability)" -ForegroundColor White
Write-Host " [b] Back to Main Menu" -ForegroundColor White
Write-Host ""
$choice = (Read-Host "Select an option").Trim().ToLower()
switch ($choice) {
"1" {
Show-PrivacyNotice
Read-Host "`nPress Enter to continue"
Show-GDPRMenu
}
"2" {
Show-LogViewer
Show-GDPRMenu
}
"3" {
Remove-AllLogs
Read-Host "`nPress Enter to continue"
Show-GDPRMenu
}
"4" {
Remove-AllLocalData
Read-Host "`nPress Enter to continue"
Show-GDPRMenu
}
"5" {
Update-GDPRConsent
Read-Host "`nPress Enter to continue"
Show-GDPRMenu
}
"6" {
Export-UserData
Read-Host "`nPress Enter to continue"
Show-GDPRMenu
}
"b" {
return
}
default {
Write-Host "Invalid option. Please try again." -ForegroundColor Red
Start-Sleep -Seconds 1
Show-GDPRMenu
}
}
}
# Function to show privacy notice
function Show-PrivacyNotice {
Clear-Host
Write-Host "===========================================================================" -ForegroundColor Cyan
Write-Host " PRIVACY NOTICE & DATA POLICY " -ForegroundColor Cyan
Write-Host "===========================================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "1. OVERVIEW" -ForegroundColor Yellow
Write-Host " This script runs on your computer and does not require an account." -ForegroundColor White
Write-Host ""
Write-Host "2. DATA COLLECTED" -ForegroundColor Yellow
Write-Host " - Network interface names" -ForegroundColor White
Write-Host " - IP addresses (pseudonymized by default)" -ForegroundColor White
Write-Host " - Network configuration settings" -ForegroundColor White
Write-Host " - Saved IP profiles and managed backup snapshots" -ForegroundColor White
Write-Host " - Timestamps of operations" -ForegroundColor White
Write-Host " - Error messages and diagnostic information" -ForegroundColor White
Write-Host ""
Write-Host "3. PURPOSE OF PROCESSING" -ForegroundColor Yellow
Write-Host " - Troubleshooting network configuration issues" -ForegroundColor White
Write-Host " - Providing operational history for review" -ForegroundColor White
Write-Host " - Debugging script errors" -ForegroundColor White
Write-Host ""
Write-Host "4. LOGGING CHOICE" -ForegroundColor Yellow
Write-Host " - Logs are written only after you opt in" -ForegroundColor White
Write-Host " - Profiles and backups are created by user actions" -ForegroundColor White
Write-Host ""
Write-Host "5. DATA STORAGE" -ForegroundColor Yellow
Write-Host " - Location: $script:AppDataDir" -ForegroundColor White
Write-Host " - Log retention: rotated after $script:MaxLogSizeMB MB; keeping $script:MaxLogArchives archive(s) for up to $script:MaxLogAgeDays day(s)" -ForegroundColor White
Write-Host " - Backup retention: keeping $script:MaxBackupArchives backup(s) per type for up to $script:MaxBackupAgeDays day(s)" -ForegroundColor White
Write-Host " - Access follows the file permissions on your computer" -ForegroundColor White
Write-Host ""
Write-Host "6. DATA SHARING" -ForegroundColor Yellow
Write-Host " - Logs, profiles, and backups are stored locally" -ForegroundColor Green
Write-Host " - MAC vendor lookup sends the first 6 MAC digits to api.macvendors.com" -ForegroundColor White
Write-Host " - Update checks download the script from GitHub" -ForegroundColor White
Write-Host ""
Write-Host "7. DATA CONTROLS" -ForegroundColor Yellow
Write-Host " - View logs" -ForegroundColor White
Write-Host " - Change or withdraw logging consent" -ForegroundColor White
Write-Host " - Delete logs or all local script data" -ForegroundColor White
Write-Host " - Export local script data" -ForegroundColor White
Write-Host ""
Write-Host "8. DATA SECURITY" -ForegroundColor Yellow
Write-Host " - Log IP addresses are pseudonymized (last octet replaced with 'xxx')" -ForegroundColor White
Write-Host " - Profiles and backups may store full IP settings so they remain usable" -ForegroundColor White
Write-Host " - Log access follows the file permissions on your computer" -ForegroundColor White
Write-Host " - Automatic log and backup cleanup to prevent excessive data retention" -ForegroundColor White
Write-Host ""
Write-Host "9. CONTACT" -ForegroundColor Yellow
Write-Host " This is an open-source tool. For questions, visit:" -ForegroundColor White
Write-Host " https://github.com/Dantdmnl/Network_Configuration_Script" -ForegroundColor Cyan
}
# Function to delete logs and consent record without removing saved profiles or backups
function Remove-AllLogs {
Write-Host ""
Write-Host "=== Delete Logs Only ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "This will permanently delete:" -ForegroundColor Yellow
Write-Host " - All log files" -ForegroundColor White
Write-Host " - All rotated log archives" -ForegroundColor White
Write-Host " - Consent record (you will be asked again)" -ForegroundColor White
Write-Host ""
Write-Host "Note: Configuration files (IP settings, interface) will NOT be deleted." -ForegroundColor Gray
Write-Host ""
if (Read-YesNo -Prompt "Delete logs and consent record?" -Default $false) {
$deletedCount = 0
# Delete main log file
if (Remove-LocalItemSafe -Path $script:LogFile -DisplayName "main log file") {
$deletedCount++
}
# Delete rotated logs
$logArchivePattern = "$($script:LogFileName).*"
foreach ($archiveLog in @(Get-ChildItem -Path $script:AppDataDir -Filter $logArchivePattern -File -ErrorAction SilentlyContinue)) {
if (Remove-LocalItemSafe -Path $archiveLog.FullName -DisplayName "log archive $($archiveLog.Name)") {
$deletedCount++
}
}
# Delete consent file
if (Remove-LocalItemSafe -Path $script:ConsentPath -DisplayName "consent record") {
$deletedCount++
}
$script:LoggingConsent = $false
Write-Host ""
Write-Host "[OK] Successfully deleted $deletedCount log file(s)" -ForegroundColor Green
Write-Host " Your data has been erased." -ForegroundColor Green
} else {
Write-Host "[X] Deletion cancelled" -ForegroundColor Yellow
}
}
function Remove-AllLocalData {
Write-Host ""
Write-Host "=== Delete All Local Data ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "This will permanently delete local data stored by this script:" -ForegroundColor Yellow
Write-Host " - Logs and rotated log archives" -ForegroundColor White
Write-Host " - GDPR consent record" -ForegroundColor White
Write-Host " - Selected adapter and legacy configuration files" -ForegroundColor White
Write-Host " - Saved IP profiles" -ForegroundColor White
Write-Host " - Managed backup files" -ForegroundColor White
Write-Host ""
Write-Host "The script file itself will not be deleted." -ForegroundColor Gray
Write-Host ""
$confirmation = (Read-Host "Type DELETE to permanently remove all local data").Trim()
if ($confirmation -ne "DELETE") {
Write-Host "[X] Local data deletion cancelled" -ForegroundColor Yellow
return
}
$deletedCount = 0
$pathsToDelete = @(
$script:LogFile,
$script:ConfigPath,
$script:VersionPath,
$script:InterfacePath,
$script:ConsentPath
)
foreach ($path in $pathsToDelete) {
if (Remove-LocalItemSafe -Path $path) {
$deletedCount++
}
}
foreach ($filter in @("$($script:LogFileName).*")) {
foreach ($file in @(Get-ChildItem -Path $script:AppDataDir -Filter $filter -File -ErrorAction SilentlyContinue)) {
if (Remove-LocalItemSafe -Path $file.FullName -DisplayName $file.Name) {
$deletedCount++
}
}
}
foreach ($directory in @($script:ProfilesPath, $script:BackupsPath)) {
if (Remove-LocalItemSafe -Path $directory -Recurse) {
$deletedCount++
}
}
foreach ($directory in @($script:ProfilesPath, $script:BackupsPath)) {
if (-not (Test-Path $directory)) {
New-Item -Path $directory -ItemType Directory -Force | Out-Null
}
}
$script:LoggingConsent = $false
$script:PseudonymizeData = $true
Write-Host ""
Write-Host "[OK] Deleted $deletedCount local data item(s)" -ForegroundColor Green
Write-Host " You will be asked for privacy consent again next time." -ForegroundColor Gray
}
# Function to update consent
function Update-GDPRConsent {
Write-Host ""
Write-Host "=== Change Logging Consent ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "Current Status: " -NoNewline
if ($script:LoggingConsent) {
Write-Host "Logging ENABLED" -ForegroundColor Green
} else {
Write-Host "Logging DISABLED" -ForegroundColor Red
}
Write-Host ""
$script:LoggingConsent = Read-YesNo -Prompt "Enable logging?" -Default $script:LoggingConsent
$consentData = @{
LoggingConsent = $script:LoggingConsent
PseudonymizeData = $true
ConsentDate = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
Version = $script:ScriptVersion
}
$consentData | ConvertTo-Json | Set-Content -Path $script:ConsentPath -Encoding UTF8
Write-Host ""
if ($script:LoggingConsent) {
Write-Host "[OK] Logging enabled" -ForegroundColor Green
} else {
Write-Host "[OK] Logging disabled" -ForegroundColor Yellow
}
}
# Function to export user data (Data Portability)
function Export-UserData {
param (
[string]$ExportDirectory = [Environment]::GetFolderPath('Desktop'),
[string]$TemporaryRoot = [System.IO.Path]::GetTempPath()
)
Write-Host ""
Write-Host "=== Data Portability ===" -ForegroundColor Cyan
Write-Host ""
$tempDir = $null
$exportPath = $null
try {
if (-not (Test-Path -LiteralPath $ExportDirectory -PathType Container)) {
throw "Export directory does not exist: $ExportDirectory"
}
if (-not (Test-Path -LiteralPath $TemporaryRoot -PathType Container)) {
throw "Temporary directory does not exist: $TemporaryRoot"
}
$exportId = "$(Get-Date -Format 'yyyyMMdd_HHmmss')_$([guid]::NewGuid().ToString('N').Substring(0, 8))"
$exportPath = Join-Path $ExportDirectory "NetworkScript_DataExport_$exportId.zip"
$tempDir = Join-Path $TemporaryRoot "NetworkScript_Export_$exportId"
New-Item -Path $tempDir -ItemType Directory -ErrorAction Stop | Out-Null
# Copy all data files
$filesToExport = @(
@{Path = $script:LogFile; Name = "logs\network_config.log"},
@{Path = $script:ConfigPath; Name = "config\IPConfiguration.xml"},
@{Path = $script:ConsentPath; Name = "consent\gdpr_consent.txt"},
@{Path = $script:InterfacePath; Name = "config\selected_interface.txt"}
)
foreach ($file in $filesToExport) {
if (Test-Path $file.Path) {
$destDir = Join-Path $tempDir (Split-Path $file.Name)
if (-not (Test-Path $destDir)) {
New-Item -Path $destDir -ItemType Directory -Force | Out-Null
}
Copy-Item -LiteralPath $file.Path -Destination (Join-Path $tempDir $file.Name) -Force -ErrorAction Stop
}
}
# Copy rotated logs
for ($i = 1; $i -le $script:MaxLogArchives; $i++) {
$archiveLog = "$script:LogFile.$i.log"
if (Test-Path $archiveLog) {
$logsDir = Join-Path $tempDir "logs"
if (-not (Test-Path -LiteralPath $logsDir)) {
New-Item -Path $logsDir -ItemType Directory -ErrorAction Stop | Out-Null
}
Copy-Item -LiteralPath $archiveLog -Destination (Join-Path $logsDir "network_config.$i.log") -Force -ErrorAction Stop
}
}
# Copy modern JSON profiles
if (Test-Path $script:ProfilesPath) {
$profilesExportDir = Join-Path $tempDir "profiles"
New-Item -Path $profilesExportDir -ItemType Directory -Force | Out-Null
foreach ($profileFile in @(Get-ChildItem -LiteralPath $script:ProfilesPath -Filter '*.json' -File -ErrorAction Stop)) {
Copy-Item -LiteralPath $profileFile.FullName -Destination $profilesExportDir -Force -ErrorAction Stop
}
}
# Copy managed backups
if (Test-Path $script:BackupsPath) {
$backupsExportDir = Join-Path $tempDir "backups"
New-Item -Path $backupsExportDir -ItemType Directory -Force | Out-Null
foreach ($backupFile in @(Get-ChildItem -LiteralPath $script:BackupsPath -File -ErrorAction Stop)) {
Copy-Item -LiteralPath $backupFile.FullName -Destination $backupsExportDir -Force -ErrorAction Stop
}
}
# Create README
$readme = @"
NETWORK CONFIGURATION SCRIPT - DATA EXPORT
Export Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
Script Version: $script:ScriptVersion
This archive contains the available local data stored by the Network Configuration Script.
CONTENTS:
- logs/ : All log files (current and rotated)
- config/ : Network configuration files
- profiles/ : Saved JSON IP profiles
- backups/ : Managed update and network configuration backups
- consent/ : GDPR consent record
DATA FORMAT:
- Logs are in JSON format
- Profiles are in JSON format
- Legacy configuration files are in XML format
- Logs pseudonymize IP addresses when pseudonymization is enabled
- Profiles and backups may contain full IP settings so they can be reused or restored
YOUR RIGHTS:
You have the right to:
- Access this data at any time
- Request deletion of all data
- Withdraw consent for logging
- Receive data in a portable format (this export)
For more information, visit:
https://github.com/Dantdmnl/Network_Configuration_Script
"@
$readme | Set-Content -Path (Join-Path $tempDir "README.txt")
# Create ZIP archive
Compress-Archive -Path "$tempDir\*" -DestinationPath $exportPath -ErrorAction Stop
Write-Host "[OK] Data exported successfully!" -ForegroundColor Green
Write-Host " Location: $exportPath" -ForegroundColor Cyan
Write-Host ""
if (Read-YesNo -Prompt "Open export location?" -Default $false) {
Start-Process -FilePath "explorer.exe" -ArgumentList "/select,`"$exportPath`""
}
} catch {
Write-Host "[X] Error exporting data: $_" -ForegroundColor Red
if ($exportPath -and (Test-Path -LiteralPath $exportPath)) {
Remove-Item -LiteralPath $exportPath -Force -ErrorAction SilentlyContinue
}
} finally {
if ($tempDir -and (Test-Path -LiteralPath $tempDir)) {
$resolvedTempDir = [System.IO.Path]::GetFullPath($tempDir)
$resolvedTempRoot = [System.IO.Path]::GetFullPath($TemporaryRoot).TrimEnd('\') + '\'
if ($resolvedTempDir.StartsWith($resolvedTempRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
try {
Remove-Item -LiteralPath $resolvedTempDir -Recurse -Force -ErrorAction Stop
} catch {
Write-Host "[WARN] Could not remove temporary export data: $_" -ForegroundColor Yellow
}
}
}
}
}
# Check GDPR consent on script start
Get-GDPRConsent
#endregion
# Function to rotate logs
#region Logging Functions
function Invoke-LogRotation {
if (Test-Path -Path $script:LogFile) {
$fileSizeMB = (Get-Item $script:LogFile).Length / 1MB
if ($fileSizeMB -ge $script:MaxLogSizeMB) {
$oldestLog = "$script:LogFile.$script:MaxLogArchives.log"
if (Test-Path -Path $oldestLog) {
Remove-Item -Path $oldestLog -Force
}
for ($i = $script:MaxLogArchives - 1; $i -ge 1; $i--) {
$oldLog = "$script:LogFile.$i.log"
$newLog = "$script:LogFile.$($i + 1).log"
if (Test-Path -Path $oldLog) {
Rename-Item -Path $oldLog -NewName $newLog -Force
}
}
Rename-Item -Path $script:LogFile -NewName "$script:LogFile.1.log" -Force
}
}
$null = Remove-OldFiles -Path $script:AppDataDir `
-Filter "$($script:LogFileName).*" `
-KeepNewest $script:MaxLogArchives `
-MaxAgeDays $script:MaxLogAgeDays
}
# Function to log messages
function Write-LogMessage {
param (
[string]$Message,
[ValidateSet("DEBUG", "INFO", "WARN", "ERROR", "CRITICAL")]
[string]$Level = "INFO"
)
# Respect GDPR consent - only log if user consented
if (-not $script:LoggingConsent) { return }
if ($script:LogLevels[$Level] -lt $script:LogLevels[$script:MinLogLevel]) { return }
try {
# File logging must never prevent configuration recovery.
$ErrorActionPreference = 'Stop'
# Pseudonymize IP addresses in the message
if ($script:PseudonymizeData) {
# Parse IPv6 candidates so compressed and full addresses are masked in full.
$ipv6Candidate = '(?<![0-9A-Za-z:.%])(?=[0-9A-Fa-f:.%]*:)[0-9A-Fa-f:.%]+(?![0-9A-Za-z:.%])'
$Message = [regex]::Replace($Message, $ipv6Candidate, [System.Text.RegularExpressions.MatchEvaluator]{
param($match)
$parsedAddress = $null
if ([System.Net.IPAddress]::TryParse($match.Value, [ref]$parsedAddress) -and
$parsedAddress.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) {
return Hide-IPAddress -IPAddress $match.Value
}
return $match.Value
})
# Match IPv4 addresses after IPv6, including IPv4-mapped IPv6 addresses.
$Message = $Message -replace '\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}\b', '${1}xxx'
}
Invoke-LogRotation
$logEntry = [ordered]@{
timestamp = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
level = $Level
message = $Message
} | ConvertTo-Json -Compress
$logEntry = $logEntry -replace '\\u0027', "'" -replace '\\u003c', '<' -replace '\\u003e', '>' -replace '\\u0026', '&'
$logEntry | Out-File -FilePath $script:LogFile -Append -Encoding UTF8
} catch {
if (-not $script:LogWriteFailureReported) {
$script:LogWriteFailureReported = $true
Write-Host '[WARN] File logging unavailable; network operations will continue.' -ForegroundColor Yellow
}
}
}
#endregion
function Invoke-BackupRetention {
[CmdletBinding()]
param (
[string]$Filter = "*"
)
$removed = Remove-OldFiles -Path $script:BackupsPath `
-Filter $Filter `
-KeepNewest $script:MaxBackupArchives `
-MaxAgeDays $script:MaxBackupAgeDays
if ($removed -gt 0) {
Write-LogMessage -Message "Backup retention removed $removed old backup file(s) matching '$Filter'." -Level "INFO"
}
}
function New-ManagedBackupPath {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$BaseName,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Extension
)
if (-not (Test-Path $script:BackupsPath)) {
New-Item -Path $script:BackupsPath -ItemType Directory -Force | Out-Null
}
$safeBaseName = $BaseName -replace '[\\/:*?"<>|]', '_'
$safeExtension = $Extension.TrimStart('.')
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss_fff"
$uniqueId = [guid]::NewGuid().ToString('N').Substring(0, 8)
return (Join-Path $script:BackupsPath "$safeBaseName`_$timestamp`_$uniqueId.$safeExtension")
}
function Invoke-StartupHousekeeping {
$null = Remove-OldFiles -Path $script:AppDataDir `
-Filter "$($script:LogFileName).*" `
-KeepNewest $script:MaxLogArchives `
-MaxAgeDays $script:MaxLogAgeDays
$null = Remove-OldFiles -Path $script:BackupsPath `
-Filter "*" `
-KeepNewest ($script:MaxBackupArchives * 4) `
-MaxAgeDays $script:MaxBackupAgeDays
}
Invoke-StartupHousekeeping
Write-LogMessage -Message "Script initialized." -Level "INFO"
# Loading animation function with progress steps
function Show-LoadingAnimation {
param (
[string]$Message = "Initializing",
[string[]]$Steps = @(),
[int]$StepDelayMs = 300
)
if ($Steps.Count -eq 0) {
# Simple loading with progress dots
Write-Host -NoNewline "$Message"
for ($i = 0; $i -lt 3; $i++) {
Write-Host -NoNewline "."
Start-Sleep -Milliseconds 200
}
Write-Host " [OK]" -ForegroundColor Green
} else {
# Multi-step loading with checkmarks
Write-Host $Message -ForegroundColor Cyan
foreach ($step in $Steps) {
Write-Host -NoNewline " [" -ForegroundColor Gray
Write-Host -NoNewline "..." -ForegroundColor Yellow
Write-Host -NoNewline "]" -ForegroundColor Gray
Write-Host -NoNewline " $step"
Start-Sleep -Milliseconds $StepDelayMs
Write-Host "`r " -NoNewline
Write-Host "[OK]" -ForegroundColor Green -NoNewline
Write-Host " $step"
}
}
}
# Function to open the log file
function Open-LogFile {
if (Test-Path -Path $script:LogFile) {
Start-Process -FilePath "notepad.exe" -ArgumentList $script:LogFile
} else {
Write-Host "Log file not found." -ForegroundColor Red
}
}
function Get-NetworkLogEntries {
[CmdletBinding()]
param (
[string]$LogPath = $script:LogFile,
[ValidateRange(0,100)][int]$MaxArchives = $script:MaxLogArchives,
[ValidateSet('ALL','DEBUG','INFO','WARN','ERROR','CRITICAL')][string]$Level = 'ALL',
[datetime]$From = [datetime]::MinValue,
[datetime]$Until = [datetime]::MaxValue,
[string]$SearchText = '',
[ValidateRange(1,1000)][int]$MaxResults = 200
)
if ($From -ge $Until) { throw 'The start date must be earlier than the end date.' }
$entries = New-Object 'System.Collections.Generic.List[object]'
$paths = @($LogPath)
for ($i = 1; $i -le $MaxArchives; $i++) {
$paths += "$LogPath.$i.log"
}
foreach ($filePath in $paths) {
if (-not (Test-Path -LiteralPath $filePath -PathType Leaf)) { continue }
try {
foreach ($line in (Get-Content -LiteralPath $filePath -ErrorAction Stop)) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
try {
$record = $line | ConvertFrom-Json -ErrorAction Stop
$timestamp = [datetime]::MinValue
$validTime = [datetime]::TryParseExact(
[string]$record.timestamp, 'yyyy-MM-dd HH:mm:ss',
[System.Globalization.CultureInfo]::InvariantCulture,
[System.Globalization.DateTimeStyles]::None, [ref]$timestamp)
if (-not $validTime -or $null -eq $record.message) { continue }
$recordLevel = ([string]$record.level).ToUpperInvariant()
if ($recordLevel -notin @('DEBUG','INFO','WARN','ERROR','CRITICAL')) { continue }
if ($Level -ne 'ALL' -and $recordLevel -ne $Level) { continue }
if ($timestamp -lt $From -or $timestamp -ge $Until) { continue }
$message = [string]$record.message
if ($SearchText -and $message.IndexOf($SearchText, [System.StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
$entries.Add([pscustomobject]@{
Timestamp = $timestamp
Level = $recordLevel
Message = $message
Source = Split-Path -Leaf $filePath
})
} catch {
# Old or damaged log lines should not hide valid entries.
continue
}
}
} catch {
Write-Warning "Could not read log file '$filePath': $_"
}
}
return @($entries | Sort-Object Timestamp -Descending | Select-Object -First $MaxResults)
}
function Show-LogViewer {
while ($true) {
Clear-Host
Write-Host "=== Log Viewer ===" -ForegroundColor Cyan
Write-Host " [1] Recent entries (current log and archives)" -ForegroundColor White
Write-Host " [2] Query by level, date, and message" -ForegroundColor White
Write-Host " [3] Open current raw log in Notepad" -ForegroundColor White
Write-Host " [b] Back" -ForegroundColor Gray
if (-not $script:LoggingConsent) {
Write-Host "Logging is off; previously saved logs can still be viewed." -ForegroundColor Yellow