Security Audit and Compliance Toolkit (Windows) – A Comprehensive Guide with Code Walkthrough

TATHAGATA ROYTATHAGATA ROY
16 min read

Introduction to Security Audit and Compliance Toolkit

In today's digital landscape, ensuring the security and compliance of our systems is crucial. With threats ranging from unauthorized access to data breaches, organizations must regularly conduct security audits and comply with industry standards like HIPAA, ISO 27001, and PCI DSS. The Security Audit and Compliance Toolkit is a powerful yet simple tool designed for Windows users, enabling easy-to-run security audits and compliance checks through a clean web interface.

This toolkit is designed to automate the auditing process, making it simpler to check for firewall vulnerabilities, manage active users, and ensure that our system adheres to essential compliance standards. It provides a straightforward interface where users can select various audit types and run them without needing extensive technical knowledge.

Key Features of the Toolkit

Firewall Audit

The Firewall Audit checks the status of the system's firewall settings, ensuring that the firewall is correctly configured to prevent unauthorized access. This audit can also identify open ports, which are potential entry points for malicious activity.

User Audit

The User Audit lists all active users on the system, including remote users. This is critical in ensuring that only authorized personnel have access to the system, and it helps detect potential unauthorized login sessions.

HIPAA Compliance

HIPAA (Health Insurance Portability and Accountability Act) compliance is essential for organizations handling healthcare data. The toolkit helps ensure that sensitive data is encrypted, proper access control measures are in place, and other key HIPAA requirements are met.

ISO 27001 Compliance

ISO 27001 is the international standard for information security management. This feature ensures that key security controls, such as password policies and firewall configurations, meet the necessary criteria.

PCI DSS Compliance

PCI DSS (Payment Card Industry Data Security Standard) is critical for organizations handling payment card data. The toolkit checks for SSL/TLS usage, unnecessary open ports, and other key elements to ensure that our system complies with PCI DSS.

Toolkit Installation and Setup

To get started with the Security Audit and Compliance Toolkit, follow these simple steps:

1. Cloning the Repository

First, you need to clone the repository from GitHub. The following command will download all the necessary files for the toolkit:


git clone https://github.com/roy9495/Security-Audit-and-Compliance-Toolkit.git

This command creates a local copy of the repository on your system. After cloning, navigate to the directory using the following command:


cd roy9495-Security-Audit-and-Compliance-Toolkit

2. Installing Dependencies

The toolkit relies on Python and the Flask web framework to run the server-side logic. To install the required dependencies, run the following command inside the project's root directory:


pip install -r requirements.txt

This will install the necessary Python packages, such as Flask and Werkzeug. These packages are crucial for setting up the web server and handling HTTP requests.

3. Running the Application

Once all dependencies are installed, you can start the toolkit by running the app.py file, which contains the main logic for the web application. Navigate to the src folder and execute the following command:


cd src/
python app.py

This command starts the Flask web server, making the toolkit accessible via the browser at http://localhost:5000/.

The GitHub repository is at https://github.com/roy9495/Security-Audit-and-Compliance-Toolkit .

Project Structure Breakdown

The Security Audit and Compliance Toolkit has separate frontend, backend, and script files. Here’s an overview of the project structure:


/security-audit-toolkit/
├── frontend/
│   ├── static/
│   │   └── styles.css
│   ├── templates/
│   │   └── index.html
├── scripts/
│   ├── audit_firewall.bat
│   ├── audit_users.bat
│   ├── compliance_iso27001.ps1
│   ├── compliance_pci_dss.ps1
│   ├── compliance_hipaa.ps1
│   ├── intrusion_detection.ps1
│   ├── patch_management.ps1
│   ├── privilege_escalation_test.ps1
│   ├── system_hardening.ps1
├── src/
│   ├── app.py
│   ├── audit.py
│   ├── compliance.py
│   ├── db.py
│   ├── security_tools.py
├── requirements.txt
├── README.md

Explanation of Project Structure

frontend: Contains the static assets and templates for the web interface. The static folder stores the CSS for styling, while the templates folder holds the main HTML file (index.html) that structures the web interface.

scripts: This directory holds all the batch scripts (.bat) and PowerShell scripts (.ps1) that perform the actual auditing and compliance tasks. These scripts are executed via Python code when the user initiates a task from the web interface.

src: Contains the core Python files for running the application, including app.py, which serves as the entry point, and audit.py, compliance.py, and security_tools.py, which handle specific auditing and compliance functions.

requirements.txt: Lists the Python dependencies required to run the application.

README.md: Provides instructions and an overview of the toolkit.

Code Walkthrough of Each Component

Let’s dive into each component to understand how the code is structured and functions.

Frontend Code Overview

The frontend part of the toolkit handles the user interface where the audits and compliance checks are initiated. This part of the project is found under the frontend/ directory. The main files to look at here are index.html and styles.css.

1.styles.css

The styles.css file sets the page's layout, centers the content, and styles the buttons used to trigger various audits and checks.


body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.container {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    text-align: center;
}

button {
    padding: 10px 20px;
    margin: 10px;
    border: none;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    border-radius: 5px;
}

button:hover {
    background-color: #0056b3;
}

pre {
    background-color: #e9ecef;
    padding: 15px;
    border-radius: 8px;
    text-align: left;
}

2.index.html

The main HTML file index.html provides the structure of the web interface. It contains buttons to initiate each audit and displays the results in a preformatted text area.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Security Audit Dashboard</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <div class="container">
        <h1>Security Audit and Compliance Toolkit</h1>

        <button onclick="runTask('firewall', 'audit')">Run Firewall Audit</button>
        <button onclick="runTask('users', 'audit')">Run User Audit</button>
        <button onclick="runTask('iso27001', 'compliance')">ISO 27001 Compliance</button>
        <button onclick="runTask('pci-dss', 'compliance')">PCI-DSS Compliance</button>
        <button onclick="runTask('hipaa', 'compliance')">HIPAA Compliance</button><br>
        <button onclick="runSecurityCheck('patch_management')">Patch Management</button>
        <button onclick="runSecurityCheck('system_hardening')">System Hardening</button>
        <button onclick="runSecurityCheck('privilege_escalation_test')">Privilege Escalation Test</button>
        <button onclick="runSecurityCheck('intrusion_detection')">Intrusion Detection</button>

        <!-- Output Area -->
        <pre id="audit-results">Audit results will appear here...</pre>
    </div>

    <script>
        // General function to handle both audits and compliance tasks
        function runTask(type, category) {
            const resultsContainer = document.getElementById('audit-results');
            // Clear previous results and display loading message
            resultsContainer.innerText = `Running ${type.toUpperCase()} ${category}... Please wait.`;

            let endpoint = category === 'audit' ? `/api/${type}` : `/api/compliance/${type}`;

            // Fetch the data from the correct API endpoint
            fetch(endpoint)
                .then(response => response.json())
                .then(data => {
                    // Display the result in the preformatted text area
                    resultsContainer.innerText = data.result;
                })
                .catch(error => {
                    // Handle errors gracefully
                    resultsContainer.innerText = `Error: ${error.message}`;
                });
        }

        // Function to handle security checks
        function runSecurityCheck(type) {
            const resultsContainer = document.getElementById('audit-results');
            // Clear previous results and display loading message
            resultsContainer.innerText = `Running ${type.replace('_', ' ').toUpperCase()}... Please wait.`;

            // Fetch the data from the API endpoint for security checks
            fetch(`/api/${type}`)
                .then(response => response.json())
                .then(data => {
                    // Display the result in the preformatted text area
                    resultsContainer.innerText = data.result;
                })
                .catch(error => {
                    // Handle errors gracefully
                    resultsContainer.innerText = `Error: ${error.message}`;
                });
        }
    </script>
</body>
</html>

Backend Code Overview

The backend of the toolkit is powered by Flask, a lightweight Python web framework. The backend code is responsible for serving the web interface and handling requests for different security tasks. Let’s break down the key components of the backend, starting with app.py.

app.py– Main Application Logic

The app.py file is the entry point for the Flask web application. It defines the routes for the different APIs that handle audits and compliance tasks. Here’s the breakdown of its functionality:


from flask import Flask, render_template, jsonify
import audit  # Import our audit logic
import compliance
import security_tools


app = Flask(__name__, template_folder='../frontend/templates', static_folder='../frontend/static')

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/api/firewall')
def api_firewall():
    firewall_result = audit.audit_firewall()
    return jsonify({"result": firewall_result})

@app.route('/api/users')
def api_users():
    user_result = audit.audit_users()
    return jsonify({"result": user_result})

# API routes for compliance tests
@app.route('/api/compliance/iso27001')
def api_iso27001():
    result = compliance.iso27001_compliance()
    return jsonify({"result": result})

@app.route('/api/compliance/pci-dss')
def api_pci_dss():
    result = compliance.pci_dss_compliance()
    return jsonify({"result": result})

@app.route('/api/compliance/hipaa')
def api_hipaa():
    result = compliance.hipaa_compliance()
    return jsonify({"result": result})

# API routes for security tasks
@app.route('/api/patch_management')
def api_patch_management():
    result = security_tools.patch_management()
    return jsonify({"result": result})

@app.route('/api/system_hardening')
def api_system_hardening():
    result = security_tools.system_hardening()
    return jsonify({"result": result})

@app.route('/api/privilege_escalation_test')
def api_privilege_escalation_test():
    result = security_tools.privilege_escalation_test()
    return jsonify({"result": result})

@app.route('/api/intrusion_detection')
def api_intrusion_detection():
    result = security_tools.intrusion_detection()
    return jsonify({"result": result})

if __name__ == '__main__':
    app.run(debug=True)

The code above does the following:

  • home(): Renders the main HTML page (index.html) when the user visits the root URL.

  • api_firewall(): Executes the firewall audit using a function from audit.py and returns the result as JSON.

  • api_users(): Runs the user audit and returns the list of active users.

  • Compliance Routes: Separate routes handle compliance checks for ISO 27001, HIPAA, and PCI DSS, using the appropriate functions from compliance.py.

  • Security Tasks: Additional routes run patch management, system hardening, privilege escalation tests, and intrusion detection, using functions from security_tools.py.

Whenever a user clicks a button on the frontend, it triggers one of these API routes. The Flask application then processes the request and returns the audit result, which is displayed on the web page.

audit.py– Running Audit Scripts

The audit.py file contains the logic for running the batch scripts used in firewall and user audits. It utilizes Python's subprocess module to execute external commands and capture the output.

import subprocess
import os

def run_bash_script(script_name):
    """Executes a batch script using a corrected relative path"""
    base_dir = os.path.dirname(os.path.abspath(__file__))  # Get absolute path of current script (src/)
    script_path = os.path.join(base_dir, '..', 'scripts', script_name)  # Go up one level to find scripts/

    # Check if the script file exists
    if not os.path.exists(script_path):
        return f"Error: Script {script_path} not found!"

    # Execute the batch file
    result = subprocess.run(script_path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    # Return any error messages if the script fails
    if result.returncode != 0:
        return f"Error: {result.stderr.decode('utf-8')}"

    return result.stdout.decode('utf-8')

def audit_firewall():
    """Runs the firewall audit"""
    return run_bash_script('audit_firewall.bat')

def audit_users():
    """Runs the user audit"""
    return run_bash_script('audit_users.bat')

The run_bash_script() function takes a script name as input, constructs its path, and runs the batch file using subprocess.run(). The firewall and user audits are initiated using the audit_firewall() and audit_users() functions, respectively.

compliance.py– Running Compliance Scripts

The compliance.py file contains functions to execute the PowerShell scripts that check compliance with HIPAA, ISO 27001, and PCI DSS. Like audit.py, it uses subprocess to execute these scripts.

import subprocess

def run_compliance_check(script_name):
    """Executes a compliance script and returns the result"""
    script_path = f'../scripts/{script_name}'
    result = subprocess.run(["powershell", "-ExecutionPolicy", "Bypass", "-File", script_path],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    if result.returncode != 0:
        return f"Error: {result.stderr.decode('utf-8')}"

    return result.stdout.decode('utf-8')

def iso27001_compliance():
    return run_compliance_check('compliance_iso27001.ps1')

def pci_dss_compliance():
    return run_compliance_check('compliance_pci_dss.ps1')

def hipaa_compliance():
    return run_compliance_check('compliance_hipaa.ps1')

Each compliance function (e.g., iso27001_compliance()) calls run_compliance_check() with the appropriate PowerShell script name. The output is returned as a string to be displayed on the web interface.

Security Tools and Script Breakdown

In addition to audit and compliance checks, the Security Audit and Compliance Toolkit includes various PowerShell scripts that perform essential security tasks. These tasks range from patch management and system hardening to privilege escalation tests and intrusion detection.

All these scripts are located in the scripts/ directory and are executed by the backend code in security_tools.py. Let’s go over each script and see how they work.

Patch Management

Regular patch management is crucial to keeping a system secure. The patch_management.ps1 script automates the process of checking for missing Windows updates and installing them. The script also accepts auto-reboot commands to ensure the updates are fully applied.

Write-Output "Checking for missing updates..."

Get-WindowsUpdate -Install -AcceptAll -AutoReboot | Out-String | Write-Output

This PowerShell script utilizes the Get-WindowsUpdate cmdlet to fetch and install all missing updates. It accepts all updates without requiring user intervention and reboots the system automatically if necessary.

Backend Execution of Patch Management

The patch_management() function in security_tools.py handles the execution of this script. It’s triggered by the corresponding button on the web interface.

def patch_management():
    return run_powershell_script('patch_management.ps1')

The run_powershell_script() function runs the patch_management.ps1 script, capturing the output and returning it to the frontend for display.

System Hardening

System hardening involves applying security configurations to reduce the attack surface. The system_hardening.ps1 script checks key configurations, such as password policies and Remote Desktop Protocol (RDP) settings, to ensure the system is hardened.

Write-Output "System Hardening Check..."

# Check for password policy (complexity)
$PasswordPolicy = Get-ADDefaultDomainPasswordPolicy
if ($PasswordPolicy.ComplexityEnabled) {
    Write-Output "PASS: Password complexity is enabled."
} else {
    Write-Output "FAIL: Password complexity is disabled."
}

# Check if remote desktop is disabled
$RemoteDesktop = Get-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Terminal Server\' -Name "fDenyTSConnections"
if ($RemoteDesktop.fDenyTSConnections -eq 1) {
    Write-Output "PASS: Remote desktop is disabled."
} else {
    Write-Output "FAIL: Remote desktop is enabled."

This script checks two important security configurations:

  • Whether the password policy enforces password complexity.

  • Whether Remote Desktop Protocol (RDP) is disabled, reducing the risk of remote attacks.

Like the patch management script, this script is executed by the system_hardening() function in security_tools.py.

Privilege Escalation Test

Privilege escalation is a common attack where malicious users try to gain administrative access to the system. The privilege_escalation_test.ps1 script checks whether the current user has administrator privileges and whether there are any weak service permissions that could be exploited.

Write-Output "Privilege Escalation Test..."

# Check if current user has admin privileges
if ([Security.Principal.WindowsIdentity]::GetCurrent().Groups -match "S-1-5-32-544") {
    Write-Output "Warning: User has local administrator privileges."
} else {
    Write-Output "PASS: User does not have local administrator privileges."
}

# Check for weak service permissions (can lead to privilege escalation)
$services = Get-WmiObject win32_service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Running' }
foreach ($service in $services) {
    $permissions = Get-Acl "HKLM:\SYSTEM\CurrentControlSet\Services\$($service.Name)"
    if ($permissions.Access | Where-Object { $_.IdentityReference -eq 'Everyone' -or $_.IdentityReference -eq 'Authenticated Users' }) {
        Write-Output "Warning: Service $($service.Name) has weak permissions."
    }
}

This script performs two checks:

  • Admin Privileges: It verifies if the current user has local administrator privileges, which could be exploited.

  • Weak Service Permissions: It checks the system's services for weak access control lists (ACLs) that allow excessive permissions, such as Everyone or Authenticated Users.

Backend Execution of Privilege Escalation Test

The privilege_escalation_test() function in security_tools.py handles the execution of this script and returns the result to the frontend.


def privilege_escalation_test():
    return run_powershell_script('privilege_escalation_test.ps1')

By running this script, administrators can identify users with elevated privileges and services with weak permissions, helping to reduce the risk of privilege escalation attacks.

Intrusion Detection

The intrusion_detection.ps1 script helps detect potential security breaches by scanning Windows Event Logs for failed login attempts and suspicious processes.

Write-Output "Intrusion Detection Check..."

# Detect failed login attempts in Event Viewer (Event ID 4625)
$failedLogins = Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4625} | Select-Object -First 10
if ($failedLogins) {
    Write-Output "Warning: Found failed login attempts!"
    $failedLogins | Format-List | Write-Output
} else {
    Write-Output "PASS: No failed login attempts found."
}

# Check for suspicious process creations (Event ID 4688)
$suspiciousProcesses = Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4688} | Where-Object { $_.Message -like '*powershell.exe*' -or $_.Message -like '*cmd.exe*' }
if ($suspiciousProcesses) {
    Write-Output "Warning: Found suspicious processes created!"
    $suspiciousProcesses | Format-List | Write-Output
} else {
    Write-Output "PASS: No suspicious processes found."

This script performs the following intrusion detection checks:

  • Failed Logins: It scans Event Viewer for failed login attempts (Event ID 4625) and displays details of these attempts.

  • Suspicious Processes: It checks for suspicious process creations, such as powershell.exe or cmd.exe, which are commonly used in attacks.

By running this script, administrators can detect unauthorized login attempts and potentially malicious activities, helping to catch intrusions early.

Backend Execution of Intrusion Detection

The intrusion_detection() function in security_tools.py handles the execution of the intrusion detection script.


def intrusion_detection():
    return run_powershell_script('intrusion_detection.ps1')

Database for Storing Audit Results

The toolkit also includes a simple SQLite database to store audit results. This functionality is handled by the db.py file, which contains functions to initialize the database and save audit results.

Database Initialization

The init_db() function initializes the SQLite database if it doesn’t already exist. It creates a table named results to store the audit type, result, and date.

import sqlite3

def init_db():
    conn = sqlite3.connect('audit_results.db')
    cursor = conn.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS results 
                      (id INTEGER PRIMARY KEY, audit_type TEXT, result TEXT, date TEXT)''')
    conn.commit()
    conn.close()

Saving Audit Results

The save_audit_result() function inserts new audit results into the database. It logs the type of audit (e.g., firewall, users), the result of the audit, and the timestamp when it was conducted.

def save_audit_result(audit_type, result):
    conn = sqlite3.connect('audit_results.db')
    cursor = conn.cursor()
    cursor.execute("INSERT INTO results (audit_type, result, date) VALUES (?, ?, datetime('now'))", 
                   (audit_type, result))
    conn.commit()
    conn.close()

This function ensures that the results of every audit or compliance check are stored for future reference, allowing administrators to track the system’s security status over time.

Real-World Use Cases for the Toolkit

The Security Audit and Compliance Toolkit is designed to address security and compliance requirements across various industries. It automates the process of performing audits and ensures compliance with major security frameworks like HIPAA, PCI DSS, and ISO 27001. Let’s explore a few real-world use cases where this toolkit can be invaluable.

Use Case 1: Corporate Environment Firewall and User Audits

In large corporate environments, administrators need to maintain strict control over network firewalls and user access. With the toolkit’s Firewall Audit, organizations can quickly check firewall settings across multiple workstations to ensure that only necessary ports are open and that the firewall is properly configured.

In addition, the User Audit allows organizations to monitor who is currently logged into each machine, including remote users. This is critical for identifying unauthorized access or dormant sessions that could lead to a security breach.

Use Case 2: Ensuring HIPAA Compliance in Healthcare Organizations

Healthcare organizations are required to follow strict regulations to protect patient data under HIPAA (Health Insurance Portability and Accountability Act). The toolkit’s HIPAA compliance feature checks essential aspects like data encryption and access control to ensure that patient information is secure.

For instance, the compliance_hipaa.ps1 script checks if disk encryption (e.g., BitLocker) is enabled and if sensitive data is properly protected with Access Control Lists (ACLs). This can help prevent data breaches and ensure that the organization remains compliant with HIPAA regulations.

Use Case 3: PCI DSS Compliance for Payment Processors

For organizations that handle credit card payments, ensuring PCI DSS (Payment Card Industry Data Security Standard) compliance is crucial. The toolkit’s PCI DSS compliance checks ensure that systems handling payment data are secure.

The compliance_pci_dss.ps1 script checks if SSL/TLS is enabled for secure communications on port 443 and ensures that there are no unnecessary open ports, which could be exploited by attackers. This is essential for organizations processing payments, as non-compliance with PCI DSS can result in hefty fines and reputational damage.

Use Case 4: System Hardening and Intrusion Detection for Small Businesses

Small businesses often lack the resources for a dedicated IT security team, making it essential to use tools that automate system hardening and intrusion detection. The System Hardening feature ensures that security best practices, such as strong password policies and disabling remote desktop access, are in place.

Additionally, the toolkit’s Intrusion Detection feature scans for suspicious activities like failed login attempts and unauthorized process executions. This helps small businesses detect potential security breaches before they escalate into full-blown incidents.

Benefits and Limitations of the Toolkit

The Security Audit and Compliance Toolkit offers numerous benefits for organizations looking to improve their security posture and ensure compliance with industry standards. However, like any tool, it has some limitations. Let’s explore both aspects.

Benefits

  • User-Friendly Web Interface: The toolkit’s simple web interface allows users to run audits and compliance checks without needing deep technical knowledge. The clear layout and preformatted output make it easy to interpret results.

  • Automated Audits and Compliance Checks: Instead of manually running scripts or checking each system, the toolkit automates the process. This not only saves time but also ensures consistency in how audits are conducted across systems.

  • Comprehensive Compliance Coverage: The toolkit covers major compliance frameworks, including HIPAA, ISO 27001, and PCI DSS.

  • Customizable Scripts: Since the toolkit is open-source, organizations can easily modify the PowerShell and batch scripts to add new checks or tailor existing ones to meet their specific needs.

  • Real-Time Security Monitoring: Features like Intrusion Detection and Privilege Escalation Testing help administrators detect and address security threats in real-time, reducing the risk of compromised systems.

Limitations

  • Windows-Only: The toolkit is currently limited to Windows systems.

  • Focus on Basic Audits: The toolkit provides basic security and compliance audits.

Potential Features for Future Versions

  • Linux and macOS Compatibility: A future version of the toolkit could include support for Linux and macOS systems. This would involve creating shell scripts or using other system-specific commands to perform similar audits and compliance checks.

  • GDPR Compliance Module: With increasing data privacy regulations, adding a module for GDPR (General Data Protection Regulation) compliance checks would allow organizations to ensure that they handle personal data in accordance with EU law.

  • Enhanced Reporting and Logging: Providing more detailed reports and logs on audit results could help organizations maintain compliance documentation and provide better visibility into their security posture.

Conclusion

The Security Audit and Compliance Toolkit provides a powerful solution for organizations looking to automate their security audits and ensure compliance with industry standards. With features like firewall audits, user audits, and compliance checks for HIPAA, PCI DSS, and ISO 27001, the toolkit offers a comprehensive solution for securing Windows environments.

0
Subscribe to my newsletter

Read articles from TATHAGATA ROY directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

TATHAGATA ROY
TATHAGATA ROY

Hello! I'm a passionate and dedicated individual with a love for learning and writing about it.