-
Notifications
You must be signed in to change notification settings - Fork 3
/
AutoHarden_RELEASE.ps1
3147 lines (2890 loc) · 183 KB
/
AutoHarden_RELEASE.ps1
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
# AutoHarden - A simple script that automates Windows Hardening
#
# Filename: AutoHarden_RELEASE.ps1
# Author: 1mm0rt41PC - immortal-pc.info - https://github.com/1mm0rt41PC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to the
# Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Update: 2024-07-16-15-52-52
$AutoHarden_version="2024-07-16-15-52-52"
$global:AutoHarden_boradcastMsg=$true
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
Add-Type -AssemblyName System.Windows.Forms
$AutoHarden_Folder='C:\Windows\AutoHarden'
$AutoHarden_Logs="${AutoHarden_Folder}\logs"
$AutoHarden_AsksFolder="${AutoHarden_Folder}\asks"
$AutoHarden_Group='RELEASE'
$AutoHarden_Asks=($AutoHarden_Group -eq 'RELEASE')
$AutoHarden_WebDomain="https://raw.githubusercontent.com/1mm0rt41PC/AutoHarden/master/AutoHarden_${AutoHarden_Group}.ps1"
#$AutoHarden_SysmonUrl="https://raw.githubusercontent.com/olafhartong/sysmon-modular/master/sysmonconfig.xml"
$AutoHarden_SysmonUrl="https://raw.githubusercontent.com/1mm0rt41PC/AutoHarden/master/sysmonconfig.xml"
Get-Variable
gci env:* | sort-object name
###############################################################################
# FUNCTIONS - Const var
$askMigration = ConvertFrom-StringData -StringData @'
0.1-AutoUpdate.ask = 0-AutoUpdate.ask
1.2-Firewall-Office.ask = block-communication-for-excel,word.ask
1.3-Firewall-IE.ask = block-communication-for-InternetExplorer.ask
1.1-Firewall-Malware.ask = block-communication-for-powershell,eviltools.ask
Hardening-DisableMimikatz__CredentialsGuard.ask = CredentialsGuard.ask
1.4-Firewall-BlockOutgoingSNMP.ask = Hardening-BlockOutgoingSNMP.ask
Hardening-DisableMimikatz__Mimikatz-DomainCredAdv.ask = Mimikatz-DomainCred.ask
Crapware-RemoveUseLessSoftware__Uninstall-OneNote.ask = Uninstall-OneNote.ask
Crapware-RemoveUseLessSoftware__Uninstall-Skype.ask = Uninstall-Skype.ask
'@
$isLaptop = (Get-WmiObject -Class win32_systemenclosure | Where-Object { $_.chassistypes -eq 9 -or $_.chassistypes -eq 10 -or $_.chassistypes -eq 14}).Count -gt 0 -And (Get-WmiObject -Class win32_battery).Name -ne ''
$getRole = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ProductOptions" -ErrorAction SilentlyContinue -ErrorVariable GetItemPropertyError
$getRole = @{
"WinNT" = "WorkStation";
"LanmanNT" = "Domain Controller";
"ServerNT" = "Server";
}[$getRole.ProductType];
$isDomainLinked = ( "\\$($env:COMPUTERNAME)" -eq $env:LOGONSERVER -And $getRole -eq "Domain Controller" ) -Or "\\$($env:COMPUTERNAME)" -ne $env:LOGONSERVER
###############################################################################
# FUNCTIONS - Logs
function logInfo( $msg )
{
Write-Host -NoNewline -Background 'Blue' '[i]'
Write-Host " $msg"
}
function logSuccess( $msg )
{
Write-Host -NoNewline -Background 'Green' '[v]'
Write-Host " $msg"
}
function logError( $msg )
{
Write-Host -NoNewline -Background 'Red' '[X]'
Write-Host " $msg"
}
###############################################################################
# FUNCTIONS - RPC
$RpcRules = (netsh rpc filter show filter).Replace(' ','')
function addRpcAcl( $name='', $uuid=@(), $acl='' )
{
if( $uuid.Count -gt 0 -Or $uuid -ne '' ){
$acl = $uuid | foreach {
return RpcRuleCreator $_ $name
}
}
if( $acl -eq '' ){
return $null;
}
$acl = @"
rpc
filter
$acl
quit
"@
$file=createTempFile $acl
netsh -f $file
$global:RpcRules = (netsh rpc filter show filter)
echo $global:RpcRules
$global:RpcRules = ($global:RpcRules).Replace(' ','')
rm $file
}
# Add a rule to drop access to EFS for non DA
# From: https://twitter.com/tiraniddo/status/1422223511599284227
# From: https://gist.github.com/tyranid/5527f5559041023714d67414271ca742
function RpcRuleCreator( $uuid, $name )
{
$1st_uuid=$uuid.Split('-')[0]
if( $RpcRules -Like "*$uuid*" -Or $RpcRules -Like "*$1st_uuid*" ){
logInfo "RpcRules is already applied for $name => $uuid"
return '';
}
$ret = '';
if( $isDomainLinked ){
logSuccess "RpcRules applied for $name with DOMAIN support => $uuid"
$ret = @"
add rule layer=um actiontype=permit
add condition field=if_uuid matchtype=equal data=$uuid
add condition field=remote_user_token matchtype=equal data=D:(A;;CC;;;DA)
add filter
"@
}else{
logSuccess "RpcRules applied for $name withOUT DOMAIN support => $uuid"
}
return $ret+@"
add rule layer=um actiontype=block
add condition field=if_uuid matchtype=equal data=$uuid
add filter
"@
}
###############################################################################
# FUNCTIONS - Global
$global:asks_cache = @{}
function ask( $query, $config )
{
if( $global:asks_cache.ContainsKey($config) ){
Write-Host ("# [${AutoHarden_AsksFolder}\${config}] In cache => {0}" -f $global:asks_cache[$config])
return $global:asks_cache[$config];
}
if( [System.IO.File]::Exists("${AutoHarden_AsksFolder}\${config}") ){
Write-Host "# [${AutoHarden_AsksFolder}\${config}] Exist => Using the new file location"
$ret = _ask $query $config $AutoHarden_AsksFolder
$global:asks_cache[$config] = $ret
return $ret;
}
if( [System.IO.File]::Exists("${AutoHarden_Folder}\${config}") ){
Write-Host "# [${AutoHarden_Folder}\${config}] The new 'ask' location doesn't exist but the old one exist => Using the old file location"
$ret = _ask $query $config $AutoHarden_Folder
[System.IO.File]::WriteAllLines("${AutoHarden_AsksFolder}\${config}", "$ret", (New-Object System.Text.UTF8Encoding $False));
Remove-Item -Force "${AutoHarden_Folder}\${config}" -ErrorAction Ignore;
$global:asks_cache[$config] = $ret
return $ret;
}
if( $askMigration.Contains($config) ){
if( [System.IO.File]::Exists("${AutoHarden_Folder}\$($askMigration[$config])") ){
$ret=cat "${AutoHarden_Folder}\$($askMigration[$config])" -ErrorAction Ignore;
if( $config -eq 'Hardening-DisableMimikatz__Mimikatz-DomainCredAdv.ask' ){
if( $ret -eq 'Yes' ){
$ret = 'No'
}else{
$ret = 'Yes'
}
}
Write-Host ("# [${AutoHarden_AsksFolder}\${config}] Not found but the old configuration exist ${AutoHarden_Folder}\$($askMigration[$config]) with the value ${ret} => {0}" -f ($ret -eq 'Yes'))
[System.IO.File]::WriteAllLines("${AutoHarden_AsksFolder}\${config}","$ret", (New-Object System.Text.UTF8Encoding $False));
Remove-Item -Force $AutoHarden_Folder\$askMigration[$config] -ErrorAction Ignore;
$global:asks_cache[$config] = $ret -eq 'Yes'
return $global:asks_cache[$config];
}
}
Write-Host "# [${AutoHarden_AsksFolder}\${config}] This parameter is new and doesn't exist at all"
$ret = _ask $query $config $AutoHarden_AsksFolder
$global:asks_cache[$config] = $ret
return $ret;
}
function _ask( $query, $config, $folder )
{
$ret=cat "${folder}\${config}" -ErrorAction Ignore;
logInfo "[${folder}\${config}] Checking..."
try{
if( [string]::IsNullOrEmpty($ret) ){
logInfo "[${folder}\${config}] Undefined... Asking"
if( $AutoHarden_Asks ){
$ret = 'No'
if( -not [Environment]::UserInteractive ){
throw 'UserNotInteractive'
}
Write-Host ""
do{
$ret = (Read-Host "${query}? (Y/n)").toupper()
if( $ret.Length -gt 0 ){
$ret = $ret.substring(0,1)
}else{
$ret = 'Y'
}
}while( $ret -ne 'Y' -and $ret -ne 'N' -and $ret -ne '' );
if( $ret -eq 'Y' ){
$ret = 'Yes'
}else{
$ret = 'No'
}
logInfo "[${folder}\${config}] Admin said >$ret<"
}else{
logInfo "[${folder}\${config}] AutoManagement ... NOASKING => YES"
$ret = 'Yes'
}
[System.IO.File]::WriteAllLines("${AutoHarden_AsksFolder}\${config}","$ret", (New-Object System.Text.UTF8Encoding $False));
}
logSuccess ("[${folder}\${config}] is >$ret< => parsed={0}" -f ($ret -eq 'Yes' -Or $ret -eq 'True'))
return $ret -eq 'Yes' -Or $ret -eq 'True';
}catch{
logError "[${folder}\${config}][WARN] An update of AutoHarden require an action from the administrator."
if( $global:AutoHarden_boradcastMsg -And $AutoHarden_Asks ) {
$global:AutoHarden_boradcastMsg=$false
msg * "An update of AutoHarden require an action from the administrator.`r`n`r`n${query}?`r`nPlease run ${AutoHarden_Folder}\AutoHarden.ps1"
}
return $null;
}
}
function createTempFile( $data, [Parameter(Mandatory=$false)][string]$ext='' )
{
$tmpFileName = -join ((65..90) + (97..122) | Get-Random -Count 25 | % {[char]$_});
$tmpFileName = "${AutoHarden_Folder}\${tmpFileName}${ext}"
[System.IO.File]::WriteAllLines($tmpFileName, $data, (New-Object System.Text.UTF8Encoding $False));
return $tmpFileName;
}
# reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\System" /t REG_DWORD /v PublishUserActivities /d 0 /f
function reg()
{
$action = $args[0].ToLower()
$hk = $args[1].Replace('HKCU','HKCU:').Replace('HKEY_CURRENT_USER','HKCU:')
$type = 'REG_DWORD'
$key = ''
$value = ''
for( $i=2; $i -lt $args.Count; $i+=2 )
{
if( $args[$i] -eq '/t' ){
$type=$args[$i+1]
}elseif( $args[$i] -eq '/v' ){
$key=$args[$i+1]
}elseif( $args[$i] -eq '/d' ){
$value=$args[$i+1]
}elseif( $args[$i] -eq '/f' ){
$i-=1
# Pass
}
}
if( $action -eq 'add' ){
if( $hk.StartsWith('HKCU:') ){
$path = $hk.Replace('HKCU:\','')
Get-ChildItem REGISTRY::HKEY_USERS | select Name | foreach {
$name = $_.Name.Trim('\')
$name = ('{0}\{1}' -f $name,$path).Replace('\\','\')
Write-host "reg.exe add $name /v $key /d $value /t $type /f"
try{
if( (Get-ItemPropertyValue "Registry::$name" -Name $key -ErrorAction SilentlyContinue) -ne $value ){
throw "Invalid value"
}
logInfo "[${name}:$key] is OK ($value)"
}catch{
logSuccess "[${name}:$key] is now set to $value"
reg.exe add "$name" /v "$key" /t $type /d "$value" /f
}
}
return $null
}
try{
Write-Host "reg.exe add $hk /v $key /d $value /t $type /f"
if( (Get-ItemPropertyValue "Registry::$hk" -Name $key -ErrorAction Stop) -eq $value ){
logInfo "[${hk}:$key] is OK ($value)"
}else{
logSuccess "[${hk}:$key] is now set to $value"
reg.exe add "$hk" /v "$key" /d "$value" /t $type /f
}
}catch{
logSuccess "[${hk}:$key] is now set to $value"
reg.exe add "$hk" /v "$key" /d "$value" /t $type /f
}
return $null
}elseif( $action -eq 'delete' ){
if( $hk.StartsWith('HKCU:') ){
$path = $hk.Replace('HKCU:\','')
Get-ChildItem REGISTRY::HKEY_USERS | select Name | foreach {
$name = $_.Name.Trim('\')
$name = ('{0}\{1}' -f $name,$path).Replace('\\','\')
try{
Get-ItemPropertyValue "Registry::$name" -Name $key -ErrorAction Stop
if( -not [string]::IsNullOrEmpty($key) ){
logSuccess "[${name}:$key] is now DELETED"
Write-Host "reg.exe delete $name /v $key /f"
reg.exe delete "$name" /v "$key" /f
}else{
logSuccess "[$name] is now DELETED"
Write-Host "reg.exe delete $name /f"
reg.exe delete "$name" /f
}
}catch{
logInfo "[${name}:$key] is NOT present"
}
}
return $null
}
try{
Get-ItemPropertyValue "Registry::$hk" -Name $key -ErrorAction Stop
if( -not [string]::IsNullOrEmpty($key) ){
logSuccess "[${hk}:$key] is now DELETED"
Write-Information "reg.exe delete $hk /v $key /f"
reg.exe delete "$hk" /v "$key" /f
}else{
logSuccess "[${hk}] is now DELETED"
Write-Information "reg.exe delete $hk /f"
reg.exe delete "$hk" /f
}
}catch{
logInfo "[${hk}:$key] is NOT present"
}
return $null
}
Write-Error "Not implemented"
}
function mywget( $Uri, $OutFile=$null )
{
$ret = $null
Get-NetFirewallRule -DisplayName '*AutoHarden*Powershell*' -ErrorAction SilentlyContinue | Disable-NetFirewallRule
try{
if( $OutFile -eq $null ){
$ret=Invoke-WebRequest -UseBasicParsing -Uri $Uri
}else{
Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $OutFile > $null
}
}catch{
if( $OutFile -eq $null ){
$ret=curl.exe $Uri
}else{
curl.exe $Uri --output $OutFile > $null
}
}
Get-NetFirewallRule -DisplayName '*AutoHarden*Powershell*' -ErrorAction SilentlyContinue | Enable-NetFirewallRule
return $ret;
}
if( ![bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544") ){ Write-Host -BackgroundColor Red -ForegroundColor White "Administrator privileges required ! This terminal has not admin priv. This script ends now !"; pause;exit;}
mkdir $AutoHarden_Folder -Force -ErrorAction Continue > $null
mkdir $AutoHarden_Logs -Force -ErrorAction Continue > $null
mkdir $AutoHarden_AsksFolder -Force -ErrorAction Continue > $null
Move-Item -ErrorAction SilentlyContinue -Force ${AutoHarden_Folder}\*.log ${AutoHarden_Logs}
Move-Item -ErrorAction SilentlyContinue -Force ${AutoHarden_Folder}\*.7z ${AutoHarden_Logs}
$AutoHardenTransScriptLog = "${AutoHarden_Logs}\Activities_${AutoHarden_Group}_"+(Get-Date -Format "yyyy-MM-dd")+".log"
Start-Transcript -Force -IncludeInvocationHeader -Append ($AutoHardenTransScriptLog)
#$DebugPreference = "Continue"
#$VerbosePreference = "Continue"
$InformationPreference = "Continue"
Get-ChildItem -File $AutoHarden_Folder\*.log | foreach {
$name = $_.Name
$_ | Compress-Archive -CompressionLevel "Optimal" -DestinationPath ${AutoHarden_Logs}\${name}.zip -ErrorAction SilentlyContinue
}
####################################################################################################
logInfo "Asking questions for the configuration"
ask "Fetch the latest version of AutoHarden from Github every day at 08h00 AM" "0-AutoUpdateFromWeb.ask" | Out-Null
ask "Execute AutoHarden every day at 08h00 AM" "0.1-AutoScheduledTask.ask" | Out-Null
ask "Block Internet communication for evil tools ?
This filtering prevents viruses from downloading the payload." "1.1-Firewall-Malware.ask" | Out-Null
ask "Block Internet communication for Word and Excel ?
Excel and Word will still be able to access files on local network shares.
This filtering prevents viruses from downloading the payload.
Block Internet communication for Word and Excel" "1.2-Firewall-Office.ask" | Out-Null
ask "Block Internet communication for 'Internet Explorer' ?
'Internet Explorer' will still be able to access web server on local network.
This filtering prevents viruses from downloading the payload.
Block Internet communication for 'Internet Explorer'" "1.3-Firewall-IE.ask" | Out-Null
ask "Disable SNMP communication (can break printers)" "1.4-Firewall-BlockOutgoingSNMP.ask" | Out-Null
ask "Avoid sending notification to Users about the firewall" "1.5-Firewall-DisableNotification.ask" | Out-Null
ask "Disable Cortana in Windows search bar" "Crapware-Cortana.ask" | Out-Null
ask "Remove OneDrive" "Crapware-Onedrive.ask" | Out-Null
ask "Uninstall OneNote" "Crapware-RemoveUseLessSoftware__Uninstall-OneNote.ask" | Out-Null
ask "Uninstall Skype" "Crapware-RemoveUseLessSoftware__Uninstall-Skype.ask" | Out-Null
ask "Harden Apps in APPDATA folder ? Be careful, can crach some app... Harden Apps in APPDATA folder ?" "Harden-AppData.ask" | Out-Null
ask "Disable voice control" "Harden-VoiceControl.ask" | Out-Null
ask "Harden Windows Defender" "Harden-WindowsDefender.ask" | Out-Null
ask "Invert the administrator and guest accounts" "Hardening-AccountRename.ask" | Out-Null
ask "Deny auto installation of vendor's application/drivers by the user" "Hardening-Co-Installers.ask" | Out-Null
ask "Do you want to enable 'Credentials Guard' and disable VMWare/VirtualBox" "Hardening-DisableMimikatz__CredentialsGuard.ask" | Out-Null
ask "Harden domain credential against hijacking ?
WARNING If this Windows is a mobile laptop, this configuration will break this Windows !!!
Harden domain credential against hijacking" "Hardening-DisableMimikatz__Mimikatz-DomainCredAdv.ask" | Out-Null
ask "Block DLL from SMB share and WebDav Share" "Hardening-DLLHijacking.ask" | Out-Null
ask "Disable Remote Assistance on this computer" "Hardening-RemoteAssistance.ask" | Out-Null
ask "When enabled, UAC prompts require both a valid username and a valid password to be entered in a secure desktop (default: interactive window proposes 'deny' or 'accept')." "Hardening-UAC-credz.ask" | Out-Null
ask "Show file extension and show windows title in the taskbar" "Optimiz-ClasicExplorerConfig.ask" | Out-Null
ask "Disable auto Windows Update during work time" "Optimiz-DisableAutoUpdate.ask" | Out-Null
ask "Disable WindowsDefender" "Optimiz-DisableDefender.ask" | Out-Null
ask "Replace notepad with notepad++" "Software-install-notepad++.ask" | Out-Null
$global:asks_cache | Format-Table -Autosize
logSuccess "All asks have been processed"
####################################################################################################
echo "####################################################################################################"
echo "# 0-AutoUpdateFromWeb"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "0-AutoUpdateFromWeb" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 0-AutoUpdateFromWeb"
$q=ask "Fetch the latest version of AutoHarden from Github every day at 08h00 AM" "0-AutoUpdateFromWeb.ask"
if( $q -eq $true ){
$ps1TestSign = "${AutoHarden_Folder}\AutoHarden_${AutoHarden_Group}.ps1"
if( -not [System.IO.File]::Exists($ps1TestSign) ){
$ps1TestSign = "${AutoHarden_Folder}\AutoHarden.ps1"
}
if( -not [System.IO.File]::Exists($ps1TestSign) ){
$ps1TestSign = $null
}
for( $i=3; $i -gt 0; $i-- )
{
# Install cert to avoid git takeover
$AutoHardenCert = "${env:temp}\"+[System.IO.Path]::GetRandomFileName()+".cer"
while( -not [System.IO.File]::Exists($AutoHardenCert) )
{
[IO.File]::WriteAllBytes($AutoHardenCert, [Convert]::FromBase64String("MIIFGTCCAwGgAwIBAgIQlPiyIshB45hFPPzNKE4fTjANBgkqhkiG9w0BAQ0FADAYMRYwFAYDVQQDEw1BdXRvSGFyZGVuLUNBMB4XDTE5MTAyOTIxNTUxNVoXDTM5MTIzMTIzNTk1OVowFTETMBEGA1UEAxMKQXV0b0hhcmRlbjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALrMv49xZXZjF92Xi3cWVFQrkIF+yYNdU3GSl1NergVq/3WmT8LDpaZ0XSpExZ7soHR3gs8eztnfe07r+Fl+W7l6lz3wUGFt52VY17WCa53tr5dYRPzYt2J6TWT874tqZqlo+lUl8ONK1roAww2flcDajm8VUXM0k0sLM17H9NLykO3DeBuh2PVaXUxGDej+N8PsYF3/7Gv2AW0ZHGflrondcXb2/eh8xwbwRENsGaMXvnGr9RWkufC6bKq31J8BBnP+/65M6541AueBoH8pLbANPZgHKES+8V9UWlYKOeSoeBhtL1k3Rr8tfizRWx1zg/pBNL0WTOLcusmuJkdHkdHbHaW6Jc/vh06Cs6xqz9/Dkg+K3BvOmfwZfAjl+qdgzM8dUU8/GWhswngwLAz64nZ82mZv/Iw6egC0rj5MYV0tpEjIgtVVgHavUfyXoIETNXFQR4SoK6PfeVkEzbRh03xhU65MSgBgWVv1YbOtdgXK0MmCs3ngVPJdVaqBjgcrK++X3Kxasb/bOkcfQjff/EK+BPb/xs+pXEqryYbtbeX0v2rbV9cugPUj+mneucZBLFjuRcXhzVbXLrwXVne7yTD/sIKfe7dztzchg19AY6/qkkRkroaKLASpfCAVx2LuCgeFGn//QaEtCpFxMo2dcnW2a+54pkzrCRTRg1N2wBQFAgMBAAGjYjBgMBMGA1UdJQQMMAoGCCsGAQUFBwMDMEkGA1UdAQRCMECAEPp+TbkVy9u5igk2CqcX2OihGjAYMRYwFAYDVQQDEw1BdXRvSGFyZGVuLUNBghBrxVMud93NnE/XjEko2+2HMA0GCSqGSIb3DQEBDQUAA4ICAQAQLtHeMr2qJnfhha2x2aCIApPjfHiHT4RNPI2Lq71jEbTpzdDFJQkKq4R3brGcpcnuU9VjUwz/BgKer+SFpkwFwTHyJpEFkbGavNo/ez3bqoehvqlTYDJO/i2mK0fvKmShfne6dZT+ftLpZCP4zngcANlp+kHy7mNRMB+LJv+jPc0kJ2oP4nIsLejyfxMj0lXuTJJRhxeZssdh0tq4MZP5MjSeiE5/AMuKT12uJ6klNUFS+OlEpZyHkIpgy4HxflXSvhchJ9U1YXF2IQ47WOrqwCXPUinHKZ8LwB0b0/35IlRCpub5KdRf803+4Okf9fL4rfc1cg9ZbLxuK9neFg1+ESL4aPyoV03TbN7Cdsd/sfx4mJ8jXJD+AXZ1ZofAAapYf9J5C71ChCZlhIGBvVc+dTUCWcUYgNOD9Nw+NiV6mARmVHl9SFL7yEtNYFgo0nWiNklqMqBLDxmrrD27sgBpFUwbMZ52truQwaaSHD7hFb4Tb1B0JVaGoog3QfNOXaFeez/fAt5L+yo78cDm7Q2tXvy2g0xDAL/TXn7bhtDzQunltBzdULrJEQO4zI0h8YgmF88a0zYZ9HRkDUn6dR9+G8TlZuUsWSOdvLdEvad9RqiHKeSrL6qgLBT5kqVt6AFsEtmFNz1s7xpsw/zPZvIXtQTmb4h+GcE/b2sUFZUkRA=="))
Import-Certificate -Filepath $AutoHardenCert -CertStoreLocation Cert:\LocalMachine\TrustedPublisher > $null
}
$AutoHardenCertCA = "${env:temp}\"+[System.IO.Path]::GetRandomFileName()+".cer"
while( -not [System.IO.File]::Exists($AutoHardenCertCA) )
{
[IO.File]::WriteAllBytes($AutoHardenCertCA, [Convert]::FromBase64String("MIIFHDCCAwSgAwIBAgIQa8VTLnfdzZxP14xJKNvthzANBgkqhkiG9w0BAQ0FADAYMRYwFAYDVQQDEw1BdXRvSGFyZGVuLUNBMB4XDTE5MTAyOTIxNTUwOVoXDTM5MTIzMTIzNTk1OVowGDEWMBQGA1UEAxMNQXV0b0hhcmRlbi1DQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANlm8tv2IqVairIP90RnIsNlQYPMAvUwRcC6Nw+0Qlv56tWczvMl9IF0+h2vUF5+lnSEkJMGBqeLFaJgSo9lNyHeTfjjqpEcMVBw1nXl6VSfNiirD7fJTkyZ3rl63PsOwbfWCPDW1AvLufYhBiijPlK1k4RJFkiFZbZkpe5ys0uY4QVFj+ZTaW0EA0MncX2YZ775QnX7HJO0HfMcHGGTxOPhAqJ7Pp+IBrs75laaASekJSTVub7jqs5aeApQkUWgKel1fmK0tBv35deE1P5ABXi+KnuzWCZDU8znIDAnj1qz+6c21KKhslEdzYlRSlq4kPcF964GECxRtgq0z1pzhV/WvBJjWjNp3G5e8jUfjuAg2utF/xd/j7GNU8vllDAXFjl4czc1saGZDcU8a/uaweKMjqR4WfyUp/H/mB7JFJlOHBGTRszWaAU/4E0V+bICXNI5augkV29ci0HouBG3WFcQiA5q+1U2vY/scVyMPm8ZecCe2b+SD/ipPtFspcOPStRm5EQgL4CWdVpSmm8+JRO0NcrSnQtNPCwPBT3c7OLOwYLBl8WHcJG1yOJtQvLjv1koMmJkHR0djODx8Ig9fqAFLH0c694E6VJbojDVGp/LRR9LnJnzYlWAYoT3ScPQ9uesgr4x8VSnrM6cMG3ASQD92RVXKCDep/Rq29IXtvjpAgMBAAGjYjBgMBMGA1UdJQQMMAoGCCsGAQUFBwMDMEkGA1UdAQRCMECAEPp+TbkVy9u5igk2CqcX2OihGjAYMRYwFAYDVQQDEw1BdXRvSGFyZGVuLUNBghBrxVMud93NnE/XjEko2+2HMA0GCSqGSIb3DQEBDQUAA4ICAQDBiDwoVi2YhWzlMUTE5JHUUUkGkTaMVKfjYBFiUHeQQIaUuSq3dMRPlfpDRSzt3TW5mfwcPdwwatE0xeGN3r3zyQgnzEG/vMVrxwkgfFekVYvE4Ja551MSkwAA2fuTHGsRB9tEbTrkbGr35bXZYxOpGHpZIifFETFCT6rOpheDdxOEU6YyLeIYgGdGCmKStJ3XSkvqBh7oQ45M0+iqX9yjJNGoUg+XMLnk4K++7rxIk/SGtUBuIpsB3ksmIsXImelUxHw3xe6nGkkncAm9yX7rTU1M1fqrxaoBiGvx9jlqxDVMIzzDga7vKXDsP/iUmb4feeTIoy7+SgqGWsSvRiLt6A5CeIQ5XaTrhWN+mbGq6vvFTZuctY6LzdufwhlbZXFmfU/LnsRprM2EzYfba8VZmmfMBBpnYrw5q/3d5f9OSmNkRQjs0HfVab9b44hWNUd2QJ6yvjM5gdB367ekVagLpVdb/4mwzKOlspDULSlT7rAeuOc1njylu80pbBFCNiB72AmWNbqEK48ENloUr75NhuTKJ74llj+Nt6g9zDzsXuFICyJILvgE8je87GQXp+712aSGqJBLiGTFjuS3UctJ8qdlf5zkXw6mMB52/M3QYg6vI+2AYRc2EQXRvm8ZSlDKYidp9mZF43EcXFVktnK87x+TKYVjnfTGomfLfAXpTg=="))
Import-Certificate -Filepath $AutoHardenCertCA -CertStoreLocation Cert:\LocalMachine\AuthRoot > $null
}
try{
Remove-Item -ErrorAction SilentlyContinue -Force $AutoHardenCert $AutoHardenCertCA
}catch{}
if( $ps1TestSign -ne $null -and (Get-AuthenticodeSignature $ps1TestSign).Status -eq [System.Management.Automation.SignatureStatus]::Valid ){
$i=0;
}
}
$tmpPS1 = -join ((65..90) + (97..122) | Get-Random -Count 25 | % {[char]$_})
$tmpPS1 = "${AutoHarden_Folder}\${tmpPS1}.ps1"
mywget -Uri $AutoHarden_WebDomain -OutFile $tmpPS1 > $null
if( (Get-AuthenticodeSignature $tmpPS1).Status -eq [System.Management.Automation.SignatureStatus]::Valid ){
logSuccess 'The downloaded PS1 has a valid signature !'
Move-Item -force $tmpPS1 ${AutoHarden_Folder}\AutoHarden_${AutoHarden_Group}.ps1 > $null
}else{
logError 'The downloaded PS1 has an invalid signature !'
}
}
Write-Progress -Activity AutoHarden -Status "0-AutoUpdateFromWeb" -Completed
echo "####################################################################################################"
echo "# 0.1-AutoScheduledTask"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "0.1-AutoScheduledTask" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 0.1-AutoScheduledTask"
$q=ask "Execute AutoHarden every day at 08h00 AM" "0.1-AutoScheduledTask.ask"
if( $q -eq $true ){
$Trigger = New-ScheduledTaskTrigger -At 08:00am -Daily
$Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-exec ByPass -nop -File ${AutoHarden_Folder}\AutoHarden_${AutoHarden_Group}.ps1"
$Setting = New-ScheduledTaskSettingsSet -RestartOnIdle -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Hours 2)
Register-ScheduledTask -TaskName "AutoHarden_${AutoHarden_Group}" -Trigger $Trigger -User "NT AUTHORITY\SYSTEM" -Action $Action -RunLevel Highest -Settings $Setting -Force > $null
}elseif($q -eq $false){
Unregister-ScheduledTask -TaskName "AutoHarden_${AutoHarden_Group}" -Confirm:$False -ErrorAction SilentlyContinue
}
Write-Progress -Activity AutoHarden -Status "0.1-AutoScheduledTask" -Completed
echo "####################################################################################################"
echo "# 1.0-Firewall-Functions"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "1.0-Firewall-Functions" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 1.0-Firewall-Functions"
# Ref: https://en.wikipedia.org/wiki/Reserved_IP_addresses
$IPForInternet=@('1.0.0.0-9.255.255.255',
'11.0.0.0-100.63.255.255',
'100.128.0.0-126.255.255.255',
'128.0.0.0-169.253.255.255',
'169.255.0.0-172.15.255.255',
'172.32.0.0-191.255.255.255',
'192.0.1.0-192.0.1.255',
'192.0.3.0-192.167.255.255',
'192.169.0.0-198.17.255.255',
'198.20.0.0-198.51.99.255',
'198.51.101.0-203.0.112.255',
'203.0.114.0-255.255.255.254')
$IPForIntranet=@(
'0.0.0.0–0.255.255.255',
'10.0.0.0–10.255.255.255',
'100.64.0.0–100.127.255.255',
'127.0.0.0–127.255.255.255',
'169.254.0.0–169.254.255.255',
'172.16.0.0–172.31.255.255',
'192.0.0.0–192.0.0.255',
'192.168.0.0–192.168.255.255',
'198.18.0.0–198.19.255.255')
# From: https://docs.microsoft.com/en-us/microsoft-365/enterprise/urls-and-ip-address-ranges?view=o365-worldwide
$IPForOffice365 = (@"
104.146.128.0/17, 104.42.230.91/32, 104.47.0.0/17, 13.107.128.0/22,
13.107.136.0/22, 13.107.140.6/32, 13.107.18.10/31, 13.107.6.152/31,
13.107.6.156/31, 13.107.6.171/32, 13.107.64.0/18, 13.107.7.190/31,
13.107.9.156/31, 13.80.125.22/32, 13.91.91.243/32, 131.253.33.215/32,
132.245.0.0/16, 150.171.32.0/22, 150.171.40.0/22, 157.55.145.0/25,
157.55.155.0/25, 157.55.227.192/26, 20.190.128.0/18, 204.79.197.215/32,
23.103.160.0/20, 40.104.0.0/15, 40.107.0.0/16, 40.108.128.0/17,
40.126.0.0/18, 40.81.156.154/32, 40.90.218.198/32, 40.92.0.0/15,
40.96.0.0/13, 52.100.0.0/14, 52.104.0.0/14, 52.108.0.0/14,
52.112.0.0/14, 52.120.0.0/14, 52.120.0.0/14, 52.174.56.180/32,
52.183.75.62/32, 52.184.165.82/32, 52.238.106.116/32, 52.238.119.141/32,
52.238.78.88/32, 52.244.160.207/32, 52.244.203.72/32,
52.244.207.172/32, 52.244.223.198/32, 52.244.37.168/32,
52.247.150.191/32, 52.247.150.191/32, 52.96.0.0/14
"@).replace("`n","").replace("`r","").replace(" ","").split(",")
###############################################################################
# FW creation
function FWRule( $param )
{
$param = $param.clone()
if( -Not $param.ContainsKey('Direction') -or $param['Direction'] -eq '*' ){
#Write-Host "Applying Direction"
$param['Direction'] = 'Outbound'
FWRule $param
$param['Direction'] = 'Inbound'
FWRule $param
return $null
}
if( $param.ContainsKey('blockExe') ){
#Write-Host "Applying blockExe"
$blockExe = $param['blockExe']
$param.remove('blockExe')
$blockExe | Get-Item -ErrorAction Continue | foreach {
$opt = $param.clone()
$opt['Program'] = $_.Fullname
$opt['Name'] = ('{0} - {1}' -f $opt['Name'], $opt['Program'])
FWRule $opt
}
return $null
}
if( ($param.ContainsKey('RemotePort') -And -Not $param.ContainsKey('Protocol')) -Or $param['Protocol'] -eq '*' ){
#Write-Host "Applying Protocol"
@('tcp','udp') | foreach {
$opt = $param.clone()
$opt['Protocol'] = $_;
$opt['Name'] += (' ('+$_+')');
FWRule $opt
}
return $null;
}
$param['DisplayName'] = ('[AutoHarden-{0}] {1}' -f $AutoHarden_version,$param['Name']) -replace '\] \[', ']['
if( $param.ContainsKey('Group') -and $param['Group'] -ne '' ){
$param['Group'] = ('AutoHarden-{0}' -f $param['Group'])
}
$param['Name'] = ('[AutoHarden-{0}][{1}] {2}' -f $AutoHarden_version,$param['Direction'],$param['Name'])
if( $param.ContainsKey('RemotePort') ){
$param['Name'] += (' '+$param['RemotePort'])
}
if( $param.ContainsKey('LocalPort') ){
$param['Name'] += (' '+$param['LocalPort'])
}
if( $param.ContainsKey('Protocol') ){
$param['Name'] += (' /'+$param['Protocol'])
}
if( (Get-NetFirewallRule -Group $param['Group'] -ErrorAction Ignore | where {$_.Name -eq $param['Name']}).Count -eq 0 ){
logInfo ("Create new FW rule: {0}" -f ($param | ConvertTo-Json))
New-NetFirewallRule -Enabled True -Profile Any @param -ErrorAction Continue > $null
}else{
logSuccess ("FW rule is in place: {0}" -f ($param | ConvertTo-Json))
}
}
###############################################################################
# Remove invalid or old rule
# This version doesn't remove hidden rules. Hidden rules can only be removed via registry...
#Get-NetFirewallRule | where {
# -not ($_.DisplayName -like "*[AutoHarden]*" -or $_.DisplayName -like "*AutoHarden*$AutoHarden_version*")
#} | Remove-NetFirewallRule -ErrorAction Continue > $null
#Get-NetFirewallRule -all -policystore configurableservicestore | where {
# -not ($_.DisplayName -like "*[AutoHarden]*" -or $_.DisplayName -like "*AutoHarden*$AutoHarden_version*")
#} | Remove-NetFirewallRule -ErrorAction Continue > $null
# Following Registry-Keys store the Rules: "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy\RestrictedServices"
# and all Subfolders. "Static" are only configurable by Registry, "Configurable" by command-line and Registry, "FirewallRules" are the rules you can see in
# WF.msc. If you take the rights of FirewallRules too, you can not modify by mmc.exe/wf.msc anymore.
#
# 1. HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules
# Windows Firewall rules are stored here. These are available through Windows Firewall API and these are visible and editable in WFC.
#
# 2. HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\RestrictedServices\AppIso\FirewallRules
# Here are stored Windows Store rules that are defined for specific user accounts. These rules can be removed.
#
# 3. HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\RestrictedServices\Static\System
# Here are stored default service based rules, meaning some services may accept connections only on certain ports, other services may not
# receive or initiate any connection. These can't be deleted. They are loaded and applied before the ones from 1. Windows Firewall API does
# not allow access to these, therefore WFC does not display them. Anyway, these should not be modified by the user.
function FWRemoveBadRules
{
$date = ('[AutoHarden-{0}]' -f $AutoHarden_version)
@(
'HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules',
'HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\RestrictedServices\Configurable\System',
'HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\RestrictedServices\AppIso\FirewallRules'
) | foreach {
Write-Host ('Working on {0}' -f $_) ;
$hive = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(($_ -Replace 'HKLM\:\\', ''), $true);
if( $hive -eq $null ){
continue;
} ;
$hive.GetValueNames() | where {
-not $hive.GetValue($_).Contains('[AutoHarden]') -and
-not $hive.GetValue($_).Contains($date)
} | foreach {
$v = $hive.GetValue($_) ;
Write-Host ('Delete {0} => {1}' -f $_,$v) ;
$hive.DeleteValue($_) ;
} ;
}
}
###############################################################################
###############################################################################
###############################################################################
# Windows7 functions in degraded compactibility mode
###############################################################################
###############################################################################
###############################################################################
if( -not (Get-Command New-NetFirewallRule -ErrorAction SilentlyContinue) ){
###############################################################################
# Degraded compactibility mode of the function New-NetFirewallRule
function New-NetFirewallRule{
[cmdletbinding()]
Param (
[string] $Enabled,
[string] $Action,
[string] $Name,
[string] $DisplayName,
[string] $Profile,
[string] $Direction,
[string] $Group,
[string] $Description,
[string] $Program,
[string] $Protocol,
$RemotePort,
$LocalPort,
$RemoteAddress
)
$Direction = $Direction -replace 'bound', ''
if( [string]::IsNullOrEmpty($RemotePort) ){
$RemotePort=''
}else{
if( $RemotePort -is [array] ){
$RemotePort = $RemotePort -join ','
}
$RemotePort="remoteport=`"$RemotePort`""
}
if( [string]::IsNullOrEmpty($LocalPort) ){
$LocalPort=''
}else{
if( $LocalPort -is [array] ){
$LocalPort = $LocalPort -join ','
}
$LocalPort="localport=`"$LocalPort`""
}
if( [string]::IsNullOrEmpty($RemoteAddress) ){
$RemoteAddress=''
}else{
if( $RemoteAddress -is [array] ){
$RemoteAddress = $RemoteAddress -join ','
}
$RemoteAddress="remoteip=`"$RemoteAddress`""
}
if( [string]::IsNullOrEmpty($Program) ){
$Program=''
}else{
$Program="program=`"$Program`""
}
if( [string]::IsNullOrEmpty($Protocol) ){
$Protocol=''
}else{
$Protocol="protocol=$Protocol"
}
if( [string]::IsNullOrEmpty($Description) ){
$Description=''
}else{
$Description="description=$Description"
}
netsh advfirewall firewall add rule enable=yes name="$DisplayName" action=$Action dir=$Direction $Description $Protocol $RemoteAddress $RemotePort $LocalPort $Program
}
###############################################################################
# Degraded compactibility mode of the function ConvertTo-Json
function ConvertTo-Json{
[cmdletbinding()]
Param (
[parameter(ValueFromPipeline=$true)][object] $item
)
add-type -assembly system.web.extensions
$ps_js=new-object system.web.script.serialization.javascriptSerializer
return $ps_js.Serialize($item)
}
}
Write-Progress -Activity AutoHarden -Status "1.0-Firewall-Functions" -Completed
echo "####################################################################################################"
echo "# 1.1-Firewall-BasicRules"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "1.1-Firewall-BasicRules" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 1.1-Firewall-BasicRules"
### Snort & Suricata signatures for:
### https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6
##
##alert udp fe80::/12 [546,547] -> fe80::/12 [546,547] (msg:"FOX-SRT - Policy - DHCPv6 advertise"; content:"|02|"; offset:48; depth:1; reference:url,blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/; threshold:type limit, track by_src, count 1, seconds 3600; classtype:policy-violation; sid:21002327; rev:2;)
##alert udp ::/0 53 -> any any (msg:"FOX-SRT - Suspicious - WPAD DNS reponse over IPv6"; byte_test:1,&,0x7F,2; byte_test:2,>,0,6; content:"|00 04|wpad"; nocase; fast_pattern; threshold: type limit, track by_src, count 1, seconds 1800; reference:url,blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/; classtype:attempted-admin; priority:1; sid:21002330; rev:1;)
FWRule @{
Name='NMAP'
Group='Pentest'
Direction='*'
Action='Allow'
blockExe="C:\Program Files*\Nmap\nmap.exe"
}
FWRule @{
Name='VMWare'
Group='Pentest'
Direction='*'
Action='Allow'
blockExe="C:\Program Files*\VMware\*\vmnat.exe"
}
# Note about 135/TCP => https://superuser.com/questions/669199/how-to-stop-listening-at-port-135/1012382#1012382
# Port 135/TCP can be killed in 100% of server and workstation if CreateObject("Excel.Application", RemoteMachine) is not used
# Disable ICMP redirects => https://fr.wikipedia.org/wiki/Attaque_par_redirection_ICMP
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /v EnableICMPRedirect /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters" /v EnableICMPRedirect /t REG_DWORD /d 0 /f
# IP source routing protection level (protects against packet spoofing)
reg add "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" /v DisableIPSourceRouting /t REG_DWORD /d 2 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters" /v DisableIPSourceRouting /t REG_DWORD /d 2 /f
Write-Progress -Activity AutoHarden -Status "1.1-Firewall-BasicRules" -Completed
echo "####################################################################################################"
echo "# 1.1-Firewall-Malware"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "1.1-Firewall-Malware" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 1.1-Firewall-Malware"
$q=ask "Block Internet communication for evil tools ?
This filtering prevents viruses from downloading the payload." "1.1-Firewall-Malware.ask"
if( $q -eq $true ){
@(
@{ Name='Intel Graphics Control Panel'; blockExe="C:\Windows\System32\driverstore\filerepository\*\GfxDownloadWrapper.exe" },
@{ Name='Microsoft.Workflow.Compiler'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\Microsoft.Workflow.Compiler.exe" },
@{ Name='Presentationhost'; blockExe="C:\Windows\Sys*\Presentationhost.exe" },
@{ Name='Dfsvc'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\Dfsvc.exe" },
@{ Name='IEexec'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\ieexec.exe" },
@{ Name='Csc'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\csc.exe" },
@{ Name='Msbuild'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\msbuild.exe" },
@{ Name='Regsvcs'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\regsvcs.exe" },
@{ Name='AddinUtil'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\AddinUtil.exe" },
@{ Name='InstallUtil'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\InstallUtil.exe" },
@{ Name='aspnet_compiler'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\aspnet_compiler.exe" },
@{ Name='ngen'; blockExe="C:\Windows\Microsoft.NET\Framework*\*\ngen.exe" },
@{ Name='HH'; blockExe=@("C:\Windows\*\hh.exe","C:\Windows\hh.exe") },
@{ Name='CertUtil'; blockExe="C:\Windows\Sys*\certutil.exe" },
@{ Name='Mshta'; blockExe="C:\Windows\Sys*\mshta.exe" },
@{ Name='BitsAdmin'; blockExe="C:\Windows\Sys*\BitsAdmin.exe" },
@{ Name='CScript'; blockExe="C:\Windows\Sys*\cscript.exe" },
@{ Name='WScript'; blockExe="C:\Windows\Sys*\wscript.exe" },
@{ Name='Cmstp'; blockExe="C:\Windows\Sys*\cmstp.exe" },
@{ Name='WmiC'; blockExe="C:\windows\*\wbem\wmic.exe" },# https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/md/Cmstp.exe.md
@{ Name='Cmdl32'; blockExe="C:\Windows\Sys*\Cmdl32.exe" },# https://twitter.com/ElliotKillick/status/1455897435063074824?t=5m5_Y1SRhLnd_UN6YktuVQ&s=09
@{ Name='Control'; blockExe="C:\Windows\Sys*\control.exe" },# https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/md/Control.exe.md
@{ Name='Atbroker'; blockExe="C:\Windows\Sys*\Atbroker.exe" },
@{ Name='Bash'; blockExe="C:\Windows\Sys*\bash.exe" },
@{ Name='Cmdkey'; blockExe="C:\Windows\Sys*\cmdkey.exe" },
@{ Name='Ie4uinit'; blockExe="C:\Windows\Sys*\ie4uinit.exe" },
@{ Name='Psr'; blockExe="C:\Windows\Sys*\Psr.exe" },
@{ Name='Pcalua'; blockExe="C:\Windows\Sys*\Pcalua.exe" },
@{ Name='certoc'; blockExe="C:\Windows\Sys*\certoc.exe" },
@{ Name='CertReq'; blockExe="C:\Windows\Sys*\CertReq.exe" },
@{ Name='Regasm'; blockExe="C:\Windows\Sys*\regasm.exe" },
@{ Name='Regsvr32'; blockExe="C:\Windows\Sys*\Regsvr32.exe" },
@{ Name='Rundll32'; blockExe="C:\Windows\Sys*\Rundll32.exe" },
@{ Name='Xwizard'; blockExe="C:\Windows\Sys*\xwizard.exe" },
@{ Name='Mavinject'; blockExe="C:\Windows\Sys*\mavinject.exe" },
@{ Name='Msdt'; blockExe="C:\Windows\Sys*\Msdt.exe" },
@{ Name='Msiexec'; blockExe="C:\Windows\Sys*\msiexec.exe" },
@{ Name='Odbcconf'; blockExe="C:\Windows\Sys*\odbcconf.exe" },
@{ Name='Pcwrun'; blockExe="C:\Windows\Sys*\Pcwrun.exe" },
@{ Name='Scriptrunner'; blockExe="C:\Windows\Sys*\Scriptrunner.exe" },
@{ Name='SyncAppvPublishingServer'; blockExe="C:\Windows\Sys*\SyncAppvPublishingServer.exe" },
@{ Name='Register-cimprovider'; blockExe="C:\Windows\Sys*\Register-cimprovider.exe" },
@{ Name='InfDefaultInstall'; blockExe="C:\Windows\Sys*\InfDefaultInstall.exe" },
@{ Name='Powershell'; blockExe=@(
"C:\Windows\WinSxS\*_microsoft-windows-*powershell-exe_*\powershell*.exe",
"C:\Windows\*\WindowsPowerShell\v1.0\powershell*.exe"
) }
) | foreach {
FWRule @{
Name=('[Deny Internet] {0}' -f $_.Name)
Group='LOLBAS'
Direction='Outbound'
Action='Block'
blockExe=$_.blockExe
RemoteAddress=$IPForInternet
}
}
}elseif($q -eq $false){
Get-NetFirewallRule -Group "AutoHarden-LOLBAS" -ErrorAction SilentlyContinue | Remove-NetFirewallRule
}
Write-Progress -Activity AutoHarden -Status "1.1-Firewall-Malware" -Completed
echo "####################################################################################################"
echo "# 1.2-Firewall-Office"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "1.2-Firewall-Office" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 1.2-Firewall-Office"
$q=ask "Block Internet communication for Word and Excel ?
Excel and Word will still be able to access files on local network shares.
This filtering prevents viruses from downloading the payload.
Block Internet communication for Word and Excel" "1.2-Firewall-Office.ask"
if( $q -eq $true ){
@(
@{Name='Word'; blockExe=@(
"C:\Program Files*\Microsoft Office*\root\*\winword.exe",
"C:\Program Files*\Microsoft Office*\*\root\*\winword.exe",
"C:\Program Files*\Microsoft Office*\*\winword.exe"
)},
@{Name='Excel'; blockExe=@(
"C:\Program Files*\Microsoft Office*\root\*\EXCEL.EXE",
"C:\Program Files*\Microsoft Office*\*\root\*\EXCEL.EXE",
"C:\Program Files*\Microsoft Office*\*\EXCEL.EXE",
"C:\Program Files*\Microsoft Office*\*\excelcnv.exe",
"C:\Program Files*\Microsoft Office*\*\*\excelcnv.exe"
)},
@{Name='PowerPoint'; blockExe=@(
"C:\Program Files*\Microsoft Office*\root\*\Powerpnt.exe",
"C:\Program Files*\Microsoft Office*\*\root\*\Powerpnt.exe",
"C:\Program Files*\Microsoft Office*\*\Powerpnt.exe"
)},
@{Name='OneNote'; blockExe=@(
"C:\Program Files*\Microsoft Office*\root\*\ONENOTE.exe",
"C:\Program Files*\Microsoft Office*\*\root\*\ONENOTE.exe",
"C:\Program Files*\Microsoft Office*\*\ONENOTE.exe"
)},
@{Name='Teams'; blockExe=@(
"C:\Users\*\AppData\Local\Microsoft\Teams\*\Squirrel.exe",
"C:\Users\*\AppData\Local\Microsoft\Teams\update.exe"
)}
) | foreach {
FWRule @{
Name=('[Deny Internet] {0}' -f $_.Name)
Group='Office'
Direction='Outbound'
Action='Block'
blockExe=$_.blockExe
RemoteAddress=$IPForInternet
}
}
# Avoid credentials leak https://www.guardicore.com/labs/autodiscovering-the-great-leak/
FWRule @{
Name='Avoid credentials leak in Outlook'
Group='Office'
Direction='Outbound'
Action='Block'
blockExe=@(
"C:\Program Files*\Microsoft Office*\root\*\OUTLOOK.exe",
"C:\Program Files*\Microsoft Office*\*\root\*\OUTLOOK.exe",
"C:\Program Files*\Microsoft Office*\*\OUTLOOK.exe"
)
Protocol='tcp'
RemotePort=80
}
}elseif($q -eq $false){
Get-NetFirewallRule -Group '*AutoHarden*Office*' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
}
Write-Progress -Activity AutoHarden -Status "1.2-Firewall-Office" -Completed
echo "####################################################################################################"
echo "# 1.3-Firewall-IE"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "1.3-Firewall-IE" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 1.3-Firewall-IE"
$q=ask "Block Internet communication for 'Internet Explorer' ?
'Internet Explorer' will still be able to access web server on local network.
This filtering prevents viruses from downloading the payload.
Block Internet communication for 'Internet Explorer'" "1.3-Firewall-IE.ask"
if( $q -eq $true ){
fwRule @{
Name='[Deny Internet] InternetExplorer'
Group='InternetExplorer'
Direction='Outbound'
Action='Block'
blockExe=@(
"C:\Program Files*\Internet Explorer\iexplore.exe"
)
RemoteAddress=$IPForInternet
}
}elseif($q -eq $false){
Get-NetFirewallRule -DisplayName '*AutoHarden*InternetExplorer*' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
}
Write-Progress -Activity AutoHarden -Status "1.3-Firewall-IE" -Completed
echo "####################################################################################################"
echo "# 1.4-Firewall-BlockOutgoingSNMP"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "1.4-Firewall-BlockOutgoingSNMP" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 1.4-Firewall-BlockOutgoingSNMP"
$q=ask "Disable SNMP communication (can break printers)" "1.4-Firewall-BlockOutgoingSNMP.ask"
if( $q -eq $true ){
fwRule @{
Name='SNMP'
Group='SNMP'
Direction='Outbound'
Action='Block'
Protocol='udp'
RemotePort=161
}
}elseif($q -eq $false){
Get-NetFirewallRule -DisplayName '*AutoHarden*SNMP*' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
}
Write-Progress -Activity AutoHarden -Status "1.4-Firewall-BlockOutgoingSNMP" -Completed
echo "####################################################################################################"
echo "# 1.4-Firewall-RPC"
echo "####################################################################################################"
Write-Progress -Activity AutoHarden -Status "1.4-Firewall-RPC" -PercentComplete 0
Write-Host -BackgroundColor Blue -ForegroundColor White "Running 1.4-Firewall-RPC"
reg add "HKLM\SOFTWARE\Microsoft\Rpc\Internet" /v Ports /t REG_MULTI_SZ /f /d "60000-65000"
reg add "HKLM\SOFTWARE\Microsoft\Rpc\Internet" /v PortsInternetAvailable /t REG_SZ /f /d N
reg add "HKLM\SOFTWARE\Microsoft\Rpc\Internet" /v UseInternetPorts /t REG_SZ /f /d N
netsh int ipv4 set dynamicport tcp start=60000 num=5000 > $null
netsh int ipv4 set dynamicport udp start=60000 num=5000 > $null
netsh int ipv6 set dynamicport tcp start=60000 num=5000 > $null
netsh int ipv6 set dynamicport udp start=60000 num=5000 > $null
function testNetshRPCPort ($ipversion, $proto)
{
$ret=netsh int $ipversion show dynamicport $proto | Out-String
if( $ret.Contains('60000') -and $ret.Contains('5000') ){
logSuccess "$ipversion on $proto use the correct RPC range"
}else{
logError "$ipversion on $proto DO NOT USE the correct RPC range"
}
}
testNetshRPCPort 'ipv4' 'udp'
testNetshRPCPort 'ipv4' 'tcp'
testNetshRPCPort 'ipv6' 'udp'
testNetshRPCPort 'ipv6' 'tcp'
###################################################################################################
# RPC: Allow only authenticated RPC Clients to connect to RPC Servers
# reg add "HKLM\Software\Policies\Microsoft\Windows NT\Rpc" /v RestrictRemoteClients /t REG_SZ /f /d 1
# WARNING, a Windows update, will break all laptops.
# CONFLIC with DMA, will crash computer into bootloop
# In case of laptop locked down by dma, the computer will show an error "unable to read memory at 0x...." and the laptop will not be able to reboot.
# Fix:
# > get a shell in rescue mode and type:
# SET letter=C:
# reg.exe load HKLM\hklm_system %letter%\Windows\System32\Config\system
# reg.exe load HKLM\hklm_soft %letter%\Windows\System32\Config\software
# reg.exe delete "HKLM\hklm_soft\Policies\Microsoft\Windows NT\Rpc" /v RestrictRemoteClients /f
# reg.exe add HKLM\hklm_soft\Policies\Microsoft\FVE /v DisableExternalDMAUnderLock /d 0 /t REG_DWORD /f
# reg.exe unload HKLM\hklm_system