ADSec.psm1
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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 |
$script:ModuleRoot = $PSScriptRoot $script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\ADSec.psd1").ModuleVersion # Detect whether at some level dotsourcing was enforced $script:doDotSource = Get-PSFConfigValue -FullName ADSec.Import.DoDotSource -Fallback $false if ($ADSec_dotsourcemodule) { $script:doDotSource = $true } <# Note on Resolve-Path: All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator. This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS. Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist. This is important when testing for paths. #> # Detect whether at some level loading individual module files, rather than the compiled module was enforced $importIndividualFiles = Get-PSFConfigValue -FullName ADSec.Import.IndividualFiles -Fallback $false if ($ADSec_importIndividualFiles) { $importIndividualFiles = $true } if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true } if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true } function Import-ModuleFile { <# .SYNOPSIS Loads files into the module on module import. .DESCRIPTION This helper function is used during module initialization. It should always be dotsourced itself, in order to proper function. This provides a central location to react to files being imported, if later desired .PARAMETER Path The path to the file to load .EXAMPLE PS C:\> . Import-ModuleFile -File $function.FullName Imports the file stored in $function according to import policy #> [CmdletBinding()] Param ( [string] $Path ) $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath if ($doDotSource) { . $resolvedPath } else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) } } #region Load individual files if ($importIndividualFiles) { # Execute Preimport actions . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1" # Import all internal functions foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Import all public functions foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Execute Postimport actions . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1" # End it here, do not load compiled code below return } #endregion Load individual files #region Load compiled code <# This file loads the strings documents from the respective language folders. This allows localizing messages and errors. Load psd1 language files for each language you wish to support. Partial translations are acceptable - when missing a current language message, it will fallback to English or another available language. #> Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'ADSec' -Language 'en-US' function Assert-ADConnection { <# .SYNOPSIS Ensures basic ad connectivity .DESCRIPTION Ensures basic ad connectivity Used to ensure subsequent commands have a chance to succeed with the specified server/credential combination. .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER Cmdlet $PSCmdlet of the calling command. Used to handle errors. .EXAMPLE PS C:\> Assert-ADConnection @adParameters -Cmdlet $PSCmdlet Asserts that AD operations under the specified circumstances are possible. #> [CmdletBinding()] Param ( [string] $Server, [System.Management.Automation.PSCredential] $Credential, [System.Management.Automation.PSCmdlet] $Cmdlet ) process { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential try { $null = Get-ADDomain @adParameters -ErrorAction Stop } catch { if ($Credential) { $userName = $Credential.UserName } else { $userName = '{0}\{1}' -f $env:USERDOMAIN, $env:USERNAME } if ($Server) { $target = $Server } else { $target = $env:USERDNSDOMAIN } Stop-PSFFunction -String 'Assert-ADConnection.Failed' -StringValues $target, $userName -EnableException $true -Cmdlet $Cmdlet -FunctionName $Cmdlet.CommandRuntime.ToString() -ErrorRecord $_ } } } function Get-LdapObject { <# .SYNOPSIS Use LDAP to search in Active Directory .DESCRIPTION Utilizes LDAP to perform swift and efficient LDAP Queries. .PARAMETER LdapFilter The search filter to use when searching for objects. Must be a valid LDAP filter. .PARAMETER Properties The properties to retrieve. Keep bandwidth in mind and only request what is needed. .PARAMETER SearchRoot The root path to search in. This generally expects either the distinguished name of the Organizational unit or the DNS name of the domain. Alternatively, any legal LDAP protocol address can be specified. .PARAMETER Configuration Rather than searching in a specified path, switch to the configuration naming context. .PARAMETER Raw Return the raw AD object without processing it for PowerShell convenience. .PARAMETER PageSize Rather than searching in a specified path, switch to the schema naming context. .PARAMETER SearchScope Whether to search all OUs beneath the target root, only directly beneath it or only the root itself. .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use. .EXAMPLE PS C:\> Get-LdapObject -LdapFilter '(PrimaryGroupID=516)' Searches for all objects with primary group ID 516 (hint: Domain Controllers). #> [CmdletBinding(DefaultParameterSetName = 'SearchRoot')] param ( [Parameter(Mandatory = $true)] [string] $LdapFilter, [string[]] $Properties = "*", [Parameter(ParameterSetName = 'SearchRoot')] [string] $SearchRoot, [Parameter(ParameterSetName = 'Configuration')] [switch] $Configuration, [switch] $Raw, [ValidateRange(1, 1000)] [int] $PageSize = 1000, [System.DirectoryServices.SearchScope] $SearchScope = 'Subtree', [string] $Server, [System.Management.Automation.PSCredential] $Credential ) begin { $searcher = New-Object system.directoryservices.directorysearcher $searcher.PageSize = $PageSize $searcher.SearchScope = $SearchScope if ($Credential) { $searcher.SearchRoot.Username = $Credential.UserName try { $searcher.SearchRoot.Password = $Credential.GetNetworkCredential().Password } catch { Stop-PSFFunction -String 'Get-LdapObject.CredentialError' -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $true } } if ($SearchRoot) { if ($SearchRoot -like "LDAP://*") { $searcher.SearchRoot.Path = $SearchRoot } elseif ($SearchRoot -notlike "*=*") { $searcher.SearchRoot.Path = "LDAP://DC={0}" -f ($SearchRoot -split "\." -join ",DC=") } else { $searcher.SearchRoot.Path = "LDAP://$($SearchRoot)" } } if ($Configuration) { $searcher.SearchRoot.Path = "LDAP://CN=Configuration,{0}" -f $searcher.SearchRoot.distinguishedName[0] } if ($Server -and ($searcher.SearchRoot.Path -notmatch '^LDAP://[\w\.]+/')) { $searcher.SearchRoot.Path = $searcher.SearchRoot.Path -replace '^LDAP://', "LDAP://$Server/" } Write-PSFMessage -String Get-LdapObject.SearchRoot -StringValues $SearchScope, $searcher.SearchRoot.Path -Level Debug $searcher.Filter = $LdapFilter foreach ($property in $Properties) { $null = $searcher.PropertiesToLoad.Add($property) } Write-PSFMessage -String Get-LdapObject.Searchfilter -StringValues $LdapFilter -Level Debug } process { try { foreach ($ldapobject in $searcher.FindAll()) { if ($Raw) { $ldapobject continue } $resultHash = @{ } foreach ($key in $ldapobject.Properties.Keys) { # Write-Output verwandelt Arrays mit nur einem Wert in nicht-Array Objekt $resultHash[$key] = $ldapobject.Properties[$key] | Write-Output } if ($resultHash.ContainsKey("ObjectClass")) { $resultHash["PSTypeName"] = $resultHash["ObjectClass"] } [pscustomobject]$resultHash } } catch { Stop-PSFFunction -String 'Get-LdapObject.SearchError' -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $true } } } function Disable-AdsInheritance { <# .SYNOPSIS Disables inheritance on an Active Directoey object. .DESCRIPTION Disables inheritance on an Active Directoey object. .PARAMETER Path The distinguished name of the object to process. .PARAMETER DiscardInherited By default, all previously inherited access rules will be preserved as new explicit rules. Using this parameter, all inherited access rules will be discarded instead. .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Get-ADUser administrator | Disable-AdsInheritance Disables inheritance on the administrator object. .EXAMPLE PS C:\> Get-ADComputer -LDAPFilter '(primaryGroupID=516)' | Disable-AdsInheritance -DiscardInherited Disables inheritance on all domain controllers, remove all previously inherited access rules. #> [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] Param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [Alias('DistinguishedName')] [string[]] $Path, [switch] $DiscardInherited, [string] $Server, [System.Management.Automation.PSCredential] $Credential, [switch] $EnableException ) begin { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential Assert-ADConnection @adParameters -Cmdlet $PSCmdlet # Wrap as nested pipeline to avoid asserting connection each time $getCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException } $getAdsAcl = $getCmd.GetSteppablePipeline() $getAdsAcl.Begin($true) $setCmd = { Set-AdsAcl @adParameters -EnableException:$EnableException } $setAdsAcl = $setCmd.GetSteppablePipeline() $setAdsAcl.Begin($true) } process { foreach ($pathItem in $Path) { Write-PSFMessage -String 'Disable-AdsInheritance.Processing' -StringValues $pathItem -Target $pathItem try { $aclObject = ($getAdsAcl.Process($pathItem))[0] } catch { Stop-PSFFunction -String 'Disable-AdsInheritance.ReadAcl.Failed' -StringValues $pathItem -ErrorRecord $_ -EnableException $EnableException -Continue -Target $pathItem } $changedAnything = $false if (-not $aclObject.AreAccessRulesProtected) { $aclObject.SetAccessRuleProtection($true, (-not $DiscardInherited)) $changedAnything = $true } if (-not $changedAnything) { Write-PSFMessage -String 'Disable-AdsInheritance.NoChange.Skipping' -StringValues $pathItem -Target $pathItem continue } Invoke-PSFProtectedCommand -ActionString 'Disable-AdsInheritance.Updating.Acl' -Target $pathItem -ScriptBlock { $setAdsAcl.Process($aclObject) } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue } } end { $getAdsAcl.End() $setAdsAcl.End() } } function Enable-AdsInheritance { <# .SYNOPSIS Enables inheritance on an Active Directoey object. .DESCRIPTION Enables inheritance on an Active Directoey object. .PARAMETER Path The distinguished name of the object to process. .PARAMETER RemoveExplicit By default, all previous access rules will be preserved. Using this parameter, all explicit access rules will instead be removed. .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Get-ADUser administrator | Enable-AdsInheritance Enables inheritance on the administrator object. .EXAMPLE PS C:\> Get-ADComputer -LDAPFilter '(primaryGroupID=516)' | Enable-AdsInheritance -RemoveExplicit Remove all explicit permissions for deletion. #> [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] Param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [Alias('DistinguishedName')] [string[]] $Path, [switch] $RemoveExplicit, [string] $Server, [System.Management.Automation.PSCredential] $Credential, [switch] $EnableException ) begin { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential Assert-ADConnection @adParameters -Cmdlet $PSCmdlet # Wrap as nested pipeline to avoid asserting connection each time $getCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException } $getAdsAcl = $getCmd.GetSteppablePipeline() $getAdsAcl.Begin($true) $setCmd = { Set-AdsAcl @adParameters -EnableException:$EnableException } $setAdsAcl = $setCmd.GetSteppablePipeline() $setAdsAcl.Begin($true) } process { foreach ($pathItem in $Path) { Write-PSFMessage -String 'Enable-AdsInheritance.Processing' -StringValues $pathItem -Target $pathItem try { $aclObject = ($getAdsAcl.Process($pathItem))[0] } catch { Stop-PSFFunction -String 'Enable-AdsInheritance.ReadAcl.Failed' -StringValues $pathItem -ErrorRecord $_ -EnableException $EnableException -Continue -Target $pathItem } $changedAnything = $false if ($aclObject.AreAccessRulesProtected) { $aclObject.SetAccessRuleProtection($false, $true) $changedAnything = $true } if ($RemoveExplicit -and ($aclObject.Access | Where-Object IsInherited -EQ $false)) { ($aclObject.Access) | Where-Object IsInherited -EQ $false | & { process { Write-PSFMessage -Level Debug -String 'Enable-AdsInheritance.AccessRule.Remove' -StringValues $_.IdentityReference, $_.ActiveDirectoryRights, $_.AccessControlType -Target $pathItem $null = $aclObject.RemoveAccessRule($_) } } $changedAnything = $true } if (-not $changedAnything) { Write-PSFMessage -String 'Enable-AdsInheritance.NoChange.Skipping' -StringValues $pathItem -Target $pathItem continue } Invoke-PSFProtectedCommand -ActionString 'Enable-AdsInheritance.Updating.Acl' -Target $pathItem -ScriptBlock { $setAdsAcl.Process($aclObject) } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue } } end { $getAdsAcl.End() $setAdsAcl.End() } } function Get-AdsAcl { <# .SYNOPSIS Reads the ACL from an AD object. .DESCRIPTION Reads the ACL from an AD object. Allows specifying the server to ask. .PARAMETER Path The DistinguishedName path to the item. .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Get-ADUser -Filter * | Get-AdsAcl Returns the ACL of every user in the domain. #> [OutputType([System.DirectoryServices.ActiveDirectorySecurity])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [Alias('DistinguishedName')] [string[]] $Path, [string] $Server, [System.Management.Automation.PSCredential] $Credential, [switch] $EnableException ) begin { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential Assert-ADConnection @adParameters -Cmdlet $PSCmdlet } process { if (Test-PSFFunctionInterrupt) { return } foreach ($pathItem in $Path) { if (-not $pathItem) { continue } Write-PSFMessage -String 'Get-AdsAcl.Processing' -StringValues $pathItem try { $adObject = Get-ADObject @adParameters -Identity $pathItem -Properties ntSecurityDescriptor } catch { Stop-PSFFunction -String 'Get-AdsAcl.ObjectError' -StringValues $pathItem -Target $pathItem -EnableException $EnableException -Cmdlet $PSCmdlet -ErrorRecord $_ -Continue } $aclObject = $adObject.ntSecurityDescriptor Add-Member -InputObject $aclObject -MemberType NoteProperty -Name DistinguishedName -Value $adObject.DistinguishedName -Force $aclObject } } } function Get-AdsOrphanAce { <# .SYNOPSIS Returns list of all access rules that have an unresolveable identity. .DESCRIPTION Returns list of all access rules that have an unresolveable identity. This is aimed at identifying and help remediating orphaned SIDs in active directory. .PARAMETER Path The full distinguished name to the object to scan. .PARAMETER ExcludeDomainSID SIDs from the specified domain SIDs will be ignored. Use this to safely handle one-way trust where ID resolution is impossible for some IDs. .PARAMETER IncludeDomainSID If specified, only unresolved identities from the specified SIDs will be listed. Use this to safely target only rules from your owned domains in the targeted domain. .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Get-ADObject -LDAPFillter '(objectCategory=*)' | Get-AdsOrphanAce Scans all objects in the current domain for orphaned access rules. #> [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [string[]] $Path, [string[]] $ExcludeDomainSID, [string[]] $IncludeDomainSID, [string] $Server, [System.Management.Automation.PSCredential] $Credential, [switch] $EnableException ) begin { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential Assert-ADConnection @adParameters -Cmdlet $PSCmdlet function Write-Result { [CmdletBinding()] param ( [string] $Path, [System.DirectoryServices.ActiveDirectoryAccessRule] $AccessRule ) [PSCustomObject]@{ PSTypeName = 'ADSec.AccessRule' Path = $Path Identity = $AccessRule.IdentityReference ADRights = $AccessRule.ActiveDirectoryRights Type = $AccessRule.AccessControlType ObjectType = $AccessRule.ObjectType InheritedOpectType = $AccessRule.InheritedObjectType Rule = $AccessRule } } # Wrap as nested pipeline to avoid asserting connection each time $scriptCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException } $getAdsAcl = $scriptCmd.GetSteppablePipeline() $getAdsAcl.Begin($true) } process { foreach ($pathItem in $Path) { try { $acl = $getAdsAcl.Process($pathItem) } catch { Stop-PSFFunction -String 'Get-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -ErrorRecord $_ -Cmdlet $PSCmdlet -Continue } if (-not $acl) { Stop-PSFFunction -String 'Get-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -Cmdlet $PSCmdlet -Continue } foreach ($rule in $acl.Access) { if ($rule.IsInherited) { continue } if ($rule.IdentityReference -is [System.Security.Principal.NTAccount]) { continue } if ($rule.IdentityReference.AccountDomainSID.Value -in $ExcludeDomainSID) { continue } if ($IncludeDomainSID -and ($rule.IdentityReference.AccountDomainSID.Value -notin $IncludeDomainSID)) { continue } try { $null = $rule.IdentityReference.Translate([System.Security.Principal.NTAccount]) } catch { Write-Result -Path $pathItem -AccessRule $rule } } } } end { $getAdsAcl.End() } } function Remove-AdsOrphanAce { <# .SYNOPSIS Removes all access rules that have an unresolveable identity. .DESCRIPTION Removes all access rules that have an unresolveable identity. This is aimed at identifying and remediating orphaned SIDs in active directory. .PARAMETER Path The full distinguished name to the object to clean. .PARAMETER ExcludeDomainSID SIDs from the specified domain SIDs will be ignored. Use this to safely handle one-way trust where ID resolution is impossible for some IDs. .PARAMETER IncludeDomainSID If specified, only unresolved identities from the specified SIDs will be listed. Use this to safely target only rules from your owned domains in the targeted domain. .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Get-ADObject -LDAPFillter '(objectCategory=*)' | Remove-AdsOrphanAce Purges all objects in the current domain from orphaned access rules. #> [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] param ( [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [string[]] $Path, [string[]] $ExcludeDomainSID, [string[]] $IncludeDomainSID, [string] $Server, [System.Management.Automation.PSCredential] $Credential, [switch] $EnableException ) begin { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential Assert-ADConnection @adParameters -Cmdlet $PSCmdlet function Write-Result { [CmdletBinding()] param ( [string] $Path, [System.DirectoryServices.ActiveDirectoryAccessRule] $AccessRule, [ValidateSet('Deleted', 'Failed')] [string] $Action, [System.Management.Automation.ErrorRecord] $ErrorRecord ) [PSCustomObject]@{ PSTypeName = 'ADSec.AccessRule' Path = $Path Identity = $AccessRule.IdentityReference Action = $Action ADRights = $AccessRule.ActiveDirectoryRights Type = $AccessRule.AccessControlType ObjectType = $AccessRule.ObjectType InheritedOpectType = $AccessRule.InheritedObjectType Rule = $AccessRule Error = $ErrorRecord } } # Wrap as nested pipeline to avoid asserting connection each time $scriptCmd = { Get-AdsAcl @adParameters -EnableException:$EnableException } $getAdsAcl = $scriptCmd.GetSteppablePipeline() $getAdsAcl.Begin($true) } process { foreach ($pathItem in $Path) { Write-PSFMessage -Level Verbose -String 'Remove-AdsOrphanAce.Searching' -StringValues $pathItem try { $acl = $getAdsAcl.Process($pathItem) | Write-Output } catch { Stop-PSFFunction -String 'Remove-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -ErrorRecord $_ -Cmdlet $PSCmdlet -Continue } if (-not $acl) { Stop-PSFFunction -String 'Remove-AdsOrphanAce.Read.Failed' -StringValues $pathItem -EnableException $EnableException -Cmdlet $PSCmdlet -Continue } $rulesToPurge = foreach ($rule in $acl.Access) { if ($rule.IsInherited) { continue } if ($rule.IdentityReference -is [System.Security.Principal.NTAccount]) { continue } if ($rule.IdentityReference.AccountDomainSID.Value -in $ExcludeDomainSID) { continue } if ($IncludeDomainSID -and ($rule.IdentityReference.AccountDomainSID.Value -notin $IncludeDomainSID)) { continue } try { $null = $rule.IdentityReference.Translate([System.Security.Principal.NTAccount]) } catch { $null = $acl.RemoveAccessRule($rule) $rule } } if (-not $rulesToPurge) { Write-PSFMessage -Level Verbose -String 'Remove-AdsOrphanAce.NoOrphans' -StringValues $pathItem continue } Invoke-PSFProtectedCommand -ActionString 'Remove-AdsOrphanAce.Removing' -ActionStringValues ($rulesToPurge | Measure-Object).Count -Target $pathItem -ScriptBlock { try { Set-ADObject @adParameters -Identity $pathItem -Replace @{ ntSecurityDescriptor = $acl } -ErrorAction Stop foreach ($rule in $rulesToPurge) { Write-Result -Path $pathItem -AccessRule $rule -Action Deleted } } catch { foreach ($rule in $rulesToPurge) { Write-Result -Path $pathItem -AccessRule $rule -Action Failed -ErrorRecord $_ } throw } } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet -Continue } } end { $getAdsAcl.End() } } function Set-AdsAcl { <# .SYNOPSIS Updates the ACL on an active directory object. .DESCRIPTION Updates the ACL on an active directory object. Used to manage AD delegation. .PARAMETER Path The path / distinguishedname to the object to manage. .PARAMETER AclObject The acl to apply .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> $acl | Set-AdsAcl Applies the acl object(s) stored in $acl. Assumes that 'Get-AdsAcl' was used to retrieve the data originally. .EXAMPLE PS C:\> Set-AdsAcl -AclObject $acl -Path $dn -Server fabrikam.com Updates the acl on the object stored in $dn within the fabrikam.com domain. #> [CmdletBinding(SupportsShouldProcess = $true)] Param ( [Alias('DistinguishedName')] [string] $Path, [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [System.DirectoryServices.ActiveDirectorySecurity] $AclObject, [string] $Server, [System.Management.Automation.PSCredential] $Credential, [switch] $EnableException ) begin { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential Assert-ADConnection @adParameters -Cmdlet $PSCmdlet } process { if (-not $Path) { if ($AclObject.DistinguishedName) { $Path = $AclObject.DistinguishedName } else { Stop-PSFFunction -String 'Set-AdsAcl.NoPath' -Target $AclObject -EnableException $EnableException -Category InvalidArgument return } } Invoke-PSFProtectedCommand -ActionString 'Set-AdsAcl.SettingSecurity' -Target $Path -ScriptBlock { Set-ADObject @adParameters -Identity $Path -Replace @{ ntSecurityDescriptor = $AclObject } -ErrorAction Stop } -EnableException $EnableException.ToBool() -PSCmdlet $PSCmdlet } } function Set-AdsOwner { <# .SYNOPSIS Changes the owner of the specified AD object to the target identity. .DESCRIPTION Changes the owner of the specified AD object to the target identity. .PARAMETER Path Path to the object to update .PARAMETER Identity Identity to make the new owner. .PARAMETER WinRMFailover Whether on execution error it should try again using WinRM. Default-Value determined using the configuration setting 'ADSec.WinRM.FailOver' .PARAMETER Server The server / domain to connect to. .PARAMETER Credential The credentials to use for AD operations. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Set-AdsOwner -Path $dn -Identity 'contoso\Domain Admins' Makes the domain admins owner of the path specified in $dn #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseUsingScopeModifierInNewRunspaces', '')] [CmdletBinding(SupportsShouldProcess = $true)] Param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [Alias('DistinguishedName')] [string[]] $Path, [Parameter(Mandatory = $true)] [string] $Identity, [switch] $WinRMFailover = (Get-PSFConfigValue -FullName 'ADSec.WinRM.FailOver'), [string] $Server, [System.Management.Automation.PSCredential] $Credential, [switch] $EnableException ) begin { $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential Assert-ADConnection @adParameters -Cmdlet $PSCmdlet if ($Identity -as [System.Security.Principal.SecurityIdentifier]) { $idReference = [System.Security.Principal.SecurityIdentifier]$Identity } else { $idReference = [System.Security.Principal.NTAccount]$Identity try { $null = $idReference.Translate([System.Security.Principal.SecurityIdentifier]) } catch { Stop-PSFFunction -String 'Set-AdsOwner.UnresolvedIdentity' -StringValues $Identity -EnableException $EnableException -ErrorRecord $_ -OverrideExceptionMessage return } } $basePath = 'LDAP://{0}' if ($Server) { $basePath = "LDAP://$Server/{0}" } } process { if (Test-PSFFunctionInterrupt) { return } foreach ($pathItem in $Path) { $aclObject = Get-AdsAcl @adParameters -Path $pathItem if ($aclObject.Owner -eq $idReference) { Write-PSFMessage -String 'Set-AdsOwner.AlreadyOwned' -StringValues $pathItem, $idReference continue } # Switching to LDAP as owner changes don't work using AD Module if ($Credential) { $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry(($basePath -f $pathItem), $Credential.UserName, $Credential.GetNetworkCredential().Password) } else { $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry(($basePath -f $pathItem)) } Invoke-PSFProtectedCommand -ActionString 'Set-AdsOwner.UpdatingOwner' -ActionStringValues $idReference -ScriptBlock { try { $secDescriptor = $directoryEntry.InvokeGet('nTSecurityDescriptor') if (-not $secDescriptor) { throw 'Failed to access security information' } $secDescriptor.Owner = "$idReference" $directoryEntry.InvokeSet('nTSecurityDescriptor', $secDescriptor) $directoryEntry.CommitChanges() } catch { if (-not $WinRMFailover) { throw } #region Fallback to WinRM $domainController = Get-ADDomainController @adParameters $credParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential $ldapPath = "LDAP://localhost/$($pathItem)" Invoke-Command -ComputerName $domainController.HostName @credParam -ScriptBlock { param ( $Identity, $LdapPath ) try { $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry($LdapPath) $secDescriptor = $directoryEntry.InvokeGet('nTSecurityDescriptor') if (-not $secDescriptor) { throw 'Failed to access security information' } $secDescriptor.Owner = $Identity $directoryEntry.InvokeSet('nTSecurityDescriptor', $secDescriptor) $directoryEntry.CommitChanges() } catch { throw } } -ArgumentList "$idReference", $ldapPath -ErrorAction Stop #endregion Fallback to WinRM } } -Target $pathItem -EnableException $EnableException.ToBool() -Continue -PSCmdlet $PSCmdlet } } } <# This is an example configuration file By default, it is enough to have a single one of them, however if you have enough configuration settings to justify having multiple copies of it, feel totally free to split them into multiple files. #> <# # Example Configuration Set-PSFConfig -Module 'ADSec' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'" #> Set-PSFConfig -Module 'ADSec' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging." Set-PSFConfig -Module 'ADSec' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments." Set-PSFConfig -Module 'ADSec' -Name 'WinRM.FailOver' -Value $false -Initialize -Validation 'bool' -Description 'Whether to fail over to WinRM if LDAP-Based operations fail. Used for ownership changes.' <# Stored scriptblocks are available in [PsfValidateScript()] attributes. This makes it easier to centrally provide the same scriptblock multiple times, without having to maintain it in separate locations. It also prevents lengthy validation scriptblocks from making your parameter block hard to read. Set-PSFScriptblock -Name 'ADSec.ScriptBlockName' -Scriptblock { } #> <# # Example: Register-PSFTeppScriptblock -Name "ADSec.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> <# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name ADSec.alcohol #> New-PSFLicense -Product 'ADSec' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-10-01") -Text @" Copyright (c) 2019 Friedrich Weinmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "@ #endregion Load compiled code |