Skip to content

Commit

Permalink
Merge pull request #42 from KelvinTegelaar/master
Browse files Browse the repository at this point in the history
[pull] master from KelvinTegelaar:master
  • Loading branch information
pull[bot] authored Aug 4, 2024
2 parents b5329b5 + ebf0ca9 commit a788d47
Show file tree
Hide file tree
Showing 46 changed files with 1,527 additions and 250 deletions.
26 changes: 26 additions & 0 deletions Modules/CIPPCore/Public/Add-CIPPAlias.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
function Add-CIPPAlias {
[CmdletBinding()]
param (
$user,
$Aliases,
$UserprincipalName,
$TenantFilter,
$APIName = 'Set Manager',
$ExecutingUser
)

try {
foreach ($Alias in $Aliases) {
Write-Host "Adding alias $Alias to $user"
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$user" -tenantid $TenantFilter -type 'patch' -body "{`"mail`": `"$Alias`"}" -verbose
}
Write-Host "Resetting primary alias to $User"
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($user)" -tenantid $TenantFilter -type 'patch' -body "{`"mail`": `"$User`"}" -verbose
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Added alias $($Alias) to $($UserprincipalName)" -Sev 'Info'
return ("Added Aliases: $($Aliases -join ',')")
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Failed to set alias. Error:$($_.Exception.Message)" -Sev 'Error'
throw "Failed to set alias: $($_.Exception.Message)"
}
}

22 changes: 22 additions & 0 deletions Modules/CIPPCore/Public/Alerts/Get-CIPPAlertDeviceCompliance.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

function Get-CIPPAlertDeviceCompliance {
<#
.FUNCTIONALITY
Entrypoint
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[Alias('input')]
$InputValue,
$TenantFilter
)
try {
$AlertData = New-GraphGETRequest -uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?`$top=999" -tenantid $TenantFilter | Where-Object -Property complianceState -NE 'compliant' | ForEach-Object {
$_ | Select-Object -Property id, deviceName, deviceType, complianceState, lastReportedDateTime
}
Write-AlertTrace -cmdletName $MyInvocation.MyCommand -tenantFilter $TenantFilter -data $AlertData
} catch {
Write-AlertMessage -tenant $($TenantFilter) -message "Could not get compliance state for $($TenantFilter): $(Get-NormalizedError -message $_.Exception.message)"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,12 @@ function Push-DomainAnalyserDomain {
if (![string]::IsNullOrEmpty($DomainObject.DkimSelectors)) {
$DkimParams.Selectors = $DomainObject.DkimSelectors | ConvertFrom-Json
}
# Check if its a onmicrosoft.com domain and add special selectors for these
if ($Domain -match 'onmicrosoft.com' -and $Domain -notmatch 'mail.onmicrosoft.com') {
$DKIMSelector1Value = "selector1-$($Domain -replace '\.', '-' )"
$DKIMSelector2Value = "selector2-$($Domain -replace '\.', '-' )"
$DkimParams.Add('Selectors', @("$DKIMSelector1Value", "$DKIMSelector2Value"))
}

$DkimRecord = Read-DkimRecord @DkimParams -ErrorAction Stop

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function Push-ListGraphRequestQueue {
Get-GraphRequestList @GraphRequestParams
} catch {
[PSCustomObject]@{
Tenant = $Item.Tenant
Tenant = $Item.TenantFilter
CippStatus = "Could not connect to tenant. $($_.Exception.message)"
}
}
Expand All @@ -62,4 +62,4 @@ function Push-ListGraphRequestQueue {
Write-Information "Queue Error: $($_.Exception.Message)"
throw $_
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ Function Push-ExecOnboardTenantQueue {
if ($AccessAssignments.id -and !$Invite) {
$MissingRoles = [System.Collections.Generic.List[object]]::new()
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = 'Relationship has existing access assignments, checking for missing mappings' })
#Write-Host ($AccessAssignments | ConvertTo-Json -Depth 5)

if ($Item.Roles -and $Item.AutoMapRoles -eq $true) {
foreach ($Role in $Item.Roles) {
if ($AccessAssignments.accessContainer.accessContainerid -notcontains $Role.GroupId -and $Relationship.accessDetails.unifiedRoles.roleDefinitionId -contains $Role.roleDefinitionId) {
Expand All @@ -161,7 +161,7 @@ Function Push-ExecOnboardTenantQueue {
}
}

if (!$AccessAssignments.id -and !$Invite -and $Item.Roles) {
if (!$AccessAssignments.id -and $Item.Roles) {
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = 'No access assignments found, using defined role mapping.' })
$MatchingRoles = [System.Collections.Generic.List[object]]::new()
foreach ($Role in $Item.Roles) {
Expand All @@ -177,7 +177,7 @@ Function Push-ExecOnboardTenantQueue {
'InviteUrl' = 'https://admin.microsoft.com/AdminPortal/Home#/partners/invitation/granularAdminRelationships/{0}' -f $Id
'RoleMappings' = [string](@($MatchingRoles) | ConvertTo-Json -Depth 10 -Compress)
}
Add-CIPPAzDataTableEntity @InviteTable -Entity $Invite
Add-CIPPAzDataTableEntity @InviteTable -Entity $Invite -Force
$GroupSuccess = $true
} else {
$TenantOnboarding.Status = 'failed'
Expand Down Expand Up @@ -292,10 +292,10 @@ Function Push-ExecOnboardTenantQueue {
}
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = 'Added initial CPV consent permissions' })
} catch {
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = 'CPV Consent Failed' })
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = ('CPV Consent Failed, error: {0}' -f $Consent) })
$TenantOnboarding.Status = 'failed'
$OnboardingSteps.Step4.Status = 'failed'
$OnboardingSteps.Step4.Message = 'CPV Consent failed, check the App Registration in your partner tenant for missing admin consent.'
$OnboardingSteps.Step4.Message = 'CPV Consent failed, check the logs for more details.'
$TenantOnboarding.OnboardingSteps = [string](ConvertTo-Json -InputObject $OnboardingSteps -Compress)
$TenantOnboarding.Logs = [string](ConvertTo-Json -InputObject @($Logs) -Compress)
Add-CIPPAzDataTableEntity @OnboardTable -Entity $TenantOnboarding -Force -ErrorAction Stop
Expand All @@ -309,13 +309,15 @@ Function Push-ExecOnboardTenantQueue {
$TenantOnboarding.OnboardingSteps = [string](ConvertTo-Json -InputObject $OnboardingSteps -Compress)
$TenantOnboarding.Logs = [string](ConvertTo-Json -InputObject @($Logs) -Compress)
Add-CIPPAzDataTableEntity @OnboardTable -Entity $TenantOnboarding -Force -ErrorAction Stop
$LastCPVError = ''
do {
try {
Add-CIPPApplicationPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Relationship.customer.tenantId
Add-CIPPDelegatedPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Relationship.customer.tenantId
$CPVSuccess = $true
$Refreshing = $false
} catch {
$LastCPVError = $_.Exception.Message
Start-Sleep -Seconds 30
}
} while ($Refreshing -and (Get-Date) -lt $Start.AddMinutes(8))
Expand All @@ -328,10 +330,10 @@ Function Push-ExecOnboardTenantQueue {
$Tenant = Get-Tenants -TriggerRefresh -IncludeAll | Where-Object { $_.customerId -eq $Relationship.customer.tenantId } | Select-Object -First 1
}
} else {
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = 'CPV permissions failed to refresh' })
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = 'CPV permissions failed to refresh. {0}' -f $LastCPVError })
$TenantOnboarding.Status = 'failed'
$OnboardingSteps.Step4.Status = 'failed'
$OnboardingSteps.Step4.Message = 'CPV permissions failed to refresh, try again later'
$OnboardingSteps.Step4.Message = 'CPV permissions failed to refresh, check the logs for more details.'
}
} else {
$Logs.Add([PSCustomObject]@{ Date = Get-Date -UFormat $DateFormat; Log = 'Tenant not found' })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function Push-ListMFAUsersQueue {
Write-Host "PowerShell queue trigger function processed work item: $($Item.defaultDomainName)"

try {
Update-CippQueueEntry -RowKey $Item.QueueId -Status 'Running' -Name $Item.displayName
#Update-CippQueueEntry -RowKey $Item.QueueId -Status 'Running' -Name $Item.displayName
$domainName = $Item.defaultDomainName
$Table = Get-CIPPTable -TableName cachemfa
Try {
Expand All @@ -29,6 +29,12 @@ function Push-ListMFAUsersQueue {
RowKey = [string]"$domainName"
PartitionKey = 'users'
}
} else {
$GraphRequest = foreach ($Request in $GraphRequest) {
$Request.CAPolicies = try { [string](@($Request.CAPolicies) | ConvertTo-Json -Compress -Depth 5) } catch { [string]$Request.CAPolicies }
$Request.MFAMethods = try { [string](@($Request.MFAMethods) | ConvertTo-Json -Compress -Depth 5) } catch { [string]$Request.MFAMethods }
$Request
}
}
Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force | Out-Null

Expand All @@ -47,7 +53,7 @@ function Push-ListMFAUsersQueue {
}
Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force | Out-Null
} finally {
Update-CippQueueEntry -RowKey $QueueItem -Status 'Completed'
#Update-CippQueueEntry -RowKey $QueueItem -Status 'Completed'
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,50 @@ function Push-UpdatePermissionsQueue {
Entrypoint
#>
param($Item)
Write-Host "Applying permissions for $($Item.defaultDomainName)"
$Table = Get-CIPPTable -TableName cpvtenants
$CPVRows = Get-CIPPAzDataTableEntity @Table | Where-Object -Property Tenant -EQ $Item.customerId
if (!$CPVRows -or $ENV:ApplicationID -notin $CPVRows.applicationId) {
Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message 'A New tenant has been added, or a new CIPP-SAM Application is in use' -Sev 'Warn' -API 'NewTenant'
Write-Host 'Adding CPV permissions'
Set-CIPPCPVConsent -Tenantfilter $Item.customerId
}

Add-CIPPApplicationPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
Add-CIPPDelegatedPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
try {
$DomainRefreshRequired = $false

if (!$Item.defaultDomainName) {
$DomainRefreshRequired = $true
}

Write-Information "Applying permissions for $($Item.displayName)"
$Table = Get-CIPPTable -TableName cpvtenants
$CPVRows = Get-CIPPAzDataTableEntity @Table | Where-Object -Property Tenant -EQ $Item.customerId

if (!$CPVRows -or $ENV:ApplicationID -notin $CPVRows.applicationId) {
Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message 'A New tenant has been added, or a new CIPP-SAM Application is in use' -Sev 'Warn' -API 'NewTenant'
Write-Information 'Adding CPV permissions'
Set-CIPPCPVConsent -Tenantfilter $Item.customerId
$DomainRefreshRequired = $true
}
Write-Information 'Updating permissions'
Add-CIPPApplicationPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
Add-CIPPDelegatedPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message "Updated permissions for $($Item.displayName)" -Sev 'Info' -API 'UpdatePermissionsQueue'

Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message "Updated permissions for $($Item.displayName)" -Sev 'Info' -API 'UpdatePermissionsQueue'
}
Write-Information 'Pushing CIPP-SAM admin roles'
Set-CIPPSAMAdminRoles -TenantFilter $Item.customerId

$Table = Get-CIPPTable -TableName cpvtenants
$unixtime = [int64](([datetime]::UtcNow) - (Get-Date '1/1/1970')).TotalSeconds
$GraphRequest = @{
LastApply = "$unixtime"
applicationId = "$($ENV:applicationId)"
Tenant = "$($Item.customerId)"
PartitionKey = 'Tenant'
RowKey = "$($Item.customerId)"
}
Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force

if ($DomainRefreshRequired) {
$UpdatedTenant = Get-Tenants -TenantFilter $Item.customerId -TriggerRefresh
if ($UpdatedTenant.defaultDomainName) {
Write-Information "Updated tenant domains $($UpdatedTenant.defaultDomainName)"
}
}
} catch {
Write-Information "Error updating permissions for $($Item.displayName)"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ function Push-AuditLogTenant {
}

if (($NewBundles | Measure-Object).Count -gt 0) {
Add-CIPPAzDataTableEntity @AuditBundleTable -Entity $NewBundles
Add-CIPPAzDataTableEntity @AuditBundleTable -Entity $NewBundles -Force
Write-Information ($NewBundles | ConvertTo-Json -Depth 5 -Compress)

$Batch = $NewBundles | Select-Object @{Name = 'ContentId'; Expression = { $_.RowKey } }, @{Name = 'TenantFilter'; Expression = { $_.PartitionKey } }, @{Name = 'FunctionName'; Expression = { 'AuditLogBundleProcessing' } }
Expand All @@ -62,4 +62,4 @@ function Push-AuditLogTenant {
Write-Host "Started orchestration with ID = '$InstanceId'"
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ function Push-Schedulerwebhookcreation {
if ($Row.tenantid -ne 'AllTenants') {
Remove-AzDataTableEntity @Table -Entity $Row
}
if (($Webhook | Measure-Object).Count -gt 1) {
$Webhook = $Webhook | Select-Object -First 1
$WebhooksToRemove = $ExistingWebhooks | Where-Object { $_.RowKey -ne $Webhook.RowKey }
foreach ($RemoveWebhook in $WebhooksToRemove) {
Remove-AzDataTableEntity @WebhookTable -Entity $RemoveWebhook
}
}
} else {
Write-Information "No existing webhook for $Tenant - $($Row.webhookType) - Time to create."
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,13 @@ Function Invoke-ExecExtensionsConfig {
Write-Information 'PowerShell HTTP trigger function processed a request.'
$results = try {
if ($Request.Body.CIPPAPI.Enabled) {
$APIConfig = New-CIPPAPIConfig -ExecutingUser $Request.Headers.'x-ms-client-principal' -resetpassword $Request.Body.CIPPAPI.ResetPassword
$AddedText = $APIConfig.Results
try {
$APIConfig = New-CIPPAPIConfig -ExecutingUser $Request.Headers.'x-ms-client-principal' -resetpassword $Request.Body.CIPPAPI.ResetPassword
$AddedText = $APIConfig.Results
} catch {
$AddedText = ' Could not enable CIPP-API. Check the CIPP documentation for API requirements.'
$Request.Body = $Request.Body | Select-Object * -ExcludeProperty CIPPAPI
}
}

# Check if NinjaOne URL is set correctly and the instance has at least version 5.6
Expand All @@ -31,7 +36,7 @@ Function Invoke-ExecExtensionsConfig {
throw "Failed to connect to NinjaOne check your Instance is set correctly eg 'app.ninjarmmm.com'"
}
if ($Version -lt [version]'5.6.0.0') {
throw 'NinjaOne 5.6.0.0 is required. This will be rolling out regionally between the end of November and mid-December. Please try again at a later date.'
throw 'NinjaOne 5.6.0.0 is required.'
}
}

Expand Down Expand Up @@ -84,9 +89,9 @@ Function Invoke-ExecExtensionsConfig {
Add-AzDataTableEntity @ConfigTable -Entity $AddObject -Force

Register-CIPPExtensionScheduledTasks
"Successfully set the configuration. $AddedText"
"Successfully saved the extension configuration. $AddedText"
} catch {
"Failed to set configuration: $($_.Exception.message) Linenumber: $($_.InvocationInfo.ScriptLineNumber)"
"Failed to save the extensions configuration: $($_.Exception.message) Linenumber: $($_.InvocationInfo.ScriptLineNumber)"
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Function Invoke-ExecCPVPermissions {

Write-Host "Our tenant is $($Tenant.displayName) - $($Tenant.defaultDomainName)"

$TenantFilter = $Request.Query.TenantFilter
$CPVConsentParams = @{
TenantFilter = $Request.Query.TenantFilter
}
Expand All @@ -27,24 +28,29 @@ Function Invoke-ExecCPVPermissions {
}

$GraphRequest = try {
Set-CIPPCPVConsent @CPVConsentParams
Add-CIPPApplicationPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Request.Query.TenantFilter
Add-CIPPDelegatedPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Request.Query.TenantFilter
if ($TenantFilter -ne 'PartnerTenant') {
Set-CIPPCPVConsent @CPVConsentParams
} else {
$TenantFilter = $env:TenantId
}
Add-CIPPApplicationPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $TenantFilter
Add-CIPPDelegatedPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $TenantFilter
Set-CIPPSAMAdminRoles -TenantFilter $TenantFilter
$Success = $true
} catch {
"Failed to update permissions for $($Tenant.displayName): $($_.Exception.Message)"
$Success = $false
}

$Tenant = Get-Tenants -IncludeAll | Where-Object -Property customerId -EQ $TenantFilter
$Tenant = Get-Tenants -IncludeAll | Where-Object -Property customerId -EQ $TenantFilter | Select-Object -First 1

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = @{
Results = $GraphRequest
Metadata = @{
Heading = 'CPV Permission - {0} ({1})' -f $Tenant.displayName, $Tenant.defaultDomainName
Heading = ('CPV Permission - {0} ({1})' -f $Tenant.displayName, $Tenant.defaultDomainName)
Success = $Success
}
}
Expand Down
Loading

0 comments on commit a788d47

Please sign in to comment.