Skip to content

Commit

Permalink
Merge pull request KelvinTegelaar#411 from KelvinTegelaar/dev
Browse files Browse the repository at this point in the history
Dev to release
  • Loading branch information
KelvinTegelaar authored Aug 27, 2023
2 parents 56c6b53 + ea6d9cf commit 3f5acf2
Show file tree
Hide file tree
Showing 30 changed files with 336 additions and 198 deletions.
46 changes: 1 addition & 45 deletions AddCAPolicy/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -8,54 +8,10 @@ Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -

$Tenants = ($Request.body | Select-Object Select_*).psobject.properties.value
if ("AllTenants" -in $Tenants) { $Tenants = (Get-Tenants).defaultDomainName }
$displayname = ($request.body.RawJSON | ConvertFrom-Json).Displayname
function Remove-EmptyArrays ($Object) {
if ($Object -is [Array]) {
foreach ($Item in $Object) { Remove-EmptyArrays $Item }
}
elseif ($Object -is [HashTable]) {
foreach ($Key in @($Object.get_Keys())) {
if ($Object[$Key] -is [Array] -and $Object[$Key].get_Count() -eq 0) {
$Object.Remove($Key)
}
else { Remove-EmptyArrays $Object[$Key] }
}
}
elseif ($Object -is [PSCustomObject]) {
foreach ($Name in @($Object.psobject.properties.Name)) {
if ($Object.$Name -is [Array] -and $Object.$Name.get_Count() -eq 0) {
$Object.PSObject.Properties.Remove($Name)
}
elseif ($object.$name -eq $null) {
$Object.PSObject.Properties.Remove($Name)
}
else { Remove-EmptyArrays $Object.$Name }
}
}
}

$JSONObj = $request.body.RawJSON | ConvertFrom-Json | Select-Object * -ExcludeProperty ID, GUID, *time*
Remove-EmptyArrays $JSONObj
#Remove context as it does not belong in the payload.
$JsonObj.grantControls.PSObject.Properties.Remove('[email protected]')
if ($JSONObj.conditions.users.excludeGuestsOrExternalUsers.externalTenants.Members) {
$JsonObj.conditions.users.excludeGuestsOrExternalUsers.externalTenants.PSObject.Properties.Remove('@odata.context')
$JsonObj.conditions.users.excludeGuestsOrExternalUsers.externalTenants.PSObject.Properties.Remove('@odata.type')
}
if ($Request.body.newstate -and $Request.body.newstate -ne 'donotchange') {
$Jsonobj.state = $Request.body.newstate
}
$RawJSON = $JSONObj | ConvertTo-Json -Depth 10

$results = foreach ($Tenant in $tenants) {
try {
$CheckExististing = New-GraphGETRequest -uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies" -tenantid $tenant
$PolicyName = ($RawJSON | ConvertFrom-Json).displayName
if ($PolicyName -in $CheckExististing.displayName) {
Throw "Conditional Access Policy with Display Name $($Displayname) Already exists"
}

$CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/identity/conditionalAccess/policies" -tenantid $tenant -type POST -body $RawJSON
$CAPolicy = New-CIPPCAPolicy -TenantFilter $tenant -state $request.body.NewState -RawJSON $Request.body.RawJSON -APIName $APIName -ExecutingUser $request.headers.'x-ms-client-principal'
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Added Conditional Access Policy $($Displayname)" -Sev "Error"
"Successfully added Conditional Access Policy for $($Tenant)"
}
Expand Down
25 changes: 23 additions & 2 deletions AddCATemplate/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ param($Request, $TriggerMetadata)

$APIName = $TriggerMetadata.FunctionName
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Accessed this API" -Sev "Debug"
Write-Host ($request | ConvertTo-Json -Compress)

$TenantFilter = $Request.Query.TenantFilter
try {
$GUID = (New-Guid).GUID
$JSON = if ($request.body.rawjson) {
Expand All @@ -18,7 +18,28 @@ try {
$_ | Select-Object -Property $NonEmptyProperties
}
}
$JSON = ($JSON | ConvertTo-Json -Depth 10)

$includelocations = New-Object System.Collections.ArrayList
$IncludeJSON = foreach ($Location in $JSON.conditions.locations.includeLocations) {
$locationinfo = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/identity/conditionalAccess/namedLocations" -tenantid $TenantFilter | Where-Object -Property id -EQ $location | Select-Object * -ExcludeProperty id, *time*
$null = if ($locationinfo) { $includelocations.add($locationinfo.displayName) } else { $includelocations.add($location) }
$locationinfo
}
if ($includelocations) { $JSON.conditions.locations.includeLocations = $includelocations }


$excludelocations = New-Object System.Collections.ArrayList
$ExcludeJSON = foreach ($Location in $JSON.conditions.locations.excludeLocations) {
$locationinfo = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/identity/conditionalAccess/namedLocations" -tenantid $TenantFilter | Where-Object -Property id -EQ $location | Select-Object * -ExcludeProperty id, *time*
$null = if ($locationinfo) { $excludelocations.add($locationinfo.displayName) } else { $excludelocations.add($location) }
$locationinfo
}

if ($excludelocations) { $JSON.conditions.locations.excludeLocations = $excludelocations }

$JSON | Add-Member -NotePropertyName 'LocationInfo' -NotePropertyValue @($IncludeJSON, $ExcludeJSON)

$JSON = ($JSON | ConvertTo-Json -Depth 100)
$Table = Get-CippTable -tablename 'templates'
$Table.Force = $true
Add-AzDataTableEntity @Table -Entity @{
Expand Down
1 change: 1 addition & 0 deletions AddNamedLocation/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Write-Host "PowerShell HTTP trigger function processed a request."
# Input bindings are passed in via param block.
$Tenants = $request.body.selectedTenants.defaultDomainName
Write-Host ($Request.body | ConvertTo-Json)
if ($Tenants -eq "AllTenants") { $Tenants = (Get-Tenants).defaultDomainName }
$results = foreach ($Tenant in $tenants) {
try {
$ObjBody = if ($Request.body.Type -eq "IPLocation") {
Expand Down
6 changes: 3 additions & 3 deletions Config/CIPPDefaultTable.BPATemplate.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
{
"name": "OAuthAppConsent",
"API": "Graph",
"URL": "https://graph.microsoft.com/beta/policies/authorizationPolicy/authorizationPolicy",
"ExtractFields": "permissionGrantPolicyIdsAssignedToDefaultUserRole",
"where": "'ManagePermissionGrantsForSelf.microsoft-user-default-legacy' -notin $_.permissionGrantPolicyIdsAssignedToDefaultUserRole",
"URL": "https://graph.microsoft.com/v1.0/policies/authorizationPolicy?$select=defaultUserRolePermissions",
"ExtractFields": "defaultuserrolepermissions",
"where": "'ManagePermissionGrantsForSelf.microsoft-user-default-legacy' -notin $_.defaultuserrolepermissions.permissionGrantPoliciesAssigned",
"StoreAs": "bool",
"FrontendFields": [
{
Expand Down
15 changes: 5 additions & 10 deletions DomainAnalyser_GetTenantDomains/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ $TenantDomains = $Tenants | ForEach-Object -Parallel {
$Tenant = $_
# Get Domains to Lookup
try {
$Domains = New-GraphGetRequest -uri 'https://graph.microsoft.com/v1.0/domains' -tenantid $Tenant.defaultDomainName | Where-Object { ($_.id -notlike '*.onmicrosoft.com' -and $_.id -notlike '*.microsoftonline.com' -and $_.id -NotLike '*.exclaimer.cloud' -and $_.id -NotLike '*.codetwo.online' -and $_.id -NotLike '*.call2teams.com' -and $_.isVerified) }
$Domains = New-GraphGetRequest -uri 'https://graph.microsoft.com/v1.0/domains' -tenantid $Tenant.defaultDomainName | Where-Object { ($_.id -notlike '*.microsoftonline.com' -and $_.id -NotLike '*.exclaimer.cloud' -and $_.id -NotLike '*.codetwo.online' -and $_.id -NotLike '*.call2teams.com' -and $_.isVerified) }
foreach ($d in $domains) {
[PSCustomObject]@{
Tenant = $Tenant.defaultDomainName
Expand All @@ -23,8 +23,7 @@ $TenantDomains = $Tenants | ForEach-Object -Parallel {
SupportedServices = $d.supportedServices
}
}
}
catch {
} catch {
Write-LogMessage -API 'DomainAnalyser' -tenant $tenant.defaultDomainName -message "DNS Analyser GraphGetRequest Exception: $($_.Exception.Message)" -sev Error
}
} | Sort-Object -Unique -Property Domain
Expand All @@ -40,7 +39,6 @@ foreach ($Exclude in $ExcludedTenants) {
}
}


$TenantCount = ($TenantDomains | Measure-Object).Count
if ($TenantCount -gt 0) {
Write-Host "$TenantCount tenant Domains"
Expand Down Expand Up @@ -75,8 +73,7 @@ if ($TenantCount -gt 0) {
$DomainObject.MailProviders = $OldDomain.MailProviders
}
$Domain = $DomainObject
}
else {
} else {
$Domain.TenantDetails = $TenantDetails
if ($OldDomain) {
$Domain.DkimSelectors = $OldDomain.DkimSelectors
Expand All @@ -90,8 +87,6 @@ if ($TenantCount -gt 0) {
# Batch insert all tenant domains
try {
Add-AzDataTableEntity @DomainTable -Entity $TenantDomainObjects -Force
}
catch { Write-LogMessage -API 'DomainAnalyser' -message "Domain Analyser GetTenantDomains Error $($_.Exception.Message)" -sev info }
}
catch { Write-LogMessage -API 'DomainAnalyser' -message "GetTenantDomains loop exception: $($_.Exception.Message) line $($_.InvocationInfo.ScriptLineNumber)" -sev "Error"}
} catch { Write-LogMessage -API 'DomainAnalyser' -message "Domain Analyser GetTenantDomains Error $($_.Exception.Message)" -sev info }
} catch { Write-LogMessage -API 'DomainAnalyser' -message "GetTenantDomains loop exception: $($_.Exception.Message) line $($_.InvocationInfo.ScriptLineNumber)" -sev 'Error' }
}
20 changes: 14 additions & 6 deletions EditTenant/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ $tokens = try {
$tenantObjectId = $allTenantsDetails.value | Where-Object { $_.customerContextId -eq $customerContextId } | Select-Object 'objectId'
}
catch {
"Failed to retrieve list of tenants. Error: $($_.Exception.Message)"
$Results = "Failed to retrieve list of tenants. Error: $($_.Exception.Message)"
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantDisplayName) -message "Failed to retrieve list of tenants. Error: $($_.Exception.Message)" -Sev 'Error'
}

Expand All @@ -27,18 +27,26 @@ if ($tenantObjectId) {
$bodyToPatch = '{"displayName":"' + $tenantDisplayName + '","defaultDomainName":"' + $tenantDefaultDomainName + '"}'
$patchTenant = (Invoke-RestMethod -Method PATCH -Uri "https://graph.windows.net/myorganization/contracts/$($tenantObjectId.objectId)?api-version=1.6" -Body $bodyToPatch -ContentType 'application/json' -Headers $AADGraphtoken -ErrorAction Stop)
$Filter = "PartitionKey eq 'Tenants' and defaultDomainName eq '{0}'" -f $tenantDefaultDomainName
$TenantsTable = Get-CippTable -tablename Tenants
$Tenant = Get-AzDataTableEntity @TenantsTable -Filter $Filter
$Tenant.displayName = $tenantDisplayName
Update-AzDataTableEntity @TenantsTable -Entity $Tenant
try {
$TenantsTable = Get-CippTable -tablename Tenants
$Tenant = Get-AzDataTableEntity @TenantsTable -Filter $Filter
$Tenant.displayName = $tenantDisplayName
Update-AzDataTableEntity @TenantsTable -Entity $Tenant
}
catch {
$AddedText = "but could not edit the tenant cache. Clear the tenant cache to display the updated details"
}
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantDisplayName -message "Edited tenant $tenantDisplayName" -Sev 'Info'
$results = "Successfully amended details for $($Tenant.displayName)"
$results = "Successfully amended details for $($Tenant.displayName) $AddedText"
}
catch {
$results = "Failed to amend details for $tenantDisplayName : $($_.Exception.Message)"
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenantDisplayName -message "Failed amending details $tenantDisplayName. Error: $($_.Exception.Message)" -Sev 'Error'
}
}
else {
$Results = "Could not find the tenant to edit in the contract endpoint. Please ensure you have a reseller relationship with the tenant you are trying to edit."
}

$body = [pscustomobject]@{'Results' = $results }

Expand Down
2 changes: 1 addition & 1 deletion ExecAccessChecks/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ if ($Request.query.Permissions -eq 'true') {
$KeyVaultRefresh = Get-AzKeyVaultSecret -VaultName $kv -Name 'RefreshToken' -AsPlainText
if ($ENV:RefreshToken -ne $KeyVaultRefresh) {
$Success = $false
$Messages.Add('Your refresh token does not match key vault, follow the Clear Token Cache procedure.') | Out-Null
$Messages.Add('Your refresh token does not match key vault, clear your cache or wait 30 minutes.') | Out-Null
$Links.Add([PSCustomObject]@{
Text = 'Clear Token Cache'
Href = 'https://cipp.app/docs/general/troubleshooting/#clear-token-cache'
Expand Down
6 changes: 3 additions & 3 deletions ExecCPVPermissions/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,10 @@ foreach ($Grant in $grants) {
"Failed to grant $($grant.appRoleId) to $($grant.resourceId): $($_.Exception.Message). "
}
}
$StatusCode = [HttpStatusCode]::OK


# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = $StatusCode
Body = @(@{Results = $GraphRequest })
StatusCode = [HttpStatusCode]::OK
Body = @{Results = $GraphRequest }
})
37 changes: 28 additions & 9 deletions ExecDnsConfig/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ try {
if ($ValidResolvers -contains $Resolver) {
try {
$Config.Resolver = $Resolver
}
catch {
} catch {
$Config = @{
Resolver = $Resolver
}
Expand All @@ -53,28 +52,48 @@ try {
}
if ($updated) {
Add-AzDataTableEntity @ConfigTable -Entity $Config -Force
Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message 'DNS configuration updated' -Sev 'Info'
Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message 'DNS configuration updated' -Sev 'Info'
$body = [pscustomobject]@{'Results' = 'Success: DNS configuration updated.' }
}
else {
} else {
$StatusCode = [HttpStatusCode]::BadRequest
$body = [pscustomobject]@{'Results' = 'Error: No DNS resolver provided.' }
}
}
'SetDkimConfig' {
$Domain = $Request.Query.Domain
$Selector = ($Request.Query.Selector).trim() -split '\s*,\s*'
$DomainTable = Get-CIPPTable -Table 'Domains'
$Filter = "RowKey eq '{0}'" -f $Domain
$DomainInfo = Get-AzDataTableEntity @DomainTable -Filter $Filter
$DkimSelectors = [string]($Selector | ConvertTo-Json -Compress)
if ($DomainInfo) {
$DomainInfo.DkimSelectors = $DkimSelectors
} else {
$DomainInfo = @{
'RowKey' = $Request.Query.Domain
'PartitionKey' = 'ManualEntry'
'TenantId' = 'NoTenant'
'MailProviders' = ''
'TenantDetails' = ''
'DomainAnalyser' = ''
'DkimSelectors' = $DkimSelectors
}
}
Add-AzDataTableEntity @DomainTable -Entity $DomainInfo -Force
}
'GetConfig' {
$body = [pscustomobject]$Config
Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message 'Retrieved DNS configuration' -Sev 'Info'
Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message 'Retrieved DNS configuration' -Sev 'Info'
}
'RemoveDomain' {
$Filter = "RowKey eq '{0}'" -f $Request.Query.Domain
$DomainRow = Get-AzDataTableEntity @DomainTable -Filter $Filter
$DomainRow = Get-AzDataTableEntity @DomainTable -Filter $Filter
Remove-AzDataTableEntity @DomainTable -Entity $DomainRow
Write-LogMessage -API $APINAME -tenant 'Global' -user $request.headers.'x-ms-client-principal' -message "Removed Domain - $($Request.Query.Domain) " -Sev 'Info'
$body = [pscustomobject]@{ 'Results' = "Domain removed - $($Request.Query.Domain)" }
}
}
}
catch {
} catch {
Write-LogMessage -API $APINAME -tenant $($name) -user $request.headers.'x-ms-client-principal' -message "DNS Config API failed. $($_.Exception.Message)" -Sev 'Error'
$body = [pscustomobject]@{'Results' = "Failed. $($_.Exception.Message)" }
$StatusCode = [HttpStatusCode]::BadRequest
Expand Down
2 changes: 1 addition & 1 deletion ExecExtensionsConfig/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ $results = try {
if ($request.body.$APIKey.APIKey) {
$null = Set-AzKeyVaultSecret -VaultName $ENV:WEBSITE_DEPLOYMENT_ID -Name $APIKey -SecretValue (ConvertTo-SecureString -String $request.body.$APIKey.APIKey -AsPlainText -Force)
}
$request.body.$APIKey = @{ APIKey = "SentToKeyVault" }
$request.body.$APIKey.APIKey = "SentToKeyVault"
}
}
$body = $request.body | Select-Object * -ExcludeProperty APIKey, Enabled | ConvertTo-Json -Depth 10 -Compress
Expand Down
2 changes: 1 addition & 1 deletion ExecGDAPInviteApproved_Timer/function.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"name": "Timer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 0 */3 * * 0"
"schedule": "0 0 */3 * * *"
},
{
"type": "queue",
Expand Down
9 changes: 7 additions & 2 deletions ExecSAMSetup/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ if ($env:MSI_SECRET) {
Disable-AzContextAutosave -Scope Process | Out-Null
$AzSession = Connect-AzAccount -Identity
}
if (!$ENV:SetFromProfile) {
Write-Host "We're reloading from KV"
Get-CIPPAuthentication
}

$KV = $ENV:WEBSITE_DEPLOYMENT_ID
$Table = Get-CIPPTable -TableName SAMWizard
$Rows = Get-AzDataTableEntity @Table | Where-Object -Property Timestamp -GT (Get-Date).AddMinutes(-10)
Expand All @@ -40,7 +45,7 @@ try {
if ($request.body.RefreshToken) { Set-AzKeyVaultSecret -VaultName $kv -Name 'RefreshToken' -SecretValue (ConvertTo-SecureString -String $request.body.RefreshToken -AsPlainText -Force) }
if ($request.body.applicationid) { Set-AzKeyVaultSecret -VaultName $kv -Name 'applicationid' -SecretValue (ConvertTo-SecureString -String $request.body.applicationid -AsPlainText -Force) }
if ($request.body.applicationsecret) { Set-AzKeyVaultSecret -VaultName $kv -Name 'applicationsecret' -SecretValue (ConvertTo-SecureString -String $request.body.applicationsecret -AsPlainText -Force) }
$Results = @{ Results = "Replaced keys successfully. Please clear your token cache or wait 24 hours for the cache to be cleared." }
$Results = @{ Results = "The keys have been replaced. Please perform a permissions check." }
}
if ($Request.query.error -eq 'invalid_client') { $Results = "Client ID was not found in Azure. Try waiting 10 seconds to try again, if you have gotten this error after 5 minutes, please restart the process." }
if ($request.query.code) {
Expand Down Expand Up @@ -177,7 +182,7 @@ try {
Remove-AzDataTableEntity @Table -Entity $Rows

$step = 5
$Results = @{"message" = "Installation completed. You must perform a token cache clear. For instructions click "; step = $step ; url = "https://cipp.app/docs/general/troubleshooting/#clear-token-cache"
$Results = @{"message" = "Installation completed."; step = $step
}
}
}
Expand Down
Loading

0 comments on commit 3f5acf2

Please sign in to comment.