-
Notifications
You must be signed in to change notification settings - Fork 1
/
FIMwin.ps1
88 lines (71 loc) · 2.84 KB
/
FIMwin.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
Function Calculate-File-Hash($filepath) {
$filehash = Get-FileHash -Path $filepath -Algorithm SHA512
return $filehash
}
Function Erase-Baseline-If-Already-Exists() {
$baselineExists = Test-Path -Path .\baseline.txt
if ($baselineExists) {
# Delete it
Remove-Item -Path .\baseline.txt
}
}
Write-Host ""
Write-Host "What would you like to do?"
Write-Host ""
Write-Host " A) Collect new Baseline?"
Write-Host " B) Begin monitoring files with saved Baseline?"
Write-Host ""
$response = Read-Host -Prompt "Please enter 'A' or 'B'"
Write-Host ""
if ($response -eq "A".ToUpper()) {
# Delete baseline.txt if it already exists
Erase-Baseline-If-Already-Exists
# Calculate Hash from the target files and store in baseline.txt
# Collect all files in the target folder
$files = Get-ChildItem -Path .\Files
# For each file, calculate the hash, and write to baseline.txt
foreach ($f in $files) {
$hash = Calculate-File-Hash $f.FullName
"$($hash.Path)|$($hash.Hash)" | Out-File -FilePath .\baseline.txt -Append
}
}
elseif ($response -eq "B".ToUpper()) {
$fileHashDictionary = @{}
# Load file|hash from baseline.txt and store them in a dictionary
$filePathsAndHashes = Get-Content -Path .\baseline.txt
foreach ($f in $filePathsAndHashes) {
$fileHashDictionary.add($f.Split("|")[0],$f.Split("|")[1])
}
# Begin (continuously) monitoring files with saved Baseline
while ($true) {
Start-Sleep -Seconds 1
$files = Get-ChildItem -Path .\Files
# For each file, calculate the hash, and write to baseline.txt
foreach ($f in $files) {
$hash = Calculate-File-Hash $f.FullName
#"$($hash.Path)|$($hash.Hash)" | Out-File -FilePath .\baseline.txt -Append
# Notify if a new file has been created
if ($fileHashDictionary[$hash.Path] -eq $null) {
# A new file has been created!
Write-Host "$($hash.Path) has been created!" -ForegroundColor Green
}
else {
# Notify if a new file has been changed
if ($fileHashDictionary[$hash.Path] -eq $hash.Hash) {
# The file has not changed
}
else {
# File file has been compromised!, notify the user
Write-Host "$($hash.Path) has changed!!!" -ForegroundColor Yellow
}
}
}
foreach ($key in $fileHashDictionary.Keys) {
$baselineFileStillExists = Test-Path -Path $key
if (-Not $baselineFileStillExists) {
# One of the baseline files must have been deleted, notify the user
Write-Host "$($key) has been deleted!" -ForegroundColor DarkRed -BackgroundColor Gray
}
}
}
}