Skip to content

Commit a6fef0d

Browse files
committed
Merge branch 'dev' of https://github.com/Jr7468/CIPP-API into dev
2 parents 0a3f814 + bc90d78 commit a6fef0d

File tree

89 files changed

+1688
-988
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+1688
-988
lines changed

DomainAnalyser_All/run.ps1

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ $Result = [PSCustomObject]@{
4242
ExpectedSPFRecord = ''
4343
ActualSPFRecord = ''
4444
SPFPassAll = ''
45+
ActualMXRecords = ''
4546
MXPassTest = ''
4647
DMARCPresent = ''
4748
DMARCFullPolicy = ''
@@ -79,6 +80,7 @@ $MXRecord = Read-MXRecord -Domain $Domain -ErrorAction Stop
7980

8081
$Result.ExpectedSPFRecord = $MXRecord.ExpectedInclude
8182
$Result.MXPassTest = $false
83+
$Result.ActualMXRecords = $MXRecord.Records
8284

8385
# Check fail counts to ensure all tests pass
8486
#$MXWarnCount = $MXRecord.ValidationWarns | Measure-Object | Select-Object -ExpandProperty Count

Durable_BECRun/run.ps1

Lines changed: 37 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,46 +2,45 @@ param($Context)
22
#$Context does not allow itself to be cast to a pscustomobject for some reason, so we convert
33
$context = $Context | ConvertTo-Json | ConvertFrom-Json
44
$APIName = $TriggerMetadata.FunctionName
5-
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Accessed this API" -Sev "Debug"
5+
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug'
66
$TenantFilter = $Context.input.tenantfilter
77
$SuspectUser = $Context.input.userid
88
$UserName = $Context.input.username
99
Write-Host "Working on $UserName"
1010
try {
1111
$startDate = (Get-Date).AddDays(-7)
1212
$endDate = (Get-Date)
13-
$auditLog = (New-ExoRequest -tenantid $Tenantfilter -cmdlet "Get-AdminAuditLogConfig").UnifiedAuditLogIngestionEnabled
13+
$auditLog = (New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Get-AdminAuditLogConfig').UnifiedAuditLogIngestionEnabled
1414
$7dayslog = if ($auditLog -eq $false) {
15-
$ExtractResult = "AuditLog is disabled. Cannot perform full analysis"
16-
}
17-
else {
15+
$ExtractResult = 'AuditLog is disabled. Cannot perform full analysis'
16+
} else {
1817
$sessionid = Get-Random -Minimum 10000 -Maximum 99999
1918
$operations = @(
20-
"New-InboxRule",
21-
"Set-InboxRule",
22-
"UpdateInboxRules",
23-
"Remove-MailboxPermission",
24-
"Add-MailboxPermission",
25-
"UpdateCalendarDelegation",
26-
"AddFolderPermissions",
27-
"MailboxLogin",
28-
"UserLoggedIn"
19+
'New-InboxRule',
20+
'Set-InboxRule',
21+
'UpdateInboxRules',
22+
'Remove-MailboxPermission',
23+
'Add-MailboxPermission',
24+
'UpdateCalendarDelegation',
25+
'AddFolderPermissions',
26+
'MailboxLogin',
27+
'UserLoggedIn'
2928
)
3029
$startDate = (Get-Date).AddDays(-7)
3130
$endDate = (Get-Date)
3231
$SearchParam = @{
33-
SessionCommand = "ReturnLargeSet"
32+
SessionCommand = 'ReturnLargeSet'
3433
Operations = $operations
3534
sessionid = $sessionid
3635
startDate = $startDate
3736
endDate = $endDate
3837
}
3938
do {
40-
New-ExoRequest -tenantid $Tenantfilter -cmdlet "Search-unifiedAuditLog" -cmdParams $SearchParam -Anchor $Username
39+
New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Search-unifiedAuditLog' -cmdParams $SearchParam -Anchor $Username
4140
Write-Host "Retrieved $($logsTenant.count) logs" -ForegroundColor Yellow
4241
$logsTenant
4342
} while ($LogsTenant.count % 5000 -eq 0 -and $LogsTenant.count -ne 0)
44-
$ExtractResult = "Succesfully extracted logs from auditlog"
43+
$ExtractResult = 'Succesfully extracted logs from auditlog'
4544
}
4645
Try {
4746
$URI = "https://graph.microsoft.com/beta/auditLogs/signIns?`$filter=(userId eq '$SuspectUser')&`$top=1&`$orderby=createdDateTime desc"
@@ -50,29 +49,26 @@ try {
5049
@{ Name = 'AppDisplayName'; Expression = { $_.resourceDisplayName } },
5150
@{ Name = 'Status'; Expression = { if (($_.conditionalAccessStatus -eq 'Success' -or 'Not Applied') -and $_.status.errorCode -eq 0) { 'Success' } else { 'Failed' } } },
5251
@{ Name = 'IPAddress'; Expression = { $_.ipAddress } }
53-
}
54-
catch {
52+
} catch {
5553
$LastSignIn = [PSCustomObject]@{
56-
AppDisplayName = "Unknown - could not retrieve information. No access to sign-in logs"
57-
CreatedDateTime = "Unknown"
58-
Id = "0"
59-
Status = "Could not retrieve additional details"
54+
AppDisplayName = 'Unknown - could not retrieve information. No access to sign-in logs'
55+
CreatedDateTime = 'Unknown'
56+
Id = '0'
57+
Status = 'Could not retrieve additional details'
6058
}
6159
}
6260
#List all users devices
6361
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($SuspectUser)
6462
$base64IdentityParam = [Convert]::ToBase64String($Bytes)
6563
Try {
6664
$Devices = New-GraphGetRequest -uri "https://outlook.office365.com:443/adminapi/beta/$($TenantFilter)/mailbox('$($base64IdentityParam)')/MobileDevice/Exchange.GetMobileDeviceStatistics()/?IsEncoded=True" -Tenantid $tenantfilter -scope ExchangeOnline
67-
}
68-
catch {
65+
} catch {
6966
$Devices = $null
7067
}
71-
$PermissionsLog = ($7dayslog | Where-Object -Property Operations -In "Remove-MailboxPermission", "Add-MailboxPermission", "UpdateCalendarDelegation", "AddFolderPermissions" ).AuditData | ConvertFrom-Json -Depth 100 | ForEach-Object {
68+
$PermissionsLog = ($7dayslog | Where-Object -Property Operations -In 'Remove-MailboxPermission', 'Add-MailboxPermission', 'UpdateCalendarDelegation', 'AddFolderPermissions' ).AuditData | ConvertFrom-Json -Depth 100 | ForEach-Object {
7269
$perms = if ($_.Parameters) {
73-
$_.Parameters | ForEach-Object { if ($_.Name -eq "AccessRights") { $_.Value } }
74-
}
75-
else
70+
$_.Parameters | ForEach-Object { if ($_.Name -eq 'AccessRights') { $_.Value } }
71+
} else
7672
{ $_.item.ParentFolder.MemberRights }
7773
$objectID = if ($_.ObjectID) { $_.ObjectID } else { $($_.MailboxOwnerUPN) + $_.item.ParentFolder.Path }
7874
[pscustomobject]@{
@@ -83,43 +79,42 @@ try {
8379
}
8480
}
8581

86-
$RulesLog = @(($7dayslog | Where-Object -Property Operations -In "New-InboxRule", "Set-InboxRule", "UpdateInboxRules").AuditData | ConvertFrom-Json) | ForEach-Object {
82+
$RulesLog = @(($7dayslog | Where-Object -Property Operations -In 'New-InboxRule', 'Set-InboxRule', 'UpdateInboxRules').AuditData | ConvertFrom-Json) | ForEach-Object {
8783
Write-Host ($_ | ConvertTo-Json)
8884
[pscustomobject]@{
8985
ClientIP = $_.ClientIP
9086
CreationTime = $_.CreationTime
9187
UserId = $_.UserId
92-
RuleName = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq "RuleName") { $_.Value } })
93-
RuleCondition = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq "RuleCondition") { $_.Value } })
88+
RuleName = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq 'RuleName') { $_.Value } })
89+
RuleCondition = ($_.OperationProperties | ForEach-Object { if ($_.Name -eq 'RuleCondition') { $_.Value } })
9490
}
9591
}
9692
$PasswordChanges = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users?`select=lastPasswordChangeDateTime,displayname,UserPrincipalName" -Tenantid $tenantfilter | Where-Object { $_.lastPasswordChangeDateTime -gt $startDate }
97-
$NewUsers = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users?`$select=displayname,UserPrincipalName,CreatedDateTime" -Tenantid $tenantfilter | Where-Object { $_.CreatedDateTime -gt $startDate }
93+
$NewUsers = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users?`$select=displayname,UserPrincipalName,CreatedDateTime" -Tenantid $tenantfilter | Where-Object { $_.CreatedDateTime -gt $startDate }
9894
$MFADevices = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($SuspectUser)/authentication/methods" -Tenantid $tenantfilter
9995
$NewSPs = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$select=displayName,createdDateTime,id,AppDisplayName&`$filter=createdDateTime ge $($startDate.ToString('yyyy-MM-ddTHH:mm:ssZ'))" -Tenantid $tenantfilter
100-
$Last50Logons = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/auditLogs/signIns?`$top=50&`$orderby=createdDateTime desc" -tenantid $TenantFilter -noPagination $true -verbose | Select-Object @{ Name = 'CreatedDateTime'; Expression = { $(($_.createdDateTime | Out-String) -replace '\r\n') } },
96+
$Last50Logons = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/auditLogs/signIns?`$top=50&`$orderby=createdDateTime desc" -tenantid $TenantFilter -noPagination $true -verbose | Select-Object @{ Name = 'CreatedDateTime'; Expression = { $(($_.createdDateTime | Out-String) -replace '\r\n') } },
10197
id,
10298
@{ Name = 'AppDisplayName'; Expression = { $_.resourceDisplayName } },
10399
@{ Name = 'Status'; Expression = { if (($_.conditionalAccessStatus -eq 'Success' -or 'Not Applied') -and $_.status.errorCode -eq 0) { 'Success' } else { 'Failed' } } },
104100
@{ Name = 'IPAddress'; Expression = { $_.ipAddress } }, UserPrincipalName
105101
$Results = [PSCustomObject]@{
106-
AddedApps = $NewSPs
107-
SuspectUserMailboxLogons = $Last50Logons
102+
AddedApps = @($NewSPs)
103+
SuspectUserMailboxLogons = @($Last50Logons)
108104
LastSuspectUserLogon = @($LastSignIn)
109105
SuspectUserDevices = @($Devices)
110106
NewRules = @($RulesLog)
111107
MailboxPermissionChanges = @($PermissionsLog)
112108
NewUsers = @($NewUsers)
113-
MFADevices = $MFADevices
114-
ChangedPasswords = $PasswordChanges
109+
MFADevices = @($MFADevices)
110+
ChangedPasswords = @($PasswordChanges)
115111
ExtractedAt = (Get-Date).ToString('s')
116112
ExtractResult = $ExtractResult
117113
}
118114

119-
}
120-
catch {
115+
} catch {
121116
$errMessage = Get-NormalizedError -message $_.Exception.Message
122-
$results = [pscustomobject]@{"Results" = "$errMessage" }
117+
$results = [pscustomobject]@{'Results' = "$errMessage" }
123118
}
124119

125120
$Table = Get-CippTable -tablename 'cachebec'
@@ -128,5 +123,5 @@ Add-CIPPAzDataTableEntity @Table -Entity @{
128123
UserId = $Context.input.userid
129124
Results = "$($results | ConvertTo-Json -Depth 10)"
130125
RowKey = $Context.input.userid
131-
PartitionKey = "bec"
126+
PartitionKey = 'bec'
132127
}

Modules/CIPPCore/Public/Entrypoints/Invoke-AddPolicy.ps1

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ Function Invoke-AddPolicy {
4242
if ($PolicyName -in $CheckExististing.displayName) {
4343
Throw "Policy with Display Name $($Displayname) Already exists"
4444
}
45-
45+
$PolicyFile = $RawJSON | ConvertFrom-Json
46+
$Null = $PolicyFile | Add-Member -MemberType NoteProperty -Name 'description' -Value $description -Force
47+
$null = $PolicyFile | Add-Member -MemberType NoteProperty -Name 'displayName' -Value $displayname -Force
48+
$RawJSON = ConvertTo-Json -InputObject $PolicyFile -Depth 20
4649
$CreateRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$TemplateTypeURL" -tenantid $tenant -type POST -body $RawJSON
4750
}
4851
'Catalog' {
@@ -62,8 +65,7 @@ Function Invoke-AddPolicy {
6265
Set-CIPPAssignedPolicy -GroupName $AssignTo -PolicyId $CreateRequest.id -Type $TemplateTypeURL -TenantFilter $tenant
6366
}
6467
"Successfully added policy for $($Tenant)"
65-
}
66-
catch {
68+
} catch {
6769
"Failed to add policy for $($Tenant): $($_.Exception.Message)"
6870
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Failed adding policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error'
6971
continue

Modules/CIPPCore/Public/Entrypoints/Invoke-AddUser.ps1

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Function Invoke-AddUser {
88
[CmdletBinding()]
99
param($Request, $TriggerMetadata)
1010

11-
$APIName = "AddUser"
11+
$APIName = 'AddUser'
1212
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug'
1313

1414
$Results = [System.Collections.ArrayList]@()
@@ -56,8 +56,7 @@ Function Invoke-AddUser {
5656
$results.add('Created user.')
5757
$results.add("Username: $($UserprincipalName)")
5858
$results.add("Password: $password")
59-
}
60-
catch {
59+
} catch {
6160
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantid) -message "Failed to create user. Error:$($_.Exception.Message)" -Sev 'Error'
6261
$body = $results.add("Failed to create user. $($_.Exception.Message)" )
6362
}
@@ -70,8 +69,7 @@ Function Invoke-AddUser {
7069
$LicenseBody = if ($licenses.count -ge 2) {
7170
$liclist = foreach ($license in $Licenses) { '{"disabledPlans": [],"skuId": "' + $license + '" },' }
7271
'{"addLicenses": [' + $LicList + '], "removeLicenses": [ ] }'
73-
}
74-
else {
72+
} else {
7573
'{"addLicenses": [ {"disabledPlans": [],"skuId": "' + $licenses + '" }],"removeLicenses": [ ]}'
7674
}
7775
Write-Host $LicenseBody
@@ -97,8 +95,7 @@ Function Invoke-AddUser {
9795
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantid) -message "Added alias $($Alias) to $($userobj.displayname)" -Sev 'Info'
9896
$body = $results.add("Added Aliases: $($Aliases -join ',')")
9997
}
100-
}
101-
catch {
98+
} catch {
10299
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($userobj.tenantid) -message "Failed to create the Aliases. Error:$($_.Exception.Message)" -Sev 'Error'
103100
$body = $results.add("Failed to create the Aliases: $($_.Exception.Message)")
104101
}
@@ -107,7 +104,15 @@ Function Invoke-AddUser {
107104
$results.Add($CopyFrom.Success -join ', ')
108105
$results.Add($CopyFrom.Error -join ', ')
109106
}
110-
107+
108+
if ($Request.body.setManager) {
109+
$ManagerBody = [PSCustomObject]@{'@odata.id' = "https://graph.microsoft.com/beta/users/$($Request.body.setManager.value)" }
110+
$ManagerBodyJSON = ConvertTo-Json -Compress -Depth 10 -InputObject $ManagerBody
111+
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($GraphRequest.id)/manager/`$ref" -tenantid $Userobj.tenantid -type PUT -body $ManagerBodyJSON -Verbose
112+
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)" -Sev 'Info'
113+
$results.add("Success. Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)")
114+
}
115+
111116
$copyFromResults = @{
112117
'Success' = $CopyFrom.Success
113118
'Error' = $CopyFrom.Error
@@ -119,6 +124,8 @@ Function Invoke-AddUser {
119124
'Password' = $password
120125
'CopyFrom' = $copyFromResults
121126
}
127+
128+
122129
# Associate values to output bindings by calling 'Push-OutputBinding'.
123130
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
124131
StatusCode = [HttpStatusCode]::OK

Modules/CIPPCore/Public/Entrypoints/Invoke-EditUser.ps1

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ Function Invoke-EditUser {
1212
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug'
1313

1414
$userobj = $Request.body
15+
if ($userobj.Userid -eq '') {
16+
$body = @{'Results' = @('Failed to edit user. No user ID provided') }
17+
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
18+
StatusCode = [HttpStatusCode]::BadRequest
19+
Body = $Body
20+
})
21+
return
22+
}
1523
$Results = [System.Collections.ArrayList]@()
1624
$licenses = ($userobj | Select-Object 'License_*').psobject.properties.value
1725
$Aliases = if ($userobj.AddedAliases) { ($userobj.AddedAliases).Split([Environment]::NewLine) }
@@ -153,7 +161,14 @@ Function Invoke-EditUser {
153161

154162
}
155163
}
156-
164+
if ($Request.body.setManager) {
165+
$ManagerBody = [PSCustomObject]@{'@odata.id' = "https://graph.microsoft.com/beta/users/$($Request.body.setManager.value)" }
166+
$ManagerBodyJSON = ConvertTo-Json -Compress -Depth 10 -InputObject $ManagerBody
167+
New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userobj.Userid)/manager/`$ref" -tenantid $Userobj.tenantid -type PUT -body $ManagerBodyJSON -Verbose
168+
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Userobj.tenantid -message "Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)" -Sev 'Info'
169+
$results.add("Success. Set $($UserObj.DisplayName)'s manager to $($Request.body.setManager.label)")
170+
}
171+
157172
if ($RemoveFromGroups) {
158173
$RemoveFromGroups | ForEach-Object {
159174

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using namespace System.Net
2+
3+
Function Invoke-ExecDeviceDelete {
4+
<#
5+
.FUNCTIONALITY
6+
Entrypoint
7+
#>
8+
[CmdletBinding()]
9+
param($Request, $TriggerMetadata)
10+
11+
$APIName = $TriggerMetadata.FunctionName
12+
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug'
13+
14+
# Interact with query parameters or the body of the request.
15+
16+
17+
try {
18+
$url = "https://graph.microsoft.com/beta/devices/$($request.query.id)"
19+
if ($Request.query.action -eq 'delete') {
20+
$ActionResult = New-GraphPOSTRequest -uri $url -type DELETE -tenantid $Request.Query.TenantFilter
21+
} else {
22+
$ActionResult = New-GraphPOSTRequest -uri $url -type PATCH -tenantid $Request.Query.TenantFilter -body '{"accountEnabled": false }'
23+
}
24+
$body = [pscustomobject]@{'Results' = "Executed action $($Request.query.action) on $($Request.query.id)" }
25+
} catch {
26+
$body = [pscustomobject]@{'Results' = "Failed to queue action $($Request.query.action) on $($request.query.id): $($_.Exception.Message)" }
27+
}
28+
29+
# Associate values to output bindings by calling 'Push-OutputBinding'.
30+
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
31+
StatusCode = [HttpStatusCode]::OK
32+
Body = $body
33+
})
34+
35+
}

Modules/CIPPCore/Public/Entrypoints/Invoke-ExecGraphExplorerPreset.ps1

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,27 @@ Function Invoke-ExecGraphExplorerPreset {
2121
$Id = (New-Guid).Guid
2222
}
2323
'Save' {
24-
$Id = $Request.Body.values.reportTemplate.value
24+
$Id = $Request.Body.preset.reportTemplate.value
2525
}
2626
'Delete' {
27-
$Id = $Request.Body.values.reportTemplate.value
27+
$Id = $Request.Body.preset.reportTemplate.value
28+
}
29+
default {
30+
$Request.Body.Action = 'Copy'
31+
$Id = (New-Guid).Guid
2832
}
2933
}
3034

31-
$params = $Request.Body.values | Select-Object endpoint, '$filter', '$select', '$count', '$expand', '$search', NoPagination, '$top', IsShared
35+
$params = $Request.Body.preset | Select-Object endpoint, '$filter', '$select', '$count', '$expand', '$search', NoPagination, '$top', IsShared
36+
if ($params.'$select') { $params.'$select' = ($params.'$select').value -join ',' }
37+
3238
$Preset = [PSCustomObject]@{
3339
PartitionKey = 'Preset'
3440
RowKey = [string]$Id
3541
id = [string]$Id
36-
name = [string]$Request.Body.values.name
42+
name = [string]$Request.Body.preset.name
3743
Owner = [string]$Username
38-
IsShared = $Request.Body.values.IsShared
44+
IsShared = $Request.Body.preset.IsShared
3945
params = [string](ConvertTo-Json -InputObject $params -Compress)
4046
}
4147

0 commit comments

Comments
 (0)