diff --git a/LICENSE b/LICENSE index b03ff96..45ebd56 100644 --- a/LICENSE +++ b/LICENSE @@ -1,11 +1,28 @@ MIT License -Copyright (c) 2023 scriptos +Copyright © -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Name: Patrick Asmus (scriptos) +Email: support@techniverse.net +Website: https://www.patrick-asmus.de +Blog: https://www.cleveradmin.de -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +--- -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -Patrick Asmus | www.media-techport.de \ No newline at end of file +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 2b4b7b3..ee818cd 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,40 @@ -# Benachrichtigungsmail bei Anmeldung per Remote Desktop Protokoll +

+ + Techniverse Community + +

+

RDP Login Notifier

-**1. Skript: rdp-access-mail-notification.v3.ad.ps1** +

+ Versendet Benachrichtigungen (E-Mail und/oder Ntfy Push) wenn sich jemand per RDP auf einem Windows-System anmeldet. +

-- **Beschreibung:** Dieses Skript sendet eine E-Mail-Benachrichtigung an alle Mitglieder einer Sicherheitsgruppe, wenn sich jemand per Remote Desktop Protocol (RDP) auf einem Windows-System anmeldet. Es extrahiert Informationen aus dem Ereignisprotokoll und informiert die Benutzer über die Anmeldung, einschließlich Datum, Uhrzeit, Domäne, Benutzer und IP-Adresse des Clients. +
+ 🏰 Website + · + 📰 Community + · + 🐘 Mastodon + · + 💬 Support +
+

-**Voraussetzung:** -Folgendes Modul muss auf allen Systemen, auf denen das Script läuft, installiert sein: +## Schnellstart -Dies kann man einfach per Powershell machen: +1. [Voraussetzungen](docs/prerequisites.md) pruefen (RSAT-Modul bei AD-Modus installieren) +2. `rdp-access-notification.ps1`, `config.conf` und `rdp-access-notification.xml` nach `C:\scripts\rdp-login-notifier` kopieren +3. `config.conf` anpassen — siehe [Konfiguration](docs/configuration.md) +4. Task-Scheduler-Aufgabe einrichten — siehe [Task-Scheduler](docs/task-scheduler.md) - Install-WindowsFeature RSAT-AD-PowerShell +

+

+ +

- -**2. Skript: rdp-access-mail-notification.v3.local.ps1** - -- **Beschreibung:** Dieses Skript sendet eine E-Mail-Benachrichtigung, wenn sich jemand per Remote Desktop Protocol (RDP) auf einem Windows-System anmeldet. Es verwendet Informationen aus dem Ereignisprotokoll, um die Benutzer über die Anmeldung zu informieren, einschließlich Datum, Uhrzeit, Domäne, Benutzer und IP-Adresse des Clients. Die Benachrichtigung geht an eine vordefinierte Empfängeradresse. - - -Das ganze könnte dann so aussehen: - -![notification](/screenshots/notification.png) \ No newline at end of file +

+ + © Patrick Asmus · Techniverse Network · Lizenz + +

\ No newline at end of file diff --git a/ad-version/.archiv/rdp-access-mail-notification.v1.ps1 b/ad-version/.archiv/rdp-access-mail-notification.v1.ps1 deleted file mode 100644 index 1637b78..0000000 --- a/ad-version/.archiv/rdp-access-mail-notification.v1.ps1 +++ /dev/null @@ -1,92 +0,0 @@ -# Konfigurationsparameter -$SMTPServer = "smtp.media-techport.int" -$FromName = "Media-Techport.DE | Notification Service" -$FromEmail = "noreply@media-techport.de" -$SecurityGroupDN = "CN=GG-MailAT_RDP-Access,OU=Benachrichtigungsgruppen,OU=Benutzergruppen,DC=media-techport,DC=int" - -# Überwachung der Ereignisprotokolle -$EventLogName = "Security" -$EventID = 1149 # Event ID für Anmeldungen - -# Filter für Ereignisse -$FilterXML = @" - - - - - -"@ - -# Funktion zum Senden von E-Mails -function Send-Email { - param( - [string]$To, - [string]$Subject, - [string]$Message, - [string]$GivenName, - [string]$Surname - ) - $EmailBody = @" - - - - - - - -

Logo-Schwarz

-

Hallo $GivenName $Surname,

-

$Message

- - -"@ - - Send-MailMessage -SmtpServer $SMTPServer -From "$FromName <$FromEmail>" -To $To -Subject $Subject -Body $EmailBody -BodyAsHtml -Encoding "UTF8" -} - -# Hauptüberwachungsschleife -$events = Get-WinEvent -LogName $EventLogName -FilterXPath $FilterXML -foreach ($event in $events) { - $eventTime = $event.TimeCreated - $clientIP = $event.Properties[18].Value # IP-Adresse des Clients - $serverIP = $env:COMPUTERNAME # IP-Adresse des Servers - $user = $event.Properties[5].Value - $domain = $event.Properties[6].Value - - $userEmails = Get-ADGroupMember -Identity $SecurityGroupDN | Where-Object { $_.objectClass -eq "user" } | ForEach-Object { - $userDetails = Get-ADUser $_.DistinguishedName -Properties GivenName, Surname, EmailAddress - $GivenName = $userDetails.GivenName - $Surname = $userDetails.Surname - $EmailAddress = $userDetails.EmailAddress - [PSCustomObject]@{ - EmailAddress = $EmailAddress - GivenName = $GivenName - Surname = $Surname - } - } - - $emailMessage = @" -Es wurde eine Anmeldung per RDP auf dem Windows Server $serverIP registriert.

-Datum: $($eventTime.ToString('dd.MM.yyyy'))
-Uhrzeit: $($eventTime.ToString('HH:mm:ss'))
-Domäne: $domain
-Benutzer: $user
-IP-Adresse des Clients: $clientIP -"@ - foreach ($userDetail in $userEmails) { - Send-Email -To $userDetail.EmailAddress -Subject "RDP-Anmeldung auf $serverIP registriert" -Message $emailMessage -GivenName $userDetail.GivenName -Surname $userDetail.Surname - } -} diff --git a/ad-version/.archiv/rdp-access-mail-notification.v2.ps1 b/ad-version/.archiv/rdp-access-mail-notification.v2.ps1 deleted file mode 100644 index 4fea0bc..0000000 --- a/ad-version/.archiv/rdp-access-mail-notification.v2.ps1 +++ /dev/null @@ -1,52 +0,0 @@ -# Konfigurationsparameter -$SMTPServer = "smtp.media-techport.int" -$FromName = "Media-Techport.DE | Notification Service" -$FromEmail = "noreply@media-techport.de" -$SecurityGroupDN = "CN=GG-MailAT_RDP-Access,OU=Benachrichtigungsgruppen,OU=Benutzergruppen,DC=media-techport,DC=int" - -# Funktion zum Senden von E-Mails -function Send-Email { - param( - [string]$To, - [string]$Subject, - [string]$Message - ) - - Send-MailMessage -SmtpServer $SMTPServer -From "$FromName <$FromEmail>" -To $To -Subject $Subject -Body $Message -BodyAsHtml -Encoding "UTF8" -} - -# Parameter aus dem Ereignisprotokoll auslesen -$eventID = 1149 # Event ID für RDP-Anmeldungen -$eventLogName = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" - -$latestEvent = Get-WinEvent -LogName $eventLogName -FilterXPath "" | Select-Object -First 1 - -if ($latestEvent) { - $xml = [xml]$latestEvent.ToXml() - - if ($xml.Event.UserData) { - $user = $xml.Event.UserData.EventXML.Param1 - $domain = $xml.Event.UserData.EventXML.Param2 - $clientIP = $xml.Event.UserData.EventXML.Param3 - - $eventTime = $latestEvent.TimeCreated - $computerName = $latestEvent.MachineName - - $userEmails = Get-ADGroupMember -Identity $SecurityGroupDN | Where-Object { $_.objectClass -eq "user" } | ForEach-Object { - Get-ADUser $_.DistinguishedName -Properties EmailAddress | Select-Object -ExpandProperty EmailAddress - } - - $emailMessage = @" -Es wurde eine Anmeldung per RDP auf dem Windows Server $computerName registriert.

-Datum: $($eventTime.ToString('dd.MM.yyyy'))
-Uhrzeit: $($eventTime.ToString('HH:mm:ss'))
-Domäne: $domain
-Benutzer: $user
-IP-Adresse des Clients: $clientIP -"@ - - foreach ($email in $userEmails) { - Send-Email -To $email -Subject "RDP-Anmeldung auf $computerName registriert" -Message $emailMessage - } - } -} diff --git a/ad-version/Mailbenachrichtigung bei RDP Anmeldung (AD Version).xml b/ad-version/Mailbenachrichtigung bei RDP Anmeldung (AD Version).xml deleted file mode 100644 index 3301d03..0000000 Binary files a/ad-version/Mailbenachrichtigung bei RDP Anmeldung (AD Version).xml and /dev/null differ diff --git a/ad-version/rdp-access-mail-notification.v3.ad.ps1 b/ad-version/rdp-access-mail-notification.v3.ad.ps1 deleted file mode 100644 index 1151707..0000000 --- a/ad-version/rdp-access-mail-notification.v3.ad.ps1 +++ /dev/null @@ -1,92 +0,0 @@ -# Script Name: rdp-access-mail-notification.v3.ad.ps1 -# Beschreibung: Schickt allen Mitgliedern einer GG eine Mail, wenn sich jemand per RDP auf einem System anmeldet -# Aufruf: - -# Autor: Patrick Asmus -# Web: https://www.media-techport.de -# Git-Reposit.: https://git.media-techport.de/scriptos/private-script-collection.git -# Version: 3.1 -# Datum: 22.10.2023 -# Modifikation: Umzug ins neue Repo und damit verbundene Anpassungen -##################################################### - -# Konfigurationsparameter -$SMTPServer = "smtp.media-techport.int" -$FromName = "Media-Techport.DE | Notification Service" -$FromEmail = "noreply@media-techport.de" -$SecurityGroupDN = "CN=GG-MailAT_RDP-Access,OU=Benachrichtigungsgruppen,OU=Benutzergruppen,DC=media-techport,DC=int" -$LogoURL = "https://assets.media-techport.de/logos/main/LogoSchwarz.png" - -# Funktion zum Senden von E-Mails -function Send-Email { - param( - [string]$To, - [string]$Subject, - [string]$HTMLBody - ) - - $emailMessage = @" - - - - - - - $HTMLBody - - -"@ - - Send-MailMessage -SmtpServer $SMTPServer -From "$FromName <$FromEmail>" -To $To -Subject $Subject -Body $emailMessage -BodyAsHtml -Encoding "UTF8" -} - -# Parameter aus dem Ereignisprotokoll auslesen -$eventID = 1149 # Event ID für RDP-Anmeldungen -$eventLogName = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" - -$latestEvent = Get-WinEvent -LogName $eventLogName -FilterXPath "" | Select-Object -First 1 - -if ($latestEvent) { - $xml = [xml]$latestEvent.ToXml() - - if ($xml.Event.UserData) { - $user = $xml.Event.UserData.EventXML.Param1 - $domain = $xml.Event.UserData.EventXML.Param2 - $clientIP = $xml.Event.UserData.EventXML.Param3 - - $eventTime = $latestEvent.TimeCreated - $computerName = $latestEvent.MachineName - - $userEmails = Get-ADGroupMember -Identity $SecurityGroupDN | Where-Object { $_.objectClass -eq "user" } | ForEach-Object { - $userDetails = Get-ADUser $_.DistinguishedName -Properties GivenName, Surname, EmailAddress - $GivenName = $userDetails.GivenName - $Surname = $userDetails.Surname - $EmailAddress = $userDetails.EmailAddress - [PSCustomObject]@{ - EmailAddress = $EmailAddress - GivenName = $GivenName - Surname = $Surname - } - } - - foreach ($userDetails in $userEmails) { - $GivenName = $userDetails.GivenName - $Surname = $userDetails.Surname - $EmailAddress = $userDetails.EmailAddress - - $HTMLBody = @" - - - - - -

-

Hallo $GivenName $Surname,

-

Es wurde eine Anmeldung per RDP auf der Windows Maschine $computerName registriert.

Datum: $($eventTime.ToString('dd.MM.yyyy'))
Uhrzeit: $($eventTime.ToString('HH:mm:ss'))
Domäne: $domain
Benutzer: $user
IP-Adresse des Clients: $clientIP

- - -"@ - - Send-Email -To $EmailAddress -Subject "RDP-Anmeldung auf $computerName registriert" -HTMLBody $HTMLBody - } - } -} diff --git a/config.conf b/config.conf new file mode 100644 index 0000000..be68f5c --- /dev/null +++ b/config.conf @@ -0,0 +1,26 @@ +# RDP Access Notification - Konfiguration +# Dokumentation: docs/configuration.md + +# Modus: ad | local +MODE=ad + +# Benachrichtigungsmethoden: email, ntfy oder email,ntfy +NOTIFICATION_METHODS=email + +# E-Mail +SMTP_SERVER= +SMTP_FROM_NAME= +SMTP_FROM_EMAIL= + +# AD-Modus (nur bei MODE=ad) +AD_SECURITY_GROUP_DN= + +# Local-Modus (nur bei MODE=local, Format: Name,Email;Name,Email) +LOCAL_RECIPIENTS= + +# Ntfy (nur wenn ntfy in NOTIFICATION_METHODS) +NTFY_SERVER=https://ntfy.sh +NTFY_TOPIC= +NTFY_PRIORITY=3 +NTFY_TAGS=warning,computer +NTFY_AUTH_TOKEN= diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..401e467 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,92 @@ +# Konfiguration + +Alle Einstellungen werden in der `config.conf` vorgenommen, die im selben Verzeichnis wie das Script liegen muss. + +## Modus + +| Wert | Beschreibung | +|---|---| +| `MODE=ad` | Empfaenger werden aus einer AD-Sicherheitsgruppe gelesen | +| `MODE=local` | Empfaenger werden manuell in der Konfiguration definiert | + +**RSAT-Modul installieren (nur fuer AD-Modus):** + +```powershell +Install-WindowsFeature RSAT-AD-PowerShell +``` + +## Benachrichtigungsmethoden + +Kommasepariert — einzeln oder kombiniert: + +``` +NOTIFICATION_METHODS=email +NOTIFICATION_METHODS=ntfy +NOTIFICATION_METHODS=email,ntfy +``` + +## E-Mail + +| Key | Beschreibung | +|---|---| +| `SMTP_SERVER` | SMTP-Server Adresse | +| `SMTP_FROM_NAME` | Anzeigename des Absenders | +| `SMTP_FROM_EMAIL` | E-Mail-Adresse des Absenders | + +Beispiel: + +``` +SMTP_SERVER=smtp.example.com +SMTP_FROM_NAME=Notification Service +SMTP_FROM_EMAIL=noreply@example.com +``` + +## AD-Modus + +Nur relevant wenn `MODE=ad`. + +| Key | Beschreibung | +|---|---| +| `AD_SECURITY_GROUP_DN` | Distinguished Name der AD-Sicherheitsgruppe, deren Mitglieder benachrichtigt werden | + +Beispiel: + +``` +AD_SECURITY_GROUP_DN=CN=Gruppe,OU=Gruppen,DC=domain,DC=local +``` + +## Local-Modus + +Nur relevant wenn `MODE=local`. Mehrere Empfaenger mit Semikolon trennen. + +| Key | Beschreibung | +|---|---| +| `LOCAL_RECIPIENTS` | Empfaengerliste im Format `Name,Email;Name,Email` | + +Beispiel: + +``` +LOCAL_RECIPIENTS=Max Mustermann,max@example.com;Lisa Mueller,lisa@example.com +``` + +## Ntfy Push-Benachrichtigung + +Nur relevant wenn `ntfy` in `NOTIFICATION_METHODS` enthalten ist. + +| Key | Beschreibung | +|---|---| +| `NTFY_SERVER` | URL des Ntfy-Servers | +| `NTFY_TOPIC` | Ntfy-Topic | +| `NTFY_PRIORITY` | Prioritaet 1-5 (1=min, 3=default, 5=max) | +| `NTFY_TAGS` | Kommaseparierte Emoji-Tags | +| `NTFY_AUTH_TOKEN` | Bearer-Token (leer lassen wenn nicht benoetigt) | + +Beispiel: + +``` +NTFY_SERVER=https://ntfy.sh +NTFY_TOPIC=rdp-access +NTFY_PRIORITY=3 +NTFY_TAGS=warning,computer +NTFY_AUTH_TOKEN=tk_geheim123 +``` diff --git a/docs/prerequisites.md b/docs/prerequisites.md new file mode 100644 index 0000000..39272ed --- /dev/null +++ b/docs/prerequisites.md @@ -0,0 +1,51 @@ +# Voraussetzungen + +## PowerShell ExecutionPolicy + +Windows blockiert standardmaessig die Ausfuehrung von PowerShell-Scripts. Es gibt zwei Moeglichkeiten, das Script ausfuehrbar zu machen: + +**Variante 1 — Nur fuer die Task-Scheduler-Aufgabe (empfohlen):** + +In der Aufgabe wird `-ExecutionPolicy Bypass` als Argument uebergeben. Das betrifft nur diese eine Ausfuehrung und aendert keine systemweite Einstellung. Details dazu in der [Task-Scheduler-Dokumentation](task-scheduler.md). + +**Variante 2 — Systemweit erlauben:** + +```powershell +Set-ExecutionPolicy RemoteSigned -Scope LocalMachine +``` + +## RSAT ActiveDirectory PowerShell-Modul + +Das AD-Modul wird nur benoetigt, wenn `MODE=ad` in der `config.conf` gesetzt ist. Im Local-Modus (`MODE=local`) kann dieser Abschnitt uebersprungen werden. + +### Windows Server + +```powershell +Install-WindowsFeature RSAT-AD-PowerShell +``` + +Ein Neustart ist in der Regel nicht erforderlich. + +### Windows Client (Windows 10 / 11 Pro oder Enterprise) + +```powershell +Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 +``` + +Alternativ ueber DISM: + +```cmd +DISM /Online /Add-Capability /CapabilityName:Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 +``` + +Nach der Installation pruefen, ob das Modul verfuegbar ist: + +```powershell +Get-Module -ListAvailable -Name ActiveDirectory +``` + +### Wichtige Hinweise zum AD-Modus + +- Das Zielsystem muss Mitglied der Domaene sein. +- Das Script laeuft als `SYSTEM` (S-1-5-18) und nutzt das Computerkonto fuer AD-Abfragen. Dafuer sind keine separaten Credentials noetig. +- Die Windows Home-Edition unterstuetzt weder RDP-Host noch RSAT und ist daher nicht kompatibel. diff --git a/docs/task-scheduler.md b/docs/task-scheduler.md new file mode 100644 index 0000000..94c63c5 --- /dev/null +++ b/docs/task-scheduler.md @@ -0,0 +1,67 @@ +# Task-Scheduler einrichten + +Die Aufgabe wird durch das Windows-Event **1149** im Log `Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational` ausgeloest. Dieses Event wird bei jeder erfolgreichen RDP-Anmeldung geschrieben. + +## Variante 1 — XML importieren (empfohlen) + +Die mitgelieferte Datei `rdp-access-notification.xml` kann direkt importiert werden: + +**Per PowerShell:** + +```powershell +Register-ScheduledTask -Xml (Get-Content "C:\scripts\rdp-access-notification.xml" -Raw) -TaskName "RDP Access Notification" +``` + +**Per Aufgabenplanung (GUI):** + +1. Aufgabenplanung oeffnen (`taskschd.msc`) +2. Aktion > Aufgabe importieren +3. Die Datei `rdp-access-notification.xml` auswaehlen +4. Bei Bedarf den Pfad zum Script unter *Aktionen* anpassen + +## Variante 2 — Manuell anlegen + +### Allgemein + +| Einstellung | Wert | +|---|---| +| Name | `RDP Access Notification` | +| Ausfuehren als | `SYSTEM` | +| Unabhaengig von der Benutzeranmeldung ausfuehren | Ja | +| Mit hoechsten Privilegien ausfuehren | Nein | + +### Trigger + +| Einstellung | Wert | +|---|---| +| Trigger-Typ | Bei einem Ereignis | +| Protokoll | `Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational` | +| Quelle | `Microsoft-Windows-TerminalServices-RemoteConnectionManager` | +| Ereignis-ID | `1149` | + +### Aktion + +| Einstellung | Wert | +|---|---| +| Programm/Script | `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe` | +| Argumente | `-ExecutionPolicy Bypass -File "C:\scripts\rdp-access-notification.ps1"` | + +Der Parameter `-ExecutionPolicy Bypass` sorgt dafuer, dass das Script auch ohne systemweite Aenderung der ExecutionPolicy ausgefuehrt wird. Er gilt nur fuer diesen einen Prozess. + +### Einstellungen + +| Einstellung | Wert | +|---|---| +| Aufgabe bei Bedarf starten | Ja | +| Aufgabe beenden, falls laenger als | 72 Stunden | +| Nicht starten, falls im Akkubetrieb | Nein | + +## Aufgabe testen + +Nach dem Anlegen kann die Aufgabe manuell ausgeloest werden: + +```powershell +Start-ScheduledTask -TaskName "RDP Access Notification" +``` + +Oder im Aufgabenplaner per Rechtsklick > *Ausfuehren*. diff --git a/local-version/Mailbenachrichtigung bei RDP Anmeldung (Local Version).xml b/local-version/Mailbenachrichtigung bei RDP Anmeldung (Local Version).xml deleted file mode 100644 index 671034c..0000000 Binary files a/local-version/Mailbenachrichtigung bei RDP Anmeldung (Local Version).xml and /dev/null differ diff --git a/local-version/rdp-access-mail-notification.v3.local.ps1 b/local-version/rdp-access-mail-notification.v3.local.ps1 deleted file mode 100644 index a2e62b5..0000000 --- a/local-version/rdp-access-mail-notification.v3.local.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -# Script Name: rdp-access-mail-notification.v3.local.ps1 -# Beschreibung: Versendet eine Mail, wenn sich jemand per RDP auf einem System anmeldet -# Aufruf: - -# Autor: Patrick Asmus -# Web: https://www.media-techport.de -# Git-Reposit.: https://git.media-techport.de/scriptos/private-script-collection.git -# Version: 3.1 -# Datum: 22.10.2023 -# Modifikation: Umzug ins neue Repo und damit verbundene Anpassungen -##################################################### - -# Konfigurationsparameter -$SMTPServer = "smtp.media-techport.int" -$FromName = "Media-Techport.DE | Notification Service" -$FromEmail = "noreply@media-techport.de" -$LogoURL = "https://assets.media-techport.de/logos/main/LogoSchwarz.png" -$ManualRecipient = "system@media-techport.de" - -# Funktion zum Senden von E-Mails -function Send-Email { - param( - [string]$To, - [string]$Subject, - [string]$HTMLBody - ) - - $emailMessage = @" - - - - - - - $HTMLBody - - -"@ - - Send-MailMessage -SmtpServer $SMTPServer -From "$FromName <$FromEmail>" -To $To -Subject $Subject -Body $emailMessage -BodyAsHtml -Encoding "UTF8" -} - -# Parameter aus dem Ereignisprotokoll auslesen -$eventID = 1149 # Event ID für RDP-Anmeldungen -$eventLogName = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" - -$latestEvent = Get-WinEvent -LogName $eventLogName -FilterXPath "" | Select-Object -First 1 - -if ($latestEvent) { - $xml = [xml]$latestEvent.ToXml() - - if ($xml.Event.UserData) { - $user = $xml.Event.UserData.EventXML.Param1 - $domain = $xml.Event.UserData.EventXML.Param2 - $clientIP = $xml.Event.UserData.EventXML.Param3 - - $eventTime = $latestEvent.TimeCreated - $computerName = $latestEvent.MachineName - - $HTMLBody = @" - - - - - -

-

Hallo Patrick Asmus,

-

Es wurde eine Anmeldung per RDP auf der Windows Maschine $computerName registriert.

Datum: $($eventTime.ToString('dd.MM.yyyy'))
Uhrzeit: $($eventTime.ToString('HH:mm:ss'))
Domäne: $domain
Benutzer: $user
IP-Adresse des Clients: $clientIP

- - -"@ - - Send-Email -To $ManualRecipient -Subject "RDP-Anmeldung auf $computerName registriert" -HTMLBody $HTMLBody - } -} diff --git a/rdp-access-notification.ps1 b/rdp-access-notification.ps1 new file mode 100644 index 0000000..f287256 --- /dev/null +++ b/rdp-access-notification.ps1 @@ -0,0 +1,225 @@ +# Script Name: rdp-access-notification.ps1 +# Beschreibung: Versendet Benachrichtigungen (E-Mail / Ntfy) bei RDP-Anmeldung +# Autor: Patrick Asmus +# Web: https://www.patrick-asmus.de +# Git-Reposit.: https://git.techniverse.net/scriptos/rdp-access-mailbenachrichtigung.git +# Version: 4.0 +# Datum: 26.04.2026 +# Modifikation: Zusammenfuehrung AD/Local, Config-Datei, Ntfy-Support +##################################################### + +$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +$configPath = Join-Path $scriptDir "config.conf" + +if (-not (Test-Path $configPath)) { + Write-Error "Konfigurationsdatei nicht gefunden: $configPath" + exit 1 +} + +# --- Config parsen --- + +$conf = @{} +foreach ($line in Get-Content -Path $configPath) { + $line = $line.Trim() + if ($line -eq "" -or $line.StartsWith("#")) { continue } + $parts = $line -split "=", 2 + if ($parts.Count -eq 2) { + $conf[$parts[0].Trim()] = $parts[1].Trim() + } +} + +# --- Funktionen --- + +function Send-Email { + param( + [string]$To, + [string]$RecipientName, + [string]$Subject, + [string]$ComputerName, + [string]$EventDate, + [string]$EventTime, + [string]$Domain, + [string]$User, + [string]$ClientIP + ) + + $htmlBody = @" + + + + + + + +
+
RDP-Zugriff erkannt
+
+

Hallo $RecipientName,

+

auf der Windows-Maschine $ComputerName wurde eine RDP-Anmeldung registriert.

+ + + + + + +
Datum$EventDate
Uhrzeit$EventTime
Domäne$Domain
Benutzer$User
IP-Adresse des Clients$ClientIP
+
+ +
+ + +"@ + + if (-not $To) { + Write-Warning "Kein Empfaenger fuer E-Mail (Name: $RecipientName) - uebersprungen" + return + } + + try { + Send-MailMessage ` + -SmtpServer $conf["SMTP_SERVER"] ` + -From "$($conf["SMTP_FROM_NAME"]) <$($conf["SMTP_FROM_EMAIL"])>" ` + -To $To ` + -Subject $Subject ` + -Body $htmlBody ` + -BodyAsHtml ` + -Encoding ([System.Text.Encoding]::UTF8) ` + -ErrorAction Stop + } + catch { + Write-Error "E-Mail an $To fehlgeschlagen: $_" + } +} + +function Send-Ntfy { + param( + [string]$Title, + [string]$Message + ) + + $ntfyUrl = "$($conf["NTFY_SERVER"])/$($conf["NTFY_TOPIC"])" + + $headers = @{ + "Title" = $Title + "Priority" = $conf["NTFY_PRIORITY"] + "Tags" = $conf["NTFY_TAGS"] + } + + if ($conf["NTFY_AUTH_TOKEN"]) { + $headers["Authorization"] = "Bearer $($conf["NTFY_AUTH_TOKEN"])" + } + + try { + Invoke-RestMethod ` + -Uri $ntfyUrl ` + -Method Post ` + -Headers $headers ` + -Body ([System.Text.Encoding]::UTF8.GetBytes($Message)) ` + -ContentType "text/plain; charset=utf-8" + } + catch { + Write-Error "Ntfy-Benachrichtigung fehlgeschlagen: $_" + } +} + +# --- RDP-Event auslesen --- + +$eventID = 1149 +$eventLogName = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" + +$latestEvent = Get-WinEvent -LogName $eventLogName -FilterXPath "" | Select-Object -First 1 + +if (-not $latestEvent) { + exit 0 +} + +$xml = [xml]$latestEvent.ToXml() + +if (-not $xml.Event.UserData) { + exit 0 +} + +$user = $xml.Event.UserData.EventXML.Param1 +$domain = $xml.Event.UserData.EventXML.Param2 +$clientIP = $xml.Event.UserData.EventXML.Param3 +$eventTime = $latestEvent.TimeCreated +$computerName = $latestEvent.MachineName + +$eventDate = $eventTime.ToString('dd.MM.yyyy') +$eventTimeStr = $eventTime.ToString('HH:mm:ss') +$subject = "RDP-Anmeldung auf $computerName registriert" + +# --- Empfaenger ermitteln --- + +$recipients = @() + +switch ($conf["MODE"]) { + "ad" { + $adMembers = Get-ADGroupMember -Identity $conf["AD_SECURITY_GROUP_DN"] | Where-Object { $_.objectClass -eq "user" } + foreach ($member in $adMembers) { + $adUser = Get-ADUser $member.DistinguishedName -Properties GivenName, Surname, EmailAddress + $recipients += [PSCustomObject]@{ + Name = "$($adUser.GivenName) $($adUser.Surname)" + Email = $adUser.EmailAddress + } + } + } + "local" { + foreach ($entry in $conf["LOCAL_RECIPIENTS"] -split ";") { + $entry = $entry.Trim() + if ($entry -eq "") { continue } + $parts = $entry -split ",", 2 + if ($parts.Count -eq 2) { + $recipients += [PSCustomObject]@{ + Name = $parts[0].Trim() + Email = $parts[1].Trim() + } + } + } + } + default { + Write-Error "Unbekannter Modus: $($conf["MODE"]). Erlaubt: 'ad', 'local'" + exit 1 + } +} + +# --- Benachrichtigungen versenden --- + +$methods = $conf["NOTIFICATION_METHODS"] -split "," + +if ($methods.Trim() -contains "email") { + foreach ($recipient in $recipients) { + Send-Email ` + -To $recipient.Email ` + -RecipientName $recipient.Name ` + -Subject $subject ` + -ComputerName $computerName ` + -EventDate $eventDate ` + -EventTime $eventTimeStr ` + -Domain $domain ` + -User $user ` + -ClientIP $clientIP + } +} + +if ($methods.Trim() -contains "ntfy") { + $ntfyMessage = @" +Maschine: $computerName +Datum: $eventDate +Uhrzeit: $eventTimeStr +Domaene: $domain +Benutzer: $user +Client-IP: $clientIP +"@ + + Send-Ntfy -Title $subject -Message $ntfyMessage +} diff --git a/rdp-access-notification.xml b/rdp-access-notification.xml new file mode 100644 index 0000000..6300e29 --- /dev/null +++ b/rdp-access-notification.xml @@ -0,0 +1,47 @@ + + + + 2026-04-26T00:00:00 + Administrator + \Benachrichtigung bei RDP Anmeldung + + + + true + <QueryList><Query Id="0" Path="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational"><Select Path="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational">*[System[Provider[@Name='Microsoft-Windows-TerminalServices-RemoteConnectionManager'] and EventID=1149]]</Select></Query></QueryList> + + + + + S-1-5-18 + LeastPrivilege + + + + IgnoreNew + false + true + true + false + false + + true + false + + true + true + false + false + false + true + false + PT72H + 7 + + + + C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe + -ExecutionPolicy Bypass -File "C:\scripts\rdp-login-notifier\rdp-access-notification.ps1" + + + diff --git a/screenshots/notification.png b/screenshots/notification.png deleted file mode 100644 index 6ebac90..0000000 Binary files a/screenshots/notification.png and /dev/null differ