ShareAccessMonitor – Monitoring des accès fichiers avec PowerShell

Bonjour,

Aujourd’hui, encore un petit outils créé avec PowerShell Studio 2015 ! Il s’agit d’un petit programme qui a pour but d’indiquer par une icône (NotifyIcon) toute tentative d’accès à distance à nos fichiers (accès aux partages réseau).

ShareAccessScreen1

Ainsi, si un quelqu’un accède à notre PC par un partage réseau (ex: \\monpc\c$), le programme nous le fera savoir, et inscrira un événement dans le journal (Event Log). Cet événement permet d’identifier qui a accédé à quels fichiers/dossiers, quand il l’a fait, et depuis quelle machine.

Events

 

Pour ceux que cela intéresse, voici le code PowerShell utilisé :

# Checking if the mandatory Event Log exists, if not, creating it
$eventlog = get-eventlog -list | ? {$_.Log -eq "ShareAccessMonitor"}

if (!$eventlog)
{
    New-EventLog -LogName ShareAccessMonitor -Source scripts
}

# Log the script execution in the previously created Event Log
Write-EventLog -LogName ShareAccessMonitor -Source Scripts -Message "Script started" -EventId 1 -EntryType information

# Creating the Form
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

# Initializing the required objects and variables 
$form = New-Object System.Windows.Forms.form
$NotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$ContextMenu = New-Object System.Windows.Forms.ContextMenu
$MenuItem = New-Object System.Windows.Forms.MenuItem
$MenuItem2 = New-Object System.Windows.Forms.MenuItem
$MenuItem3 = New-Object System.Windows.Forms.MenuItem
$MenuItem4 = New-Object System.Windows.Forms.MenuItem
$MenuItem5 = New-Object System.Windows.Forms.MenuItem
$Timer = New-Object System.Windows.Forms.Timer
$iconOK = New-Object System.Drawing.Icon("RAS.ico")
$iconNOK = New-Object System.Drawing.Icon("ERROR.ico")

# Hide the form itself, as we only want to display the tray icon
$form.ShowInTaskbar = $false
$form.WindowState = "minimized"

# Initialize the Tray icon and its properties
$NotifyIcon.Icon =  $iconOK
$NotifyIcon.ContextMenu = $ContextMenu

# Loading the contextual menu (showed while right clicking on the icon)
$NotifyIcon.contextMenu.MenuItems.AddRange($MenuItem4) 
$NotifyIcon.contextMenu.MenuItems.AddRange($MenuItem3) 
$NotifyIcon.contextMenu.MenuItems.AddRange($MenuItem5)
$NotifyIcon.contextMenu.MenuItems.AddRange($MenuItem2)
$NotifyIcon.contextMenu.MenuItems.AddRange($MenuItem)

# At start, the icon shows the OK icon and the 'mouse hover' message bellow
$NotifyIcon.Visible = $True
$NotifyIcon.Text = "No share access detected"

# We want the script to run every 2 seconds
$Timer.Interval = 2000
$Timer.add_Tick({get-ShareAccess})
$Timer.start()

# This is the 'Exit' menu entry 
$MenuItem.Text = "Exit"
$MenuItem.add_Click({
	$Timer.stop()
	$NotifyIcon.Visible = $False
	$form.close()
})

# This is the 'About' menu entry
$MenuItem2.Text = "About"
$MenuItem2.add_Click({
    $wshell = New-Object -ComObject Wscript.Shell
    $wshell.Popup("ShareAccessMonitor - Version 1.0.0.1`r`n`r`nAuthor : Antoine DELRUE`r`nContact : antoine@delrue.me`r`nhttps://obilan.be", 0, "About ShareAccessMonitor",0x0)
})

# This is the 'EventViewer' menu entry 
$MenuItem3.Text = "Open Event Viewer"
$MenuItem3.add_Click({
    eventvwr /c:"ShareAccessMonitor"
})

# This is the 'Clear logs' menu entry 
$MenuItem4.Text = "Clear Event Log"
$MenuItem4.add_Click({
    Clear-EventLog -LogName ShareAccessMonitor
})

$MenuItem5.radiocheck = $true
$MenuItem5.text = "Disable notifications"
$MenuItem5.add_Click({
    if ($MenuItem5.checked -eq $true)
    {
        $MenuItem5.checked = $false
    }

    else
    {
        $MenuItem5.checked = $true
    }
})

# This main function will monitor the shared folders access and trigger the appropriate events
function Get-ShareAccess {

    function get-file {
        & net file | ? { $_ -match '^(\d+)\s+(.*)\s+(\w+)\s+(\d+)\s*$' } | % {
          New-Object -Type PSObject -Property @{
            'ID'    = $matches[1]
            'File'  = $matches[2].Trim()
            'User'  = $matches[3]
            'Locks' = $matches[4]
          }
        }
    }

    function Get-Session {
        & net session | ? { $_ -match '^(\S+)\s+(\w+)\s+(.*)\s+(\d+)\s+(\S+)\s*$' } | % {
            New-Object -Type PSObject -Property @{
            'Client' = $matches[1]
            'User'   = $matches[2]
            'Type'   = $matches[3].Trim()
            'Open'   = $matches[4]
            'Idle'   = $matches[5]
            }
        }
    }

    $session = Get-Session
    $files = get-file

    if ($session)
    {
        $source = $session.Client.split("\\")[2]
    }

    $result = @()

    foreach ($file in $files)
    {
		$Object = New-Object PSObject
		$Object | Add-Member -MemberType NoteProperty -Name "Source" -Value $source
		$Object | Add-Member -MemberType NoteProperty -Name "User" -Value $session.User
		$Object | Add-Member -MemberType NoteProperty -Name "Target" -Value ($file).File
		$result += $Object
    }

	if ($result)
    {
	    $NotifyIcon.Icon = $iconNOK
	    $notifyicon.text="Someone is accessing your files !"
        write-host "ALERT"

        $message = $result | Out-String
        write-host $message

        $test = get-eventlog -LogName ShareAccessMonitor -Source Scripts | ? {$_.Message -eq $message}
        if (!$test)
        {
            Write-EventLog -LogName ShareAccessMonitor -Source scripts -Message $message -EventId 2 -EntryType error
             if ($MenuItem3.checked -eq $false)
            {
                $NotifyIcon.ShowBalloonTip(3500,"Attention!", "Someone is accessing your files !",[system.windows.forms.ToolTipIcon]"Warning")
            }
        }
    }

else
    {
        $NotifyIcon.Icon = $iconOK
        $NotifyIcon.text = "No share access detected"
		write-host "ALL OK - No share access detected"
		$result=$null
    }
}

# Now let's run the script
get-ShareAccess
[void][System.Windows.Forms.Application]::Run($form)

 

Une fois l’installation effectuée, le programme sera accessible via le menu Démarrer.

Les fichiers sont installé sous : C:\Program Files (x86)\ShareAccessMonitor

Dans une prochaine version, je vais essayer d’inclure des alertes sur l’accès RDP, PowerShell Remoting, et également sur les accès refusés (logon failure).

J’espère que cela peut vous être utile, n’hésitez pas à commenter !

Télécharger ShareAccessMonitor.zip

Laisser un commentaire