Skip to content

Commit

Permalink
Merge branch 'KelvinTegelaar:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
pcollinsISL authored Jan 13, 2024
2 parents 3f1e5d4 + 36be990 commit cebc117
Show file tree
Hide file tree
Showing 18 changed files with 215 additions and 153 deletions.
26 changes: 14 additions & 12 deletions Modules/CIPPCore/Public/Add-CIPPApplicationPermission.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,44 @@ function Add-CIPPApplicationPermission {
$ApplicationId,
$Tenantfilter
)
if ($ApplicationId -eq $ENV:ApplicationID -and $Tenantfilter -eq $env:TenantID) {
return @('Cannot modify application permissions for CIPP-SAM on partner tenant')
}
Set-Location (Get-Item $PSScriptRoot).FullName
if ($RequiredResourceAccess -eq "CIPPDefaults") {
if ($RequiredResourceAccess -eq 'CIPPDefaults') {
$RequiredResourceAccess = (Get-Content '.\SAMManifest.json' | ConvertFrom-Json).requiredResourceAccess
}
$ServicePrincipalList = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/servicePrincipals?`$select=AppId,id,displayName&`$top=999" -skipTokenCache $true -tenantid $Tenantfilter
$ourSVCPrincipal = $ServicePrincipalList | Where-Object -Property AppId -EQ $ApplicationId
if(!$ourSVCPrincipal) {
if (!$ourSVCPrincipal) {
#Our Service Principal isn't available yet. We do a sleep and reexecute after 3 seconds.
Start-Sleep -Seconds 5
$ServicePrincipalList = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/servicePrincipals?`$select=AppId,id,displayName&`$top=999" -skipTokenCache $true -tenantid $Tenantfilter
$ourSVCPrincipal = $ServicePrincipalList | Where-Object -Property AppId -EQ $ApplicationId
}

$Results = [System.Collections.ArrayList]@()

$CurrentRoles = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/servicePrincipals/$($ourSVCPrincipal.id)/appRoleAssignments" -tenantid $Tenantfilter -skipTokenCache $true
$Grants = foreach ($App in $RequiredResourceAccess) {

$Grants = foreach ($App in $RequiredResourceAccess) {
$svcPrincipalId = $ServicePrincipalList | Where-Object -Property AppId -EQ $App.resourceAppId
if (!$svcPrincipalId) { continue }
foreach ($SingleResource in $App.ResourceAccess | Where-Object -Property Type -EQ "Role") {
if (!$svcPrincipalId) { continue }
foreach ($SingleResource in $App.ResourceAccess | Where-Object -Property Type -EQ 'Role') {
if ($SingleResource.id -In $CurrentRoles.appRoleId) { continue }
[pscustomobject]@{
principalId = $($ourSVCPrincipal.id)
resourceId = $($svcPrincipalId.id)
appRoleId = "$($SingleResource.Id)"
}
}
}
}
}
$counter = 0
foreach ($Grant in $Grants) {
try {
$SettingsRequest = New-GraphPOSTRequest -body ($Grant | ConvertTo-Json) -uri "https://graph.microsoft.com/beta/servicePrincipals/$($ourSVCPrincipal.id)/appRoleAssignedTo" -tenantid $Tenantfilter -type POST
$SettingsRequest = New-GraphPOSTRequest -body ($Grant | ConvertTo-Json) -uri "https://graph.microsoft.com/beta/servicePrincipals/$($ourSVCPrincipal.id)/appRoleAssignedTo" -tenantid $Tenantfilter -type POST
$counter ++
}
catch {
} catch {
$Results.add("Failed to grant $($Grant.appRoleId) to $($Grant.resourceId): $($_.Exception.Message)") | Out-Null
}
}
Expand Down
14 changes: 9 additions & 5 deletions Modules/CIPPCore/Public/Add-CIPPDelegatedPermission.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,27 @@ function Add-CIPPDelegatedPermission {
)
Write-Host 'Adding Delegated Permissions'
Set-Location (Get-Item $PSScriptRoot).FullName
Write-Host "RequiredResourceAccess: $($RequiredResourceAccess | ConvertTo-Json -Depth 10)"

if ($ApplicationId -eq $ENV:ApplicationID -and $Tenantfilter -eq $env:TenantID) {
return @('Cannot modify delgated permissions for CIPP-SAM on partner tenant')
}

if ($RequiredResourceAccess -eq 'CIPPDefaults') {
$RequiredResourceAccess = (Get-Content '.\SAMManifest.json' | ConvertFrom-Json).requiredResourceAccess
}
$Translator = Get-Content '.\PermissionsTranslator.json' | ConvertFrom-Json
$ServicePrincipalList = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/servicePrincipals?`$select=AppId,id,displayName&`$top=999" -tenantid $Tenantfilter -skipTokenCache $true
$ourSVCPrincipal = $ServicePrincipalList | Where-Object -Property AppId -EQ $ApplicationId
$Results = [System.Collections.ArrayList]@()

$CurrentDelegatedScopes = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/servicePrincipals/$($ourSVCPrincipal.id)/oauth2PermissionGrants" -skipTokenCache $true -tenantid $Tenantfilter

foreach ($App in $requiredResourceAccess) {
$svcPrincipalId = $ServicePrincipalList | Where-Object -Property AppId -EQ $App.resourceAppId
if (!$svcPrincipalId) { continue }
if (!$svcPrincipalId) { continue }
$NewScope = ($Translator | Where-Object { $_.id -in $App.ResourceAccess.id } | Where-Object { $_.value -notin 'profile', 'openid', 'offline_access' }).value -join ' '
$OldScope = ($CurrentDelegatedScopes | Where-Object -Property Resourceid -EQ $svcPrincipalId.id)

if (!$OldScope) {
$Createbody = @{
clientId = $ourSVCPrincipal.id
Expand Down
39 changes: 13 additions & 26 deletions Modules/CIPPCore/Public/Entrypoints/Invoke-EditGroup.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,12 @@ Function Invoke-EditGroup {
if ($userobj.groupType -eq 'Distribution list' -or $userobj.groupType -eq 'Mail-Enabled Security') {
$Params = @{ Identity = $userobj.groupid; Member = $member; BypassSecurityGroupManagerCheck = $true }
New-ExoRequest -tenantid $Userobj.tenantid -cmdlet 'Add-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true
}
else {
} else {
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)" -tenantid $Userobj.tenantid -type patch -body $addmemberbody -Verbose
}
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Added $member to $($userobj.groupName) group" -Sev 'Info'
$body = $results.add("Success. $member has been added")
}
catch {
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Failed to add member $member to $($userobj.groupName). Error:$($_.Exception.Message)" -Sev 'Error'
$body = $results.add("Failed to add member $member to $($userobj.groupName): $($_.Exception.Message)")
}
Expand All @@ -53,13 +51,11 @@ Function Invoke-EditGroup {
New-ExoRequest -tenantid $Userobj.tenantid -cmdlet 'Add-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true
Write-LogMessage -API $APINAME -tenant $Userobj.tenantid -user $request.headers.'x-ms-client-principal' -message "Added $member to $($userobj.groupName) group" -Sev 'Info'
$body = $results.add("Success. $member has been added")
}
else {
} else {
Write-LogMessage -API $APINAME -tenant $Userobj.tenantid -user $request.headers.'x-ms-client-principal' -message 'You cannot add a contact to a security group' -Sev 'Error'
$body = $results.add('You cannot add a contact to a security group')
}
}
catch {
} catch {
$body = $results.add("Failed to add member $member to $($userobj.groupName): $($_.Exception.Message)")
}
}
Expand All @@ -74,17 +70,15 @@ Function Invoke-EditGroup {
if ($userobj.groupType -eq 'Distribution list' -or $userobj.groupType -eq 'Mail-Enabled Security') {
$Params = @{ Identity = $userobj.groupid; Member = $member ; BypassSecurityGroupManagerCheck = $true }
New-ExoRequest -tenantid $Userobj.tenantid -cmdlet 'Remove-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true
}
else {
} else {
$MemberInfo = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($_)" -tenantid $Userobj.tenantid)
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)/members/$($MemberInfo.id)/`$ref" -tenantid $Userobj.tenantid -type DELETE
}
Write-LogMessage -API $APINAME -tenant $Userobj.tenantid -user $request.headers.'x-ms-client-principal' -message "Removed $member from $($userobj.groupName) group" -Sev 'Info'
$body = $results.add("Success. Member $member has been removed")
}
}
}
catch {
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Failed to remove $RemoveMembers from $($userobj.groupName). Error:$($_.Exception.Message)" -Sev 'Error'
$body = $results.add("Could not remove $RemoveMembers from $($userobj.groupName). $($_.Exception.Message)")
}
Expand All @@ -99,16 +93,14 @@ Function Invoke-EditGroup {
$AddOwner = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)/owners/`$ref" -tenantid $Userobj.tenantid -type POST -body ('{"@odata.id": "' + $ID + '"}')
Write-LogMessage -API $APINAME -tenant $Userobj.tenantid -user $request.headers.'x-ms-client-principal' -message "Added owner $_ to $($userobj.groupName) group" -Sev 'Info'
$body = $results.add("Success. $_ has been added")
}
catch {
} catch {
$body = $results.add("Failed to add owner $_ to $($userobj.groupName): Error:$($_.Exception.Message)")
}
}

}

}
catch {
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $Userobj.tenantid -API $APINAME -message "Add member API failed. $($_.Exception.Message)" -Sev 'Error'
}

Expand All @@ -121,14 +113,12 @@ Function Invoke-EditGroup {
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($userobj.groupid)/owners/$($MemberInfo.id)/`$ref" -tenantid $Userobj.tenantid -type DELETE
Write-LogMessage -API $APINAME -tenant $Userobj.tenantid -user $request.headers.'x-ms-client-principal' -message "Removed $($MemberInfo.UserPrincipalname) from $($userobj.displayname) group" -Sev 'Info'
$body = $results.add("Success. Member $_ has been removed from $($userobj.groupName)")
}
catch {
} catch {
$body = $results.add("Failed to remove $_ from $($userobj.groupName): $($_.Exception.Message)")
}
}
}
}
catch {
} catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Failed to remove $RemoveMembers from $($userobj.groupName). Error:$($_.Exception.Message)" -Sev 'Error'
$body = $results.add("Could not remove $RemoveMembers from $($userobj.groupName). $($_.Exception.Message)")
}
Expand All @@ -138,16 +128,14 @@ Function Invoke-EditGroup {
if ($userobj.groupType -eq 'Distribution list') {
$Params = @{ Identity = $userobj.groupid; RequireSenderAuthenticationEnabled = $false }
New-ExoRequest -tenantid $Userobj.tenantid -cmdlet 'Set-DistributionGroup' -cmdParams $params
}
else {
} else {
$Params = @{ Identity = $userobj.groupid; RequireSenderAuthenticationEnabled = $false }
New-ExoRequest -tenantid $Userobj.tenantid -cmdlet 'Set-UnifiedGroup' -cmdParams $params
}
$body = $results.add("Allowed external senders to send to $($userobj.groupName).")
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Allowed external senders to send to $($userobj.groupName)" -Sev 'Info'

}
catch {
} catch {
$body = $results.add("Failed to allow external senders to send to $($userobj.groupName).")
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Failed to allow external senders for $($userobj.groupName). Error:$($_.Exception.Message)" -Sev 'Error'
}
Expand All @@ -170,8 +158,7 @@ Function Invoke-EditGroup {

$body = $results.add("Send Copies of team emails and events to team members inboxes for $($userobj.mail) enabled.")
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Send Copies of team emails and events to team members inboxes for $($userobj.mail) enabled." -Sev 'Info'
}
catch {
} catch {
$body = $results.add("Failed to Send Copies of team emails and events to team members inboxes for $($userobj.mail).")
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Failed to Send Copies of team emails and events to team members inboxes for $($userobj.mail). Error:$($_.Exception.Message)" -Sev 'Error'
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ Function Invoke-ExecGDAPInvite {
if ($NewRelationshipRequest.action -eq 'lockForApproval') {
$InviteUrl = "https://admin.microsoft.com/AdminPortal/Home#/partners/invitation/granularAdminRelationships/$($NewRelationship.id)"
$Uri = ([System.Uri]$TriggerMetadata.Headers.referer)
$OnboardingUrl = $Uri.AbsoluteUri.Replace($Uri.PathAndQuery, '/tenant/administration/tenant-onboarding-wizard?tableFilter=Complex: id eq {0}' -f $NewRelationship.id)
$TableFilter = [System.Web.HttpUtility]::UrlEncode(('Complex: id eq {0}' -f $NewRelationship.id))
$OnboardingUrl = $Uri.AbsoluteUri.Replace($Uri.PathAndQuery, "/tenant/administration/tenant-onboarding-wizard?tableFilter=$TableFilter")

$InviteEntity = [PSCustomObject]@{
'PartitionKey' = 'invite'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Function Invoke-ListAlertsQueue {
DepTokenExpiry = [bool]$QueueFile.DepTokenExpiry
NoCAConfig = [bool]$QueueFile.NoCAConfig
SecDefaultsUpsell = [bool]$QueueFile.SecDefaultsUpsell
SharepointQuota = [bool]$QueueFile.SharePointQuota
SharePointQuota = [bool]$QueueFile.SharePointQuota
ExpiringLicenses = [bool]$QueueFile.ExpiringLicenses
tenantId = $QueueFile.tenantid
}
Expand Down
8 changes: 2 additions & 6 deletions Modules/CIPPCore/Public/Entrypoints/Invoke-ListSites.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,8 @@ Function Invoke-ListSites {
@{ Name = 'siteid'; Expression = { $_.'site Id' } }

#Temporary workaround for url as report is broken.
if ($Type -eq 'SharePointSiteUsage') {
$URLs = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/sites?search=*&`$select=sharepointIds" -asapp $true -tenantid $TenantFilter).sharepointIds
} else {
#Get all OneDrive Urls
#$URLs = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users?`$select=displayName,userPrincipalName" -tenantid $TenantFilter)
}
#This API is so stupid its great.
$URLs = (New-GraphGetRequest -uri 'https://graph.microsoft.com/v1.0/sites/getAllSites?$select=SharePointIds' -asapp $true -tenantid $TenantFilter).SharePointIds

$GraphRequest = foreach ($site in $GraphRequest) {
$site.URL = ($URLs | Where-Object { $_.siteId -eq $site.SiteId }).siteUrl
Expand Down
11 changes: 6 additions & 5 deletions Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAdmins.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,14 @@ function Push-CIPPAlertMFAAdmins {
} else {
Write-LogMessage -message 'Potentially using Duo for MFA, could not check MFA status for Admins with 100% accuracy' -API 'MFA Alerts - Informational' -tenant $QueueItem.tenant -sev Info
}
$LastRun = @{
RowKey = 'MFAAllAdmins'
PartitionKey = $QueueItem.tenantid
}
Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force
}
} catch {
Write-AlertMessage -tenant $($QueueItem.tenant) -message "Could not get MFA status for admins for $($QueueItem.tenant): $(Get-NormalizedError -message $_.Exception.message)"
}
$LastRun = @{
RowKey = 'MFAAllAdmins'
PartitionKey = $QueueItem.tenantid
}
Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force

}
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,10 @@ Function Push-ExecOnboardTenantQueue {
$OnboardingSteps.Step3.Message = 'Failed to map security groups, no pending invite available'
}

$x = 0
do {
$x++
$AccessAssignments = New-GraphGetRequest -Uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships/$Id/accessAssignments"
Start-Sleep -Seconds 15
} while ($AccessAssignments.status -contains 'pending' -and $x -le 12)
} while ($AccessAssignments.status -contains 'pending' -and (Get-Date) -lt $Start.AddMinutes(8))

if ($AccessAssignments.status -notcontains 'pending') {
$OnboardingSteps.Step3.Message = 'Group check: Access assignments are mapped and active'
Expand Down
9 changes: 9 additions & 0 deletions Modules/CIPPCore/Public/Invoke-CIPPWebhookProcessing.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,15 @@ function Invoke-CippWebhookProcessing {
Proxy = "$Proxy"
Hosting = "$hosting"
ASName = "$ASName"
Region = "$($location.region)"
RegionName = "$($location.regionName)"
org = "$($location.org)"
zip = "$($location.zip)"
mobile = "$($location.mobile)"
lat = "$($location.lat)"
lon = "$($location.lon)"
isp = "$($location.isp)"
Country = "$($location.country)"
}
$null = Add-CIPPAzDataTableEntity @LocationTable -Entity $LocationInfo -Force
}
Expand Down
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/New-CIPPAlertTemplate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function New-CIPPAlertTemplate {
$AfterButtonText = ''
$RuleTable = ''
$Table = ''

$LocationInfo = $LocationInfo | Select-Object *, -excludeproperty Etag, PartitionKey, RowKey, TimeStamp
switch ($Data.Operation) {
'New-InboxRule' {
$Title = "$($TenantFilter) - New Rule Detected for $($data.UserId)"
Expand Down
Loading

0 comments on commit cebc117

Please sign in to comment.