-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdvanced PowerShell script.ps1
More file actions
1545 lines (1292 loc) · 67.3 KB
/
Advanced PowerShell script.ps1
File metadata and controls
1545 lines (1292 loc) · 67.3 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
<#
SCRIPT DE AUDITORIA DE SEGURIDAD EMPRESARIAL
VERSION 2.0 - PROFESIONAL
.SYNOPSIS
Script avanzado de auditoria de seguridad empresarial que recopila informacion
critica del sistema en multiples formatos para analisis forense y respuesta a incidentes.
.DESCRIPTION
Este script realiza una auditoria completa de seguridad incluyendo:
- Analisis de sistema de archivos y archivos modificados recientemente
- Analisis detallado de red y conexiones activas
- Analisis de procesos, servicios y tareas programadas
- Analisis de logs y eventos de seguridad criticos
- Analisis de configuraciones de seguridad
- Deteccion de indicadores de compromiso (IOCs)
- Analisis de persistencia y registro
Los resultados se exportan en JSON, CSV y TXT para analisis posterior.
.NOTES
Autor: Equipo de Ciberseguridad
Version: 2.0
Fecha: 2 de noviembre de 2025
Requisitos: PowerShell 5.1+, Windows 10/Server 2016+
Privilegios: Se recomienda ejecutar como Administrador para auditoria completa
.EXAMPLE
.\Auditoria_Empresarial_Completa.ps1
Ejecuta la auditoria completa y crea carpeta con timestamp en el directorio actual
.LINK
https://docs.microsoft.com/en-us/powershell/
https://attack.mitre.org/
#>
#Requires -Version 5.1
#
# SECCION 1: CONFIGURACION INICIAL Y VARIABLES GLOBALES
#
# Configuracion de ErrorAction por defecto
$ErrorActionPreference = "Continue"
# Variables globales del script
$Global:ScriptVersion = "2.0"
$Global:ScriptStartTime = Get-Date
$Global:TotalModules = 10
$Global:CurrentModule = 0
$Global:WarningsCount = 0
$Global:ErrorsCount = 0
$Global:ThreatsDetected = @()
# Puertos sospechosos comunes (C2, backdoors, malware)
$Global:SuspiciousPorts = @(4444, 5555, 6666, 7777, 8080, 8888, 9999, 31337, 12345, 1337, 6667)
# Extensiones de archivos sospechosos para analisis
$Global:SuspiciousExtensions = @("*.exe", "*.dll", "*.ps1", "*.bat", "*.vbs", "*.js", "*.hta", "*.scr")
# Binarios LOLBAS (Living Off the Land Binaries) frecuentemente abusados
$Global:LOLBASBinaries = @(
"certutil.exe", "regsvr32.exe", "mshta.exe", "bitsadmin.exe",
"regasm.exe", "regsvcs.exe", "msbuild.exe", "installutil.exe",
"rundll32.exe", "odbcconf.exe", "wmic.exe", "powershell.exe", "cmd.exe"
)
# Patrones maliciosos comunes en PowerShell
$Global:MaliciousPatterns = @(
'Invoke-Expression', 'IEX', 'Invoke-Mimikatz', 'Invoke-Obfuscation',
'Net.WebClient', 'DownloadString', 'DownloadFile', 'EncodedCommand',
'Hidden', 'New-Object', '-Enc', 'FromBase64String', 'Invoke-Shellcode',
'Invoke-ReflectivePEInjection', 'Get-GPPPassword', 'mimikatz'
)
#
# SECCION 2: FUNCIONES AUXILIARES
#
<#
.SYNOPSIS
Muestra el banner del script con informacion de version
#>
function Show-Banner {
Clear-Host
Write-Host "" -ForegroundColor Cyan
Write-Host " AUDITORIA DE SEGURIDAD EMPRESARIAL COMPLETA " -ForegroundColor Cyan
Write-Host " VERSION $Global:ScriptVersion - PROFESIONAL " -ForegroundColor Cyan
Write-Host "" -ForegroundColor Cyan
Write-Host ""
Write-Host " [INFO] Sistema: " -NoNewline -ForegroundColor Yellow
Write-Host "$env:COMPUTERNAME" -ForegroundColor White
Write-Host " [USER] Usuario: " -NoNewline -ForegroundColor Yellow
Write-Host "$env:USERNAME" -ForegroundColor White
Write-Host " [TIME] Fecha/Hora: " -NoNewline -ForegroundColor Yellow
Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor White
Write-Host " [PRIV] Privilegios: " -NoNewline -ForegroundColor Yellow
if (Test-Administrator) {
Write-Host "ADMINISTRADOR [OK]" -ForegroundColor Green
} else {
Write-Host "USUARIO NORMAL (Auditoria limitada)" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "" -ForegroundColor Gray
Write-Host ""
}
<#
.SYNOPSIS
Verifica si el script se esta ejecutando con privilegios de administrador
.OUTPUTS
Boolean - True si es administrador, False si no
#>
function Test-Administrator {
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
<#
.SYNOPSIS
Muestra una barra de progreso visual durante la ejecucion
.PARAMETER Activity
Descripcion de la actividad actual
.PARAMETER Status
Estado detallado de la operacion
.PARAMETER PercentComplete
Porcentaje de completitud (0-100)
#>
function Show-Progress {
param(
[string]$Activity,
[string]$Status,
[int]$PercentComplete
)
Write-Progress -Activity $Activity -Status $Status -PercentComplete $PercentComplete
}
<#
.SYNOPSIS
Actualiza el progreso basado en modulos completados
.PARAMETER ModuleName
Nombre del modulo que se esta ejecutando
#>
function Update-ModuleProgress {
param([string]$ModuleName)
$Global:CurrentModule++
$percentComplete = [math]::Round(($Global:CurrentModule / $Global:TotalModules) * 100)
Show-Progress -Activity "Ejecutando Auditoria de Seguridad" `
-Status "Modulo $Global:CurrentModule de $Global:TotalModules : $ModuleName" `
-PercentComplete $percentComplete
}
<#
.SYNOPSIS
Exporta datos en multiples formatos (JSON, CSV, TXT)
.PARAMETER Data
Datos a exportar (objeto de PowerShell)
.PARAMETER BasePath
Ruta base sin extension donde se guardaran los archivos
.PARAMETER Title
Titulo descriptivo para el reporte TXT
#>
function Export-MultiFormat {
param(
[Parameter(Mandatory=$true)]
$Data,
[Parameter(Mandatory=$true)]
[string]$BasePath,
[Parameter(Mandatory=$false)]
[string]$Title = "Reporte de Auditoria"
)
try {
# Validar que hay datos para exportar
if ($null -eq $Data -or ($Data -is [Array] -and $Data.Count -eq 0)) {
Write-Warning "No hay datos para exportar en: $BasePath"
return
}
# Exportar a JSON (formato estructurado para analisis automatizado)
$jsonPath = "$BasePath.json"
$Data | ConvertTo-Json -Depth 5 | Out-File $jsonPath -Encoding UTF8
# Exportar a CSV (formato tabular para Excel)
$csvPath = "$BasePath.csv"
if ($Data -is [Array]) {
$Data | Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
} else {
@($Data) | Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
}
# Exportar a TXT (formato legible para humanos)
$txtPath = "$BasePath.txt"
"" | Out-File $txtPath -Encoding UTF8
" $Title" | Out-File $txtPath -Append -Encoding UTF8
" Generado: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Out-File $txtPath -Append -Encoding UTF8
"" | Out-File $txtPath -Append -Encoding UTF8
"" | Out-File $txtPath -Append -Encoding UTF8
$Data | Format-Table -AutoSize | Out-File $txtPath -Append -Encoding UTF8 -Width 200
Write-Verbose "[OK] Exportado: $BasePath en formatos json, csv y txt"
} catch {
Write-Error "Error al exportar datos a $BasePath : $($_.Exception.Message)"
$Global:ErrorsCount++
}
}
<#
.SYNOPSIS
Registra una amenaza detectada durante la auditoria
.PARAMETER ThreatType
Tipo de amenaza (ej: "Proceso Sospechoso", "Conexion Maliciosa")
.PARAMETER Severity
Nivel de severidad (LOW, MEDIUM, HIGH, CRITICAL)
.PARAMETER Description
Descripcion detallada de la amenaza
.PARAMETER Details
Objeto con detalles adicionales de la amenaza
#>
function Add-ThreatDetection {
param(
[string]$ThreatType,
[ValidateSet("LOW", "MEDIUM", "HIGH", "CRITICAL")]
[string]$Severity,
[string]$Description,
$Details
)
$threat = [PSCustomObject]@{
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
ThreatType = $ThreatType
Severity = $Severity
Description = $Description
Details = $Details
}
$Global:ThreatsDetected += $threat
# Mostrar alerta en consola
$color = switch ($Severity) {
"CRITICAL" { "Red" }
"HIGH" { "Magenta" }
"MEDIUM" { "Yellow" }
"LOW" { "Cyan" }
}
Write-Host " [!] [$Severity] $ThreatType : $Description" -ForegroundColor $color
}
<#
.SYNOPSIS
Escribe un mensaje de log con timestamp
.PARAMETER Message
Mensaje a registrar
.PARAMETER Level
Nivel de log (INFO, WARNING, ERROR)
#>
function Write-AuditLog {
param(
[string]$Message,
[ValidateSet("INFO", "WARNING", "ERROR", "SUCCESS")]
[string]$Level = "INFO"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logMessage = "[$timestamp] [$Level] $Message"
# Agregar al log file global si existe
if ($Global:LogFile) {
$logMessage | Out-File $Global:LogFile -Append -Encoding UTF8
}
# Mostrar en consola con colores
$color = switch ($Level) {
"INFO" { "White" }
"SUCCESS" { "Green" }
"WARNING" { "Yellow" }
"ERROR" { "Red" }
}
Write-Host $logMessage -ForegroundColor $color
}
#
# SECCION 3: MODULOS DE AUDITORIA
#
<#
.SYNOPSIS
MODULO 1: Informacion General del Sistema
.DESCRIPTION
Recopila informacion basica del sistema operativo, hardware y configuracion
#>
function Get-SystemInformation {
Update-ModuleProgress -ModuleName "Informacion del Sistema"
Write-AuditLog "Iniciando recopilacion de informacion del sistema..." -Level INFO
try {
# Informacion basica del sistema
$computerInfo = Get-ComputerInfo -ErrorAction Stop
$systemInfo = [PSCustomObject]@{
Hostname = $env:COMPUTERNAME
Domain = $env:USERDOMAIN
OSName = $computerInfo.OsName
OSVersion = $computerInfo.OsVersion
OSBuild = $computerInfo.OsBuildNumber
OSArchitecture = $computerInfo.OsArchitecture
Manufacturer = $computerInfo.CsManufacturer
Model = $computerInfo.CsModel
TotalRAM_GB = [math]::Round($computerInfo.CsTotalPhysicalMemory / 1GB, 2)
Processors = $computerInfo.CsNumberOfProcessors
LogicalProcessors = $computerInfo.CsNumberOfLogicalProcessors
LastBootUpTime = $computerInfo.OsLastBootUpTime
InstallDate = $computerInfo.OsInstallDate
SystemUptime = (Get-Date) - $computerInfo.OsLastBootUpTime | Select-Object -ExpandProperty Days
TimeZone = $computerInfo.TimeZone
WindowsDirectory = $env:SystemRoot
CurrentUser = $env:USERNAME
IsAdmin = Test-Administrator
}
# Exportar resultados
$outputPath = Join-Path $Global:AuditPath "01_Sistema\informacion_sistema"
Export-MultiFormat -Data $systemInfo -BasePath $outputPath -Title "Informacion General del Sistema"
Write-AuditLog "[OK] Informacion del sistema recopilada correctamente" -Level SUCCESS
} catch {
Write-AuditLog "Error al recopilar informacion del sistema: $($_.Exception.Message)" -Level ERROR
$Global:ErrorsCount++
}
}
<#
.SYNOPSIS
MODULO 2: Analisis de Usuarios y Permisos
.DESCRIPTION
Analiza cuentas de usuario locales, grupos y asignaciones de privilegios
#>
function Get-UsersAndPermissions {
Update-ModuleProgress -ModuleName "Usuarios y Permisos"
Write-AuditLog "Analizando usuarios y permisos del sistema..." -Level INFO
try {
# Usuarios locales
$localUsers = Get-LocalUser | Select-Object Name, Enabled, PasswordRequired,
PasswordLastSet, LastLogon, AccountExpires, Description,
@{Name="PasswordAge_Days"; Expression={
if ($_.PasswordLastSet) {
((Get-Date) - $_.PasswordLastSet).Days
} else {
"Never"
}
}}
$outputPath = Join-Path $Global:AuditPath "02_Usuarios\usuarios_locales"
Export-MultiFormat -Data $localUsers -BasePath $outputPath -Title "Usuarios Locales del Sistema"
# Detectar usuarios con configuraciones inseguras
$localUsers | ForEach-Object {
if (-not $_.PasswordRequired) {
Add-ThreatDetection -ThreatType "Usuario sin contrasena" -Severity "HIGH" `
-Description "Usuario '$($_.Name)' no requiere contrasena" -Details $_
}
if ($_.Enabled -and $null -eq $_.LastLogon) {
Add-ThreatDetection -ThreatType "Usuario habilitado sin uso" -Severity "MEDIUM" `
-Description "Usuario '$($_.Name)' esta habilitado pero nunca ha iniciado sesion" -Details $_
}
}
# Administradores locales
$administrators = Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue |
Select-Object Name, ObjectClass, PrincipalSource
if ($administrators) {
$outputPath = Join-Path $Global:AuditPath "02_Usuarios\administradores_locales"
Export-MultiFormat -Data $administrators -BasePath $outputPath -Title "Miembros del Grupo Administradores"
Write-AuditLog " -> Administradores locales: $($administrators.Count)" -Level INFO
}
# Otros grupos privilegiados
$privilegedGroups = @("Remote Desktop Users", "Power Users", "Backup Operators")
foreach ($group in $privilegedGroups) {
try {
$members = Get-LocalGroupMember -Group $group -ErrorAction SilentlyContinue
if ($members) {
$groupName = $group -replace ' ', '_'
$outputPath = Join-Path $Global:AuditPath "02_Usuarios\grupo_$groupName"
Export-MultiFormat -Data $members -BasePath $outputPath -Title "Miembros del Grupo $group"
}
} catch {
Write-Verbose "Grupo '$group' no existe o no tiene miembros"
}
}
Write-AuditLog "[OK] Analisis de usuarios y permisos completado" -Level SUCCESS
} catch {
Write-AuditLog "Error en analisis de usuarios: $($_.Exception.Message)" -Level ERROR
$Global:ErrorsCount++
}
}
<#
.SYNOPSIS
MODULO 3: Analisis de Procesos y Servicios
.DESCRIPTION
Analiza procesos en ejecucion, servicios y detecta anomalias
#>
function Get-ProcessesAndServices {
Update-ModuleProgress -ModuleName "Procesos y Servicios"
Write-AuditLog "Analizando procesos y servicios en ejecucion..." -Level INFO
try {
# Procesos en ejecucion
$processes = Get-Process | Select-Object Name, Id, Path, Company, Product,
CPU, @{Name="Memory_MB"; Expression={[math]::Round($_.WorkingSet64/1MB, 2)}},
StartTime, SessionId,
@{Name="Signed"; Expression={
if ($_.Path) {
$sig = Get-AuthenticodeSignature $_.Path -ErrorAction SilentlyContinue
$sig.Status -eq 'Valid'
} else {
$false
}
}}
$outputPath = Join-Path $Global:AuditPath "03_Procesos\procesos_activos"
Export-MultiFormat -Data $processes -BasePath $outputPath -Title "Procesos en Ejecucion"
# Detectar procesos sin ruta (altamente sospechoso)
$processesNoPath = Get-Process | Where-Object {
$null -eq $_.Path -and $_.Name -ne "Idle" -and $_.Name -ne "System"
}
if ($processesNoPath) {
$outputPath = Join-Path $Global:AuditPath "03_Procesos\procesos_sin_ruta"
Export-MultiFormat -Data $processesNoPath -BasePath $outputPath -Title "[!] Procesos sin Ruta (SOSPECHOSO)"
$processesNoPath | ForEach-Object {
Add-ThreatDetection -ThreatType "Proceso sin ruta" -Severity "HIGH" `
-Description "Proceso '$($_.Name)' (PID: $($_.Id)) ejecutandose sin ruta de archivo" -Details $_
}
}
# Procesos con linea de comandos (detectar comandos sospechosos)
$processesWithCmdLine = Get-WmiObject Win32_Process | Select-Object ProcessId, Name, CommandLine,
@{Name="CreationDate"; Expression={$_.ConvertToDateTime($_.CreationDate)}}
$outputPath = Join-Path $Global:AuditPath "03_Procesos\procesos_con_comandos"
Export-MultiFormat -Data $processesWithCmdLine -BasePath $outputPath -Title "Procesos con Linea de Comandos"
# Detectar comandos codificados y patrones maliciosos
$processesWithCmdLine | ForEach-Object {
if ($_.CommandLine) {
$cmdLine = $_.CommandLine.ToLower()
# Detectar comando codificado en Base64
if ($cmdLine -match "-enc|-encodedcommand") {
Add-ThreatDetection -ThreatType "Comando codificado" -Severity "CRITICAL" `
-Description "Proceso '$($_.Name)' (PID: $($_.ProcessId)) usando comando codificado" -Details $_
}
# Detectar patrones maliciosos
foreach ($pattern in $Global:MaliciousPatterns) {
if ($cmdLine -match $pattern.ToLower()) {
Add-ThreatDetection -ThreatType "Patron malicioso detectado" -Severity "HIGH" `
-Description "Proceso '$($_.Name)' contiene patron '$pattern'" -Details $_
break
}
}
}
}
# Servicios del sistema
$services = Get-Service | Select-Object Name, DisplayName, Status, StartType,
@{Name="BinaryPath"; Expression={
(Get-WmiObject Win32_Service -Filter "Name='$($_.Name)'" -ErrorAction SilentlyContinue).PathName
}}
$outputPath = Join-Path $Global:AuditPath "03_Procesos\servicios"
Export-MultiFormat -Data $services -BasePath $outputPath -Title "Servicios del Sistema"
# Servicios automaticos en ejecucion
$autoServices = $services | Where-Object { $_.StartType -eq "Automatic" -and $_.Status -eq "Running" }
$outputPath = Join-Path $Global:AuditPath "03_Procesos\servicios_automaticos"
Export-MultiFormat -Data $autoServices -BasePath $outputPath -Title "Servicios Automaticos en Ejecucion"
Write-AuditLog " -> Total procesos: $($processes.Count)" -Level INFO
Write-AuditLog " -> Total servicios: $($services.Count)" -Level INFO
Write-AuditLog "[OK] Analisis de procesos y servicios completado" -Level SUCCESS
} catch {
Write-AuditLog "Error en analisis de procesos: $($_.Exception.Message)" -Level ERROR
$Global:ErrorsCount++
}
}
<#
.SYNOPSIS
MODULO 4: Analisis de Red y Conexiones
.DESCRIPTION
Analiza conexiones de red activas, puertos abiertos y configuracion de red
#>
function Get-NetworkAnalysis {
Update-ModuleProgress -ModuleName "Red y Conexiones"
Write-AuditLog "Analizando red y conexiones activas..." -Level INFO
try {
# Conexiones TCP activas con informacion de proceso
$tcpConnections = Get-NetTCPConnection | ForEach-Object {
$proc = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue
[PSCustomObject]@{
LocalAddress = $_.LocalAddress
LocalPort = $_.LocalPort
RemoteAddress = $_.RemoteAddress
RemotePort = $_.RemotePort
State = $_.State
PID = $_.OwningProcess
ProcessName = $proc.Name
ProcessPath = $proc.Path
Company = $proc.Company
}
}
$outputPath = Join-Path $Global:AuditPath "04_Red\conexiones_tcp"
Export-MultiFormat -Data $tcpConnections -BasePath $outputPath -Title "Conexiones TCP Activas"
# Conexiones establecidas (trafico activo)
$establishedConnections = $tcpConnections | Where-Object { $_.State -eq "Established" }
$outputPath = Join-Path $Global:AuditPath "04_Red\conexiones_establecidas"
Export-MultiFormat -Data $establishedConnections -BasePath $outputPath -Title "Conexiones Establecidas"
# Detectar conexiones a puertos sospechosos
$establishedConnections | ForEach-Object {
if ($_.RemotePort -in $Global:SuspiciousPorts) {
Add-ThreatDetection -ThreatType "Conexion a puerto sospechoso" -Severity "HIGH" `
-Description "Proceso '$($_.ProcessName)' conectado a puerto sospechoso $($_.RemotePort)" -Details $_
}
# Detectar conexiones externas de procesos del sistema
if ($_.ProcessName -in @('svchost', 'lsass', 'csrss', 'smss', 'wininit') -and
$_.RemoteAddress -notmatch "^(127\.0\.0\.1|::1|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.)") {
Add-ThreatDetection -ThreatType "Proceso del sistema con conexion externa" -Severity "CRITICAL" `
-Description "Proceso del sistema '$($_.ProcessName)' conectado a IP externa $($_.RemoteAddress)" -Details $_
}
}
# Puertos en escucha (superficie de ataque)
$listeningPorts = $tcpConnections | Where-Object { $_.State -eq "Listen" }
$outputPath = Join-Path $Global:AuditPath "04_Red\puertos_escucha"
Export-MultiFormat -Data $listeningPorts -BasePath $outputPath -Title "Puertos en Escucha"
# Endpoints UDP
$udpEndpoints = Get-NetUDPEndpoint | ForEach-Object {
$proc = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue
[PSCustomObject]@{
LocalAddress = $_.LocalAddress
LocalPort = $_.LocalPort
PID = $_.OwningProcess
ProcessName = $proc.Name
}
}
$outputPath = Join-Path $Global:AuditPath "04_Red\udp_endpoints"
Export-MultiFormat -Data $udpEndpoints -BasePath $outputPath -Title "Endpoints UDP"
# Cache DNS (dominios resueltos recientemente)
$dnsCache = Get-DnsClientCache -ErrorAction SilentlyContinue |
Select-Object Entry, Name, Data, TimeToLive, Type
if ($dnsCache) {
$outputPath = Join-Path $Global:AuditPath "04_Red\dns_cache"
Export-MultiFormat -Data $dnsCache -BasePath $outputPath -Title "Cache DNS"
}
# Configuracion de adaptadores de red
$networkAdapters = Get-NetAdapter | Select-Object Name, InterfaceDescription, Status,
MacAddress, LinkSpeed, MediaType
$outputPath = Join-Path $Global:AuditPath "04_Red\adaptadores_red"
Export-MultiFormat -Data $networkAdapters -BasePath $outputPath -Title "Adaptadores de Red"
Write-AuditLog " -> Conexiones TCP: $($tcpConnections.Count)" -Level INFO
Write-AuditLog " -> Conexiones establecidas: $($establishedConnections.Count)" -Level INFO
Write-AuditLog " -> Puertos en escucha: $($listeningPorts.Count)" -Level INFO
Write-AuditLog "[OK] Analisis de red completado" -Level SUCCESS
} catch {
Write-AuditLog "Error en analisis de red: $($_.Exception.Message)" -Level ERROR
$Global:ErrorsCount++
}
}
<#
.SYNOPSIS
MODULO 5: Analisis de Logs y Eventos de Seguridad
.DESCRIPTION
Analiza eventos criticos del sistema, logins fallidos y eventos de PowerShell
#>
function Get-SecurityEvents {
Update-ModuleProgress -ModuleName "Logs y Eventos de Seguridad"
Write-AuditLog "Analizando eventos de seguridad..." -Level INFO
try {
# Verificar si se ejecuta como administrador (necesario para leer Security log)
if (-not (Test-Administrator)) {
Write-AuditLog "[!] Ejecutando sin privilegios de administrador - Eventos de seguridad limitados" -Level WARNING
$Global:WarningsCount++
}
# Eventos de logins fallidos (Event ID 4625)
try {
$failedLogins = Get-WinEvent -FilterHashtable @{
LogName='Security';
ID=4625
} -MaxEvents 100 -ErrorAction SilentlyContinue | ForEach-Object {
[PSCustomObject]@{
TimeCreated = $_.TimeCreated
Username = $_.Properties[5].Value
Domain = $_.Properties[6].Value
SourceIP = $_.Properties[19].Value
FailureReason = $_.Properties[8].Value
SourceComputer = $_.Properties[13].Value
}
}
if ($failedLogins) {
$outputPath = Join-Path $Global:AuditPath "05_Eventos\logins_fallidos"
Export-MultiFormat -Data $failedLogins -BasePath $outputPath -Title "Intentos de Login Fallidos (Event ID 4625)"
# Detectar posibles ataques de fuerza bruta
$failedLoginsByUser = $failedLogins | Group-Object Username | Where-Object { $_.Count -ge 5 }
if ($failedLoginsByUser) {
$failedLoginsByUser | ForEach-Object {
Add-ThreatDetection -ThreatType "Posible ataque de fuerza bruta" -Severity "HIGH" `
-Description "Usuario '$($_.Name)' tiene $($_.Count) intentos fallidos de login" -Details $_
}
}
Write-AuditLog " -> Logins fallidos: $($failedLogins.Count)" -Level INFO
}
} catch {
Write-AuditLog "No se pudieron leer eventos de logins fallidos (requiere privilegios de admin)" -Level WARNING
$Global:WarningsCount++
}
# Eventos de bloqueo de cuenta (Event ID 4740)
try {
$accountLockouts = Get-WinEvent -FilterHashtable @{
LogName='Security';
ID=4740
} -MaxEvents 50 -ErrorAction SilentlyContinue | ForEach-Object {
[PSCustomObject]@{
TimeCreated = $_.TimeCreated
LockedAccount = $_.Properties[0].Value
CallerComputer = $_.Properties[1].Value
}
}
if ($accountLockouts) {
$outputPath = Join-Path $Global:AuditPath "05_Eventos\cuentas_bloqueadas"
Export-MultiFormat -Data $accountLockouts -BasePath $outputPath -Title "Bloqueos de Cuenta (Event ID 4740)"
Write-AuditLog " -> Cuentas bloqueadas: $($accountLockouts.Count)" -Level INFO
}
} catch {
Write-Verbose "No hay eventos de bloqueo de cuenta recientes"
}
# Eventos de PowerShell (ScriptBlock Logging - Event ID 4104)
try {
$psEvents = Get-WinEvent -FilterHashtable @{
LogName='Microsoft-Windows-PowerShell/Operational';
ID=4104
} -MaxEvents 200 -ErrorAction SilentlyContinue | Select-Object TimeCreated, Id,
@{Name="ScriptBlock"; Expression={$_.Properties[2].Value}}
if ($psEvents) {
$outputPath = Join-Path $Global:AuditPath "05_Eventos\powershell_scriptblock"
Export-MultiFormat -Data $psEvents -BasePath $outputPath -Title "PowerShell ScriptBlock Logging"
# Detectar comandos codificados o patrones maliciosos
$psEvents | ForEach-Object {
$scriptBlock = $_.ScriptBlock.ToLower()
if ($scriptBlock -match "-enc|-encodedcommand") {
Add-ThreatDetection -ThreatType "PowerShell comando codificado" -Severity "HIGH" `
-Description "Comando PowerShell codificado detectado" -Details $_
}
foreach ($pattern in $Global:MaliciousPatterns) {
if ($scriptBlock -match $pattern.ToLower()) {
Add-ThreatDetection -ThreatType "PowerShell patron malicioso" -Severity "HIGH" `
-Description "Patron malicioso '$pattern' detectado en PowerShell" -Details $_
break
}
}
}
Write-AuditLog " -> Eventos PowerShell: $($psEvents.Count)" -Level INFO
}
} catch {
Write-Verbose "No se pudieron leer eventos de PowerShell"
}
# Eventos de aplicacion (errores y warnings)
try {
$appEvents = Get-WinEvent -FilterHashtable @{
LogName='Application';
Level=1,2,3 # Critical, Error, Warning
} -MaxEvents 100 -ErrorAction SilentlyContinue | Select-Object TimeCreated, Level,
ProviderName, Id, Message
if ($appEvents) {
$outputPath = Join-Path $Global:AuditPath "05_Eventos\eventos_aplicacion"
Export-MultiFormat -Data $appEvents -BasePath $outputPath -Title "Eventos de Aplicacion (Criticos/Errores)"
}
} catch {
Write-Verbose "No se pudieron leer eventos de aplicacion"
}
# Eventos del sistema (errores y warnings)
try {
$systemEvents = Get-WinEvent -FilterHashtable @{
LogName='System';
Level=1,2,3
} -MaxEvents 100 -ErrorAction SilentlyContinue | Select-Object TimeCreated, Level,
ProviderName, Id, Message
if ($systemEvents) {
$outputPath = Join-Path $Global:AuditPath "05_Eventos\eventos_sistema"
Export-MultiFormat -Data $systemEvents -BasePath $outputPath -Title "Eventos del Sistema (Criticos/Errores)"
}
} catch {
Write-Verbose "No se pudieron leer eventos del sistema"
}
Write-AuditLog "[OK] Analisis de eventos de seguridad completado" -Level SUCCESS
} catch {
Write-AuditLog "Error en analisis de eventos: $($_.Exception.Message)" -Level ERROR
$Global:ErrorsCount++
}
}
<#
.SYNOPSIS
MODULO 6: Analisis de Archivos y Persistencia
.DESCRIPTION
Analiza archivos modificados recientemente, registro de persistencia y archivos sospechosos
#>
function Get-FilesAndPersistence {
Update-ModuleProgress -ModuleName "Archivos y Persistencia"
Write-AuditLog "Analizando archivos y mecanismos de persistencia..." -Level INFO
try {
# Archivos modificados en las ultimas 24 horas en directorios criticos
$criticalPaths = @(
"C:\Windows\System32",
"C:\Windows\Temp",
"C:\ProgramData",
"C:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
)
$recentFiles = @()
foreach ($path in $criticalPaths) {
if (Test-Path $path) {
$files = Get-ChildItem -Path $path -Force -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-1) } |
Select-Object FullName, LastWriteTime, Length, Attributes,
@{Name="SizeMB"; Expression={[math]::Round($_.Length/1MB, 2)}}
$recentFiles += $files
}
}
if ($recentFiles) {
$outputPath = Join-Path $Global:AuditPath "06_Archivos\archivos_modificados_24h"
Export-MultiFormat -Data $recentFiles -BasePath $outputPath -Title "Archivos Modificados (Ultimas 24 Horas)"
Write-AuditLog " -> Archivos modificados: $($recentFiles.Count)" -Level INFO
}
# Archivos ocultos en directorios de usuario
$hiddenFiles = Get-ChildItem -Path "C:\Users" -Hidden -Recurse -Force -ErrorAction SilentlyContinue -Include $Global:SuspiciousExtensions |
Select-Object FullName, Attributes, Length, CreationTime, LastWriteTime
if ($hiddenFiles) {
$outputPath = Join-Path $Global:AuditPath "06_Archivos\archivos_ocultos_sospechosos"
Export-MultiFormat -Data $hiddenFiles -BasePath $outputPath -Title "Archivos Ocultos Sospechosos"
$hiddenFiles | ForEach-Object {
Add-ThreatDetection -ThreatType "Archivo ejecutable oculto" -Severity "MEDIUM" `
-Description "Archivo oculto encontrado: $($_.FullName)" -Details $_
}
}
# Analisis de persistencia en registro - Run Keys
$runKeysPaths = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'
)
$runKeys = @()
foreach ($path in $runKeysPaths) {
if (Test-Path $path) {
$keys = Get-ItemProperty -Path $path -ErrorAction SilentlyContinue
if ($keys) {
$keys.PSObject.Properties | Where-Object { $_.Name -notmatch '^PS' } | ForEach-Object {
$runKeys += [PSCustomObject]@{
RegistryPath = $path
Name = $_.Name
Command = $_.Value
}
}
}
}
}
if ($runKeys) {
$outputPath = Join-Path $Global:AuditPath "06_Archivos\persistencia_run_keys"
Export-MultiFormat -Data $runKeys -BasePath $outputPath -Title "Persistencia en Run Keys del Registro"
Write-AuditLog " -> Entradas de Run Keys: $($runKeys.Count)" -Level INFO
# Detectar comandos sospechosos en Run Keys
$runKeys | ForEach-Object {
$command = $_.Command.ToLower()
if ($command -match "temp|appdata.*local.*temp|programdata") {
Add-ThreatDetection -ThreatType "Run Key sospechoso" -Severity "HIGH" `
-Description "Run Key ejecuta desde ubicacion temporal: $($_.Command)" -Details $_
}
if ($command -match "powershell|cmd|wscript|cscript") {
Add-ThreatDetection -ThreatType "Run Key con script" -Severity "MEDIUM" `
-Description "Run Key ejecuta script: $($_.Command)" -Details $_
}
}
}
# Tareas programadas (otra forma comun de persistencia)
$scheduledTasks = Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' } |
Select-Object TaskName, TaskPath, State,
@{Name="Actions"; Expression={($_.Actions | ForEach-Object { $_.Execute + " " + $_.Arguments }) -join "; "}}
$outputPath = Join-Path $Global:AuditPath "06_Archivos\tareas_programadas"
Export-MultiFormat -Data $scheduledTasks -BasePath $outputPath -Title "Tareas Programadas Activas"
# Verificar integridad del archivo HOSTS
$hostsFile = "C:\Windows\System32\drivers\etc\hosts"
if (Test-Path $hostsFile) {
$hostsContent = Get-Content $hostsFile
$hostsHash = (Get-FileHash $hostsFile -Algorithm SHA256).Hash
$hostsInfo = [PSCustomObject]@{
FilePath = $hostsFile
SHA256 = $hostsHash
LastModified = (Get-Item $hostsFile).LastWriteTime
LineCount = $hostsContent.Count
Content = $hostsContent -join "`n"
}
$outputPath = Join-Path $Global:AuditPath "06_Archivos\archivo_hosts"
Export-MultiFormat -Data $hostsInfo -BasePath $outputPath -Title "Archivo HOSTS del Sistema"
# Detectar entradas sospechosas en HOSTS
$hostsContent | ForEach-Object {
if ($_ -notmatch "^#" -and $_ -match "^\s*\d+\.\d+\.\d+\.\d+" -and $_ -notmatch "127\.0\.0\.1.*localhost") {
Add-ThreatDetection -ThreatType "Entrada sospechosa en HOSTS" -Severity "HIGH" `
-Description "Redireccion en archivo HOSTS: $_" -Details $_
}
}
}
Write-AuditLog "[OK] Analisis de archivos y persistencia completado" -Level SUCCESS
} catch {
Write-AuditLog "Error en analisis de archivos: $($_.Exception.Message)" -Level ERROR
$Global:ErrorsCount++
}
}
<#
.SYNOPSIS
MODULO 7: Configuraciones de Seguridad
.DESCRIPTION
Analiza politicas de seguridad, firewall, antivirus y configuraciones del sistema
#>
function Get-SecurityConfiguration {
Update-ModuleProgress -ModuleName "Configuraciones de Seguridad"
Write-AuditLog "Analizando configuraciones de seguridad..." -Level INFO
try {
# Politica de ejecucion de PowerShell
$executionPolicy = Get-ExecutionPolicy -List | Select-Object Scope, ExecutionPolicy
$outputPath = Join-Path $Global:AuditPath "07_Configuracion\powershell_execution_policy"
Export-MultiFormat -Data $executionPolicy -BasePath $outputPath -Title "Politica de Ejecucion de PowerShell"
# Perfiles de firewall
$firewallProfiles = Get-NetFirewallProfile | Select-Object Name, Enabled,
DefaultInboundAction, DefaultOutboundAction, LogAllowed, LogBlocked, LogFileName
$outputPath = Join-Path $Global:AuditPath "07_Configuracion\firewall_perfiles"
Export-MultiFormat -Data $firewallProfiles -BasePath $outputPath -Title "Perfiles del Firewall de Windows"
# Detectar firewall deshabilitado
$firewallProfiles | ForEach-Object {
if (-not $_.Enabled) {
Add-ThreatDetection -ThreatType "Firewall deshabilitado" -Severity "HIGH" `
-Description "Perfil de firewall '$($_.Name)' esta deshabilitado" -Details $_
}
}
# Reglas de firewall habilitadas
$firewallRules = Get-NetFirewallRule | Where-Object { $_.Enabled -eq $true } |
Select-Object DisplayName, Direction, Action, Profile,
@{Name="LocalPort"; Expression={(Get-NetFirewallPortFilter -AssociatedNetFirewallRule $_).LocalPort}},
@{Name="RemotePort"; Expression={(Get-NetFirewallPortFilter -AssociatedNetFirewallRule $_).RemotePort}},
@{Name="Protocol"; Expression={(Get-NetFirewallPortFilter -AssociatedNetFirewallRule $_).Protocol}}
$outputPath = Join-Path $Global:AuditPath "07_Configuracion\firewall_reglas"
Export-MultiFormat -Data $firewallRules -BasePath $outputPath -Title "Reglas del Firewall Habilitadas"
# Windows Defender (si esta disponible)
try {
$defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue
if ($defenderStatus) {
$defenderInfo = [PSCustomObject]@{
AntivirusEnabled = $defenderStatus.AntivirusEnabled
RealTimeProtectionEnabled = $defenderStatus.RealTimeProtectionEnabled
BehaviorMonitorEnabled = $defenderStatus.BehaviorMonitorEnabled
IoavProtectionEnabled = $defenderStatus.IoavProtectionEnabled
OnAccessProtectionEnabled = $defenderStatus.OnAccessProtectionEnabled
AntivirusSignatureLastUpdated = $defenderStatus.AntivirusSignatureLastUpdated
QuickScanAge = $defenderStatus.QuickScanAge
FullScanAge = $defenderStatus.FullScanAge
}
$outputPath = Join-Path $Global:AuditPath "07_Configuracion\windows_defender"
Export-MultiFormat -Data $defenderInfo -BasePath $outputPath -Title "Estado de Windows Defender"
# Detectar Defender deshabilitado
if (-not $defenderStatus.AntivirusEnabled) {
Add-ThreatDetection -ThreatType "Windows Defender deshabilitado" -Severity "CRITICAL" `
-Description "Windows Defender esta deshabilitado" -Details $defenderInfo
}
if (-not $defenderStatus.RealTimeProtectionEnabled) {
Add-ThreatDetection -ThreatType "Proteccion en tiempo real deshabilitada" -Severity "HIGH" `
-Description "La proteccion en tiempo real de Defender esta deshabilitada" -Details $defenderInfo
}
# Verificar actualizacion de firmas
if ($defenderStatus.AntivirusSignatureLastUpdated -lt (Get-Date).AddDays(-7)) {
Add-ThreatDetection -ThreatType "Firmas de antivirus desactualizadas" -Severity "MEDIUM" `
-Description "Las firmas de antivirus tienen mas de 7 dias de antigedad" -Details $defenderInfo
}
}
} catch {
Write-Verbose "Windows Defender no esta disponible o no se pudo consultar"
}
# Recursos compartidos de red
$networkShares = Get-SmbShare | Select-Object Name, Path, Description,
CurrentUsers, EncryptData,
@{Name="Permissions"; Expression={
(Get-SmbShareAccess -Name $_.Name | ForEach-Object { "$($_.AccountName):$($_.AccessRight)" }) -join "; "
}}
$outputPath = Join-Path $Global:AuditPath "07_Configuracion\recursos_compartidos"
Export-MultiFormat -Data $networkShares -BasePath $outputPath -Title "Recursos Compartidos de Red"
# Detectar recursos compartidos peligrosos
$networkShares | ForEach-Object {
if ($_.Name -match "^[A-Z]\$$" -and $_.Name -ne "ADMIN$" -and $_.Name -ne "IPC$") {
Add-ThreatDetection -ThreatType "Recurso compartido de disco" -Severity "MEDIUM" `
-Description "Disco compartido detectado: $($_.Name)" -Details $_
}