Powershell audits Active Directory with change alerts. Part 2

  • Tutorial

In the previous article, I published my first post on the hub In continuation of the topic I was going to write the second part.

In the comments to the first part, I casually mentioned that I expanded the functionality of monitoring scripts for connections to servers. In particular, he added notifications to the instant messaging service XMPP (Jabber), as well as writing the log to a separate text file.


Instant alert.


The good thing about instant alerts is that there is no need to constantly check mail for new messages - messages come in and let you know right away (Depending on the client’s settings, of course).
For myself, I made messages open on top of all windows. Of course, in order not to spam itself, such alerts are sent to critical events.
To the critical ones, I attributed: unsuccessful login attempts to domain controllers, unsuccessful login attempts to the VPN service (PPTP on WIndows). Also added this function to AD monitoring scripts. Because I have several people who have access to AD, then over time you can lose the thread of relevant data (something, once, someone deleted / moved / added, and you don’t know). And these messages will be just in time to know in real time about the changes.

Search for a solution

When I came up with the idea of ​​this kind of notification (given the fact that our organization uses the Jabber service quite actively), the first thing I did was hammer Powershell Jabber to Google . My very first link sent me to the site of Microsoft Technet Xaerg, a forum not unknown in the open spaces . The fact that I saw there could not but please me: “Did you know that the NetCmdlets snap-in, which includes cmdlets for working with a huge number of network protocols, is completely free for non-commercial use?”
And a list of available commands is provided. “This is what I need, and even for free !!!” - I thought, and was upset when I went to the developer’s site for this cmdlet snap-in, it turns out they don’t have a free version, they only have a trial version for 1 month, after which you need to request a key again. Only after that I drew attention to the date of the article, it turned out to be 2008 - a bit old :(.
For the sake of experiment I downloaded the trial version. Installed on the server on which I want to use alerts. Installation took place with a bang. New cmdlets immediately became available. Their syntax is quite simple and there were no problems with sending messages. For a while, I used this trial license once a month by re-registering it. But the very feeling that using the trial version depressed me, even more depressed the fact that it is necessary to register it every month for each server where it is installed. And since there were a little less than 30 servers in the infrastructure at that time, even the thought of re-registering at least once a month on all servers terrified me.
When it became more free over time, I decided to finish this idea. What was needed was a tool that enabled Powershell to send messages using the XMPP protocol. In this case, the conditions for using this product should be an important factor - it should be free.

I started tormenting Google again. And my efforts were not in vain. In one fine click, I got to a page with a utility that just allows you to send messages from the PS console using the XMPP protocol.
I was especially pleased with the inscription in the title of the page: Project Hosting for Open Source Software. What made me think that this product is free to use is just what I need.

Audit of unsuccessful attempts to enter the server, with notification by e-mail, Jabber service, and writing to the log file.


#Поиск последней записи в WIndowsEventLog на предмет неудачной попытки входа на сервер, и запись значения в переменную Body
$HostName = HostName
$Body=Get-WinEvent -FilterHashtable @{LogName="Security";ID=4625} | Select TimeCreated,@{n="User";e={([xml]$_.ToXml()).Event.EventData.Data | ? {$_.Name -eq "TargetUserName"} | %{$_.'#text'}}},@{n="ComputerName";e={([xml]$_.ToXml()).Event.EventData.Data | ? {$_.Name -eq "WorkstationName"}| %{$_.'#text'}}},@{n="IPAddress";e={([xml]$_.ToXml()).Event.EventData.Data | ? {$_.Name -eq "IPAddress"}| %{$_.'#text'}}} | select-object -first 1

#$BodyL - переменная для записи в текстовый лог-файл
$BodyL = "`n"+$Body.TimeCreated +"`t"+ $Body.User +"`t"+ $Body.ComputerName +"`t"+ $Body.IPAddress
#$Body - переменная для тела письма при отправке сообщения на почту и Jabber
$Body = "`nВремя: "+$Body.TimeCreated +"`nИмя пользователя: "+ $Body.User +"`nКомпьютер-источник: "+ $Body.ComputerName +"`nIP источника: "+ $Body.IPAddress

#$Theme - тема письма. $Hostname - имя сервера
$Theme = "Неудачный вход в систему на "+$hostname

#Отправка Jabber-сообщения

Add-PSSnapin poshxmpp
new-client -JabberId AUDIT@domain.ru -Password PASSWORD
Send-Message admin@domain.ru "$Theme      $Body"
$PoshXmppClient.Close()



#Описание переменных для отправки e-mail сообщения о инциденте
$Subject = "Неудачный вход в систему на "+$hostname

$Server = "mail.domain.ru" # SMTP Сервер
$From = "audit@domain.ru" # Адрес отправителя
$To = "admin@domain.ru" # Получатель
$pass = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("AUDIT" , $pass)
$encoding = [System.Text.Encoding]::UTF8
#Отправка e-mail
Send-MailMessage -From $From -To $To -SmtpServer $server -Body "$Theme `n$Body" -Subject $Subject -Credential $cred -Encoding $encoding
#Запись данных в текстовый лог-файл FaildConnect.txt
$BodyL | out-file "\ServerNameServerLogFilesServerFaildConnect.txt" -append


As I wrote in the first part , for the script to automatically execute, you need to put it in the task scheduler and configure the launch of this script when it detects an event with ID = 4625 in the Security log in EvenLog.

Recommendations


It is such scripts that work for me on the VPN server and on all domain controllers.
Now I always know when and who connects to the VPN, for example. Or when someone tries to pick up a password to access the server.
I also recommend hanging such a script on those services that are “lit up” on the Internet, for example, terminal access services.
A record in a separate file will allow you, in the future, to analyze the connection. By the way, the log can be opened through the spreadsheet editor (MS Excel or OO Calc) and already work with the log as a table (sort, filter, etc.).