diff --git a/!README.md b/!README.md deleted file mode 100644 index afaf756..0000000 --- a/!README.md +++ /dev/null @@ -1,2 +0,0 @@ -# PowerShell -Collection of PowerShell Scripts that I have written and accumulated. diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a892e0b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{ps1,psd1}] +charset = utf-8-bom +indent_style = space +indent_size = 4 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..3a626c3 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..2947c36 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,10 @@ +## What changed and why? + +Describe the user-visible behavior and any command-line compatibility changes. + +## Validation + +- Run `tools/Test-Repository.ps1` with the pinned test dependencies. +- Add regression coverage for behavioral fixes using mocks or synthetic fixtures. +- For administrative changes, show a `-WhatIf` example and recovery procedure. +- Record any live validation separately; never put credentials or private reports in a PR. diff --git a/.github/workflows/powershell.yml b/.github/workflows/powershell.yml new file mode 100644 index 0000000..02f843e --- /dev/null +++ b/.github/workflows/powershell.yml @@ -0,0 +1,54 @@ +name: PowerShell validation +on: + push: + branches: [main] + pull_request: + workflow_dispatch: +permissions: + contents: read +concurrency: + group: validation-${{ github.ref }} + cancel-in-progress: true +jobs: + validate: + runs-on: windows-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + edition: [Desktop, Core] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - name: Install pinned test tools + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + if (-not (Get-PackageProvider -Name NuGet -ListAvailable -ErrorAction SilentlyContinue)) { + $null = Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope CurrentUser + } + $moduleRoot = Join-Path $env:RUNNER_TEMP modules + $null = New-Item -ItemType Directory -Path $moduleRoot -Force + Save-Module Pester -RequiredVersion 5.7.1 -Path $moduleRoot -Force -Repository PSGallery + Save-Module PSScriptAnalyzer -RequiredVersion 1.24.0 -Path $moduleRoot -Force -Repository PSGallery + "TOOLKIT_TEST_MODULES=$moduleRoot" | Out-File $env:GITHUB_ENV -Encoding utf8 -Append + $archive = Join-Path $env:RUNNER_TEMP sqlite.zip + Invoke-WebRequest https://www.sqlite.org/2026/sqlite-tools-win-x64-3540100.zip -OutFile $archive -UseBasicParsing + if ((Get-FileHash $archive -Algorithm SHA256).Hash -ne 'FB20997ADE5583A5FBF1E36DB7BC3C82C9416B3F314F16961E1572AA4E49487D') { throw 'SQLite checksum mismatch' } + $directory = Join-Path $env:RUNNER_TEMP sqlite + Expand-Archive $archive -DestinationPath $directory -Force + "TOOLKIT_TEST_SQLITE=$directory\sqlite3.exe" | Out-File $env:GITHUB_ENV -Encoding utf8 -Append + - name: Parse, analyze and run offline regression tests + shell: pwsh + env: + TOOLKIT_EDITION: ${{ matrix.edition }} + run: | + $env:PSModulePath = $env:TOOLKIT_TEST_MODULES + [IO.Path]::PathSeparator + $env:PSModulePath + if ($env:TOOLKIT_EDITION -eq 'Desktop') { + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File ./tools/Test-Repository.ps1 + } else { + & pwsh -NoProfile -File ./tools/Test-Repository.ps1 + } + if ($LASTEXITCODE -ne 0) { throw "Validation failed in $env:TOOLKIT_EDITION" } diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..531a722 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# Reports can contain personal or security-sensitive information. +*.csv +*.sqlite +*.db +TestResults*.xml +coverage.xml +.vscode/ diff --git a/AD Group Member Extractor b/AD Group Member Extractor deleted file mode 100644 index 1979459..0000000 --- a/AD Group Member Extractor +++ /dev/null @@ -1,26 +0,0 @@ -<# -.DESCRIPTION - AD Group Member Extractor -.INPUTS - $domain - Prompts for domain to search - $group - Prompts for what group you are looking for - $filename - Builds the filename based on the group that you are searching for -.OUTPUTS - Produces a list of all users in the group -.NOTES - Created John Skinner -.LINK - -#> - -Write-Host "***************************************************************" -ForegroundColor cyan -Write-Host "Welcome to your Friendly Neighborhood AD Group Member Extractor" -ForegroundColor cyan -Write-Host "***************************************************************" -ForegroundColor cyan - -$domain = read-host "What Domain do you want to look at?" -$group = read-host "What AD group do you want to extract?" -$filename = 'c:\temp\ADGroup' + $group + '.csv' - -Get-ADGroupMember -Server $domain -Identity $group | Select-Object Name,samaccountname | Export-Csv $filename -Write-Host "Export stored here --> $filename" -ForegroundColor yellow -Write-Host "Script Complete!" -ForegroundColor green diff --git a/AD GroupMember_AccountCreationDate b/AD GroupMember_AccountCreationDate deleted file mode 100644 index cbfc1d8..0000000 --- a/AD GroupMember_AccountCreationDate +++ /dev/null @@ -1,39 +0,0 @@ -<# -.DESCRIPTION - Created to review group members and account creation dates -.INPUTS - $domain - Prompts for domain to search - $group - Promptes for the group name -.OUTPUTS - Produces a list of All users in the selected group, then searches that user list for AD Creation Dates -.NOTES - Created by John Skinner -.LINK - -#> - -# PowerShell to extract members of the groups -Write-Host "***************************************************************" -ForegroundColor cyan -Write-Host "Welcome to your Friendly Neighborhood AD Group Member Extractor" -ForegroundColor cyan -Write-Host "***************************************************************" -ForegroundColor cyan - -# Group selection variables -$domain = read-host "What Domain do you want to look at?" -$group = read-host "What AD group do you want to extract?" - -Get-ADGroupMember -Server $domain -Identity $group | Select samaccountName -ExpandProperty samaccountName | Out-File c:\temp\users.txt -Write-Host "AD Group Extract complete, Searching creation date... this will take some time" -ForegroundColor yellow - -# Loop variables -$UserNamesList = get-content -path "C:\temp\users.txt" -$exportPath = "C:\temp\Users_Detailed.csv" - -# Run the magic -foreach ($name in $UserNamesList){ - -Get-ADUser -Server $domain $name -properties * | select Name,samaccountname,whenCreated | Export-CSV $ExportPath -Append -NoTypeInformation - -} - -Write-Host "Script Complete!" -ForegroundColor green -Write-Host "The export file is stored here --> $ExportPath" -ForegroundColor Cyan diff --git a/AD-PasswordNeverExpires b/AD-PasswordNeverExpires deleted file mode 100644 index a345a0f..0000000 --- a/AD-PasswordNeverExpires +++ /dev/null @@ -1,4 +0,0 @@ -# Search for the users and export report -get-aduser -filter * -properties Name, PasswordNeverExpires | where { -$_.passwordNeverExpires -eq "true" } | Select-Object DistinguishedName,Name,Enabled | -Export-csv c:\temp\pw_never_expires.csv -NoTypeInformation diff --git a/ADEnable-DisabledUsers-fromList b/ADEnable-DisabledUsers-fromList deleted file mode 100644 index 56d6e6c..0000000 --- a/ADEnable-DisabledUsers-fromList +++ /dev/null @@ -1,38 +0,0 @@ -# Created by John Skinner - -# Prompt for domain selection -$domain = Read-Host "Enter the domain name" - -# Prompt for the path to the text file containing the user list -$filePath = Read-Host "Enter the path to the text file containing the user list" - -# Read the user list from the text file -$users = Get-Content $filePath - -# Array to store user information -$userInfo = @() - -# Retrieve user information from the selected domain -foreach ($user in $users) { - $userObject = Get-ADUser -Filter {SamAccountName -eq $user} -Properties Enabled -ErrorAction SilentlyContinue - if ($userObject) { - $status = if ($userObject.Enabled) { "Enabled" } else { "Disabled" } - $userRow = [PSCustomObject]@{ - User = $userObject.Name - Enabled = $status - } - } else { - $userRow = [PSCustomObject]@{ - User = $user - Enabled = "User not found" - } - } - $userInfo += $userRow -} - -# Output user information as a table & CSV -$userInfo | Format-Table -AutoSize -$filepath = 'c:\temp\EnableORDisabledUsers' + '-' + $domain + '.csv' -$userinfo | Export-Csv -path $filePath -NoTypeInformation - -Write-Host "User information exported to $filePath" -ForegroundColor Yellow diff --git a/ADUserSearch - ForCreator b/ADUserSearch - ForCreator deleted file mode 100644 index e8bdca4..0000000 --- a/ADUserSearch - ForCreator +++ /dev/null @@ -1,21 +0,0 @@ -# Create a variable to store the username -$username = Read-Host -Prompt "Please enter the username" - -# Get the user object -$user = Get-ADUser -Filter {samaccountname -eq $username} - -# Check if the user object exists -if ($user) -{ - # Get the account creation date - $created = $user.whenCreated - # Get the creator of the account - $creator = (Get-ADUser -Filter {distinguishedName -eq $user.createdby}).name - - # Output the results - Write-Host "The user account was created on $created by $creator" -} -else -{ - Write-Host "The user does not exist" -} diff --git a/ADUsers - Last 30 days b/ADUsers - Last 30 days deleted file mode 100644 index 8135bdf..0000000 --- a/ADUsers - Last 30 days +++ /dev/null @@ -1,10 +0,0 @@ -#Set date to 30 days ago -$date = (Get-Date).AddDays(-30) - -# Get all AD users created in the last 30 days -$users = Get-ADUser -Filter {whenCreated -ge $date} -Properties whenCreated,CreatedBy - -# Output results -foreach ($user in $users) { - Write-Output "Account Name: $($user.Name) | Created By: $($user.CreatedBy) | Created On: $($user.whenCreated)" -} diff --git a/AzureAD-GraphAPI ExtensionAttributeUpdate b/AzureAD-GraphAPI ExtensionAttributeUpdate deleted file mode 100644 index 616b2a7..0000000 --- a/AzureAD-GraphAPI ExtensionAttributeUpdate +++ /dev/null @@ -1,8 +0,0 @@ -# Connect with the appropriate scope, will prompt to login, use admin creds. -Connect-MgGraph -Scopes "Directory.AccessAsUser.All" - -# Set the variable that we need changed -$params = '{ "extensionAttributes": { "extensionAttribute6": "hello" } }' - -# Update the extension attribute -Update-MgDevice -DeviceId '' -BodyParameter $params diff --git a/AzureFirewallCommands.ps1 b/AzureFirewallCommands.ps1 deleted file mode 100644 index 0d59d54..0000000 --- a/AzureFirewallCommands.ps1 +++ /dev/null @@ -1,36 +0,0 @@ -#################################################################### -## General PowerShell commands for doing things in Azure Firewall ## -#################################################################### - -#Import AZ Module and Connect to Azure -Import-Module AZ - -connect-azaccount - -#Retrieve all firewalls in a resource group -Get-AzFirewall -ResourceGroupName rgName - -#Retrieve a firewall by name -Get-AzFirewall -ResourceGroupName rgName -Name azFw - -#Retrieve a firewall and then add a application rule collection to the firewall -$azFw=Get-AzFirewall -Name "azFw" -ResourceGroupName "rgName" -$appRule = New-AzFirewallApplicationRule -Name R1 -Protocol "http:80","https:443" -TargetFqdn "*google.com", "*microsoft.com" -SourceAddress "10.0.0.0" -$appRuleCollection = New-AzFirewallApplicationRuleCollection -Name "MyAppRuleCollection" -Priority 100 -Rule $appRule -ActionType "Allow" -$azFw.AddApplicationRuleCollection($appRuleCollection) - -#Retrieve a firewall and then add a network rule collection to the firewall -$azFw=Get-AzFirewall -Name "azFw" -ResourceGroupName "rgName" -$netRule = New-AzFirewallNetworkRule -Name "all-udp-traffic" -Description "Rule for all UDP traffic" -Protocol "UDP" -SourceAddress "*" -DestinationAddress "*" -DestinationPort "*" -$netRuleCollection = New-AzFirewallNetworkRuleCollection -Name "MyNetworkRuleCollection" -Priority 100 -Rule $netRule -ActionType "Allow" -$azFw.AddNetworkRuleCollection($netRuleCollection) - -#Add a new Network collection to the firewall, without a rule -$azFw=Get-AzFirewall -Name "azFw" -ResourceGroupName "rgName" -$netRuleCollection = New-AzFirewallNetworkRuleCollection -Name "MyNetworkRuleCollection" -Priority 100 -$azFw.AddNetworkRuleCollection($netRuleCollection) - -#Add a new Application collection to the firewall, without a rule -$azFw=Get-AzFirewall -Name "azFw" -ResourceGroupName "rgName" -$appRuleCollection = New-AzFirewallApplicationRuleCollection -Name "MyAppRuleCollection" -Priority 100 -$azFw.AddApplicationRuleCollection($appRuleCollection) diff --git a/BlockLegacyAuthentication.ps1 b/BlockLegacyAuthentication.ps1 index cbb0c47..f0908d6 100644 --- a/BlockLegacyAuthentication.ps1 +++ b/BlockLegacyAuthentication.ps1 @@ -1,79 +1,72 @@ -#################################################### -## ## -## Block Legacy Authentication in Office365 ## -## Date: 09/26/21 ## -## Create by: John Skinner ## -## ## -#################################################### -<# -.SYNOPSIS - Block Basic Authentication in Office265 -.DESCRIPTION - As of Feb 2021, Microsoft has put on hold disabling legacy authentication protocols. However this disablement is still coming and therefore - we have need to design a solution to disable legacy protocols - - Note: This script will need to be run from Exchange Online Powershell, there for you must run the following command first to connect - - "Connect-ExchangeOnline" - Then Authenticate with your credentials. - - This script works by creating an authentications policy to block legacy auth. - - Block Basic Auth - Blocks all legacy authentication protocols - - Note - Exchange Active Sync is blocked at the Tenant level and is not included in this solution at this time - - The Script below uses the "New-AuthenticationPolicy" cmdlet to create the policy and name it accordingly - Once the policy is created, the "Get-AuthticationPolicy" cmdlet can be used to verify the policy and the settings - - At this point a text file of the users will need to be created. This information is in the "Inputs" section of the comments here - It is important that the text file is formatted exactly as noted in these comments. - - Once the text file is verified for all users that this policy needs to be applied to, we can then run the rest of the script - to apply the authentication policy to those users. - - The script runs a simply loop against users in the text file to apply the policy - - Reverting: - If we need to revert the script, or set the users back to the way they were configured before, We can run the last 2 lines of this script - to rest the users to the old auth policy that was originally configured. - -.INPUTS - Use a list of specific user accounts: This method requires a text file to identify the user accounts. - Values that don't contain spaces (for example, the Office 365 or Microsoft 365 work or school account) work best. - The text file must contain one user account on each line like this: - - akol@contoso.com - tjohnston@contoso.com - kakers@contoso.com - - The users variable below should point to the location of this text file -.OUTPUTS - There are no specific outputs for this script other than making the configuration changes to the users Auth Policy - -.NOTES - -.LINK - https://docs.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/disable-basic-authentication-in-exchange-online - https://docs.microsoft.com/en-us/azure/active-directory/conditional-access/block-legacy-authentication - https://docs.microsoft.com/en-us/powershell/module/exchange/new-authenticationpolicy?view=exchange-ps - https://docs.microsoft.com/en-us/powershell/module/exchange/remove-authenticationpolicy?view=exchange-ps -#> - -# Create Auth Policy to block basic authentication (Make sure this has all protocols listed) -New-AuthenticationPolicy -Name "BlockBasicAuth" -BlockLegacyAuthAutodiscover -BlockLegacyAuthImap -BlockLegacyAuthMapi -BlockLegacyAuthOfflineAddressBook -BlockLegacyAuthOutlookService -BlockLegacyAuthPop -BlockLegacyAuthRpc -BlockLegacyAuthWebServices - -# Get All authtications policies list -Get-AuthenticationPolicy | Format-Table Name -Auto - -# Verify the new authentication policy created successfully -Get-ADAuthenticationPolicy -Identity "BlockBasicAuth" - -# Set users auth policy to block basic auth -$users = Get-Content "C:\temp\users.txt" -$users | ForEach-Object {Set-User -Identity $_ -AuthenticationPolicy "BlockBasicAuth" -STSRefreshTokensValidFrom $([System.DateTime]::UtcNow)} - -# Revert the changes -# Set users auth policy to to $null, effectively removing the policy from the users assignment -$users = Get-Content "C:\temp\users.txt" -$users | ForEach-Object {Set-User -Identity $_ -AuthenticationPolicy "$null" -STSRefreshTokensValidFrom $([System.DateTime]::UtcNow)} - +<# +.SYNOPSIS +Apply an Exchange Online authentication policy or explicitly restore saved assignments. +.DESCRIPTION +Connect-ExchangeOnline first with Exchange RBAC policy/user management rights. +Apply saves previous assignments BEFORE changes. Restore is a separate invocation. +A null assignment inherits the tenant default. Changes may take time to propagate. +Authentication policies do not replace Conditional Access. +.EXAMPLE +.\BlockLegacyAuthentication.ps1 -Mode Apply -UserListPath .\users.txt -BackupPath .\before.csv -WhatIf +.EXAMPLE +.\BlockLegacyAuthentication.ps1 -Mode Restore -RestoreSavedAssignments -BackupPath .\before.csv +#> +[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'Apply')] +param( + [Parameter(Mandatory)][ValidateSet('Apply', 'Restore')][string]$Mode, + [Parameter(Mandatory, ParameterSetName = 'Apply')][string]$UserListPath, + [Parameter(Mandatory)][string]$BackupPath, + [Parameter(ParameterSetName = 'Apply')][ValidateNotNullOrEmpty()][string]$PolicyName = 'BlockBasicAuth', + [Parameter(Mandatory, ParameterSetName = 'Restore')][switch]$RestoreSavedAssignments +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +if ($Mode -eq 'Restore' -and -not $RestoreSavedAssignments) { throw 'Explicitly select -RestoreSavedAssignments.' } +if ($Mode -ne $PSCmdlet.ParameterSetName) { throw 'Apply requires -UserListPath; Restore requires -RestoreSavedAssignments.' } +$connection = @(Get-ConnectionInformation -ErrorAction Stop | Where-Object { $_.State -eq 'Connected' }) +if ($connection.Count -ne 1) { throw 'Connect exactly one Exchange Online session before running.' } +$organizationId = [string](Get-OrganizationConfig -ErrorAction Stop).Guid +if (-not $organizationId) { throw 'Unable to identify the Exchange organization.' } +if ($Mode -eq 'Apply') { + $users = @(Read-ToolkitIdentityList -Path $UserListPath | ForEach-Object { Get-User -Identity $_ -ErrorAction Stop }) + $backup = @($users | ForEach-Object { + [pscustomobject]@{ OrganizationId = $organizationId; Identity = [string]$_.UserPrincipalName; AuthenticationPolicy = [string]$_.AuthenticationPolicy } + }) + if (@($backup | Where-Object { -not $_.Identity }).Count) { throw 'A user has no UPN; no changes made.' } + $policy = @(Get-AuthenticationPolicy -ErrorAction Stop | Where-Object { $_.Name -eq $PolicyName }) + if ($policy.Count -gt 1) { throw 'Ambiguous authentication policy.' } + if ($policy.Count -eq 1) { + $flags = @($policy[0].PSObject.Properties | Where-Object { $_.Name -like 'AllowBasicAuth*' }) + if (-not $flags.Count -or @($flags | Where-Object { $_.Value -eq $true }).Count) { throw 'Existing policy does not verifiably block all Basic authentication protocols.' } + } + if ($PSCmdlet.ShouldProcess("$($users.Count) users in $organizationId", "Save $BackupPath and apply $PolicyName")) { + Export-ToolkitReport -InputObject $backup -Path $BackupPath + if (-not $policy.Count) { + # No AllowBasicAuth switches: Exchange Online blocks all protocols. + $null = New-AuthenticationPolicy -Name $PolicyName -Confirm:$false -ErrorAction Stop + } + foreach ($user in $users) { + Set-User -Identity $user.UserPrincipalName -AuthenticationPolicy $PolicyName -Confirm:$false -ErrorAction Stop + $actual = Get-User -Identity $user.UserPrincipalName -ErrorAction Stop + if (-not $actual.AuthenticationPolicy -or (Get-AuthenticationPolicy -Identity $actual.AuthenticationPolicy -ErrorAction Stop).Name -ne $PolicyName) { throw "Policy verification failed: $($user.UserPrincipalName). Backup: $BackupPath" } + [pscustomobject]@{ Identity = $user.UserPrincipalName; Status = 'Applied'; Policy = $PolicyName } + } + } +} else { + $rows = @(Import-Csv -LiteralPath $BackupPath) + if (-not $rows.Count) { throw 'Backup is empty.' } + foreach ($row in $rows) { + if (-not $row.Identity -or $row.OrganizationId -ne $organizationId -or 'AuthenticationPolicy' -notin $row.PSObject.Properties.Name) { throw 'Invalid backup or wrong organization.' } + $null = Get-User -Identity $row.Identity -ErrorAction Stop + if ($row.AuthenticationPolicy) { $null = Get-AuthenticationPolicy -Identity $row.AuthenticationPolicy -ErrorAction Stop } + } + foreach ($row in $rows) { + if ($PSCmdlet.ShouldProcess($row.Identity, 'Restore saved authentication policy')) { + $previous = if ($row.AuthenticationPolicy) { $row.AuthenticationPolicy } else { $null } + Set-User -Identity $row.Identity -AuthenticationPolicy $previous -Confirm:$false -ErrorAction Stop + $actual = Get-User -Identity $row.Identity -ErrorAction Stop + if ([string]$actual.AuthenticationPolicy -ne [string]$previous) { throw "Restore verification failed: $($row.Identity)" } + [pscustomobject]@{ Identity = $row.Identity; Status = 'Restored'; Policy = $previous } + } + } +} diff --git a/!CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md similarity index 96% rename from !CODE_OF_CONDUCT.md rename to CODE_OF_CONDUCT.md index f897e67..2088f58 100644 --- a/!CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -59,8 +59,9 @@ representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -email. +reported to the repository maintainer, SecopsEngineer, using the contact options +on their GitHub profile: https://github.com/SecopsEngineer. Do not post private +incident details in public issues. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a403483 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Contributing + +Keep each script's purpose, prerequisites, access requirements and examples in +comment-based help. Return structured objects; keep display formatting out of +report pipelines. Use explicit domain/tenant/subscription targets, terminating +errors and parameter validation. Do not add hardcoded accounts, credentials, +organization identifiers, machine addresses or paths. + +Changes to accounts and security settings must support ShouldProcess (`-WhatIf` +and confirmation), show targets, and document recovery. Do not install modules +or connect/disconnect a caller's cloud session implicitly. Avoid broad permissions +unless required by the service API and explain them when they are required. + +Run `tools/Test-Repository.ps1` using the README's pinned dependencies. Add focused +regression tests using fail-closed mocks or synthetic data. CI must never use a +production tenant or change a workstation's actual protection settings. Describe +any additional non-production integration validation and its limits in the PR. + +Preserve author/source attribution. Confirm redistribution terms before adding +third-party code. Never include real report exports, browser history or secrets. diff --git a/Copy_AD_UserGroups.ps1 b/Copy_AD_UserGroups.ps1 index 455be42..2693b9c 100644 --- a/Copy_AD_UserGroups.ps1 +++ b/Copy_AD_UserGroups.ps1 @@ -1,46 +1,40 @@ -<# -.SYNOPSIS - Simple script to produce a listing of user's group memberships - -.DESCRIPTION - Script will create a simple listing of a user's group memberships. - Output is in object format so you can use other Powershell cmdlet's - with the output, such as Export-CSV, Out-File, ConvertTo-HTML, etc. - - Groups are presented using the friendly name, and are sorted - alphabetically. - -.PARAMETER User - Name of the user you want to copy from ($copy) - Name of the user you want to copy to ($paste) - -.INPUTS - Pipeline - Get-ADUser - -.OUTPUTS - PSObject User Name - Group Name -.EXAMPLE - .\Get-UserGroupMembership.ps1 -User username - List all of the groups for "username" - -.NOTES - -#> - -# import the Active Directory module in order to be able to use get-ADuser and Add-AdGroupMember cmdlet -import-Module ActiveDirectory - -# enter login name of the first user -$copy = Read-host -Prompt 'Enter username to copy from: ' - -# enter login name of the second user -$paste = Read-host -Prompt 'Enter username to copy to: ' - -Write-host "Adding User Group Memberships..." -ForegroundColor cyan - -# copy-paste process. Get-ADuser membership | then selecting membership | and add it to the second user -get-ADuser -identity $copy -properties memberof | select-object memberof -expandproperty memberof | Add-AdGroupMember -Members $paste - -Write-host "Successfully copied AD Group Memberships from username $copy to username $paste" -ForegroundColor green \ No newline at end of file +<# +.SYNOPSIS +Copy approved direct AD group memberships, excluding protected groups by default. +.DESCRIPTION +Requires ActiveDirectory and delegated group-management rights. Does not copy the +primary group or nested memberships. Custom groups can confer privileges without +adminCount; review the preview and use -GroupIdentity as an allowlist. +.EXAMPLE +.\Copy_AD_UserGroups.ps1 -SourceUser alice -TargetUser bob -Server dc.example.com -WhatIf +#> +[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] +param( + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$SourceUser, + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$TargetUser, + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Server, + [string[]]$GroupIdentity, + [switch]$IncludePrivilegedGroups +) +$ErrorActionPreference = 'Stop' +$source = Get-ADUser -Identity $SourceUser -Server $Server -Properties memberOf -ErrorAction Stop +$target = Get-ADUser -Identity $TargetUser -Server $Server -Properties memberOf -ErrorAction Stop +if ($source.DistinguishedName -eq $target.DistinguishedName) { throw 'Source and target must differ.' } +$groups = @($source.memberOf | ForEach-Object { Get-ADGroup -Identity $_ -Server $Server -Properties adminCount, SID -ErrorAction Stop }) +if ($GroupIdentity) { + $allowed = @($GroupIdentity | ForEach-Object { (Get-ADGroup -Identity $_ -Server $Server -ErrorAction Stop).DistinguishedName }) + $groups = @($groups | Where-Object { $_.DistinguishedName -in $allowed }) +} +foreach ($group in $groups) { + $privileged = $group.adminCount -eq 1 -or [string]$group.SID -match '-(512|516|518|519|520|521|522|526|527|544|548|549|550|551|552)$' + $status = 'Preview' + if ($group.DistinguishedName -in $target.memberOf) { $status = 'AlreadyMember' } + elseif ($privileged -and -not $IncludePrivilegedGroups) { $status = 'SkippedProtectedGroup' } + elseif ($PSCmdlet.ShouldProcess("$TargetUser on $Server", "Add membership: $($group.Name)")) { + Add-ADGroupMember -Identity $group.DistinguishedName -Members $target.DistinguishedName -Server $Server -Confirm:$false -ErrorAction Stop + $verified = Get-ADUser -Identity $target.DistinguishedName -Server $Server -Properties memberOf -ErrorAction Stop + if ($group.DistinguishedName -notin $verified.memberOf) { throw "Membership verification failed: $($group.Name)" } + $status = 'Added' + } + [pscustomobject]@{ SourceUser = $SourceUser; TargetUser = $TargetUser; Group = $group.Name; Status = $status } +} diff --git a/Date_Selector.ps1 b/Date_Selector.ps1 index 9d8e0a0..1b2cca3 100644 --- a/Date_Selector.ps1 +++ b/Date_Selector.ps1 @@ -1,43 +1,37 @@ -# This script will allow you to select a date from a form -# Then this will be saved as the variable "$date" - -Add-Type -AssemblyName System.Windows.Forms -Add-Type -AssemblyName System.Drawing - -$form = New-Object Windows.Forms.Form -Property @{ - StartPosition = [Windows.Forms.FormStartPosition]::CenterScreen - Size = New-Object Drawing.Size 243, 230 - Text = 'Select a Date' - Topmost = $true -} - -$calendar = New-Object Windows.Forms.MonthCalendar -Property @{ - ShowTodayCircle = $false - MaxSelectionCount = 1 -} -$form.Controls.Add($calendar) - -$OKButton = New-Object Windows.Forms.Button -Property @{ - Location = New-Object Drawing.Point 38, 165 - Size = New-Object Drawing.Size 75, 23 - Text = 'OK' - DialogResult = [Windows.Forms.DialogResult]::OK -} -$form.AcceptButton = $OKButton -$form.Controls.Add($OKButton) - -$CancelButton = New-Object Windows.Forms.Button -Property @{ - Location = New-Object Drawing.Point 113, 165 - Size = New-Object Drawing.Size 75, 23 - Text = 'Cancel' - DialogResult = [Windows.Forms.DialogResult]::Cancel -} -$form.CancelButton = $CancelButton -$form.Controls.Add($CancelButton) - -$result = $form.ShowDialog() - -if ($result -eq [Windows.Forms.DialogResult]::OK) { - $date = $calendar.SelectionStart - Write-Host "Date selected: $($date.ToShortDateString())" -} \ No newline at end of file +<# +.SYNOPSIS +Display a Windows date picker and return the selected DateTime (nothing on cancel). +.DESCRIPTION +Requires an interactive Windows desktop and an STA PowerShell session. +.EXAMPLE +$date = .\Date_Selector.ps1 +#> +[CmdletBinding()] +param() +$ErrorActionPreference = 'Stop' +if ($env:OS -ne 'Windows_NT') { throw 'The date picker requires Windows.' } +if ([Threading.Thread]::CurrentThread.ApartmentState -ne 'STA') { throw 'Run PowerShell with -STA to use the date picker.' } +Add-Type -AssemblyName System.Windows.Forms +Add-Type -AssemblyName System.Drawing +$form = [Windows.Forms.Form]::new() +try { + $form.StartPosition = 'CenterScreen' + $form.ClientSize = [Drawing.Size]::new(250,230) + $form.Text = 'Select a Date' + $calendar = [Windows.Forms.MonthCalendar]::new() + $calendar.MaxSelectionCount = 1 + $form.Controls.Add($calendar) + $ok = [Windows.Forms.Button]::new() + $ok.Location = [Drawing.Point]::new(38,190) + $ok.Text = 'OK' + $ok.DialogResult = 'OK' + $form.Controls.Add($ok) + $form.AcceptButton = $ok + $cancel = [Windows.Forms.Button]::new() + $cancel.Location = [Drawing.Point]::new(133,190) + $cancel.Text = 'Cancel' + $cancel.DialogResult = 'Cancel' + $form.Controls.Add($cancel) + $form.CancelButton = $cancel + if ($form.ShowDialog() -eq 'OK') { $calendar.SelectionStart } +} finally { $form.Dispose() } diff --git a/DefenderToolkit b/DefenderToolkit deleted file mode 100644 index 0994c3d..0000000 --- a/DefenderToolkit +++ /dev/null @@ -1,122 +0,0 @@ -# DefenderToolkit.ps1 - -function Show-Banner { - Clear-Host - Write-Host "" - Write-Host "======================================================" -ForegroundColor Cyan - Write-Host " DEFENDER TOOLKIT" -ForegroundColor Green - Write-Host " Manage Microsoft Defender with PowerShell" -ForegroundColor DarkGray - Write-Host " Run Powershell as administrator" -ForegroundColor Cyan - Write-Host "======================================================" -ForegroundColor Cyan - Write-Host "" -} - -function Pause-And-Return { - Write-Host "" - Read-Host "Press Enter to return to the menu" -} - -function Show-Menu { - Show-Banner - Write-Host " [1] Get Defender Status" -ForegroundColor Yellow - Write-Host " [2] Update Definitions" -ForegroundColor Yellow - Write-Host " [3] Quick Scan" -ForegroundColor Yellow - Write-Host " [4] Full Scan" -ForegroundColor Yellow - Write-Host " [5] Custom Scan" -ForegroundColor Yellow - Write-Host " [6] Show Threat Detections" -ForegroundColor Yellow - Write-Host " [7] Remove Detected Threats" -ForegroundColor Yellow - Write-Host " [8] View Defender Preferences" -ForegroundColor Yellow - Write-Host " [9] Add Folder Exclusion" -ForegroundColor Yellow - Write-Host " [10] Disable Real-Time Protection" -ForegroundColor Yellow - Write-Host " [11] Enable Real-Time Protection" -ForegroundColor Yellow - Write-Host " [12] Enable Passive Mode (Registry)" -ForegroundColor Yellow - Write-Host " [13] Exit" -ForegroundColor Red - Write-Host "" -} - -do { - Show-Menu - $choice = Read-Host "Enter your choice (1-13)" - - switch ($choice) { - '1' { - Get-MpComputerStatus - Pause-And-Return - } - '2' { - Update-MpSignature - Write-Host "`nDefinitions updated." -ForegroundColor Green - Pause-And-Return - } - '3' { - Start-MpScan -ScanType QuickScan - Write-Host "`nQuick scan started." -ForegroundColor Green - Pause-And-Return - } - '4' { - Start-MpScan -ScanType FullScan - Write-Host "`nFull scan started." -ForegroundColor Green - Pause-And-Return - } - '5' { - $path = Read-Host "Enter the folder path to scan" - if (Test-Path $path) { - Start-MpScan -ScanType CustomScan -ScanPath $path - Write-Host "`nCustom scan started." -ForegroundColor Green - } else { - Write-Host "`nPath not found." -ForegroundColor Red - } - Pause-And-Return - } - '6' { - Get-MpThreatDetection - Pause-And-Return - } - '7' { - Remove-MpThreat - Write-Host "`nThreats removed (if any)." -ForegroundColor Green - Pause-And-Return - } - '8' { - Get-MpPreference - Pause-And-Return - } - '9' { - $excl = Read-Host "Enter the full path to exclude" - if (Test-Path $excl) { - Add-MpPreference -ExclusionPath $excl - Write-Host "`nExclusion added." -ForegroundColor Green - } else { - Write-Host "`nPath not found." -ForegroundColor Red - } - Pause-And-Return - } - '10' { - Set-MpPreference -DisableRealtimeMonitoring $true - Write-Host "`nReal-time protection disabled (temporary)." -ForegroundColor Red - Pause-And-Return - } - '11' { - Set-MpPreference -DisableRealtimeMonitoring $false - Write-Host "`nReal-time protection enabled." -ForegroundColor Green - Pause-And-Return - } - '12' { - try { - New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" -Force | Out-Null - Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" -Name "PassiveMode" -Value 1 -Type DWord - Write-Host "`nPassive Mode enabled in registry. A reboot is required." -ForegroundColor Cyan - } catch { - Write-Host "`nFailed to write to registry. Are you running as Administrator?" -ForegroundColor Red - } - Pause-And-Return - } - '13' { - Write-Host "`nExiting... Stay safe out there!" -ForegroundColor Magenta - } - default { - Write-Host "`nInvalid selection. Try again." -ForegroundColor Red - Pause-And-Return - } - } -} while ($choice -ne '13') diff --git a/DefenderToolkit.ps1 b/DefenderToolkit.ps1 new file mode 100644 index 0000000..9f0e9d4 --- /dev/null +++ b/DefenderToolkit.ps1 @@ -0,0 +1,60 @@ +<# +.SYNOPSIS +Run a specific Microsoft Defender operation. Defaults to status only. +.DESCRIPTION +Windows with the Defender module. Mutating actions require elevation. Reducing +protection requires -AllowProtectionReduction and confirmation. Tamper protection +and central policy may reject settings; verify actual state. Passive-mode registry +editing is intentionally omitted: configure supported policy for the target OS. +.EXAMPLE +.\DefenderToolkit.ps1 -Action AddExclusion -Path C:\TrustedBuild -AllowProtectionReduction -WhatIf +#> +[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] +param( + [ValidateSet('Status','Preferences','Detections','Update','QuickScan','FullScan','CustomScan','RemoveThreats','AddExclusion','RemoveExclusion','DisableRealtime','EnableRealtime')] + [string]$Action = 'Status', + [string]$Path, + [switch]$AllowProtectionReduction +) +$ErrorActionPreference = 'Stop' +if ($env:OS -ne 'Windows_NT') { throw 'Microsoft Defender operations require Windows.' } +switch ($Action) { + 'Status' { Get-MpComputerStatus -ErrorAction Stop; return } + 'Preferences' { Get-MpPreference -ErrorAction Stop; return } + 'Detections' { Get-MpThreatDetection -ErrorAction Stop; return } +} +$principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()) +if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Open an elevated PowerShell session.' } +if ($Action -in 'AddExclusion','DisableRealtime' -and -not $AllowProtectionReduction) { throw 'This action reduces protection. Supply -AllowProtectionReduction after reviewing the risk.' } +if ($Action -in 'CustomScan','AddExclusion') { + if (-not $Path -or -not (Test-Path -LiteralPath $Path -PathType Container)) { throw 'Supply an existing folder with -Path.' } + $Path = (Resolve-Path -LiteralPath $Path).ProviderPath + if ($Action -eq 'AddExclusion' -and $Path.TrimEnd('\') -eq [IO.Path]::GetPathRoot($Path).TrimEnd('\')) { throw 'Excluding a drive root is not supported.' } +} +if ($Action -eq 'RemoveExclusion' -and -not $Path) { throw 'Supply the exact exclusion path to remove.' } +if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "$Action $Path")) { + switch ($Action) { + 'Update' { Update-MpSignature -ErrorAction Stop } + 'QuickScan' { Start-MpScan -ScanType QuickScan -ErrorAction Stop } + 'FullScan' { Start-MpScan -ScanType FullScan -ErrorAction Stop } + 'CustomScan' { Start-MpScan -ScanType CustomScan -ScanPath $Path -ErrorAction Stop } + 'RemoveThreats' { Remove-MpThreat -ErrorAction Stop } + 'AddExclusion' { + Add-MpPreference -ExclusionPath $Path -ErrorAction Stop + if ($Path -notin (Get-MpPreference -ErrorAction Stop).ExclusionPath) { throw 'Exclusion was not applied.' } + } + 'RemoveExclusion' { + Remove-MpPreference -ExclusionPath $Path -ErrorAction Stop + if ($Path -in (Get-MpPreference -ErrorAction Stop).ExclusionPath) { throw 'Exclusion is still present.' } + } + 'DisableRealtime' { + Set-MpPreference -DisableRealtimeMonitoring $true -ErrorAction Stop + if ((Get-MpComputerStatus -ErrorAction Stop).RealTimeProtectionEnabled) { throw 'Real-time protection remains enabled; check managed policy and tamper protection.' } + } + 'EnableRealtime' { + Set-MpPreference -DisableRealtimeMonitoring $false -ErrorAction Stop + if (-not (Get-MpComputerStatus -ErrorAction Stop).RealTimeProtectionEnabled) { throw 'Real-time protection is not active; check managed policy and Defender mode.' } + } + } + Get-MpComputerStatus -ErrorAction Stop +} diff --git a/Export-0365 Blocked Senders and Domains b/Export-0365 Blocked Senders and Domains deleted file mode 100644 index dacf21a..0000000 --- a/Export-0365 Blocked Senders and Domains +++ /dev/null @@ -1,29 +0,0 @@ -<# -.DESCRIPTION - Export O365 blocked domains and blocked senders -.Inputs - Date Variable - Adds the date to the filename - Filename variables - Adds the date to the filename -.OUTPUTS - Produces a list of blocked domains and senders from O365 -.NOTES - Created by John Skinner -.LINK - -#> - -# Connect to Exchange Online -Connect-ExchangeOnline - -#Set the save file -$GetDate = (Get-date -UFormat %m-%d-%y) -$Filename1 = 'c:\temp\BlockedDomains_' + $GetDate + '.csv' -$Filename2 = 'c:\temp\BlockedSenders_' + $GetDate + '.csv' - -# Grab blocked domains -(Get-HostedContentFilterPolicy -Identity “Default” | select BlockedSenderDomains).BlockedSenderDomains | Export-Csv $Filename1 - -# Grab blocked senders -(Get-HostedContentFilterPolicy -Identity “Default” | select BlockedSenders).BlockedSenders | Export-Csv $Filename2 - -Write-Host "Script Complete" -ForegroundColor Green diff --git a/Export-ADGroupMemberCreationDates.ps1 b/Export-ADGroupMemberCreationDates.ps1 new file mode 100644 index 0000000..02affc4 --- /dev/null +++ b/Export-ADGroupMemberCreationDates.ps1 @@ -0,0 +1,17 @@ +<# +.SYNOPSIS +Report creation dates of user members of an AD group; other object types are excluded. +.EXAMPLE +.\Export-ADGroupMemberCreationDates.ps1 -Server dc.example.com -Group Finance -OutputPath .\created.csv +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [Parameter(Mandatory)][string]$Group, [switch]$Recursive, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$rows = @(Get-ADGroupMember -Identity $Group -Server $Server -Recursive:$Recursive -ErrorAction Stop | + Where-Object { $_.ObjectClass -eq 'user' } | ForEach-Object { + Get-ADUser -Identity $_.DistinguishedName -Server $Server -Properties whenCreated -ErrorAction Stop | + Select-Object Name, SamAccountName, DistinguishedName, whenCreated + }) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Export-ADGroupMembers.ps1 b/Export-ADGroupMembers.ps1 new file mode 100644 index 0000000..3920c7e --- /dev/null +++ b/Export-ADGroupMembers.ps1 @@ -0,0 +1,14 @@ +<# +.SYNOPSIS +Export direct or recursive AD group members, preserving user/group/computer type. +.EXAMPLE +.\Export-ADGroupMembers.ps1 -Server dc.example.com -Group Finance -Recursive -OutputPath .\members.csv +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [Parameter(Mandatory)][string]$Group, [switch]$Recursive, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$rows = @(Get-ADGroupMember -Identity $Group -Server $Server -Recursive:$Recursive -ErrorAction Stop | + Select-Object Name, SamAccountName, ObjectClass, DistinguishedName, SID) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Export-GraphDevices.ps1 b/Export-GraphDevices.ps1 new file mode 100644 index 0000000..a9a30b2 --- /dev/null +++ b/Export-GraphDevices.ps1 @@ -0,0 +1,30 @@ +<# +.SYNOPSIS +Report Graph directory devices with optional OS and display-name prefix filters. +.DESCRIPTION +Connect-MgGraph first with Device.Read.All. IsCompliant is the directory's nullable +compliance flag, not a full Intune compliance assessment. No data is exported unless +-OutputPath is supplied. This is the shared implementation for the Graph device reports. +.EXAMPLE +.\Export-GraphDevices.ps1 -TenantId TENANT-GUID -OperatingSystem Windows -OutputPath .\devices.csv +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$TenantId, + [string]$OperatingSystem, + [string]$DisplayNamePrefix, + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +Assert-ToolkitGraphContext -TenantId $TenantId +$properties = 'id','deviceId','displayName','operatingSystem','operatingSystemVersion','onPremisesLastSyncDateTime','isCompliant','isManaged','accountEnabled' +$query = @{ All = $true; Property = $properties } +$filters = @() +if ($OperatingSystem) { $filters += "operatingSystem eq '$($OperatingSystem.Replace("'", "''"))'" } +if ($DisplayNamePrefix) { $filters += "startsWith(displayName,'$($DisplayNamePrefix.Replace("'", "''"))')" } +if ($filters.Count) { $query.Filter = $filters -join ' and ' } +$rows = @(Get-MgDevice @query -ErrorAction Stop | Select-Object $properties) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Export-O365BlockedSendersAndDomains.ps1 b/Export-O365BlockedSendersAndDomains.ps1 new file mode 100644 index 0000000..3adbc90 --- /dev/null +++ b/Export-O365BlockedSendersAndDomains.ps1 @@ -0,0 +1,20 @@ +<# +.SYNOPSIS +Report blocked senders/domains from a selected Exchange Online anti-spam policy. +.DESCRIPTION +Connect-ExchangeOnline first with RBAC to read hosted content filter policies. +Produces a single CSV with Policy, Type and Value columns; does not change policy. +.EXAMPLE +.\Export-O365BlockedSendersAndDomains.ps1 -PolicyName Default -OutputPath .\blocked.csv +#> +[CmdletBinding()] +param([string]$PolicyName = 'Default', [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$policy = Get-HostedContentFilterPolicy -Identity $PolicyName -ErrorAction Stop +$rows = @( + foreach ($domain in $policy.BlockedSenderDomains) { [pscustomobject]@{ Policy = $policy.Name; Type = 'Domain'; Value = [string]$domain } } + foreach ($blockedSender in $policy.BlockedSenders) { [pscustomobject]@{ Policy = $policy.Name; Type = 'Sender'; Value = [string]$blockedSender } } +) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Export-O365MailboxHolds.ps1 b/Export-O365MailboxHolds.ps1 new file mode 100644 index 0000000..f0d6af8 --- /dev/null +++ b/Export-O365MailboxHolds.ps1 @@ -0,0 +1,55 @@ +<# +.SYNOPSIS +Report Exchange Online mailbox hold flags without changing hold configuration. +.DESCRIPTION +Connect-ExchangeOnline first with mailbox read RBAC. Unattended runs should use +certificate or managed-identity authentication supported by that module. This script +does not accept passwords, install modules, open UI, or disconnect caller sessions. +RetentionHoldEnabled pauses MRM processing; it is NOT an evidence-preservation hold. +This report does not resolve organization-wide retention/eDiscovery policy coverage. +The previous version was credited to O365Reports Team: +https://o365reports.com/2021/06/29/export-office-365-mailbox-holds-report-using-powershell/ +This replacement retains provenance; see THIRD_PARTY.md. +.EXAMPLE +.\Export-O365MailboxHolds.ps1 -HoldType All -OutputPath .\holds.csv +#> +[CmdletBinding()] +param( + [ValidateSet('All','Litigation','InPlace','RetentionPause')][string]$HoldType = 'All', + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +if (-not @(Get-ConnectionInformation -ErrorAction Stop | Where-Object { $_.State -eq 'Connected' }).Count) { throw 'Connect-ExchangeOnline first.' } +$rows = @(foreach ($mailbox in (Get-Mailbox -IncludeInactiveMailbox -ResultSize Unlimited -ErrorAction Stop)) { + $inPlace = @($mailbox.InPlaceHolds | Where-Object { $_ }) + $include = switch ($HoldType) { + 'Litigation' { $mailbox.LitigationHoldEnabled -eq $true } + 'InPlace' { $inPlace.Count -gt 0 } + 'RetentionPause' { $mailbox.RetentionHoldEnabled -eq $true } + 'All' { $mailbox.LitigationHoldEnabled -eq $true -or $inPlace.Count -gt 0 -or $mailbox.RetentionHoldEnabled -eq $true -or $mailbox.ComplianceTagHoldApplied -eq $true } + } + if ($include) { + [pscustomobject]@{ + MailboxName = $mailbox.Name + UPN = $mailbox.UserPrincipalName + ExchangeGuid = $mailbox.ExchangeGuid + RecipientTypeDetails = $mailbox.RecipientTypeDetails + IsInactiveMailbox = $mailbox.IsInactiveMailbox + LitigationHoldEnabled = $mailbox.LitigationHoldEnabled + LitigationHoldOwner = $mailbox.LitigationHoldOwner + LitigationHoldDate = $mailbox.LitigationHoldDate + LitigationHoldDuration = [string]$mailbox.LitigationHoldDuration + InPlaceHoldIdentifiers = $inPlace -join ';' + InPlaceHoldIdentifierCount = $inPlace.Count + RetentionProcessingPaused = $mailbox.RetentionHoldEnabled + RetentionPauseStart = $mailbox.StartDateForRetentionHold + RetentionPauseEnd = $mailbox.EndDateForRetentionHold + RetentionPolicy = $mailbox.RetentionPolicy + ComplianceTagHoldApplied = $mailbox.ComplianceTagHoldApplied + } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/ExportNSG_All_BySubscription.ps1 b/ExportNSG_All_BySubscription.ps1 index 20f66d9..81999a5 100644 --- a/ExportNSG_All_BySubscription.ps1 +++ b/ExportNSG_All_BySubscription.ps1 @@ -1,89 +1,60 @@ -############################################################################################## -## This script was created in response to a need to export all NSG details for Audit ## -## ## -## ## -## Created by John Skinner ## -############################################################################################## - -<# -.Synopsis - Export NSG's to CSV Files for Audit Review - -.DESCRIPTION - This script will login to Azure and pull the NSGs from all Subscriptions, exporting them to CSV's - -.INPUTS - Inputs from this script are as follows - - .NSG details from Azure - -.OUTPUTS - Outputs from this script are as follows - - .Individual CSV files for each NSG - .This CSV is formatted to show all the inbound and outbound rules - -.NOTES - This script could also be used to backup NSG's to CSV, if new Subscriptions are added, - the #sub_names variable will need to be modified belo - -.ROLE - The role this cmdlet belongs to Secops - -.REVISION - June 25, 2020 - Initial Script creation and testing - -#> - -Import-Module AZ - -#Connect-AzureRmAccount <---- OLD Command -connect-azaccount -$exportPath = 'UNC Path to a server location (e.g. \\server\folder)' - -#get all subscriptions -$sub_names = "subscriptionname1","subscriptionname2","subscriptionname3","subscriptionname4" -$subs = get-azsubscription | where {$sub_Names -contains $_.name} - -#new array to hold results -$nsgs = new-object system.collections.arraylist - -#cycle through each Subscription -foreach ($subscription in $subs){ - write-host "Working on the"$subscription.name "Subscription.." -ForegroundColor cyan - Select-AzSubscription $subscription - - #$nsgs = Get-AzureRmNetworkSecurityGroup <---- OLD Command (using new "Get-AzNetworkSecurityGroup") - $Temp_nsgs = Get-AzNetworkSecurityGroup - foreach ($nsg in $Temp_nsgs) {$nsgs.Add($nsg)|out-null} - } - -write-host "Found"$nsgs.count "NSG's..." -ForegroundColor cyan - -Foreach ($nsg in $nsgs) { - $nsgRules = $nsg.SecurityRules + $nsg.DefaultSecurityRules - $nsgrules = $nsgRules |Sort-Object direction,Priority - - foreach ($nsgRule in $nsgRules) { - [string]$source_address = $nsgrule.SourceAddressPrefix - [string]$source_port = $nsgrule.SourcePortRange - [string]$dest_address = $nsgrule.DestinationAddressPrefix - [string]$destport = $nsgrule.DestinationPortRange - $NSG_Obj = [PSCustomObject]@{ - "NSG Name" = $nsg.Name - "NSG location" = $nsg.Location - "NSG Resource Group" = $nsg.ResourceGroupName - "Rule Name" = $nsgrule.Name - "Rule Description" = $nsgrule.Description - "Rule Priority" = $nsgrule.Priority - "Rule Source Address" = $source_address - "Rule Source Port Range" = $source_port - "Rule Destination Address" = $dest_address - "Rule Destination Port Range" = $destport - "Rule Protocol" = $nsgrule.Protocol - "Rule Access" = $nsgrule.Access - "Rule Direction" = $nsgrule.Direction - } - $NSG_Obj | Export-Csv "$exportPath\all_rules.csv" -NoTypeInformation -Encoding ASCII -Append - } #end rule -} #end NSG \ No newline at end of file +<# +.SYNOPSIS +Export NSG rules for explicitly selected subscriptions in one tenant. +.DESCRIPTION +Connect-AzAccount first. Requires Reader access. Includes default rules, plural +address/port fields, ASGs and subscription/resource identity. Temporarily switches the +active Azure context and restores it in finally. The CSV is an audit report, not a restorable NSG backup. +.EXAMPLE +.\ExportNSG_All_BySubscription.ps1 -TenantId TENANT-GUID -SubscriptionId SUB-GUID -OutputPath .\rules.csv +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$TenantId, + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string[]]$SubscriptionId, + [Parameter(Mandatory)][string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$initialContext = Get-AzContext -ErrorAction Stop +if (-not $initialContext -or $initialContext.Tenant.Id -ne $TenantId) { throw 'Connect-AzAccount to the requested tenant first.' } +$subscriptions = @(Get-AzSubscription -TenantId $TenantId -ErrorAction Stop | Where-Object { $_.Id -in $SubscriptionId }) +foreach ($id in $SubscriptionId) { + if ($id -notin $subscriptions.Id) { throw "Subscription not accessible in tenant: $id" } +} +$rows = @(foreach ($subscription in $subscriptions) { + # Select each subscription explicitly and restore the caller context even if collection fails. + try { + $context = Set-AzContext -SubscriptionId $subscription.Id -Tenant $TenantId -Scope Process -ErrorAction Stop + foreach ($nsg in (Get-AzNetworkSecurityGroup -DefaultProfile $context -ErrorAction Stop)) { + foreach ($rule in (@($nsg.SecurityRules) + @($nsg.DefaultSecurityRules) | Where-Object { $null -ne $_ } | Sort-Object Direction, Priority)) { + [pscustomobject]@{ + SubscriptionId = $subscription.Id + SubscriptionName = $subscription.Name + ResourceId = $nsg.Id + NSGName = $nsg.Name + ResourceGroup = $nsg.ResourceGroupName + Location = $nsg.Location + RuleName = $rule.Name + Description = $rule.Description + Priority = $rule.Priority + Direction = $rule.Direction + Access = $rule.Access + Protocol = $rule.Protocol + SourceAddresses = (@($rule.SourceAddressPrefix) + @($rule.SourceAddressPrefixes) | Where-Object { $_ }) -join ';' + SourcePorts = (@($rule.SourcePortRange) + @($rule.SourcePortRanges) | Where-Object { $_ }) -join ';' + DestinationAddresses = (@($rule.DestinationAddressPrefix) + @($rule.DestinationAddressPrefixes) | Where-Object { $_ }) -join ';' + DestinationPorts = (@($rule.DestinationPortRange) + @($rule.DestinationPortRanges) | Where-Object { $_ }) -join ';' + SourceApplicationSecurityGroups = @($rule.SourceApplicationSecurityGroups | ForEach-Object { $_.Id }) -join ';' + DestinationApplicationSecurityGroups = @($rule.DestinationApplicationSecurityGroups | ForEach-Object { $_.Id }) -join ';' + IsDefault = $rule.Name -in @($nsg.DefaultSecurityRules | ForEach-Object { $_.Name }) + } + } + } + } finally { + $null = Set-AzContext -Context $initialContext -Scope Process -ErrorAction Stop + } +}) +Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force +$rows diff --git a/Find-GraphDevice.ps1 b/Find-GraphDevice.ps1 new file mode 100644 index 0000000..cc82b3a --- /dev/null +++ b/Find-GraphDevice.ps1 @@ -0,0 +1,9 @@ +<# +.SYNOPSIS +Find directory devices by display-name prefix, returning every matching page. +.EXAMPLE +.\Find-GraphDevice.ps1 -TenantId TENANT-GUID -DisplayNamePrefix Android +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$TenantId, [Parameter(Mandatory)][string]$DisplayNamePrefix, [string]$OutputPath, [switch]$Force) +& "$PSScriptRoot/Export-GraphDevices.ps1" @PSBoundParameters diff --git a/Get-ADExpiredAccounts.ps1 b/Get-ADExpiredAccounts.ps1 new file mode 100644 index 0000000..5398606 --- /dev/null +++ b/Get-ADExpiredAccounts.ps1 @@ -0,0 +1,22 @@ +<# +.SYNOPSIS +Report enabled AD accounts whose expiration date has passed. +.DESCRIPTION +The original script did not filter expired accounts. Use -WithoutExpiration to +report enabled accounts with no expiration date instead, as its old help described. +.EXAMPLE +.\Get-ADExpiredAccounts.ps1 -Server dc.example.com +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [pscredential]$Credential, [switch]$WithoutExpiration, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$query = @{ Server = $Server; Filter = 'Enabled -eq $true'; Properties = 'AccountExpirationDate' } +if ($Credential) { $query.Credential = $Credential } +$now = Get-Date +$rows = @(Get-ADUser @query -ErrorAction Stop | Where-Object { + if ($WithoutExpiration) { $null -eq $_.AccountExpirationDate } + else { $null -ne $_.AccountExpirationDate -and $_.AccountExpirationDate -lt $now } +} | Select-Object Name, SamAccountName, DistinguishedName, AccountExpirationDate) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-ADExpired_Accounts b/Get-ADExpired_Accounts deleted file mode 100644 index 00b607e..0000000 --- a/Get-ADExpired_Accounts +++ /dev/null @@ -1,19 +0,0 @@ -<# -.DESCRIPTION - Created for the monthly AD Expired Accounts -.INPUTS - $cred - Prompts for a credential to access AD - $domain - Prompts for domain to search -.OUTPUTS - Produces a list of Enabled AD user accounts that are do not have an expiry date -.NOTES - Created by John Skinner -.LINK - -#> -$cred = Get-Credential -$domain = Read-Host "What domain would you like to search? " - -#Get-ADUser -Filter * -Server $domain -Credential $cred -Properties AccountExpirationDate | Where-Object {($_.Enabled -eq $True) -and ($_.AccountExpirationDate -eq $null)} | Select-Object name, sAMAccountName, AccountExpirationDate - -Get-ADUser -Filter 'enabled -eq $true' -Properties AccountExpirationDate | Select-Object Name, sAMAccountName, distinguishedName, AccountExpirationDate diff --git a/Get-ADMissingPhoneNumbers b/Get-ADMissingPhoneNumbers deleted file mode 100644 index 8dd812f..0000000 --- a/Get-ADMissingPhoneNumbers +++ /dev/null @@ -1,5 +0,0 @@ -# Search AD for missing phone numbers -$cred = Get-Credential -$domain = Read-Host "What domain would you like to search? " - -Get-ADUser -Filter * -Server $domain -properties telephoneNumber,MobilePhone,HomePhone | Where-Object {($_.Enabled -eq $True) -and ($_.telephoneNumber -eq $null) -and ($_.MobilePhone -eq $null) -and ($_.HomePhone -eq $null)} |Select-Object Name,telephoneNumber,MobilePhone,HomePhone diff --git a/Get-ADMissingPhoneNumbers.ps1 b/Get-ADMissingPhoneNumbers.ps1 new file mode 100644 index 0000000..3140d6b --- /dev/null +++ b/Get-ADMissingPhoneNumbers.ps1 @@ -0,0 +1,17 @@ +<# +.SYNOPSIS +Report enabled AD users with no telephone, mobile, or home phone value. +.EXAMPLE +.\Get-ADMissingPhoneNumbers.ps1 -Server dc.example.com -Credential (Get-Credential) +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [pscredential]$Credential, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$query = @{ Server = $Server; Filter = 'Enabled -eq $true'; Properties = 'telephoneNumber','MobilePhone','HomePhone' } +if ($Credential) { $query.Credential = $Credential } +$rows = @(Get-ADUser @query -ErrorAction Stop | Where-Object { + [string]::IsNullOrWhiteSpace($_.telephoneNumber) -and [string]::IsNullOrWhiteSpace($_.MobilePhone) -and [string]::IsNullOrWhiteSpace($_.HomePhone) +} | Select-Object Name, SamAccountName, telephoneNumber, MobilePhone, HomePhone) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-ADPasswordNeverExpires.ps1 b/Get-ADPasswordNeverExpires.ps1 new file mode 100644 index 0000000..9b11450 --- /dev/null +++ b/Get-ADPasswordNeverExpires.ps1 @@ -0,0 +1,14 @@ +<# +.SYNOPSIS +Report AD users configured with non-expiring passwords. +.EXAMPLE +.\Get-ADPasswordNeverExpires.ps1 -Server dc.example.com -OutputPath .\passwords.csv +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$rows = @(Get-ADUser -Server $Server -Filter 'PasswordNeverExpires -eq $true' -Properties PasswordNeverExpires -ErrorAction Stop | + Select-Object Name, SamAccountName, DistinguishedName, Enabled, PasswordNeverExpires) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-ADRecentlyCreatedUsers.ps1 b/Get-ADRecentlyCreatedUsers.ps1 new file mode 100644 index 0000000..8b28c35 --- /dev/null +++ b/Get-ADRecentlyCreatedUsers.ps1 @@ -0,0 +1,18 @@ +<# +.SYNOPSIS +Report AD users created within a configurable number of days (default 30). +.DESCRIPTION +Creator attribution requires retained DC security audit event 4720. It is not a +standard CreatedBy user property; use Get-ADUserCreationAudit.ps1 for that evidence. +.EXAMPLE +.\Get-ADRecentlyCreatedUsers.ps1 -Server dc.example.com -Days 30 +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [ValidateRange(1,36500)][int]$Days = 30, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$since = (Get-Date).AddDays(-$Days) +$rows = @(Get-ADUser -Server $Server -Filter { whenCreated -ge $since } -Properties whenCreated -ErrorAction Stop | + Select-Object Name, SamAccountName, DistinguishedName, whenCreated) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-ADUserCreationAudit.ps1 b/Get-ADUserCreationAudit.ps1 new file mode 100644 index 0000000..9d61960 --- /dev/null +++ b/Get-ADUserCreationAudit.ps1 @@ -0,0 +1,45 @@ +<# +.SYNOPSIS +Find retained DC event 4720 evidence for an AD user's creation, matching the target SID. +.DESCRIPTION +Requires ActiveDirectory, Security-log read access and User Account Management +success auditing. Supply every relevant DC or a collector: events do not replicate. +NoAvailableRecord means evidence was not found in the selected logs/time window. +.EXAMPLE +.\Get-ADUserCreationAudit.ps1 -Server dc.example.com -Identity alice -DomainController dc1.example.com,dc2.example.com +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$Server, + [Parameter(Mandatory)][string]$Identity, + [Parameter(Mandatory)][string[]]$DomainController, + [datetime]$StartTime, + [datetime]$EndTime, + [pscredential]$Credential +) +$ErrorActionPreference = 'Stop' +$adQuery = @{ Identity = $Identity; Server = $Server; Properties = 'whenCreated' } +if ($Credential) { $adQuery.Credential = $Credential } +$user = Get-ADUser @adQuery -ErrorAction Stop +if (-not $PSBoundParameters.ContainsKey('StartTime')) { $StartTime = ([datetime]$user.whenCreated).AddDays(-1) } +if (-not $PSBoundParameters.ContainsKey('EndTime')) { $EndTime = ([datetime]$user.whenCreated).AddDays(1) } +if ($StartTime -ge $EndTime) { throw 'StartTime must precede EndTime.' } +$rows = @(foreach ($dc in $DomainController) { + $query = @{ ComputerName = $dc; FilterHashtable = @{ LogName = 'Security'; Id = 4720; StartTime = $StartTime; EndTime = $EndTime } } + if ($Credential) { $query.Credential = $Credential } + try { $auditEvents = @(Get-WinEvent @query -ErrorAction Stop) } catch { + if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw } + $auditEvents = @() + } + foreach ($auditEvent in $auditEvents) { + $xml = [xml]$auditEvent.ToXml() + $data = @{} + foreach ($item in $xml.Event.EventData.Data) { $data[$item.Name] = $item.'#text' } + if ($data.TargetSid -eq [string]$user.SID) { + [pscustomobject]@{ User = $user.SamAccountName; Created = $user.whenCreated; Creator = "$($data.SubjectDomainName)\$($data.SubjectUserName)"; DomainController = $dc; EventTime = $auditEvent.TimeCreated; RecordId = $auditEvent.RecordId; Evidence = 'Event4720' } + } + } +}) +if ($rows.Count) { $rows } else { + [pscustomobject]@{ User = $user.SamAccountName; Created = $user.whenCreated; Creator = $null; DomainController = $DomainController -join ';'; EventTime = $null; RecordId = $null; Evidence = 'NoAvailableRecord' } +} diff --git a/Get-ADUserEnabledStatus.ps1 b/Get-ADUserEnabledStatus.ps1 new file mode 100644 index 0000000..4ff57c9 --- /dev/null +++ b/Get-ADUserEnabledStatus.ps1 @@ -0,0 +1,27 @@ +<# +.SYNOPSIS +Export enabled/disabled status for a text list of AD identities; never enables accounts. +.EXAMPLE +.\Get-ADUserEnabledStatus.ps1 -Server dc.example.com -UserListPath .\users.txt -OutputPath .\status.csv +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$Server, + [Parameter(Mandatory)][string]$UserListPath, + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$rows = @(foreach ($identity in (Read-ToolkitIdentityList -Path $UserListPath)) { + try { + $user = Get-ADUser -Identity $identity -Server $Server -Properties Enabled -ErrorAction Stop + [pscustomobject]@{ Identity = $identity; Name = $user.Name; Enabled = $user.Enabled; Status = 'Found'; Error = $null } + } catch { + # Only AD's identity-not-found exception is a missing user. Connection and access errors stop the report. + if ($_.Exception.GetType().FullName -ne 'Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException') { throw } + [pscustomobject]@{ Identity = $identity; Name = $null; Enabled = $null; Status = 'NotFound'; Error = $_.Exception.Message } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-ADUserLoginData.ps1 b/Get-ADUserLoginData.ps1 new file mode 100644 index 0000000..a9c91b1 --- /dev/null +++ b/Get-ADUserLoginData.ps1 @@ -0,0 +1,13 @@ +<# +.SYNOPSIS +Read one AD user's password and replicated logon metadata. +.DESCRIPTION +LastLogonDate is replicated and approximate; it is not an exact latest logon across DCs. +.EXAMPLE +.\Get-ADUserLoginData.ps1 -Server dc.example.com -Identity alice +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [Parameter(Mandatory)][string]$Identity) +$ErrorActionPreference = 'Stop' +Get-ADUser -Identity $Identity -Server $Server -Properties PasswordLastSet, LastLogonDate, PasswordNeverExpires -ErrorAction Stop | + Select-Object Name, SamAccountName, Enabled, PasswordLastSet, LastLogonDate, PasswordNeverExpires diff --git a/Get-BrowserHistory.ps1 b/Get-BrowserHistory.ps1 index c333880..54034b7 100644 --- a/Get-BrowserHistory.ps1 +++ b/Get-BrowserHistory.ps1 @@ -1,429 +1,136 @@ -function Get-BrowserHistory { - <# - .SYNOPSIS - Gets web browsing history - - .DESCRIPTION - Parses Chrome and IE browser history. Optionally refines the results by username and/or URL. - - .PARAMETER ComputerName - The computer name to get browsing history from. Defaults to localhost (actually... `$env:COMPUTERNAME) - Accepts values from the pipeline. - - .PARAMETER UserName - RegEx to match the desired username. Defaults to '.' (All characters, excluding newline) - - .PARAMETER SearchTerm - RegEx to match the desired SearchTerm. Used to filter based on URL. - Defaults to '.' (All characters, excluding newline) - - .PARAMETER AsJob - Switch to use PSRemoting Jobs - - .EXAMPLE - Get-BrowserHistory -ComputerName host1 - Gets browsing history for all users on host1. - - .EXAMPLE - 'host1','host2','host3' | Get-BrowserHistory -UserName user1 -SearchTerm evil - Gets browsing history for user1 on host1, host2, and host3 where the URL matches 'evil' - - .INPUTS - System.Object - Microsoft.ActiveDirectory.Management.ADComputer - - .OUTPUTS - System.Management.Automation.PSCustomObject - - .NOTES - This script must be run with your admin account that has access to pull this data - - #> - - [CmdletBinding()] - [OutputType([psobject])] - - param ( - - [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)] - [Alias('PSComputerName','DNSHostName','CN','Hostname')] - [string[]] - $ComputerName, - - [string] - $UserName = '.', - - [string] - $SearchTerm = '.', - - [switch] - $AsJob - - ) #param - - begin { - - <# - This code currently supports parsing Chrome, IE, and FireFox history. - Roadmap: Include Timestamps, Include Visit Count - #> - - if (-not $ComputerName) { - - $ComputerName = $env:COMPUTERNAME - - } #if - - Write-Verbose -Message 'Start of function definitions.' - - function Get-ChromeHistory { - - [CmdletBinding()] - [OutputType([psobject])] - - param ( - - [string] - $UserName, - - [string] - $SearchTerm, - - [string] - $UrlRegex = '(htt(p|ps))://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?', - - [string] - $UserExpression = '$(Split-Path -Path $(Resolve-Path -Path "$_\..\..\..\..\..\..\..") -Leaf)' - - ) #param - - begin {} #begin - - process { - - Resolve-Path -Path "$env:SystemDrive\Users\*\AppData\Local\Google\Chrome\User Data\Default\History" | - - Where-Object { $($UserExpression | Invoke-Expression) -match $UserName } | - - ForEach-Object { - - $SourceFile = $_ - - $UserProfile = $($UserExpression | Invoke-Expression) - - Get-Content -Path $SourceFile | - - Select-String -Pattern $UrlRegex -AllMatches | - - ForEach-Object { ($_.Matches).Value } | - - Sort-Object -Unique | - - ForEach-Object { - - $EachUrl = $_ - - $DomainName = $EachUrl -replace 'http:\/\/','' -replace 'https:\/\/','' -replace '\/.*','' - - New-Object -TypeName psobject -Property @{ UserName = $UserProfile - Url = $_ - ComputerName = $env:COMPUTERNAME - Browser = 'Chrome' - DomainName = $DomainName } - - } #ForEach - - } | Where-Object { $_.Url -match $SearchTerm } - - } #process - - end {} #end - - } #function Get-ChromeHistory - - function Get-InternetExplorerHistory { - - [CmdletBinding()] - [OutputType([psobject])] - - param ( - - [string] - $UserName, - - [string] - $SearchTerm, - - [string] - $SidRegEx = 'S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$' - - ) #param - - begin {} #begin - - process { - - Get-ChildItem -Path Registry::\HKEY_USERS -ErrorAction SilentlyContinue | - - Where-Object { $_.Name -match $SidRegEx } | ForEach-Object { - - $UserAccount = Split-Path -Path $(( - [System.Security.Principal.SecurityIdentifier] $_.PSChildName - ).Translate( - [System.Security.Principal.NTAccount] - ).Value.ToString() - ) -Leaf - - if ($UserAccount -match $UserName) { - - $UserPath = $_ | Select-Object -ExpandProperty PSPath - - $KeyPath = "$UserPath\Software\Microsoft\Internet Explorer\TypedURLs" - - Get-Item -Path $KeyPath -ErrorAction SilentlyContinue | ForEach-Object { - - $Key = $_ - - $Key.GetValueNames() | ForEach-Object { - - $EachUrl = $Key.GetValue($_).Trim() - - $DomainName = $EachUrl -replace 'http:\/\/','' -replace 'https:\/\/','' -replace '\/.*','' - - New-Object -TypeName psobject -Property @{ UserName = $UserAccount - Url = $EachUrl - ComputerName = $env:COMPUTERNAME - Browser = 'IE' - DomainName = $DomainName } | - - Sort-Object -Property Url -Unique | - - Where-Object { $_.Url -match $SearchTerm } - - } #ForEach Url - - } #ForEach Key - - } #if - - } #ForEach RegPath - - } #process - - end {} #end - - } #function Get-InternetExplorerHistory - - function Get-FireFoxHistory { - - param ( - - [string] $UserName = '.', - - [string] $SearchTerm = '.', - - [string] $UrlRegex = '(htt(p|ps))://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?', - - [string] - $UserExpression = '$(Split-Path -Path $(Resolve-Path -Path "$_\..\..\..\..\..\..") -Leaf)' - - ) #param - - begin {} #begin - - process { - - Resolve-Path -Path "$env:SystemDrive\Users\*\AppData\Roaming\Mozilla\Firefox\Profiles\*.default\" | - - Where-Object { $($UserExpression | Invoke-Expression) -match $UserName } | - - ForEach-Object { - - $EachPath = $_ - - $SourceFile = Join-Path -Path $EachPath -ChildPath 'places.sqlite' - - $UserProfile = Split-Path -Path $(Resolve-Path -Path "$SourceFile\..\..\..\..\..\..\..") -Leaf - - Get-Content -Path $SourceFile | - - Select-String -Pattern $UrlRegex -AllMatches | - - ForEach-Object { ($_.Matches).Value } | - - Sort-Object -Unique | - - ForEach-Object { - - $EachUrl = $_ - - $DomainName = $EachUrl -replace 'http:\/\/','' -replace 'https:\/\/','' -replace '\/.*','' - - New-Object -TypeName psobject -Property @{ UserName = $UserProfile - Url = $EachUrl - ComputerName = $env:COMPUTERNAME - Browser = 'FireFox' - DomainName = $DomainName } - - } #ForEach Url - - } | Where-Object { $_.Url -match $SearchTerm } - - } #process - - end {} #end - - } #function Get-FireFoxHistory - - Write-Verbose -Message 'End of function definitions.' - - Write-Verbose -Message 'Start of function packaging.' - - $ChromeFunction = "function Get-ChromeHistory { ${function:Get-ChromeHistory} }" - - $IeFunction = "function Get-InternetExplorerHistory { ${function:Get-InternetExplorerHistory} }" - - $FireFoxFunction = "function Get-FireFoxHistory { ${function:Get-FireFoxHistory} }" - - Write-Verbose -Message 'End of function packaging.' - - } #begin - - process { - - $ComputerName | ForEach-Object { - - $EachComputer = $_ - - Write-Verbose -Message "Starting execution on '$EachComputer'" - Write-Verbose -Message 'Checking for -AsJob switch parameter.' - - if ($AsJob) { - - Write-Verbose -Message 'Running asynchronously due to -AsJob switch parameter.' - Write-Verbose -Message "Check to see if we're running locally." - - if ($EachComputer -match $env:COMPUTERNAME) { - - Write-Verbose -Message "We're running locally." - Write-Verbose -Message 'Starting local job.' - - Start-Job -ScriptBlock { - - Get-ChromeHistory -UserName $UserName -SearchTerm $SearchTerm - - Get-InternetExplorerHistory -UserName $UserName -SearchTerm $SearchTerm - - Get-FireFoxHistory -UserName $UserName -SearchTerm $SearchTerm - - } # Local Job - - Write-Verbose -Message 'Use "Get-Job" to see if it was successful or not.' - - } else { - - Write-Verbose -Message "We're running remotely." - Write-Verbose -Message 'Using Invoke-Command -AsJob to start remote job.' - - Invoke-Command -ComputerName $EachComputer -ScriptBlock { - - param ( - - $UserName, - $SearchTerm, - $ChromeFunction, - $IeFunction, - $FireFoxFunction - - ) #param - - . ([ScriptBlock]::Create($ChromeFunction)) - - . ([ScriptBlock]::Create($IeFunction)) - - . ([ScriptBlock]::Create($FireFoxFunction)) - - Get-ChromeHistory -UserName $UserName -SearchTerm $SearchTerm - - Get-InternetExplorerHistory -UserName $UserName -SearchTerm $SearchTerm - - Get-FireFoxHistory -UserName $UserName -SearchTerm $SearchTerm - - } -ArgumentList $UserName,$SearchTerm,$ChromeFunction,$IeFunction,$FireFoxFunction -AsJob - - Write-Verbose -Message 'Remote job created.' - Write-Verbose -Message 'Use "Get-Job" to see if it was successful or not.' - - } #if ($EachComputer -match $env:COMPUTERNAME) - - } else { - - Write-Verbose -Message 'Running synchronously due to lack of -AsJob switch parameter.' - Write-Verbose -Message "Check to see if we're running locally." - - if ($EachComputer -match $env:COMPUTERNAME) { - - Write-Verbose -Message "We're running locally." - - Get-ChromeHistory -UserName $UserName -SearchTerm $SearchTerm | - Select-Object -Property ComputerName,UserName,Browser,DomainName,Url - - Get-InternetExplorerHistory -UserName $UserName -SearchTerm $SearchTerm | - Select-Object -Property ComputerName,UserName,Browser,DomainName,Url - - Get-FireFoxHistory -UserName $UserName -SearchTerm $SearchTerm | - Select-Object -Property ComputerName,UserName,Browser,DomainName,Url - - } else { - - Write-Verbose -Message "We're running remotely." - Write-Verbose -Message 'Using Invoke-Command -AsJob to start remote job.' - - Invoke-Command -ComputerName $EachComputer -ScriptBlock { - - param ( - - $UserName, - $SearchTerm, - $ChromeFunction, - $IeFunction, - $FireFoxFunction - - ) #param - - . ([ScriptBlock]::Create($ChromeFunction)) - - . ([ScriptBlock]::Create($IeFunction)) - - . ([ScriptBlock]::Create($FireFoxFunction)) - - Get-ChromeHistory -UserName $UserName -SearchTerm $SearchTerm - - Get-InternetExplorerHistory -UserName $UserName -SearchTerm $SearchTerm - - Get-FireFoxHistory -UserName $UserName -SearchTerm $SearchTerm - - } -ArgumentList $UserName,$SearchTerm,$ChromeFunction,$IeFunction,$FireFoxFunction | - - Select-Object -Property ComputerName,UserName,Browser,DomainName,Url - - } #if ($EachComputer -match $env:COMPUTERNAME) - - } #if ($AsJob) - - } #ForEach $ComputerName - - } #process - - end {} #end - -} #function Get-BrowserHistory - - -# Prompt for the computer name -$compname = Read-Host "Enter the Computer name or IP address" - -# Run the function -Get-BrowserHistory -ComputerName $compname | Out-GridView - -Write-Host "Script Complete" -ForegroundColor Green \ No newline at end of file +<# +.SYNOPSIS +Collect Chrome, Edge and Firefox history using read-only SQLite snapshots. +.DESCRIPTION +Windows only. Install sqlite3 >= 3.33 on each target and make it available in PATH, +or pass -SqlitePath. No software is downloaded. Uses the SQLite backup API to +capture a consistent database including WAL data. Browsers are never terminated. +Requires permission to read selected profiles; outputs may contain sensitive URLs. +IE TypedURLs is not a complete history source and is no longer collected. +-AsJob returns jobs; use Receive-Job -Wait -AutoRemoveJob to retrieve results/errors. +.EXAMPLE +.\Get-BrowserHistory.ps1 -ComputerName workstation01 -UserName alice -SearchTerm example.com +#> +[CmdletBinding()] +param( + [string[]]$ComputerName = @($env:COMPUTERNAME), + [string]$UserName = '*', + [string]$SearchTerm = '', + [string]$SqlitePath = 'sqlite3', + [string]$ProfileRoot, + [pscredential]$Credential, + [switch]$AsJob +) +$ErrorActionPreference = 'Stop' +# A self-contained block works in both local jobs and remote sessions. +$collector = { + param($UserPattern, $Term, $SqliteExecutable, $Root) + $ErrorActionPreference = 'Stop' + if ($env:OS -ne 'Windows_NT') { throw 'This collector requires Windows browser profile paths.' } + $sqlite = (Get-Command -Name $SqliteExecutable -CommandType Application -ErrorAction Stop).Source + if (-not $Root) { $Root = Join-Path $env:SystemDrive 'Users' } + function Invoke-HistorySqlite { + [CmdletBinding()] + param([string[]]$ArgumentList) + # Process streams use explicit UTF-8, including in Windows PowerShell and + # remote sessions without a console. Escape Windows argv, never a shell. + $quoted = foreach ($argument in $ArgumentList) { + $escaped = [regex]::Replace($argument, '(\*)"', '$1$1\"') + $escaped = [regex]::Replace($escaped, '(\+)$', '$1$1') + '"' + $escaped + '"' + } + $process = [Diagnostics.Process]::new() + try { + $process.StartInfo.FileName = $sqlite + $process.StartInfo.Arguments = $quoted -join ' ' + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + $process.StartInfo.StandardOutputEncoding = [Text.UTF8Encoding]::new($false) + $process.StartInfo.StandardErrorEncoding = [Text.UTF8Encoding]::new($false) + $null = $process.Start() + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(120000)) { + $process.Kill() + $process.WaitForExit() + throw 'SQLite command exceeded the two-minute timeout.' + } + $output = $stdout.GetAwaiter().GetResult() + $errorText = $stderr.GetAwaiter().GetResult() + if ($process.ExitCode -ne 0) { throw "SQLite exit code $($process.ExitCode): $errorText" } + $output + } finally { $process.Dispose() } + } + $sources = [System.Collections.Generic.List[object]]::new() + foreach ($userProfile in (Get-ChildItem -LiteralPath $Root -Directory -Force)) { + if ($userProfile.Name -notlike $UserPattern) { continue } + foreach ($browser in 'Chrome','Edge') { + $relative = if ($browser -eq 'Chrome') { 'AppData\Local\Google\Chrome\User Data' } else { 'AppData\Local\Microsoft\Edge\User Data' } + $browserRoot = Join-Path $userProfile.FullName $relative + if (-not (Test-Path -LiteralPath $browserRoot)) { continue } + foreach ($browserProfile in (Get-ChildItem -LiteralPath $browserRoot -Directory)) { + $database = Join-Path $browserProfile.FullName 'History' + if (Test-Path -LiteralPath $database -PathType Leaf) { + $sources.Add([pscustomobject]@{ User = $userProfile.Name; Browser = $browser; Profile = $browserProfile.Name; Database = $database }) + } + } + } + $browserRoot = Join-Path $userProfile.FullName 'AppData\Roaming\Mozilla\Firefox\Profiles' + if (Test-Path -LiteralPath $browserRoot) { + foreach ($browserProfile in (Get-ChildItem -LiteralPath $browserRoot -Directory)) { + $database = Join-Path $browserProfile.FullName 'places.sqlite' + if (Test-Path -LiteralPath $database -PathType Leaf) { + $sources.Add([pscustomobject]@{ User = $userProfile.Name; Browser = 'Firefox'; Profile = $browserProfile.Name; Database = $database }) + } + } + } + } + foreach ($source in $sources) { + $snapshot = Join-Path ([IO.Path]::GetTempPath()) ("history-$([guid]::NewGuid()).sqlite") + try { + # The destination is generated by this script; escape the SQLite dot-command argument. + $destination = $snapshot.Replace('\','/') + try { $null = Invoke-HistorySqlite -ArgumentList @('-readonly', $source.Database, '.timeout 5000', ".backup `"$destination`"") } + catch { throw "SQLite snapshot failed for $($source.Database): $_" } + $sql = if ($source.Browser -eq 'Firefox') { + "SELECT url, title, visit_count AS VisitCount, strftime('%Y-%m-%dT%H:%M:%fZ',last_visit_date/1000000.0,'unixepoch') AS LastVisitUtc FROM moz_places WHERE last_visit_date IS NOT NULL;" + } else { + "SELECT url, title, visit_count AS VisitCount, strftime('%Y-%m-%dT%H:%M:%fZ',(last_visit_time/1000000.0)-11644473600,'unixepoch') AS LastVisitUtc FROM urls WHERE last_visit_time > 0;" + } + try { $json = Invoke-HistorySqlite -ArgumentList @('-readonly','-json',$snapshot,$sql) } + catch { throw "SQLite query failed for $($source.Database): $_" } + if (-not $json) { continue } + foreach ($record in (($json -join "`n") | ConvertFrom-Json)) { + if ($Term -and $record.url.IndexOf($Term, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue } + $uri = $null + $domain = if ([uri]::TryCreate($record.url, [UriKind]::Absolute, [ref]$uri)) { $uri.Host } else { $null } + [pscustomobject]@{ + ComputerName = $env:COMPUTERNAME + UserName = $source.User + Browser = $source.Browser + Profile = $source.Profile + Url = $record.url + DomainName = $domain + Title = $record.title + VisitCount = $record.VisitCount + LastVisitUtc = ([datetimeoffset]$record.LastVisitUtc).UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'") + } + } + } finally { + if (Test-Path -LiteralPath $snapshot) { Remove-Item -LiteralPath $snapshot -Force } + } + } +} +foreach ($computer in $ComputerName) { + $local = $computer -in @('.', 'localhost', $env:COMPUTERNAME) + if ($local -and -not $Credential) { + if ($AsJob) { Start-Job -ScriptBlock $collector -ArgumentList $UserName,$SearchTerm,$SqlitePath,$ProfileRoot } + else { & $collector $UserName $SearchTerm $SqlitePath $ProfileRoot } + } else { + $invoke = @{ ComputerName = $computer; ScriptBlock = $collector; ArgumentList = $UserName,$SearchTerm,$SqlitePath,$ProfileRoot; AsJob = $AsJob } + if ($Credential) { $invoke.Credential = $Credential } + Invoke-Command @invoke + } +} diff --git a/Get-ComputerInfo.ps1 b/Get-ComputerInfo.ps1 index 071e629..ffe7e45 100644 --- a/Get-ComputerInfo.ps1 +++ b/Get-ComputerInfo.ps1 @@ -1,52 +1,29 @@ -<# -.SYNOPSIS - Get Computer info -.DESCRIPTION - This tool returns a variety of information about an AD user and prompts for the user name - -.EXAMPLE - No examples at this time. - -.INPUTS - $cred - This prompts the user for credentials - Note - Be sure to use the credentials in the right domain - for which the target system resides. (e.g. bbcgrp\username or bbc\username) - $comp - This prompts the suer for the computer name or target that we are searching for - Note - This will accept a computer name or an IP address -.OUTPUTS - - OS version of the remote computer to the screen - - Current Logged on user of the remote computer - - All hotfix installs on the remote computer - -.NOTES - Created by John Skinner - - When prompted for your credentials, be sure to loggin to the domain where the target computer exists - Or this script will not be able to find the target computer. - -.LINK - -#> - -# Get and store credentials and Prompte for Computer name or IP Address -# When prompted for your credentials, be sure to loggin to the domain where the target computer exists -$cred = Get-Credential -$comp = Read-Host -Prompt 'Enter the Computer Name or IP address' - - Write-host "Getting Basic Computer Info..." -ForegroundColor cyan - -#Get OS version on remote system -Get-WmiObject Win32_OperatingSystem -ComputerName $comp -Credential $cred | -Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber | FL - - Write-host "Getting Current Logged in User..." -ForegroundColor cyan - -# Get Current logged on user -Get-WmiObject -ComputerName $comp -Credential $cred -Class Win32_ComputerSystem | Select-Object UserName - - Write-host "Getting all installed Hotfix's..." -ForegroundColor cyan - -#Get hotfix installed on remote computer -Get-HotFix -ComputerName $comp -Credential $cred - - Write-host "Script Complete!" -ForegroundColor green +<# +.SYNOPSIS +Read OS, logged-on user and installed hotfix inventory through a CIM session. +.DESCRIPTION +Requires remote CIM/WinRM access. Credentials are optional; the current identity is +used otherwise. The session is always removed. Output remains structured. +.EXAMPLE +.\Get-ComputerInfo.ps1 -ComputerName server01 -Credential (Get-Credential) +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$ComputerName, [pscredential]$Credential) +$ErrorActionPreference = 'Stop' +$query = @{ ComputerName = $ComputerName } +if ($Credential) { $query.Credential = $Credential } +$session = New-CimSession @query -ErrorAction Stop +try { + $os = Get-CimInstance -CimSession $session -ClassName Win32_OperatingSystem -ErrorAction Stop + $computer = Get-CimInstance -CimSession $session -ClassName Win32_ComputerSystem -ErrorAction Stop + [pscustomobject]@{ + ComputerName = $ComputerName + Caption = $os.Caption + OSArchitecture = $os.OSArchitecture + Version = $os.Version + BuildNumber = $os.BuildNumber + LoggedOnUser = $computer.UserName + HotFixes = @(Get-CimInstance -CimSession $session -ClassName Win32_QuickFixEngineering -ErrorAction Stop | + Select-Object HotFixID, Description, InstalledOn) + } +} finally { Remove-CimSession -CimSession $session -ErrorAction Stop } diff --git a/Get-GraphDeviceCompliance.ps1 b/Get-GraphDeviceCompliance.ps1 new file mode 100644 index 0000000..8e36bb2 --- /dev/null +++ b/Get-GraphDeviceCompliance.ps1 @@ -0,0 +1,9 @@ +<# +.SYNOPSIS +Report nullable Graph directory compliance flags; this is not a full Intune assessment. +.EXAMPLE +.\Get-GraphDeviceCompliance.ps1 -TenantId TENANT-GUID +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$TenantId, [string]$OutputPath, [switch]$Force) +& "$PSScriptRoot/Export-GraphDevices.ps1" @PSBoundParameters diff --git a/Get-GraphWindowsDevices.ps1 b/Get-GraphWindowsDevices.ps1 new file mode 100644 index 0000000..86a6e98 --- /dev/null +++ b/Get-GraphWindowsDevices.ps1 @@ -0,0 +1,9 @@ +<# +.SYNOPSIS +Report Windows directory devices from the connected Microsoft Graph tenant. +.EXAMPLE +.\Get-GraphWindowsDevices.ps1 -TenantId TENANT-GUID +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$TenantId, [string]$OutputPath, [switch]$Force) +& "$PSScriptRoot/Export-GraphDevices.ps1" @PSBoundParameters -OperatingSystem Windows diff --git a/Get-RemoteSerialNumber.ps1 b/Get-RemoteSerialNumber.ps1 index d12fbc7..0de80a9 100644 --- a/Get-RemoteSerialNumber.ps1 +++ b/Get-RemoteSerialNumber.ps1 @@ -1,65 +1,16 @@ -<# -.SYNOPSIS -This script solves a need to retrieve serial numbers for inventory tracking - -.DESCRIPTION -The utilizes the "Get-CIMInstance" module to reach into the bios of a remote computer -and return the following bits of information - --SMBIOSBIOSVersion --Manufacturer --Name --SerialNumber --Version --PSComputerName - -.EXAMPLE -The below example shows the expected response, if you do not get this response, -then most likely the computer is offline. - -C:\scripts\Get-RemoteSerialNumber.ps1 -Enter the computer name you want to search: ATLLMorrow - -SMBIOSBIOSVersion : T76 Ver. 01.04.01 -Manufacturer : HP -Name : T76 Ver. 01.04.01 -SerialNumber : 5CG1131XLR -Version : HPQOEM - 0 -PSComputerName : ATLLMorrow - -Script Complete! - -.INPUTS -Prompts the Admin to type the computer name - -This script declares a variable "$compname" and uses the "Read-Host: -command to take the name of the computer from the admin that is running -the search. - -.OUTPUTS -This script outputs the following information to the screen - --SMBIOSBIOSVersion --Manufacturer --Name --SerialNumber --Version --PSComputerName - -.NOTES -Created by John Skinner, please let me know if you have questions -about this script - -***This script will require admin credentials, so launch the PowerShell ISE as another user -Type in your admin creds, and then browse to this script and run it.*** - -#> - -#Declare the Compname variable - Accept input from the Admin -$compname = Read-Host "Enter the computer name you want to search" - -#Run the magic, grab the information from the remote computer - Output to the screen -get-ciminstance -classname win32_bios -computername $compname - -#Tell the admin the script is finished -Write-Host "Script Complete!" -ForegroundColor Green \ No newline at end of file +<# +.SYNOPSIS +Retrieve remote BIOS serial and version information through CIM. +.EXAMPLE +.\Get-RemoteSerialNumber.ps1 -ComputerName server01 +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$ComputerName, [pscredential]$Credential) +$ErrorActionPreference = 'Stop' +$query = @{ ComputerName = $ComputerName } +if ($Credential) { $query.Credential = $Credential } +$session = New-CimSession @query -ErrorAction Stop +try { + Get-CimInstance -CimSession $session -ClassName Win32_BIOS -ErrorAction Stop | + Select-Object PSComputerName, SerialNumber, Manufacturer, SMBIOSBIOSVersion, Name, Version +} finally { Remove-CimSession -CimSession $session -ErrorAction Stop } diff --git a/Get-WindowsEvents.ps1 b/Get-WindowsEvents.ps1 index cb0b8ec..2b7414e 100644 --- a/Get-WindowsEvents.ps1 +++ b/Get-WindowsEvents.ps1 @@ -1,43 +1,35 @@ -<# -.SYNOPSIS - Get Windows events for a particular computer - -.DESCRIPTION -I needed a quick way to pull the event logs from a remote computer, for a selected date range -This oneliner script is that solution... I have tested the script and seems to work as expected -but the script is in its infancy and could possibly be tweaked if we need to. - -.INPUTS -Prompts for the computer name or IP address - self explanatory, what computer are you interested in - -The "-Credential" value will need to be modified to your admin account -Important to note that you will need to use your admin account on the right domain for the host that -you are investigating. (bbc or bbcgrp) - -Takes inputs for the start and end date [StartTime="date";"EndTime="date"] -Will need to change the dates as necessary depended on the range you are interested in -Keep in mind this is a lot of events... try to limit to one day -This allow us to pull the logs for between a specific date - -The -FilterHashtable command allows us to select the logname (eg. Application, System, Security...) -This will need to be modified as needed depending on what you are looking for - -.EXAMPLE --Pull system events for Investments PC for a specific time and date ranged. Then export to CSV - -Get-WinEvent -ComputerName $Computer -Credential bbcgp\x-jwskinner -FilterHashtable @{logname='System';StartTime="09/12/21";EndTime="09/13/21"} | Out-GridView - -.OUTPUTS -This script outputs to the Grid on the screen which allows you to easily view the results and sort those results -You could change this if needed to Export to a CSV - -.NOTES -Script created by John Skinner. - -#> - -#Prompt for the computer name -$Computer = Read-Host "Enter the Computer Name or IP Address" - -#Run the magic and grab the logs -Get-WinEvent -ComputerName $Computer -Credential bbcgrp\x-jwskinner -FilterHashtable @{logname='Application';StartTime="09/12/21 6:00";EndTime="09/12/21 10:00"} | Export-Csv c:\temp\10.12.170.51_Application.csv \ No newline at end of file +<# +.SYNOPSIS +Read Windows events for an explicit host and time window; optionally export CSV. +.DESCRIPTION +Requires Windows Event Log remote access and appropriate log-read permissions. +Times are interpreted by PowerShell as supplied; include an offset for portability. +.EXAMPLE +.\Get-WindowsEvents.ps1 -ComputerName server01 -LogName System -StartTime '2026-10-01T00:00:00-05:00' -EndTime '2026-10-02T00:00:00-05:00' +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$ComputerName, + [Parameter(Mandatory)][datetime]$StartTime, + [Parameter(Mandatory)][datetime]$EndTime, + [string]$LogName = 'System', + [int[]]$Id, + [pscredential]$Credential, + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +if ($StartTime -ge $EndTime) { throw 'StartTime must precede EndTime.' } +$filter = @{ LogName = $LogName; StartTime = $StartTime; EndTime = $EndTime } +if ($Id) { $filter.Id = $Id } +$query = @{ ComputerName = $ComputerName; FilterHashtable = $filter } +if ($Credential) { $query.Credential = $Credential } +try { + $rows = @(Get-WinEvent @query -ErrorAction Stop | Select-Object MachineName, LogName, TimeCreated, Id, LevelDisplayName, ProviderName, RecordId, Message) +} catch { + if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound*') { throw } + $rows = @() +} +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/GrabAD-GroupMembers.ps1 b/GrabAD-GroupMembers.ps1 index 1101340..6245743 100644 --- a/GrabAD-GroupMembers.ps1 +++ b/GrabAD-GroupMembers.ps1 @@ -1,42 +1,9 @@ -#For this screipt to work you will need to change lines 18 and 23 -#the "-server domainname" should be the name of the domain tha tyou want to search - -Function Get-ADGroupMemberJohn { - [CmdletBinding()] - param( - [Parameter( - Mandatory = $true, - ValueFromPipeline = $true, - ValueFromPipelineByPropertyName = $true, - Position = 0 - )] - [string[]] - $Identity - ) - process { - foreach ($GroupIdentity in $Identity) { - $Group = $null - $Group = Get-ADGroup -Identity $GroupIdentity -Properties Member -server domainname - if (-not $Group) { - continue - } - Foreach ($Member in $Group.Member) { - Get-ADUser $Member -server domainname |Select-object -ExpandProperty name - } - } - } -} -Write-Host "***************************************************************" -ForegroundColor cyan -Write-Host "Welcome to your Friendly Nieghborhood AD Group Member Extractor" -ForegroundColor cyan -Write-Host "***************************************************************" -ForegroundColor cyan - -$x = "go" -do { - $group = read-host "What group do you want?" - Get-ADGroupMemberJohn $group | Out-File C:\temp\MFAUsers.csv - Write-Host "Your Group Member list is stored in c:\Temp\MFAUsers.csv" -ForgroundColor green - $answer = Read-host "another one?" - if ($answer -eq "no" -or $answer -eq "n"){$x = "stop"} - cls - } - while ($x -ne "stop") +<# +.SYNOPSIS +Compatibility entry point for the consolidated AD group-member report. +.EXAMPLE +.\GrabAD-GroupMembers.ps1 -Server dc.example.com -Group Finance -OutputPath .\members.csv +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$Server, [Parameter(Mandatory)][string]$Group, [switch]$Recursive, [string]$OutputPath, [switch]$Force) +& "$PSScriptRoot/Export-ADGroupMembers.ps1" @PSBoundParameters diff --git a/GrabAD-UserLoginData b/GrabAD-UserLoginData deleted file mode 100644 index db5837c..0000000 --- a/GrabAD-UserLoginData +++ /dev/null @@ -1,26 +0,0 @@ -<# -.SYNOPSIS - Simple script to find quick information about the user - -.DESCRIPTION - This script find the Last Password Set data, the users last login date, and if the users password never expires - -.INPUTS - This script prompts for the domain, and then prompts for the user account - -.OUTPUTS - Outputs the information to the screen - -.NOTES - Create by John Skinner -#> - -# Set Variables -$domain = Read-Host "What domain would you like to search? " -$user = Read-Host "What is the user ID? " - -# Run the Magic -Get-ADUser $user -Server $domain -Properties passwordlastset, LastLogonDate, PasswordNeverExpires - -# Mark the script complete -Write-Host "Script Complete" -ForegroundColor Green diff --git a/GraphAPI-GuestUserStatus.ps1 b/GraphAPI-GuestUserStatus.ps1 index ae05a50..4947a27 100644 --- a/GraphAPI-GuestUserStatus.ps1 +++ b/GraphAPI-GuestUserStatus.ps1 @@ -1,82 +1,44 @@ - -# ReportLastAccountSignIn-Mg.PS1 -# -# -# Connect to the Graph, specifying the tenant and profile to use - Add your tenant identifier here -Connect-MgGraph -TenantId TENANTID -Scope Auditlog.Read.All -Select-MgProfile beta # Beta needed to get more informtion from the Graph -$Details = Get-MgContext -$Scopes = $Details | Select -ExpandProperty Scopes -$Scopes = $Scopes -Join ", " -$ProfileName = (Get-MgProfile).Name -$OrgName = (Get-MgOrganization).DisplayName -CLS -Write-Host "Microsoft Graph Connection Information" -ForegroundColor Cyan -Write-Host "--------------------------------------" -ForegroundColor Cyan -Write-Host " " -Write-Host ("Connected to Tenant {0} ({1}) as account {2}" -f $Details.TenantId, $OrgName, $Details.Account) -ForegroundColor Green -Write-Host "+-------------------------------------------------------------------------------------------------------------------+" -ForegroundColor Green -Write-Host ("Profile set as {0}. The following permission scope is defined: {1}" -f $ProfileName, $Scopes) -ForegroundColor Green -Write-Host "" -#$Username = Read-Host "What User would you like to look for ? (Include the full UPN) " -Write-Host "Finding Azure AD Users" -ForegroundColor Yellow -#This is the magic -Can change things here to do different stuff -#The below command searchs for a user name -# ********************************************* -#[array]$Users = Get-MgUser -UserId $Username -# This command searches for all Guest users -# ********************************************* -[array]$Users = Get-MgUser -All -Filter "UserType eq 'Guest'" - -If ($Users.Count -eq 0) { Write-Host "Sorry, no Azure AD user info fetched"; break} -CLS -$ProgressDelta = 100/($Users.count); $PercentComplete = 0; $UserNumber = 0 -Write-Host ("{0} accounts to process..." -f $Users.Count) -CLS;$Report = [System.Collections.Generic.List[Object]]::new();$CSVOutput = "C:\temp\LastAccountSignIn.CSV" -ForEach ($User in $Users) { # See if we can find the last sign in record for an account - $UserNumber++ - $PercentComplete += $ProgressDelta - $UserStatus = $User.DisplayName + " ["+ $UserNumber +"/" + $Users.Count + "]" - Write-Progress -Activity "Processing user" -Status $UserStatus -PercentComplete $PercentComplete - [array]$LastSignIn = Get-MgAuditLogSignIn -Filter "UserId eq '$($User.Id)'" -Top 1 - If ($LastSignIn) { # We found a sign in record, so report it - $ReportLine = [PSCustomObject][Ordered]@{ - Name = $LastSignIn.UserDisplayName - UPN = $LastSignIn.UserPrincipalName - Id = $LastSignIn.UserId - UserType = $User.UserType - AccountCreated = $User.CreatedDateTime - CreationType = $User.CreationType - InvitationState = $User.externalUserState - SignInDate = $LastSignIn.CreatedDateTime - DaysSince = ($LastSignIn.CreatedDateTime | New-TimeSpan).Days - Location = $LastSignIn.Location.City - App = $LastSignIn.AppDisplayName - Client = $LastSignIn.ClientAppUsed - IPAddress = $LastSignIn.IPAddress - IsInteractive = $LastSignIn.IsInterActive - CAAccess = $LastSignIn.ConditionalAccessStatus - RiskState = $LastSignIn.RiskState } - $Report.Add($ReportLine) } #End if - Else { # No sign in record found, so we report that" - $ReportLine = [PSCustomObject][Ordered]@{ - Name = $User.UserDisplayName - UPN = $User.UserPrincipalName - Id = $User.Id - UserType = $User.UserType - AccountCreated = $User.CreatedDateTime - CreationType = $User.CreationType - InvitationState = $User.externalUserState - SignInDate = "No sign in data found" - DaysSince = "N/A" - App = "N/A" - Client = "N/A" - IPAddress = "N/A" - IsInteractive = "N/A" - CAAccess = "N/A" - RiskState = "N/A" } - $Report.Add($ReportLine) } #End Else -} #End ForEach -$Report | Sort {$_.SignInDate -as [datetime]} -descending | Out-GridView -$Report | Export-CSV -NoTypeInformation $CSVOutput -Write-Host "All done. Report is on the screen and available in" $CSVOutput -ForegroundColor Green +<# +.SYNOPSIS +Report each guest's latest available interactive sign-in from Microsoft Graph v1.0. +.DESCRIPTION +Connect-MgGraph first with User.Read.All and AuditLog.Read.All. Sign-in API access +requires appropriate licensing and roles. NoAvailableRecord does NOT mean never +signed in: data is limited by retention. API failures terminate the report. +.EXAMPLE +.\GraphAPI-GuestUserStatus.ps1 -TenantId TENANT-GUID -OutputPath .\guests.csv +#> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$TenantId, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +Assert-ToolkitGraphContext -TenantId $TenantId +$properties = 'id','displayName','userPrincipalName','userType','createdDateTime','creationType','externalUserState' +$users = @(Get-MgUser -All -Filter "userType eq 'Guest'" -Property $properties -ErrorAction Stop) +$rows = @(foreach ($user in $users) { + # The signIns endpoint returns descending createdDateTime order by default. + $latest = @(Get-MgAuditLogSignIn -Filter "userId eq '$($user.Id)'" -Top 1 -ErrorAction Stop) + $signIn = if ($latest.Count) { $latest[0] } else { $null } + [pscustomobject]@{ + Name = $user.DisplayName + UPN = $user.UserPrincipalName + Id = $user.Id + UserType = $user.UserType + AccountCreated = $user.CreatedDateTime + CreationType = $user.CreationType + InvitationState = $user.ExternalUserState + RecordStatus = if ($signIn) { 'Available' } else { 'NoAvailableRecord' } + SignInDate = if ($signIn) { $signIn.CreatedDateTime } else { $null } + DaysSince = if ($signIn) { [math]::Floor(([datetimeoffset]::UtcNow - [datetimeoffset]$signIn.CreatedDateTime).TotalDays) } else { $null } + Location = if ($signIn) { $signIn.Location.City } else { $null } + App = if ($signIn) { $signIn.AppDisplayName } else { $null } + Client = if ($signIn) { $signIn.ClientAppUsed } else { $null } + IPAddress = if ($signIn) { $signIn.IPAddress } else { $null } + IsInteractive = if ($signIn) { $signIn.IsInteractive } else { $null } + ConditionalAccessStatus = if ($signIn) { $signIn.ConditionalAccessStatus } else { $null } + RiskState = if ($signIn) { $signIn.RiskState } else { $null } + SignInErrorCode = if ($signIn) { $signIn.Status.ErrorCode } else { $null } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/!LICENSE b/LICENSE similarity index 100% rename from !LICENSE rename to LICENSE diff --git a/MSGraph API Get All Devices & Compliant b/MSGraph API Get All Devices & Compliant deleted file mode 100644 index d0d1841..0000000 --- a/MSGraph API Get All Devices & Compliant +++ /dev/null @@ -1 +0,0 @@ -Get-MgDevice -All -Property displayName,OperatingSystemVersion,OnPremisesLastSyncDateTime,isCompliant -CountVariable CountVar -ConsistencyLevel eventual | Select-Object displayName,OperatingSystemVersion,OnPremisesLastSyncDateTime,IsCompliant diff --git a/MSGraph API Get all Devices b/MSGraph API Get all Devices deleted file mode 100644 index 25037ab..0000000 --- a/MSGraph API Get all Devices +++ /dev/null @@ -1 +0,0 @@ -get-mgdevice -All | Export-CSV c:\temp\DeviceList.csv diff --git a/MSGraph API Search for Device b/MSGraph API Search for Device deleted file mode 100644 index 47da9f7..0000000 --- a/MSGraph API Search for Device +++ /dev/null @@ -1,2 +0,0 @@ -Import-Module Microsoft.Graph.Identity.DirectoryManagement -Get-MgDevice -Search "displayName:Android" -CountVariable CountVar -ConsistencyLevel eventual diff --git a/MSGraphAPI Get all devices with various info b/MSGraphAPI Get all devices with various info deleted file mode 100644 index aa50adc..0000000 --- a/MSGraphAPI Get all devices with various info +++ /dev/null @@ -1 +0,0 @@ -Get-MgDevice -All -Search "OperatingSystem:Windows" -Property displayName,OperatingSystemVersion,OnPremisesLastSyncDateTime -CountVariable CountVar -ConsistencyLevel eventual | Select-Object displayName,OperatingSystemVersion,OnPremisesLastSyncDateTime diff --git a/O365 Holds Enabled Mailboxes b/O365 Holds Enabled Mailboxes deleted file mode 100644 index c890739..0000000 --- a/O365 Holds Enabled Mailboxes +++ /dev/null @@ -1,214 +0,0 @@ -<# -============================================================================================= -Name: Export Office 365 Mailbox Holds Report -Description: This script exports hold enabled mailboxes to CSV -Version: 1.0 -website: o365reports.com -Script by: O365Reports Team -For detailed Script execution: http://o365reports.com/2021/06/29/export-office-365-mailbox-holds-report-using-powershell -============================================================================================ -#> - -param ( - [string] $UserName = $null, - [string] $Password = $null, - [Switch] $LitigationHoldsOnly, - [Switch] $InPlaceHoldsOnly, - [Switch] $RetentionHoldsOnly -) - -Function GetBasicData { - $global:ExportedMailbox = $global:ExportedMailbox + 1 - $global:MailboxName = $_.Name - $global:RecipientTypeDetails = $_.RecipientTypeDetails - $global:UPN = $_.UserPrincipalName -} -Function RetrieveAllHolds { - if ($LitigationHoldsOnly.IsPresent) { - $global:ExportCSVFileName = "LitigationHoldsReport" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv" - Get-mailbox -IncludeInactiveMailbox -ResultSize Unlimited | Where-Object { $_.LitigationHoldEnabled -eq $True } | foreach-object { - $CurrLitigationHold = $_ - GetLitigationHoldsReport - } - } - elseif ($InPlaceHoldsOnly.IsPresent) { - $global:ExportCSVFileName = "InPlaceHoldsReport" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv" - Get-mailbox -IncludeInactiveMailbox -ResultSize Unlimited | Where-Object { $_.InPlaceHolds -ne $Empty } | foreach-object { - $CurrInPlaceHold = $_ - GetInPlaceHoldsReport - } - } - elseif ($RetentionHoldsOnly.IsPresent) { - $global:ExportCSVFileName = "RetentionHoldsReport" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv" - Get-mailbox -IncludeInactiveMailbox -ResultSize Unlimited | Where-Object { $_.RetentionHoldEnabled -eq $True } | foreach-object { - $CurrRetentionHold = $_ - GetRetentionHoldsReport - } - } - else { - $global:ExportCSVFileName = "AllActiveHoldsReport" + ((Get-Date -format "MMM-dd hh-mm-ss tt").ToString()) + ".csv" - Get-mailbox -IncludeInactiveMailbox -ResultSize Unlimited | Where-Object { $_.LitigationHoldEnabled -eq $True -or $_.RetentionHoldEnabled -eq $True -or $_.InPlaceHolds -ne $Empty -or $_.ComplianceTagHoldApplied -eq $True } | foreach-object { - $CurrMailbox = $_ - GetDefaultReport - } - } -} - -Function GetInPlaceHoldType($HoldGuidList) { - $HoldTypes = @() - $InPlaceHoldCount = 0 - $HoldGuidList | ForEach-Object { - $InPlaceHoldCount = $InPlaceHoldCount + 1 - if ($_ -match "UniH") { - $HoldTypes += "eDiscovery Case" - } - elseif ($_ -match "^mbx") { - $HoldTypes += "Specific Location Retention Policy" - } - elseif ($_ -match "^\-mbx") { - $HoldTypes += "Mailbox Excluded Retention Policy" - } - elseif ($_ -match "skp") { - $HoldTypes += "Retention Policy on Skype" - } - else { - $HoldTypes += "In-Place Hold" - } - } - - return ($HoldTypes -join ", "), $InPlaceHoldCount -} - -Function GetLitigationHoldsReport { - GetBasicData - $LitigationOwner = $CurrLitigationHold.LitigationHoldOwner - if ($null -ne $CurrLitigationHold.LitigationHoldDate) { - $LitigationHoldDate = ($CurrLitigationHold.LitigationHoldDate).ToString().Split(" ") | Select-Object -Index 0 - } - $LitigationDuration = $CurrLitigationHold.LitigationHoldDuration - if ($LitigationDuration -ne "Unlimited") { - $LitigationDuration = ($LitigationDuration).split(".") | Select-Object -Index 0 - } - - Write-Progress "Retrieving the Litigation Hold Information for the User: $global:MailboxName" "Processed Mailboxes Count: $global:ExportedMailbox" - - #ExportResult - $ExportResult = @{'Mailbox Name' = $global:MailboxName; 'Mailbox Type' = $global:RecipientTypeDetails; 'UPN' = $global:UPN; 'Litigation Owner' = $LitigationOwner; 'Litigation Duration' = $LitigationDuration; 'Litigation Hold Date' = $LitigationHoldDate } - $ExportResults = New-Object PSObject -Property $ExportResult - $ExportResults | Select-object 'Mailbox Name', 'UPN', 'Mailbox Type', 'Litigation Owner', 'Litigation Duration', 'Litigation Hold Date' | Export-csv -path $global:ExportCSVFileName -NoType -Append -Force -} - -Function GetInPlaceHoldsReport { - GetBasicData - $InPlaceHoldInfo = GetInPlaceHoldType ($CurrInPlaceHold.InPlaceHolds) - $InPlaceHoldType = $InPlaceHoldInfo[0] - $NumberOfHolds = $InPlaceHoldInfo[1] - - Write-Progress "Retrieving the In-Place Hold Information for the User: $global:MailboxName" "Processed Mailboxes Count: $global:ExportedMailbox" - - #Export Results - $ExportResult = @{'Mailbox Name' = $global:MailboxName; 'Mailbox Type' = $global:RecipientTypeDetails; 'UPN' = $global:UPN; 'Configured InPlace Hold Count' = $NumberOfHolds; 'InPlace Hold Type' = $InPlaceHoldType } - $ExportResults = New-Object PSObject -Property $ExportResult - $ExportResults | Select-object 'Mailbox Name', 'UPN', 'Mailbox Type', 'Configured InPlace Hold Count', 'InPlace Hold Type' | Export-csv -path $global:ExportCSVFileName -NoType -Append -Force -} - -Function GetRetentionHoldsReport { - GetBasicData - $RetentionPolicy = $CurrRetentionHold.RetentionPolicy - $RetentionPolicyTag = ((Get-RetentionPolicy -Identity $RetentionPolicy).RetentionPolicyTagLinks) -join "," - - if (($CurrRetentionHold.StartDateForRetentionHold) -ne $Empy) { - $StartDateForRetentionHold = ($CurrRetentionHold.StartDateForRetentionHold).ToString().split(" ") | Select-Object -Index 0 - } - else { - $StartDateForRetentionHold = "-" - } - if (($CurrRetentionHold.EndDateForRetentionHold) -ne $Empy) { - $EndDateForRetentionHold = ($CurrRetentionHold.EndDateForRetentionHold).ToString().split(" ") | Select-Object -Index 0 - } - else { - $EndDateForRetentionHold = "-" - } - - Write-Progress "Retrieving the Retention Hold Information for the User: $global:MailboxName" "Processed Mailboxes Count: $global:ExportedMailbox" - - #ExportResult - $ExportResult = @{'Mailbox Name' = $global:MailboxName; 'Mailbox Type' = $global:RecipientTypeDetails; 'UPN' = $global:UPN; 'Retention Policy Name' = $RetentionPolicy; 'Start Date for Retention Hold' = $StartDateForRetentionHold; 'End Date for Retention Hold' = $EndDateForRetentionHold; 'Retention Policy Tag' = $RetentionPolicyTag } - $ExportResults = New-Object PSObject -Property $ExportResult - $ExportResults | Select-object 'Mailbox Name', 'UPN', 'Mailbox Type', 'Retention Policy Name', 'Start Date for Retention Hold', 'End Date for Retention Hold', 'Retention Policy Tag' | Export-csv -path $global:ExportCSVFileName -NoType -Append -Force -} - -Function GetDefaultReport { - GetBasicData - $LitigationHold = $CurrMailbox.LitigationHoldEnabled - $ComplianceTag = $CurrMailbox.ComplianceTagHoldApplied - $RetentionHold = $CurrMailbox.RetentionHoldEnabled - $ArchiveStatus = $CurrMailbox.ArchiveStatus - $RetentionPolicy = $CurrMailbox.RetentionPolicy - - $LitigationDuration = $CurrMailbox.LitigationHoldDuration - if ($LitigationDuration -ne "Unlimited") { - $LitigationDuration = ($LitigationDuration).split(".") | Select-Object -Index 0 - } - $InPlaceHold = $CurrMailbox.InPlaceHolds - if ($InPlaceHold -ne $Empty) { - $InPlaceHold = "Enabled" - } - else { - $InPlaceHold = "Disabled" - } - - Write-Progress "Retrieving All Active Holds Applied on the User: $global:MailboxName" "Processed Mailboxes Count: $global:ExportedMailbox" - - #ExportResult - $ExportResult = @{'Mailbox Name' = $global:MailboxName; 'Mailbox Type' = $global:RecipientTypeDetails; 'UPN' = $global:UPN; 'Archive Status' = $ArchiveStatus; 'Litigation Hold Enabled' = $LitigationHold; 'Compliance Tag Hold Enabled' = $ComplianceTag; 'Retention Hold Enabled' = $RetentionHold; 'Litigation Duration' = $LitigationDuration; 'In-Place Hold Status' = $InPlaceHold; 'Retention Policy Name' = $RetentionPolicy } - $ExportResults = New-Object PSObject -Property $ExportResult - $ExportResults | Select-object 'Mailbox Name', 'UPN', 'Mailbox Type', 'Archive Status', 'Litigation Hold Enabled', 'In-Place Hold Status', 'Retention Hold Enabled', 'Compliance Tag Hold Enabled', 'Litigation Duration', 'Retention Policy Name' | Export-csv -path $global:ExportCSVFileName -NoType -Append -Force - -} -Function ConnectToExchange { - $Exchange = (get-module ExchangeOnlineManagement -ListAvailable).Name - if ($Exchange -eq $null) { - Write-host "Important: ExchangeOnline PowerShell module is unavailable. It is mandatory to have this module installed in the system to run the script successfully." - $confirm = Read-Host Are you sure you want to install module? [Y] Yes [N] No - if ($confirm -match "[yY]") { - Write-host "Installing ExchangeOnlineManagement" - Install-Module ExchangeOnlineManagement -Repository PSGallery -AllowClobber -Force - Write-host "ExchangeOnline PowerShell module is installed in the machine successfully." - } - elseif ($confirm -cnotmatch "[yY]" ) { - Write-host "Exiting. `nNote: ExchangeOnline PowerShell module must be available in your system to run the script." - Exit - } - } - #Storing credential in script for scheduling purpose/Passing credential as parameter - if (($UserName -ne "") -and ($Password -ne "")) { - $SecuredPassword = ConvertTo-SecureString -AsPlainText $Password -Force - $Credential = New-Object System.Management.Automation.PSCredential $UserName, $SecuredPassword - Connect-ExchangeOnline -Credential $Credential -ShowProgress $false | Out-Null - } - else { - Connect-ExchangeOnline | Out-Null - } - Write-Host "ExchangeOnline PowerShell module is connected successfully" - #End of Connecting Exchange Online -} - -ConnectToExchange -$global:ExportedMailbox = 0 -RetrieveAllHolds - -if ((Test-Path -Path $global:ExportCSVFileName) -eq "True") { - Write-Host "The output file available in $global:ExportCSVFileName" -ForegroundColor Green - write-host "There are $global:ExportedMailbox mailboxes records in the output file" -ForegroundColor Cyan - $prompt = New-Object -ComObject wscript.shell - $userInput = $prompt.popup("Do you want to open output file?", 0, "Open Output File", 4) - If ($userInput -eq 6) { - Invoke-Item "$global:ExportCSVFileName" - } -} -else { - Write-Host "No data found with the specified criteria" -} -Disconnect-ExchangeOnline -Confirm:$false -InformationAction Ignore -ErrorAction SilentlyContinue -Write-Host "Disconnected active ExchangeOnline session" -ForegroundColor Green diff --git a/Private/Common.ps1 b/Private/Common.ps1 new file mode 100644 index 0000000..1b6eabe --- /dev/null +++ b/Private/Common.ps1 @@ -0,0 +1,36 @@ +# Shared helpers. Dot-source from scripts; no administrative side effects. +function Export-ToolkitReport { + [CmdletBinding()] + param( + [Parameter(Mandatory)][AllowEmptyCollection()][object[]]$InputObject, + [Parameter(Mandatory)][string]$Path, + [switch]$Force + ) + $fullPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) + $parent = Split-Path -Parent $fullPath + if (-not (Test-Path -LiteralPath $parent -PathType Container)) { throw "Output directory does not exist: $parent" } + if ((Test-Path -LiteralPath $fullPath) -and -not $Force) { throw "Report already exists: $fullPath. Choose another path or use -Force." } + if ($InputObject.Count -eq 0) { Write-Warning 'No rows returned. No report was written.'; return } + $temporary = Join-Path $parent ([guid]::NewGuid().ToString() + '.tmp') + try { + $InputObject | Export-Csv -LiteralPath $temporary -NoTypeInformation -Encoding utf8 -ErrorAction Stop + Move-Item -LiteralPath $temporary -Destination $fullPath -Force:$Force -ErrorAction Stop + } finally { + if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -ErrorAction Stop } + } +} +function Assert-ToolkitGraphContext { + [CmdletBinding()] + param([Parameter(Mandatory)][string]$TenantId) + $context = Get-MgContext -ErrorAction Stop + if (-not $context -or $context.TenantId -ne $TenantId) { throw "Connect-MgGraph to tenant '$TenantId' with the documented permissions first." } +} +function Read-ToolkitIdentityList { + [CmdletBinding()] + [OutputType([string])] + param([Parameter(Mandatory)][string]$Path) + $items = @(Get-Content -LiteralPath $Path -ErrorAction Stop | ForEach-Object { $_.Trim() } | + Where-Object { $_ -and -not $_.StartsWith('#') } | Sort-Object -Unique) + if ($items.Count -eq 0) { throw 'The identity list is empty.' } + $items | ForEach-Object { [string]$_ } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..0301e1e --- /dev/null +++ b/README.md @@ -0,0 +1,153 @@ +# PowerShell SecOps scripts + +A collection of scripts written and accumulated by John Skinner for Active +Directory, Azure, Microsoft Graph, Exchange Online and Windows administration. + +## Start here + +Download or clone the **whole repository**: scripts share `Private/Common.ps1`. +Run a script explicitly; do not run every file as a batch. Read its help first: + +```powershell +Get-Help .\Copy_AD_UserGroups.ps1 -Full +.\Copy_AD_UserGroups.ps1 -SourceUser alice -TargetUser bob -Server dc.example.com -WhatIf +``` + +Windows PowerShell 5.1 and PowerShell 7 on Windows are validation targets. Install +only the administrative modules needed for your task; the scripts never install +modules automatically. ActiveDirectory requires RSAT/domain connectivity. Defender, +the date picker, credential validation and browser collection require Windows. +The date picker additionally requires an interactive STA session. + +Authenticate to cloud services yourself before running reports. Verify the tenant, +subscription and account. Graph scripts require `-TenantId` and reject a different +connected tenant. Exchange policy changes require exactly one connected session. + +```powershell +# Install from your organization's approved source and authenticate interactively. +Connect-MgGraph -TenantId 'YOUR-TENANT-ID' -Scopes 'Device.Read.All' +.\Export-GraphDevices.ps1 -TenantId 'YOUR-TENANT-ID' -OutputPath .\devices.csv +``` + +For unattended jobs use the service's supported certificate or managed-identity +flow with the documented permissions and roles. Do not embed passwords or tokens. +Scripts reuse the caller's session and do not disconnect it. + +## Script catalog + +| Area / script | Purpose | Prerequisites / access | Changes systems? | +|---|---|---|---| +| `Export-ADGroupMembers.ps1` | Direct/recursive members, including object type | ActiveDirectory; directory read | No | +| `Export-ADGroupMemberCreationDates.ps1` | Creation dates of user members | ActiveDirectory; directory read | No | +| `GrabAD-GroupMembers.ps1` | Compatibility entry point for group report | Same as group report | No | +| `Get-ADUserEnabledStatus.ps1` | Enabled/disabled status from an identity list | ActiveDirectory; directory read | No | +| `Get-ADPasswordNeverExpires.ps1` | Non-expiring password configuration | ActiveDirectory; directory read | No | +| `Get-ADExpiredAccounts.ps1` | Enabled expired accounts; optional no-expiration report | ActiveDirectory; directory read | No | +| `Get-ADMissingPhoneNumbers.ps1` | Enabled users missing all phone fields | ActiveDirectory; directory read | No | +| `Get-ADRecentlyCreatedUsers.ps1` | Recently created users | ActiveDirectory; directory read | No | +| `Get-ADUserCreationAudit.ps1` | Match creator evidence in DC event 4720 by target SID | AD read; DC Security-log read; retained account-management auditing | No | +| `Get-ADUserLoginData.ps1` | Password/logon metadata | ActiveDirectory; directory read | No | +| `Copy_AD_UserGroups.ps1` | Copy reviewed direct memberships | ActiveDirectory; delegated group management | **Yes** | +| `verify-credentials.ps1` | Validate one credential against a domain | DirectoryServices; domain connectivity | Authentication attempt; can affect lockout counters | +| `ExportNSG_All_BySubscription.ps1` | NSG rule audit with subscription identity and plural fields | Az.Accounts, Az.Network; Reader in selected subscriptions | Session context temporarily switched and restored | +| `Export-GraphDevices.ps1` | Directory-device report with optional filters | Graph Authentication + Identity.DirectoryManagement; Device.Read.All | No | +| `Get-GraphDeviceCompliance.ps1` | Directory compliance flags | Same as device report | No | +| `Find-GraphDevice.ps1` | Device display-name prefix search | Same as device report | No | +| `Get-GraphWindowsDevices.ps1` | Windows directory devices | Same as device report | No | +| `GraphAPI-GuestUserStatus.ps1` | Latest available interactive guest sign-in | Graph Users + Reports; User.Read.All, AuditLog.Read.All; supported role/license | No | +| `Set-GraphDeviceExtensionAttribute.ps1` | Set one selected attribute, then read it back | Graph device update/read; see permission notes below | **Yes** | +| `Export-O365MailboxHolds.ps1` | Mailbox hold flags and retention-processing pauses | ExchangeOnlineManagement; mailbox-read RBAC | No | +| `Export-O365BlockedSendersAndDomains.ps1` | Selected anti-spam policy's blocked entries | ExchangeOnlineManagement; policy-read RBAC | No | +| `BlockLegacyAuthentication.ps1` | Apply a blocking policy or restore saved assignments | ExchangeOnlineManagement; policy/user-management RBAC | **Yes** | +| `DefenderToolkit.ps1` | Explicit Defender status, scans and configuration actions | Defender module; elevation for changes | **Yes**, except Status/Preferences/Detections | +| `Get-BrowserHistory.ps1` | Chrome/Edge/Firefox SQLite history with UTC timestamps | Windows; sqlite3 >= 3.33 on targets; profile-read rights; WinRM for remote collection | Temporary snapshot/job files only | +| `Get-ComputerInfo.ps1` | OS, logged-on user and hotfix inventory | CIM/WinRM; target permissions | Temporary CIM session only | +| `Get-RemoteSerialNumber.ps1` | BIOS/serial inventory | CIM/WinRM; target permissions | Temporary CIM session only | +| `Get-WindowsEvents.ps1` | Selected log and time range | Windows Event Log remote access; log-read rights | No | +| `Date_Selector.ps1` | Return selected date or no value on cancel | Interactive Windows desktop; STA | No | + +Azure Firewall commands are now [reference examples](docs/AzureFirewallExamples.md), +not an executable sequence of placeholder changes. + +## Change safety and recovery + +Mutating scripts support `-WhatIf` and high-impact confirmation. Preview first. +`-Confirm:$false` deliberately bypasses prompts; use it only after reviewing targets. +Protected AD groups are skipped unless explicitly included. This check does not +identify every custom or nested privilege path; use `-GroupIdentity` to allow only +reviewed source groups. Primary-group membership is not copied. A failed operation +stops the script; previous successful operations are not automatically rolled back. +Record returned `Added` rows if you need to reverse a membership change. + +Exchange policy apply and restore are separate invocations: + +```powershell +.\BlockLegacyAuthentication.ps1 -Mode Apply -UserListPath .\users.txt -BackupPath .\before.csv -WhatIf +# Apply without -WhatIf only after reviewing its targets. Keep the backup secure. +.\BlockLegacyAuthentication.ps1 -Mode Restore -RestoreSavedAssignments -BackupPath .\before.csv -WhatIf +``` + +Apply refuses to overwrite an existing backup and validates an existing policy's +Basic-authentication flags. Backups include organization identity; restore refuses a +wrong organization. Restore affects every user in the supplied backup. Review +partial failures before restoring. Restoring user assignments does not delete the +created policy or undo other administrators' later changes. Authentication changes +can take time to propagate; this does not validate a client's actual sign-in path. + +Defender protection reductions require `-AllowProtectionReduction` plus +confirmation. The old passive-mode registry action was removed because OS, +onboarding and tamper-protection requirements make a generic registry toggle +unsafe. Use [Microsoft's supported configuration](https://learn.microsoft.com/en-us/defender-endpoint/microsoft-defender-antivirus-windows-server-configure). +Remove an exclusion with `-Action RemoveExclusion -Path ...`; restore real-time +monitoring with `-Action EnableRealtime`. Managed policy can reject local changes. + +Device extension updates require an explicit object ID, attribute number, value +and tenant. Output includes the previous value; retain it securely for recovery. +Delegated Graph device updates currently require `Directory.AccessAsUser.All` and a +supported role, while application updates use `Device.ReadWrite.All`; read-back +also needs read access. Do not substitute a guessed narrower delegated scope. +See the [API's OS and permission restrictions](https://learn.microsoft.com/en-us/graph/api/device-update?view=graph-rest-1.0). + +## Report handling and limitations + +Reports return objects; use `-OutputPath` where supported for UTF-8 CSV. The output +directory must exist. Existing reports require `-Force`; runs never append to old +results. An empty result warns and writes no file. Reports are audit data, not +restorable configuration backups. A directory, permission or service failure is +reported as an error rather than silently treated as "no users" or "no activity". + +- Treat report contents as untrusted text when importing into a spreadsheet; + source values may begin with formula characters. CSV output preserves evidence. +- Protect reports, backups and browser URLs with appropriate filesystem access + and retention. Do not commit them; common report/database formats are ignored. +- No retained sign-in or event record does not prove an account was never used or + has no creator. Specify all relevant DCs/collectors for creation audits. +- AD `LastLogonDate` is replicated and approximate. +- Graph `IsCompliant` is nullable directory metadata, not full Intune compliance. +- Mailbox `RetentionHoldEnabled` pauses MRM; it is not a preservation hold. The + mailbox report does not resolve organization-wide retention/eDiscovery coverage. +- Browser collection uses read-only SQLite backups including WAL data. It does + not close browsers. Locked/inaccessible/corrupt databases fail visibly. It does + not recover deleted records or collect legacy IE TypedURLs. +- `-AsJob` returns job objects. Retrieve results and errors with + `Receive-Job -Wait -AutoRemoveJob`. Remote hosts need sqlite3 installed themselves. + +## Validation and contribution + +Use Pester **5.7.1**, PSScriptAnalyzer **1.24.0**, and sqlite3 **>=3.33** on Windows. +Install dependencies from your approved source, then run: + +```powershell +.\tools\Test-Repository.ps1 +``` + +GitHub Actions runs parsing, default analyzer error/warning checks, mock-based +regressions and synthetic SQLite integration tests in Windows PowerShell and pwsh. +It has read-only repository permissions and no production credentials. SQLite and +Actions dependencies are pinned; Dependabot proposes Actions updates. Module and +SQLite version/hash updates require deliberate review. + +Offline validation cannot certify tenant roles, policy propagation, remoting, +Defender policy or every browser version. Validate those in a non-production +environment before operational use. See [migration notes](docs/Migration.md), +[contribution guidance](CONTRIBUTING.md), and [third-party provenance](THIRD_PARTY.md). diff --git a/Set-GraphDeviceExtensionAttribute.ps1 b/Set-GraphDeviceExtensionAttribute.ps1 new file mode 100644 index 0000000..745493c --- /dev/null +++ b/Set-GraphDeviceExtensionAttribute.ps1 @@ -0,0 +1,33 @@ +<# +.SYNOPSIS +Update one selected device extension attribute in the connected Graph tenant. +.DESCRIPTION +Connect-MgGraph first. Delegated use requires Directory.AccessAsUser.All and a +supported role; application use requires Device.ReadWrite.All. See Graph's update +device documentation for OS and identity restrictions. DeviceObjectId is the +Graph directory object id, not the device registration id. Requires read access +for verification. No permissions are requested automatically. +.EXAMPLE +.\Set-GraphDeviceExtensionAttribute.ps1 -TenantId TENANT-GUID -DeviceObjectId OBJECT-GUID -AttributeNumber 6 -Value 'Finance' -WhatIf +#> +[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] +param( + [Parameter(Mandatory)][string]$TenantId, + [Parameter(Mandatory)][guid]$DeviceObjectId, + [Parameter(Mandatory)][ValidateRange(1,15)][int]$AttributeNumber, + [Parameter(Mandatory)][AllowEmptyString()][string]$Value +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +Assert-ToolkitGraphContext -TenantId $TenantId +$attribute = "extensionAttribute$AttributeNumber" +$device = Get-MgDevice -DeviceId $DeviceObjectId -Property id,displayName,extensionAttributes -ErrorAction Stop +$before = $device.ExtensionAttributes.$attribute +if ($before -eq $Value) { + [pscustomobject]@{ DeviceId = $DeviceObjectId; Attribute = $attribute; Previous = $before; Value = $Value; Status = 'Unchanged' } +} elseif ($PSCmdlet.ShouldProcess("$($device.DisplayName) ($DeviceObjectId) in $TenantId", "Set $attribute to '$Value' (previous '$before')")) { + Update-MgDevice -DeviceId $DeviceObjectId -BodyParameter @{ extensionAttributes = @{ $attribute = $Value } } -ErrorAction Stop + $after = Get-MgDevice -DeviceId $DeviceObjectId -Property extensionAttributes -ErrorAction Stop + if ($after.ExtensionAttributes.$attribute -ne $Value) { throw 'Attribute verification failed.' } + [pscustomobject]@{ DeviceId = $DeviceObjectId; Attribute = $attribute; Previous = $before; Value = $Value; Status = 'Updated' } +} diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 0000000..25f0f1d --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,16 @@ +# Third-party provenance + +The previous `O365 Holds Enabled Mailboxes` file credited the O365Reports Team and +linked to https://o365reports.com/2021/06/29/export-office-365-mailbox-holds-report-using-powershell/. +It has been replaced by `Export-O365MailboxHolds.ps1`, a smaller implementation of +mailbox-property reporting with explicit retention-pause semantics. The old source +and credit remain in Git history. Its original redistribution terms have not been +verified; the repository license must not be taken as a relicensing of upstream +material or history. + +Other accumulated scripts may also have outside origins. Existing history and +attribution are preserved. Do not claim new ownership of upstream contributions. + +`CODE_OF_CONDUCT.md` retains its Contributor Covenant attribution. Pester, +PSScriptAnalyzer, SQLite and GitHub Actions are external dependencies under their +respective terms; no downloaded dependency binaries are committed here. diff --git a/docs/AzureFirewallExamples.md b/docs/AzureFirewallExamples.md new file mode 100644 index 0000000..f881b9d --- /dev/null +++ b/docs/AzureFirewallExamples.md @@ -0,0 +1,28 @@ +# Azure Firewall examples + +The former `AzureFirewallCommands.ps1` was a sequence of examples rather than a +runnable script. It used placeholder resources, reused collection names and +priorities, and included an allow-all UDP rule. It has been replaced with this +reference so executing the script collection cannot accidentally apply examples. +The original remains available in Git history. + +Use an authenticated Az session with Reader access to inspect a specific firewall: + +```powershell +$context = Get-AzContext +if (-not $context) { throw 'Connect-AzAccount to the intended tenant first.' } +# Supply actual names. Check $context.Tenant and $context.Subscription first. +$firewall = Get-AzFirewall -ResourceGroupName 'YOUR-RESOURCE-GROUP' -Name 'YOUR-FIREWALL' -DefaultProfile $context -ErrorAction Stop +$firewall.ApplicationRuleCollections +$firewall.NetworkRuleCollections +``` + +Before writing a change, determine whether the firewall uses classic rule +collections or Azure Firewall Policy. Use the matching management commands. +Select exact source ranges, destinations, protocols and ports; avoid wildcard +allow rules. Export the current configuration, review priorities and existing +collection names, and preview the write with `-WhatIf`. Use the supported write +command only after reviewing the complete resulting configuration. An in-memory +`AddNetworkRuleCollection()` call alone does not persist an Azure firewall change. + +See [Azure Firewall PowerShell documentation](https://learn.microsoft.com/en-us/azure/firewall/deploy-ps). diff --git a/docs/Migration.md b/docs/Migration.md new file mode 100644 index 0000000..99401ee --- /dev/null +++ b/docs/Migration.md @@ -0,0 +1,44 @@ +# Migration notes + +The safety update changes command-line interfaces. Read `Get-Help SCRIPT -Full` +before using an existing scheduled task. Prompts and hardcoded values have been +replaced with explicit parameters. The complete checkout is required for helpers. + +| Previous path | Current path | +|---|---| +| `!CODE_OF_CONDUCT.md` | `CODE_OF_CONDUCT.md` | +| `!LICENSE` | `LICENSE` | +| `!README.md` | `README.md` | +| `AD Group Member Extractor` | `Export-ADGroupMembers.ps1` | +| `AD GroupMember_AccountCreationDate` | `Export-ADGroupMemberCreationDates.ps1` | +| `AD-PasswordNeverExpires` | `Get-ADPasswordNeverExpires.ps1` | +| `ADEnable-DisabledUsers-fromList` | `Get-ADUserEnabledStatus.ps1` | +| `ADUsers - Last 30 days` | `Get-ADRecentlyCreatedUsers.ps1` | +| `ADUserSearch - ForCreator` | `Get-ADUserCreationAudit.ps1` | +| `AzureAD-GraphAPI ExtensionAttributeUpdate` | `Set-GraphDeviceExtensionAttribute.ps1` | +| `DefenderToolkit` | `DefenderToolkit.ps1` | +| `Export-0365 Blocked Senders and Domains` | `Export-O365BlockedSendersAndDomains.ps1` | +| `Get-ADExpired_Accounts` | `Get-ADExpiredAccounts.ps1` | +| `Get-ADMissingPhoneNumbers` | `Get-ADMissingPhoneNumbers.ps1` | +| `GrabAD-UserLoginData` | `Get-ADUserLoginData.ps1` | +| `MSGraph API Get all Devices` | `Export-GraphDevices.ps1` | +| `MSGraph API Get All Devices & Compliant` | `Get-GraphDeviceCompliance.ps1` | +| `MSGraph API Search for Device` | `Find-GraphDevice.ps1` | +| `MSGraphAPI Get all devices with various info` | `Get-GraphWindowsDevices.ps1` | +| `O365 Holds Enabled Mailboxes` | `Export-O365MailboxHolds.ps1` | +| `AzureFirewallCommands.ps1` | `docs/AzureFirewallExamples.md` (reference only) | + +Behavior changes: + +- The enabled-status report never enables accounts. +- Expired-account reporting now filters expiration dates; use `-WithoutExpiration` for the no-expiration report described by the old help. +- Creator reporting uses Security event 4720 evidence rather than a nonexistent generic CreatedBy property. +- Graph device search now accepts a display-name prefix, and Windows filtering uses an OS filter. +- Reports no longer append to old CSVs. Use a fresh path or explicit `-Force`. +- Exchange apply never automatically restores policy assignments. Restore requires its own invocation and the saved backup. +- Defender uses explicit actions instead of an interactive menu. Passive-mode registry editing was removed. +- Browser search terms are literal substrings; user selection is a wildcard pattern. SQLite is required on each target. +- The mailbox hold report accepts `-HoldType` instead of three overlapping switches; it no longer accepts usernames or plaintext passwords. +- The date picker returns a DateTime rather than setting a caller variable. + +Original author credit and the pre-update files remain available in Git history. diff --git a/tests/BrowserHistory.Tests.ps1 b/tests/BrowserHistory.Tests.ps1 new file mode 100644 index 0000000..533e8f5 --- /dev/null +++ b/tests/BrowserHistory.Tests.ps1 @@ -0,0 +1,48 @@ +BeforeAll { + $repo = Split-Path $PSScriptRoot -Parent + $sqliteCommand = Get-Command sqlite3 -CommandType Application -ErrorAction SilentlyContinue + $sqlite = if ($env:TOOLKIT_TEST_SQLITE) { $env:TOOLKIT_TEST_SQLITE } elseif ($sqliteCommand) { $sqliteCommand.Source } else { $null } +} +Describe 'Browser history SQLite integration' -Skip:($env:OS -ne 'Windows_NT') { + BeforeEach { + if (-not $sqlite) { throw 'SQLite >= 3.33 is required for the browser integration tests. Set TOOLKIT_TEST_SQLITE or install sqlite3 in PATH.' } + $profileRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString()) + $chrome = Join-Path $profileRoot 'alice/AppData/Local/Google/Chrome/User Data/Profile 1' + $firefox = Join-Path $profileRoot 'alice/AppData/Roaming/Mozilla/Firefox/Profiles/example.default-release' + $null = New-Item -ItemType Directory -Path $chrome,$firefox -Force + $chromeDb = Join-Path $chrome History + $firefoxDb = Join-Path $firefox places.sqlite + & $sqlite $chromeDb "CREATE TABLE urls (url TEXT,title TEXT,visit_count INTEGER,last_visit_time INTEGER); INSERT INTO urls VALUES ('https://example.com/a?x=1','Éxample',3,13380163200000000),('https://other.test','Other',1,13380163200000000);" + if ($LASTEXITCODE) { throw 'Chrome fixture creation failed.' } + & $sqlite $firefoxDb "CREATE TABLE moz_places (url TEXT,title TEXT,visit_count INTEGER,last_visit_date INTEGER); INSERT INTO moz_places VALUES ('https://example.com/firefox','Firefox',2,1735689600000000);" + if ($LASTEXITCODE) { throw 'Firefox fixture creation failed.' } + } + It 'queries non-default Chromium and modern Firefox profiles with correct UTC epochs' { + $rows = @(& "$repo/Get-BrowserHistory.ps1" -ComputerName localhost -ProfileRoot $profileRoot -SqlitePath $sqlite -UserName alice -SearchTerm example.com) + $rows.Count | Should -Be 2 + ($rows | Where-Object Browser -eq Chrome).LastVisitUtc | Should -Be '2025-01-01T00:00:00.000Z' + ($rows | Where-Object Browser -eq Firefox).LastVisitUtc | Should -Be '2025-01-01T00:00:00.000Z' + ($rows | Where-Object Browser -eq Chrome).VisitCount | Should -Be 3 + $rows[0].DomainName | Should -Be 'example.com' + $rows[0].UserName | Should -Be alice + ($rows | Where-Object Browser -eq Chrome).Title | Should -Be 'Éxample' + } + It 'runs a complete collector in the local job without missing helper functions' { + $job = & "$repo/Get-BrowserHistory.ps1" -ComputerName localhost -ProfileRoot $profileRoot -SqlitePath $sqlite -AsJob -SearchTerm firefox + try { + $rows = @($job | Receive-Job -Wait -ErrorAction Stop) + $job.State | Should -Be Completed + $rows.Count | Should -Be 1 + $rows[0].Browser | Should -Be Firefox + } finally { $job | Remove-Job -Force } + } + It 'treats the search term literally rather than as a regular expression' { + $rows = @(& "$repo/Get-BrowserHistory.ps1" -ComputerName localhost -ProfileRoot $profileRoot -SqlitePath $sqlite -SearchTerm '?x=1') + $rows.Count | Should -Be 1 + $rows[0].Url | Should -Be 'https://example.com/a?x=1' + } + It 'reports SQLite/schema errors rather than returning a clean empty history' { + & $sqlite $chromeDb 'DROP TABLE urls;' + { & "$repo/Get-BrowserHistory.ps1" -ComputerName localhost -ProfileRoot $profileRoot -SqlitePath $sqlite } | Should -Throw '*SQLite query failed*' + } +} diff --git a/tests/Toolkit.Tests.ps1 b/tests/Toolkit.Tests.ps1 new file mode 100644 index 0000000..81d7293 --- /dev/null +++ b/tests/Toolkit.Tests.ps1 @@ -0,0 +1,319 @@ +BeforeAll { + $repo = Split-Path $PSScriptRoot -Parent + $testComputer = 'fixture-host.example.test' + . "$repo/Private/Common.ps1" + # Fail-closed stubs allow mocks without installing or authenticating admin modules. + function Get-ADUser { [CmdletBinding()] param($Identity,$Server,$Properties,$Filter,[pscredential]$Credential) throw 'Unmocked AD call' } + function Get-ADGroup { [CmdletBinding()] param($Identity,$Server,$Properties) throw 'Unmocked AD call' } + function Add-ADGroupMember { [CmdletBinding(SupportsShouldProcess)] param($Identity,$Members,$Server) throw 'Unmocked AD mutation' } + function Get-ConnectionInformation { [CmdletBinding()] param() throw 'Unmocked Exchange call' } + function Get-OrganizationConfig { [CmdletBinding()] param() throw 'Unmocked Exchange call' } + function Get-AuthenticationPolicy { [CmdletBinding()] param($Identity) throw 'Unmocked Exchange call' } + function New-AuthenticationPolicy { [CmdletBinding(SupportsShouldProcess)] param($Name) throw 'Unmocked Exchange mutation' } + function Get-User { [CmdletBinding()] param($Identity) throw 'Unmocked Exchange call' } + function Set-User { [CmdletBinding(SupportsShouldProcess)] param($Identity,$AuthenticationPolicy) throw 'Unmocked Exchange mutation' } + function Get-AzContext { [CmdletBinding()] param() throw 'Unmocked Azure call' } + function Set-AzContext { [CmdletBinding()] param($SubscriptionId,$Tenant,$Scope,$Context) throw 'Unmocked Azure call' } + function Get-AzSubscription { [CmdletBinding()] param($TenantId) throw 'Unmocked Azure call' } + function Get-AzNetworkSecurityGroup { [CmdletBinding()] param($DefaultProfile) throw 'Unmocked Azure call' } + function Get-MgContext { [CmdletBinding()] param() throw 'Unmocked Graph call' } + function Get-MgUser { [CmdletBinding()] param([switch]$All,$Filter,$Property) throw 'Unmocked Graph call' } + function Get-MgAuditLogSignIn { [CmdletBinding()] param($Filter,$Top) throw 'Unmocked Graph call' } + function Get-MgDevice { [CmdletBinding()] param([switch]$All,$Filter,$Property,$DeviceId) throw 'Unmocked Graph call' } + function Update-MgDevice { [CmdletBinding()] param($DeviceId,$BodyParameter) throw 'Unmocked Graph mutation' } + function Get-Mailbox { [CmdletBinding()] param([switch]$IncludeInactiveMailbox,$ResultSize) throw 'Unmocked Exchange call' } +} + +Describe 'Report files' { + It 'preserves Unicode and refuses to overwrite or append existing results' { + $path = Join-Path $TestDrive 'report.csv' + Export-ToolkitReport -InputObject @([pscustomobject]@{ Name = 'Ålice' }) -Path $path + (Import-Csv $path).Name | Should -Be 'Ålice' + { Export-ToolkitReport -InputObject @([pscustomobject]@{Name='Bob'}) -Path $path } | Should -Throw '*already exists*' + (Import-Csv $path).Name | Should -Be 'Ålice' + Export-ToolkitReport -InputObject @([pscustomobject]@{Name='Bob'}) -Path $path -Force + @(Import-Csv $path).Count | Should -Be 1 + (Import-Csv $path).Name | Should -Be 'Bob' + } + It 'writes no file for an empty result and rejects a missing directory' { + $path = Join-Path $TestDrive 'empty.csv' + Export-ToolkitReport -InputObject @() -Path $path -WarningAction SilentlyContinue + Test-Path $path | Should -BeFalse + { Export-ToolkitReport -InputObject @([pscustomobject]@{Name='A'}) -Path (Join-Path $TestDrive 'missing/report.csv') } | Should -Throw '*directory*' + } + It 'normalizes and deduplicates identity lists' { + $path = Join-Path $TestDrive 'users.txt' + @(' alice ', '# comment', '', 'alice', 'bob') | Set-Content $path + @(Read-ToolkitIdentityList $path).Count | Should -Be 2 + } +} + +Describe 'AD membership safeguards' { + BeforeEach { + Mock Get-ADUser { + if ($Identity -eq 'alice') { [pscustomobject]@{ DistinguishedName='CN=alice'; memberOf=@('CN=Finance','CN=Admins') } } + else { [pscustomobject]@{ DistinguishedName='CN=bob'; memberOf=@() } } + } + Mock Get-ADGroup { + if ($Identity -eq 'CN=Admins') { [pscustomobject]@{Name='Admins';DistinguishedName='CN=Admins';adminCount=1;SID='S-1-5-21-100-512'} } + else { [pscustomobject]@{Name='Finance';DistinguishedName='CN=Finance';adminCount=0;SID='S-1-5-21-100-1001'} } + } + Mock Add-ADGroupMember {} + } + It 'previews changes without writing and skips protected groups' { + $rows = @(& "$repo/Copy_AD_UserGroups.ps1" -SourceUser alice -TargetUser bob -Server dc.example.com -WhatIf) + ($rows | Where-Object Group -eq Admins).Status | Should -Be 'SkippedProtectedGroup' + ($rows | Where-Object Group -eq Finance).Status | Should -Be 'Preview' + Should -Invoke Add-ADGroupMember -Times 0 + Should -Invoke Get-ADUser -Times 2 -ParameterFilter { $Server -eq 'dc.example.com' } + } + It 'does not add memberships that already exist' { + Mock Get-ADUser { [pscustomobject]@{DistinguishedName="CN=$Identity";memberOf=@('CN=Finance')} } + $rows = @(& "$repo/Copy_AD_UserGroups.ps1" -SourceUser alice -TargetUser bob -Server dc -Confirm:$false) + $rows[0].Status | Should -Be 'AlreadyMember' + Should -Invoke Add-ADGroupMember -Times 0 + } + It 'stops on a failed addition instead of claiming success' { + Mock Add-ADGroupMember { throw 'Access denied' } + { & "$repo/Copy_AD_UserGroups.ps1" -SourceUser alice -TargetUser bob -Server dc -Confirm:$false } | Should -Throw '*Access denied*' + } + It 'fails if read-back does not confirm the addition' { + { & "$repo/Copy_AD_UserGroups.ps1" -SourceUser alice -TargetUser bob -Server dc -Confirm:$false } | Should -Throw '*verification failed*' + } +} + +Describe 'Exchange authentication policy safety' { + BeforeEach { + Mock Get-ConnectionInformation { [pscustomobject]@{State='Connected'} } + Mock Get-OrganizationConfig { [pscustomobject]@{Guid='tenant-one'} } + Mock Get-AuthenticationPolicy { [pscustomobject]@{Name='BlockBasicAuth';AllowBasicAuthImap=$false;AllowBasicAuthSmtp=$false} } + Mock Get-User { [pscustomobject]@{UserPrincipalName='alice@example.com';AuthenticationPolicy='PreviousPolicy'} } + Mock New-AuthenticationPolicy {} + Mock Set-User {} + $usersPath = Join-Path $TestDrive 'auth-users.txt' + 'alice@example.com' | Set-Content $usersPath + $backupPath = Join-Path $TestDrive ([guid]::NewGuid().ToString()+'.csv') + } + It 'WhatIf neither writes a backup nor changes or creates policies' { + & "$repo/BlockLegacyAuthentication.ps1" -Mode Apply -UserListPath $usersPath -BackupPath $backupPath -WhatIf + Test-Path $backupPath | Should -BeFalse + Should -Invoke Set-User -Times 0 + Should -Invoke New-AuthenticationPolicy -Times 0 + } + It 'saves the previous policy before setting and never runs rollback on Apply' { + Mock Set-User { + Test-Path $backupPath | Should -BeTrue + (Import-Csv $backupPath).AuthenticationPolicy | Should -Be 'PreviousPolicy' + } + Mock Get-User { + if (Test-Path $backupPath) { [pscustomobject]@{UserPrincipalName='alice@example.com';AuthenticationPolicy='BlockBasicAuth'} } + else { [pscustomobject]@{UserPrincipalName='alice@example.com';AuthenticationPolicy='PreviousPolicy'} } + } + & "$repo/BlockLegacyAuthentication.ps1" -Mode Apply -UserListPath $usersPath -BackupPath $backupPath -Confirm:$false + Should -Invoke Set-User -Times 1 -Exactly -ParameterFilter { $AuthenticationPolicy -eq 'BlockBasicAuth' } + } + It 'does not overwrite a recovery file or mutate users when backup fails' { + 'existing recovery data' | Set-Content $backupPath + { & "$repo/BlockLegacyAuthentication.ps1" -Mode Apply -UserListPath $usersPath -BackupPath $backupPath -Confirm:$false } | Should -Throw '*already exists*' + Should -Invoke Set-User -Times 0 + } + It 'rejects an existing policy that allows Basic authentication' { + Mock Get-AuthenticationPolicy { [pscustomobject]@{Name='BlockBasicAuth';AllowBasicAuthImap=$true} } + { & "$repo/BlockLegacyAuthentication.ps1" -Mode Apply -UserListPath $usersPath -BackupPath $backupPath -Confirm:$false } | Should -Throw '*does not verifiably block*' + Should -Invoke Set-User -Times 0 + } + It 'restores a null assignment as null rather than an empty string' { + [pscustomobject]@{OrganizationId='tenant-one';Identity='alice@example.com';AuthenticationPolicy=''} | Export-Csv $backupPath + Mock Get-User { [pscustomobject]@{UserPrincipalName='alice@example.com';AuthenticationPolicy=$null} } + & "$repo/BlockLegacyAuthentication.ps1" -Mode Restore -RestoreSavedAssignments -BackupPath $backupPath -Confirm:$false + Should -Invoke Set-User -Times 1 -ParameterFilter { $null -eq $AuthenticationPolicy } + Should -Invoke New-AuthenticationPolicy -Times 0 + } + It 'refuses a backup from another organization before restoring anyone' { + [pscustomobject]@{OrganizationId='wrong-tenant';Identity='alice@example.com';AuthenticationPolicy='Old'} | Export-Csv $backupPath + { & "$repo/BlockLegacyAuthentication.ps1" -Mode Restore -RestoreSavedAssignments -BackupPath $backupPath -Confirm:$false } | Should -Throw '*wrong organization*' + Should -Invoke Set-User -Times 0 + } +} + +Describe 'AD domain selection and failures' { + It 'uses the requested domain and propagates directory outages' { + $path = Join-Path $TestDrive 'ad-users.txt' + 'alice' | Set-Content $path + Mock Get-ADUser { throw 'Directory unavailable' } + { & "$repo/Get-ADUserEnabledStatus.ps1" -Server selected.dc -UserListPath $path } | Should -Throw '*Directory unavailable*' + Should -Invoke Get-ADUser -Times 1 -ParameterFilter { $Server -eq 'selected.dc' } + } + It 'reports enabled status without changing accounts' { + $path = Join-Path $TestDrive 'ad-users-ok.txt' + 'alice' | Set-Content $path + Mock Get-ADUser { [pscustomobject]@{Name='Alice';Enabled=$false} } + $row = & "$repo/Get-ADUserEnabledStatus.ps1" -Server selected.dc -UserListPath $path + $row.Status | Should -Be Found + $row.Enabled | Should -BeFalse + } +} + +Describe 'Azure NSG reporting' { + BeforeEach { + Mock Get-AzContext { [pscustomobject]@{Tenant=[pscustomobject]@{Id='tenant'};Name='original'} } + Mock Get-AzSubscription { [pscustomobject]@{Id='sub1';Name='Production'} } + Mock Set-AzContext { [pscustomobject]@{Name='selected'} } + Mock Get-AzNetworkSecurityGroup { + [pscustomobject]@{ + Id='/subscriptions/sub1/nsg/nsg1';Name='nsg1';Location='eastus';ResourceGroupName='rg' + DefaultSecurityRules=@() + SecurityRules=@([pscustomobject]@{ + Name='multi';Priority=100;Direction='Inbound';Access='Allow';Protocol='Tcp';Description='Åudit' + SourceAddressPrefixes=@('10.0.0.0/24','10.0.1.0/24');SourceAddressPrefix=$null + SourcePortRanges=@('80','443');SourcePortRange=$null + DestinationAddressPrefixes=@('10.1.0.0/24');DestinationAddressPrefix=$null + DestinationPortRanges=@('8080','8443');DestinationPortRange=$null + SourceApplicationSecurityGroups=@([pscustomobject]@{Id='/asg/source'}) + DestinationApplicationSecurityGroups=@() + }) + } + } + } + It 'includes plural fields, ASGs and subscription identity without appending across runs' { + $path = Join-Path $TestDrive 'nsg.csv' + $row = & "$repo/ExportNSG_All_BySubscription.ps1" -TenantId tenant -SubscriptionId sub1 -OutputPath $path + $row.SubscriptionId | Should -Be sub1 + $row.SourceAddresses | Should -Be '10.0.0.0/24;10.0.1.0/24' + $row.SourcePorts | Should -Be '80;443' + $row.DestinationPorts | Should -Be '8080;8443' + $row.SourceApplicationSecurityGroups | Should -Be '/asg/source' + (Import-Csv $path).Description | Should -Be 'Åudit' + Should -Invoke Set-AzContext -Times 1 -ParameterFilter { $null -ne $Context -and $Context.Name -eq 'original' } + } + It 'restores the active context even when collection fails' { + Mock Get-AzNetworkSecurityGroup { throw 'Azure unavailable' } + { & "$repo/ExportNSG_All_BySubscription.ps1" -TenantId tenant -SubscriptionId sub1 -OutputPath (Join-Path $TestDrive 'bad.csv') } | Should -Throw '*Azure unavailable*' + Should -Invoke Set-AzContext -Times 1 -ParameterFilter { $null -ne $Context -and $Context.Name -eq 'original' } + } + It 'rejects unknown subscriptions without changing context' { + { & "$repo/ExportNSG_All_BySubscription.ps1" -TenantId tenant -SubscriptionId other -OutputPath (Join-Path $TestDrive 'bad.csv') } | Should -Throw '*not accessible*' + Should -Invoke Set-AzContext -Times 0 + } +} + +Describe 'Graph reporting' { + BeforeEach { + Mock Get-MgContext { [pscustomobject]@{TenantId='tenant'} } + Mock Get-MgUser { [pscustomobject]@{Id='guest-id';DisplayName='Guest';UserPrincipalName='guest@example.com';UserType='Guest'} } + Mock Get-MgAuditLogSignIn { @() } + Mock Get-MgDevice { @() } + Mock Update-MgDevice {} + } + It 'distinguishes absent retained sign-ins from a never-used account' { + $row = & "$repo/GraphAPI-GuestUserStatus.ps1" -TenantId tenant + $row.Name | Should -Be Guest + $row.RecordStatus | Should -Be NoAvailableRecord + $row.SignInDate | Should -BeNullOrEmpty + Should -Invoke Get-MgUser -Times 1 -ParameterFilter { $All -and 'createdDateTime' -in $Property } + } + It 'does not turn API failures into an empty sign-in history' { + Mock Get-MgAuditLogSignIn { throw 'Forbidden' } + { & "$repo/GraphAPI-GuestUserStatus.ps1" -TenantId tenant } | Should -Throw '*Forbidden*' + } + It 'refuses the wrong tenant before querying data' { + { & "$repo/Export-GraphDevices.ps1" -TenantId wrong } | Should -Throw '*Connect-MgGraph*' + Should -Invoke Get-MgDevice -Times 0 + } + It 'escapes apostrophes in OData prefix input and follows all pages' { + & "$repo/Find-GraphDevice.ps1" -TenantId tenant -DisplayNamePrefix "O'Brien" + Should -Invoke Get-MgDevice -Times 1 -ParameterFilter { $All -and $Filter -eq "startsWith(displayName,'O''Brien')" } + } + It 'does not write a device attribute during WhatIf' { + Mock Get-MgDevice { [pscustomobject]@{Id='d';DisplayName='Device';ExtensionAttributes=@{extensionAttribute6='Before'}} } + & "$repo/Set-GraphDeviceExtensionAttribute.ps1" -TenantId tenant -DeviceObjectId '11111111-1111-1111-1111-111111111111' -AttributeNumber 6 -Value After -WhatIf + Should -Invoke Update-MgDevice -Times 0 + } +} + +Describe 'Mailbox hold semantics' { + It 'keeps retention processing pauses distinct and reports each mailbox once' { + Mock Get-ConnectionInformation { [pscustomobject]@{State='Connected'} } + Mock Get-Mailbox { + [pscustomobject]@{Name='A';UserPrincipalName='a@example.com';InPlaceHolds=@();RetentionHoldEnabled=$true;LitigationHoldEnabled=$false;ComplianceTagHoldApplied=$false} + [pscustomobject]@{Name='B';UserPrincipalName='b@example.com';InPlaceHolds=@('mbx1','UniH2');RetentionHoldEnabled=$false;LitigationHoldEnabled=$true;ComplianceTagHoldApplied=$true} + } + $rows = @(& "$repo/Export-O365MailboxHolds.ps1") + $rows.Count | Should -Be 2 + $rows[0].RetentionProcessingPaused | Should -BeTrue + $rows[1].InPlaceHoldIdentifierCount | Should -Be 2 + $rows[1].InPlaceHoldIdentifiers | Should -Be 'mbx1;UniH2' + } +} + +Describe 'Additional report regressions' { + BeforeAll { + function Get-MpComputerStatus { [CmdletBinding()] param() throw 'Unmocked Defender call' } + } + It 'filters expired accounts and keeps no-expiration reporting explicit' { + Mock Get-ADUser { + [pscustomobject]@{Name='Expired';AccountExpirationDate=(Get-Date).AddDays(-1)} + [pscustomobject]@{Name='Future';AccountExpirationDate=(Get-Date).AddDays(1)} + [pscustomobject]@{Name='None';AccountExpirationDate=$null} + } + $expired = @(& "$repo/Get-ADExpiredAccounts.ps1" -Server dc) + $expired.Count | Should -Be 1 + $expired[0].Name | Should -Be Expired + $none = @(& "$repo/Get-ADExpiredAccounts.ps1" -Server dc -WithoutExpiration) + $none.Count | Should -Be 1 + $none[0].Name | Should -Be None + } + It 'uses event 4720 target SID evidence rather than a CreatedBy property' { + Mock Get-ADUser { [pscustomobject]@{SamAccountName='Alice';whenCreated=[datetime]'2025-01-01';SID='S-1-5-21-100-1000'} } + Mock Get-WinEvent { + $entry = [pscustomobject]@{TimeCreated=[datetime]'2025-01-01';RecordId=42} + $entry | Add-Member -MemberType ScriptMethod -Name ToXml -Value { + 'S-1-5-21-100-1000EXAMPLEOperator' + } + $entry + } + $row = & "$repo/Get-ADUserCreationAudit.ps1" -Server dc -Identity alice -DomainController dc1 + $row.Creator | Should -Be 'EXAMPLE\Operator' + $row.Evidence | Should -Be Event4720 + $row.RecordId | Should -Be 42 + Should -Invoke Get-WinEvent -Times 1 -ParameterFilter { $FilterHashtable.Id -eq 4720 -and $ComputerName -eq 'dc1' } + } + It 'does not attribute another SID creation event to the selected user' { + Mock Get-ADUser { [pscustomobject]@{SamAccountName='Alice';whenCreated=[datetime]'2025-01-01';SID='S-1-5-21-100-1000'} } + Mock Get-WinEvent { + $entry = [pscustomobject]@{TimeCreated=[datetime]'2025-01-01';RecordId=43} + $entry | Add-Member -MemberType ScriptMethod -Name ToXml -Value { + 'S-1-5-21-100-1001EXAMPLEOperator' + } + $entry + } + $row = & "$repo/Get-ADUserCreationAudit.ps1" -Server dc -Identity alice -DomainController dc1 + $row.Creator | Should -BeNullOrEmpty + $row.Evidence | Should -Be NoAvailableRecord + } + It 'rejects invalid event ranges before contacting a remote computer' { + Mock Get-WinEvent {} + { & "$repo/Get-WindowsEvents.ps1" -ComputerName $testComputer -StartTime '2025-01-02' -EndTime '2025-01-01' } | Should -Throw '*StartTime must precede*' + Should -Invoke Get-WinEvent -Times 0 + } + It 'passes selected log, dates and credentials to event collection' { + Mock Get-WinEvent { [pscustomobject]@{MachineName='host1';Id=7;Message='sample'} } + $credential = [pscredential]::new('EXAMPLE\reader', [Security.SecureString]::new()) + $row = & "$repo/Get-WindowsEvents.ps1" -ComputerName $testComputer -StartTime '2025-01-01' -EndTime '2025-01-02' -LogName Application -Credential $credential + $row.Id | Should -Be 7 + Should -Invoke Get-WinEvent -Times 1 -ParameterFilter { $ComputerName -eq $testComputer -and $FilterHashtable.LogName -eq 'Application' -and $null -ne $Credential } + } + It 'removes the CIM session even if inventory collection fails' { + Mock New-CimSession { New-MockObject -Type Microsoft.Management.Infrastructure.CimSession } + Mock Get-CimInstance { throw 'Remote inventory failed' } + Mock Remove-CimSession {} + { & "$repo/Get-ComputerInfo.ps1" -ComputerName $testComputer } | Should -Throw '*Remote inventory failed*' + Should -Invoke Remove-CimSession -Times 1 + } + It 'defaults Defender toolkit to reading status without a mutation' { + Mock Get-MpComputerStatus { [pscustomobject]@{RealTimeProtectionEnabled=$true} } + $row = & "$repo/DefenderToolkit.ps1" + $row.RealTimeProtectionEnabled | Should -BeTrue + Should -Invoke Get-MpComputerStatus -Times 1 + } +} diff --git a/tools/Test-Repository.ps1 b/tools/Test-Repository.ps1 new file mode 100644 index 0000000..062d5b3 --- /dev/null +++ b/tools/Test-Repository.ps1 @@ -0,0 +1,34 @@ +<# +.SYNOPSIS +Parse, lint and test the collection without importing administrative modules. +.DESCRIPTION +Install Pester 5.7.1 and PSScriptAnalyzer 1.24.0 first. Windows browser tests also +require sqlite3 >= 3.33; supply TOOLKIT_TEST_SQLITE or install it in PATH. +.EXAMPLE +.\tools\Test-Repository.ps1 +#> +[CmdletBinding()] +param() +$ErrorActionPreference = 'Stop' +$root = Split-Path $PSScriptRoot -Parent +Import-Module PSScriptAnalyzer -RequiredVersion 1.24.0 +Import-Module Pester -RequiredVersion 5.7.1 +$parseErrors = @(foreach ($file in (Get-ChildItem $root -Filter *.ps1 -Recurse)) { + $tokens = $null + $errors = $null + $null = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$tokens, [ref]$errors) + $errors +}) +if ($parseErrors.Count) { $parseErrors | Format-List | Out-String | Write-Output; throw 'PowerShell parsing failed.' } +$findings = @(foreach ($file in (Get-ChildItem $root -Recurse -Filter *.ps1)) { + $analyzer = @{ Path = $file.FullName; Severity = 'Error','Warning' } + if ($file.Name -like '*.Tests.ps1') { + # Pester discovers variables across blocks; fail-closed mock stubs deliberately + # declare SDK signatures but never invoke real ShouldProcess operations. + $analyzer.ExcludeRule = 'PSUseDeclaredVarsMoreThanAssignments','PSReviewUnusedParameter','PSUseShouldProcessForStateChangingFunctions','PSShouldProcess','PSAvoidOverwritingBuiltInCmdlets' + } + Invoke-ScriptAnalyzer @analyzer +}) +if ($findings.Count) { $findings | Format-Table -AutoSize | Out-String | Write-Output; throw 'PSScriptAnalyzer found errors or warnings.' } +$result = Invoke-Pester -Path (Join-Path $root tests) -PassThru -Output Detailed +if ($result.FailedCount -gt 0 -or $result.TotalCount -eq 0) { throw 'Regression tests failed or no tests ran.' } diff --git a/verify-credentials.ps1 b/verify-credentials.ps1 index d3cf59b..f2eaf6c 100644 --- a/verify-credentials.ps1 +++ b/verify-credentials.ps1 @@ -1,52 +1,35 @@ -<# -Verify credentials against Active directory - -This script will allow you to verify the credentials for a user -Prompts you for a user name and prompts for a secure password entry - -#> -param ( - [Parameter(Mandatory=$true)] [string] $user -) - -Function Test-UserCredentials -{ - param( - [Parameter(Mandatory=$True)] - [string] $LoginName, - - [Parameter(Mandatory=$True)] - [string] $Password - ) - - Add-Type -AssemblyName System.DirectoryServices.AccountManagement - $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('domain') - $result = $DS.ValidateCredentials($LoginName, $Password) - - If ($result) - { - Write-Host "$LoginName - The account successfully authenticated, the password is correct." -ForegroundColor green - } - Else - { - Write-Host "$LoginName - Authentication failed with the provided password." -ForegroundColor red - } - - return $result -} - -Write-Host "(BEFORE) Account Status:`n" -net user $user /domain - -$securePassword = Read-Host -Prompt "Enter password" -AsSecureString -$BSTR = ` - [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword) -$plainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) - -Test-UserCredentials "$user" "$plainPassword" - -pause - -Write-Host "`n(AFTER) Account Status:" -net user $user /domain - +<# +.SYNOPSIS +Validate one supplied credential against the selected AD domain. +.DESCRIPTION +Windows only. Failed attempts can contribute to account lockout. The directory API +requires a transient managed plaintext string; it cannot be reliably zeroed by .NET. +The unmanaged BSTR is always zeroed and freed, and the directory context disposed. +.EXAMPLE +.\verify-credentials.ps1 -Domain example.com -Credential (Get-Credential) +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Domain, + [Parameter(Mandatory)][pscredential]$Credential +) +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.DirectoryServices.AccountManagement +$context = $null +$pointer = [IntPtr]::Zero +$plainPassword = $null +try { + $context = [System.DirectoryServices.AccountManagement.PrincipalContext]::new( + [System.DirectoryServices.AccountManagement.ContextType]::Domain, $Domain) + $pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password) + $plainPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) + [pscustomobject]@{ + Domain = $Domain + UserName = $Credential.UserName + Authenticated = $context.ValidateCredentials($Credential.UserName, $plainPassword) + } +} finally { + if ($pointer -ne [IntPtr]::Zero) { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) } + $plainPassword = $null + if ($null -ne $context) { $context.Dispose() } +}