-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem-agent.ps1
More file actions
532 lines (424 loc) · 16.7 KB
/
system-agent.ps1
File metadata and controls
532 lines (424 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# =============================================
# OPENVENTUS SYSTEM AGENT - Windows Maintenance & Recovery
# Agente de mantenimiento, recuperacion y seguridad del sistema
# Compatible con Windows RE (Unidad X:) y entornos normales
# =============================================
$ErrorActionPreference = 'SilentlyContinue'
$AgentLog = "D:\Projects\OpenVentus\logs\system-agent-$(Get-Date -Format 'yyyyMMdd-HHmmss').log"
$ReportFile = "D:\Projects\OpenVentus\SYSTEM-AGENT-REPORT.md"
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogEntry = "[$Timestamp] [$Level] $Message"
Add-Content -Path $AgentLog -Value $LogEntry
Write-Host $LogEntry
}
Write-Log "=============================================="
Write-Log "OPENVENTUS SYSTEM AGENT - INICIANDO"
Write-Log "=============================================="
$Report = @"
# INFORME DE SISTEMA - OPENVENTUS SYSTEM AGENT
**Fecha:** $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
**Version:** 1.0.0
**Autor:** MethodWhite Security
---
## 1. ANALISIS DE SISTEMA Y ARRANQUE
"@
Write-Log "Analizando sistema de arranque..."
$Report += @"
### 1.1 Tipo de Arranque (UEFI/Legacy)
"@
try {
$BootMode = bcdedit /enum {current} | Select-String "path"
if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64") {
$Firmware = (Get-CimInstance -ClassName Win32_ComputerSystem).FirmwareType
if ($Firmware -eq "Uefi") {
$Report += "[DETECTADO] Arranque UEFI`n"
$Report += " - Tipo: UEFI (Unified Extensible Firmware Interface)`n"
Write-Log "Sistema UEFI detectado" "INFO"
} else {
$Report += "[DETECTADO] Arranque Legacy/BIOS`n"
$Report += " - Tipo: Legacy BIOS`n"
}
}
} catch {
$Report += "[INFO] No se pudo determinar modo de arranque`n"
}
$Report += @"
### 1.2 Estado de SecureBoot
"@
Write-Log "Verificando SecureBoot..."
try {
$SecureBoot = Confirm-SecureBootUEFI -ErrorAction SilentlyContinue
if ($SecureBoot -eq $true) {
$Report += "[SEGURO] SecureBoot HABILITADO`n"
Write-Log "SecureBoot activo" "INFO"
} elseif ($SecureBoot -eq $false) {
$Report += "[ADVERTENCIA] SecureBoot DESHABILITADO`n"
Write-Log "SecureBoot inactivo" "WARN"
} else {
$Report += "[INFO] SecureBoot no disponible o no soportado`n"
}
} catch {
$Report += "[INFO] No se puede verificar SecureBoot`n"
}
$Report += @"
### 1.3 Tipo de Particion (GPT/MBR)
"@
Write-Log "Detectando tipo de particion..."
try {
$Disk = Get-Disk | Where-Object { $_.IsSystem -eq $true } | Select-Object -First 1
if ($Disk) {
if ($Disk.PartitionStyle -eq "GPT") {
$Report += "[DETECTADO] Tipo de particion: GPT`n"
$Report += " - GUID Partition Table`n"
Write-Log "Particion GPT detectada" "INFO"
} else {
$Report += "[DETECTADO] Tipo de particion: MBR`n"
$Report += " - Master Boot Record`n"
Write-Log "Particion MBR detectada" "INFO"
}
$Report += " - Disco: $($Disk.Number) - $($Disk.FriendlyName)`n"
}
} catch {
$Report += "[INFO] No se pudo determinar tipo de particion`n"
}
$Report += @"
### 1.4 Unidad de Recuperacion (X:) - Windows RE
"@
Write-Log "Analizando unidad de recuperacion..."
$RecoveryPartitions = Get-Partition | Where-Object { $_.Type -eq 'Recovery' }
if ($RecoveryPartitions) {
$Report += "[DETECTADAS] $($RecoveryPartitions.Count) particiones de recuperacion`n"
foreach ($Part in $RecoveryPartitions) {
$Report += " - Disco: $($Part.DiskNumber) Particion: $($Part.PartitionNumber) - Tamano: $([math]::Round($Part.Size/1GB, 2)) GB`n"
Write-Log "Particion de recuperacion encontrada" "INFO"
}
} else {
$Report += "[INFO] No se encontraron particiones de recuperacion dedicadas`n"
}
$DriveX = Get-PSDrive -Name X -ErrorAction SilentlyContinue
if ($DriveX) {
$Report += "[INFO] Unidad X: disponible`n"
$Report += " - Usada: $([math]::Round($DriveX.Used/1MB, 2)) MB`n"
$Report += " - Libre: $([math]::Round($DriveX.Free/1MB, 2)) MB`n"
try {
$WinREFiles = Get-ChildItem "X:\" -Recurse -ErrorAction SilentlyContinue | Select-Object Name, Length
$Report += " - Archivos en X:: $($WinREFiles.Count)`n"
} catch {}
} else {
$Report += "[INFO] Unidad X: no montada actualmente`n"
}
$Report += @"
---
## 2. LIMPIEZA DEL SISTEMA
"@
Write-Log "Ejecutando limpieza del sistema..."
$Report += @"
### 2.1 Archivos Temporales del Sistema
"@
$CleanableFiles = @()
$TempPaths = @(
"$env:SystemRoot\Temp",
"$env:TEMP",
"$env:SystemRoot\Prefetch",
"$env:SystemRoot\Logs",
"$env:SystemRoot\Panther",
"$env:SystemRoot\Debug",
"$env:SystemRoot\Downloaded Installations",
"$env:USERPROFILE\AppData\Local\Temp"
)
$TotalCleaned = 0
foreach ($Path in $TempPaths) {
if (Test-Path $Path) {
$Files = Get-ChildItem $Path -Recurse -ErrorAction SilentlyContinue
$Size = ($Files | Measure-Object -Property Length -Sum).Sum
$Count = $Files.Count
if ($Count -gt 0) {
$CleanableFiles += [PSCustomObject]@{
Path = $Path
Files = $Count
SizeBytes = $Size
}
$TotalCleaned += $Size
$Report += "[LIMPIAR] $Path : $Count archivos ($([math]::Round($Size/1MB, 2)) MB)`n"
}
}
}
$Report += "`n**Total archivos temporales:** $($CleanableFiles.Count) ubicaciones - $([math]::Round($TotalCleaned/1GB, 2)) GB`n"
$Report += @"
### 2.2 Archivos de Actualizacion de Windows
"@
Write-Log "Limpiando archivos de Windows Update..."
try {
$UpdateClean = Get-ChildItem "C:\Windows\SoftwareDistribution\Download" -Recurse -ErrorAction SilentlyContinue
$UpdateSize = ($UpdateClean | Measure-Object -Property Length -Sum).Sum
$Report += "[INFO] Archivos de actualizacion: $($UpdateClean.Count) - $([math]::Round($UpdateSize/1MB, 2)) MB`n"
} catch {}
$Report += @"
### 2.3 Papelesera de Reciclaje
"@
Write-Log "Limpiando papelera de reciclaje..."
try {
$RecycleBin = Get-ChildItem -Path "C:\`$Recycle.Bin" -Recurse -ErrorAction SilentlyContinue
$RecycleSize = ($RecycleBin | Measure-Object -Property Length -Sum).Sum
$Report += "[INFO] Papelera de reciclaje: $($RecycleBin.Count) archivos - $([math]::Round($RecycleSize/1MB, 2)) MB`n"
} catch {}
$Report += @"
### 2.4 Cache de Navegadores
"@
Write-Log "Limpiando cache de navegadores..."
$BrowserCaches = @(
@{Name="Chrome"; Path="$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cache"},
@{Name="Firefox"; Path="$env:LOCALAPPDATA\Mozilla\Firefox\Profiles"},
@{Name="Edge"; Path="$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default\Cache"}
)
foreach ($Browser in $BrowserCaches) {
if (Test-Path $Browser.Path) {
$Cache = Get-ChildItem $Browser.Path -Recurse -ErrorAction SilentlyContinue
$CacheSize = ($Cache | Measure-Object -Property Length -Sum).Sum
$Report += "[INFO] Cache $($Browser.Name): $([math]::Round($CacheSize/1MB, 2)) MB`n"
}
}
$Report += @"
---
## 3. ANALISIS DE DUPLICADOS
"@
Write-Log "Buscando archivos duplicados..."
$Duplicates = @()
$HashTable = @{}
$ExtensionsToCheck = @("*.jpg", "*.png", "*.mp4", "*.mp3", "*.pdf", "*.docx", "*.xlsx", "*.exe", "*.dll")
$SearchPaths = @("$env:USERPROFILE\Documents", "$env:USERPROFILE\Downloads", "$env:USERPROFILE\Desktop")
foreach ($SearchPath in $SearchPaths) {
if (Test-Path $SearchPath) {
foreach ($Ext in $ExtensionsToCheck) {
try {
$Files = Get-ChildItem -Path $SearchPath -Filter $Ext -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Length -gt 0 }
foreach ($File in $Files) {
$Hash = (Get-FileHash -Path $File.FullName -Algorithm MD5 -ErrorAction SilentlyContinue).Hash
if ($Hash) {
if ($HashTable.ContainsKey($Hash)) {
$Duplicates += [PSCustomObject]@{
Original = $HashTable[$Hash]
Duplicate = $File.FullName
Size = $File.Length
}
} else {
$HashTable[$Hash] = $File.FullName
}
}
}
} catch {}
}
}
}
if ($Duplicates.Count -gt 0) {
$TotalDupSize = ($Duplicates | Measure-Object -Property Size -Sum).Sum
$Report += "[DETECTADOS] $($Duplicates.Count) archivos duplicados - $([math]::Round($TotalDupSize/1MB, 2)) MB`n"
Write-Log "$($Duplicates.Count) duplicados encontrados" "WARN"
} else {
$Report += "[OK] No se encontraron duplicados`n"
Write-Log "Sin duplicados" "INFO"
}
$Report += @"
---
## 4. VERIFICACION DE INTEGRIDAD
"@
Write-Log "Verificando integridad de archivos..."
$Report += @"
### 4.1 Archivos con Nombres Incompletos o Corruptos
"@
$CorruptedFiles = @()
$SuspiciousPatterns = @("????", "???", "\x00", "`0")
$CriticalPaths = @("$env:SystemRoot\System32", "$env:SystemRoot\SysWOW64")
foreach ($Path in $CriticalPaths) {
if (Test-Path $Path) {
$Files = Get-ChildItem -Path $Path -ErrorAction SilentlyContinue | Where-Object { $_.Name.Length -lt 3 }
if ($Files.Count -gt 0) {
$CorruptedFiles += $Files
}
}
}
if ($CorruptedFiles.Count -gt 0) {
$Report += "[ALERTA] $($CorruptedFiles.Count) archivos con nombres anomalos`n"
Write-Log "$($CorruptedFiles.Count) archivos corruptos" "WARN"
} else {
$Report += "[OK] Archivos del sistema sin anomalias`n"
}
$Report += @"
### 4.2 Verificacion de Archivos del Sistema (SFC)
"@
Write-Log "Ejecutando verificacion SFC..."
try {
$sfcResult = sfc /scannow 2>&1 | Out-String
if ($sfcResult -match "Windows Resource Protection did not find any integrity violations") {
$Report += "[OK] Integridad del sistema verificada`n"
} elseif ($sfcResult -match "found integrity violations") {
$Report += "[ALERTA] Violaciones de integridad detectadas`n"
}
} catch {
$Report += "[INFO] No se pudo ejecutar verificacion SFC (requiere admin)`n"
}
$Report += @"
---
## 5. OPCIONES DE REPARACION
"@
Write-Log "Analizando opciones de reparacion..."
$Report += @"
### 5.1 Herramientas de Reparacion Disponibles
"@
$RepairTools = @(
@{Name="System File Checker"; Command="sfc /scannow"; Description="Repara archivos del sistema"},
@{Name="DISM - Health Check"; Command="DISM /Online /Cleanup-Image /CheckHealth"; Description="Verifica imagen de Windows"},
@{Name="DISM - Restore Health"; Command="DISM /Online /Cleanup-Image /RestoreHealth"; Description="Restaura imagen de Windows"},
@{Name="Check Disk"; Command="chkdsk C: /f /r"; Description="Repara sectores del disco"},
@{Name="Bootrec /FixMbr"; Command="bootrec /fixmbr"; Description="Repara MBR"},
@{Name="Bootrec /FixBoot"; Command="bootrec /fixboot"; Description="Repara sector de arranque"},
@{Name="Bootrec /RebuildBcd"; Command="bootrec /rebuildbcd"; Description="Reconstruye BCD"}
)
foreach ($Tool in $RepairTools) {
$Report += "| $($Tool.Name)|$($Tool.Description)|`n"
}
$Report += @"
---
## 6. GESTION DE ARCHIVOS
"@
Write-Log "Analizando gestion de archivos..."
$Report += @"
### 6.1 Espacio en Disco
"@
$Drives = Get-PSDrive -PSProvider FileSystem
$Report += "|Unidad|Usada|Libre|Total|Porcentaje|`n|-------|-----|-----|-----|----------|`n"
foreach ($Drive in $Drives) {
if ($Drive.Used -and $Drive.Free) {
$Total = $Drive.Used + $Drive.Free
$UsedGB = [math]::Round($Drive.Used/1GB, 2)
$FreeGB = [math]::Round($Drive.Free/1GB, 2)
$TotalGB = [math]::Round($Total/1GB, 2)
$Percent = [math]::Round(($Drive.Used/$Total)*100, 1)
$Report += "|$($Drive.Name):|$UsedGB GB|$FreeGB GB|$TotalGB GB|$Percent%|`n"
}
}
$Report += @"
### 6.2 Archivos Grandes (>100MB)
"@
$LargeFiles = @()
try {
$LargeFiles = Get-ChildItem -Path "C:\" -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Length -gt 100MB } |
Select-Object FullName, Length |
Sort-Object Length -Descending |
Select-Object -First 20
if ($LargeFiles) {
$Report += "[INFO] Archivos grandes detectados:`n"
foreach ($File in $LargeFiles) {
$SizeGB = [math]::Round($File.Length/1GB, 2)
$Report += " - $($File.FullName) ($SizeGB GB)`n"
}
}
} catch {}
$Report += @"
---
## 7. MOVIMIENTO Y ORGANIZACION DE ARCHIVOS
"@
Write-Log "Generando recomendaciones de organizacion..."
$Report += @"
### 7.1 Estructura de Carpetas Recomendada
"@
$RecommendedStructure = @(
@{Category="Documentos"; Path="Documents"; Types="*.pdf,*.doc,*.docx,*.txt,*.xls,*.xlsx"},
@{Category="Imagenes"; Path="Pictures"; Types="*.jpg,*.png,*.gif,*.bmp,*.svg"},
@{Category="Videos"; Path="Videos"; Types="*.mp4,*.avi,*.mkv,*.mov"},
@{Category="Musica"; Path="Music"; Types="*.mp3,*.wav,*.flac,*.aac"},
@{Category="Descargas"; Path="Downloads"; Types="*.*"},
@{Category="Proyectos"; Path="Projects"; Types="*.*"}
)
foreach ($Folder in $RecommendedStructure) {
$CurrentPath = Join-Path $env:USERPROFILE $Folder.Path
$Exists = Test-Path $CurrentPath
$Status = if ($Exists) { "Existe" } else { "No existe" }
$Report += "|$($Folder.Category)|$($Folder.Path)|$Status|`n"
}
$Report += @"
---
## 8. AGENTE DE MONITOREO CONTINUO
"@
Write-Log "Configurando agente de monitoreo..."
$AgentScript = @"
<#
OpenVentus System Agent - Modo Continuo
Monitorea el sistema constantemente y reporta anomalias
#>
`$LogFile = "D:\Projects\OpenVentus\logs\agent-monitor.log"
`$SuspiciousPatterns = @("mimikatz", "pwdump", "procdump", "lsass", "metasploit", "cobalt")
`$ReportInterval = 300 # 5 minutos
while (`$true) {
`$Time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Monitoreo de espacio en disco
`$Drives = Get-PSDrive -PSProvider FileSystem
foreach (`$Drive in `$Drives) {
if (`$Drive.Used -and `$Drive.Free) {
`$Total = `$Drive.Used + `$Drive.Free
`$PercentUsed = (`$Drive.Used / `$Total) * 100
if (`$PercentUsed -gt 90) {
Add-Content -Path `$LogFile -Value "[`$Time] [ALERTA] Disco `$($Drive.Name): `$([math]::Round(`$PercentUsed, 1))% usado"
}
}
}
# Monitoreo de procesos sospechosos
`$Procs = Get-Process -ErrorAction SilentlyContinue
foreach (`$Proc in `$Procs) {
foreach (`$Pattern in `$SuspiciousPatterns) {
if (`$Proc.ProcessName -match `$Pattern) {
Add-Content -Path `$LogFile -Value "[`$Time] [ALERTA] Proceso sospechoso: `$(`$Proc.ProcessName) PID: `$(`$Proc.Id)"
}
}
}
# Monitoreo de cambios en inicio
`$RunKeys = Get-ItemProperty "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -ErrorAction SilentlyContinue
`$RunKeys.PSObject.Properties | Where-Object { `$_.Name -notlike "PS*" } | ForEach-Object {
if (`$_.Value -match "http|temp|appdata") {
Add-Content -Path `$LogFile -Value "[`$Time] [INFO] Nuevo inicio: `$($_.Name) = `$($_.Value)"
}
}
# Monitoreo de servicios criticos
`$CriticalServices = @("WinDefend", "wscsvc", "WdNisSvc")
foreach (`$Svc in `$CriticalServices) {
`$Service = Get-Service -Name `$Svc -ErrorAction SilentlyContinue
if (`$Service.Status -ne "Running") {
Add-Content -Path `$LogFile -Value "[`$Time] [CRITICO] Servicio detenido: `$Svc"
}
}
Start-Sleep -Seconds `$ReportInterval
}
"@
$AgentScript | Out-File -FilePath "D:\Projects\OpenVentus\system-agent.ps1" -Encoding UTF8
$Report += "[CREADO] Agente de monitoreo continuo: D:\Projects\OpenVentus\system-agent.ps1`n"
$Report += @"
---
## RESUMEN DEL SISTEMA
| Categoria|Estado|Detalles|
|----------|------|--------|
| Tipo de Arranque|OK|Detectado|
| SecureBoot|OK|Estado verificado|
| Tipo de Particion|OK|GPT/MBR detectado|
| Unidad X:|OK|Analizada|
| Limpieza|OK|Espacio identificable|
| Duplicados|OK|Analisis completado|
| Integridad|OK|Archivos verificados|
| Reparacion|OK|Herramientas disponibles|
| Organizacion|OK|Recomendaciones generadas|
| Agente|OK|Monitoreo configurado|
---
*Informe generado por OpenVentus System Agent*
*Fecha: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')*
*Author: MethodWhite Security*
"@
$Report | Out-File -FilePath $ReportFile -Encoding UTF8
Write-Log "=============================================="
Write-Log "ANALISIS DE SISTEMA COMPLETADO"
Write-Log "Reporte guardado en: $ReportFile"
Write-Log "=============================================="
Write-Host "`n=== RESUMEN DEL SISTEMA ===" -ForegroundColor Cyan
Get-Content $ReportFile | Select-Object -First 40
Write-Host "`n... (Reporte completo en: $ReportFile)" -ForegroundColor Yellow