Skip to content

fabrizioiacobucci/AutoShutdown

Repository files navigation

AutoShutdown - Advanced Windows Scheduled Shutdown System

📋 Table of Contents


🎯 Overview

AutoShutdown is a sophisticated PowerShell-based system that automatically shuts down a Windows computer at a configurable scheduled time with advanced anti-tampering protection, guardian password override, and email notifications.

The system is designed to be resilient against attempts to disable or modify it, while still providing a secure way for authorized users to override the shutdown when needed. All timing parameters (shutdown time, backstop verification time, countdown duration, and enforcement window) are configurable during installation.

Key Innovation: The system includes startup enforcement protection that prevents users from bypassing the shutdown by simply rebooting the computer. If the system is restarted within the configured enforcement window (e.g., between 23:00 and 07:00), AutoShutdown automatically re-initiates the shutdown, closing the reboot bypass loophole.

Why AutoShutdown?

  • Enforce computer usage policies (e.g., parental controls, work hours)
  • Energy savings in enterprise environments
  • Security compliance requiring systems to be shut down after hours
  • Remote monitoring via email notifications
  • Tamper-proof protection with cryptographic verification

✨ Key Features

🔒 Security & Anti-Tampering

  • DPAPI Encryption: All sensitive configurations encrypted with Windows DPAPI (Data Protection API)
  • HMAC Authentication: Cryptographic verification of all encrypted data
  • File Obfuscation: All files use pure GUID names without extensions
  • Task XML Hash Verification: Detects any modification to scheduled tasks
  • PBKDF2 Password Hashing: Guardian password stored with 100,000 iterations
  • Restrictive ACLs: Files and tasks accessible only to SYSTEM and Administrators

🛡️ Multi-Layer Protection

  1. Main Task: Initiates shutdown countdown (configurable duration)
    • Daily trigger at configured time
    • At Startup trigger to enforce shutdown if system rebooted during enforcement window
  2. Backstop Task: Monitors Main task integrity, triggers if tampered
    • Daily trigger at configured verification time
    • At Startup trigger with intelligent delay to allow Main to complete
  3. OnAbort Task: Detects shutdown cancellation attempts and resets shutdown
  4. Enforcement Window: Time range (e.g., 23:00-07:00) during which shutdown is enforced even after reboot

📧 Email Notifications

  • Gmail SMTP integration with App Password support
  • Notifications sent when tampering is detected
  • Installation summary emailed automatically

🔐 Guardian Override System

  • Password-protected emergency override
  • Secure password change mechanism
  • Complete system cleanup on authorized shutdown

🧪 Test Mode

  • Immediate task execution (1-2 minutes) for testing
  • Debug logging and verbose output
  • Temporary passwords for development

🔄 How It Works

Installation Phase

  1. Initialization

    • Creates event log source (AutoShutdown)
    • Selects random secure system folder for file storage
    • Generates all required GUID-named files
  2. Encryption Setup

    • Encrypts SMTP configuration with DPAPI + Entropy + HMAC
    • Creates guardian password hash (PBKDF2)
    • Encrypts all script payloads
  3. Task Creation

    • Main Task:
      • Daily trigger at user-specified time (or +1 min in test mode)
      • At Startup trigger for enforcement window protection
    • Backstop Task:
      • Daily trigger at user-specified time (or +2 min in test mode)
      • At Startup trigger with delay logic for enforcement verification
    • OnAbort Task: Event-triggered (EventID 1075 - shutdown cancellation)
  4. File Registry

    • Creates encrypted mapping of all GUID files
    • Stores file purposes and paths in encrypted registry
  5. Cleanup (Production Mode)

    • Removes plain-text script files
    • Keeps only encrypted payloads and override scripts

Runtime Operation

Main Task Execution (Daily Trigger)

[User-Specified Time] → Main Task Runs
  ↓
Initiates shutdown: /s /f /t [configurable seconds]
  ↓
Logs event to Windows Event Log

Main Task Execution (At Startup Trigger)

System Boots → Main Task Triggered
  ↓
Check Current Time vs Enforcement Window
  ├─ Outside Window (e.g., 10:00 AM) → Exit gracefully
  ├─ Inside Window (e.g., 02:00 AM) → Continue
  ↓
Calculate time since shutdown time
  ↓
Log enforcement activation (Warning level)
  ↓
Initiates shutdown: /s /f /t [configurable seconds]

Backstop Task Execution (Daily Trigger)

[User-Specified Time] → Backstop Task Runs
  ↓
Checks if Main Task exists
  ├─ NO → Send email + Immediate shutdown (60s)
  ├─ Disabled? → Send email + Immediate shutdown (60s)
  ↓
Verifies Task XML hash
  ├─ Tampered? → Send email + Immediate shutdown (60s)
  ↓
All OK → Log success + Exit

Backstop Task Execution (At Startup Trigger)

System Boots → Backstop Task Triggered
  ↓
Check Current Time vs Enforcement Window
  ├─ Outside Window → Exit gracefully
  ├─ Inside Window → Continue
  ↓
Check Main Task LastRunTime
  ├─ Main ran < N minutes ago → Wait for Main to complete
  │   ↓
  │   Sleep [wait time] minutes
  │   ↓
  │   Log: Wait period complete
  ├─ Main ran > N minutes ago → Proceed immediately
  ↓
Perform normal integrity verification
  ↓
If issues found → Send email + Immediate shutdown

OnAbort Task Execution

User cancels shutdown (Ctrl+Alt+Del)
  ↓
Windows logs EventID 1075
  ↓
OnAbort Task Triggered
  ↓
Sends notification email
  ↓
Resets shutdown: /s /f /t 60

🏗️ Architecture

Component Diagram

┌─────────────────────────────────────────────────────┐
│                  AutoShutdown.ps1                   │
│              (Installer & Generator)                │
└────────────────────┬────────────────────────────────┘
                     │
                     ├─► Creates Encrypted Files
                     ├─► Generates Scripts
                     └─► Registers Tasks
                          │
        ┌─────────────────┼─────────────────┐
        │                 │                 │
   ┌────▼────┐      ┌────▼────┐      ┌────▼────┐
   │  Main   │      │Backstop │      │ OnAbort │
   │  Task   │      │  Task   │      │  Task   │
   │(Custom) │      │(Custom) │      │ (Event) │
   └────┬────┘      └────┬────┘      └────┬────┘
        │                │                 │
        │                │                 │
   Shutdown         Verify &          Reset on
   Countdown        Enforce           Cancel
        │                │                 │
        └────────────────┴─────────────────┘
                          │
                ┌─────────▼─────────┐
                │  Override.ps1     │
                │  (User Override)  │
                └───────────────────┘

File Structure

Random System Folder (e.g., C:\Windows\System32\catroot2\{GUID}\)
├── {GUID}              ← Main.ps1 (encrypted, test mode only)
├── {GUID}              ← Backstop.ps1 (encrypted, test mode only)
├── {GUID}              ← OnAbort.ps1 (encrypted, test mode only)
├── {GUID}              ← Override.ps1 (plain, for user access)
├── {GUID}              ← Killer.ps1 (plain, for cleanup)
├── {GUID}              ← GuardianPwd.ps1 (plain, password change)
├── {GUID}              ← Password hash (JSON)
├── {GUID}              ← SMTP config (encrypted)
├── {GUID}              ← SMTP config entropy
├── {GUID}              ← SMTP HMAC metadata
├── {GUID}              ← Task XML hash reference
├── {GUID}              ← Main payload (encrypted)
├── {GUID}              ← Main entropy
├── {GUID}              ← Main HMAC
├── {GUID}              ← Backstop payload (encrypted)
├── {GUID}              ← Backstop entropy
├── {GUID}              ← Backstop HMAC
├── {GUID}              ← OnAbort payload (encrypted)
├── {GUID}              ← OnAbort entropy
├── {GUID}              ← OnAbort HMAC
├── {GUID}              ← File registry (encrypted)
└── {GUID}              ← File registry entropy

📦 Installation

Prerequisites

  • Windows 10/11 or Windows Server 2016+
  • PowerShell 5.1 or higher
  • Administrator privileges
  • Gmail account with App Password (for notifications)

Step-by-Step Installation

  1. Download all script files to a folder:

    AutoShutdown.ps1
    Backstop.ps1
    Common.ps1
    GuardianPwd.ps1
    Killer.ps1
    Main.ps1
    OnAbort.ps1
    Override.ps1
    
  2. Open PowerShell as Administrator

  3. Run the installer:

    Test Mode (recommended for first run):

    .\AutoShutdown.ps1 -TestMode $true
    • Tasks execute in 1-2 minutes
    • Debug logging enabled
    • Plain scripts kept for inspection

    Production Mode:

    .\AutoShutdown.ps1 -TestMode $false
    • Tasks scheduled at user-specified times
    • Plain scripts deleted after encryption
    • Full security hardening
  4. Provide configuration when prompted:

    • Shutdown countdown duration (in minutes, e.g., 10 for 10-minute warning)
    • Main task start time (HH:mm format, e.g., 23:00) - when daily shutdown begins
    • Enforcement end time (HH:mm format, e.g., 07:00) - when enforcement window closes
    • Backstop task start time (HH:mm format, e.g., 23:10 or 03:00) - verification time
    • Backstop delay minutes (e.g., 5) - how long Backstop waits for Main after startup
    • SMTP Username (Gmail address)
    • Gmail App Password (16 characters, no spaces)
    • Guardian notification email
    • Guardian password (for emergency override)
  5. Save the installation summary

    • Displayed on screen
    • Saved to AUTOSHUTDOWN_SUMMARY.txt
    • Emailed to guardian address
    • CRITICAL: Save BaseDir path and Override script path
  6. Confirm data saved:

    When you are done, type exactly: I SAVED IT
    

🎮 Usage

Normal Operation

Once installed, the system runs automatically:

  • Main task triggers at configured time daily
  • Backstop task verifies at configured time daily
  • OnAbort task monitors for cancellation attempts

No user interaction required unless override is needed.

Emergency Override

If you need to prevent shutdown on a specific day:

  1. Locate the Override script from your installation summary:

    C:\Windows\...\{GUID}
    
  2. Run as Administrator:

    powershell -ExecutionPolicy Bypass -File "C:\Windows\...\{GUID}"
  3. Enter guardian password when prompted

  4. Tasks will be removed and system cleanup initiated

Change Guardian Password

  1. Locate the GuardianPwd script from your installation summary

  2. Run as Administrator:

    powershell -ExecutionPolicy Bypass -File "C:\Windows\...\{GUID}"
  3. Enter current password

  4. Enter new password

  5. Password hash updated immediately

Complete System Removal

Use the Killer script for complete cleanup:

powershell -ExecutionPolicy Bypass -File "C:\Windows\...\{GUID-Killer}"

This will:

  • Disable and remove all tasks
  • Delete all files and folders
  • Self-destruct the killer script

🔐 Security Features

Encryption Layers

1. DPAPI (Data Protection API)

  • Uses Windows ProtectedData.Protect() with LocalMachine scope
  • Keys derived from machine and SYSTEM account credentials
  • Cannot be decrypted on different machines or by different users

2. Entropy Salt

  • 32-byte random entropy added to each DPAPI encryption
  • Prevents identical plaintext from producing identical ciphertext
  • Stored separately from encrypted payload

3. HMAC-SHA256 Authentication

  • Each encrypted payload has HMAC signature
  • HMAC key itself encrypted with DPAPI
  • Constant-time comparison prevents timing attacks
  • Detects any modification to encrypted data

Password Security

Guardian Password
       ↓
   PBKDF2
   (100,000 iterations)
       ↓
   Random Salt (16 bytes)
       ↓
   32-byte key
       ↓
   Stored as Base64 JSON

Anti-Tampering Mechanisms

  1. Task Integrity Monitoring

    • SHA-256 hash of task XML <Actions> block
    • Normalized XML to avoid false positives
    • Verified every time Backstop runs
  2. File Obfuscation

    • Pure GUID filenames (no extensions)
    • Hidden in deep system folders
    • Encrypted file registry mapping
  3. ACL Restrictions

    • SYSTEM:(OI)(CI)F - Full control for SYSTEM
    • Administrators:(OI)(CI)F - Full control for Admins
    • Users explicitly removed
    • Inheritance disabled
  4. Execution Context

    • All tasks run as SYSTEM account
    • Highest privilege level
    • No user interaction possible

Rollback Protection

If installation fails:

  • Automatic rollback initiated
  • All created files deleted
  • All registered tasks removed
  • Folders cleaned up if empty

🔧 Technical Details

Scheduled Tasks Configuration

Main Task

Triggers:
  1. Daily at [User-Configured Time] (e.g., 23:00)
  2. At Startup (for enforcement window protection)
Principal: SYSTEM (ServiceAccount, Highest)
Action: powershell.exe -EncodedCommand [BASE64]

At Startup Logic:

  • Checks if current time falls within enforcement window (StartTime to EndTime)
  • If outside window: exits gracefully without action
  • If inside window: calculates time since scheduled shutdown and initiates countdown
  • Prevents reboot bypass vulnerability

Backstop Task

Triggers:
  1. Daily at [User-Configured Time] (e.g., 23:10 or 03:00)
  2. At Startup (for enforcement window verification)
Principal: SYSTEM (ServiceAccount, Highest)
Action: powershell.exe -EncodedCommand [BASE64]

At Startup Logic:

  • Checks if current time falls within enforcement window
  • If Main task recently executed: waits configured delay (e.g., 5 minutes) to allow shutdown completion
  • Prevents race condition between Main and Backstop startup triggers
  • Proceeds with normal integrity verification after delay

OnAbort Task

Trigger: Event (System, USER32, EventID 1075)
Principal: SYSTEM (ServiceAccount, Highest)
Action: powershell.exe -EncodedCommand [BASE64]
Settings: IgnoreNew, AllowBatteries, NoStop

Event Log Integration

All operations logged to:

Log: AutoShutdown
Source: AutoShutdown

Event IDs:

  • 100 - Main OK (including startup enforcement activation)
  • 101 - Main Error
  • 102 - Main Warning (enforcement window active)
  • 103 - Main Debug (outside enforcement window)
  • 200 - Backstop OK (including startup delay logic)
  • 201 - Backstop Reset (tampering detected)
  • 202 - Backstop Error
  • 300 - OnAbort OK
  • 301 - OnAbort Error
  • 400 - Override OK
  • 401 - Override Error
  • 900 - General Error

Email Configuration

Uses Gmail SMTP with TLS 1.2+:

Server: smtp.gmail.com
Port: 587
Security: STARTTLS
Authentication: Username/Password

Important: Use Gmail App Password, not account password:

  1. Enable 2FA on Gmail account
  2. Generate App Password: https://myaccount.google.com/apppasswords
  3. Use 16-character password (remove spaces)

PowerShell Cmdlets Used

  • Register-ScheduledTask - Task creation
  • Export-ScheduledTask - Task XML extraction
  • New-EventLog / Write-EventLog - Logging
  • ProtectedData.Protect/Unprotect - DPAPI encryption
  • Rfc2898DeriveBytes - PBKDF2 key derivation
  • HMACSHA256 - Message authentication
  • icacls - ACL manipulation

💼 Use Cases

1. Self-Discipline & Healthy Habits

Scenario: Enforce personal discipline to limit computer time and maintain healthy sleep schedule

Implementation:

.\AutoShutdown.ps1 -TestMode $false
# When prompted:
# - Shutdown countdown: 15 minutes (time to finish up and save work)
# - Main task: 23:00 (11 PM - reasonable bedtime)
# - Enforcement end time: 07:00 (enforcement until morning)
# - Backstop task: 02:00 (catch late-night override attempts)
# - Backstop delay: 5 minutes (allow Main to complete on reboot)

Benefits:

  • Break bad habits: Force yourself to stop late-night browsing, gaming, or work
  • Consistent sleep schedule: Computer shuts down at same time daily
  • Reduce screen time: Natural limit on daily computer usage
  • Prevent procrastination: Hard deadline prevents "just 5 more minutes" syndrome
  • Reboot protection: Can't bypass by restarting computer during enforcement window (23:00-07:00)
  • Override available: Guardian password allows flexibility for legitimate late-night work
  • Anti-tampering: Can't easily disable when tired/tempted to stay up late
  • Health benefits: Encourages better sleep hygiene and work-life balance

Perfect for:

  • Night owls trying to fix sleep schedule
  • Remote workers struggling with work-life boundaries
  • Students procrastinating on bedtime
  • Anyone fighting internet/gaming addiction
  • People with ADHD who lose track of time

Real-world scenario: You get frustrated at 23:05 after the shutdown starts, force reboot the computer thinking you'll "just quickly check something." AutoShutdown detects you're within the 23:00-07:00 enforcement window and immediately re-initiates shutdown. No escape!

Tip: Set the countdown to 15-30 minutes to give yourself time to save work and wind down naturally, making the transition less abrupt.


2. Parental Controls

Scenario: Enforce bedtime for children using shared computer

Implementation:

.\AutoShutdown.ps1 -TestMode $false
# When prompted:
# - Shutdown countdown: 10 minutes
# - Main task: 21:00 (9 PM - children's bedtime)
# - Enforcement end time: 06:00 (enforcement until morning)
# - Backstop task: 21:10 (10 minutes after main)
# - Backstop delay: 3 minutes (quick verification on reboot)

Benefits:

  • Cannot be disabled by non-admin children
  • Prevents reboot bypass: Kids can't restart computer to continue using it (21:00-06:00)
  • Email notification if tampering attempted
  • Parents can override with password for homework/legitimate use
  • Configurable warning time before shutdown
  • Morning startup (after 06:00) works normally - ready for school day

3. Enterprise Energy Savings

Scenario: Corporate policy requires workstations off by 22:00

Implementation:

.\AutoShutdown.ps1 -TestMode $false
# When prompted:
# - Shutdown countdown: 30 minutes (give users warning)
# - Main task: 22:00 (10 PM - end of extended hours)
# - Enforcement end time: 06:00 (enforcement until office opens)
# - Backstop task: 03:00 (overnight verification)
# - Backstop delay: 5 minutes (allow Main to complete)
  • Deploy via Group Policy or SCCM
  • Central monitoring via email alerts
  • IT can override for maintenance windows
  • Prevents after-hours reboot: Users can't restart to continue working late

Benefits:

  • Significant energy cost reduction
  • Compliance enforcement with reboot protection
  • Security benefit (reduced attack surface)
  • Flexible countdown for user notification
  • Automatic morning availability (after 06:00)

4. Security Compliance

Scenario: Regulatory requirement for system shutdown

Implementation:

.\AutoShutdown.ps1 -TestMode $false
# When prompted:
# - Shutdown countdown: 15 minutes (compliance window)
# - Main task: 18:00 (end of business day)
# - Backstop task: 18:30 (verify compliance)
  • Scheduled shutdown aligned with business hours
  • Audit trail via Event Log
  • Guardian override for authorized exceptions

Benefits:

  • Automated compliance
  • Reduced human error
  • Auditable override mechanism
  • Customizable to organizational policies

5. Remote Worker Management

Scenario: Ensure remote employees disconnect at end of day

Implementation:

.\AutoShutdown.ps1 -TestMode $false
# When prompted:
# - Shutdown countdown: 60 minutes (long warning for work saving)
# - Main task: 19:00 (end of extended hours)
# - Backstop task: 20:00 (verify disconnection)
  • Standardized shutdown time across organization
  • Email notifications to managers
  • Exception handling via guardian password

Benefits:

  • Work-life balance enforcement
  • Reduced burnout
  • Clear boundaries for remote work
  • Extended countdown for saving work

6. Kiosk/Public Terminal Management

Scenario: Public computers must reset nightly

Implementation:

.\AutoShutdown.ps1 -TestMode $false
# When prompted:
# - Shutdown countdown: 5 minutes (minimal warning for public terminal)
# - Main task: 23:00 (after business hours)
# - Backstop task: 02:00 (deep night verification)
  • Scheduled shutdown triggers cleanup scripts
  • Anti-tampering prevents user bypass
  • No user interaction required

Benefits:

  • Consistent nightly maintenance
  • Tamper-proof operation
  • Reduced manual intervention
  • Minimal disruption with short countdown

🛠️ Troubleshooting

Enforcement Window Not Working

Symptoms:

  • System reboots and stays running during enforcement window
  • No shutdown initiated after startup

Check Event Log:

Get-EventLog -LogName AutoShutdown -Newest 10 |
    Where-Object {$_.EventID -in 100, 102, 103} |
    Format-List TimeGenerated, Message

Look for:

  • "Outside enforcement window" messages (EventID 103) - indicates time check is working
  • "ENFORCEMENT ACTIVE" messages (EventID 102) - confirms enforcement triggered
  • "Countdown start" messages (EventID 100) - shutdown initiated

Common Issues:

  1. System Clock Incorrect:

    # Check current time
    Get-Date -Format "HH:mm"
    
    # Verify time zone
    Get-TimeZone
  2. Enforcement Window Misconfigured:

    • Check if enforcement window makes sense (e.g., 23:00-07:00)
    • Verify Main task trigger includes "At Startup"
  3. Task Trigger Missing:

    # Check Main task triggers
    $task = Get-ScheduledTask -TaskName "AS_Main_*"
    $task.Triggers | Format-List
    
    # Should show BOTH:
    # - TriggerType: Daily
    # - TriggerType: AtStartup

Backstop Interfering with Main

Symptoms:

  • Both Main and Backstop trigger on startup
  • Duplicate shutdown attempts
  • Backstop sending false tampering alerts

Expected Behavior:

  • Backstop should wait configured delay (e.g., 5 minutes) after Main runs
  • Check Event Log for "Waiting X minute(s) for Main to complete" message

Check Backstop Delay Configuration:

Get-EventLog -LogName AutoShutdown -Newest 20 |
    Where-Object {$_.Message -like "*Waiting*minutes*Main*"}

If Backstop runs too early:

  • Increase BackstopDelayMinutes during reinstallation
  • Recommended: 5-10 minutes for typical systems

Task Not Executing

Check Task Status:

Get-ScheduledTask | Where-Object {$_.TaskName -like "AS_*"}

View Task History:

Get-WinEvent -LogName 'Microsoft-Windows-TaskScheduler/Operational' -MaxEvents 50 |
    Where-Object {$_.Message -like "*AS_*"}

Check Event Log:

Get-EventLog -LogName AutoShutdown -Newest 20

Email Notifications Not Received

Test Gmail Credentials:

$cred = Get-Credential
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -UseSsl `
    -Credential $cred -From "you@gmail.com" -To "recipient@example.com" `
    -Subject "Test" -Body "Test"

Common Issues:

  • Using account password instead of App Password
  • 2FA not enabled on Gmail
  • "Less secure apps" blocking (use App Password instead)
  • Incorrect SMTP settings

Cannot Locate Override Script

Find BaseDir from Event Log:

Get-EventLog -LogName AutoShutdown | Where-Object {$_.Message -like "*BaseDir*"}

Search for Override Script:

Get-ChildItem -Path "C:\Windows" -Recurse -Force -ErrorAction SilentlyContinue |
    Where-Object {$_.Length -gt 1KB -and $_.Length -lt 50KB} |
    Where-Object {$_.Name -match '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'}

Forgot Guardian Password

No password recovery available by design (security feature)

Options:

  1. Reinstall: Run AutoShutdown.ps1 again (will create new system)
  2. Manual cleanup: Delete tasks and files manually as Administrator
  3. System restore: Restore to pre-installation state

Prevention: Store password in secure password manager

System Boots but Shutdown Doesn't Trigger

Check BIOS/Firmware settings:

  • Fast Boot may skip task scheduler initialization
  • Power settings may prevent scheduled tasks

Check Task Scheduler Service:

Get-Service -Name Schedule | Restart-Service

Hash Mismatch Errors (False Positives)

If Backstop reports tampering but task is legitimate:

Review Event Log:

Get-EventLog -LogName AutoShutdown -Newest 1 |
    Select-Object -ExpandProperty Message

Check for Windows Updates:

  • Windows Updates may modify task metadata
  • Usually safe to regenerate hash

Regenerate Task Hash:

  1. Note current task configuration
  2. Delete and recreate Main task
  3. System will regenerate reference hash

📋 Requirements

System Requirements

  • OS: Windows 10 (1809+) or Windows Server 2016+
  • PowerShell: 5.1 or higher
  • .NET Framework: 4.7.2 or higher (for DPAPI/Crypto APIs)
  • Privileges: Administrator rights required

Network Requirements

  • Outbound SMTP: Port 587 (TLS)
  • DNS Resolution: smtp.gmail.com
  • Firewall: Allow PowerShell.exe outbound connections

Account Requirements

  • Gmail Account with 2FA enabled
  • Gmail App Password (16 characters)
  • Guardian email (can be same as Gmail or different)

Disk Space

  • Installation: ~1 MB
  • Runtime: ~500 KB (after cleanup)
  • Logs: ~10 MB (Event Log, cumulative)

Optional Requirements

  • Test Mode: Additional 2-3 MB for plain scripts
  • Debugging: ProcMon, Event Viewer

📁 Files Structure

Installation Files (Required)

File Description Required
AutoShutdown.ps1 Main installer script
Common.ps1 Shared utility functions
Main.ps1 Shutdown countdown logic
Backstop.ps1 Integrity verification
OnAbort.ps1 Cancellation handler
Override.ps1 User override mechanism
Killer.ps1 Complete cleanup script
GuardianPwd.ps1 Password change utility

Generated Files (Post-Installation)

File Type Count Purpose
Encrypted Scripts 3-6 Main/Backstop/OnAbort payloads
Entropy Files 3-4 DPAPI salts
HMAC Files 3-4 Authentication tags
Config Files 3 SMTP, Password, Hash reference
Registry Files 2 File mapping (encrypted + entropy)
User Scripts 3 Override, Killer, GuardianPwd

Total: ~18-25 files with GUID names

Documentation Files

File Description
README.md This file
FIXES_APPLIED.md Change log
AUTOSHUTDOWN_SUMMARY.txt Installation summary

⚠️ Important Notes

Security Considerations

  1. Guardian Password: Store securely. No recovery mechanism exists.
  2. Installation Summary: Keep AUTOSHUTDOWN_SUMMARY.txt in safe location.
  3. Email Access: Protect Gmail App Password.
  4. Override Script Path: Document location of Override script.

Limitations

  1. Machine-Specific: Encrypted files only work on installation machine.
  2. Account-Specific: SYSTEM account required; won't work with different user.
  3. Time-Based: Relies on system time; fails if clock severely skewed.
  4. Network-Dependent: Email notifications require internet connectivity.
  5. Timing Configuration: Cannot be changed after installation without reinstalling.
  6. Enforcement Window:
    • Requires accurate system clock for time-based enforcement
    • Does not prevent Safe Mode boot (by design - recovery option)
    • Enforcement ends at configured time (e.g., 07:00) - system can boot normally after

Best Practices

  1. Test First: Always use -TestMode $true before production deployment.
  2. Plan Timing: Choose appropriate shutdown time, backstop time, and countdown duration for your use case.
  3. Configure Enforcement Window: Set realistic window (e.g., 23:00-07:00) that covers sleep hours but allows morning use.
  4. Backstop Delay: Set to 5-10 minutes to give Main task enough time to complete shutdown on reboot.
  5. Document Everything: Save all paths, passwords, and timing configuration securely.
  6. Regular Audits: Check Event Log weekly for enforcement activations and anomalies.
  7. Backup Tasks: Export task XML periodically.
  8. Monitor Emails: Ensure guardian receives test notifications.
  9. Countdown Duration: Balance between user warning time and enforcement strictness.
  10. Test Enforcement: After installation, test a reboot during enforcement window to verify protection works.

Known Issues

  1. Windows Updates: May rarely cause hash mismatches (false positives).
  2. Time Sync: NTP failures can cause tasks to miss schedule or incorrect enforcement window detection.
  3. Hibernate/Sleep: May delay task execution until wake.
  4. Fast Startup: Can interfere with boot-time initialization and At Startup triggers.
  5. Rapid Reboots: If user reboots multiple times in quick succession, both Main and Backstop may trigger simultaneously (Backstop delay mitigates this).
  6. Time Zone Changes: Enforcement window based on local time; DST or timezone changes may affect behavior.

🤝 Contributing

This is a security-critical system. Contributions should:

  • Maintain backward compatibility
  • Include thorough testing
  • Document all security implications
  • Follow PowerShell best practices

📄 License

This project is provided as-is for educational and personal use.


🆘 Support

For issues or questions:

  1. Check Event Log: AutoShutdown log
  2. Review AUTOSHUTDOWN_SUMMARY.txt
  3. Consult this README
  4. Check FIXES_APPLIED.md for recent changes

🔄 Version History

v1.1.0 (October 2025)

  • NEW: Enforcement window protection (prevents reboot bypass)
  • NEW: At Startup triggers for Main and Backstop tasks
  • NEW: Intelligent Backstop delay logic to avoid race conditions
  • NEW: Test-EnforcementWindow helper function
  • Enhanced Event Log messages with enforcement status
  • Improved documentation with enforcement window examples

v1.0.0 (October 2025)

  • Initial release
  • DPAPI + HMAC encryption
  • Three-task architecture
  • Gmail notification support
  • Guardian password override
  • File obfuscation with GUIDs
  • Event log integration

📞 Emergency Contacts

Critical System Failure:

  1. Boot to Safe Mode
  2. Manually delete tasks: C:\Windows\System32\Tasks\AS_*
  3. Delete folder from BaseDir
  4. Restart normally

Lost All Documentation:

  1. Search Event Log for installation details
  2. Use Get-ScheduledTask to find task paths
  3. Extract BaseDir from task command line
  4. Locate Override script by GUID pattern match

End of README | Last Updated: October 9, 2025

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors