Hey y’all! I was part of the ECTS CyberPatriot team during the school year of 2024-25. During this time, my team and I managed to place in the top 30% in platinum (although we would have placed much higher had we actually shut down our machines properly, and if Windows file search worked faster). In this post, I’m gonna run through everything our team used to achieve this accomplishment.

THE HOLY GRAIL

Starting, we were pretty unknowledgeable about most things CyberPatriot. That was until we discovered the power of our lord and savior: Pentests and Tech. Here are the videos that kickstarted our success:

Linux:

Windows:

For the love of god, please watch the videos above if you want any chance to make it to platinum. However, keep in mind that Windows Server and Linux Mint are not covered.

The Next Steps

ALSO, MAKE SURE TO CHECK THINGS MANUALLY DO NOT TRUST THE SCRIPTS NO MATTER HOW MUCH YOU THINK THEY WORK

PS: I made all of the scripts for the senior team in 2024. I am not a programmer; I am a computer networking student, Please make fun of me if you see anything wrong with the scripts.

This script Is The Isaac Trost safeguard: THIS SCRIPT IS THE LAST WINDOWS SCRIPT YOU RUN!!!!

This script was made foolproof to ensure you do not lock yourself out of the Windows machine. You may ask why you would need this. Well, we needed it because this funny guy, Isaac Trost, enabled Windows Hello and smart card and lock use out of the VM, so now we have this, which makes sure that you can still log into your computer and gives the same password to all users.

# The Isaac Trost safeguard 
# Run in admin and do not turn off or update till you run this script

if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "This script must be run as administrator." -ForegroundColor Red
    exit
}

Write-Host "Starting script"

# Function to check and install required modules
function Install-ModuleIfNotExists {
    param (
        [string]$ModuleName
    )
    
    if (-not (Get-Module -ListAvailable -Name $ModuleName)) {
        Write-Host "Installing $ModuleName module" -ForegroundColor Cyan
        try {
            Install-Module -Name $ModuleName -Force -Scope AllUsers -AllowClobber
            Write-Host "$ModuleName module installed successfully." -ForegroundColor Green
        } catch {
            Write-Host "Failed to install $ModuleName module: $_" -ForegroundColor Red
        }
    } else {
        Write-Host "$ModuleName module is already installed." -ForegroundColor Green
    }
}

# Check for required modules
$requiredModules = @("PowerShellGet", "PackageManagement", "PSWindowsUpdate")
foreach ($module in $requiredModules) {
    Install-ModuleIfNotExists -ModuleName $module
}

# Path to Windows Hello biometrics policy registry key
$biometricRegistryPath = "HKLM:\SOFTWARE\Policies\Microsoft\Biometrics"

# Check if the Biometrics key exists
if (-not (Test-Path $biometricRegistryPath)) {
    # Create the key if it doesn't exist
    New-Item -Path $biometricRegistryPath -Force | Out-Null
}

# Check if Windows Hello (biometrics) is enabled
$biometricEnabled = Get-ItemProperty -Path $biometricRegistryPath -Name "Enabled" -ErrorAction SilentlyContinue

if ($biometricEnabled -and $biometricEnabled.Enabled -eq 1) {
    Write-Output "Windows Hello biometrics is currently enabled. Disabling it now"
    
    # Set the "Enabled" property to 0 to disable Windows Hello
    Set-ItemProperty -Path $biometricRegistryPath -Name "Enabled" -Value 0

    # Confirm change
    $newSetting = Get-ItemProperty -Path $biometricRegistryPath -Name "Enabled"
    if ($newSetting.Enabled -eq 0) {
        Write-Output "Windows Hello biometrics has been successfully disabled."
    } else {
        Write-Output "Failed to disable Windows Hello biometrics. Please check permissions or try running as administrator."
    }
} else {
    Write-Output "Windows Hello biometrics is already disabled or not configured."
}

# Defines the target password
$targetPassword = "r0b10x_k1in$@gy@tt.org"

# Checks if the LocalAccounts module is available; if not, install it
if (-not (Get-Module -ListAvailable -Name "Microsoft.PowerShell.LocalAccounts")) {
    Write-Output "Installing Microsoft.PowerShell.LocalAccounts module"
    Install-Module -Name "Microsoft.PowerShell.LocalAccounts" -Force -Scope CurrentUser
}

# Import the module
Import-Module Microsoft.PowerShell.LocalAccounts -ErrorAction Stop

# Get all local user accounts
$users = Get-LocalUser | Where-Object { $_.Enabled -eq $true -and $_.Name -ne "Administrator" }

foreach ($user in $users) {
    try {
        # Set the password for each user
        Write-Output "Setting password for user: $($user.Name)"
        
        # Convert password to SecureString
        $securePassword = ConvertTo-SecureString -String $targetPassword -AsPlainText -Force
        
        # Set the password
        $user | Set-LocalUser -Password $securePassword
        
        Write-Output "Password for user $($user.Name) has been updated successfully."
    }
    catch {
        Write-Output "Failed to update password for user $($user.Name): $_"
    }
}

# This script checks file integrity and verifies that essential Windows services are enabled and running.

# Function to check for file integrity
function Check-FileIntegrity {
    param (
        [string]$filePath,
        [string]$expectedHash
    )

    if (Test-Path $filePath) {
        $fileHash = Get-FileHash -Path $filePath -Algorithm SHA256
        if ($fileHash.Hash -eq $expectedHash) {
            Write-Host "File integrity check passed for: $filePath" -ForegroundColor Green
        } else {
            Write-Host "File integrity check failed for: $filePath" -ForegroundColor Red
        }
    } else {
        Write-Host "File not found: $filePath" -ForegroundColor Red
    }
}

# Function to check if a service is running
function Check-ServiceStatus {
    param (
        [string]$serviceName
    )

    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service) {
        if ($service.Status -eq 'Running') {
            Write-Host "$serviceName is running." -ForegroundColor Green
        } else {
            Write-Host "$serviceName is not running. Attempting to start" -ForegroundColor Yellow
            Start-Service -Name $serviceName -ErrorAction SilentlyContinue
            if ((Get-Service -Name $serviceName).Status -eq 'Running') {
                Write-Host "$serviceName started successfully." -ForegroundColor Green
            } else {
                Write-Host "Failed to start $serviceName." -ForegroundColor Red
            }
        }
    } else {
        Write-Host "Service not found: $serviceName" -ForegroundColor Red
    }
}

# Example file paths and expected hashes (update with actual files and hashes)
$filesToCheck = @(
    @{ Path = "C:\Path\To\Your\File1.exe"; Hash = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" },
    @{ Path = "C:\Path\To\Your\File2.dll"; Hash = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890" }
)

# Check file integrity
foreach ($file in $filesToCheck) {
    Check-FileIntegrity -filePath $file.Path -expectedHash $file.Hash
}

# Check required services
$requiredServices = @("WinDefend", "wuauserv", "bits") # Add more essential services as needed
foreach ($service in $requiredServices) {
    Check-ServiceStatus -serviceName $service
}

Write-Host "Script execution completed." -ForegroundColor Green

Powershell Script1: This script downloads and updates all of the needed Powershell modules.

Powershell Script2: This script does the basic tasks like turning on Windows Defender and setting password policies for all of the users.

Powershell Script3: This script does other tasks that should be done after you do the forensics questions, like disabling guest users and checking for file shares that are not default. CHECK THE README FOR NON-DEFAULT FILE SHARES NEEDED.

Powershell Script2:#RUN IN ADMIN 
#Make sure to do your questions first this script does disable network shares
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "This script must be run as administrator." -ForegroundColor Red
    exit
}

Write-Host "Starting script"

# Disable all guest user accounts
$users = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount=True"

foreach ($user in $users) {
    if ($user.SID -like "*-501" -or $user.Name -eq "Guest") {
        Write-Host "Disabling guest account: $($user.Name)"
        try {
            Disable-LocalUser -Name $user.Name
            Write-Host "$($user.Name) has been disabled."
        } catch {
            Write-Host "Failed to disable $($user.Name): $_"
        }
    } else {
        Write-Host "User $($user.Name) is not a guest account."
    }
}

Write-Host "Checking for file shares"

# List of allowed standard shares
$allowedShares = @("ADMIN$", "C$", "IPC$")

# Get all shared folders on the system
$shares = Get-WmiObject -Class Win32_Share | Where-Object { $_.Name -notin $allowedShares }

# Check if there are any non-standard shares
if ($shares.Count -eq 0) {
    Write-Host "Only standard shares (ADMIN$, C$, IPC$) are present. No action needed."
} else {
    Write-Host "Non-standard shares found:"
    $shares | ForEach-Object { Write-Host " - $($_.Name)" }

    # Prompt user for confirmation to delete non-standard shares
    $response = Read-Host "Do you want to delete the non-standard shares? (y/n)"

    if ($response -eq "y") {
        # Delete each non-standard share
        foreach ($share in $shares) {
            try {
                $share.Delete() | Out-Null
                Write-Host "Deleted share: $($share.Name)"
            } catch {
                Write-Host "Failed to delete share: $($share.Name)" -ForegroundColor Red
            }
        }
        Write-Host "Non-standard shares have been deleted."
    } else {
        Write-Host "No shares were deleted. Continuing."
    }
}

# Define the registry path and name for Windows SmartScreen
$registryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
$registryName = "EnableSmartScreen"

# Set the value for Windows SmartScreen (Warn = "Prompt"; Block = "Block"; Disabled = "Off")
$SmartScreenSetting = "Prompt"

# Check if the key exists, create if it does not
if (!(Test-Path -Path $registryPath)) {
    New-Item -Path $registryPath -Force | Out-Null
}

# Set the registry key to configure SmartScreen
Set-ItemProperty -Path $registryPath -Name $registryName -Value $SmartScreenSetting

# Output result
Write-Output "Windows Defender SmartScreen configured to Warn (Prompt) setting."

# Firewall rules - Disabling inbound rules for specified applications
$applications = @(
    "MicrosoftEdge",
    "Search",
    "Microsoft.MSN.Money",
    "Microsoft.MSN.Sports",
    "Microsoft.MSN.News",
    "Microsoft.MSN.Weather",
    "Microsoft.Photos",
    "Microsoft.XboxApp"
)

foreach ($app in $applications) {
    Write-Host "Disabling inbound firewall rule for $app"
    New-NetFirewallRule -DisplayName "$app Inbound Block" -Direction Inbound -Action Block -Program "C:\Program Files\WindowsApps\$app" -Profile Any -Enabled True -ErrorAction SilentlyContinue
}

# Function to enable auditing for success and failure for all options
function Enable-Auditing {
    Write-Host "Enabling auditing for success and failure for all options" -ForegroundColor Cyan

    # Enable auditing for all categories using AuditPol
    $auditCategories = @(
        "Logon/Logoff",
        "Account Logon",
        "Account Management",
        "Directory Service Access",
        "Object Access",
        "Privilege Use",
        "Process Tracking",
        "System Events",
        "Detailed Tracking",
        "Policy Change",
        "Account Lockout",
        "Special Logon",
        "Other Logon/Logoff Events"
    )

    foreach ($category in $auditCategories) {
        try {
            Write-Host "Checking available subcategories for: $category" -ForegroundColor Yellow
            # Verify available subcategories for the category
            $availableSubcategories = auditpol /list /subcategory:$category
            
            # Enable Success and Failure auditing for each category
            Write-Host "Enabling auditing for: $category" -ForegroundColor Green
            auditpol /set /subcategory:"$category" /success:enable /failure:enable
            Write-Host "Successfully enabled auditing for: $category" -ForegroundColor Green
        } catch {
            Write-Host "Failed to enable auditing for: $category" -ForegroundColor Red
        }
    }
}

# Call the function to enable auditing
Enable-Auditing

Write-Host "Auditing for success and failure has been enabled for all available categories." -ForegroundColor Green

# Function to enable Strict Windows Search mode
function Enable-StrictWindowsSearchMode {
    try {
        Write-Host "Enabling Strict Windows Search Mode" -ForegroundColor Cyan

        # Define the registry path for Windows Search settings
        $registryPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search"

        # Set Windows Search to "Strict" mode (restrict indexing locations)
        Set-ItemProperty -Path $registryPath -Name "BingSearchEnabled" -Value 0 # Disable Bing search integration
        Set-ItemProperty -Path $registryPath -Name "CortanaEnabled" -Value 0 # Disable Cortana
        Set-ItemProperty -Path $registryPath -Name "AllowSearchToUseLocation" -Value 0 # Disable location-based search results

        # Disable indexing of file contents and user profile
        Set-ItemProperty -Path $registryPath -Name "EnableIndexer" -Value 0 # Disable the indexing service
        Set-ItemProperty -Path $registryPath -Name "DisableSearchBoxSuggestions" -Value 1 # Disable search suggestions

        # Disable indexing of user profiles and certain sensitive areas
        Set-ItemProperty -Path $registryPath -Name "ExcludeFromIndexing" -Value 1 # Exclude certain file types from indexing

        # Restart Windows Search service to apply changes
        Write-Host "Restarting Windows Search service" -ForegroundColor Cyan
        Restart-Service -Name "WSearch" -Force

        Write-Host "Strict Windows Search Mode enabled successfully." -ForegroundColor Green
    } catch {
        Write-Host "An error occurred: $_" -ForegroundColor Red
    }
}

# Call the function to enable strict Windows search mode
Enable-StrictWindowsSearchMode

Write-Host "Script execution completed." -ForegroundColor Green

PowerShell Script 4: This script is not done and does not work fully. It is a good starting point to disable services, and it also checks for exfiltrations and runs a full defender scan

# This is the second Windows 10 script. This is to be run at the end.
# YOU NEED TO RUN IN ADMIN

# Check if the script is run as administrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "This script must be run as administrator." -ForegroundColor Red
    exit
}

Write-Host "Starting script"

# Function to get Microsoft Defender exclusions and output to a file
function Get-MsDefenderExclusions {
    # Define output file path (ensure it's a valid path)
    $outputFile = "C:\Users\$env:USERNAME\Desktop\ms_defender_exclusions.txt"

    # Get current date and time
    $currentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    
    # Start writing to the output file
    try {
        # Write date to file
        Add-Content -Path $outputFile -Value "MS Defender Exclusions - $currentDate"
        Add-Content -Path $outputFile -Value "----------------------------------------"
        
        # Get the exclusions from Defender
        $exclusions = Get-MpPreference | Select-Object -ExpandProperty ExclusionProcess, ExclusionExtension, ExclusionPath

        # Check if exclusions exist
        if ($exclusions) {
            # Write exclusions to file
            Add-Content -Path $outputFile -Value "Exclusions List:"
            $exclusions | ForEach-Object {
                Add-Content -Path $outputFile -Value $_
            }
        } else {
            Add-Content -Path $outputFile -Value "No exclusions found."
        }

        Write-Host "Exclusions saved to $outputFile"
    } catch {
        Write-Host "Error occurred: $_" -ForegroundColor Red
    }
}

# Call the function to get exclusions
Get-MsDefenderExclusions

# Function to check and install required module
function Install-ModuleIfNotExists {
    param (
        [string]$ModuleName
    )

    if (-not (Get-Module -ListAvailable -Name $ModuleName)) {
        Write-Host "Module '$ModuleName' not found. Installing" -ForegroundColor Yellow
        try {
            Install-Module -Name $ModuleName -Force -Scope CurrentUser
            Write-Host "Module '$ModuleName' installed successfully." -ForegroundColor Green
        } catch {
            Write-Host "Failed to install module '$ModuleName': $_" -ForegroundColor Red
            exit
        }
    } else {
        Write-Host "Module '$ModuleName' is already installed." -ForegroundColor Green
    }
}

# Check for and install required modules (if needed)
Install-ModuleIfNotExists -ModuleName "PSWindowsUpdate"

# Run Windows Update
Write-Host "Starting Windows Update" -ForegroundColor Cyan
try {
    Import-Module PSWindowsUpdate
    Get-WindowsUpdate -AcceptAll -Install -AutoReboot
    Write-Host "Windows Update completed successfully." -ForegroundColor Green
} catch {
    Write-Host "Failed to run Windows Update: $_" -ForegroundColor Red
    exit
}

# Run Microsoft Defender Full Scan
Write-Host "Starting Microsoft Defender Full Scan" -ForegroundColor Cyan
try {
    Start-MpScan -ScanType FullScan
    Write-Host "Microsoft Defender Full Scan started successfully." -ForegroundColor Green
} catch {
    Write-Host "Failed to start Microsoft Defender scan: $_" -ForegroundColor Red
    exit
}

# List of services to disable
$insecureServices = @(
    "RemoteRegistry",  # Allows remote access to the registry
    "Telnet",          # Unsecured remote command-line
    "TrkWks",          # Distributed Link Tracking Client
    "W3SVC",           # Web Publishing Service
    "SMB1Protocol",    # SMBv1 Protocol, vulnerable to attacks
    "TermService",     # Remote Desktop Services
    "WinRM",           # Windows Remote Management
    "Winmgmt",         # Windows Management Instrumentation (WMI)
    "LanmanServer",    # SMB/Server Service
    "FTPSVC",          # File Transfer Protocol (FTP)
    "POP3SVC",         # Post Office Protocol (POPv1/v2)
    "FTP",             # FTP Service (alternative name)
    "RpcSs",           # Remote Procedure Call (RPC)
    "SNMP",            # Simple Network Management Protocol (SNMP)
    "HTTP",            # HTTP service (Commonly used in various attacks, such as web-based RCE)
    "RasMan",          # Remote Access Connection Manager (Exploited in certain remote access attacks)
    "ADWS",            # Active Directory Web Services
    "DNS",             # DNS Server
    "DHCPServer",      # DHCP Server
    "Fax",             # Fax Service
    "VMMS",            # Hyper-V Virtual Machine Management
    "WDS",             # Windows Deployment Services
    "IISAdmin",        # IIS Admin Service
    "DFS",             # Distributed File System
    "NPS",             # Network Policy Server
    "WSS",             # Windows Server Backup
    "WSUS"             # Windows Server Update Services
)

# Loop through each service and disable it
foreach ($service in $insecureServices) {
    try {
        # Get the current status of the service
        $serviceStatus = Get-Service -Name $service -ErrorAction SilentlyContinue

        if ($serviceStatus -and $serviceStatus.Status -eq "Running") {
            Write-Host "Stopping and disabling $service"
            Stop-Service -Name $service -Force
        }

        # Set the service to Disabled startup type
        Set-Service -Name $service -StartupType Disabled
        Write-Host "$service has been disabled."
    } catch {
        Write-Host "Service $service could not be found or modified. It may not be installed on this system." -ForegroundColor Yellow
    }
}

Write-Host "All specified services have been processed." -ForegroundColor Green

This script can help with user enumeration on Windows. USE AT YOUR OWN RISK. READ THE READ ME !!!!!!!!!!!!!!!!!

# Check if running as administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)

if (-not $isAdmin) {
    Clear-Host
    Write-Host ""
    Write-Host "=============================================================" -ForegroundColor Red
    Write-Host "=============================================================" -ForegroundColor Red
    Write-Host "                !!! NOT RUNNING AS ADMINISTRATOR !!!          " -ForegroundColor Red -BackgroundColor Black
    Write-Host "=============================================================" -ForegroundColor Red
    Write-Host "=============================================================" -ForegroundColor Red
    Write-Host ""
    Write-Host " Please restart this script with Administrator privileges." -ForegroundColor Pink
    Write-Host ""
    Pause
    exit
}
else {
    Write-Host "Running as Administrator." -ForegroundColor Green
}

# Ensure LocalAccounts module is available
if (-not (Get-Module -ListAvailable -Name Microsoft.PowerShell.LocalAccounts)) {
    Write-Host "LocalAccounts module not found. Attempting to install" -ForegroundColor Yellow
    
    try {
        Install-WindowsFeature RSAT:ActiveDirectory-Domain-Services -ErrorAction Stop
        Import-Module Microsoft.PowerShell.LocalAccounts
        Write-Host "Module installed successfully." -ForegroundColor Green
    } catch {
        Write-Host "Failed to install LocalAccounts module. Falling back to 'net user'." -ForegroundColor Red
    }
} else {
    Write-Host "LocalAccounts module found, importing." -ForegroundColor Cyan
    Import-Module Microsoft.PowerShell.LocalAccounts
    Write-Host "LocalAccounts module imported successfully." -ForegroundColor Green
}



# Allowed users list 
#add the user in the read me to allowedUsers 
$allowedUsers = @("Administrator", "Guest", "ServiceAccount","Guest","WDAGUtilityAccount")

# Get all local users on Windows
$localUsers = Get-LocalUser | Select-Object -ExpandProperty Name

# Compare lists
$unapprovedUsers = $localUsers | Where-Object { $_ -notin $allowedUsers }

# Make Sure that you double check the read me to verfiy that all of the user that you are going to delete are not aproved.
if ($unapprovedUsers.Count -eq 0) {
    Write-Host " All users match the approved list"
} else {
    Write-Host "`n Unapproved Users Found:`n"
    $unapprovedUsers | ForEach-Object { Write-Host " - $_" }

    foreach ($user in $unapprovedUsers) {
        Write-Host "`n=============================="
        Write-Host "!!!   CHECK THE README   !!!"
        Write-Host "=============================="
        $response = Read-Host "Do you want to DELETE user '$user'? (Y/N)"
        
        if ($response -eq "Y") {
            try {
                Remove-LocalUser -Name $user -ErrorAction Stop
                Write-Host " User '$user' deleted."
            } catch {
                Write-Host " Failed to delete '$user': $_"
            }
        } else {
            Write-Host " Skipped '$user'."
        }
    }
}

Linux script: We had only one Linux script that handled most of the tasks we wanted to automate. One problem was that the script would sometimes break the PAM files, so make sure to test it before using it.

#!/bin/bash
# Check for sudo/root privileges
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root or with sudo privileges."
   exit 1
fi

set -e

echo "Starting the setup for automatic security updates"

# Update and upgrade the package lists
sudo apt update && sudo apt upgrade -y

# Install the unattended-upgrades package if not already installed
echo "Installing unattended-upgrades if not present"
sudo apt install -y unattended-upgrades

# Enable automatic updates
echo "Enabling automatic updates"
sudo dpkg-reconfigure -plow unattended-upgrades

# Configure updates for security and recommended packages
echo "Configuring updates for security and recommended packages"
cat <<EOF | sudo tee -a /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Origins-Pattern {
        "o=Ubuntu,a=\$(lsb_release -sc)-security";
        "o=Ubuntu,a=\$(lsb_release -sc)-updates";
        "o=Ubuntu,a=\$(lsb_release -sc)-proposed";
        "o=Ubuntu,a=\$(lsb_release -sc)-backports";
};
Unattended-Upgrade::Automatic-Reboot "false";
EOF

# Restart the unattended-upgrades service
echo "Restarting the unattended-upgrades service"
sudo systemctl restart unattended-upgrades

# Set up a cron job for daily updates
echo "Setting up daily updates"
CRON_JOB="0 2 * * * /usr/bin/apt update && /usr/bin/apt upgrade -y"
(crontab -l 2>/dev/null | grep -v "$CRON_JOB"; echo "$CRON_JOB") | crontab -

echo "Setup complete! Security and recommended updates are now enabled and will run daily without automatic reboots."

echo "Checking the status of the Ubuntu Firewall (ufw)"

# Check if ufw is installed
if ! dpkg -l | grep -qw ufw; then
    echo "The firewall (ufw) is not installed. Installing it now"
    sudo apt update
    sudo apt install -y ufw
else
    echo "The firewall (ufw) is already installed."
fi

# Check if ufw is enabled
if sudo ufw status | grep -q "inactive"; then
    echo "The firewall (ufw) is installed but inactive. Enabling it now"
    sudo ufw enable
else
    echo "The firewall (ufw) is already active."
fi

# Configure firewall rules: deny incoming, allow outgoing
echo "Configuring firewall rules: deny all incoming, allow all outgoing"
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Display the current firewall status and rules
echo "Firewall configuration complete. Current status:"
sudo ufw status verbose

# Configure LightDM 
echo "Configuring LightDM for enhanced security"
if [ -f /etc/lightdm/lightdm.conf ]; then
    echo -e "\nallow-guest=false\ngreeter-hide-users=true\ngreeter-show-manual-login=true\nautologin-user=none" | tee -a /etc/lightdm/lightdm.conf
elif [ -f /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf ]; then
    echo -e "\nallow-guest=false\ngreeter-hide-users=true\ngreeter-show-manual-login=true\nautologin-user=none" | tee -a /usr/share/lightdm/lightdm.conf.d/50-ubuntuP.conf
fi

# New password
NEW_PASSWORD="r0b10x_k1in@gy@tt.org"

# Function to change password
change_password() {
    local username=$1
    echo "Changing password for user: $username"
    echo "$username:$NEW_PASSWORD" | sudo chpasswd
}

echo "Starting to change passwords for all users"

# Get a list of non-system user accounts
USER_LIST=$(awk -F: '$3 >= 1000 && $3 < 65534 {print $1}' /etc/passwd)

# Iterate through each user and change their password
for user in $USER_LIST; do
    change_password $user
done

echo "Password change process completed."

echo "Configuring password policies"

# Set password history to remember the last 5 passwords
echo "Setting password history to 5"
if ! grep -q "pam_pwhistory.so" /etc/pam.d/common-password; then
    echo "password requisite pam_pwhistory.so remember=5" >> /etc/pam.d/common-password
else
    sed -i 's/\(pam_pwhistory.so.*\)/\1 remember=5/' /etc/pam.d/common-password
fi

# Set password length to 12 and enforce complexity
echo "Setting password length to 12 and enforcing complexity"
if ! grep -q "pam_pwquality.so" /etc/security/pwquality.conf; then
    echo "minlen = 12" >> /etc/security/pwquality.conf
    echo "minclass = 4" >> /etc/security/pwquality.conf
else
    sed -i 's/^minlen.*/minlen = 12/' /etc/security/pwquality.conf
    sed -i 's/^minclass.*/minclass = 4/' /etc/security/pwquality.conf
fi

# Define the minimum password age in days
MIN_PASS_AGE=5

# Modify the /etc/login.defs file to set the minimum password age
echo "Setting minimum password age to $MIN_PASS_AGE days in /etc/login.defs"

# Backup the original login.defs
cp /etc/login.defs /etc/login.defs.bak

# Update the MIN_DAYS setting in /etc/login.defs
sed -i "s/^PASS_MIN_DAYS.*/PASS_MIN_DAYS   $MIN_PASS_AGE/" /etc/login.defs

# Ensure the change was applied in the file
if grep -q "^PASS_MIN_DAYS" /etc/login.defs; then
    echo "Successfully updated PASS_MIN_DAYS in /etc/login.defs to $MIN_PASS_AGE days."
else
    echo "Failed to update /etc/login.defs. Please check the file manually."
    exit 1
fi

# Apply the minimum password age for existing users using chage
echo "Applying minimum password age of $MIN_PASS_AGE days to existing users"

for user in $(cut -f1 -d: /etc/passwd); do
    chage --mindays $MIN_PASS_AGE "$user"
done

# Confirm the change
echo "Password minimum age set for all users. Verification:"

# Check for the minimum password age for a sample user 
chage -l root | grep "Minimum" 

# Configure max and min password age and warning period
echo "Setting max password age to 99 days, min password age to 10 days, and warning at 7 days"
sed -i 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS   99/' /etc/login.defs
sed -i 's/^PASS_MIN_DAYS.*/PASS_MIN_DAYS   10/' /etc/login.defs
sed -i 's/^PASS_WARN_AGE.*/PASS_WARN_AGE   7/' /etc/login.defs

# Enforce account lockout policy for failed login attempts
#echo "Setting account lockout policy: 5 failed attempts, 10 unlock tries, 30 minutes timeout"
#if ! grep -q "pam_tally2.so" /etc/pam.d/common-auth; then
    #echo "auth required pam_tally2.so deny=5 unlock_time=1800 onerr=fail audit" >> /etc/pam.d/common-auth
#else
    #sed -i 's/\(pam_tally2.so.*\)/auth required pam_tally2.so deny=5 unlock_time=1800 onerr=fail audit/' /etc/pam.d/common-auth
#fi

# Restart services to apply changes
#echo "Restarting services to apply changes"
#service ssh restart
#service login restart

#echo "Configuration completed successfully"

# Create the faillock configuration file if it doesn't exist
echo "Creating /usr/share/pam-configs/faillock file"
sudo touch /usr/share/pam-configs/faillock

# Edit the faillock configuration to enforce failed login attempt counter
echo "Editing /usr/share/pam-configs/faillock to enforce failed login attempt counter"
echo "Name: Enforce failed login attempt counter
Default: no
Priority: 0
Auth-Type: Primary
Auth:
[default=die] pam_faillock.so authfail
sufficient pam_faillock.so authsucc" | sudo tee /usr/share/pam-configs/faillock > /dev/null

# Create the faillock_notify configuration file if it doesn't exist
echo "Creating /usr/share/pam-configs/faillock_notify file"
sudo touch /usr/share/pam-configs/faillock_notify

#  Edit the faillock_notify configuration to notify on failed login attempts
echo "Editing /usr/share/pam-configs/faillock_notify to notify on failed login attempts"
echo "Name: Notify on failed login attempts
Default: no
Priority: 1024
Auth-Type: Primary
Auth:
requisite pam_faillock.so preauth" | sudo tee /usr/share/pam-configs/faillock_notify > /dev/null

echo "Account lockout policy configured successfully!"
echo "Please verify that the PAM modules are correctly configured using the 'pam-auth-update' menu."

# Enable IPv4 TCP SYN cookies
echo "Enabling IPv4 TCP SYN cookies"

# Modify /etc/sysctl.conf to set net.ipv4.tcp_syncookies=1
sudo sed -i '/^net.ipv4.tcp_syncookies=/c\net.ipv4.tcp_syncookies=1' /etc/sysctl.conf

# Disable IPv4 forwarding
echo "Disabling IPv4 forwarding"

# Modify /etc/sysctl.conf to set net.ipv4.ip_forward=0
sudo sed -i '/^net.ipv4.ip_forward=/c\net.ipv4.ip_forward=0' /etc/sysctl.conf

# Apply the new sysctl settings
echo "Applying the new sysctl settings"
sudo sysctl --system

echo "IPv4 security settings have been successfully configured:
- TCP SYN cookies enabled
- IPv4 forwarding disabled"

# Define the output file path for media files
OUTPUT_FILE="/root/Desktop/media_files_list.txt"

# Create or clear the output file
> "$OUTPUT_FILE"

echo "Searching for .mp3, .mp4, and .mov files"

# Use the `find` command to locate files
find "$HOME" -type f \( -iname "*.mp3" -o -iname "*.mp4" -o -iname "*.mov" \) -print >> "$OUTPUT_FILE"

echo "Search completed. Results saved to: $OUTPUT_FILE"

# Disable root SSH access
if [ -f /etc/ssh/sshd_config ]; then
    echo "Disabling root SSH access"
    if ! grep -q "^PermitRootLogin" /etc/ssh/sshd_config; then
        echo "PermitRootLogin no" | sudo tee -a /etc/ssh/sshd_config
    else
        sudo sed -i 's/^#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
    fi
    sudo systemctl restart ssh
fi

# Check current permissions of /etc/shadow
echo "Checking permissions of /etc/shadow"
current_permissions=$(ls -alF /etc/shadow)

# Output current permissions
echo "Current permissions of /etc/shadow: $current_permissions"

# Fix permissions if they are not 640
echo "Fixing permissions of /etc/shadow"
sudo chmod 640 /etc/shadow

# Verify the updated permissions
echo "Verifying updated permissions of /etc/shadow"
updated_permissions=$(ls -alF /etc/shadow)
echo "Updated permissions of /etc/shadow: $updated_permissions"

echo "Insecure permissions on /etc/shadow have been fixed. It now has the correct permissions of 640."

# Configure sysctl for security
echo "Configuring sysctl settings for security"
cat <<EOL >> /etc/sysctl.conf
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.all.accept_source_route=0
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5
net.ipv4.tcp_syncookies = 1
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
EOL
sysctl -p

# Define the output file
output_file="tool_usage_info.txt"

# Write usage information to the file
{
    echo -e "\nInstallation complete! Here is how to use the installed tools:\n"
    echo -e "1. **tmux**: Terminal multiplexer to create multiple sessions within one terminal."
    echo -e "   - Start a session: \`tmux\`"
    echo -e "   - Detach from a session: \`Ctrl-b d\`"
    echo -e "   - List sessions: \`tmux ls\`"
    echo -e "   - Reattach to a session: \`tmux attach -t <session_name>\`"
    echo -e "   - Kill a session: \`tmux kill-session -t <session_name>\`\n"
    echo -e "2. **screen**: Another terminal multiplexer similar to tmux."
    echo -e "   - Start a session: \`screen\`"
    echo -e "   - Detach from a session: \`Ctrl-a d\`"
    echo -e "   - List sessions: \`screen -ls\`"
    echo -e "   - Reattach to a session: \`screen -r <session_name>\`"
    echo -e "   - Kill a session: \`screen -X -S <session_name> quit\`\n"
    echo -e "3. **htop**: Advanced process viewer."
    echo -e "   - Run: \`htop\`\n"
    echo -e "4. **Job Control**: Basic commands to manage background processes."
    echo -e "   - Run a command in the background: \`command &\`"
    echo -e "   - List jobs: \`jobs\`"
    echo -e "   - Bring a job to the foreground: \`fg %<job_number>\`"
    echo -e "   - Resume a job in the background: \`bg %<job_number>\`"
    echo -e "   - Kill a specific job: \`kill %<job_number>\`\n"
    echo -e "5. **nohup**: Run commands that persist even after logout."
    echo -e "   - Run with nohup: \`nohup command &\`"
    echo -e "   - Output goes to nohup.out by default.\n"
    echo -e "All tools installed and ready to use. For more details, check their respective man pages, e.g., \`man tmux\` or \`man screen\`.\n"
} > "$output_file"

# Check for duplicate UIDs and GIDs in /etc/passwd
echo "Checking for duplicate UIDs and GIDs in /etc/passwd"
duplicate_uids=$(awk -F: '{print $3}' /etc/passwd | sort | uniq -d)
if [[ -n "$duplicate_uids" ]]; then
    echo "Warning: Duplicate UIDs found: $duplicate_uids"
else
    echo "No duplicate UIDs found."
fi
duplicate_gids=$(awk -F: '{print $4}' /etc/passwd | sort | uniq -d)
if [[ -n "$duplicate_gids" ]]; then
    echo "Warning: Duplicate GIDs found: $duplicate_gids"
else
    echo "No duplicate GIDs found."
fi

# Function to stop and disable a service
disable_service() {
    local service_name=$1

    if systemctl list-unit-files | grep -q "^$service_name.service"; then
        echo "Stopping and disabling $service_name service"
        systemctl stop $service_name
        systemctl disable $service_name
        systemctl mask $service_name
        echo "$service_name service stopped and disabled."
    else
        echo "$service_name service not found on this system."
    fi
}

# List of FTP service Names
ftp_services=("vsftpd" "proftpd" "pure-ftpd")

# Disable all found FTP service
for ftp_service in "${ftp_services[@]}"; do
    disable_service "$ftp_service"
done

# Disable OpenSSH service
disable_service "ssh"

# Disable Telnet service
disable_service "telnet"

These scripts can be used by anyone at ECTS for cyber patriot, but DO NOT publish them or share them anywhere other than with your team. The same goes for any script or checklist you make you should not publish or share them not at the cyber-patriot summer camp, or with your friend on the ROTC team at McDowell do not share them !!!!!!.

Issues with the scripts

So there were a lot of growing pains with the scripts with Windows and Linux. The most glaring mistake I made was the lack of testing the scripts on the practice machines we were only doing this for the last two competitions so you should test on every image. For PowerShell, if you get stuck, go to learn.microsoft.com/en-us/training/modules/script-with-powershell/ or you, of course, can use AI, BUT DO NOT JUST USE WHAT AI GIVES YOU, test it on a VM or a practice image.

(Klins add) Link to all Scripts and documents from the 24-25 CP Senior Team: https://drive.google.com/file/d/1ZNROfpX67s1Mruxh_J-YQCQ7F3tKmBRP/view?usp=drive_link

Recourses to lean scripting

https://learn.microsoft.com/en-us/training/modules/script-with-powershell

These are CIS Checklist For Securing Operating Systems

These will help you make scripts, but most things will not apply to cyber-patriots so make sure to make that distinction. You will also need to get up-to-date ones https://downloads.cisecurity.org/#/ if you need clarification, ask Brian or Mr. Kilns.

How to Do Forensics Questions

So, you will come across many forms of forensic questions, everything from simple to hard. Some of the common ones we had were pulling the hash of files or decoding messages (a great tool for this is cyebrchef, but AI can also help with this). You will also need to be able to decode packet capture files in Wireshark. One other tasks you might run into is finding information about CVE vulnerability. https://www.cve.org/ This site can help but there are others that you can use like https://www.tenable.com/cve or https://www.cvedetails.com/ .

Other study resources

So we used many other resources to learn. One thing you will need to have is an in-depth understanding of the Windows operating system. You might think you know it, but you don’t. There is always more. For starters, you will want to know most of the control panel, service, security policies, and computer management.

You will also want to know your standard “hacking tools” like Wireshark, zenmap, Nmap,cclearner, hashcat,ophcrack, but make sure that these tools are not needed. LOOK AT THE READ ME!!!

,nc.exe(this is a service you will see is 99% of the time bad, but make sure you do not need it), Ncap(which is another app that you will see with things like Nmap). You might want to delete it, but make sure you do not need it.

Cisco Packet Tracer

So for Packet Tracer, you want to possibly have a networking student join you and help you with this portion of the competition. All topics can be learned on Cisco, and most information parallels the CCNA. Make sure when you get the cisco learn accounts, you do not start the test before competition day.

The Tournament

Approaching the tourney, ensure you have evenly distributed your tasks and who will be on what machine. Upon arriving at Gannon, you will have ample time to set up your devices and will then compete for around four hours. Needless to say, spend this time efficiently and effectively(also READ THE READ ME BEFORE YOU DO ANYTHING!)! Grind out points and don’t get disappointed when you don’t get any in the last hour or so! Just remember that in the end, the difference between hundreds of places is just a couple of points. For team morale, I would recommend turning the points sound on and keeping track of y’all’s overall points on the whiteboard! Lastly, just remember to have fun and don’t fret about your scores (oh, and if you need to mess with PAM files or do something else that could be risky, do it at the beginning so you can reset quickly!).

PS: Take pictures of your scores often in case anything happens so that you can reference them for future tournaments. Also, save all of the answer keys of the practice images!

-Tanmay Sharma, Jarek Smith, Isaac Trost, Ryan Vrobel, team name — The Disciples of klins (Jarek Smith– this name was not my idea)

Leave a Reply

Your email address will not be published. Required fields are marked *