Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions .github/workflows/security-validation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
name: Security validation

on:
pull_request:
push:
branches: [master]

permissions:
contents: read

jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Install shell runtimes
run: sudo apt-get update && sudo apt-get install -y shellcheck zsh

- name: Parse Bash scripts
shell: bash
run: |
while IFS= read -r -d '' script; do
first_line="$(head -n 1 "$script")"
if [[ "$first_line" == *bash* || "$first_line" == "#!/bin/sh" ]]; then
bash -n "$script"
fi
done < <(find . -type f -name '*.sh' -print0)

- name: Parse Zsh scripts
shell: bash
run: |
while IFS= read -r -d '' script; do
if head -n 1 "$script" | grep -q zsh; then
zsh -n "$script"
fi
done < <(find . -type f -name '*.sh' -print0)

- name: Run ShellCheck
shell: bash
run: |
mapfile -d '' scripts < <(
while IFS= read -r -d '' script; do
first_line="$(head -n 1 "$script")"
if [[ "$first_line" == *bash* || "$first_line" == "#!/bin/sh" ]]; then
printf '%s\0' "$script"
fi
done < <(find . -type f -name '*.sh' -print0)
)
shellcheck --severity=error "${scripts[@]}"

- name: Parse Python and run tests
run: |
python -m compileall -q .
python -m unittest discover -s tests -v

- name: Parse JavaScript
run: node --check tampermonkey/edx-download-transcripts.js

- name: Parse PowerShell
shell: pwsh
run: |
$failed = $false
Get-ChildItem -Recurse -Filter *.ps1 | ForEach-Object {
$tokens = $null
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile(
$_.FullName,
[ref]$tokens,
[ref]$errors
) | Out-Null
if ($errors.Count) {
$failed = $true
$errors | ForEach-Object { Write-Error $_.Message }
}
}
if ($failed) { exit 1 }
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__
203 changes: 91 additions & 112 deletions Monitor-ADGroupChanges.ps1
Original file line number Diff line number Diff line change
@@ -1,128 +1,107 @@
# Monitor-ADGroupMemberChanges
#
# 1. Get members.
# 2. Compare to previous members.
# 3. Output changes.
#
# Credit to https://github.com/lazywinadmin/Monitor-ADGroupMembership
# Portions Copyright (c) 2015 Francois-Xavier Cat
[CmdletBinding()]
param(
[Parameter()]
[string]$GroupName = "Domain Admins",

# The MIT License (MIT)
[Parameter()]
[string]$StateDirectory = (Join-Path $env:ProgramData "ScriptSecurity\ADGroupMonitor")
)

# Copyright (c) 2020 Benjamin Hunter
# Copyright (c) 2015 Francois-Xavier Cat
$ErrorActionPreference = "Stop"
Import-Module ActiveDirectory -ErrorAction Stop

# 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:
function Protect-CsvValue {
param([AllowNull()][object]$Value)

# 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.

#######################################
# Simple version


$item = "Domain Admins"
$ScriptName = $MyInvocation.MyCommand
$ScriptPath = (Split-Path -Path ((Get-Variable -Name MyInvocation).Value).MyCommand.Path)
$ScriptPathOutput = $ScriptPath + "\Output"

$MemberObjs = Get-ADGroupMember -Identity $item -Recursive -ErrorAction Stop
[Array]$Members = $MemberObjs | Where-Object {$_.objectClass -eq "user" } | Get-ADUser -Properties PasswordExpired | Select-Object -Property *,@{ Name = 'DN'; Expression = { $_.DistinguishedName } }
$Members += $MemberObjs | Where-Object {$_.objectClass -eq "computer" } | Get-ADComputer -Properties PasswordExpired | Select-Object -Property *,@{ Name = 'DN'; Expression = { $_.DistinguishedName } }

# Load previous membership
$ImportCSV = Import-Csv -Path (Join-Path -Path $ScriptPathOutput -ChildPath $StateFile) -ErrorAction Stop -ErrorVariable ErrorProcessImportCSV

# Write twice - time stamped and reference file for next comparison.
$Members | Export-Csv -Path (Join-Path -Path $ScriptPathOutput -ChildPath ($StateFile + (Get-Date -Format FileDateTimeUniversal)) -NoTypeInformation -Encoding Unicode
$Members | Export-Csv -Path (Join-Path -Path $ScriptPathOutput -ChildPath $StateFile) -NoTypeInformation -Encoding Unicode

$Changes = Compare-Object -DifferenceObject $ImportCSV -ReferenceObject $Members -ErrorAction Stop -ErrorVariable ErrorProcessCompareObject -Property Name, SamAccountName, DN |
Select-Object -Property @{ Name = "DateTime"; Expression = { Get-Date -Format "yyyyMMdd-hh:mm:ss" } }, @{
Name = 'State'; expression = {
if ($_.SideIndicator -eq "=>") { "Removed" }
else { "Added" }
$text = [string]$Value
if ($text -match '^[=+\-@]') {
return "'$text"
}
}, DisplayName, Name, SamAccountName, DN | Where-Object { $_.name -notlike "*no user or group*" }

Write-Output $Changes



#######################################
# Work in progress
# Based on https://github.com/lazywinadmin/Monitor-ADGroupMembership



return $text
}

$item = "Domain Admins"
function Set-RestrictedDirectoryAcl {
param([Parameter(Mandatory)][string]$Path)

$ScriptName = $MyInvocation.MyCommand
$ScriptPath = (Split-Path -Path ((Get-Variable -Name MyInvocation).Value).MyCommand.Path)
$ScriptPathOutput = $ScriptPath + "\Output"
$acl = Get-Acl -LiteralPath $Path
$acl.SetAccessRuleProtection($true, $false)
foreach ($rule in @($acl.Access)) {
[void]$acl.RemoveAccessRuleAll($rule)
}

if (-not(Test-Path -Path $ScriptPathOutput))
{
Write-Verbose -Message "[$ScriptName][Begin] Creating the Output Folder : $ScriptPathOutput"
New-Item -Path $ScriptPathOutput -ItemType Directory | Out-Null
$identities = @(
"NT AUTHORITY\SYSTEM",
"BUILTIN\Administrators",
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
) | Select-Object -Unique

foreach ($identity in $identities) {
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
$identity,
[System.Security.AccessControl.FileSystemRights]::FullControl,
[System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit",
[System.Security.AccessControl.PropagationFlags]::None,
[System.Security.AccessControl.AccessControlType]::Allow
)
$acl.AddAccessRule($rule)
}
Set-Acl -LiteralPath $Path -AclObject $acl
}

$GroupName = Get-ADGroup @GroupSplatting -Properties * -ErrorAction Continue -ErrorVariable ErrorProcessGetADGroup
Write-Verbose -Message "[$ScriptName][Process] Extracting Domain Name from $($GroupName.CanonicalName)"
$DomainName = ($GroupName.CanonicalName -split '/')[0]
$RealGroupName = $GroupName.Name

$MemberObjs = Get-ADGroupMember -Identity $item -Recursive -ErrorAction Stop
[Array]$Members = $MemberObjs | Where-Object {$_.objectClass -eq "user" } | Get-ADUser -Properties PasswordExpired | Select-Object -Property *,@{ Name = 'DN'; Expression = { $_.DistinguishedName } }
$Members += $MemberObjs | Where-Object {$_.objectClass -eq "computer" } | Get-ADComputer -Properties PasswordExpired | Select-Object -Property *,@{ Name = 'DN'; Expression = { $_.DistinguishedName } }
function ConvertTo-StateRecord {
param([Parameter(Mandatory)]$DirectoryObject)

# GroupName Membership File
# if the file doesn't exist, assume we don't have a record to refer to
$StateFile = "$($DomainName)_$($RealGroupName)-membership.csv"

if (-not (Test-Path -Path (Join-Path -Path $ScriptPathOutput -ChildPath $StateFile)))
{
Write-Verbose -Message "[$ScriptName][Process] $item - The following file did not exist: $StateFile"
Write-Verbose -Message "[$ScriptName][Process] $item - Exporting the current membership information into the file: $StateFile"
[pscustomobject]@{
Name = Protect-CsvValue $DirectoryObject.Name
SamAccountName = Protect-CsvValue $DirectoryObject.SamAccountName
DN = Protect-CsvValue $DirectoryObject.DistinguishedName
ObjectClass = Protect-CsvValue $DirectoryObject.ObjectClass
}
}

$Members | Export-Csv -Path (Join-Path -Path $ScriptPathOutput -ChildPath $StateFile) -NoTypeInformation -Encoding Unicode
if (-not (Test-Path -LiteralPath $StateDirectory)) {
New-Item -Path $StateDirectory -ItemType Directory -Force | Out-Null
}
else
{
Write-Verbose -Message "[$ScriptName][Process] $item - The following file exists: $StateFile"
$StateDirectory = (Resolve-Path -LiteralPath $StateDirectory).Path
Set-RestrictedDirectoryAcl -Path $StateDirectory

$group = Get-ADGroup -Identity $GroupName -ErrorAction Stop
$safeGroupName = $group.SamAccountName -replace '[^A-Za-z0-9_.-]', '_'
$stateFile = Join-Path $StateDirectory "$safeGroupName-membership.csv"

$members = @(
Get-ADGroupMember -Identity $group -Recursive -ErrorAction Stop |
Where-Object { $_.ObjectClass -in @("user", "computer", "group") } |
ForEach-Object { ConvertTo-StateRecord $_ } |
Sort-Object ObjectClass, SamAccountName, DN
)

if (Test-Path -LiteralPath $stateFile) {
$previous = @(Import-Csv -LiteralPath $stateFile)
$changes = Compare-Object `
-ReferenceObject $previous `
-DifferenceObject $members `
-Property Name, SamAccountName, DN, ObjectClass |
ForEach-Object {
[pscustomobject]@{
DateTime = Get-Date -Format "yyyy-MM-ddTHH:mm:ssK"
State = if ($_.SideIndicator -eq "=>") { "Added" } else { "Removed" }
Name = $_.Name
SamAccountName = $_.SamAccountName
DN = $_.DN
ObjectClass = $_.ObjectClass
}
}
$changes
}

# GroupName Membership File is compared with the current GroupName Membership
Write-Verbose -Message "[$ScriptName][Process] $item - Comparing Current and Before"

$ImportCSV = Import-Csv -Path (Join-Path -Path $ScriptPathOutput -ChildPath $StateFile) -ErrorAction Stop -ErrorVariable ErrorProcessImportCSV

$Changes = Compare-Object -DifferenceObject $ImportCSV -ReferenceObject $Members -ErrorAction Stop -ErrorVariable ErrorProcessCompareObject -Property Name, SamAccountName, DN |
Select-Object -Property @{ Name = "DateTime"; Expression = { Get-Date -Format "yyyyMMdd-hh:mm:ss" } }, @{
Name = 'State'; expression = {
if ($_.SideIndicator -eq "=>") { "Removed" }
else { "Added" }
$temporaryFile = Join-Path $StateDirectory ([System.IO.Path]::GetRandomFileName())
try {
$members | Export-Csv -LiteralPath $temporaryFile -NoTypeInformation -Encoding Unicode
Move-Item -LiteralPath $temporaryFile -Destination $stateFile -Force
}
finally {
if (Test-Path -LiteralPath $temporaryFile) {
Remove-Item -LiteralPath $temporaryFile -Force
}
}, DisplayName, Name, SamAccountName, DN | Where-Object { $_.name -notlike "*no user or group*" }

Write-Verbose -Message "[$ScriptName][Process] $item - Compare Block Done!"






}
Loading
Loading