diff --git a/CHANGELOG.md b/CHANGELOG.md index 95054c78ab..06d66cb4cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,14 @@ # Change log for Microsoft365DSC -# Unreleased +# UNRELEASED +* AADEntitlementManagementSettings + * Added support for ApplicationSecret * EXOMigrationEndpoint * Initial Release +* M365DSCDRGUtil + * Fixes an issue for the handling of skipped one-property elements in the + Settings Catalog. FIXES [#5086](https://github.com/microsoft/Microsoft365DSC/issues/5086) # 1.24.1002.1 @@ -20,6 +25,8 @@ * Added ReportSuspiciousActivitySettings * AADAuthenticationMethodPolicyHardware * Initial release. +* AADAuthenticationRequirement + * Initial release. * AADEntitlementManagementSettings * Initial release. * AADFeatureRolloutPolicy diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 index 636e27a4db..d8c5b97231 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 @@ -933,7 +933,16 @@ function Set-TargetResource if($needToUpdateKeyCredentials -and $KeyCredentials) { - Write-Warning -Message "KeyCredentials is a readonly property and cannot be configured." + Write-Verbose -Message "Updating for Azure AD Application {$($currentAADApp.DisplayName)} with KeyCredentials:`r`n$($KeyCredentials| Out-String)" + + if((currentAADApp.KeyCredentials.Length -eq 0 -and $KeyCredentials.Length -eq 1) -or (currentAADApp.KeyCredentials.Length -eq 1 -and $KeyCredentials.Length -eq 0)) + { + Update-MgApplication -ApplicationId $currentAADApp.Id -KeyCredentials $KeyCredentials | Out-Null + } + else + { + Write-Warning -Message "KeyCredentials cannot be updated for AAD Applications with more than one KeyCredentials due to technical limitation of Update-MgApplication Cmdlet. Learn more at: https://learn.microsoft.com/en-us/graph/api/application-addkey" + } } } diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/MSFT_AADAuthenticationRequirement.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/MSFT_AADAuthenticationRequirement.psm1 new file mode 100644 index 0000000000..d78d5bfbf1 --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/MSFT_AADAuthenticationRequirement.psm1 @@ -0,0 +1,382 @@ +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [Parameter()] + [ValidateSet('enabled', 'disabled')] + [System.String] + $PerUserMfaState, + + [Parameter(Mandatory = $true)] + [System.String] + $UserPrincipalName, + + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + try + { + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullResult = $PSBoundParameters + + $getValue = $null + $url = $Global:MSCloudLoginConnectionProfile.MicrosoftGraph.ResourceUrl + "beta/users/$UserPrincipalName/authentication/requirements" + $getValue = Invoke-MgGraphRequest -Method Get -Uri $url + + if ($null -eq $getValue) + { + Write-Verbose -Message "Could not find an Azure AD Authentication Requirement for user with UPN {$UserPrincipalName}" + return $nullResult + } + + Write-Verbose -Message "An Azure AD Authentication Method Policy Requirement for a user with UPN {$UserPrincipalName} was found." + + $results = @{ + PerUserMfaState = $getValue.perUserMfaState + UserPrincipalName = $UserPrincipalName + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + ApplicationSecret = $ApplicationSecret + CertificateThumbprint = $CertificateThumbprint + Managedidentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens + } + + return [System.Collections.Hashtable] $results + } + catch + { + New-M365DSCLogEntry -Message 'Error retrieving data:' ` + -Exception $_ ` + -Source $($MyInvocation.MyCommand.Source) ` + -TenantId $TenantId ` + -Credential $Credential + + return $nullResult + } +} + +function Set-TargetResource +{ + [CmdletBinding()] + param + ( + [Parameter()] + [ValidateSet('enabled', 'disabled')] + [System.String] + $PerUserMfaState, + + [Parameter(Mandatory = $true)] + [System.String] + $UserPrincipalName, + + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $currentInstance = Get-TargetResource @PSBoundParameters + $url = $Global:MSCloudLoginConnectionProfile.MicrosoftGraph.ResourceUrl + "beta/users/$UserPrincipalName/authentication/requirements" + + $params = @{} + if ($PerUserMfaState -eq 'enabled' -and $currentInstance.PerUserMfaState -eq 'disabled') + { + $params = @{ + "perUserMfaState" = "enabled" + } + } + elseif ($PerUserMfaState -eq 'disabled' -and $currentInstance.PerUserMfaState -eq 'enabled') + { + $params = @{ + "perUserMfaState" = "disabled" + } + } + + $jsonParams = $params | ConvertTo-Json + + Invoke-MgGraphRequest -Method PATCH -Uri $url -Body $jsonParams +} + +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [Parameter()] + [ValidateSet('enabled', 'disabled')] + [System.String] + $PerUserMfaState, + + [Parameter(Mandatory = $true)] + [System.String] + $UserPrincipalName, + + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + Write-Verbose -Message "Testing configuration of the Azure AD Authentication Requirement for a user with UPN {$UserPrincipalName}" + + $CurrentValues = Get-TargetResource @PSBoundParameters + $ValuesToCheck = ([Hashtable]$PSBoundParameters).clone() + + $testResult = $true + + $CurrentValues.remove('Id') | Out-Null + $ValuesToCheck.remove('Id') | Out-Null + + Write-Verbose -Message "Current Values: $(Convert-M365DscHashtableToString -Hashtable $CurrentValues)" + Write-Verbose -Message "Target Values: $(Convert-M365DscHashtableToString -Hashtable $ValuesToCheck)" + + if ($testResult) + { + $testResult = Test-M365DSCParameterState -CurrentValues $CurrentValues ` + -Source $($MyInvocation.MyCommand.Source) ` + -DesiredValues $PSBoundParameters ` + -ValuesToCheck $ValuesToCheck.Keys + } + + Write-Verbose -Message "Test-TargetResource returned $testResult" + + return $testResult +} + +function Export-TargetResource +{ + [CmdletBinding()] + [OutputType([System.String])] + param + ( + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + try + { + [array]$getValue = Get-MgUser -ErrorAction Stop | Where-Object -FilterScript {$null -ne $_.Id} + + $i = 1 + $dscContent = '' + if ($getValue.Length -eq 0) + { + Write-Host $Global:M365DSCEmojiGreenCheckMark + } + else + { + Write-Host "`r`n" -NoNewline + } + foreach ($config in $getValue) + { + if ($null -ne $Global:M365DSCExportResourceInstancesCount) + { + $Global:M365DSCExportResourceInstancesCount++ + } + + $displayedKey = $config.Id + if (-not [String]::IsNullOrEmpty($config.DisplayName)) + { + $displayedKey = $config.DisplayName + } + + Write-Host " |---[$i/$($getValue.Count)] $displayedKey" -NoNewline + $params = @{ + UserPrincipalName = $config.UserPrincipalName + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + ApplicationSecret = $ApplicationSecret + CertificateThumbprint = $CertificateThumbprint + Managedidentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens + } + + $Results = Get-TargetResource @Params + $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` + -Results $Results + + $currentDSCBlock = Get-M365DSCExportContentForResource -ResourceName $ResourceName ` + -ConnectionMode $ConnectionMode ` + -ModulePath $PSScriptRoot ` + -Results $Results ` + -Credential $Credential + + $dscContent += $currentDSCBlock + Save-M365DSCPartialExport -Content $currentDSCBlock ` + -FileName $Global:PartialExportFileName + $i++ + Write-Host $Global:M365DSCEmojiGreenCheckMark + } + return $dscContent + } + catch + { + Write-Host $Global:M365DSCEmojiRedX + + New-M365DSCLogEntry -Message 'Error during Export:' ` + -Exception $_ ` + -Source $($MyInvocation.MyCommand.Source) ` + -TenantId $TenantId ` + -Credential $Credential + + return '' + } +} + +Export-ModuleMember -Function *-TargetResource diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/MSFT_AADAuthenticationRequirement.schema.mof b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/MSFT_AADAuthenticationRequirement.schema.mof new file mode 100644 index 0000000000..f1182e0ff3 --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/MSFT_AADAuthenticationRequirement.schema.mof @@ -0,0 +1,14 @@ +[ClassVersion("1.0.0.0"), FriendlyName("AADAuthenticationRequirement")] +class MSFT_AADAuthenticationRequirement : OMI_BaseResource +{ + [Write, Description("The state of the MFA enablement for the user. Possible values are: enabled, disabled."), ValueMap{"enabled","disabled"}, Values{"enabled","disabled"}] String PerUserMfaState; + [Key, Description("The unique identifier for an entity. Read-only.")] String UserPrincipalName; + + [Write, Description("Credentials of the Admin"), EmbeddedInstance("MSFT_Credential")] string Credential; + [Write, Description("Id of the Azure Active Directory application to authenticate with.")] String ApplicationId; + [Write, Description("Id of the Azure Active Directory tenant used for authentication.")] String TenantId; + [Write, Description("Secret of the Azure Active Directory tenant used for authentication."), EmbeddedInstance("MSFT_Credential")] String ApplicationSecret; + [Write, Description("Thumbprint of the Azure Active Directory application's authentication certificate to use for authentication.")] String CertificateThumbprint; + [Write, Description("Managed ID being used for authentication.")] Boolean ManagedIdentity; + [Write, Description("Access token used for authentication.")] String AccessTokens[]; +}; diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/readme.md b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/readme.md new file mode 100644 index 0000000000..8495f479ee --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/readme.md @@ -0,0 +1,6 @@ + +# AADAuthenticationRequirement + +## Description + +Azure AD Authentication Requirement Resource to set up Per-User MFA settings diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/settings.json b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/settings.json new file mode 100644 index 0000000000..e56d74c0d4 --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationRequirement/settings.json @@ -0,0 +1,40 @@ +{ + "resourceName": "AADAuthenticationRequirement", + "description": "This resource configures Azure AD Authentication MFA Requirements for a user.", + "roles": { + "read": [], + "update": [] + }, + "permissions": { + "graph": { + "delegated": { + "read": + [ + { + "name": "UserAuthenticationMethod.Read.All" + } + ], + "update": + [ + { + "name": "UserAuthenticationMethod.ReadWrite.All" + } + ] + }, + "application": { + "read": + [ + { + "name": "UserAuthenticationMethod.Read.All" + } + ], + "update": + [ + { + "name": "UserAuthenticationMethod.ReadWrite.All" + } + ] + } + } + } +} diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADEntitlementManagementSettings/MSFT_AADEntitlementManagementSettings.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADEntitlementManagementSettings/MSFT_AADEntitlementManagementSettings.psm1 index f145e6744d..7ffb6e65bc 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADEntitlementManagementSettings/MSFT_AADEntitlementManagementSettings.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADEntitlementManagementSettings/MSFT_AADEntitlementManagementSettings.psm1 @@ -28,6 +28,10 @@ function Get-TargetResource [System.String] $TenantId, + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + [Parameter()] [System.String] $CertificateThumbprint, @@ -72,6 +76,7 @@ function Get-TargetResource Credential = $Credential ApplicationId = $ApplicationId TenantId = $TenantId + ApplicationSecret = $ApplicationSecret CertificateThumbprint = $CertificateThumbprint ManagedIdentity = $ManagedIdentity.IsPresent AccessTokens = $AccessTokens @@ -120,6 +125,10 @@ function Set-TargetResource [System.String] $TenantId, + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + [Parameter()] [System.String] $CertificateThumbprint, @@ -181,6 +190,10 @@ function Test-TargetResource [System.String] $TenantId, + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + [Parameter()] [System.String] $CertificateThumbprint, @@ -281,6 +294,7 @@ function Export-TargetResource Credential = $Credential ApplicationId = $ApplicationId TenantId = $TenantId + ApplicationSecret = $ApplicationSecret CertificateThumbprint = $CertificateThumbprint ManagedIdentity = $ManagedIdentity.IsPresent AccessTokens = $AccessTokens diff --git a/Modules/Microsoft365DSC/Examples/Resources/AADAuthenticationRequirement/2-Update.ps1 b/Modules/Microsoft365DSC/Examples/Resources/AADAuthenticationRequirement/2-Update.ps1 new file mode 100644 index 0000000000..ec3edca920 --- /dev/null +++ b/Modules/Microsoft365DSC/Examples/Resources/AADAuthenticationRequirement/2-Update.ps1 @@ -0,0 +1,34 @@ +<# +This example is used to test new resources and showcase the usage of new resources being worked on. +It is not meant to use as a production baseline. +#> + +Configuration Example +{ + param( + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.String] + $CertificateThumbprint + ) + Import-DscResource -ModuleName Microsoft365DSC + + Node localhost + { + AADAuthenticationRequirement "AADAuthenticationRequirement-TestMailbox109@xtasdftestorg.onmicrosoft.com" + { + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + PerUserMfaState = "disabled"; + UserPrincipalName = "TestMailbox109@$OrganizationName"; + } + } +} diff --git a/Modules/Microsoft365DSC/Modules/M365DSCDRGUtil.psm1 b/Modules/Microsoft365DSC/Modules/M365DSCDRGUtil.psm1 index 542a206b3d..962544bf28 100644 --- a/Modules/Microsoft365DSC/Modules/M365DSCDRGUtil.psm1 +++ b/Modules/Microsoft365DSC/Modules/M365DSCDRGUtil.psm1 @@ -105,7 +105,7 @@ function Rename-M365DSCCimInstanceParameter $subValue = Rename-M365DSCCimInstanceParameter $property -KeyMapping $KeyMapping if ($null -ne $subValue) { - $hashProperties.add($keyName, $subValue) + $hashProperties.Add($keyName, $subValue) } } catch @@ -830,7 +830,7 @@ function Convert-M365DSCDRGComplexTypeToHashtable $propertyName = $key[0].ToString().ToLower() + $key.Substring(1, $key.Length - 1) $propertyValue = $results[$key] $results.remove($key) | Out-Null - $results.add($propertyName, $propertyValue) + $results.Add($propertyName, $propertyValue) } } } @@ -1015,11 +1015,11 @@ function Get-SettingCatalogPolicySettingsFromTemplate $settingKey = $DSCParams.keys | Where-Object -FilterScript { $templateSetting.settingDefinitionId -like "*$($_)" } if ((-not [String]::IsNullOrEmpty($settingKey)) -and $DSCParams."$settingKey") { - $setting.add('@odata.type', '#microsoft.graph.deviceManagementConfigurationSetting') + $setting.Add('@odata.type', '#microsoft.graph.deviceManagementConfigurationSetting') $myFormattedSetting = Format-M365DSCParamsToSettingInstance -DSCParams @{$settingKey = $DSCParams."$settingKey" } ` -TemplateSetting $templateSetting - $setting.add('settingInstance', $myFormattedSetting) + $setting.Add('settingInstance', $myFormattedSetting) $settings += $setting $DSCParams.Remove($settingKey) | Out-Null } @@ -1033,23 +1033,23 @@ function Get-SettingCatalogPolicySettingsFromTemplate foreach ($groupCollectionTemplateSetting in $groupCollectionTemplateSettings) { $setting = @{} - $setting.add('@odata.type', '#microsoft.graph.deviceManagementConfigurationSetting') + $setting.Add('@odata.type', '#microsoft.graph.deviceManagementConfigurationSetting') $settingInstance = [ordered]@{} - $settingInstance.add('@odata.type', '#microsoft.graph.deviceManagementConfigurationGroupSettingCollectionInstance') - $settingInstance.add('settingDefinitionId', $groupCollectionTemplateSetting.settingDefinitionId) - $settingInstance.add('settingInstanceTemplateReference', @{ + $settingInstance.Add('@odata.type', '#microsoft.graph.deviceManagementConfigurationGroupSettingCollectionInstance') + $settingInstance.Add('settingDefinitionId', $groupCollectionTemplateSetting.settingDefinitionId) + $settingInstance.Add('settingInstanceTemplateReference', @{ '@odata.type' = '#microsoft.graph.deviceManagementConfigurationSettingInstanceTemplateReference' 'settingInstanceTemplateId' = $groupCollectionTemplateSetting.settingInstanceTemplateId }) $groupSettingCollectionValues = @() $groupSettingCollectionValueChildren = @() $groupSettingCollectionValue = @{} - $groupSettingCollectionValue.add('@odata.type', '#microsoft.graph.deviceManagementConfigurationGroupSettingValue') + $groupSettingCollectionValue.Add('@odata.type', '#microsoft.graph.deviceManagementConfigurationGroupSettingValue') $settingValueTemplateId = $groupCollectionTemplateSetting.AdditionalProperties.groupSettingCollectionValueTemplate.settingValueTemplateId if (-Not [string]::IsNullOrEmpty($settingValueTemplateId)) { - $groupSettingCollectionValue.add('settingValueTemplateReference', @{'settingValueTemplateId' = $SettingValueTemplateId }) + $groupSettingCollectionValue.Add('settingValueTemplateReference', @{'settingValueTemplateId' = $SettingValueTemplateId }) } foreach ($key in $DSCParams.keys) @@ -1067,10 +1067,10 @@ function Get-SettingCatalogPolicySettingsFromTemplate $groupSettingCollectionValueChildren += $groupSettingCollectionValueChild } } - $groupSettingCollectionValue.add('children', $groupSettingCollectionValueChildren) + $groupSettingCollectionValue.Add('children', $groupSettingCollectionValueChildren) $groupSettingCollectionValues += $groupSettingCollectionValue - $settingInstance.add('groupSettingCollectionValue', $groupSettingCollectionValues) - $setting.add('settingInstance', $settingInstance) + $settingInstance.Add('groupSettingCollectionValue', $groupSettingCollectionValues) + $setting.Add('settingInstance', $settingInstance) if ($setting.settingInstance.groupSettingCollectionValue.children.count -gt 0) { @@ -1202,7 +1202,7 @@ function ConvertTo-IntunePolicyAssignment } if ($assignment.dataType -like '*CollectionAssignmentTarget') { - $target.add('collectionId', $assignment.collectionId) + $target.Add('collectionId', $assignment.collectionId) } elseif ($assignment.dataType -like '*GroupAssignmentTarget') { @@ -1401,7 +1401,7 @@ function Update-DeviceConfigurationPolicyAssignment #Skipping assignment if group not found from either groupId or groupDisplayName if ($null -ne $group) { - $formattedTarget.add('groupId',$group.Id) + $formattedTarget.Add('groupId',$group.Id) } } if ($target.collectionId) @@ -1735,18 +1735,56 @@ function Get-IntuneSettingCatalogPolicySettingInstanceValue if ($childSettingValue.Keys.Count -gt 0) { - if ($childSettingValue.Keys -notcontains 'settingDefinitionId') + # If only one child item is allowed but we have multiple values, we need to create an object for each child + # Happens e.g. for the IntuneDeviceControlPolicyWindows10 resource --> {ruleid} and {ruleid}_ruledata definitions + if ($childSettingValue.groupSettingCollectionValue.Count -gt 1 -and + $childDefinition.AdditionalProperties.maximumCount -eq 1 -and + $groupSettingCollectionDefinitionChildren.Count -eq 1) { - $childSettingValue.Add('settingDefinitionId', $childDefinition.Id) + $childSettingValueOld = $childSettingValue + $childSettingValue = @() + foreach ($childSettingValueItem in $childSettingValueOld.groupSettingCollectionValue) + { + $childSettingValueInner = @{ + children = @() + } + $childSettingValueItem.Add('@odata.type', $childSettingType) + $childSettingValueInner.children += @{ + '@odata.type' = '#microsoft.graph.deviceManagementConfigurationGroupSettingCollectionInstance' + groupSettingCollectionValue = @( + @{ + children = $childSettingValueItem.children + } + ) + settingDefinitionId = $childDefinition.Id + } + if (-not [string]::IsNullOrEmpty($childSettingInstanceTemplate.settingInstanceTemplateId)) + { + $childSettingValueInner.children[0].groupSettingCollectionValue.settingInstanceTemplateReference = @{ + 'settingInstanceTemplateId' = $childSettingInstanceTemplate.settingInstanceTemplateId + } + } + $childSettingValue += $childSettingValueInner + } + $groupSettingCollectionValue += $childSettingValue } - if (-not [string]::IsNullOrEmpty($childSettingInstanceTemplate.settingInstanceTemplateId)) + else { - $childSettingValue.Add('settingInstanceTemplateReference', @{'settingInstanceTemplateId' = $childSettingInstanceTemplate.settingInstanceTemplateId }) + if ($childSettingValue.Keys -notcontains 'settingDefinitionId') + { + $childSettingValue.Add('settingDefinitionId', $childDefinition.Id) + } + if (-not [string]::IsNullOrEmpty($childSettingInstanceTemplate.settingInstanceTemplateId)) + { + $childSettingValue.Add('settingInstanceTemplateReference', @{'settingInstanceTemplateId' = $childSettingInstanceTemplate.settingInstanceTemplateId }) + } + $childSettingValue.Add('@odata.type', $childSettingType) + $groupSettingCollectionValueChildren += $childSettingValue } - $childSettingValue.Add('@odata.type', $childSettingType) - $groupSettingCollectionValueChildren += $childSettingValue } } + + # Does not happen for wrapped children elements if ($groupSettingCollectionValueChildren.Count -gt 0) { $groupSettingCollectionValue += @{ diff --git a/Modules/Microsoft365DSC/Modules/M365DSCUtil.psm1 b/Modules/Microsoft365DSC/Modules/M365DSCUtil.psm1 index d8e020b073..148c450c1a 100644 --- a/Modules/Microsoft365DSC/Modules/M365DSCUtil.psm1 +++ b/Modules/Microsoft365DSC/Modules/M365DSCUtil.psm1 @@ -3825,6 +3825,10 @@ function Get-M365DSCExportContentForResource { $primaryKey = $Results.DomainName } + elseif ($Keys.Contains('UserPrincipalName')) + { + $primaryKey = $Results.UserPrincipalName + } if ([String]::IsNullOrEmpty($primaryKey) -and ` -not $Keys.Contains('IsSingleInstance')) diff --git a/Modules/Microsoft365DSC/SchemaDefinition.json b/Modules/Microsoft365DSC/SchemaDefinition.json index 08ad6e8253..95916364b2 100644 --- a/Modules/Microsoft365DSC/SchemaDefinition.json +++ b/Modules/Microsoft365DSC/SchemaDefinition.json @@ -2044,6 +2044,56 @@ } ] }, + { + "ClassName": "MSFT_AADAuthenticationRequirement", + "Parameters": [ + { + "CIMType": "String", + "Name": "PerUserMfaState", + "Option": "Write" + }, + { + "CIMType": "String", + "Name": "UserPrincipalName", + "Option": "Key" + }, + { + "CIMType": "MSFT_Credential", + "Name": "Credential", + "Option": "Write" + }, + { + "CIMType": "String", + "Name": "ApplicationId", + "Option": "Write" + }, + { + "CIMType": "String", + "Name": "TenantId", + "Option": "Write" + }, + { + "CIMType": "MSFT_Credential", + "Name": "ApplicationSecret", + "Option": "Write" + }, + { + "CIMType": "String", + "Name": "CertificateThumbprint", + "Option": "Write" + }, + { + "CIMType": "Boolean", + "Name": "ManagedIdentity", + "Option": "Write" + }, + { + "CIMType": "String[]", + "Name": "AccessTokens", + "Option": "Write" + } + ] + }, { "ClassName": "MSFT_AADAuthenticationStrengthPolicy", "Parameters": [ diff --git a/Tests/Integration/Microsoft365DSC/M365DSCIntegration.AAD.Update.Tests.ps1 b/Tests/Integration/Microsoft365DSC/M365DSCIntegration.AAD.Update.Tests.ps1 index c9363e1d89..e28b8587c9 100644 --- a/Tests/Integration/Microsoft365DSC/M365DSCIntegration.AAD.Update.Tests.ps1 +++ b/Tests/Integration/Microsoft365DSC/M365DSCIntegration.AAD.Update.Tests.ps1 @@ -408,6 +408,14 @@ ); State = "enabled"; } + AADAuthenticationRequirement 'AADAuthenticationRequirement-TestMailbox109@xtasdftestorg.onmicrosoft.com' + { + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + PerUserMfaState = "disabled"; + UserPrincipalName = "TestMailbox109@$OrganizationName"; + } AADAuthenticationStrengthPolicy 'AADAuthenticationStrengthPolicy-Example' { AllowedCombinations = @("windowsHelloForBusiness","fido2","deviceBasedPush"); # Updated Property diff --git a/Tests/Unit/Microsoft365DSC/Microsoft365DSC.AADAuthenticationRequirement.Tests.ps1 b/Tests/Unit/Microsoft365DSC/Microsoft365DSC.AADAuthenticationRequirement.Tests.ps1 new file mode 100644 index 0000000000..04b2234a09 --- /dev/null +++ b/Tests/Unit/Microsoft365DSC/Microsoft365DSC.AADAuthenticationRequirement.Tests.ps1 @@ -0,0 +1,161 @@ +[CmdletBinding()] +param( +) +$M365DSCTestFolder = Join-Path -Path $PSScriptRoot ` + -ChildPath '..\..\Unit' ` + -Resolve +$CmdletModule = (Join-Path -Path $M365DSCTestFolder ` + -ChildPath '\Stubs\Microsoft365.psm1' ` + -Resolve) +$GenericStubPath = (Join-Path -Path $M365DSCTestFolder ` + -ChildPath '\Stubs\Generic.psm1' ` + -Resolve) +Import-Module -Name (Join-Path -Path $M365DSCTestFolder ` + -ChildPath '\UnitTestHelper.psm1' ` + -Resolve) + +$CurrentScriptPath = $PSCommandPath.Split('\') +$CurrentScriptName = $CurrentScriptPath[$CurrentScriptPath.Length -1] +$ResourceName = $CurrentScriptName.Split('.')[1] +$Global:DscHelper = New-M365DscUnitTestHelper -StubModule $CmdletModule ` + -DscResource $ResourceName -GenericStubModule $GenericStubPath + +Describe -Name $Global:DscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:DscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:DscHelper.InitializeScript -NoNewScope + BeforeAll { + + $secpasswd = ConvertTo-SecureString (New-Guid | Out-String) -AsPlainText -Force + $Credential = New-Object System.Management.Automation.PSCredential ('tenantadmin@mydomain.com', $secpasswd) + + Mock -CommandName Confirm-M365DSCDependencies -MockWith { + } + + Mock -CommandName New-M365DSCConnection -MockWith { + return "Credentials" + } + + # Mock Write-Host to hide output during the tests + Mock -CommandName Write-Host -MockWith { + } + $Script:exportedInstances =$null + $Script:ExportMode = $false + } + # Test contexts + Context -Name "The instance exists and values are already in the desired state" -Fixture { + BeforeAll { + $testParams = @{ + UserPrincipalName = "user@test.com" + PerUserMfaState = 'Enabled' + Credential = $Credential; + } + + Mock -CommandName Invoke-MgGraphRequest -MockWith { + return @{ + UserPrincipalName = "user@test.com" + PerUserMfaState = 'Enabled' + Credential = $Credential; + } + } + } + + It 'Should return true from the Test method' { + Test-TargetResource @testParams | Should -Be $true + } + } + + Context -Name "The instance exists and values are NOT in the desired state - Enable" -Fixture { + BeforeAll { + $testParams = @{ + UserPrincipalName = "user@test.com" + PerUserMfaState = 'Enabled' + Credential = $Credential; + } + + Mock -CommandName Invoke-MgGraphRequest -MockWith { + return @{ + UserPrincipalName = "user@test.com" + PerUserMfaState = 'Disabled' + Credential = $Credential; + } + } + } + + It 'Should return Values from the Get method' { + (Get-TargetResource @testParams).PerUserMfaState | Should -Be 'Disabled' + } + + It 'Should return false from the Test method' { + Test-TargetResource @testParams | Should -Be $false + } + + It 'Should call the Set method' { + Set-TargetResource @testParams + Should -Invoke -CommandName Invoke-MgGraphRequest -Exactly 1 -ParameterFilter { $Method -eq 'PATCH' } + } + } + + Context -Name "The instance exists and values are NOT in the desired state - Disable" -Fixture { + BeforeAll { + $testParams = @{ + UserPrincipalName = "user@test.com" + PerUserMfaState = 'Disabled' + Credential = $Credential; + } + + Mock -CommandName Invoke-MgGraphRequest -MockWith { + return @{ + UserPrincipalName = "user@test.com" + PerUserMfaState = 'Enabled' + Credential = $Credential; + } + } + } + + It 'Should return Values from the Get method' { + (Get-TargetResource @testParams).PerUserMfaState | Should -Be 'Enabled' + } + + It 'Should return false from the Test method' { + Test-TargetResource @testParams | Should -Be $false + } + + It 'Should call the Set method' { + Set-TargetResource @testParams + Should -Invoke -CommandName Invoke-MgGraphRequest -Exactly 1 -ParameterFilter { $Method -eq 'PATCH' } + } + } + + Context -Name 'ReverseDSC Tests' -Fixture { + BeforeAll { + $Global:CurrentModeIsExport = $true + $Global:PartialExportFileName = "$(New-Guid).partial.ps1" + $testParams = @{ + Credential = $Credential; + } + + Mock -CommandName Invoke-MgGraphRequest -MockWith { + return @{ + UserPrincipalName = "user@test.com" + PerUserMfaState = 'Enabled' + Credential = $Credential; + } + } + + Mock -CommandName Get-MgUser -MockWith { + return @{ + Id = "98ceffcc-7c54-4227-8844-835af5a023ce" + UserPrincipalName = "user@test.com" + Credential = $Credential; + } + } + } + It 'Should Reverse Engineer resource from the Export method' { + $result = Export-TargetResource @testParams + $result | Should -Not -BeNullOrEmpty + } + } + } +} + +Invoke-Command -ScriptBlock $Global:DscHelper.CleanupScript -NoNewScope diff --git a/docs/docs/resources/azure-ad/AADAuthenticationRequirement.md b/docs/docs/resources/azure-ad/AADAuthenticationRequirement.md new file mode 100644 index 0000000000..92c8880213 --- /dev/null +++ b/docs/docs/resources/azure-ad/AADAuthenticationRequirement.md @@ -0,0 +1,86 @@ +# AADAuthenticationRequirement + +## Parameters + +| Parameter | Attribute | DataType | Description | Allowed Values | +| --- | --- | --- | --- | --- | +| **PerUserMfaState** | Write | String | The state of the MFA enablement for the user. Possible values are: enabled, disabled. | `enabled`, `disabled` | +| **UserPrincipalName** | Key | String | The unique identifier for an entity. Read-only. | | +| **Credential** | Write | PSCredential | Credentials of the Admin | | +| **ApplicationId** | Write | String | Id of the Azure Active Directory application to authenticate with. | | +| **TenantId** | Write | String | Id of the Azure Active Directory tenant used for authentication. | | +| **ApplicationSecret** | Write | PSCredential | Secret of the Azure Active Directory tenant used for authentication. | | +| **CertificateThumbprint** | Write | String | Thumbprint of the Azure Active Directory application's authentication certificate to use for authentication. | | +| **ManagedIdentity** | Write | Boolean | Managed ID being used for authentication. | | +| **AccessTokens** | Write | StringArray[] | Access token used for authentication. | | + + +## Description + +Azure AD Authentication Requirement Resource to set up Per-User MFA settings + +## Permissions + +### Microsoft Graph + +To authenticate with the Microsoft Graph API, this resource required the following permissions: + +#### Delegated permissions + +- **Read** + + - UserAuthenticationMethod.Read.All + +- **Update** + + - UserAuthenticationMethod.ReadWrite.All + +#### Application permissions + +- **Read** + + - UserAuthenticationMethod.Read.All + +- **Update** + + - UserAuthenticationMethod.ReadWrite.All + +## Examples + +### Example 1 + +This example is used to test new resources and showcase the usage of new resources being worked on. +It is not meant to use as a production baseline. + +```powershell +Configuration Example +{ + param( + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.String] + $CertificateThumbprint + ) + Import-DscResource -ModuleName Microsoft365DSC + + Node localhost + { + AADAuthenticationRequirement "AADAuthenticationRequirement-TestMailbox109@xtasdftestorg.onmicrosoft.com" + { + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + PerUserMfaState = "disabled"; + UserPrincipalName = "TestMailbox109@$OrganizationName"; + } + } +} +``` +