Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions powershell/Maester.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ $__MtSession = @{
SpoCache = @{} # Cache for SharePoint Online tenant settings retrieved via PnP
FabricCache = @{} # Fabric admin API data cached for the current test run
GitHubCache = @{} # Per-session REST response cache; cleared each Invoke-Maester run
TeamsCache = @{} # Teams admin API data cached for the current test run
TeamsAuthCache = @{} # Teams unified settings MSAL client; retained until disconnect
TeamsUseDeviceCode = $false # Whether Connect-Maester requested device-code authentication
TeamsEnvironmentName = $null # Explicit Teams PowerShell environment, when provided
ADCache = @{} # Active Directory data cache
ADConnection = $null # Active Directory connection state
ADCredential = $null # Active Directory credential retained only for the connected session
Expand Down
154 changes: 154 additions & 0 deletions powershell/internal/checks/cisa/teams/TeamsChecks.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
function Get-MtCisaTeamsMeetingPolicies {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'The Teams cmdlet returns a collection of meeting policies.')]
param(
[switch]$GlobalOnly
)

$policies = if ($GlobalOnly) {
@(Get-CsTeamsMeetingPolicy -Identity Global -ErrorAction Stop)
} else {
@(Get-CsTeamsMeetingPolicy -ErrorAction Stop)
}

if ($policies.Count -eq 0) {
throw 'Teams returned no meeting policies.'
}
if ($GlobalOnly -and ($policies.Count -ne 1 -or $policies[0].Identity -ne 'Global')) {
throw 'Teams did not return exactly one Global meeting policy.'
}

return $policies
}

function Test-MtCisaTeamsMeetingPolicyBoolean {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$SettingName,
[Parameter(Mandatory)]
[bool]$ExpectedValue,
[Parameter(Mandatory)]
[string]$PolicyDescription
)

$policies = Get-MtCisaTeamsMeetingPolicies
$results = foreach ($policy in $policies) {
$setting = $policy.PSObject.Properties[$SettingName]
if ($null -eq $setting -or $setting.Value -isnot [bool]) {
throw "Teams meeting policy '$($policy.Identity)' did not return a Boolean value for $SettingName."
}

[pscustomobject]@{
Policy = $policy.Identity
Value = $setting.Value
Pass = $setting.Value -eq $ExpectedValue
}
}

$passed = @($results | Where-Object { -not $_.Pass }).Count -eq 0
$markdown = if ($passed) {
"Well done. $PolicyDescription is configured for every meeting policy.`n`n"
} else {
"$PolicyDescription is not configured for every meeting policy.`n`n"
}
$markdown += "| Policy | $SettingName | Result |`n| --- | --- | --- |`n"
foreach ($row in $results) {
$markdown += "| $($row.Policy) | $($row.Value) | $(if ($row.Pass) { 'Pass' } else { 'Fail' }) |`n"
}
Add-MtTestResultDetail -Result $markdown.TrimEnd()
return $passed
}

function Get-MtCisaTeamsGlobalMeetingPolicy {
[CmdletBinding()]
param()

$policies = Get-MtCisaTeamsMeetingPolicies -GlobalOnly
return $policies[0]
}

function Get-MtCisaTeamsFederationConfigurations {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Teams can return multiple federation configurations.')]
param()
Comment thread
JeremyFinney-lgtm marked this conversation as resolved.
Resolved

$configurations = @(Get-CsTenantFederationConfiguration -ErrorAction Stop)
if ($configurations.Count -eq 0) {
throw 'Teams returned no tenant federation configurations.'
}
return $configurations
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
}

function Test-MtCisaTeamsIsUSGovernment {
[CmdletBinding()]
param()

$context = Get-MgContext -ErrorAction Stop
if (-not $context) {
throw 'A Microsoft Graph context is required to determine the Teams environment.'
}
return ($context.Environment -in @('USGov', 'USGovDoD') -or
$__MtSession.TeamsEnvironmentName -in @('TeamsGCCH', 'TeamsDOD'))
}

function Test-MtCisaTeamsAppControl {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet('DefaultApp', 'GlobalApp', 'PrivateApp')]
[string]$SettingName,
[Parameter(Mandatory)]
[string]$AppType
)

$settings = @(Get-MtTeamsUnifiedTenantSettings)
$setting = $settings | Where-Object { $_.SettingName -eq $SettingName } | Select-Object -First 1
$policyProperty = switch ($SettingName) {
'DefaultApp' { 'DefaultCatalogAppsType' }
'GlobalApp' { 'GlobalCatalogAppsType' }
'PrivateApp' { 'PrivateCatalogAppsType' }
}

$rows = @()
if ($setting) {
$value = [string]$setting.SettingValue
$passed = $value -eq 'None'
$rows += [pscustomobject]@{
Policy = 'Org-wide setting'
Value = $value
Pass = $passed
}
} else {
$policies = @(Get-CsTeamsAppPermissionPolicy -ErrorAction Stop)
if ($policies.Count -eq 0) {
throw 'Teams returned no app permission policies.'
}

$rows = foreach ($policy in $policies) {
$type = $policy.PSObject.Properties[$policyProperty]
if ($null -eq $type -or $type.Value -notin @('AllowedAppList', 'BlockedAppList')) {
throw "Teams app permission policy '$($policy.Identity)' did not return a supported value for $policyProperty."
}

[pscustomobject]@{
Policy = $policy.Identity
Value = $type.Value
Pass = $type.Value -eq 'AllowedAppList'
}
}
$passed = @($rows | Where-Object { -not $_.Pass }).Count -eq 0
}

$markdown = if ($passed) {
"Well done. $AppType apps are restricted to the approved set.`n`n"
} else {
"$AppType apps are not restricted to the approved set.`n`n"
}
$markdown += "| Policy or setting | Value | Result |`n| --- | --- | --- |`n"
foreach ($row in $rows) {
$markdown += "| $($row.Policy) | $($row.Value) | $(if ($row.Pass) { 'Pass' } else { 'Fail' }) |`n"
}
Add-MtTestResultDetail -Result $markdown.TrimEnd()
return $passed
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
function Get-MtTeamsUnifiedTenantSettings {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'The Teams API returns a collection of settings.')]
param()

$context = Get-MgContext -ErrorAction Stop
if (-not $context) {
throw 'A Microsoft Graph context is required to retrieve Teams unified app settings.'
}

$tenantId = [string]$context.TenantId
if ([string]::IsNullOrWhiteSpace($tenantId)) {
throw 'The Microsoft Graph context does not include a tenant ID.'
}

if (($context.Environment -and $context.Environment -ne 'Global') -or
$__MtSession.TeamsEnvironmentName -in @('TeamsChina', 'TeamsGCCH', 'TeamsDOD')) {
return $null
}
if ($context.AuthType -ne 'Delegated') {
return $null
}

$cacheKey = "UnifiedAppSettings:$tenantId"
if ($__MtSession.TeamsCache.ContainsKey($cacheKey)) {
return $__MtSession.TeamsCache[$cacheKey]
}

$accessToken = Get-MtTeamsUnifiedSettingsAccessToken -Context $context
$response = Invoke-RestMethod `
-Uri 'https://substrate.office.com/AdminAppCatalog/ps/v2/admin/unifiedApp/settings' `
-Method Get `
-Headers @{ Authorization = "Bearer $accessToken" } `
-ErrorAction Stop

if ($null -eq $response) {
throw 'The Teams unified app settings API returned an empty response.'
}

$settings = if ($response.PSObject.Properties['value']) {
@($response.value)
} else {
@($response)
}

foreach ($setting in $settings) {
if ($null -eq $setting -or
$null -eq $setting.PSObject.Properties['SettingName'] -or
$null -eq $setting.PSObject.Properties['SettingValue']) {
throw 'The Teams unified app settings API returned a setting without SettingName or SettingValue.'
}
}

$__MtSession.TeamsCache[$cacheKey] = $settings
return $settings
}

function Get-MtTeamsUnifiedSettingsAccessToken {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[object]$Context
)

$tenantId = [string]$Context.TenantId
$clientId = '12128f48-ec9e-42f0-b203-ea49fb6af367'
$scope = @('08ff1ce2-4973-4b08-86a3-ebed13badc7f/.default')
$authority = "https://login.microsoftonline.com/$tenantId"
$cacheKey = "$tenantId|$($Context.Environment)"

if (-not ('Microsoft.Identity.Client.PublicClientApplicationBuilder' -as [type])) {
$authenticationModule = Get-Module Microsoft.Graph.Authentication | Sort-Object Version -Descending | Select-Object -First 1
if (-not $authenticationModule) {
throw 'Microsoft.Graph.Authentication must be loaded before acquiring a Teams unified settings token.'
}

$dependencyFolder = if ($PSVersionTable.PSEdition -eq 'Core') { 'Core' } else { 'Desktop' }
$msalPath = Join-Path $authenticationModule.ModuleBase "Dependencies\$dependencyFolder\Microsoft.Identity.Client.dll"
if (-not (Test-Path -LiteralPath $msalPath)) {
throw "Microsoft.Identity.Client.dll was not found at '$msalPath'."
}
$null = Add-Type -Path $msalPath -ErrorAction Stop
}

if (-not $__MtSession.TeamsAuthCache.ContainsKey('Clients')) {
$__MtSession.TeamsAuthCache['Clients'] = @{}
}

$clients = $__MtSession.TeamsAuthCache['Clients']
if (-not $clients.ContainsKey($cacheKey)) {
$clients[$cacheKey] = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($clientId).
WithAuthority($authority).
WithRedirectUri('http://localhost').
Build()
}
$application = $clients[$cacheKey]

$accounts = @($application.GetAccountsAsync().GetAwaiter().GetResult())
$account = $null
if ($Context.Account) {
$account = $accounts | Where-Object { $_.Username -eq [string]$Context.Account } | Select-Object -First 1
}

$result = $null
if ($account) {
try {
$result = $application.AcquireTokenSilent($scope, $account).ExecuteAsync().GetAwaiter().GetResult()
} catch [Microsoft.Identity.Client.MsalUiRequiredException] {
Write-Verbose 'Silent token acquisition requires user interaction.'
}
}

if (-not $result -and $__MtSession.TeamsUseDeviceCode) {
$deviceCodeCallback = [System.Func[Microsoft.Identity.Client.DeviceCodeResult, System.Threading.Tasks.Task]] {
param($deviceCode)
Write-Information $deviceCode.Message -InformationAction Continue
[System.Threading.Tasks.Task]::CompletedTask
}
$result = $application.AcquireTokenWithDeviceCode($scope, $deviceCodeCallback).ExecuteAsync().GetAwaiter().GetResult()
Comment thread
JeremyFinney-lgtm marked this conversation as resolved.
Resolved
} elseif (-not $result) {
$interactiveRequest = $application.AcquireTokenInteractive($scope).WithUseEmbeddedWebView($false)
if ($Context.Account) {
$interactiveRequest = $interactiveRequest.WithLoginHint([string]$Context.Account)
}
$result = $interactiveRequest.ExecuteAsync().GetAwaiter().GetResult()
}

if (-not $result -or [string]::IsNullOrWhiteSpace($result.AccessToken)) {
throw 'Microsoft identity platform returned no access token for Teams unified app settings.'
}

return $result.AccessToken
}
1 change: 1 addition & 0 deletions powershell/internal/session/Clear-ModuleVariable.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
$__MtSession.GitHubCache = @{}
$__MtSession.SpoCache = @{}
$__MtSession.FabricCache = @{}
$__MtSession.TeamsCache = @{}
$__MtSession.Console = $null
$__MtSession.ReportAttachments = $null
# $__MtSession.Connections = @() # Do not clear connections as they are used to track the connection state. This module variable should only be set by Connect-Maester and Disconnect-Maester.
Expand Down
2 changes: 2 additions & 0 deletions powershell/public/connect/Connect-Maester.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,8 @@

'MicrosoftTeams' {
if ($Service -contains 'Teams' -or $Service -contains 'All') {
$__MtSession.TeamsUseDeviceCode = $UseDeviceCode.IsPresent
$__MtSession.TeamsEnvironmentName = $TeamsEnvironmentName
Write-Verbose 'Connecting to Microsoft Teams'
try {
$teamsParams = @{ ErrorAction = 'Stop' }
Expand Down
5 changes: 5 additions & 0 deletions powershell/public/connect/Disconnect-Maester.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@
}

if ($MyInvocation.InvocationName -notmatch '(^|\\)Disconnect-MtGraph$') {
$__MtSession.TeamsCache = @{}
$__MtSession.TeamsAuthCache = @{}
$__MtSession.TeamsUseDeviceCode = $false
$__MtSession.TeamsEnvironmentName = $null

# The service list can be replaced by another Connect-Maester call. Clean up a loaded
# ADOPS session too, without importing an optional module just to disconnect it.
try {
Expand Down
Loading
Loading