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
Parad0xMS authored Jan 16, 2024
2 parents e77ebc7 + 36be990 commit bfc692e
Show file tree
Hide file tree
Showing 35 changed files with 533 additions and 233 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
24 changes: 14 additions & 10 deletions Modules/CIPPCore/Public/Add-CIPPDelegatedPermission.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,42 @@ function Add-CIPPDelegatedPermission {
$ApplicationId,
$Tenantfilter
)
Write-Host 'Adding Delegated Permissions'
Set-Location (Get-Item $PSScriptRoot).FullName

if ($RequiredResourceAccess -eq "CIPPDefaults") {
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
consentType = "AllPrincipals"
consentType = 'AllPrincipals'
resourceId = $svcPrincipalId.id
scope = $NewScope
} | ConvertTo-Json -Compress
$CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/oauth2PermissionGrants" -tenantid $Tenantfilter -body $Createbody -type POST
$CreateRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/v1.0/oauth2PermissionGrants' -tenantid $Tenantfilter -body $Createbody -type POST
$Results.add("Successfully added permissions for $($svcPrincipalId.displayName)") | Out-Null
}
else {
} else {
$compare = Compare-Object -ReferenceObject $OldScope.scope.Split(' ') -DifferenceObject $NewScope.Split(' ')
if (!$compare) {
$Results.add("All delegated permissions exist for $($svcPrincipalId.displayName)") | Out-Null
$Results.add("All delegated permissions exist for $($svcPrincipalId.displayName)") | Out-Null
continue
}
$Patchbody = @{
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
15 changes: 12 additions & 3 deletions Modules/CIPPCore/Public/Entrypoints/Invoke-ListSites.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,25 @@ Function Invoke-ListSites {
} else {
$ParsedRequest = $Result
}


$GraphRequest = $ParsedRequest | Select-Object @{ Name = 'UPN'; Expression = { $_.'Owner Principal Name' } },
@{ Name = 'displayName'; Expression = { $_.'Owner Display Name' } },
@{ Name = 'LastActive'; Expression = { $_.'Last Activity Date' } },
@{ Name = 'FileCount'; Expression = { [int]$_.'File Count' } },
@{ Name = 'UsedGB'; Expression = { [math]::round($_.'Storage Used (Byte)' / 1GB, 2) } },
@{ Name = 'URL'; Expression = { $_.'Site URL' } },
@{ Name = 'Allocated'; Expression = { [math]::round($_.'Storage Allocated (Byte)' / 1GB, 2) } },
@{ Name = 'Template'; Expression = { $_.'Root Web Template' } }
@{ Name = 'Template'; Expression = { $_.'Root Web Template' } },
@{ Name = 'siteid'; Expression = { $_.'site Id' } }

#Temporary workaround for url as report is broken.
#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
$site
}

$StatusCode = [HttpStatusCode]::OK
} catch {
$ErrorMessage = Get-NormalizedError -Message $_.Exception.Message
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ function Push-CIPPAlertApnCertExpiry {
$QueueItem,
$TriggerMetadata
)
$LastRunTable = $QueueItem.LastRunTable
$LastRunTable = Get-CIPPTable -Table AlertLastRun

try {
$Filter = "RowKey eq 'ApnCertExpiry' and PartitionKey eq '{0}'" -f $QueueItem.tenantid
$LastRun = Get-CIPPAzDataTableEntity @LastRunTable -Filter $Filter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@ function Push-CIPPAlertAppSecretExpiry {
$QueueItem,
$TriggerMetadata
)
$LastRunTable = $QueueItem.LastRunTable

$LastRunTable = Get-CIPPTable -Table AlertLastRun

Write-Host "Checking app expire for $($QueueItem.tenant)"
try {
$Filter = "RowKey eq 'AppSecretExpiry' and PartitionKey eq '{0}'" -f $QueueItem.tenantid
$LastRun = Get-CIPPAzDataTableEntity @LastRunTable -Filter $Filter
$Yesterday = (Get-Date).AddDays(-1)
if (-not $LastRun.Timestamp.DateTime -or ($LastRun.Timestamp.DateTime -le $Yesterday)) {
New-GraphGetRequest -uri "https://graph.microsoft.com/beta/applications?`$select=appId,displayName,passwordCredentials" -tenantid $QueueItem.tenant | ForEach-Object {
foreach ($App in $_) {
Write-Host "checking $($App.displayName)"
if ($App.passwordCredentials) {
foreach ($Credential in $App.passwordCredentials) {
if ($Credential.endDateTime -lt (Get-Date).AddDays(30) -and $Credential.endDateTime -gt (Get-Date).AddDays(-7)) {
Write-Host ("Application '{0}' has secrets expiring on {1}" -f $App.displayName, $Credential.endDateTime)
Write-AlertMessage -tenant $($QueueItem.tenant) -message ("Application '{0}' has secrets expiring on {1}" -f $App.displayName, $Credential.endDateTime)
}
}
Expand All @@ -31,7 +33,7 @@ function Push-CIPPAlertAppSecretExpiry {
Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force
}
} catch {
# Error handling
throw $_
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ function Push-CIPPAlertDepTokenExpiry {
$QueueItem,
$TriggerMetadata
)
$LastRunTable = $QueueItem.LastRunTable

$LastRunTable = Get-CIPPTable -Table AlertLastRun

try {
$Filter = "RowKey eq 'DepTokenExpiry' and PartitionKey eq '{0}'" -f $QueueItem.tenantid
Expand Down
Loading

0 comments on commit bfc692e

Please sign in to comment.