Tag Archive for: Security

Simple IIS Security Check Tool

<#
.SYNOPSIS
Simple IIS Security Check Tool

.DESCRIPTION
This script performs basic security checks on an IIS server. It is for educational purposes only
and should only be used on systems you own or have explicit permission to test.

.NOTES
File Name      : SimpleIISSecurityCheck.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights, and proper authorization
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\SimpleIISSecurityCheck.ps1
#>

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\IIS_Security_Check_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
$global:targetServer = "localhost"  # Default to local machine

function Show-Menu {
    Clear-Host
    Write-Host "=== Simple IIS Security Check Tool ===" -ForegroundColor Cyan
    Write-Host "Target Server: $global:targetServer"
    Write-Host "1. Set Target Server"
    Write-Host "2. Check IIS Version"
    Write-Host "3. Enumerate Web Sites"
    Write-Host "4. Check for Default Web Pages"
    Write-Host "5. Check Directory Browsing"
    Write-Host "6. Check HTTP Response Headers"
    Write-Host "7. Check SSL/TLS Configuration"
    Write-Host "8. Generate HTML Report"
    Write-Host "9. Exit"
}

function Set-TargetServer {
    $server = Read-Host "Enter the target server name or IP (or press Enter for localhost)"
    if ([string]::IsNullOrWhiteSpace($server)) {
        $global:targetServer = "localhost"
    } else {
        $global:targetServer = $server
    }
    Write-Host "Target server set to: $global:targetServer" -ForegroundColor Green
}

function Check-IISVersion {
    Write-Host "`nChecking IIS Version..." -ForegroundColor Yellow
    try {
        $iisVersion = Invoke-Command -ComputerName $global:targetServer -ScriptBlock {
            Get-ItemProperty HKLM:\SOFTWARE\Microsoft\InetStp\ | Select-Object MajorVersion, MinorVersion
        }
        $version = "$($iisVersion.MajorVersion).$($iisVersion.MinorVersion)"
        Write-Host "IIS Version: $version" -ForegroundColor Green
        return $version
    } catch {
        Write-Host "Error checking IIS version: $_" -ForegroundColor Red
        return "Error"
    }
}

function Enumerate-WebSites {
    Write-Host "`nEnumerating Web Sites..." -ForegroundColor Yellow
    try {
        $sites = Invoke-Command -ComputerName $global:targetServer -ScriptBlock {
            Import-Module WebAdministration
            Get-Website | Select-Object Name, ID, State, PhysicalPath, Bindings
        }
        $sites | Format-Table -AutoSize
        return $sites
    } catch {
        Write-Host "Error enumerating web sites: $_" -ForegroundColor Red
        return $null
    }
}

function Check-DefaultWebPages {
    Write-Host "`nChecking for Default Web Pages..." -ForegroundColor Yellow
    $defaultPages = @("iisstart.htm", "default.aspx", "index.html", "index.htm")
    $results = @()
    
    $sites = Invoke-Command -ComputerName $global:targetServer -ScriptBlock {
        Import-Module WebAdministration
        Get-Website | Select-Object Name, PhysicalPath
    }

    foreach ($site in $sites) {
        foreach ($page in $defaultPages) {
            $path = Join-Path $site.PhysicalPath $page
            $exists = Invoke-Command -ComputerName $global:targetServer -ScriptBlock {
                param($path)
                Test-Path $path
            } -ArgumentList $path

            if ($exists) {
                $results += [PSCustomObject]@{
                    Site = $site.Name
                    DefaultPage = $page
                    Exists = $true
                }
            }
        }
    }

    if ($results.Count -eq 0) {
        Write-Host "No default pages found." -ForegroundColor Green
    } else {
        $results | Format-Table -AutoSize
    }
    return $results
}

function Check-DirectoryBrowsing {
    Write-Host "`nChecking Directory Browsing..." -ForegroundColor Yellow
    try {
        $dirBrowsing = Invoke-Command -ComputerName $global:targetServer -ScriptBlock {
            Import-Module WebAdministration
            Get-WebConfigurationProperty -Filter /system.webServer/directoryBrowse -Name enabled -PSPath 'IIS:\'
        }
        if ($dirBrowsing.Value) {
            Write-Host "Directory Browsing is enabled" -ForegroundColor Red
        } else {
            Write-Host "Directory Browsing is disabled" -ForegroundColor Green
        }
        return $dirBrowsing.Value
    } catch {
        Write-Host "Error checking directory browsing: $_" -ForegroundColor Red
        return $null
    }
}

function Check-HTTPResponseHeaders {
    Write-Host "`nChecking HTTP Response Headers..." -ForegroundColor Yellow
    try {
        $headers = Invoke-Command -ComputerName $global:targetServer -ScriptBlock {
            Import-Module WebAdministration
            Get-WebConfigurationProperty -Filter /system.webServer/httpProtocol/customHeaders -Name . -PSPath 'IIS:\'
        }
        $headers | Format-Table -AutoSize
        return $headers
    } catch {
        Write-Host "Error checking HTTP response headers: $_" -ForegroundColor Red
        return $null
    }
}

function Check-SSLTLSConfiguration {
    Write-Host "`nChecking SSL/TLS Configuration..." -ForegroundColor Yellow
    try {
        $sslSettings = Invoke-Command -ComputerName $global:targetServer -ScriptBlock {
            $protocols = @("SSL 2.0", "SSL 3.0", "TLS 1.0", "TLS 1.1", "TLS 1.2")
            $results = @{}
            foreach ($protocol in $protocols) {
                $clientPath = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\$protocol\Client"
                $serverPath = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\$protocol\Server"
                $clientEnabled = (Get-ItemProperty -Path $clientPath -Name "Enabled" -ErrorAction SilentlyContinue).Enabled
                $serverEnabled = (Get-ItemProperty -Path $serverPath -Name "Enabled" -ErrorAction SilentlyContinue).Enabled
                $results[$protocol] = @{
                    "ClientEnabled" = if ($clientEnabled -eq 1) { "Enabled" } elseif ($clientEnabled -eq 0) { "Disabled" } else { "Not Configured" }
                    "ServerEnabled" = if ($serverEnabled -eq 1) { "Enabled" } elseif ($serverEnabled -eq 0) { "Disabled" } else { "Not Configured" }
                }
            }
            return $results
        }
        $sslSettings | Format-Table -AutoSize
        return $sslSettings
    } catch {
        Write-Host "Error checking SSL/TLS configuration: $_" -ForegroundColor Red
        return $null
    }
}

function Generate-HTMLReport {
    param([hashtable]$AllResults)

    Write-Host "`nGenerating HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IIS Security Check Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .warning { color: orange; }
        .critical { color: red; }
    </style>
</head>
<body>
    <h1>IIS Security Check Report</h1>
    <p>Generated on: $(Get-Date)</p>
    <p>Target Server: $global:targetServer</p>

    <h2>IIS Version</h2>
    <p>$($AllResults.IISVersion)</p>

    <h2>Web Sites</h2>
    $($AllResults.WebSites | ConvertTo-Html -Fragment)

    <h2>Default Web Pages</h2>
    $($AllResults.DefaultPages | ConvertTo-Html -Fragment)

    <h2>Directory Browsing</h2>
    <p>$(if ($AllResults.DirectoryBrowsing) { '<span class="critical">Enabled</span>' } else { '<span class="warning">Disabled</span>' })</p>

    <h2>HTTP Response Headers</h2>
    $($AllResults.HTTPHeaders | ConvertTo-Html -Fragment)

    <h2>SSL/TLS Configuration</h2>
    $($AllResults.SSLTLSConfig | ConvertTo-Html -Fragment)
</body>
</html>
"@

    $reportContent | Out-File -FilePath $global:reportPath
    Write-Host "Report generated and saved to: $global:reportPath" -ForegroundColor Green
}

# Main program loop
$allResults = @{}

do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-9)"

    switch ($choice) {
        "1" { Set-TargetServer }
        "2" { $allResults.IISVersion = Check-IISVersion }
        "3" { $allResults.WebSites = Enumerate-WebSites }
        "4" { $allResults.DefaultPages = Check-DefaultWebPages }
        "5" { $allResults.DirectoryBrowsing = Check-DirectoryBrowsing }
        "6" { $allResults.HTTPHeaders = Check-HTTPResponseHeaders }
        "7" { $allResults.SSLTLSConfig = Check-SSLTLSConfiguration }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "9") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "9")

This Simple IIS Security Check Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to perform basic security checks on an IIS server:
    • IIS version check
    • Web site enumeration
    • Default web page detection
    • Directory browsing check
    • HTTP response header analysis
    • SSL/TLS configuration check
  3. Option to set a target server (local or remote)
  4. HTML report generation for easy sharing and viewing of results

Key features:

  • Basic enumeration of IIS configuration
  • Detection of potentially risky settings like enabled directory browsing
  • Analysis of SSL/TLS protocols in use
  • Identification of default web pages that should be removed in production

Important notes:

  1. This tool is for educational purposes only and should not be used for actual penetration testing without proper authorization.
  2. It performs only basic checks and is not a comprehensive security assessment tool.
  3. Always ensure you have explicit permission before running any security checks on systems you don’t own.
  4. Some checks may require administrator privileges on the target server.
  5. Use this tool responsibly and ethically.

To use this script:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions on the target server
  3. Use caution when testing on production systems

Remember, this is a simple tool for educational purposes. Real penetration testing and security assessments should be performed by trained professionals using comprehensive, up-to-date tools and methodologies.

Microsoft 365 Security Check Tool

<#
.SYNOPSIS
Microsoft 365 Security Check Tool

.DESCRIPTION
This script analyzes and audits various security aspects of a Microsoft 365 environment,
providing insights into user accounts, licenses, Exchange Online, SharePoint Online,
Teams, and other security settings.

.NOTES
File Name      : M365SecurityCheckTool.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, Microsoft 365 PowerShell modules, and appropriate admin permissions
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\M365SecurityCheckTool.ps1
#>

# Check and install required modules
$requiredModules = @("MSOnline", "ExchangeOnlineManagement", "Microsoft.Online.SharePoint.PowerShell", "MicrosoftTeams", "AzureAD")
foreach ($module in $requiredModules) {
    if (!(Get-Module -ListAvailable -Name $module)) {
        Write-Host "Installing $module module..." -ForegroundColor Yellow
        Install-Module -Name $module -Force -AllowClobber
    }
}

# Import required modules
Import-Module MSOnline
Import-Module ExchangeOnlineManagement
Import-Module Microsoft.Online.SharePoint.PowerShell
Import-Module MicrosoftTeams
Import-Module AzureAD

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\M365_Security_Analysis_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Microsoft 365 Security Check Tool ===" -ForegroundColor Cyan
    Write-Host "1. Analyze User Accounts and MFA Status"
    Write-Host "2. Check License Assignments"
    Write-Host "3. Analyze Exchange Online Security Settings"
    Write-Host "4. Check SharePoint Online and OneDrive Security"
    Write-Host "5. Analyze Teams Security Settings"
    Write-Host "6. Check Azure AD Security Configuration"
    Write-Host "7. Analyze Conditional Access Policies"
    Write-Host "8. Check Data Loss Prevention Policies"
    Write-Host "9. Analyze Audit Log Settings"
    Write-Host "10. Generate Comprehensive HTML Report"
    Write-Host "11. Exit"
}

<#
.SYNOPSIS
Connects to Microsoft 365 services.
#>
function Connect-M365Services {
    Write-Host "Connecting to Microsoft 365 services..." -ForegroundColor Yellow
    Connect-MsolService
    Connect-ExchangeOnline
    $orgName = (Get-MsolCompanyInformation).DisplayName
    $adminSiteUrl = "https://$($orgName.Replace(' ', ''))-admin.sharepoint.com"
    Connect-SPOService -Url $adminSiteUrl
    Connect-MicrosoftTeams
    Connect-AzureAD
}

<#
.SYNOPSIS
Analyzes user accounts and MFA status.

.OUTPUTS
Array of PSObjects containing user account and MFA details.
#>
function Analyze-UserAccountsAndMFA {
    Write-Host "`nAnalyzing User Accounts and MFA Status..." -ForegroundColor Yellow
    $users = Get-MsolUser -All
    $results = @()
    foreach ($user in $users) {
        $mfaStatus = if ($user.StrongAuthenticationRequirements.State) { $user.StrongAuthenticationRequirements.State } else { "Disabled" }
        $results += [PSCustomObject]@{
            UserPrincipalName = $user.UserPrincipalName
            DisplayName = $user.DisplayName
            IsLicensed = $user.IsLicensed
            MFAStatus = $mfaStatus
            LastPasswordChangeTimestamp = $user.LastPasswordChangeTimestamp
            BlockCredential = $user.BlockCredential
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks license assignments.

.OUTPUTS
Array of PSObjects containing license assignment details.
#>
function Check-LicenseAssignments {
    Write-Host "`nChecking License Assignments..." -ForegroundColor Yellow
    $licenses = Get-MsolAccountSku
    $results = @()
    foreach ($license in $licenses) {
        $results += [PSCustomObject]@{
            AccountSkuId = $license.AccountSkuId
            ActiveUnits = $license.ActiveUnits
            ConsumedUnits = $license.ConsumedUnits
            AvailableUnits = ($license.ActiveUnits - $license.ConsumedUnits)
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Exchange Online security settings.

.OUTPUTS
PSObject containing Exchange Online security settings.
#>
function Analyze-ExchangeOnlineSecurity {
    Write-Host "`nAnalyzing Exchange Online Security Settings..." -ForegroundColor Yellow
    $transportRules = Get-TransportRule
    $malwareFilterPolicy = Get-MalwareFilterPolicy
    $result = [PSCustomObject]@{
        TransportRuleCount = $transportRules.Count
        MalwareFilterEnabled = $malwareFilterPolicy.Enabled
        AuditLogEnabled = (Get-AdminAuditLogConfig).UnifiedAuditLogIngestionEnabled
        DefaultAuthenticationPolicy = (Get-OrganizationConfig).DefaultAuthenticationPolicy
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Checks SharePoint Online and OneDrive security.

.OUTPUTS
PSObject containing SharePoint Online and OneDrive security settings.
#>
function Check-SharePointOneDriveSecurity {
    Write-Host "`nChecking SharePoint Online and OneDrive Security..." -ForegroundColor Yellow
    $sharingCapability = Get-SPOTenant | Select-Object SharingCapability
    $conditionalAccessPolicy = Get-SPOTenant | Select-Object ConditionalAccessPolicy
    $result = [PSCustomObject]@{
        SharingCapability = $sharingCapability.SharingCapability
        ConditionalAccessPolicy = $conditionalAccessPolicy.ConditionalAccessPolicy
        OneDriveForBusinessSharingCapability = (Get-SPOTenant).OneDriveForBusinessSharingCapability
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Analyzes Teams security settings.

.OUTPUTS
PSObject containing Teams security settings.
#>
function Analyze-TeamsSecuritySettings {
    Write-Host "`nAnalyzing Teams Security Settings..." -ForegroundColor Yellow
    $teamsSettings = Get-CsTeamsClientConfiguration
    $result = [PSCustomObject]@{
        AllowEmailIntoChannel = $teamsSettings.AllowEmailIntoChannel
        AllowDropBox = $teamsSettings.AllowDropBox
        AllowBox = $teamsSettings.AllowBox
        AllowGoogleDrive = $teamsSettings.AllowGoogleDrive
        AllowShareFile = $teamsSettings.AllowShareFile
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Checks Azure AD security configuration.

.OUTPUTS
PSObject containing Azure AD security configuration.
#>
function Check-AzureADSecurityConfig {
    Write-Host "`nChecking Azure AD Security Configuration..." -ForegroundColor Yellow
    $passwordPolicy = Get-MsolPasswordPolicy -TenantId (Get-MsolCompanyInformation).ObjectId
    $ssoState = (Get-MsolCompanyInformation).SelfServePasswordResetEnabled
    $result = [PSCustomObject]@{
        PasswordValidityPeriod = $passwordPolicy.ValidityPeriod
        MinimumPasswordLength = $passwordPolicy.MinimumPasswordLength
        PasswordComplexityEnabled = $passwordPolicy.StrongPasswordRequired
        SelfServicePasswordResetEnabled = $ssoState
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Analyzes Conditional Access Policies.

.OUTPUTS
Array of PSObjects containing Conditional Access Policy details.
#>
function Analyze-ConditionalAccessPolicies {
    Write-Host "`nAnalyzing Conditional Access Policies..." -ForegroundColor Yellow
    $policies = Get-AzureADMSConditionalAccessPolicy
    $results = @()
    foreach ($policy in $policies) {
        $results += [PSCustomObject]@{
            DisplayName = $policy.DisplayName
            State = $policy.State
            IncludeUsers = $policy.Conditions.Users.IncludeUsers -join ", "
            ExcludeUsers = $policy.Conditions.Users.ExcludeUsers -join ", "
            IncludeApplications = $policy.Conditions.Applications.IncludeApplications -join ", "
            GrantControls = $policy.GrantControls.BuiltInControls -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Data Loss Prevention Policies.

.OUTPUTS
Array of PSObjects containing DLP Policy details.
#>
function Check-DLPPolicies {
    Write-Host "`nChecking Data Loss Prevention Policies..." -ForegroundColor Yellow
    $policies = Get-DlpCompliancePolicy
    $results = @()
    foreach ($policy in $policies) {
        $results += [PSCustomObject]@{
            Name = $policy.Name
            Mode = $policy.Mode
            Enabled = $policy.Enabled
            ExchangeLocation = $policy.ExchangeLocation -join ", "
            SharePointLocation = $policy.SharePointLocation -join ", "
            OneDriveLocation = $policy.OneDriveLocation -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Audit Log Settings.

.OUTPUTS
PSObject containing Audit Log settings.
#>
function Analyze-AuditLogSettings {
    Write-Host "`nAnalyzing Audit Log Settings..." -ForegroundColor Yellow
    $auditConfig = Get-AdminAuditLogConfig
    $result = [PSCustomObject]@{
        UnifiedAuditLogIngestionEnabled = $auditConfig.UnifiedAuditLogIngestionEnabled
        OperationsToLog = $auditConfig.AdminAuditLogCmdlets -join ", "
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
function Generate-HTMLReport {
    param([hashtable]$AllResults)

    Write-Host "`nGenerating Comprehensive HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Microsoft 365 Security Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .warning { color: orange; }
        .critical { color: red; }
    </style>
</head>
<body>
    <h1>Microsoft 365 Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>User Accounts and MFA Status</h2>
    $($AllResults.UserAccountsAndMFA | ConvertTo-Html -Fragment)

    <h2>License Assignments</h2>
    $($AllResults.LicenseAssignments | ConvertTo-Html -Fragment)

    <h2>Exchange Online Security Settings</h2>
    $($AllResults.ExchangeOnlineSecurity | ConvertTo-Html -Fragment)

    <h2>SharePoint Online and OneDrive Security</h2>
    $($AllResults.SharePointOneDriveSecurity | ConvertTo-Html -Fragment)

    <h2>Teams Security Settings</h2>
    $($AllResults.TeamsSecuritySettings | ConvertTo-Html -Fragment)

    <h2>Azure AD Security Configuration</h2>
    $($AllResults.AzureADSecurityConfig | ConvertTo-Html -Fragment)

    <h2>Conditional Access Policies</h2>
    $($AllResults.ConditionalAccessPolicies | ConvertTo-Html -Fragment)

    <h2>Data Loss Prevention Policies</h2>
    $($AllResults.DLPPolicies | ConvertTo-Html -Fragment)

    <h2>Audit Log Settings</h2>
    $($AllResults.AuditLogSettings | ConvertTo-Html -Fragment)
</body>
</html>
"@

    $reportContent | Out-File -FilePath $global:reportPath
    Write-Host "Report generated and saved to: $global:reportPath" -ForegroundColor Green
}

# Main program loop
Connect-M365Services
$allResults = @{}

do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-11)"

    switch ($choice) {
        "1" { $allResults.UserAccountsAndMFA = Analyze-UserAccountsAndMFA }
        "2" { $allResults.LicenseAssignments = Check-LicenseAssignments }
        "3" { $allResults.ExchangeOnlineSecurity = Analyze-ExchangeOnlineSecurity }
        "4" { $allResults.SharePointOneDriveSecurity = Check-SharePointOneDriveSecurity }
        "5" { $allResults.TeamsSecuritySettings = Analyze-TeamsSecuritySettings }
        "6" { $allResults.AzureADSecurityConfig = Check-AzureADSecurityConfig }
        "7" { $allResults.ConditionalAccessPolicies = Analyze-ConditionalAccessPolicies }
        "8" { $allResults.DLPPolicies = Check-DLPPolicies }
        "9" { $allResults.AuditLogSettings = Analyze-AuditLogSettings }
        "10" { Generate-HTMLReport -AllResults $allResults }
        "11" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "11") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "11")

# Disconnect from services
Disconnect-ExchangeOnline -Confirm:$false
Disconnect-SPOService
Disconnect-MicrosoftTeams
Disconnect-AzureAD

This Microsoft 365 Security Check Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various security aspects of Microsoft 365:
    • User account analysis and MFA status
    • License assignment check
    • Exchange Online security settings analysis
    • SharePoint Online and OneDrive security check
    • Teams security settings analysis
    • Azure AD security configuration check
    • Conditional Access Policies analysis
    • Data Loss Prevention Policies check
    • Audit Log settings analysis
  3. Automatic installation of required PowerShell modules.
  4. Connection to necessary Microsoft 365 services.
  5. A function to generate an HTML report of all collected data.

Key features:

  • Comprehensive analysis of user accounts, including MFA status
  • Detailed insights into license assignments and usage
  • Review of Exchange Online, SharePoint Online, and OneDrive security settings
  • Analysis of Teams security configuration
  • Azure AD security settings check
  • Examination of Conditional Access and DLP policies
  • Audit log configuration review
  • HTML report generation for easy sharing and viewing of results

This tool is particularly useful for:

  • Microsoft 365 administrators
  • IT security professionals managing Microsoft 365 environments
  • Compliance officers ensuring adherence to security standards
  • Anyone needing to perform a security audit of their Microsoft 365 environment

To use this script effectively:

  1. Run PowerShell as an administrator
  2. Ensure you have the necessary permissions to access Microsoft 365 services (Global Administrator or appropriate admin roles)
  3. Have an active internet connection
  4. Review the generated HTML report for a comprehensive overview of your Microsoft 365 environment’s security status

This script provides a comprehensive overview of the security settings in a Microsoft 365 environment, making it easier to identify potential security issues, misconfigurations, or areas that need attention across various Microsoft 365 services.

Advanced Security Analyzer Tool for Windows Server

<#
.SYNOPSIS
Advanced Security Analyzer Tool for Windows Server

.DESCRIPTION
This script performs a comprehensive security analysis on a Windows Server,
providing detailed insights into various security aspects and potential vulnerabilities.

.NOTES
File Name      : AdvancedWindowsServerSecurityAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights on a Windows Server
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\AdvancedWindowsServerSecurityAnalyzer.ps1
#>

# Import required modules
Import-Module ActiveDirectory
Import-Module GroupPolicy

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\Advanced_WindowsServer_Security_Analysis_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Advanced Windows Server Security Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1.  Analyze Windows Updates and Patches"
    Write-Host "2.  Audit User Accounts and Permissions"
    Write-Host "3.  Check Firewall and Network Security"
    Write-Host "4.  Review File System and Share Permissions"
    Write-Host "5.  Analyze Services and Running Processes"
    Write-Host "6.  Check Group Policy Settings"
    Write-Host "7.  Audit Event Logs"
    Write-Host "8.  Analyze Installed Software"
    Write-Host "9.  Check for Common Vulnerabilities"
    Write-Host "10. Review Encryption and Certificate Settings"
    Write-Host "11. Generate Comprehensive HTML Report"
    Write-Host "12. Exit"
}

<#
.SYNOPSIS
Analyzes Windows Updates and Patches.

.OUTPUTS
PSObject containing Windows Updates and Patch status.
#>
function Analyze-WindowsUpdatesAndPatches {
    Write-Host "`nAnalyzing Windows Updates and Patches..." -ForegroundColor Yellow
    $updateSession = New-Object -ComObject Microsoft.Update.Session
    $updateSearcher = $updateSession.CreateUpdateSearcher()
    $pendingUpdates = $updateSearcher.Search("IsInstalled=0")
    $installedUpdates = Get-HotFix | Sort-Object -Property InstalledOn -Descending

    $result = [PSCustomObject]@{
        PendingUpdatesCount = $pendingUpdates.Updates.Count
        LastUpdateDate = $installedUpdates[0].InstalledOn
        CriticalUpdatesCount = ($pendingUpdates.Updates | Where-Object { $_.MsrcSeverity -eq "Critical" }).Count
        RecentlyInstalledUpdates = $installedUpdates | Select-Object -First 5 | ForEach-Object { "$($_.HotFixID) - $($_.InstalledOn)" }
    }

    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Audits User Accounts and Permissions.

.OUTPUTS
Array of PSObjects containing user account and permission details.
#>
function Audit-UserAccountsAndPermissions {
    Write-Host "`nAuditing User Accounts and Permissions..." -ForegroundColor Yellow
    $users = Get-ADUser -Filter * -Properties Enabled, PasswordLastSet, LastLogonDate, PasswordNeverExpires, MemberOf
    $results = @()
    foreach ($user in $users) {
        $adminGroups = $user.MemberOf | Where-Object { $_ -like "*admin*" }
        $results += [PSCustomObject]@{
            Username = $user.SamAccountName
            Enabled = $user.Enabled
            PasswordLastSet = $user.PasswordLastSet
            LastLogon = $user.LastLogonDate
            PasswordNeverExpires = $user.PasswordNeverExpires
            InAdminGroup = if ($adminGroups) { $true } else { $false }
            AdminGroups = $adminGroups -join ", "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Firewall and Network Security.

.OUTPUTS
PSObject containing firewall and network security details.
#>
function Check-FirewallAndNetworkSecurity {
    Write-Host "`nChecking Firewall and Network Security..." -ForegroundColor Yellow
    $firewallProfiles = Get-NetFirewallProfile
    $openPorts = Get-NetTCPConnection | Where-Object { $_.State -eq 'Listen' }
    
    $result = [PSCustomObject]@{
        DomainProfileEnabled = ($firewallProfiles | Where-Object { $_.Name -eq "Domain" }).Enabled
        PrivateProfileEnabled = ($firewallProfiles | Where-Object { $_.Name -eq "Private" }).Enabled
        PublicProfileEnabled = ($firewallProfiles | Where-Object { $_.Name -eq "Public" }).Enabled
        OpenPorts = $openPorts | Select-Object LocalPort, OwningProcess
        InboundRulesCount = (Get-NetFirewallRule -Direction Inbound).Count
        OutboundRulesCount = (Get-NetFirewallRule -Direction Outbound).Count
    }
    
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Reviews File System and Share Permissions.

.OUTPUTS
Array of PSObjects containing file system and share permission details.
#>
function Review-FileSystemAndSharePermissions {
    Write-Host "`nReviewing File System and Share Permissions..." -ForegroundColor Yellow
    $shares = Get-SmbShare | Where-Object { $_.Name -notlike "*$" }
    $results = @()
    foreach ($share in $shares) {
        $acl = Get-Acl $share.Path
        $permissions = $acl.Access | ForEach-Object {
            "$($_.IdentityReference) - $($_.FileSystemRights)"
        }
        $results += [PSCustomObject]@{
            ShareName = $share.Name
            Path = $share.Path
            Permissions = $permissions -join "; "
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Services and Running Processes.

.OUTPUTS
Array of PSObjects containing service and process details.
#>
function Analyze-ServicesAndProcesses {
    Write-Host "`nAnalyzing Services and Running Processes..." -ForegroundColor Yellow
    $services = Get-WmiObject Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Running' }
    $processes = Get-Process | Where-Object { $_.CPU -gt 10 -or $_.WorkingSet -gt 100MB }
    
    $results = @()
    foreach ($service in $services) {
        $results += [PSCustomObject]@{
            Type = "Service"
            Name = $service.Name
            DisplayName = $service.DisplayName
            StartName = $service.StartName
            State = $service.State
        }
    }
    foreach ($process in $processes) {
        $results += [PSCustomObject]@{
            Type = "Process"
            Name = $process.Name
            ID = $process.Id
            CPU = $process.CPU
            Memory = [math]::Round($process.WorkingSet / 1MB, 2)
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks Group Policy Settings.

.OUTPUTS
Array of PSObjects containing Group Policy setting details.
#>
function Check-GroupPolicySettings {
    Write-Host "`nChecking Group Policy Settings..." -ForegroundColor Yellow
    $gpos = Get-GPO -All
    $results = @()
    foreach ($gpo in $gpos) {
        $report = Get-GPOReport -Guid $gpo.Id -ReportType XML
        $settingsCount = ([xml]$report).GPO.Computer.ExtensionData.Extension.Policy.Count + 
                         ([xml]$report).GPO.User.ExtensionData.Extension.Policy.Count
        $results += [PSCustomObject]@{
            Name = $gpo.DisplayName
            CreationTime = $gpo.CreationTime
            ModificationTime = $gpo.ModificationTime
            SettingsCount = $settingsCount
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Audits Event Logs.

.OUTPUTS
Array of PSObjects containing event log details.
#>
function Audit-EventLogs {
    Write-Host "`nAuditing Event Logs..." -ForegroundColor Yellow
    $logs = @("System", "Security", "Application")
    $results = @()
    foreach ($log in $logs) {
        $events = Get-EventLog -LogName $log -Newest 100 | Group-Object -Property EntryType
        foreach ($eventType in $events) {
            $results += [PSCustomObject]@{
                LogName = $log
                EventType = $eventType.Name
                Count = $eventType.Count
            }
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes Installed Software.

.OUTPUTS
Array of PSObjects containing installed software details.
#>
function Analyze-InstalledSoftware {
    Write-Host "`nAnalyzing Installed Software..." -ForegroundColor Yellow
    $software = Get-WmiObject -Class Win32_Product | Select-Object Name, Vendor, Version, InstallDate
    $software | Format-Table -AutoSize
    return $software
}

<#
.SYNOPSIS
Checks for Common Vulnerabilities.

.OUTPUTS
Array of PSObjects containing vulnerability check results.
#>
function Check-CommonVulnerabilities {
    Write-Host "`nChecking for Common Vulnerabilities..." -ForegroundColor Yellow
    $results = @()

    # Check for SMBv1
    $smbv1 = Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol
    $results += [PSCustomObject]@{
        Check = "SMBv1 Enabled"
        Status = if ($smbv1.State -eq "Enabled") { "Vulnerable" } else { "Secure" }
    }

    # Check for PowerShell v2
    $psv2 = Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2
    $results += [PSCustomObject]@{
        Check = "PowerShell v2 Enabled"
        Status = if ($psv2.State -eq "Enabled") { "Vulnerable" } else { "Secure" }
    }

    # Check RDP settings
    $rdpEnabled = (Get-ItemProperty "HKLM:\System\CurrentControlSet\Control\Terminal Server").fDenyTSConnections -eq 0
    $nlaEnabled = (Get-ItemProperty "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp").UserAuthentication -eq 1
    $results += [PSCustomObject]@{
        Check = "RDP Enabled without NLA"
        Status = if ($rdpEnabled -and -not $nlaEnabled) { "Vulnerable" } else { "Secure" }
    }

    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Reviews Encryption and Certificate Settings.

.OUTPUTS
PSObject containing encryption and certificate details.
#>
function Review-EncryptionAndCertificates {
    Write-Host "`nReviewing Encryption and Certificate Settings..." -ForegroundColor Yellow
    $certs = Get-ChildItem -Path Cert:\LocalMachine\My
    $tlsSettings = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\*\*' | Where-Object { $_.Enabled -ne $null }

    $result = [PSCustomObject]@{
        CertificateCount = $certs.Count
        ExpiredCertificates = ($certs | Where-Object { $_.NotAfter -lt (Get-Date) }).Count
        TLS10Enabled = ($tlsSettings | Where-Object { $_.PSPath -like "*TLS 1.0*" -and $_.Enabled -eq 1 }) -ne $null
        TLS11Enabled = ($tlsSettings | Where-Object { $_.PSPath -like "*TLS 1.1*" -and $_.Enabled -eq 1 }) -ne $null
        TLS12Enabled = ($tlsSettings | Where-Object { $_.PSPath -like "*TLS 1.2*" -and $_.Enabled -eq 1 }) -ne $null
    }

    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
function Generate-HTMLReport {
    param([hashtable]$AllResults)

    Write-Host "`nGenerating Comprehensive HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Windows Server Security Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .vulnerable { color: red; font-weight: bold; }
        .secure { color: green; }
    </style>
</head>
<body>
    <h1>Advanced Windows Server Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>Windows Updates and Patches</h2>
    $($AllResults.UpdatesAndPatches | ConvertTo-Html -Fragment)

    <h2>User Accounts and Permissions</h2>
    $($AllResults.UserAccounts | ConvertTo-Html -Fragment)

    <h2>Firewall and Network Security</h2>
    $($AllResults.FirewallSecurity | ConvertTo-Html -Fragment)

    <h2>File System and Share Permissions</h2>
    $($AllResults.FileSystemPermissions | ConvertTo-Html -Fragment)

    <h2>Services and Running Processes</h2>
    $($AllResults.ServicesAndProcesses | ConvertTo-Html -Fragment)

    <h2>Group Policy Settings</h2>
    $($AllResults.GroupPolicySettings | ConvertTo-Html -Fragment)

    <h2>Event Logs Summary</h2>
    $($AllResults.EventLogs | ConvertTo-Html -Fragment)

    <h2>Installed Software</h2>
    $($AllResults.InstalledSoftware | ConvertTo-Html -Fragment)

    <h2>Common Vulnerabilities Check</h2>
    $($AllResults.Vulnerabilities | ForEach-Object {
        $_.Status = if ($_.Status -eq "Vulnerable") { '<span class="vulnerable">Vulnerable</span>' } else { '<span class="secure">Secure</span>' }
        $_
    } | ConvertTo-Html -Fragment)

    <h2>Encryption and Certificate Settings</h2>
    $($AllResults.EncryptionSettings | ConvertTo-Html -Fragment)
</body>
</html>
"@

    $reportContent | Out-File -FilePath $global:reportPath
    Write-Host "Report generated and saved to: $global:reportPath" -ForegroundColor Green
}

# Main program loop
$allResults = @{}

do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-12)"

    switch ($choice) {
        "1"  { $allResults.UpdatesAndPatches = Analyze-WindowsUpdatesAndPatches }
        "2"  { $allResults.UserAccounts = Audit-UserAccountsAndPermissions }
        "3"  { $allResults.FirewallSecurity = Check-FirewallAndNetworkSecurity }
        "4"  { $allResults.FileSystemPermissions = Review-FileSystemAndSharePermissions }
        "5"  { $allResults.ServicesAndProcesses = Analyze-ServicesAndProcesses }
        "6"  { $allResults.GroupPolicySettings = Check-GroupPolicySettings }
        "7"  { $allResults.EventLogs = Audit-EventLogs }
        "8"  { $allResults.InstalledSoftware = Analyze-InstalledSoftware }
        "9"  { $allResults.Vulnerabilities = Check-CommonVulnerabilities }
        "10" { $allResults.EncryptionSettings = Review-EncryptionAndCertificates }
        "11" { Generate-HTMLReport -AllResults $allResults }
        "12" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "12") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "12")

This Advanced Security Analyzer Tool for Windows Server includes:

  1. A comprehensive menu-driven interface.
  2. Advanced functions to analyze various security aspects:
    • Detailed Windows Updates and Patch analysis
    • In-depth user account and permission auditing
    • Comprehensive firewall and network security check
    • Detailed file system and share permissions review
    • Analysis of services and running processes
    • Group Policy settings check
    • Event log auditing
    • Installed software analysis
    • Common vulnerabilities check
    • Encryption and certificate settings review
  3. Detailed HTML report generation with color-coded vulnerability indicators.

Key features:

  • Comprehensive analysis of Windows Updates, including pending and critical updates
  • Detailed user account analysis, including admin group memberships
  • In-depth firewall analysis, including open ports and rule counts
  • File system and share permission auditing
  • Service and process analysis with focus on auto-start services and resource-intensive processes
  • Group Policy analysis
  • Event log summary for system, security, and application logs
  • Installed software inventory
  • Checks for common vulnerabilities like SMBv1, PowerShell v2, and insecure RDP settings
  • Review of encryption settings and certificate status

This tool is particularly useful for:

  • System administrators performing thorough security audits
  • IT security professionals conducting in-depth security assessments
  • Compliance officers ensuring adherence to security standards
  • Anyone needing a comprehensive overview of a Windows Server’s security posture

To use this script effectively:

  1. Run PowerShell as an administrator on the Windows Server you want to analyze
  2. Ensure you have the necessary permissions to query system information and Active Directory (if applicable)
  3. Review the generated HTML report for a detailed overview of the server’s security status

This script provides a comprehensive and advanced way to analyze the security of a Windows Server, helping to identify potential security issues, misconfigurations, and vulnerabilities across various aspects of the system.

Simple Security Analyzer Tool for Windows Server

<#
.SYNOPSIS
Simple Security Analyzer Tool for Windows Server

.DESCRIPTION
This script analyzes basic security settings and configurations on a Windows Server,
providing insights into potential security issues and misconfigurations.

.NOTES
File Name      : WindowsServerSecurityAnalyzer.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later, administrator rights on a Windows Server
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\WindowsServerSecurityAnalyzer.ps1
#>

# Global variables
$global:reportPath = "$env:USERPROFILE\Desktop\WindowsServer_Security_Analysis_Report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

<#
.SYNOPSIS
Displays the main menu of the tool.
#>
function Show-Menu {
    Clear-Host
    Write-Host "=== Windows Server Security Analyzer Tool ===" -ForegroundColor Cyan
    Write-Host "1. Check Windows Updates Status"
    Write-Host "2. Analyze User Accounts"
    Write-Host "3. Check Firewall Status"
    Write-Host "4. Review Shared Folders"
    Write-Host "5. Check Services Running as SYSTEM"
    Write-Host "6. Analyze Password Policy"
    Write-Host "7. Check for Unquoted Service Paths"
    Write-Host "8. Generate Comprehensive HTML Report"
    Write-Host "9. Exit"
}

<#
.SYNOPSIS
Checks Windows Updates status.

.OUTPUTS
PSObject containing Windows Updates status.
#>
function Check-WindowsUpdates {
    Write-Host "`nChecking Windows Updates Status..." -ForegroundColor Yellow
    $updateSession = New-Object -ComObject Microsoft.Update.Session
    $updateSearcher = $updateSession.CreateUpdateSearcher()
    $pendingUpdates = $updateSearcher.Search("IsInstalled=0")

    $result = [PSCustomObject]@{
        PendingUpdatesCount = $pendingUpdates.Updates.Count
        LastUpdateDate = (Get-HotFix | Sort-Object -Property InstalledOn -Descending | Select-Object -First 1).InstalledOn
    }

    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Analyzes user accounts.

.OUTPUTS
Array of PSObjects containing user account details.
#>
function Analyze-UserAccounts {
    Write-Host "`nAnalyzing User Accounts..." -ForegroundColor Yellow
    $users = Get-LocalUser
    $results = @()
    foreach ($user in $users) {
        $results += [PSCustomObject]@{
            Username = $user.Name
            Enabled = $user.Enabled
            PasswordExpires = $user.PasswordExpires
            LastLogon = $user.LastLogon
            PasswordRequired = $user.PasswordRequired
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks firewall status.

.OUTPUTS
PSObject containing firewall status.
#>
function Check-FirewallStatus {
    Write-Host "`nChecking Firewall Status..." -ForegroundColor Yellow
    $firewallProfiles = Get-NetFirewallProfile
    $result = [PSCustomObject]@{
        DomainProfile = ($firewallProfiles | Where-Object { $_.Name -eq "Domain" }).Enabled
        PrivateProfile = ($firewallProfiles | Where-Object { $_.Name -eq "Private" }).Enabled
        PublicProfile = ($firewallProfiles | Where-Object { $_.Name -eq "Public" }).Enabled
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Reviews shared folders.

.OUTPUTS
Array of PSObjects containing shared folder details.
#>
function Review-SharedFolders {
    Write-Host "`nReviewing Shared Folders..." -ForegroundColor Yellow
    $shares = Get-SmbShare | Where-Object { $_.Name -notlike "*$" }
    $results = @()
    foreach ($share in $shares) {
        $results += [PSCustomObject]@{
            Name = $share.Name
            Path = $share.Path
            Description = $share.Description
            AccessBasedEnumerationEnabled = $share.FolderEnumerationMode
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Checks services running as SYSTEM.

.OUTPUTS
Array of PSObjects containing service details.
#>
function Check-SystemServices {
    Write-Host "`nChecking Services Running as SYSTEM..." -ForegroundColor Yellow
    $services = Get-WmiObject Win32_Service | Where-Object { $_.StartName -eq "LocalSystem" }
    $results = @()
    foreach ($service in $services) {
        $results += [PSCustomObject]@{
            Name = $service.Name
            DisplayName = $service.DisplayName
            StartMode = $service.StartMode
            State = $service.State
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Analyzes password policy.

.OUTPUTS
PSObject containing password policy details.
#>
function Analyze-PasswordPolicy {
    Write-Host "`nAnalyzing Password Policy..." -ForegroundColor Yellow
    $policy = Get-LocalSecurityPolicy
    $result = [PSCustomObject]@{
        PasswordHistorySize = $policy.'PasswordHistorySize'
        MaximumPasswordAge = $policy.'MaximumPasswordAge'
        MinimumPasswordAge = $policy.'MinimumPasswordAge'
        MinimumPasswordLength = $policy.'MinimumPasswordLength'
        PasswordComplexity = $policy.'PasswordComplexity'
    }
    $result | Format-List
    return $result
}

<#
.SYNOPSIS
Checks for unquoted service paths.

.OUTPUTS
Array of PSObjects containing services with unquoted paths.
#>
function Check-UnquotedServicePaths {
    Write-Host "`nChecking for Unquoted Service Paths..." -ForegroundColor Yellow
    $services = Get-WmiObject Win32_Service | Where-Object { $_.PathName -notlike '"*"' -and $_.PathName -like '* *' }
    $results = @()
    foreach ($service in $services) {
        $results += [PSCustomObject]@{
            Name = $service.Name
            DisplayName = $service.DisplayName
            PathName = $service.PathName
        }
    }
    $results | Format-Table -AutoSize
    return $results
}

<#
.SYNOPSIS
Generates a comprehensive HTML report of all analyses.

.PARAMETER AllResults
Hashtable containing all analysis results.

.OUTPUTS
Saves an HTML report to the desktop.
#>
function Generate-HTMLReport {
    param([hashtable]$AllResults)

    Write-Host "`nGenerating Comprehensive HTML Report..." -ForegroundColor Yellow
    $reportContent = @"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Windows Server Security Analysis Report</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1, h2, h3 { color: #0078D4; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>Windows Server Security Analysis Report</h1>
    <p>Generated on: $(Get-Date)</p>

    <h2>Windows Updates Status</h2>
    $($AllResults.WindowsUpdates | ConvertTo-Html -Fragment)

    <h2>User Accounts</h2>
    $($AllResults.UserAccounts | ConvertTo-Html -Fragment)

    <h2>Firewall Status</h2>
    $($AllResults.FirewallStatus | ConvertTo-Html -Fragment)

    <h2>Shared Folders</h2>
    $($AllResults.SharedFolders | ConvertTo-Html -Fragment)

    <h2>Services Running as SYSTEM</h2>
    $($AllResults.SystemServices | ConvertTo-Html -Fragment)

    <h2>Password Policy</h2>
    $($AllResults.PasswordPolicy | ConvertTo-Html -Fragment)

    <h2>Unquoted Service Paths</h2>
    $($AllResults.UnquotedServicePaths | ConvertTo-Html -Fragment)
</body>
</html>
"@

    $reportContent | Out-File -FilePath $global:reportPath
    Write-Host "Report generated and saved to: $global:reportPath" -ForegroundColor Green
}

# Main program loop
$allResults = @{}

do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-9)"

    switch ($choice) {
        "1" { $allResults.WindowsUpdates = Check-WindowsUpdates }
        "2" { $allResults.UserAccounts = Analyze-UserAccounts }
        "3" { $allResults.FirewallStatus = Check-FirewallStatus }
        "4" { $allResults.SharedFolders = Review-SharedFolders }
        "5" { $allResults.SystemServices = Check-SystemServices }
        "6" { $allResults.PasswordPolicy = Analyze-PasswordPolicy }
        "7" { $allResults.UnquotedServicePaths = Check-UnquotedServicePaths }
        "8" { Generate-HTMLReport -AllResults $allResults }
        "9" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "9") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "9")

This Simple Security Analyzer Tool for Windows Server includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to analyze various security aspects:
    • Windows Updates status
    • User account analysis
    • Firewall status check
    • Shared folder review
    • Services running as SYSTEM
    • Password policy analysis
    • Check for unquoted service paths
  3. HTML report generation for all collected data.

Key features:

  • Quick overview of pending Windows Updates
  • Analysis of local user accounts and their settings
  • Firewall status check for all profiles
  • Review of non-default shared folders
  • Identification of services running with high privileges (SYSTEM)
  • Password policy review
  • Detection of potential vulnerabilities like unquoted service paths
  • Comprehensive HTML report generation

This tool is particularly useful for:

  • System administrators performing quick security checks
  • IT professionals conducting basic security audits
  • Anyone needing to get a quick overview of a Windows Server’s security posture

To use this script effectively:

  1. Run PowerShell as an administrator on the Windows Server you want to analyze
  2. Ensure you have the necessary permissions to query system information
  3. Review the generated HTML report for a comprehensive overview of the server’s security status

This script provides a simple yet effective way to perform basic security checks on a Windows Server, helping to identify potential security issues and misconfigurations quickly.