M365FoundationsCISReport.psm1
#Region '.\Classes\CISAuditResult.ps1' -1 class CISAuditResult { [string]$Status [string]$ELevel [string]$ProfileLevel [bool]$Automated [string]$Connection [string]$Rec [string]$RecDescription [string]$CISControlVer = 'v8' [string]$CISControl [string]$CISDescription [bool]$IG1 [bool]$IG2 [bool]$IG3 [bool]$Result [string]$Details [string]$FailureReason } #EndRegion '.\Classes\CISAuditResult.ps1' 19 #Region '.\Private\Assert-ModuleAvailability.ps1' -1 function Assert-ModuleAvailability { [OutputType([void]) ] param( [string]$ModuleName, [string]$RequiredVersion, [string[]]$SubModules = @() ) try { $module = Get-Module -ListAvailable -Name $ModuleName | Where-Object { $_.Version -ge [version]$RequiredVersion } if ($null -eq $module) { Write-Host "Installing $ModuleName module..." -ForegroundColor Yellow Install-Module -Name $ModuleName -RequiredVersion $RequiredVersion -Force -AllowClobber -Scope CurrentUser | Out-Null } elseif ($module.Version -lt [version]$RequiredVersion) { Write-Host "Updating $ModuleName module to required version..." -ForegroundColor Yellow Update-Module -Name $ModuleName -RequiredVersion $RequiredVersion -Force | Out-Null } else { Write-Host "$ModuleName module is already at required version or newer." -ForegroundColor Gray } if ($SubModules.Count -gt 0) { foreach ($subModule in $SubModules) { Write-Host "Importing submodule $ModuleName.$subModule..." -ForegroundColor DarkGray Import-Module -Name "$ModuleName.$subModule" -RequiredVersion $RequiredVersion -ErrorAction Stop | Out-Null } } else { Write-Host "Importing module $ModuleName..." -ForegroundColor DarkGray Import-Module -Name $ModuleName -RequiredVersion $RequiredVersion -ErrorAction Stop -WarningAction SilentlyContinue | Out-Null } } catch { Write-Warning "An error occurred with module $ModuleName`: $_" } } #EndRegion '.\Private\Assert-ModuleAvailability.ps1' 38 #Region '.\Private\Connect-M365Suite.ps1' -1 function Connect-M365Suite { [OutputType([void])] [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [string]$TenantAdminUrl, [Parameter(Mandatory)] [string[]]$RequiredConnections, [Parameter(Mandatory = $false)] [switch]$SkipConfirmation ) $VerbosePreference = "SilentlyContinue" $tenantInfo = @() $connectedServices = @() try { if ($RequiredConnections -contains "AzureAD" -or $RequiredConnections -contains "AzureAD | EXO" -or $RequiredConnections -contains "AzureAD | EXO | Microsoft Graph") { Write-Host "Connecting to Azure Active Directory..." -ForegroundColor Yellow Connect-AzureAD -WarningAction SilentlyContinue | Out-Null $tenantDetails = Get-AzureADTenantDetail -WarningAction SilentlyContinue $tenantInfo += [PSCustomObject]@{ Service = "Azure Active Directory" TenantName = $tenantDetails.DisplayName TenantID = $tenantDetails.ObjectId } $connectedServices += "AzureAD" Write-Host "Successfully connected to Azure Active Directory." -ForegroundColor Green } if ($RequiredConnections -contains "Microsoft Graph" -or $RequiredConnections -contains "EXO | Microsoft Graph") { Write-Host "Connecting to Microsoft Graph with scopes: Directory.Read.All, Domain.Read.All, Policy.Read.All, Organization.Read.All" -ForegroundColor Yellow try { Connect-MgGraph -Scopes "Directory.Read.All", "Domain.Read.All", "Policy.Read.All", "Organization.Read.All" -NoWelcome | Out-Null $graphOrgDetails = Get-MgOrganization $tenantInfo += [PSCustomObject]@{ Service = "Microsoft Graph" TenantName = $graphOrgDetails.DisplayName TenantID = $graphOrgDetails.Id } $connectedServices += "Microsoft Graph" Write-Host "Successfully connected to Microsoft Graph with specified scopes." -ForegroundColor Green } catch { Write-Host "Failed to connect to MgGraph, attempting device auth." -ForegroundColor Yellow Connect-MgGraph -Scopes "Directory.Read.All", "Domain.Read.All", "Policy.Read.All", "Organization.Read.All" -UseDeviceCode -NoWelcome | Out-Null $graphOrgDetails = Get-MgOrganization $tenantInfo += [PSCustomObject]@{ Service = "Microsoft Graph" TenantName = $graphOrgDetails.DisplayName TenantID = $graphOrgDetails.Id } $connectedServices += "Microsoft Graph" Write-Host "Successfully connected to Microsoft Graph with specified scopes." -ForegroundColor Green } } if ($RequiredConnections -contains "EXO" -or $RequiredConnections -contains "AzureAD | EXO" -or $RequiredConnections -contains "Microsoft Teams | EXO" -or $RequiredConnections -contains "EXO | Microsoft Graph") { Write-Host "Connecting to Exchange Online..." -ForegroundColor Yellow Connect-ExchangeOnline -ShowBanner:$false | Out-Null $exoTenant = (Get-OrganizationConfig).Identity $tenantInfo += [PSCustomObject]@{ Service = "Exchange Online" TenantName = $exoTenant TenantID = "N/A" } $connectedServices += "EXO" Write-Host "Successfully connected to Exchange Online." -ForegroundColor Green } if ($RequiredConnections -contains "SPO") { Write-Host "Connecting to SharePoint Online..." -ForegroundColor Yellow Connect-SPOService -Url $TenantAdminUrl | Out-Null $spoContext = Get-SPOCrossTenantHostUrl $tenantName = Get-UrlLine -Output $spoContext $tenantInfo += [PSCustomObject]@{ Service = "SharePoint Online" TenantName = $tenantName } $connectedServices += "SPO" Write-Host "Successfully connected to SharePoint Online." -ForegroundColor Green } if ($RequiredConnections -contains "Microsoft Teams" -or $RequiredConnections -contains "Microsoft Teams | EXO") { Write-Host "Connecting to Microsoft Teams..." -ForegroundColor Yellow Connect-MicrosoftTeams | Out-Null $teamsTenantDetails = Get-CsTenant $tenantInfo += [PSCustomObject]@{ Service = "Microsoft Teams" TenantName = $teamsTenantDetails.DisplayName TenantID = $teamsTenantDetails.TenantId } $connectedServices += "Microsoft Teams" Write-Host "Successfully connected to Microsoft Teams." -ForegroundColor Green } # Display tenant information and confirm with the user if (-not $SkipConfirmation) { Write-Host "Connected to the following tenants:" -ForegroundColor Yellow foreach ($tenant in $tenantInfo) { Write-Host "Service: $($tenant.Service)" -ForegroundColor Cyan Write-Host "Tenant Context: $($tenant.TenantName)`n" -ForegroundColor Green #Write-Host "Tenant ID: $($tenant.TenantID)" } $confirmation = Read-Host "Do you want to proceed with these connections? (Y/N)" if ($confirmation -notlike 'Y') { Write-Host "Connection setup aborted by user." -ForegroundColor Red Disconnect-M365Suite -RequiredConnections $connectedServices throw "User aborted connection setup." } } } catch { $VerbosePreference = "Continue" Write-Host "There was an error establishing one or more connections: $_" -ForegroundColor Red throw $_ } $VerbosePreference = "Continue" } #EndRegion '.\Private\Connect-M365Suite.ps1' 123 #Region '.\Private\Disconnect-M365Suite.ps1' -1 function Disconnect-M365Suite { [OutputType([void])] param ( [Parameter(Mandatory)] [string[]]$RequiredConnections ) # Clean up sessions try { if ($RequiredConnections -contains "EXO" -or $RequiredConnections -contains "AzureAD | EXO" -or $RequiredConnections -contains "Microsoft Teams | EXO") { Write-Host "Disconnecting from Exchange Online..." -ForegroundColor Green Disconnect-ExchangeOnline -Confirm:$false | Out-Null } } catch { Write-Warning "Failed to disconnect from Exchange Online: $_" } try { if ($RequiredConnections -contains "AzureAD" -or $RequiredConnections -contains "AzureAD | EXO") { Write-Host "Disconnecting from Azure AD..." -ForegroundColor Green Disconnect-AzureAD | Out-Null } } catch { Write-Warning "Failed to disconnect from Azure AD: $_" } try { if ($RequiredConnections -contains "Microsoft Graph") { Write-Host "Disconnecting from Microsoft Graph..." -ForegroundColor Green Disconnect-MgGraph | Out-Null } } catch { Write-Warning "Failed to disconnect from Microsoft Graph: $_" } try { if ($RequiredConnections -contains "SPO") { Write-Host "Disconnecting from SharePoint Online..." -ForegroundColor Green Disconnect-SPOService | Out-Null } } catch { Write-Warning "Failed to disconnect from SharePoint Online: $_" } try { if ($RequiredConnections -contains "Microsoft Teams" -or $RequiredConnections -contains "Microsoft Teams | EXO") { Write-Host "Disconnecting from Microsoft Teams..." -ForegroundColor Green Disconnect-MicrosoftTeams | Out-Null } } catch { Write-Warning "Failed to disconnect from Microsoft Teams: $_" } Write-Host "All necessary sessions have been disconnected." -ForegroundColor Green } #EndRegion '.\Private\Disconnect-M365Suite.ps1' 61 #Region '.\Private\Format-RequiredModuleList.ps1' -1 function Format-RequiredModuleList { [CmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory = $true)] [System.Object[]]$RequiredModules ) $requiredModulesFormatted = "" foreach ($module in $RequiredModules) { if ($module.SubModules -and $module.SubModules.Count -gt 0) { $subModulesFormatted = $module.SubModules -join ', ' $requiredModulesFormatted += "$($module.ModuleName) (SubModules: $subModulesFormatted), " } else { $requiredModulesFormatted += "$($module.ModuleName), " } } return $requiredModulesFormatted.TrimEnd(", ") } #EndRegion '.\Private\Format-RequiredModuleList.ps1' 20 #Region '.\Private\Get-Action.ps1' -1 function Get-Action { [CmdletBinding(DefaultParameterSetName = "GetDictionaries")] param ( [Parameter(Position = 0, ParameterSetName = "GetDictionaries")] [switch]$Dictionaries, [Parameter(Position = 0, ParameterSetName = "ConvertActions")] [string[]]$Actions, [Parameter(Position = 1, Mandatory = $true, ParameterSetName = "ConvertActions")] [ValidateSet("Admin", "Delegate", "Owner")] [string]$ActionType, [Parameter(Position = 0, ParameterSetName = "ReverseActions")] [string[]]$AbbreviatedActions, [Parameter(Position = 1, Mandatory = $true, ParameterSetName = "ReverseActions")] [ValidateSet("Admin", "Delegate", "Owner")] [string]$ReverseActionType ) $Dictionary = @{ AdminActions = @{ ApplyRecord = 'AR' Copy = 'CP' Create = 'CR' FolderBind = 'FB' HardDelete = 'HD' MailItemsAccessed = 'MIA' Move = 'MV' MoveToDeletedItems = 'MTDI' SendAs = 'SA' SendOnBehalf = 'SOB' Send = 'SD' SoftDelete = 'SD' Update = 'UP' UpdateCalendarDelegation = 'UCD' UpdateFolderPermissions = 'UFP' UpdateInboxRules = 'UIR' } DelegateActions = @{ ApplyRecord = 'AR' Create = 'CR' FolderBind = 'FB' HardDelete = 'HD' MailItemsAccessed = 'MIA' Move = 'MV' MoveToDeletedItems = 'MTDI' SendAs = 'SA' SendOnBehalf = 'SOB' SoftDelete = 'SD' Update = 'UP' UpdateFolderPermissions = 'UFP' UpdateInboxRules = 'UIR' } OwnerActions = @{ ApplyRecord = 'AR' Create = 'CR' HardDelete = 'HD' MailboxLogin = 'ML' MailItemsAccessed = 'MIA' Move = 'MV' MoveToDeletedItems = 'MTDI' Send = 'SD' SoftDelete = 'SD' Update = 'UP' UpdateCalendarDelegation = 'UCD' UpdateFolderPermissions = 'UFP' UpdateInboxRules = 'UIR' } } switch ($PSCmdlet.ParameterSetName) { "GetDictionaries" { return $Dictionary } "ConvertActions" { $actionDictionary = switch ($ActionType) { "Admin" { $Dictionary.AdminActions } "Delegate" { $Dictionary.DelegateActions } "Owner" { $Dictionary.OwnerActions } } $abbreviatedActions = @() foreach ($action in $Actions) { if ($actionDictionary.ContainsKey($action)) { $abbreviatedActions += $actionDictionary[$action] } } return $abbreviatedActions } "ReverseActions" { $reverseDictionary = @{} $originalDictionary = switch ($ReverseActionType) { "Admin" { $Dictionary.AdminActions } "Delegate" { $Dictionary.DelegateActions } "Owner" { $Dictionary.OwnerActions } } foreach ($key in $originalDictionary.Keys) { $reverseDictionary[$originalDictionary[$key]] = $key } $fullNames = @() foreach ($abbrAction in $AbbreviatedActions) { if ($reverseDictionary.ContainsKey($abbrAction)) { $fullNames += $reverseDictionary[$abbrAction] } } return $fullNames } } } #EndRegion '.\Private\Get-Action.ps1' 114 #Region '.\Private\Get-AdminRoleUserAndAssignment.ps1' -1 function Get-AdminRoleUserAndAssignment { [CmdletBinding()] param () $result = @{} # Get the DisplayNames of all admin roles $adminRoleNames = (Get-MgDirectoryRole | Where-Object { $null -ne $_.RoleTemplateId }).DisplayName # Get Admin Roles $adminRoles = Get-MgRoleManagementDirectoryRoleDefinition | Where-Object { ($adminRoleNames -contains $_.DisplayName) -and ($_.DisplayName -ne "Directory Synchronization Accounts") } foreach ($role in $adminRoles) { Write-Verbose "Processing role: $($role.DisplayName)" $roleAssignments = Get-MgRoleManagementDirectoryRoleAssignment -Filter "roleDefinitionId eq '$($role.Id)'" foreach ($assignment in $roleAssignments) { Write-Verbose "Processing role assignment for principal ID: $($assignment.PrincipalId)" $userDetails = Get-MgUser -UserId $assignment.PrincipalId -Property "DisplayName, UserPrincipalName, Id, OnPremisesSyncEnabled" -ErrorAction SilentlyContinue if ($userDetails) { Write-Verbose "Retrieved user details for: $($userDetails.UserPrincipalName)" $licenses = Get-MgUserLicenseDetail -UserId $assignment.PrincipalId -ErrorAction SilentlyContinue if (-not $result[$role.DisplayName]) { $result[$role.DisplayName] = @() } $result[$role.DisplayName] += [PSCustomObject]@{ AssignmentId = $assignment.Id UserDetails = $userDetails Licenses = $licenses } } } } return $result } #EndRegion '.\Private\Get-AdminRoleUserAndAssignment.ps1' 39 #Region '.\Private\Get-CISAadOutput.ps1' -1 <# .SYNOPSIS This is a sample Private function only visible within the module. .DESCRIPTION This sample function is not exported to the module and only return the data passed as parameter. .EXAMPLE $null = Get-Get-CISAadOutput -PrivateData 'NOTHING TO SEE HERE' .PARAMETER PrivateData The PrivateData parameter is what will be returned without transformation. #> function Get-CISAadOutput { [cmdletBinding()] param( [Parameter(Mandatory = $true)] [String]$Rec ) begin { # Begin Block # <# # Tests 1.2.2 # Test number $testNumbers ="1.2.2" #> } process { switch ($Rec) { '1.2.2' { # Test-BlockSharedMailboxSignIn.ps1 $users = Get-AzureADUser } default { throw "No match found for test: $Rec" } } } end { Write-Verbose "Get-CISAadOutput: Retuning data for Rec: $Rec" return $users } } # end function Get-CISAadOutput #EndRegion '.\Private\Get-CISAadOutput.ps1' 40 #Region '.\Private\Get-CISExoOutput.ps1' -1 <# .SYNOPSIS This is a sample Private function only visible within the module. .DESCRIPTION This sample function is not exported to the module and only return the data passed as parameter. .EXAMPLE $null = Get-CISExoOutput -PrivateData 'NOTHING TO SEE HERE' .PARAMETER PrivateData The PrivateData parameter is what will be returned without transformation. #> function Get-CISExoOutput { [cmdletBinding()] param( [Parameter(Mandatory = $true)] [String]$Rec ) begin { # Begin Block # <# # Tests 1.2.2 1.3.3 1.3.6 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 2.1.7 2.1.9 3.1.1 6.1.1 6.1.2 6.1.3 6.2.1 6.2.2 6.2.3 6.3.1 6.5.1 6.5.2 6.5.3 8.6.1 # Test number array $testNumbers = @('1.2.2', '1.3.3', '1.3.6', '2.1.1', '2.1.2', '2.1.3', '2.1.4', '2.1.5', '2.1.6', '2.1.7', '2.1.9', '3.1.1', '6.1.1', '6.1.2', '6.1.3', '6.2.1', '6.2.2', '6.2.3', '6.3.1', '6.5.1', '6.5.2', '6.5.3', '8.6.1') #> } process { Write-Verbose "Get-CISExoOutput: Retuning data for Rec: $Rec" switch ($Rec) { '1.2.2' { # Test-BlockSharedMailboxSignIn.ps1 $MBX = Get-EXOMailbox -RecipientTypeDetails SharedMailbox # [object[]] return $MBX } '1.3.3' { # Test-ExternalSharingCalendars.ps1 # Step: Retrieve sharing policies related to calendar sharing $sharingPolicies = Get-SharingPolicy | Where-Object { $_.Domains -like '*CalendarSharing*' } # [psobject[]] return $sharingPolicies } '1.3.6' { # Test-CustomerLockbox.ps1 # Step: Retrieve the organization configuration (Condition C: Pass/Fail) $orgConfig = Get-OrganizationConfig | Select-Object CustomerLockBoxEnabled $customerLockboxEnabled = $orgConfig.CustomerLockBoxEnabled # [bool] return $customerLockboxEnabled } '2.1.1' { # Test-SafeLinksOfficeApps.ps1 if (Get-Command Get-SafeLinksPolicy -ErrorAction SilentlyContinue) { # 2.1.1 (L2) Ensure Safe Links for Office Applications is Enabled # Retrieve all Safe Links policies $policies = Get-SafeLinksPolicy # Initialize the details collection $misconfiguredDetails = @() foreach ($policy in $policies) { # Get the detailed configuration of each policy $policyDetails = Get-SafeLinksPolicy -Identity $policy.Name # Check each required property and record failures # Condition A: Checking policy settings $failures = @() if ($policyDetails.EnableSafeLinksForEmail -ne $true) { $failures += "EnableSafeLinksForEmail: False" } # Email: On if ($policyDetails.EnableSafeLinksForTeams -ne $true) { $failures += "EnableSafeLinksForTeams: False" } # Teams: On if ($policyDetails.EnableSafeLinksForOffice -ne $true) { $failures += "EnableSafeLinksForOffice: False" } # Office 365 Apps: On if ($policyDetails.TrackClicks -ne $true) { $failures += "TrackClicks: False" } # Click protection settings: On if ($policyDetails.AllowClickThrough -ne $false) { $failures += "AllowClickThrough: True" } # Do not track when users click safe links: Off # Only add details for policies that have misconfigurations if ($failures.Count -gt 0) { $misconfiguredDetails += "Policy: $($policy.Name); Failures: $($failures -join ', ')" } } # [object[]] return $misconfiguredDetails } else { return 1 } } '2.1.2' { # Test-CommonAttachmentFilter.ps1 # 2.1.2 (L1) Ensure the Common Attachment Types Filter is enabled # Condition A: The Common Attachment Types Filter is enabled in the Microsoft 365 Security & Compliance Center. # Condition B: Using Exchange Online PowerShell, verify that the `EnableFileFilter` property of the default malware filter policy is set to `True`. # Retrieve the attachment filter policy $attachmentFilter = Get-MalwareFilterPolicy -Identity Default | Select-Object EnableFileFilter $result = $attachmentFilter.EnableFileFilter # [bool] return $result } '2.1.3' { # Test-NotifyMalwareInternal.ps1 # 2.1.3 Ensure notifications for internal users sending malware is Enabled # Retrieve all 'Custom' malware filter policies and check notification settings $malwareNotifications = Get-MalwareFilterPolicy | Where-Object { $_.RecommendedPolicyType -eq 'Custom' } # [object[]] return $malwareNotifications } '2.1.4' { # Test-SafeAttachmentsPolicy.ps1 if (Get-Command Get-SafeAttachmentPolicy -ErrorAction SilentlyContinue) { # Retrieve all Safe Attachment policies where Enable is set to True # Check if ErrorAction needed below $safeAttachmentPolicies = Get-SafeAttachmentPolicy -ErrorAction SilentlyContinue | Where-Object { $_.Enable -eq $true } # [object[]] return $safeAttachmentPolicies else { return 1 } } } '2.1.5' { # Test-SafeAttachmentsTeams.ps1 if (Get-Command Get-AtpPolicyForO365 -ErrorAction SilentlyContinue) { # 2.1.5 (L2) Ensure Safe Attachments for SharePoint, OneDrive, and Microsoft Teams is Enabled # Retrieve the ATP policies for Office 365 and check Safe Attachments settings $atpPolicies = Get-AtpPolicyForO365 # Check if the required ATP policies are enabled $atpPolicyResult = $atpPolicies | Where-Object { $_.EnableATPForSPOTeamsODB -eq $true -and $_.EnableSafeDocs -eq $true -and $_.AllowSafeDocsOpen -eq $false } # [psobject[]] return $atpPolicyResult } else { return 1 } } '2.1.6' { # Test-SpamPolicyAdminNotify.ps1 # Retrieve the default hosted outbound spam filter policy $hostedOutboundSpamFilterPolicy = Get-HostedOutboundSpamFilterPolicy | Where-Object { $_.IsDefault -eq $true } return $hostedOutboundSpamFilterPolicy } '2.1.7' { # Test-AntiPhishingPolicy.ps1 # Condition A: Ensure that an anti-phishing policy has been created $antiPhishPolicies = Get-AntiPhishPolicy return $antiPhishPolicies } '2.1.9' { # Test-EnableDKIM.ps1 # 2.1.9 (L1) Ensure DKIM is enabled for all Exchange Online Domains # Retrieve DKIM configuration for all domains $dkimConfig = Get-DkimSigningConfig | Select-Object Domain, Enabled # [object[]] return $dkimConfig } '3.1.1' { # Test-AuditLogSearch.ps1 # 3.1.1 (L1) Ensure Microsoft 365 audit log search is Enabled # Retrieve the audit log configuration $auditLogConfig = Get-AdminAuditLogConfig | Select-Object UnifiedAuditLogIngestionEnabled # $auditLogResult = $auditLogConfig.UnifiedAuditLogIngestionEnabled # [bool] return $auditLogResult } '6.1.1' { # Test-AuditDisabledFalse.ps1 # 6.1.1 (L1) Ensure 'AuditDisabled' organizationally is set to 'False' # Retrieve the AuditDisabled configuration (Condition B) $auditDisabledConfig = Get-OrganizationConfig | Select-Object AuditDisabled # [bool] $auditNotDisabled = -not $auditDisabledConfig.AuditDisabled return $auditNotDisabled } '6.1.2' { # Test-MailboxAuditingE3.ps1 $mailboxes = Get-EXOMailbox -PropertySets Audit # [object[]] return $mailboxes } '6.1.3' { # Test-MailboxAuditingE5.ps1 $mailboxes = Get-EXOMailbox -PropertySets Audit # [object[]] return $mailboxes } '6.2.1' { # Test-BlockMailForwarding.ps1 # 6.2.1 (L1) Ensure all forms of mail forwarding are blocked and/or disabled # Step 1: Retrieve the transport rules that redirect messages $transportRules = Get-TransportRule | Where-Object { $null -ne $_.RedirectMessageTo } if ($null -eq $transportRules) { $transportRules = 1 } # Step 2: Check all anti-spam outbound policies $outboundSpamPolicies = Get-HostedOutboundSpamFilterPolicy $nonCompliantSpamPolicies = $outboundSpamPolicies | Where-Object { $_.AutoForwardingMode -ne 'Off' } return $transportRules, $nonCompliantSpamPolicies } '6.2.2' { # Test-NoWhitelistDomains.ps1 # 6.2.2 (L1) Ensure mail transport rules do not whitelist specific domains # Retrieve transport rules that whitelist specific domains # Condition A: Checking for transport rules that whitelist specific domains # [object[]] $whitelistedRules = Get-TransportRule | Where-Object { $_.SetSCL -eq -1 -and $null -ne $_.SenderDomainIs } return $whitelistedRules } '6.2.3' { # Test-IdentifyExternalEmail.ps1 # 6.2.3 (L1) Ensure email from external senders is identified # Retrieve external sender tagging configuration # [object[]] $externalInOutlook = Get-ExternalInOutlook return $externalInOutlook } '6.3.1' { # Test-RestrictOutlookAddins.ps1 # 6.3.1 (L2) Ensure users installing Outlook add-ins is not allowed $customPolicyFailures = @() # Check all mailboxes for custom policies with unallowed add-ins $roleAssignmentPolicies = Get-EXOMailbox | Select-Object -Unique RoleAssignmentPolicy if ($roleAssignmentPolicies.RoleAssignmentPolicy) { foreach ($policy in $roleAssignmentPolicies) { if ($policy.RoleAssignmentPolicy) { $rolePolicyDetails = Get-RoleAssignmentPolicy -Identity $policy.RoleAssignmentPolicy $foundRoles = $rolePolicyDetails.AssignedRoles | Where-Object { $_ -in $relevantRoles } # Condition B: Using PowerShell, verify that MyCustomApps, MyMarketplaceApps, and MyReadWriteMailboxApps are not assigned to users. if ($foundRoles) { $customPolicyFailures += "Policy: $($policy.RoleAssignmentPolicy): Roles: $($foundRoles -join ', ')" } } } } # Check Default Role Assignment Policy $defaultPolicy = Get-RoleAssignmentPolicy "Default Role Assignment Policy" return $customPolicyFailures, $defaultPolicy } '6.5.1' { # Test-ModernAuthExchangeOnline.ps1 # Ensuring the ExchangeOnlineManagement module is available # 6.5.1 (L1) Ensure modern authentication for Exchange Online is enabled # Check modern authentication setting in Exchange Online configuration (Condition A and B) $orgConfig = Get-OrganizationConfig | Select-Object -Property Name, OAuth2ClientProfileEnabled return $orgConfig } '6.5.2' { # Test-MailTipsEnabled.ps1 # 6.5.2 (L2) Ensure MailTips are enabled for end users # Retrieve organization configuration for MailTips settings # [object] $orgConfig = Get-OrganizationConfig | Select-Object MailTipsAllTipsEnabled, MailTipsExternalRecipientsTipsEnabled, MailTipsGroupMetricsEnabled, MailTipsLargeAudienceThreshold return $orgConfig } '6.5.3' { # Test-RestrictStorageProvidersOutlook.ps1 # 6.5.3 (L2) Ensure additional storage providers are restricted in Outlook on the web # Retrieve all OwaMailbox policies # [object[]] $owaPolicies = Get-OwaMailboxPolicy return $owaPolicies } '8.6.1' { # Test-ReportSecurityInTeams.ps1 # 8.6.1 (L1) Ensure users can report security concerns in Teams # Retrieve the necessary settings for Teams and Exchange Online # Condition B: Verify that 'Monitor reported messages in Microsoft Teams' is checked in the Microsoft 365 Defender portal. # Condition C: Ensure the 'Send reported messages to' setting in the Microsoft 365 Defender portal is set to 'My reporting mailbox only' with the correct report email addresses. $ReportSubmissionPolicy = Get-ReportSubmissionPolicy | Select-Object -Property ReportJunkToCustomizedAddress, ReportNotJunkToCustomizedAddress, ReportPhishToCustomizedAddress,ReportJunkAddresses,ReportNotJunkAddresses,ReportPhishAddresses,ReportChatMessageEnabled,ReportChatMessageToCustomizedAddressEnabled return $ReportSubmissionPolicy } default { throw "No match found for test: $Rec" } } } end { Write-Verbose "Retuning data for Rec: $Rec" } } # end function Get-CISExoOutput #EndRegion '.\Private\Get-CISExoOutput.ps1' 298 #Region '.\Private\Get-CISMgOutput.ps1' -1 function Get-CISMgOutput { <# .SYNOPSIS This is a sample Private function only visible within the module. .DESCRIPTION This sample function is not exported to the module and only return the data passed as parameter. .EXAMPLE $null = Get-CISMgOutput -PrivateData 'NOTHING TO SEE HERE' .PARAMETER PrivateData The PrivateData parameter is what will be returned without transformation. #> [cmdletBinding()] param( [Parameter(Mandatory = $true)] [String]$Rec, [Parameter(Mandatory = $false)] [String]$DomainName ) begin { # Begin Block # # Tests <# 1.1.1 1.1.3 1.2.1 1.3.1 5.1.2.3 5.1.8.1 6.1.2 6.1.3 # Test number array $testNumbers = @('1.1.1', '1.1.3', '1.2.1', '1.3.1', '5.1.2.3', '5.1.8.1', '6.1.2', '6.1.3') #> } process { Write-Verbose "Get-CISMgOutput: Retuning data for Rec: $Rec" switch ($rec) { '1.1.1' { # 1.1.1 $AdminRoleAssignmentsAndUsers = Get-AdminRoleUserAndAssignment return $AdminRoleAssignmentsAndUsers } '1.1.3' { # Step: Retrieve global admin role $globalAdminRole = Get-MgDirectoryRole -Filter "RoleTemplateId eq '62e90394-69f5-4237-9190-012177145e10'" # Step: Retrieve global admin members $globalAdmins = Get-MgDirectoryRoleMember -DirectoryRoleId $globalAdminRole.Id return $globalAdmins } '1.2.1' { $allGroups = Get-MgGroup -All | Where-Object { $_.Visibility -eq "Public" } | Select-Object DisplayName, Visibility return $allGroups } '1.3.1' { # Test-PasswordNeverExpirePolicy.ps1 $domains = if ($DomainName) { Get-MgDomain -DomainId $DomainName } else { Get-MgDomain } return $domains } '5.1.2.3' { # Retrieve the tenant creation policy $tenantCreationPolicy = (Get-MgPolicyAuthorizationPolicy).DefaultUserRolePermissions | Select-Object AllowedToCreateTenants return $tenantCreationPolicy } '5.1.8.1' { # Retrieve password hash sync status (Condition A and C) $passwordHashSync = Get-MgOrganization | Select-Object -ExpandProperty OnPremisesSyncEnabled return $passwordHashSync } '6.1.2' { $tenantSkus = Get-MgSubscribedSku -All $e3SkuPartNumber = "SPE_E3" $founde3Sku = $tenantSkus | Where-Object { $_.SkuPartNumber -eq $e3SkuPartNumber } if ($founde3Sku.Count -ne 0) { $allE3Users = Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq $($founde3Sku.SkuId) )" -All return $allE3Users } else { return $null } } '6.1.3' { $tenantSkus = Get-MgSubscribedSku -All $e5SkuPartNumber = "SPE_E5" $founde5Sku = $tenantSkus | Where-Object { $_.SkuPartNumber -eq $e5SkuPartNumber } if ($founde5Sku.Count -ne 0) { $allE5Users = Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq $($founde5Sku.SkuId) )" -All return $allE5Users } else { return $null } } default { throw "No match found for test: $Rec" } } } end { Write-Verbose "Retuning data for Rec: $Rec" } } # end function Get-CISMgOutput #EndRegion '.\Private\Get-CISMgOutput.ps1' 111 #Region '.\Private\Get-CISMSTeamsOutput.ps1' -1 <# .SYNOPSIS This is a sample Private function only visible within the module. .DESCRIPTION This sample function is not exported to the module and only return the data passed as parameter. .EXAMPLE $null = Get-CISMSTeamsOutput -PrivateData 'NOTHING TO SEE HERE' .PARAMETER PrivateData The PrivateData parameter is what will be returned without transformation. #> function Get-CISMSTeamsOutput { [cmdletBinding()] param( [Parameter(Mandatory = $true)] [String]$Rec ) begin { # Begin Block # <# # Tests 8.1.1 8.1.2 8.2.1 8.5.1 8.5.2 8.5.3 8.5.4 8.5.5 8.5.6 8.5.7 8.6.1 # Test number array $testNumbers = @('8.1.1', '8.1.2', '8.2.1', '8.5.1', '8.5.2', '8.5.3', '8.5.4', '8.5.5', '8.5.6', '8.5.7', '8.6.1') #> } process { Write-Verbose "Get-CISMSTeamsOutput: Retuning data for Rec: $Rec" switch ($Rec) { '8.1.1' { # Test-TeamsExternalFileSharing.ps1 # 8.1.1 (L2) Ensure external file sharing in Teams is enabled for only approved cloud storage services # Connect to Teams PowerShell using Connect-MicrosoftTeams # Condition A: The `AllowDropbox` setting is set to `False`. # Condition B: The `AllowBox` setting is set to `False`. # Condition C: The `AllowGoogleDrive` setting is set to `False`. # Condition D: The `AllowShareFile` setting is set to `False`. # Condition E: The `AllowEgnyte` setting is set to `False`. # Assuming that 'approvedProviders' is a list of approved cloud storage service names # This list must be defined according to your organization's approved cloud storage services $clientConfig = Get-CsTeamsClientConfiguration return $clientConfig } '8.1.2' { # Test-BlockChannelEmails.ps1 # 8.1.2 (L1) Ensure users can't send emails to a channel email address # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: The `AllowEmailIntoChannel` setting in Teams is set to `False`. # - Condition B: The setting `Users can send emails to a channel email address` is set to `Off` in the Teams admin center. # - Condition C: Verification using PowerShell confirms that the `AllowEmailIntoChannel` setting is disabled. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `AllowEmailIntoChannel` setting in Teams is not set to `False`. # - Condition B: The setting `Users can send emails to a channel email address` is not set to `Off` in the Teams admin center. # - Condition C: Verification using PowerShell indicates that the `AllowEmailIntoChannel` setting is enabled. # Retrieve Teams client configuration $teamsClientConfig = Get-CsTeamsClientConfiguration -Identity Global return $teamsClientConfig } '8.2.1' { # Test-TeamsExternalAccess.ps1 # 8.2.1 (L1) Ensure 'external access' is restricted in the Teams admin center # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: The `AllowTeamsConsumer` setting is `False`. # - Condition B: The `AllowPublicUsers` setting is `False`. # - Condition C: The `AllowFederatedUsers` setting is `False` or, if `True`, the `AllowedDomains` contains only authorized domain names. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `AllowTeamsConsumer` setting is not `False`. # - Condition B: The `AllowPublicUsers` setting is not `False`. # - Condition C: The `AllowFederatedUsers` setting is `True` and the `AllowedDomains` contains unauthorized domain names or is not configured correctly. # Connect to Teams PowerShell using Connect-MicrosoftTeams $externalAccessConfig = Get-CsTenantFederationConfiguration return $externalAccessConfig } '8.5.1' { # Test-NoAnonymousMeetingJoin.ps1 # 8.5.1 (L2) Ensure anonymous users can't join a meeting # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: `AllowAnonymousUsersToJoinMeeting` is set to `False`. # - Condition B: Verification using the UI confirms that `Anonymous users can join a meeting` is set to `Off` in the Global meeting policy. # - Condition C: PowerShell command output indicates that anonymous users are not allowed to join meetings. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: `AllowAnonymousUsersToJoinMeeting` is not set to `False`. # - Condition B: Verification using the UI shows that `Anonymous users can join a meeting` is not set to `Off` in the Global meeting policy. # - Condition C: PowerShell command output indicates that anonymous users are allowed to join meetings. # Connect to Teams PowerShell using Connect-MicrosoftTeams $teamsMeetingPolicy = Get-CsTeamsMeetingPolicy -Identity Global return $teamsMeetingPolicy } '8.5.2' { # Test-NoAnonymousMeetingStart.ps1 # 8.5.2 (L1) Ensure anonymous users and dial-in callers can't start a meeting # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: The `AllowAnonymousUsersToStartMeeting` setting in the Teams admin center is set to `False`. # - Condition B: The setting for anonymous users and dial-in callers starting a meeting is configured to ensure they must wait in the lobby. # - Condition C: Verification using the UI confirms that the setting `Anonymous users and dial-in callers can start a meeting` is set to `Off`. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `AllowAnonymousUsersToStartMeeting` setting in the Teams admin center is not set to `False`. # - Condition B: The setting for anonymous users and dial-in callers starting a meeting allows them to bypass the lobby. # - Condition C: Verification using the UI indicates that the setting `Anonymous users and dial-in callers can start a meeting` is not set to `Off`. # Connect to Teams PowerShell using Connect-MicrosoftTeams # Retrieve the Teams meeting policy for the global scope and check if anonymous users can start meetings $CsTeamsMeetingPolicyAnonymous = Get-CsTeamsMeetingPolicy -Identity Global | Select-Object -Property AllowAnonymousUsersToStartMeeting return $CsTeamsMeetingPolicyAnonymous } '8.5.3' { # Test-OrgOnlyBypassLobby.ps1 # 8.5.3 (L1) Ensure only people in my org can bypass the lobby # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: The `AutoAdmittedUsers` setting in the Teams meeting policy is set to `EveryoneInCompanyExcludingGuests`. # - Condition B: The setting for "Who can bypass the lobby" is configured to "People in my org" using the UI. # - Condition C: Verification using the Microsoft Teams admin center confirms that the meeting join & lobby settings are configured as recommended. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `AutoAdmittedUsers` setting in the Teams meeting policy is not set to `EveryoneInCompanyExcludingGuests`. # - Condition B: The setting for "Who can bypass the lobby" is not configured to "People in my org" using the UI. # - Condition C: Verification using the Microsoft Teams admin center indicates that the meeting join & lobby settings are not configured as recommended. # Connect to Teams PowerShell using Connect-MicrosoftTeams # Retrieve the Teams meeting policy for lobby bypass settings $CsTeamsMeetingPolicyLobby = Get-CsTeamsMeetingPolicy -Identity Global | Select-Object -Property AutoAdmittedUsers return $CsTeamsMeetingPolicyLobby } '8.5.4' { # Test-DialInBypassLobby.ps1 # 8.5.4 (L1) Ensure users dialing in can't bypass the lobby # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: The `AllowPSTNUsersToBypassLobby` setting in the Global Teams meeting policy is set to `False`. # - Condition B: Verification using the UI in the Microsoft Teams admin center confirms that "People dialing in can't bypass the lobby" is set to `Off`. # - Condition C: Ensure that individuals who dial in by phone must wait in the lobby until admitted by a meeting organizer, co-organizer, or presenter. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `AllowPSTNUsersToBypassLobby` setting in the Global Teams meeting policy is not set to `False`. # - Condition B: Verification using the UI in the Microsoft Teams admin center shows that "People dialing in can't bypass the lobby" is not set to `Off`. # - Condition C: Individuals who dial in by phone are able to join the meeting directly without waiting in the lobby. # Retrieve Teams meeting policy for PSTN users $CsTeamsMeetingPolicyPSTN = Get-CsTeamsMeetingPolicy -Identity Global | Select-Object -Property AllowPSTNUsersToBypassLobby return $CsTeamsMeetingPolicyPSTN } '8.5.5' { # Test-MeetingChatNoAnonymous.ps1 # 8.5.5 (L2) Ensure meeting chat does not allow anonymous users # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: The `MeetingChatEnabledType` setting in Teams is set to `EnabledExceptAnonymous`. # - Condition B: The setting for meeting chat is configured to allow chat for everyone except anonymous users. # - Condition C: Verification using the Teams Admin Center confirms that the meeting chat settings are configured as recommended. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `MeetingChatEnabledType` setting in Teams is not set to `EnabledExceptAnonymous`. # - Condition B: The setting for meeting chat allows chat for anonymous users. # - Condition C: Verification using the Teams Admin Center indicates that the meeting chat settings are not configured as recommended. # Retrieve the Teams meeting policy for meeting chat $CsTeamsMeetingPolicyChat = Get-CsTeamsMeetingPolicy -Identity Global | Select-Object -Property MeetingChatEnabledType return $CsTeamsMeetingPolicyChat } '8.5.6' { # Test-OrganizersPresent.ps1 # 8.5.6 (L2) Ensure only organizers and co-organizers can present # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: The `DesignatedPresenterRoleMode` setting in the Teams meeting policy is set to `OrganizerOnlyUserOverride`. # - Condition B: Verification using the Teams admin center confirms that the setting "Who can present" is configured to "Only organizers and co-organizers". # - Condition C: Verification using PowerShell confirms that the `DesignatedPresenterRoleMode` is set to `OrganizerOnlyUserOverride`. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `DesignatedPresenterRoleMode` setting in the Teams meeting policy is not set to `OrganizerOnlyUserOverride`. # - Condition B: Verification using the Teams admin center indicates that the setting "Who can present" is not configured to "Only organizers and co-organizers". # - Condition C: Verification using PowerShell indicates that the `DesignatedPresenterRoleMode` is not set to `OrganizerOnlyUserOverride`. # Retrieve the Teams meeting policy for presenters $CsTeamsMeetingPolicyPresenters = Get-CsTeamsMeetingPolicy -Identity Global | Select-Object -Property DesignatedPresenterRoleMode return $CsTeamsMeetingPolicyPresenters } '8.5.7' { # Test-ExternalNoControl.ps1 # 8.5.7 (L1) Ensure external participants can't give or request control # # Validate test for a pass: # - Confirm that the automated test results align with the manual audit steps outlined in the CIS benchmark. # - Specific conditions to check: # - Condition A: Ensure the `AllowExternalParticipantGiveRequestControl` setting in Teams is set to `False`. # - Condition B: The setting is verified through the Microsoft Teams admin center or via PowerShell command. # - Condition C: Verification using the UI confirms that external participants are unable to give or request control. # # Validate test for a fail: # - Confirm that the failure conditions in the automated test are consistent with the manual audit results. # - Specific conditions to check: # - Condition A: The `AllowExternalParticipantGiveRequestControl` setting in Teams is not set to `False`. # - Condition B: The setting is verified through the Microsoft Teams admin center or via PowerShell command. # - Condition C: Verification using the UI indicates that external participants can give or request control. # Retrieve Teams meeting policy for external participant control $CsTeamsMeetingPolicyControl = Get-CsTeamsMeetingPolicy -Identity Global | Select-Object -Property AllowExternalParticipantGiveRequestControl return $CsTeamsMeetingPolicyControl } '8.6.1' { # Test-ReportSecurityInTeams.ps1 # 8.6.1 (L1) Ensure users can report security concerns in Teams # Retrieve the necessary settings for Teams and Exchange Online # Condition A: Ensure the 'Report a security concern' setting in the Teams admin center is set to 'On'. $CsTeamsMessagingPolicy = Get-CsTeamsMessagingPolicy -Identity Global | Select-Object -Property AllowSecurityEndUserReporting return $CsTeamsMessagingPolicy } default { throw "No match found for test: $Rec" } } } end { Write-Verbose "Retuning data for Rec: $Rec" } } # end function Get-CISMSTeamsOutput #EndRegion '.\Private\Get-CISMSTeamsOutput.ps1' 276 #Region '.\Private\Get-CISSpoOutput.ps1' -1 <# .SYNOPSIS This is a sample Private function only visible within the module. .DESCRIPTION This sample function is not exported to the module and only return the data passed as parameter. .EXAMPLE $null = Get-CISSpoOutput -PrivateData 'NOTHING TO SEE HERE' .PARAMETER PrivateData The PrivateData parameter is what will be returned without transformation. #> function Get-CISSpoOutput { [cmdletBinding()] param( [Parameter(Mandatory = $true)] [String]$Rec ) begin { # Begin Block # <# # Tests 7.2.1 7.2.2 7.2.3 7.2.4 7.2.5 7.2.6 7.2.7 7.2.9 7.2.10 7.3.1 7.3.2 7.3.4 # Test number array $testNumbers = @('7.2.1', '7.2.2', '7.2.3', '7.2.4', '7.2.5', '7.2.6', '7.2.7', '7.2.9', '7.2.10', '7.3.1', '7.3.2', '7.3.4') #> } process { Write-Verbose "Retuning data for Rec: $Rec" switch ($Rec) { '7.2.1' { # Test-ModernAuthSharePoint.ps1 $SPOTenant = Get-SPOTenant | Select-Object -Property LegacyAuthProtocolsEnabled return $SPOTenant } '7.2.2' { # Test-SharePointAADB2B.ps1 # 7.2.2 (L1) Ensure SharePoint and OneDrive integration with Azure AD B2B is enabled $SPOTenantAzureADB2B = Get-SPOTenant | Select-Object EnableAzureADB2BIntegration return $SPOTenantAzureADB2B } '7.2.3' { # Test-RestrictExternalSharing.ps1 # 7.2.3 (L1) Ensure external content sharing is restricted # Retrieve the SharingCapability setting for the SharePoint tenant $SPOTenantSharingCapability = Get-SPOTenant | Select-Object SharingCapability return $SPOTenantSharingCapability } '7.2.4' { # Test-OneDriveContentRestrictions.ps1 $SPOTenant = Get-SPOTenant | Select-Object OneDriveSharingCapability return $SPOTenant } '7.2.5' { # Test-SharePointGuestsItemSharing.ps1 # 7.2.5 (L2) Ensure that SharePoint guest users cannot share items they don't own $SPOTenant = Get-SPOTenant | Select-Object PreventExternalUsersFromResharing return $SPOTenant } '7.2.6' { # Test-SharePointExternalSharingDomains.ps1 # 7.2.6 (L2) Ensure SharePoint external sharing is managed through domain whitelist/blacklists $SPOTenant = Get-SPOTenant | Select-Object SharingDomainRestrictionMode, SharingAllowedDomainList return $SPOTenant } '7.2.7' { # Test-LinkSharingRestrictions.ps1 # Retrieve link sharing configuration for SharePoint and OneDrive $SPOTenantLinkSharing = Get-SPOTenant | Select-Object DefaultSharingLinkType return $SPOTenantLinkSharing } '7.2.9' { # Test-GuestAccessExpiration.ps1 # Retrieve SharePoint tenant settings related to guest access expiration $SPOTenantGuestAccess = Get-SPOTenant | Select-Object ExternalUserExpirationRequired, ExternalUserExpireInDays return $SPOTenantGuestAccess } '7.2.10' { # Test-ReauthWithCode.ps1 # 7.2.10 (L1) Ensure reauthentication with verification code is restricted # Retrieve reauthentication settings for SharePoint Online $SPOTenantReauthentication = Get-SPOTenant | Select-Object EmailAttestationRequired, EmailAttestationReAuthDays return $SPOTenantReauthentication } '7.3.1' { # Test-DisallowInfectedFilesDownload.ps1 # Retrieve the SharePoint tenant configuration $SPOTenantDisallowInfectedFileDownload = Get-SPOTenant | Select-Object DisallowInfectedFileDownload return $SPOTenantDisallowInfectedFileDownload } '7.3.2' { # Test-OneDriveSyncRestrictions.ps1 # Retrieve OneDrive sync client restriction settings $SPOTenantSyncClientRestriction = Get-SPOTenantSyncClientRestriction | Select-Object TenantRestrictionEnabled, AllowedDomainList return $SPOTenantSyncClientRestriction } '7.3.4' { # Test-RestrictCustomScripts.ps1 # Retrieve all site collections and select necessary properties $SPOSitesCustomScript = Get-SPOSite -Limit All | Select-Object Title, Url, DenyAddAndCustomizePages return $SPOSitesCustomScript } default { throw "No match found for test: $Rec" } } } end { Write-Verbose "Retuning data for Rec: $Rec" } } # end function Get-CISMSTeamsOutput #EndRegion '.\Private\Get-CISSpoOutput.ps1' 120 #Region '.\Private\Get-ExceededLengthResultDetail.ps1' -1 function Get-ExceededLengthResultDetail { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = 'UpdateArray')] [Parameter(Mandatory = $true, ParameterSetName = 'ReturnExceedingTests')] [object[]]$AuditResults, [Parameter(Mandatory = $true, ParameterSetName = 'UpdateArray')] [Parameter(Mandatory = $true, ParameterSetName = 'ReturnExceedingTests')] [string[]]$TestNumbersToCheck, [Parameter(Mandatory = $true, ParameterSetName = 'UpdateArray')] [string[]]$ExportedTests, [Parameter(Mandatory = $true, ParameterSetName = 'ReturnExceedingTests')] [switch]$ReturnExceedingTestsOnly, [int]$DetailsLengthLimit = 30000, [Parameter(Mandatory = $true, ParameterSetName = 'UpdateArray')] [int]$PreviewLineCount = 50 ) $exceedingTests = @() $updatedResults = @() for ($i = 0; $i -lt $AuditResults.Count; $i++) { $auditResult = $AuditResults[$i] if ($auditResult.Rec -in $TestNumbersToCheck) { if ($auditResult.Details.Length -gt $DetailsLengthLimit) { if ($ReturnExceedingTestsOnly) { $exceedingTests += $auditResult.Rec } else { $previewLines = ($auditResult.Details -split '\r?\n' | Select-Object -First $PreviewLineCount) -join "`n" $message = "The test result is too large to be exported to CSV. Use the audit result and the export function for full output.`n`nPreview:`n$previewLines" if ($ExportedTests -contains $auditResult.Rec) { Write-Information "The test result for $($auditResult.Rec) is too large for CSV and was included in the export. Check the exported files." $auditResult.Details = $message } else { $auditResult.Details = $message } } } } $updatedResults += $auditResult } if ($ReturnExceedingTestsOnly) { return $exceedingTests } else { return $updatedResults } } #EndRegion '.\Private\Get-ExceededLengthResultDetail.ps1' 55 #Region '.\Private\Get-MostCommonWord.ps1' -1 function Get-MostCommonWord { [CmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory = $true)] [string[]]$InputStrings ) # Combine all strings into one large string $allText = $InputStrings -join ' ' # Split the large string into words $words = $allText -split '\s+' # Group words and count occurrences $wordGroups = $words | Group-Object | Sort-Object Count -Descending # Return the most common word if it occurs at least 3 times if ($wordGroups.Count -gt 0 -and $wordGroups[0].Count -ge 3) { return $wordGroups[0].Name } else { return $null } } #EndRegion '.\Private\Get-MostCommonWord.ps1' 25 #Region '.\Private\Get-RequiredModule.ps1' -1 function Get-RequiredModule { [CmdletBinding(DefaultParameterSetName = 'AuditFunction')] [OutputType([System.Object[]])] param ( [Parameter(Mandatory = $true, ParameterSetName = 'AuditFunction')] [switch]$AuditFunction, [Parameter(Mandatory = $true, ParameterSetName = 'SyncFunction')] [switch]$SyncFunction ) switch ($PSCmdlet.ParameterSetName) { 'AuditFunction' { return @( @{ ModuleName = "ExchangeOnlineManagement"; RequiredVersion = "3.3.0"; SubModules = @() }, @{ ModuleName = "AzureAD"; RequiredVersion = "2.0.2.182"; SubModules = @() }, @{ ModuleName = "Microsoft.Graph"; RequiredVersion = "2.4.0"; SubModules = @("Groups", "DeviceManagement", "Users", "Identity.DirectoryManagement", "Identity.SignIns") }, @{ ModuleName = "Microsoft.Online.SharePoint.PowerShell"; RequiredVersion = "16.0.24009.12000"; SubModules = @() }, @{ ModuleName = "MicrosoftTeams"; RequiredVersion = "5.5.0"; SubModules = @() } ) } 'SyncFunction' { return @( @{ ModuleName = "ImportExcel"; RequiredVersion = "7.8.9"; SubModules = @() } ) } default { throw "Please specify either -AuditFunction or -SyncFunction switch." } } } #EndRegion '.\Private\Get-RequiredModule.ps1' 32 #Region '.\Private\Get-TestDefinitionsObject.ps1' -1 function Get-TestDefinitionsObject { [CmdletBinding()] [OutputType([object[]])] param ( [Parameter(Mandatory = $true)] [object[]]$TestDefinitions, [Parameter(Mandatory = $true)] [string]$ParameterSetName, [string]$ELevel, [string]$ProfileLevel, [string[]]$IncludeRecommendation, [string[]]$SkipRecommendation ) Write-Verbose "Initial test definitions count: $($TestDefinitions.Count)" switch ($ParameterSetName) { 'ELevelFilter' { Write-Verbose "Applying ELevelFilter" if ($null -ne $ELevel -and $null -ne $ProfileLevel) { Write-Verbose "Filtering on ELevel = $ELevel and ProfileLevel = $ProfileLevel" $TestDefinitions = $TestDefinitions | Where-Object { $_.ELevel -eq $ELevel -and $_.ProfileLevel -eq $ProfileLevel } } elseif ($null -ne $ELevel) { Write-Verbose "Filtering on ELevel = $ELevel" $TestDefinitions = $TestDefinitions | Where-Object { $_.ELevel -eq $ELevel } } elseif ($null -ne $ProfileLevel) { Write-Verbose "Filtering on ProfileLevel = $ProfileLevel" $TestDefinitions = $TestDefinitions | Where-Object { $_.ProfileLevel -eq $ProfileLevel } } } 'IG1Filter' { Write-Verbose "Applying IG1Filter" $TestDefinitions = $TestDefinitions | Where-Object { $_.IG1 -eq 'TRUE' } } 'IG2Filter' { Write-Verbose "Applying IG2Filter" $TestDefinitions = $TestDefinitions | Where-Object { $_.IG2 -eq 'TRUE' } } 'IG3Filter' { Write-Verbose "Applying IG3Filter" $TestDefinitions = $TestDefinitions | Where-Object { $_.IG3 -eq 'TRUE' } } 'RecFilter' { Write-Verbose "Applying RecFilter" $TestDefinitions = $TestDefinitions | Where-Object { $IncludeRecommendation -contains $_.Rec } } 'SkipRecFilter' { Write-Verbose "Applying SkipRecFilter" $TestDefinitions = $TestDefinitions | Where-Object { $SkipRecommendation -notcontains $_.Rec } } } Write-Verbose "Filtered test definitions count: $($TestDefinitions.Count)" return $TestDefinitions } #EndRegion '.\Private\Get-TestDefinitionsObject.ps1' 66 #Region '.\Private\Get-TestError.ps1' -1 <# .SYNOPSIS This is a sample Private function only visible within the module. .DESCRIPTION This sample function is not exported to the module and only return the data passed as parameter. .EXAMPLE $null = Get-TestError -PrivateData 'NOTHING TO SEE HERE' .PARAMETER PrivateData The PrivateData parameter is what will be returned without transformation. #> function Get-TestError { [cmdletBinding()] param ( $LastError, $recnum ) # Retrieve the description from the test definitions $testDefinition = $script:TestDefinitionsObject | Where-Object { $_.Rec -eq $recnum } $description = if ($testDefinition) { $testDefinition.RecDescription } else { "Description not found" } $script:FailedTests.Add([PSCustomObject]@{ Rec = $recnum; Description = $description; Error = $LastError }) # Call Initialize-CISAuditResult with error parameters $auditResult = Initialize-CISAuditResult -Rec $recnum -Failure Write-Verbose "An error occurred during the test: `n$LastError" -Verbose return $auditResult } #EndRegion '.\Private\Get-TestError.ps1' 34 #Region '.\Private\Get-UniqueConnection.ps1' -1 function Get-UniqueConnection { [CmdletBinding()] [OutputType([string[]])] param ( [Parameter(Mandatory = $true)] [string[]]$Connections ) $uniqueConnections = @() if ($Connections -contains "AzureAD" -or $Connections -contains "AzureAD | EXO" -or $Connections -contains "AzureAD | EXO | Microsoft Graph") { $uniqueConnections += "AzureAD" } if ($Connections -contains "Microsoft Graph" -or $Connections -contains "AzureAD | EXO | Microsoft Graph") { $uniqueConnections += "Microsoft Graph" } if ($Connections -contains "EXO" -or $Connections -contains "AzureAD | EXO" -or $Connections -contains "Microsoft Teams | EXO" -or $Connections -contains "AzureAD | EXO | Microsoft Graph") { $uniqueConnections += "EXO" } if ($Connections -contains "SPO") { $uniqueConnections += "SPO" } if ($Connections -contains "Microsoft Teams" -or $Connections -contains "Microsoft Teams | EXO") { $uniqueConnections += "Microsoft Teams" } return $uniqueConnections | Sort-Object -Unique } #EndRegion '.\Private\Get-UniqueConnection.ps1' 29 #Region '.\Private\Get-UrlLine.ps1' -1 <# .SYNOPSIS This is a sample Private function only visible within the module. .DESCRIPTION This sample function is not exported to the module and only return the data passed as parameter. .EXAMPLE $null = Get-UrlLine -PrivateData 'NOTHING TO SEE HERE' .PARAMETER PrivateData The PrivateData parameter is what will be returned without transformation. #> function Get-UrlLine { [cmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory=$true)] [string]$Output ) # Split the output into lines $Lines = $Output -split "`n" # Iterate over each line foreach ($Line in $Lines) { # If the line starts with 'https', return it if ($Line.StartsWith('https')) { return $Line.Trim() } } # If no line starts with 'https', return an empty string return $null } #EndRegion '.\Private\Get-UrlLine.ps1' 33 #Region '.\Private\Initialize-CISAuditResult.ps1' -1 function Initialize-CISAuditResult { [CmdletBinding()] [OutputType([CISAuditResult])] param ( [Parameter(Mandatory = $true)] [string]$Rec, [Parameter(Mandatory = $true, ParameterSetName = 'Full')] [bool]$Result, [Parameter(Mandatory = $true, ParameterSetName = 'Full')] [string]$Status, [Parameter(Mandatory = $true, ParameterSetName = 'Full')] [string]$Details, [Parameter(Mandatory = $true, ParameterSetName = 'Full')] [string]$FailureReason, [Parameter(ParameterSetName = 'Error')] [switch]$Failure ) # Import the test definitions CSV file $testDefinitions = $script:TestDefinitionsObject # Find the row that matches the provided recommendation (Rec) $testDefinition = $testDefinitions | Where-Object { $_.Rec -eq $Rec } if (-not $testDefinition) { throw "Test definition for recommendation '$Rec' not found." } # Create an instance of CISAuditResult and populate it $auditResult = [CISAuditResult]::new() $auditResult.Rec = $Rec $auditResult.ELevel = $testDefinition.ELevel $auditResult.ProfileLevel = $testDefinition.ProfileLevel $auditResult.IG1 = [bool]::Parse($testDefinition.IG1) $auditResult.IG2 = [bool]::Parse($testDefinition.IG2) $auditResult.IG3 = [bool]::Parse($testDefinition.IG3) $auditResult.RecDescription = $testDefinition.RecDescription $auditResult.CISControl = $testDefinition.CISControl $auditResult.CISDescription = $testDefinition.CISDescription $auditResult.Automated = [bool]::Parse($testDefinition.Automated) $auditResult.Connection = $testDefinition.Connection $auditResult.CISControlVer = 'v8' if ($PSCmdlet.ParameterSetName -eq 'Full') { $auditResult.Result = $Result $auditResult.Status = $Status $auditResult.Details = $Details $auditResult.FailureReason = $FailureReason } elseif ($PSCmdlet.ParameterSetName -eq 'Error') { $auditResult.Result = $false $auditResult.Status = 'Fail' $auditResult.Details = "An error occurred while processing the test." $auditResult.FailureReason = "Initialization error: Failed to process the test." } return $auditResult } #EndRegion '.\Private\Initialize-CISAuditResult.ps1' 63 #Region '.\Private\Initialize-LargeTestTable.ps1' -1 <# .SYNOPSIS This function generates a large table with the specified number of lines. .DESCRIPTION This function generates a large table with the specified number of lines. The table has a header and each line has the same format. .EXAMPLE Initialize-LargeTestTable -lineCount 1000 .PARAMETER lineCount The number of lines to generate. .INPUTS System.Int32 .OUTPUTS System.String .NOTES The function is intended for testing purposes. #> function Initialize-LargeTestTable { [cmdletBinding()] [OutputType([string])] param( [Parameter()] [int]$lineCount = 1000 # Number of lines to generate ) process { $header = "UserPrincipalName|AuditEnabled|AdminActionsMissing|DelegateActionsMissing|OwnerActionsMissing" $lineTemplate = "user{0}@contosonorthwind.net|True|FB,CP,MV|FB,MV|ML,MV,CR" # Generate the header and lines $lines = @($header) for ($i = 1; $i -le $lineCount; $i++) { $lines += [string]::Format($lineTemplate, $i) } $output = $lines -join "`n" Write-Host "Details character count: $($output.Length)" return $output } } #EndRegion '.\Private\Initialize-LargeTestTable.ps1' 37 #Region '.\Private\Invoke-TestFunction.ps1' -1 function Invoke-TestFunction { [OutputType([CISAuditResult[]])] param ( [Parameter(Mandatory = $true)] [PSObject]$FunctionFile, [Parameter(Mandatory = $false)] [string]$DomainName ) $functionName = $FunctionFile.BaseName $functionCmd = Get-Command -Name $functionName # Check if the test function needs DomainName parameter $paramList = @{} if ('DomainName' -in $functionCmd.Parameters.Keys) { $paramList.DomainName = $DomainName } # Use splatting to pass parameters Write-Verbose "Running $functionName..." try { $result = & $functionName @paramList # Assuming each function returns an array of CISAuditResult or a single CISAuditResult return $result } catch { Write-Error "An error occurred during the test: $_" $script:FailedTests.Add([PSCustomObject]@{ Test = $functionName; Error = $_ }) # Call Initialize-CISAuditResult with error parameters $auditResult = Initialize-CISAuditResult -Rec $functionName -Failure return $auditResult } } #EndRegion '.\Private\Invoke-TestFunction.ps1' 36 #Region '.\Private\Measure-AuditResult.ps1' -1 function Measure-AuditResult { [OutputType([void])] param ( [Parameter(Mandatory = $true)] [System.Collections.ArrayList]$AllAuditResults, [Parameter(Mandatory = $false)] [System.Collections.ArrayList]$FailedTests ) # Calculate the total number of tests $totalTests = $AllAuditResults.Count # Calculate the number of passed tests $passedTests = $AllAuditResults.ToArray() | Where-Object { $_.Result -eq $true } | Measure-Object | Select-Object -ExpandProperty Count # Calculate the pass percentage $passPercentage = if ($totalTests -eq 0) { 0 } else { [math]::Round(($passedTests / $totalTests) * 100, 2) } # Display the pass percentage to the user Write-Host "Audit completed. $passedTests out of $totalTests tests passed." -ForegroundColor Cyan Write-Host "Your passing percentage is $passPercentage%." -ForegroundColor Magenta # Display details of failed tests if ($FailedTests.Count -gt 0) { Write-Host "The following tests failed to complete:" -ForegroundColor Red foreach ($failedTest in $FailedTests) { Write-Host "Test: $($failedTest.Test)" -ForegroundColor Yellow Write-Host "Error: $($failedTest.Error)" -ForegroundColor Yellow } } } #EndRegion '.\Private\Measure-AuditResult.ps1' 33 #Region '.\Private\Test-IsAdmin.ps1' -1 function Test-IsAdmin { <# .SYNOPSIS Checks if the current user is an administrator on the machine. .DESCRIPTION This private function returns a Boolean value indicating whether the current user has administrator privileges on the machine. It does this by creating a new WindowsPrincipal object, passing in a WindowsIdentity object representing the current user, and then checking if that principal is in the Administrator role. .INPUTS None. .OUTPUTS Boolean. Returns True if the current user is an administrator, and False otherwise. .EXAMPLE PS C:\> Test-IsAdmin True #> # Create a new WindowsPrincipal object for the current user and check if it is in the Administrator role (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) } #EndRegion '.\Private\Test-IsAdmin.ps1' 23 #Region '.\Private\Write-AuditLog.ps1' -1 function Write-AuditLog { <# .SYNOPSIS Writes log messages to the console and updates the script-wide log variable. .DESCRIPTION The Write-AuditLog function writes log messages to the console based on the severity (Verbose, Warning, or Error) and updates the script-wide log variable ($script:LogString) with the log entry. You can use the Start, End, and EndFunction switches to manage the lifecycle of the logging. .INPUTS System.String You can pipe a string to the Write-AuditLog function as the Message parameter. You can also pipe an object with a Severity property as the Severity parameter. .OUTPUTS None The Write-AuditLog function doesn't output any objects to the pipeline. It writes messages to the console and updates the script-wide log variable ($script:LogString). .PARAMETER BeginFunction Sets the message to "Begin [FunctionName] function log.", where FunctionName is the name of the calling function, and adds it to the log variable. .PARAMETER Message The message string to log. .PARAMETER Severity The severity of the log message. Accepted values are 'Information', 'Warning', and 'Error'. Defaults to 'Information'. .PARAMETER Start Initializes the script-wide log variable and sets the message to "Begin [FunctionName] Log.", where FunctionName is the name of the calling function. .PARAMETER End Sets the message to "End Log" and exports the log to a CSV file if the OutputPath parameter is provided. .PARAMETER EndFunction Sets the message to "End [FunctionName] log.", where FunctionName is the name of the calling function, and adds it to the log variable. .PARAMETER OutputPath The file path for exporting the log to a CSV file when using the End switch. .EXAMPLE Write-AuditLog -Message "This is a test message." Writes a test message with the default severity (Information) to the console and adds it to the log variable. .EXAMPLE Write-AuditLog -Message "This is a warning message." -Severity "Warning" Writes a warning message to the console and adds it to the log variable. .EXAMPLE Write-AuditLog -Start Initializes the log variable and sets the message to "Begin [FunctionName] Log.", where FunctionName is the name of the calling function. .EXAMPLE Write-AuditLog -BeginFunction Sets the message to "Begin [FunctionName] function log.", where FunctionName is the name of the calling function, and adds it to the log variable. .EXAMPLE Write-AuditLog -EndFunction Sets the message to "End [FunctionName] log.", where FunctionName is the name of the calling function, and adds it to the log variable. .EXAMPLE Write-AuditLog -End -OutputPath "C:\Logs\auditlog.csv" Sets the message to "End Log", adds it to the log variable, and exports the log to a CSV file. .NOTES Author: DrIOSx #> [CmdletBinding(DefaultParameterSetName = 'Default')] param( ### [Parameter( Mandatory = $false, HelpMessage = 'Input a Message string.', Position = 0, ParameterSetName = 'Default', ValueFromPipeline = $true )] [ValidateNotNullOrEmpty()] [string]$Message, ### [Parameter( Mandatory = $false, HelpMessage = 'Information, Warning or Error.', Position = 1, ParameterSetName = 'Default', ValueFromPipelineByPropertyName = $true )] [ValidateNotNullOrEmpty()] [ValidateSet('Information', 'Warning', 'Error')] [string]$Severity = 'Information', ### [Parameter( Mandatory = $false, ParameterSetName = 'End' )] [switch]$End, ### [Parameter( Mandatory = $false, ParameterSetName = 'BeginFunction' )] [switch]$BeginFunction, [Parameter( Mandatory = $false, ParameterSetName = 'EndFunction' )] [switch]$EndFunction, ### [Parameter( Mandatory = $false, ParameterSetName = 'Start' )] [switch]$Start, ### [Parameter( Mandatory = $false, ParameterSetName = 'End' )] [string]$OutputPath ) begin { $ErrorActionPreference = "SilentlyContinue" # Define variables to hold information about the command that was invoked. $ModuleName = $Script:MyInvocation.MyCommand.Name -replace '\..*' $callStack = Get-PSCallStack if ($callStack.Count -gt 1) { $FuncName = $callStack[1].Command } else { $FuncName = "DirectCall" # Or any other default name you prefer } #Write-Verbose "Funcname Name is $FuncName!" -Verbose $ModuleVer = $MyInvocation.MyCommand.Version.ToString() # Set the error action preference to continue. $ErrorActionPreference = "Continue" } process { try { if (-not $Start -and -not (Test-Path variable:script:LogString)) { throw "The logging variable is not initialized. Please call Write-AuditLog with the -Start switch or ensure $script:LogString is set." } $Function = $($FuncName + '.v' + $ModuleVer) if ($Start) { $script:LogString = @() $Message = '+++ Begin Log | ' + $Function + ' |' } elseif ($BeginFunction) { $Message = '>>> Begin Function Log | ' + $Function + ' |' } $logEntry = [pscustomobject]@{ Time = ((Get-Date).ToString('yyyy-MM-dd hh:mmTss')) Module = $ModuleName PSVersion = ($PSVersionTable.PSVersion).ToString() PSEdition = ($PSVersionTable.PSEdition).ToString() IsAdmin = $(Test-IsAdmin) User = "$Env:USERDOMAIN\$Env:USERNAME" HostName = $Env:COMPUTERNAME InvokedBy = $Function Severity = $Severity Message = $Message RunID = -1 } if ($BeginFunction) { $maxRunID = ($script:LogString | Where-Object { $_.InvokedBy -eq $Function } | Measure-Object -Property RunID -Maximum).Maximum if ($null -eq $maxRunID) { $maxRunID = -1 } $logEntry.RunID = $maxRunID + 1 } else { $lastRunID = ($script:LogString | Where-Object { $_.InvokedBy -eq $Function } | Select-Object -Last 1).RunID if ($null -eq $lastRunID) { $lastRunID = 0 } $logEntry.RunID = $lastRunID } if ($EndFunction) { $FunctionStart = "$((($script:LogString | Where-Object {$_.InvokedBy -eq $Function -and $_.RunId -eq $lastRunID } | Sort-Object Time)[0]).Time)" $startTime = ([DateTime]::ParseExact("$FunctionStart", 'yyyy-MM-dd hh:mmTss', $null)) $endTime = Get-Date $timeTaken = $endTime - $startTime $Message = '<<< End Function Log | ' + $Function + ' | Runtime: ' + "$($timeTaken.Minutes) min $($timeTaken.Seconds) sec" $logEntry.Message = $Message } elseif ($End) { $startTime = ([DateTime]::ParseExact($($script:LogString[0].Time), 'yyyy-MM-dd hh:mmTss', $null)) $endTime = Get-Date $timeTaken = $endTime - $startTime $Message = '--- End Log | ' + $Function + ' | Runtime: ' + "$($timeTaken.Minutes) min $($timeTaken.Seconds) sec" $logEntry.Message = $Message } $script:LogString += $logEntry switch ($Severity) { 'Warning' { Write-Warning ('[WARNING] ! ' + $Message) $UserInput = Read-Host "Warning encountered! Do you want to continue? (Y/N)" if ($UserInput -eq 'N') { throw "Script execution stopped by user." } } 'Error' { Write-Error ('[ERROR] X - ' + $FuncName + ' ' + $Message) -ErrorAction Continue } 'Verbose' { Write-Verbose ('[VERBOSE] ~ ' + $Message) } Default { Write-Information ('[INFO] * ' + $Message) -InformationAction Continue} } } catch { throw "Write-AuditLog encountered an error (process block): $($_)" } } end { try { if ($End) { if (-not [string]::IsNullOrEmpty($OutputPath)) { $script:LogString | Export-Csv -Path $OutputPath -NoTypeInformation Write-Verbose "LogPath: $(Split-Path -Path $OutputPath -Parent)" } else { throw "OutputPath is not specified for End action." } } } catch { throw "Error in Write-AuditLog (end block): $($_.Exception.Message)" } } } #EndRegion '.\Private\Write-AuditLog.ps1' 213 #Region '.\Public\Export-M365SecurityAuditTable.ps1' -1 <# .SYNOPSIS Exports M365 security audit results to a CSV file or outputs a specific test result as an object. .DESCRIPTION This function exports M365 security audit results from either an array of CISAuditResult objects or a CSV file. It can export all results to a specified path or output a specific test result as an object. .PARAMETER AuditResults An array of CISAuditResult objects containing the audit results. .PARAMETER CsvPath The path to a CSV file containing the audit results. .PARAMETER OutputTestNumber The test number to output as an object. Valid values are "1.1.1", "1.3.1", "6.1.2", "6.1.3", "7.3.4". .PARAMETER ExportAllTests Switch to export all test results. .PARAMETER ExportPath The path where the CSV files will be exported. .PARAMETER ExportOriginalTests Switch to export the original audit results to a CSV file. .PARAMETER ExportToExcel Switch to export the results to an Excel file. .INPUTS [CISAuditResult[]], [string] .OUTPUTS [PSCustomObject] .EXAMPLE Export-M365SecurityAuditTable -AuditResults $object -OutputTestNumber 6.1.2 # Output object for a single test number from audit results .EXAMPLE Export-M365SecurityAuditTable -ExportAllTests -AuditResults $object -ExportPath "C:\temp" # Export all results from audit results to the specified path .EXAMPLE Export-M365SecurityAuditTable -CsvPath "C:\temp\auditresultstoday1.csv" -OutputTestNumber 6.1.2 # Output object for a single test number from CSV .EXAMPLE Export-M365SecurityAuditTable -ExportAllTests -CsvPath "C:\temp\auditresultstoday1.csv" -ExportPath "C:\temp" # Export all results from CSV to the specified path .EXAMPLE Export-M365SecurityAuditTable -ExportAllTests -AuditResults $object -ExportPath "C:\temp" -ExportOriginalTests # Export all results from audit results to the specified path along with the original tests .EXAMPLE Export-M365SecurityAuditTable -ExportAllTests -CsvPath "C:\temp\auditresultstoday1.csv" -ExportPath "C:\temp" -ExportOriginalTests # Export all results from CSV to the specified path along with the original tests .LINK https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Export-M365SecurityAuditTable #> function Export-M365SecurityAuditTable { [CmdletBinding()] [OutputType([PSCustomObject])] param ( [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "ExportAllResultsFromAuditResults")] [Parameter(Mandatory = $true, Position = 2, ParameterSetName = "OutputObjectFromAuditResultsSingle")] [CISAuditResult[]]$AuditResults, [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "ExportAllResultsFromCsv")] [Parameter(Mandatory = $true, Position = 2, ParameterSetName = "OutputObjectFromCsvSingle")] [ValidateScript({ (Test-Path $_) -and ((Get-Item $_).PSIsContainer -eq $false) })] [string]$CsvPath, [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "OutputObjectFromAuditResultsSingle")] [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "OutputObjectFromCsvSingle")] [ValidateSet("1.1.1", "1.3.1", "6.1.2", "6.1.3", "7.3.4")] [string]$OutputTestNumber, [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "ExportAllResultsFromAuditResults")] [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "ExportAllResultsFromCsv")] [switch]$ExportAllTests, [Parameter(Mandatory = $true, ParameterSetName = "ExportAllResultsFromAuditResults")] [Parameter(Mandatory = $true, ParameterSetName = "ExportAllResultsFromCsv")] [string]$ExportPath, [Parameter(Mandatory = $false, ParameterSetName = "ExportAllResultsFromAuditResults")] [Parameter(Mandatory = $false, ParameterSetName = "ExportAllResultsFromCsv")] [switch]$ExportOriginalTests, [Parameter(Mandatory = $false, ParameterSetName = "ExportAllResultsFromAuditResults")] [Parameter(Mandatory = $false, ParameterSetName = "ExportAllResultsFromCsv")] [switch]$ExportToExcel ) if ($ExportToExcel) { Assert-ModuleAvailability -ModuleName ImportExcel -RequiredVersion "7.8.9" } if ($PSCmdlet.ParameterSetName -like "ExportAllResultsFromCsv" -or $PSCmdlet.ParameterSetName -eq "OutputObjectFromCsvSingle") { $AuditResults = Import-Csv -Path $CsvPath | ForEach-Object { $params = @{ Rec = $_.Rec Result = [bool]$_.Result Status = $_.Status Details = $_.Details FailureReason = $_.FailureReason } Initialize-CISAuditResult @params } } if ($ExportAllTests) { $TestNumbers = "1.1.1", "1.3.1", "6.1.2", "6.1.3", "7.3.4" } $results = @() $testsToProcess = if ($OutputTestNumber) { @($OutputTestNumber) } else { $TestNumbers } foreach ($test in $testsToProcess) { $auditResult = $AuditResults | Where-Object { $_.Rec -eq $test } if (-not $auditResult) { Write-Information "No audit results found for the test number $test." continue } switch ($test) { "6.1.2" { $details = $auditResult.Details if ($details -ne "No M365 E3 licenses found.") { $csv = $details | ConvertFrom-Csv -Delimiter '|' } else { $csv = $null } if ($null -ne $csv) { foreach ($row in $csv) { $row.AdminActionsMissing = (Get-Action -AbbreviatedActions $row.AdminActionsMissing.Split(',') -ReverseActionType Admin | Where-Object { $_ -notin @("MailItemsAccessed", "Send") }) -join ',' $row.DelegateActionsMissing = (Get-Action -AbbreviatedActions $row.DelegateActionsMissing.Split(',') -ReverseActionType Delegate | Where-Object { $_ -notin @("MailItemsAccessed") }) -join ',' $row.OwnerActionsMissing = (Get-Action -AbbreviatedActions $row.OwnerActionsMissing.Split(',') -ReverseActionType Owner | Where-Object { $_ -notin @("MailItemsAccessed", "Send") }) -join ',' } $newObjectDetails = $csv } else { $newObjectDetails = $details } $results += [PSCustomObject]@{ TestNumber = $test; Details = $newObjectDetails } } "6.1.3" { $details = $auditResult.Details if ($details -ne "No M365 E5 licenses found.") { $csv = $details | ConvertFrom-Csv -Delimiter '|' } else { $csv = $null } if ($null -ne $csv) { foreach ($row in $csv) { $row.AdminActionsMissing = (Get-Action -AbbreviatedActions $row.AdminActionsMissing.Split(',') -ReverseActionType Admin) -join ',' $row.DelegateActionsMissing = (Get-Action -AbbreviatedActions $row.DelegateActionsMissing.Split(',') -ReverseActionType Delegate) -join ',' $row.OwnerActionsMissing = (Get-Action -AbbreviatedActions $row.OwnerActionsMissing.Split(',') -ReverseActionType Owner) -join ',' } $newObjectDetails = $csv } else { $newObjectDetails = $details } $results += [PSCustomObject]@{ TestNumber = $test; Details = $newObjectDetails } } Default { $details = $auditResult.Details $csv = $details | ConvertFrom-Csv -Delimiter '|' $results += [PSCustomObject]@{ TestNumber = $test; Details = $csv } } } } if ($ExportPath) { $timestamp = (Get-Date).ToString("yyyy.MM.dd_HH.mm.ss") $exportedTests = @() foreach ($result in $results) { $testDef = $script:TestDefinitionsObject | Where-Object { $_.Rec -eq $result.TestNumber } if ($testDef) { $fileName = "$ExportPath\$($timestamp)_$($result.TestNumber).$($testDef.TestFileName -replace '\.ps1$').csv" if ($result.Details.Count -eq 0) { Write-Information "No results found for test number $($result.TestNumber)." -InformationAction Continue } else { if (($result.Details -ne "No M365 E3 licenses found.") -and ($result.Details -ne "No M365 E5 licenses found.")) { if ($ExportToExcel) { $xlsxPath = [System.IO.Path]::ChangeExtension($fileName, '.xlsx') $result.Details | Export-Excel -Path $xlsxPath -WorksheetName Table -TableName Table -AutoSize -TableStyle Medium2 } else { $result.Details | Export-Csv -Path $fileName -NoTypeInformation } $exportedTests += $result.TestNumber } } } } if ($exportedTests.Count -gt 0) { Write-Information "The following tests were exported: $($exportedTests -join ', ')" -InformationAction Continue } else { if ($ExportOriginalTests) { Write-Information "Full audit results exported however, none of the following tests had exports: `n1.1.1, 1.3.1, 6.1.2, 6.1.3, 7.3.4" -InformationAction Continue } else { Write-Information "No specified tests were included in the export." -InformationAction Continue } } if ($ExportOriginalTests) { # Define the test numbers to check $TestNumbersToCheck = "1.1.1", "1.3.1", "6.1.2", "6.1.3", "7.3.4" if ($exportedTests.Count -gt 0) { $updatedAuditResults = Get-ExceededLengthResultDetail -AuditResults $AuditResults -TestNumbersToCheck $TestNumbersToCheck -ExportedTests $exportedTests -DetailsLengthLimit 30000 -PreviewLineCount 25 } else { $updatedAuditResults = $auditResults } $originalFileName = "$ExportPath\$timestamp`_M365FoundationsAudit.csv" if ($ExportToExcel) { $xlsxPath = [System.IO.Path]::ChangeExtension($originalFileName, '.xlsx') $updatedAuditResults | Export-Excel -Path $xlsxPath -WorksheetName Table -TableName Table -AutoSize -TableStyle Medium2 } else { $updatedAuditResults | Export-Csv -Path $originalFileName -NoTypeInformation } } } elseif ($OutputTestNumber) { if ($results[0].Details) { return $results[0].Details } else { Write-Information "No results found for test number $($OutputTestNumber)." -InformationAction Continue } } else { Write-Error "No valid operation specified. Please provide valid parameters." } } #EndRegion '.\Public\Export-M365SecurityAuditTable.ps1' 232 #Region '.\Public\Get-AdminRoleUserLicense.ps1' -1 <# .SYNOPSIS Retrieves user licenses and roles for administrative accounts from Microsoft 365 via the Graph API. .DESCRIPTION The Get-AdminRoleUserLicense function connects to Microsoft Graph and retrieves all users who are assigned administrative roles along with their user details and licenses. This function is useful for auditing and compliance checks to ensure that administrators have appropriate licenses and role assignments. .PARAMETER SkipGraphConnection A switch parameter that, when set, skips the connection to Microsoft Graph if already established. This is useful for batch processing or when used within scripts where multiple calls are made and the connection is managed externally. .EXAMPLE PS> Get-AdminRoleUserLicense This example retrieves all administrative role users along with their licenses by connecting to Microsoft Graph using the default scopes. .EXAMPLE PS> Get-AdminRoleUserLicense -SkipGraphConnection This example retrieves all administrative role users along with their licenses without attempting to connect to Microsoft Graph, assuming that the connection is already established. .INPUTS None. You cannot pipe objects to Get-AdminRoleUserLicense. .OUTPUTS PSCustomObject Returns a custom object for each user with administrative roles that includes the following properties: RoleName, UserName, UserPrincipalName, UserId, HybridUser, and Licenses. .NOTES Creation Date: 2024-04-15 Purpose/Change: Initial function development to support Microsoft 365 administrative role auditing. .LINK https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Get-AdminRoleUserLicense #> function Get-AdminRoleUserLicense { [OutputType([System.Collections.ArrayList])] [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [switch]$SkipGraphConnection ) begin { if (-not $SkipGraphConnection) { Connect-MgGraph -Scopes "Directory.Read.All", "Domain.Read.All", "Policy.Read.All", "Organization.Read.All" -NoWelcome } $adminRoleUsers = [System.Collections.ArrayList]::new() $userIds = [System.Collections.ArrayList]::new() } process { Write-Verbose "Retrieving all admin roles" $adminRoleNames = (Get-MgDirectoryRole | Where-Object { $null -ne $_.RoleTemplateId }).DisplayName Write-Verbose "Filtering admin roles" $adminRoles = Get-MgRoleManagementDirectoryRoleDefinition | Where-Object { ($adminRoleNames -contains $_.DisplayName) -and ($_.DisplayName -ne "Directory Synchronization Accounts") } foreach ($role in $adminRoles) { Write-Verbose "Processing role: $($role.DisplayName)" $roleAssignments = Get-MgRoleManagementDirectoryRoleAssignment -Filter "roleDefinitionId eq '$($role.Id)'" foreach ($assignment in $roleAssignments) { Write-Verbose "Processing role assignment for principal ID: $($assignment.PrincipalId)" $userDetails = Get-MgUser -UserId $assignment.PrincipalId -Property "DisplayName, UserPrincipalName, Id, OnPremisesSyncEnabled" -ErrorAction SilentlyContinue if ($userDetails) { Write-Verbose "Retrieved user details for: $($userDetails.UserPrincipalName)" [void]($userIds.Add($userDetails.Id)) [void]($adminRoleUsers.Add([PSCustomObject]@{ RoleName = $role.DisplayName UserName = $userDetails.DisplayName UserPrincipalName = $userDetails.UserPrincipalName UserId = $userDetails.Id HybridUser = [bool]$userDetails.OnPremisesSyncEnabled Licenses = $null # Initialize as $null })) } } } Write-Verbose "Retrieving licenses for admin role users" foreach ($userId in $userIds.ToArray() | Select-Object -Unique) { $licenses = Get-MgUserLicenseDetail -UserId $userId -ErrorAction SilentlyContinue if ($licenses) { $licenseList = ($licenses.SkuPartNumber -join '|') $adminRoleUsers.ToArray() | Where-Object { $_.UserId -eq $userId } | ForEach-Object { $_.Licenses = $licenseList } } } } end { Write-Host "Disconnecting from Microsoft Graph..." -ForegroundColor Green Disconnect-MgGraph | Out-Null return $adminRoleUsers } } #EndRegion '.\Public\Get-AdminRoleUserLicense.ps1' 92 #Region '.\Public\Get-MFAStatus.ps1' -1 <# .SYNOPSIS Retrieves the MFA (Multi-Factor Authentication) status for Azure Active Directory users. .DESCRIPTION The Get-MFAStatus function connects to Microsoft Online Service and retrieves the MFA status for all Azure Active Directory users, excluding guest accounts. Optionally, you can specify a single user by their User Principal Name (UPN) to get their MFA status. .PARAMETER UserId The User Principal Name (UPN) of a specific user to retrieve MFA status for. If not provided, the function retrieves MFA status for all users. .EXAMPLE Get-MFAStatus Retrieves the MFA status for all Azure Active Directory users. .EXAMPLE Get-MFAStatus -UserId "example@domain.com" Retrieves the MFA status for the specified user with the UPN "example@domain.com". .OUTPUTS System.Object Returns a sorted list of custom objects containing the following properties: - UserPrincipalName - DisplayName - MFAState - MFADefaultMethod - MFAPhoneNumber - PrimarySMTP - Aliases .NOTES The function requires the MSOL module to be installed and connected to your tenant. Ensure that you have the necessary permissions to read user and MFA status information. .LINK https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Get-MFAStatus #> function Get-MFAStatus { [OutputType([System.Object])] [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$UserId, [switch]$SkipMSOLConnectionChecks ) begin { # Connect to Microsoft Online service Import-Module MSOnline -ErrorAction SilentlyContinue } process { if (Get-Module MSOnline){ if (-not $SkipMSOLConnectionChecks) { Connect-MsolService } Write-Host "Finding Azure Active Directory Accounts..." # Get all users, excluding guests $Users = if ($PSBoundParameters.ContainsKey('UserId')) { Get-MsolUser -UserPrincipalName $UserId } else { Get-MsolUser -All | Where-Object { $_.UserType -ne "Guest" } } $Report = [System.Collections.Generic.List[Object]]::new() # Create output list Write-Host "Processing $($Users.Count) accounts..." ForEach ($User in $Users) { $MFADefaultMethod = ($User.StrongAuthenticationMethods | Where-Object { $_.IsDefault -eq "True" }).MethodType $MFAPhoneNumber = $User.StrongAuthenticationUserDetails.PhoneNumber $PrimarySMTP = $User.ProxyAddresses | Where-Object { $_ -clike "SMTP*" } | ForEach-Object { $_ -replace "SMTP:", "" } $Aliases = $User.ProxyAddresses | Where-Object { $_ -clike "smtp*" } | ForEach-Object { $_ -replace "smtp:", "" } If ($User.StrongAuthenticationRequirements) { $MFAState = $User.StrongAuthenticationRequirements.State } Else { $MFAState = 'Disabled' } If ($MFADefaultMethod) { Switch ($MFADefaultMethod) { "OneWaySMS" { $MFADefaultMethod = "Text code authentication phone" } "TwoWayVoiceMobile" { $MFADefaultMethod = "Call authentication phone" } "TwoWayVoiceOffice" { $MFADefaultMethod = "Call office phone" } "PhoneAppOTP" { $MFADefaultMethod = "Authenticator app or hardware token" } "PhoneAppNotification" { $MFADefaultMethod = "Microsoft authenticator app" } } } Else { $MFADefaultMethod = "Not enabled" } $ReportLine = [PSCustomObject] @{ UserPrincipalName = $User.UserPrincipalName DisplayName = $User.DisplayName MFAState = $MFAState MFADefaultMethod = $MFADefaultMethod MFAPhoneNumber = $MFAPhoneNumber PrimarySMTP = ($PrimarySMTP -join ',') Aliases = ($Aliases -join ',') isLicensed = $User.isLicensed } $Report.Add($ReportLine) } Write-Host "Processing complete." Write-Host "To disconnect from the MsolService close the powershell session or wait for the session to expire." return $Report | Select-Object UserPrincipalName, DisplayName, MFAState, MFADefaultMethod, MFAPhoneNumber, PrimarySMTP, Aliases, isLicensed | Sort-Object UserPrincipalName } else { Write-Host "You must first install MSOL using:`nInstall-Module MSOnline -Scope CurrentUser -Force" } } } #EndRegion '.\Public\Get-MFAStatus.ps1' 108 #Region '.\Public\Invoke-M365SecurityAudit.ps1' -1 <# .SYNOPSIS Invokes a security audit for Microsoft 365 environments. .DESCRIPTION The Invoke-M365SecurityAudit cmdlet performs a comprehensive security audit based on the specified parameters. It allows auditing of various configurations and settings within a Microsoft 365 environment, such as compliance with CIS benchmarks. .PARAMETER TenantAdminUrl The URL of the tenant admin. If not specified, none of the SharePoint Online tests will run. .PARAMETER M365DomainForPWPolicyTest The domain name of the Microsoft 365 environment to test. This parameter is not mandatory and by default it will pass/fail all found domains as a group if a specific domain is not specified. .PARAMETER ELevel Specifies the E-Level (E3 or E5) for the audit. This parameter is optional and can be combined with the ProfileLevel parameter. .PARAMETER ProfileLevel Specifies the profile level (L1 or L2) for the audit. This parameter is optional and can be combined with the ELevel parameter. .PARAMETER IncludeIG1 If specified, includes tests where IG1 is true. .PARAMETER IncludeIG2 If specified, includes tests where IG2 is true. .PARAMETER IncludeIG3 If specified, includes tests where IG3 is true. .PARAMETER IncludeRecommendation Specifies specific recommendations to include in the audit. Accepts an array of recommendation numbers. .PARAMETER SkipRecommendation Specifies specific recommendations to exclude from the audit. Accepts an array of recommendation numbers. .PARAMETER DoNotConnect If specified, the cmdlet will not establish a connection to Microsoft 365 services. .PARAMETER DoNotDisconnect If specified, the cmdlet will not disconnect from Microsoft 365 services after execution. .PARAMETER NoModuleCheck If specified, the cmdlet will not check for the presence of required modules. .PARAMETER DoNotConfirmConnections If specified, the cmdlet will not prompt for confirmation before proceeding with established connections and will disconnect from all of them. .EXAMPLE PS> Invoke-M365SecurityAudit Performs a security audit using default parameters. Output: Status : Fail ELevel : E3 ProfileLevel: L1 Connection : Microsoft Graph Rec : 1.1.1 Result : False Details : Non-compliant accounts: Username | Roles | HybridStatus | Missing Licence user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2 FailureReason: Non-Compliant Accounts: 2 .EXAMPLE PS> Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com" -ELevel "E5" -ProfileLevel "L1" Performs a security audit for the E5 level and L1 profile in the specified Microsoft 365 environment. Output: Status : Fail ELevel : E5 ProfileLevel: L1 Connection : Microsoft Graph Rec : 1.1.1 Result : False Details : Non-compliant accounts: Username | Roles | HybridStatus | Missing Licence user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2 FailureReason: Non-Compliant Accounts: 2 .EXAMPLE PS> Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com" -IncludeIG1 Performs an audit including all tests where IG1 is true. Output: Status : Fail ELevel : E3 ProfileLevel: L1 Connection : Microsoft Graph Rec : 1.1.1 Result : False Details : Non-compliant accounts: Username | Roles | HybridStatus | Missing Licence user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2 FailureReason: Non-Compliant Accounts: 2 .EXAMPLE PS> Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com" -SkipRecommendation '1.1.3', '2.1.1' Performs an audit while excluding specific recommendations 1.1.3 and 2.1.1. Output: Status : Fail ELevel : E3 ProfileLevel: L1 Connection : Microsoft Graph Rec : 1.1.1 Result : False Details : Non-compliant accounts: Username | Roles | HybridStatus | Missing Licence user1@domain.com| Global Administrator | Cloud-Only | AAD_PREMIUM user2@domain.com| Global Administrator | Hybrid | AAD_PREMIUM, AAD_PREMIUM_P2 FailureReason: Non-Compliant Accounts: 2 .EXAMPLE PS> $auditResults = Invoke-M365SecurityAudit -TenantAdminUrl "https://contoso-admin.sharepoint.com" -M365DomainForPWPolicyTest "contoso.com" PS> $auditResults | Export-Csv -Path "auditResults.csv" -NoTypeInformation Captures the audit results into a variable and exports them to a CSV file. Output: CISAuditResult[] auditResults.csv .EXAMPLE PS> Invoke-M365SecurityAudit -WhatIf Displays what would happen if the cmdlet is run without actually performing the audit. Output: What if: Performing the operation "Invoke-M365SecurityAudit" on target "Microsoft 365 environment". .INPUTS None. You cannot pipe objects to Invoke-M365SecurityAudit. .OUTPUTS CISAuditResult[] The cmdlet returns an array of CISAuditResult objects representing the results of the security audit. .NOTES - This module is based on CIS benchmarks. - Governed by the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. - Commercial use is not permitted. This module cannot be sold or used for commercial purposes. - Modifications and sharing are allowed under the same license. - For full license details, visit: https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en - Register for CIS Benchmarks at: https://www.cisecurity.org/cis-benchmarks .LINK https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Invoke-M365SecurityAudit #> function Invoke-M365SecurityAudit { [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'Default')] [OutputType([CISAuditResult[]])] param ( [Parameter(Mandatory = $false, HelpMessage = "The SharePoint tenant admin URL, which should end with '-admin.sharepoint.com'. If not specified none of the Sharepoint Online tests will run.")] [ValidatePattern('^https://[a-zA-Z0-9-]+-admin\.sharepoint\.com$')] [string]$TenantAdminUrl, [Parameter(Mandatory = $false, HelpMessage = "Specify this to test only the default domain for password expiration policy when '1.3.1' is included in the tests to be run. The domain name of your organization, e.g., 'example.com'.")] [ValidatePattern('^[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$')] [string]$M365DomainForPWPolicyTest, # E-Level with optional ProfileLevel selection [Parameter(Mandatory = $true, ParameterSetName = 'ELevelFilter')] [ValidateSet('E3', 'E5')] [string]$ELevel, [Parameter(Mandatory = $true, ParameterSetName = 'ELevelFilter')] [ValidateSet('L1', 'L2')] [string]$ProfileLevel, # IG Filters, one at a time [Parameter(Mandatory = $true, ParameterSetName = 'IG1Filter')] [switch]$IncludeIG1, [Parameter(Mandatory = $true, ParameterSetName = 'IG2Filter')] [switch]$IncludeIG2, [Parameter(Mandatory = $true, ParameterSetName = 'IG3Filter')] [switch]$IncludeIG3, # Inclusion of specific recommendation numbers [Parameter(Mandatory = $true, ParameterSetName = 'RecFilter')] [ValidateSet( '1.1.1', '1.1.3', '1.2.1', '1.2.2', '1.3.1', '1.3.3', '1.3.6', '2.1.1', '2.1.2', ` '2.1.3', '2.1.4', '2.1.5', '2.1.6', '2.1.7', '2.1.9', '3.1.1', '5.1.2.3', ` '5.1.8.1', '6.1.1', '6.1.2', '6.1.3', '6.2.1', '6.2.2', '6.2.3', '6.3.1', ` '6.5.1', '6.5.2', '6.5.3', '7.2.1', '7.2.10', '7.2.2', '7.2.3', '7.2.4', ` '7.2.5', '7.2.6', '7.2.7', '7.2.9', '7.3.1', '7.3.2', '7.3.4', '8.1.1', ` '8.1.2', '8.2.1', '8.5.1', '8.5.2', '8.5.3', '8.5.4', '8.5.5', '8.5.6', ` '8.5.7', '8.6.1' )] [string[]]$IncludeRecommendation, # Exclusion of specific recommendation numbers [Parameter(Mandatory = $true, ParameterSetName = 'SkipRecFilter')] [ValidateSet( '1.1.1', '1.1.3', '1.2.1', '1.2.2', '1.3.1', '1.3.3', '1.3.6', '2.1.1', '2.1.2', ` '2.1.3', '2.1.4', '2.1.5', '2.1.6', '2.1.7', '2.1.9', '3.1.1', '5.1.2.3', ` '5.1.8.1', '6.1.1', '6.1.2', '6.1.3', '6.2.1', '6.2.2', '6.2.3', '6.3.1', ` '6.5.1', '6.5.2', '6.5.3', '7.2.1', '7.2.10', '7.2.2', '7.2.3', '7.2.4', ` '7.2.5', '7.2.6', '7.2.7', '7.2.9', '7.3.1', '7.3.2', '7.3.4', '8.1.1', ` '8.1.2', '8.2.1', '8.5.1', '8.5.2', '8.5.3', '8.5.4', '8.5.5', '8.5.6', ` '8.5.7', '8.6.1' )] [string[]]$SkipRecommendation, # Common parameters for all parameter sets [switch]$DoNotConnect, [switch]$DoNotDisconnect, [switch]$NoModuleCheck, [switch]$DoNotConfirmConnections ) Begin { if ($script:MaximumFunctionCount -lt 8192) { $script:MaximumFunctionCount = 8192 } # Ensure required modules are installed $requiredModules = Get-RequiredModule -AuditFunction # Format the required modules list $requiredModulesFormatted = Format-RequiredModuleList -RequiredModules $requiredModules # Check and install required modules if necessary if (!($NoModuleCheck) -and $PSCmdlet.ShouldProcess("Check for required modules: $requiredModulesFormatted", "Check")) { Write-Host "Checking for and installing required modules..." -ForegroundColor DarkMagenta foreach ($module in $requiredModules) { Assert-ModuleAvailability -ModuleName $module.ModuleName -RequiredVersion $module.RequiredVersion -SubModules $module.SubModules } } # Load test definitions from CSV $testDefinitionsPath = Join-Path -Path $PSScriptRoot -ChildPath "helper\TestDefinitions.csv" $testDefinitions = Import-Csv -Path $testDefinitionsPath # Load the Test Definitions into the script scope for use in other functions $script:TestDefinitionsObject = $testDefinitions # Apply filters based on parameter sets $params = @{ TestDefinitions = $testDefinitions ParameterSetName = $PSCmdlet.ParameterSetName ELevel = $ELevel ProfileLevel = $ProfileLevel IncludeRecommendation = $IncludeRecommendation SkipRecommendation = $SkipRecommendation } $testDefinitions = Get-TestDefinitionsObject @params # Extract unique connections needed $requiredConnections = $testDefinitions.Connection | Sort-Object -Unique if ($requiredConnections -contains 'SPO') { if (-not $TenantAdminUrl) { $requiredConnections = $requiredConnections | Where-Object { $_ -ne 'SPO' } $testDefinitions = $testDefinitions | Where-Object { $_.Connection -ne 'SPO' } if ($null -eq $testDefinitions) { throw "No tests to run as no SharePoint Online tests are available." } } } # Determine which test files to load based on filtering $testsToLoad = $testDefinitions.TestFileName | ForEach-Object { $_ -replace '.ps1$', '' } Write-Verbose "The $(($testsToLoad).count) test/s that would be loaded based on filter criteria:" $testsToLoad | ForEach-Object { Write-Verbose " $_" } # Initialize a collection to hold failed test details $script:FailedTests = [System.Collections.ArrayList]::new() } # End Begin Process { $allAuditResults = [System.Collections.ArrayList]::new() # Initialize a collection to hold all results # Dynamically dot-source the test scripts $testsFolderPath = Join-Path -Path $PSScriptRoot -ChildPath "tests" $testFiles = Get-ChildItem -Path $testsFolderPath -Filter "Test-*.ps1" | Where-Object { $testsToLoad -contains $_.BaseName } $totalTests = $testFiles.Count $currentTestIndex = 0 # Establishing connections if required try { $actualUniqueConnections = Get-UniqueConnection -Connections $requiredConnections if (!($DoNotConnect) -and $PSCmdlet.ShouldProcess("Establish connections to Microsoft 365 services: $($actualUniqueConnections -join ', ')", "Connect")) { Write-Host "Establishing connections to Microsoft 365 services: $($actualUniqueConnections -join ', ')" -ForegroundColor DarkMagenta Connect-M365Suite -TenantAdminUrl $TenantAdminUrl -RequiredConnections $requiredConnections -SkipConfirmation:$DoNotConfirmConnections } } catch { Write-Host "Connection execution aborted: $_" -ForegroundColor Red break } try { Write-Host "A total of $($totalTests) tests were selected to run..." -ForegroundColor DarkMagenta # Import the test functions $testFiles | ForEach-Object { $currentTestIndex++ Write-Progress -Activity "Loading Test Scripts" -Status "Loading $($currentTestIndex) of $($totalTests): $($_.Name)" -PercentComplete (($currentTestIndex / $totalTests) * 100) Try { # Dot source the test function . $_.FullName } Catch { # Log the error and add the test to the failed tests collection Write-Verbose "Failed to load test function $($_.Name): $_" -Verbose $script:FailedTests.Add([PSCustomObject]@{ Test = $_.Name; Error = $_ }) } } $currentTestIndex = 0 # Execute each test function from the prepared list foreach ($testFunction in $testFiles) { $currentTestIndex++ Write-Progress -Activity "Executing Tests" -Status "Executing $($currentTestIndex) of $($totalTests): $($testFunction.Name)" -PercentComplete (($currentTestIndex / $totalTests) * 100) $functionName = $testFunction.BaseName if ($PSCmdlet.ShouldProcess($functionName, "Execute test")) { $auditResult = Invoke-TestFunction -FunctionFile $testFunction -DomainName $M365DomainForPWPolicyTest # Add the result to the collection [void]$allAuditResults.Add($auditResult) } } } catch { # Log the error and add the test to the failed tests collection Write-Verbose "Invoke-M365SecurityAudit: Failed to load test function $($_.Name): $_" -Verbose $script:FailedTests.Add([PSCustomObject]@{ Test = $_.Name; Error = $_ }) } finally { if (!($DoNotDisconnect) -and $PSCmdlet.ShouldProcess("Disconnect from Microsoft 365 services: $($actualUniqueConnections -join ', ')", "Disconnect")) { # Clean up sessions Disconnect-M365Suite -RequiredConnections $requiredConnections } } } End { if ($PSCmdlet.ShouldProcess("Measure and display audit results for $($totalTests) tests", "Measure")) { # Call the private function to calculate and display results Measure-AuditResult -AllAuditResults $allAuditResults -FailedTests $script:FailedTests # Return all collected audit results # Define the test numbers to check $TestNumbersToCheck = "1.1.1", "1.3.1", "6.1.2", "6.1.3", "7.3.4" # Check for large details in the audit results $exceedingTests = Get-ExceededLengthResultDetail -AuditResults $allAuditResults -TestNumbersToCheck $TestNumbersToCheck -ReturnExceedingTestsOnly -DetailsLengthLimit 30000 if ($exceedingTests.Count -gt 0) { Write-Information "The following tests exceeded the details length limit: $($exceedingTests -join ', ')" -InformationAction Continue Write-Host "(Assuming the results were instantiated. Ex: `$object = invoke-M365SecurityAudit) Use the following command and adjust as neccesary to view the full details of the test results:" -ForegroundColor DarkCyan Write-Host "Export-M365SecurityAuditTable -ExportAllTests -AuditResults `$object -ExportPath `"C:\temp`" -ExportOriginalTests" -ForegroundColor Green } return $allAuditResults.ToArray() | Sort-Object -Property Rec } } } #EndRegion '.\Public\Invoke-M365SecurityAudit.ps1' 329 #Region '.\Public\Remove-RowsWithEmptyCSVStatus.ps1' -1 <# .SYNOPSIS Removes rows from an Excel worksheet where the 'CSV_Status' column is empty and saves the result to a new file. .DESCRIPTION The Remove-RowsWithEmptyCSVStatus function imports data from a specified worksheet in an Excel file, checks for the presence of the 'CSV_Status' column, and filters out rows where the 'CSV_Status' column is empty. The filtered data is then exported to a new Excel file with a '-Filtered' suffix added to the original file name. .PARAMETER FilePath The path to the Excel file to be processed. .PARAMETER WorksheetName The name of the worksheet within the Excel file to be processed. .EXAMPLE PS C:\> Remove-RowsWithEmptyCSVStatus -FilePath "C:\Reports\Report.xlsx" -WorksheetName "Sheet1" This command imports data from the "Sheet1" worksheet in the "Report.xlsx" file, removes rows where the 'CSV_Status' column is empty, and saves the filtered data to a new file named "Report-Filtered.xlsx" in the same directory. .NOTES This function requires the ImportExcel module to be installed. #> function Remove-RowsWithEmptyCSVStatus { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$FilePath, [Parameter(Mandatory = $true)] [string]$WorksheetName ) # Import the Excel file $ExcelData = Import-Excel -Path $FilePath -WorksheetName $WorksheetName # Check if CSV_Status column exists if (-not $ExcelData.PSObject.Properties.Match("CSV_Status")) { throw "CSV_Status column not found in the worksheet." } # Filter rows where CSV_Status is not empty $FilteredData = $ExcelData | Where-Object { $null -ne $_.CSV_Status -and $_.CSV_Status -ne '' } # Get the original file name and directory $OriginalFileName = [System.IO.Path]::GetFileNameWithoutExtension($FilePath) $Directory = [System.IO.Path]::GetDirectoryName($FilePath) # Create a new file name for the filtered data $NewFileName = "$OriginalFileName-Filtered.xlsx" $NewFilePath = Join-Path -Path $Directory -ChildPath $NewFileName # Export the filtered data to a new Excel file $FilteredData | Export-Excel -Path $NewFilePath -WorksheetName $WorksheetName -Show Write-Output "Filtered Excel file created at $NewFilePath" } #EndRegion '.\Public\Remove-RowsWithEmptyCSVStatus.ps1' 50 #Region '.\Public\Sync-CISExcelAndCsvData.ps1' -1 <# .SYNOPSIS Synchronizes and updates data in an Excel worksheet with new information from a CSV file, including audit dates. .DESCRIPTION The Sync-CISExcelAndCsvData function merges and updates data in a specified Excel worksheet from a CSV file. This includes adding or updating fields for connection status, details, failure reasons, and the date of the update. It's designed to ensure that the Excel document maintains a running log of changes over time, ideal for tracking remediation status and audit history. .PARAMETER ExcelPath Specifies the path to the Excel file to be updated. This parameter is mandatory. .PARAMETER CsvPath Specifies the path to the CSV file containing new data. This parameter is mandatory. .PARAMETER SheetName Specifies the name of the worksheet in the Excel file where data will be merged and updated. This parameter is mandatory. .EXAMPLE PS> Sync-CISExcelAndCsvData -ExcelPath "path\to\excel.xlsx" -CsvPath "path\to\data.csv" -SheetName "AuditData" Updates the 'AuditData' worksheet in 'excel.xlsx' with data from 'data.csv', adding new information and the date of the update. .INPUTS System.String The function accepts strings for file paths and worksheet names. .OUTPUTS None The function directly updates the Excel file and does not output any objects. .NOTES - Ensure that the 'ImportExcel' module is installed and up to date to handle Excel file manipulations. - It is recommended to back up the Excel file before running this function to avoid accidental data loss. - The CSV file should have columns that match expected headers like 'Connection', 'Details', 'FailureReason', and 'Status' for correct data mapping. .LINK https://criticalsolutionsnetwork.github.io/M365FoundationsCISReport/#Sync-CISExcelAndCsvData #> function Sync-CISExcelAndCsvData { [OutputType([void])] [CmdletBinding()] param( [string]$ExcelPath, [string]$CsvPath, [string]$SheetName ) # Import the CSV file $csvData = Import-Csv -Path $CsvPath # Get the current date in the specified format $currentDate = Get-Date -Format "yyyy-MM-ddTHH:mm:ss" # Load the Excel workbook $excelPackage = Open-ExcelPackage -Path $ExcelPath $worksheet = $excelPackage.Workbook.Worksheets[$SheetName] # Define and check new headers, including the date header $lastCol = $worksheet.Dimension.End.Column $newHeaders = @("CSV_Connection", "CSV_Status", "CSV_Date", "CSV_Details", "CSV_FailureReason") $existingHeaders = $worksheet.Cells[1, 1, 1, $lastCol].Value # Add new headers if they do not exist foreach ($header in $newHeaders) { if ($header -notin $existingHeaders) { $lastCol++ $worksheet.Cells[1, $lastCol].Value = $header } } # Save changes made to add headers $excelPackage.Save() # Update the worksheet variable to include possible new columns $worksheet = $excelPackage.Workbook.Worksheets[$SheetName] # Mapping the headers to their corresponding column numbers $headerMap = @{} for ($col = 1; $col -le $worksheet.Dimension.End.Column; $col++) { $headerMap[$worksheet.Cells[1, $col].Text] = $col } # For each record in CSV, find the matching row and update/add data foreach ($row in $csvData) { # Find the matching recommendation # row $matchRow = $null for ($i = 2; $i -le $worksheet.Dimension.End.Row; $i++) { if ($worksheet.Cells[$i, $headerMap['Recommendation #']].Text -eq $row.rec) { $matchRow = $i break } } # Update values if a matching row is found if ($matchRow) { foreach ($header in $newHeaders) { if ($header -eq 'CSV_Date') { $columnIndex = $headerMap[$header] $worksheet.Cells[$matchRow, $columnIndex].Value = $currentDate } else { $csvKey = $header -replace 'CSV_', '' $columnIndex = $headerMap[$header] $worksheet.Cells[$matchRow, $columnIndex].Value = $row.$csvKey } } } } # Save the updated Excel file $excelPackage.Save() $excelPackage.Dispose() } #EndRegion '.\Public\Sync-CISExcelAndCsvData.ps1' 103 |