Framework/Core/SubscriptionSecurity/RBAC.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
using namespace Microsoft.Azure.Commands.Resources.Models.Authorization
using namespace System.Management.Automation
Set-StrictMode -Version Latest 

# Class to implement Subscription RBAC controls
class RBAC: CommandBase
{    
    hidden [SubscriptionRBAC] $Policy = $null;

    hidden [PSRoleAssignment[]] $RoleAssignments = $null;
    hidden [ActiveRBACAccount[]] $ApplicableActiveAccounts = $null;

    hidden [ActiveRBACAccount[]] $MissingActiveAccounts = $null;

    hidden [RBACAccountRoleMapping[]] $MatchedActiveAccounts = $null;
    hidden [RBACAccountRoleMapping[]] $MatchedDeprecatedAccounts = $null;

    RBAC([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags): 
        Base($subscriptionId, $invocationContext)
    { 
        $this.Policy = [SubscriptionRBAC] $this.LoadServerConfigFile("Subscription.RBAC.json"); 
        $this.FilterTags = $this.ConvertToStringArray($tags);
    }

    hidden [PSRoleAssignment[]] GetRoleAssignments()
    {
        if(-not $this.RoleAssignments)
        {
            $this.RoleAssignments = [RoleAssignmentHelper]::GetAzSKRoleAssignment($true, $true);
            #filter deleted user/group/spn assignments
            $deletedUserAssignments = $this.RoleAssignments | Where-Object{ [string]::IsNullOrWhiteSpace($_.DisplayName) -and [string]::IsNullOrWhiteSpace($_.SignInName) -and $_.ObjectType -eq 'Unknown'}
            if(($deletedUserAssignments | Measure-Object).Count -gt 0)
            {
                $this.RoleAssignments = $this.RoleAssignments | Where-Object{ $deletedUserAssignments.RoleAssignmentId -inotcontains $_.RoleAssignmentId }
            }
        }
        return $this.RoleAssignments;
    }
    
    hidden [ActiveRBACAccount[]] GetApplicableActiveAccounts()
    {
        if($null -eq $this.ApplicableActiveAccounts)
        {
            $this.ApplicableActiveAccounts = @();

            $subscriptionId = $this.SubscriptionContext.SubscriptionId;
            if(($this.FilterTags | Measure-Object).Count -ne 0)
            {
                $this.Policy.ValidActiveAccounts | 
                    ForEach-Object {
                        $currentItem = $_;
                        if(($currentItem.Tags | Where-Object { $this.FilterTags -Contains $_ } | Measure-Object).Count -ne 0)
                        {
                            # Resolve the value of SubscriptionId
                            $currentItem.Scope = $global:ExecutionContext.InvokeCommand.ExpandString($currentItem.Scope);
                            if([string]::IsNullOrWhiteSpace($currentItem.Scope))
                            {
                                $currentItem.Scope = "/subscriptions/$subscriptionId"
                            }

                            $this.ApplicableActiveAccounts  += $currentItem;
                        }
                    }
            }
        }
            
        return $this.ApplicableActiveAccounts;
    }
    
    hidden [void] LoadActiveAccountStatus()
    {
        $this.MissingActiveAccounts = @();
        $this.MatchedActiveAccounts = @();

        $this.GetApplicableActiveAccounts() | Where-Object { $_.Enabled } | 
            ForEach-Object { 
                $currentItem = $_;
                $matchedAccount = $this.GetRoleAssignments() | 
                                    Where-Object { 
                                        ($_.ObjectId -eq $currentItem.ObjectId) -and 
                                        ($_.Scope -eq $currentItem.Scope) -and 
                                        ($_.RoleDefinitionName -eq $currentItem.RoleDefinitionName) 
                                    } | Select-Object -First 1
                if($matchedAccount)
                {
                    $this.MatchedActiveAccounts += [RBACAccountRoleMapping]@{
                            RoleAssignment = $matchedAccount;
                            RBACAccount = $currentItem;
                        };
                }
                else
                {
                    $this.MissingActiveAccounts += $currentItem;
                }                        
            };
    }

    hidden [void] LoadDeprecatedAccountStatus()
    {
        $this.MatchedDeprecatedAccounts =  @();
        
        $this.Policy.DeprecatedAccounts | Where-Object { $_.Enabled } | 
            ForEach-Object { 
                $currentItem = $_;
                $matchedAccounts = $this.GetRoleAssignments() | 
                                    Where-Object {  ($_.ObjectId -eq $currentItem.ObjectId) };

                if(($matchedAccounts | Measure-Object).Count -ne 0)
                {
                    $matchedAccounts | ForEach-Object {
                        $this.MatchedDeprecatedAccounts += [RBACAccountRoleMapping]@{
                                RoleAssignment = $_;
                                RBACAccount = $currentItem;
                            };
                    };
                }
            };
    }
    
    [MessageData[]] SetRBACAccounts()
    {    
        [MessageData[]] $messages = @();
        [MessageData[]] $resultMessages = @();
        [CCAutomation] $caAutomation = [CCAutomation]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext);
        $caAutomation.RecoverCASPN();
        if($this.Force -or -not ($this.IsLatestVersionConfiguredOnSub($this.Policy.ActiveCentralAccountsVersion,[Constants]::CentralRBACVersionTagName,"CentralRBAC")))
        {
            #setting the tag at AzSKRG
            $azskRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
            [Helpers]::SetResourceGroupTags($azskRGName,@{"CentralRBACVersion"=$this.Policy.ActiveCentralAccountsVersion},$false)

            #set the tag on subscription based on server tag
            # Set Active accounts
            $nonConfiguredActiveAccounts = $this.GetNonConfiguredActiveAccounts(([ref]$messages));
            if($nonConfiguredActiveAccounts.Count -ne 0)
            {
                $provisionAccounts = @();
                $provisionAccounts += $nonConfiguredActiveAccounts | Where-Object { $_.Type -eq [RBACAccountType]::Provision };

                if($provisionAccounts.Count -ne 0)
                {
                    # Adding Central Accounts
                    $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nAdding following active accounts to the subscription. Total accounts: $($provisionAccounts.Count)", $provisionAccounts);                                            
                    $errorCount = 0;
                    $currentCount = 0;
                    $provisionAccounts | ForEach-Object {
                        $accountName = $_.Name;
                        $currentCount += 1;
                        # Add account
                        try
                        {
                            $this.PublishCustomMessage("Adding account [$accountName] to the subscription...");
                            New-AzRoleAssignment -ObjectId $_.ObjectId -Scope $_.Scope -RoleDefinitionName $_.RoleDefinitionName -ErrorAction Stop | Out-Null                                         
                        }
                        catch
                        {
                            $messages += [MessageData]::new("Error while adding account [$accountName] to the subscription", $_, [MessageType]::Error);
                            $errorCount += 1;
                        }

                        $this.CommandProgress($provisionAccounts.Count, $currentCount, 5);
                    };

                
                    if($errorCount -eq 0)
                    {
                        $resultMessages += [MessageData]::new("All required active accounts have been added to the subscription successfully.`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                    }
                    elseif($errorCount -eq $provisionAccounts.Count)
                    {
                        $resultMessages += [MessageData]::new("No accounts have been added due an error. Please add the accounts manually. You can find the specific account details in the log file.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error);
                    }
                    else
                    {
                        $resultMessages += [MessageData]::new("$errorCount/$($provisionAccounts.Count) required active account(s) have not been added to the subscription. Please add the accounts manually. You can find the specific account details in the log file.", [MessageType]::Error);
                        $resultMessages += [MessageData]::new("$($provisionAccounts.Count - $errorCount)/$($provisionAccounts.Count) required active account(s) have been added to the subscription successfully.`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                    }
                
                    $messages += $resultMessages;
                    $this.PublishCustomMessage($resultMessages);
                }

                $nonProvisionAccounts = @();
                $nonProvisionAccounts += $nonConfiguredActiveAccounts | Where-Object { $_.Type -ne [RBACAccountType]::Provision };

                if($nonProvisionAccounts.Count -ne 0)
                {
                    $messageText = "Some accounts are not added to the subscription, since the account type is not set to 'Provision' in RBAC policy file. Total accounts: $($nonProvisionAccounts.Count)";
                    $messages += [MessageData]::new($messageText, $nonProvisionAccounts);
                    $this.PublishCustomMessage($messageText);
                }
            }
        }
        
        return $messages;
    }

    [ActiveRBACAccount[]] GetNonConfiguredActiveAccounts([ref]$messages)
    {
        if($this.Policy.ValidActiveAccounts.Count -ne 0)
        {
            if($this.GetApplicableActiveAccounts().Count -ne 0)
            {
                $startMessage = [MessageData]::new("Processing RBAC rules for adding central accounts. Tags: [$([string]::Join(",", $this.FilterTags))]. Total accounts: $($this.GetApplicableActiveAccounts().Count)");
                $messages.Value += $startMessage;
                $this.PublishCustomMessage($startMessage);
                
                $disabledAccounts = $this.GetApplicableActiveAccounts() | Where-Object { -not $_.Enabled };
                if(($disabledAccounts | Measure-Object).Count -ne 0)
                {
                    $disabledMessage = "Found accounts which are disabled. Total disabled accounts: $($disabledAccounts.Count)";
                    $messages.Value += [MessageData]::new($disabledMessage, $disabledAccounts);
                    $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
                }

                # Load all properties
                $this.LoadActiveAccountStatus();

                if($this.MatchedActiveAccounts.Count -ne 0)
                {
                    $messages.Value += [MessageData]::new("Following accounts have correct RBAC configured. Total accounts: $($this.MatchedActiveAccounts.Count)", ($this.MatchedActiveAccounts | Select-Object -Property RoleAssignment));
                }
                
                if($this.MissingActiveAccounts.Count -ne 0)
                {
                    $missingAccountsMessage = "Following accounts do not have correct RBAC configured. Total accounts: $($this.MissingActiveAccounts.Count)";

                    $messages.Value += [MessageData]::new($missingAccountsMessage, $this.MissingActiveAccounts);
                    $this.PublishCustomMessage($missingAccountsMessage);
                }
                else
                {
                    $successMessage = [MessageData]::new("All required accounts are correctly configured");
                    $messages.Value += $successMessage;
                    $this.PublishCustomMessage($successMessage);
                }
                return $this.MissingActiveAccounts;                    
            }
            else
            {
                if($this.FilterTags)
                {
                    $this.PublishCustomMessage("No active accounts have been found that matches the specified tags. Tags: [$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
                }
                else
                {
                    $this.PublishCustomMessage("No active accounts have been found that matches the specified tags.", [MessageType]::Warning);
                }
            }
        }
        else
        {
            $this.PublishCustomMessage("No active accounts found in the RBAC policy file", [MessageType]::Warning);
        }
        return @();
    }

    [RBACAccountRoleMapping[]] GetMatchedDeprecatedAccounts([ref]$messages)
    {
        if($this.Policy.DeprecatedAccounts -and $this.Policy.DeprecatedAccounts.Count -ne 0)
        {
            #$this.PublishCustomMessage("Found deprecated accounts in the RBAC policy file");
            
            $startMessage = [MessageData]::new("Processing RBAC rules for removing deprecated central accounts. Total accounts: $($this.Policy.DeprecatedAccounts.Count)");
            $messages.Value += $startMessage;
            #$this.PublishCustomMessage($startMessage);
                
            $disabledAccounts = $this.Policy.DeprecatedAccounts | Where-Object { -not $_.Enabled };
            if(($disabledAccounts | Measure-Object).Count -ne 0)
            {
                $disabledMessage = "Found accounts which are disabled. Total disabled accounts: $($disabledAccounts.Count)";
                $messages.Value += [MessageData]::new($disabledMessage, $disabledAccounts);
                $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
            }

            # Load all properties
            $this.LoadDeprecatedAccountStatus();
                            
            if($this.MatchedDeprecatedAccounts.Count -ne 0)
            {
                $messages.Value += [MessageData]::new("Following deprecated accounts must be removed from the subscription. Total accounts: $($this.MatchedDeprecatedAccounts.Count)", ($this.MatchedDeprecatedAccounts | Select-Object -Property RoleAssignment));
            }
            else
            {
                $resultMessage = [MessageData]::new("No deprecated accounts found on the subscription", [MessageType]::Warning);
                $messages.Value += $resultMessage;
                $this.PublishCustomMessage($resultMessage);
            }
            return $this.MatchedDeprecatedAccounts;                    
        }
        else
        {
            $this.PublishCustomMessage("No deprecated accounts found in the RBAC policy file");
        }
        return @();
    }

    [MessageData[]] RemoveRBACAccounts()
    {    
        [MessageData[]] $messages = @();
        if($this.Force -or -not ($this.IsLatestVersionConfiguredOnSub($this.Policy.DeprecatedAccountsVersion,[Constants]::DeprecatedRBACVersionTagName,"DeprecatedRBAC")))
        {
            #setting the tag at AzSKRG
            $azskRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
            [Helpers]::SetResourceGroupTags($azskRGName,@{[Constants]::DeprecatedRBACVersionTagName=$this.Policy.DeprecatedAccountsVersion}, $false)            

            if($this.Policy.ValidActiveAccounts.Count -ne 0)
            {
                if($this.GetApplicableActiveAccounts().Count -ne 0)
                {
                    $startMessage = [MessageData]::new("Processing RBAC rules for removing central accounts. Tags: [$([string]::Join(",", $this.FilterTags))]. Total accounts: $($this.GetApplicableActiveAccounts().Count)");
                    $messages += $startMessage;
                    $this.PublishCustomMessage($startMessage);

                    $disabledAccounts = $this.GetApplicableActiveAccounts() | Where-Object { -not $_.Enabled };
                    if(($disabledAccounts | Measure-Object).Count -ne 0)
                    {
                        $disabledMessage = "Found accounts which are disabled. Total disabled accounts: $($disabledAccounts.Count)";
                        $messages += [MessageData]::new($disabledMessage, $disabledAccounts);
                        $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
                    }

                    # Load all properties
                    $this.LoadActiveAccountStatus();

                    $messages += $this.RemoveRoleAssignments($this.MatchedActiveAccounts);
                    [Helpers]::SetResourceGroupTags($azskRGName,@{[Constants]::CentralRBACVersionTagName=$this.Policy.ActiveCentralAccountsVersion}, $true)
                }
                else
                {
                    if($this.FilterTags)
                    {
                        $this.PublishCustomMessage("No active accounts have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
                    }
                    else
                    {
                        $this.PublishCustomMessage("No active accounts have been found that matches the specified tags.", [MessageType]::Warning);
                    }
                }
            }
            else
            {
                $this.PublishCustomMessage("No active accounts found in the RBAC policy file", [MessageType]::Warning);
            }
                
            # Remove deprecated accounts
            $depAccounts = $this.GetMatchedDeprecatedAccounts(([ref]$messages));
            $messages += $this.RemoveRBACAccounts($depAccounts);
        }

        return $messages;
    }

    hidden [MessageData[]] RemoveRoleAssignments([RBACAccountRoleMapping[]] $rbacRoleMapping)
    {
        [MessageData[]] $messages = @();
        if($rbacRoleMapping.Count -ne 0)
        {
            $messages += [MessageData]::new("Total matching accounts found in the subscription: $($rbacRoleMapping.Count)");
            $provisionAccounts = @();
            $provisionAccounts += $rbacRoleMapping | Where-Object { $_.RBACAccount.Type -eq [RBACAccountType]::Provision };

            $messages += $this.RemoveRBACAccounts($provisionAccounts);

            $nonProvisionAccounts = @();
            $nonProvisionAccounts += $rbacRoleMapping | Where-Object { $_.RBACAccount.Type -ne [RBACAccountType]::Provision };

            if($nonProvisionAccounts.Count -ne 0)
            {
                $messageText = "Some accounts were not removed from the subscription, since the account type is not set to 'Provision' in RBAC policy file. Total accounts: $($nonProvisionAccounts.Count)";
                $messages += [MessageData]::new($messageText, ($nonProvisionAccounts | Select-Object -Property RoleAssignment));                                            
                #$this.PublishCustomMessage($messageText);
            }
        }
        return $messages;
    }

    hidden [MessageData[]] RemoveRBACAccounts([RBACAccountRoleMapping[]] $rbacRoleMapping)
    {
        [MessageData[]] $messages = @();
        if($rbacRoleMapping.Count -ne 0)
        {
            # Removing Central Accounts
            $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nRemoving following accounts from the subscription. Total accounts: $($rbacRoleMapping.Count)", ($rbacRoleMapping | Select-Object -Property RoleAssignment));
            $errorCount = 0;
            $currentCount = 0;
            $rbacRoleMapping | ForEach-Object {
                $accountName = $_.RoleAssignment.DisplayName;
                $currentCount += 1;
                if(-not [string]::IsNullOrWhiteSpace($_.RoleAssignment.SignInName))
                {
                    $accountName += " ($($_.RoleAssignment.SignInName))";
                }
                # Remove account
                try
                {
                    $this.PublishCustomMessage("Removing account [$accountName] from the subscription");
                    Remove-AzRoleAssignment -ObjectId $_.RoleAssignment.ObjectId -Scope $_.RoleAssignment.Scope -RoleDefinitionName $_.RoleAssignment.RoleDefinitionName -ErrorAction Stop | Out-Null                                         
                }
                catch
                {
                    $messages += [MessageData]::new("Error while removing account [$accountName] from the subscription", $_, [MessageType]::Error);
                    $errorCount += 1;
                }

                $this.CommandProgress($rbacRoleMapping.Count, $currentCount, 5);
            };

            [MessageData[]] $resultMessages = @();
            if($errorCount -eq 0)
            {
                $resultMessages += [MessageData]::new("All matched accounts have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
            }
            elseif($errorCount -eq $rbacRoleMapping.Count)
            {
                $resultMessages += [MessageData]::new("No accounts were removed due to an error. Please remove the accounts manually. You can find the specific account details in the log file.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error);
            }
            else
            {
                $resultMessages += [MessageData]::new("$errorCount/$($rbacRoleMapping.Count) matched account(s) have not been removed from the subscription. Please remove the accounts manually.", [MessageType]::Error);
                $resultMessages += [MessageData]::new("$($rbacRoleMapping.Count - $errorCount)/$($rbacRoleMapping.Count) matched account(s) have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
            }

            $messages += $resultMessages;
            $this.PublishCustomMessage($resultMessages);
        }
        return $messages;
    }
}

class RBACAccountRoleMapping
{
    hidden [PSRoleAssignment] $RoleAssignment = $null;
    
    hidden [RBACAccount] $RBACAccount = $null;
}