ADACLScan
ADACLScan
.Synopsis
ADACLScan.ps1
THIS CODE-SAMPLE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPR
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTAB
FITNESS FOR A PARTICULAR PURPOSE.
.DESCRIPTION
A tool with GUI or command linte used to create reports of access control lists (DACLs) and system a
See https://github.com/canix1/ADACLScanner
.EXAMPLE
.\ADACLScan.ps1
Start in GUI mode.
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM"
Returns the permissions of the object CORP.
.EXAMPLE
.\ADACLScan.ps1 -Base rootdse
Returns the ACL of the domain root.
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Credentials $CREDS -Server 10.0.0
Returns the permissions of the object CORP using credentials on Domain Controller 10.0.0.20.
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Output HTML
Create a HTML file with the permissions of the object CORP.
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Output EXCEL
Create a Excel file with the permissions of the object CORP.
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Output HTML -Show
Opens the HTML (HTA) file with the permissions of the object CORP.
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Output HTML -Show -SDDate
Opens the HTML (HTA) file with the permissions of the object CORP including the modified date of th
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -OutputFolder C:\Temp
Create a CSV file in the folder C:\Temp, with the permissions of the object CORP.
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Scope subtree
Create a CSV file with the permissions of the object CORP and all child objects of type Organizationa
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Scope subtree -EffectiveRightsPrinc
Create a CSV file with the effective permissions of all the objects in the path for the user "joe".
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Scope subtree -Filter "(objectClass=
Create a CSV file with the permissions of all the objects in the path and below that matches the filter
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Scope subtree -Filter "(objectClass=
Targeted search against server "DC1" that will create a CSV file with the permissions of all the object
.EXAMPLE
.\ADACLScan.ps1 -Base "OU=CORP,DC=CONTOS,DC=COM" -Scope subtree -Filter "(objectClass=
Targeted search against server "DC1" on port 389 that will create a CSV file with the permissions of a
.EXAMPLE
.\ADACLScan.ps1 -Base "ou=mig,dc=contoso,dc=com" -Output CSVTEMPLATE
Exit
}
#Set global value for time out in paged searches
$global:TimeoutSeconds = 120
#Set global value for page size in paged searches
$global:PageSize = 1000
# Hash table for Forest Level
$global:ForestFLHashAD = @{
■0="Windows 2000 Server";
■1="Windows Server 2003/Interim";
■2="Windows Server 2003";
■3="Windows Server 2008";
■4="Windows Server 2008 R2";
■5="Windows Server 2012";
■6="Windows Server 2012 R2";
■7="Windows Server 2016";
■8="Windows Server 2019"
}
#Hash table for Domain Level
$global:DomainFLHashAD = @{
■0="Windows 2000 Server";
■1="Windows Server 2003/Interim";
■2="Windows Server 2003";
■3="Windows Server 2008";
■4="Windows Server 2008 R2";
■5="Windows Server 2012";
■6="Windows Server 2012 R2";
■7="Windows Server 2016";
■8="Windows Server 2019"
}
$global:SchemaHashAD = @{
■13="Windows 2000 Server";
■30="Windows Server 2003";
■31="Windows Server 2003 R2";
■44="Windows Server 2008";
■47="Windows Server 2008 R2";
■56="Windows Server 2012";
■69="Windows Server 2012 R2";
■72="Windows Server 2016 Technical Preview";
■81="Windows Server 2016 Technical Preview 2";
■82="Windows Server 2016 Technical Preview 3";
■85="Windows Server 2016 Technical Preview 4";
■87="Windows Server 2016";
■88="Windows Server 2019"
}
■
# List of Exchange Schema versions
$global:SchemaHashExchange = @{
■4397="Exchange Server 2000";
■4406="Exchange Server 2000 SP3";
■6870="Exchange Server 2003";
■6936="Exchange Server 2003 SP3";
■10628="Exchange Server 2007";
■10637="Exchange Server 2007";
■11116="Exchange Server 2007 SP1";
■14622="Exchange Server 2007 SP2 or Exchange Server 2010";
■14726="Exchange Server 2010 SP1";
■14732="Exchange Server 2010 SP2";
■14734="Exchange Server 2010 SP3";
■15137="Exchange Server 2013 RTM";
■15254="Exchange Server 2013 CU1";
■15281="Exchange Server 2013 CU2";
■15283="Exchange Server 2013 CU3";
■15292="Exchange Server 2013 SP1/CU4";
■15300="Exchange Server 2013 CU5";
■15303="Exchange Server 2013 CU6";
■15312="Exchange Server 2013 CU7";
■15317="Exchange Server 2016";
■15323="Exchange Server 2016 CU1";
■15325="Exchange Server 2016 CU2";
■15326="Exchange Server 2016 CU3-CU5";
■15330="Exchange Server 2016 CU6";
■15332="Exchange Server 2016 CU7-CU18";
■15333="Exchange Server 2016 CU19";
■17000="Exchange Server 2019";
■17001="Exchange Server 2019 CU2-CU7";
■17002="Exchange Server 2019 CU8"
}
■
# List of Lync Schema versions
$global:SchemaHashLync = @{
■1006="LCS 2005";
■1007="OCS 2007 R1";
■1008="OCS 2007 R2";
■1100="Lync Server 2010";
■1150="Lync Server 2013/Skype for Business 2015"
}
Function BuildSchemaDic
{
$global:dicSchemaIDGUIDs = @{"BF967ABA-0DE6-11D0-A285-00AA003049E2" ="user";`
"BF967A86-0DE6-11D0-A285-00AA003049E2" = "computer";`
"BF967A9C-0DE6-11D0-A285-00AA003049E2" = "group";`
"BF967ABB-0DE6-11D0-A285-00AA003049E2" = "volume";`
"F30E3BBE-9FF0-11D1-B603-0000F80367C1" = "gPLink";`
"F30E3BBF-9FF0-11D1-B603-0000F80367C1" = "gPOptions";`
"BF967AA8-0DE6-11D0-A285-00AA003049E2" = "printQueue";`
"4828CC14-1437-45BC-9B07-AD6F015E5F28" = "inetOrgPerson";`
"5CB41ED0-0E4C-11D0-A286-00AA003049E2" = "contact";`
"BF967AA5-0DE6-11D0-A285-00AA003049E2" = "organizationalUnit";`
"BF967A0A-0DE6-11D0-A285-00AA003049E2" = "pwdLastSet"}
$global:dicNameToSchemaIDGUIDs = @{"user"="BF967ABA-0DE6-11D0-A285-00AA003049E2";`
"computer" = "BF967A86-0DE6-11D0-A285-00AA003049E2";`
"group" = "BF967A9C-0DE6-11D0-A285-00AA003049E2";`
"volume" = "BF967ABB-0DE6-11D0-A285-00AA003049E2";`
"gPLink" = "F30E3BBE-9FF0-11D1-B603-0000F80367C1";`
"gPOptions" = "F30E3BBF-9FF0-11D1-B603-0000F80367C1";`
"printQueue" = "BF967AA8-0DE6-11D0-A285-00AA003049E2";`
"inetOrgPerson" = "4828CC14-1437-45BC-9B07-AD6F015E5F28";`
"contact" = "5CB41ED0-0E4C-11D0-A286-00AA003049E2";`
"organizationalUnit" = "BF967AA5-0DE6-11D0-A285-00AA003049E2";`
"pwdLastSet" = "BF967A0A-0DE6-11D0-A285-00AA003049E2"}
}
BuildSchemaDic
$CurrentFSPath = $PSScriptRoot
Add-Type -Assembly PresentationFramework
$xamlBase = @"
<Window x:Class="ADACLScanXAMLProj.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AD ACL Scanner" WindowStartupLocation="CenterScreen" Height="690" Width="1035" Re
<Window.Resources>
<XmlDataProvider x:Name="xmlprov" x:Key="DomainOUData"/>
<DrawingImage x:Name="FolderImage" x:Key="FolderImage" >
<DrawingImage.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="#FF3D85F5">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="3,6,32,22" RadiusX="0" RadiusY="0" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing Brush="#FF3D81F5">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="18,3,13,5" RadiusX="2" RadiusY="2" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
<HierarchicalDataTemplate x:Key="NodeTemplate" ItemsSource="{Binding XPath=OU}">
<StackPanel Orientation="Horizontal">
<Image Width="16" Height="16" Stretch="Fill" Source="{Binding XPath=@Img}"/>
<TextBlock Text="{Binding XPath=@Name}" Margin="2,0,0,0" />
</StackPanel>
</HierarchicalDataTemplate>
</Window.Resources>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Height="640" Width="1000">
<StackPanel Orientation="Vertical" Margin="10,0,0,0" >
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical">
<TabControl x:Name="tabConnect" HorizontalAlignment="Left" Height="245" Margin="
<TabItem x:Name="tabNCSelect" Header="Connect" Width="85">
<StackPanel Orientation="Vertical" Margin="05,0">
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbDSdef" Content="Domain" HorizontalAlignment="L
<RadioButton x:Name="rdbDSConf" Content="Config" HorizontalAlignment="L
<RadioButton x:Name="rdbDSSchm" Content="Schema" HorizontalAlignment
<RadioButton x:Name="rdbCustomNC" Content="Custom" HorizontalAlignme
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="05,05,0,0" >
<Label x:Name="lblServer" Content="Server:" HorizontalAlignment="Left" Hei
<TextBox x:Name="txtBdoxDSServer" HorizontalAlignment="Left" Height="18
<Label x:Name="lblPort" Content="Port:" HorizontalAlignment="Left" Height="
<TextBox x:Name="txtBdoxDSServerPort" HorizontalAlignment="Left" Height=
</StackPanel>
<StackPanel Orientation="Vertical" Margin="05,05,0,0" >
<StackPanel Orientation="Horizontal" Margin="0,0,0.0,0" >
<Label x:Name="lblDomain" Content="Naming Context:" HorizontalAlignme
<CheckBox x:Name="chkBoxCreds" Content="Credentials" HorizontalAlign
</StackPanel>
<TextBox x:Name="txtBoxDomainConnect" HorizontalAlignment="Left" Height
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="05,05,0,0" >
<Button x:Name="btnDSConnect" Content="Connect" HorizontalAlignment="L
<Button x:Name="btnListDdomain" Content="List Domains" HorizontalAlignme
</StackPanel>
<GroupBox x:Name="gBoxBrowse" Grid.Column="0" Header="Browse Options"
<StackPanel Orientation="Vertical" Margin="0,0">
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbBrowseOU" Content="OU's" HorizontalAlignm
<RadioButton x:Name="rdbBrowseAll" Content="All Objects" HorizontalA
<CheckBox x:Name="chkBoxShowDel" Content="Show Deleted" Horizon
</StackPanel>
</StackPanel>
</GroupBox>
</StackPanel>
</TabItem>
<TabItem x:Name="tabForestInfo" Header="Forest Info" Width="85">
<StackPanel Orientation="Vertical" Margin="0,05" Width="345" HorizontalAlignmen
<Button x:Name="btnGetForestInfo" Content="Get Forest Info" Margin="0,0,0,0"
<StackPanel Orientation="Horizontal" Margin="0,05">
<Label x:Name="lblFFL" Content="Forest Functional Level:" Width="150" Heig
<TextBox x:Name="txtBoxFFL" Text="" Width="170" Margin="05,0" Height="1
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,01">
<Label x:Name="lblDFL" Content="Domain Functional Level:" Width="150" He
<TextBox x:Name="txtBoxDFL" Text="" Width="170" Margin="05,0" Height="1
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,01">
<Label x:Name="ldblADSchema" Content="AD Schema Version:" Width="150
<TextBox x:Name="txtBoxADSchema" Text="" Width="170" Margin="05,0" He
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,01">
<Label x:Name="lblExchSchema" Content="Exchange Schema Version:" Wid
<TextBox x:Name="txtBoxExSchema" Text="" Width="170" Margin="05,0" He
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,01">
<Label x:Name="lblLyncSchema" Content="Lync Schema Version:" Width="15
<TextBox x:Name="txtBoxLyncSchema" Text="" Width="170" Margin="05,0,0,
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,01">
<Label x:Name="lblListObjectMode" Content="List Object Mode:" Width="150"
<TextBox x:Name="txtListObjectMode" Text="" Width="170" Margin="05,0,0,0
</StackPanel>
</StackPanel>
</TabItem>
<TabItem x:Name="tabConnectionInfo" Header="Connection Info" Width="100" Margi
<StackPanel Orientation="Vertical" Margin="0,0" HorizontalAlignment="Left" Width=
<Label x:Name="lblDC" Content="Domain Controller:" Width="175" Height="24"
<TextBox x:Name="txtDC" Text="" Width="320" Margin="05,0" Height="19" Hori
<Label x:Name="lbldefaultnamingcontext" Content="Default Naming Context:" W
<TextBox x:Name="txtdefaultnamingcontext" Text="" Width="320" Margin="05,0"
<Label x:Name="lblconfigurationnamingcontext" Content="Configuration Naming
<TextBox x:Name="txtconfigurationnamingcontext" Text="" Width="320" Margin=
<Label x:Name="lblschemanamingcontext" Content="Schema Naming Context:"
<TextBox x:Name="txtschemanamingcontext" Text="" Width="320" Margin="05,0
<Label x:Name="lblrootdomainnamingcontext" Content="Root Domain Naming C
<TextBox x:Name="txtrootdomainnamingcontext" Text="" Width="320" Margin="0
</StackPanel>
</TabItem>
</TabControl>
<GroupBox x:Name="gBoxSelectNodeTreeView" Grid.Column="0" Header="Nodes" Ho
<StackPanel Orientation="Vertical">
<TreeView x:Name="treeView1" Height="300" Width="340" Margin="0,5,0,0" Hori
DataContext="{Binding Source={StaticResource DomainOUData}, XPath=/DomainRoot}"
ItemTemplate="{StaticResource NodeTemplate}"
ItemsSource="{Binding}">
<TreeView.ContextMenu>
<ContextMenu x:Name="ContextMUpdateNode" >
<MenuItem Header="Refresh Childs">
<MenuItem.Icon>
<Image Width="15" Height="15" Source="{Binding XPath=@Icon}" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Exclude Node">
<MenuItem.Icon>
<Image Width="15" Height="15" Source="{Binding XPath=@Icon2}" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</TreeView.ContextMenu>
</TreeView>
</StackPanel>
</GroupBox>
<StackPanel Orientation="Horizontal" >
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Vertical" >
<StackPanel Orientation="Horizontal" >
<Label x:Name="lblStyleVersion1" Content="AD ACL Scanner 7.9" Horizontal
</StackPanel>
<StackPanel Orientation="Horizontal" >
<Label x:Name="lblStyleVersion2" Content="written by Robin Granberg " Hori
<Image x:Name="imgTwitter" HorizontalAlignment="Left" Height="15" Vertical
<Label x:Name="lblStyleVersion3" Content="@ipcdollar1" HorizontalAlignmen
<Image x:Name="imgGithub" HorizontalAlignment="Left" Height="15" VerticalA
<Label x:Name="lblStyleVersion4" Content="@canix1" HorizontalAlignment="
</StackPanel>
</StackPanel>
</StackPanel>
</StackPanel>
</StackPanel>
<StackPanel Orientation="Vertical">
<Label x:Name="lblSelectedNode" Content="Selected Object:" HorizontalAlignment="Le
<StackPanel Orientation="Horizontal" >
<TextBox x:Name="txtBoxSelected" HorizontalAlignment="Left" Height="20" Margin="
</StackPanel>
<Label x:Name="lblStatusBar" Content="Log:" HorizontalAlignment="Left" Height="26" M
<ListBox x:Name="TextBoxStatusMessage" DisplayMemberPath="Message" SelectionM
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Type}" Value="Error">
<Setter Property="ListBoxItem.Foreground" Value="Red" />
<Setter Property="ListBoxItem.Background" Value="LightGray" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=Type}" Value="Warning">
<Setter Property="ListBoxItem.Foreground" Value="Yellow" />
<Setter Property="ListBoxItem.Background" Value="Gray" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=Type}" Value="Info">
<Setter Property="ListBoxItem.Foreground" Value="Black" />
<Setter Property="ListBoxItem.Background" Value="White" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<TabControl x:Name="tabScanTop" HorizontalAlignment="Left" Height="405" VerticalA
<TabItem x:Name="tabScan" Header="Scan Options" Width="85">
<Grid >
<StackPanel Orientation="Vertical" Margin="0,0">
<StackPanel Orientation="Horizontal" Margin="0,0">
<StackPanel Orientation="Vertical" Margin="0,0">
<GroupBox x:Name="gBoxScanType" Header="Scan Type" HorizontalAl
<StackPanel Orientation="Vertical" Margin="0,0">
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbDACL" Content="DACL (Access)" Hor
<RadioButton x:Name="rdbSACL" Content="SACL (Audit)" Horizo
</StackPanel>
<StackPanel Orientation="Horizontal" Height="35" Margin="0,0,0.2,0
<CheckBox x:Name="chkBoxRAWSDDL" Content="RAW SDDL"
</StackPanel>
</StackPanel>
</GroupBox>
<GroupBox x:Name="gBoxScanDepth" Header="Scan Depth" Horizontal
<StackPanel Orientation="Vertical" Margin="0,0">
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbBase" Content="Base" HorizontalAlign
<RadioButton x:Name="rdbOneLevel" Content="One Level" Horiz
<RadioButton x:Name="rdbSubtree" Content="Subtree" Horizonta
</StackPanel>
</StackPanel>
</GroupBox>
<GroupBox x:Name="gBoxRdbFile" Header="Output Options" Horizontal
<StackPanel Orientation="Vertical" Margin="0,0">
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbOnlyHTA" Content="HTML" Horizonta
<RadioButton x:Name="rdbOnlyCSV" Content="CSV file" Horizon
<RadioButton x:Name="rdbOnlyCSVTEMPLATE" Content="CSV
</StackPanel>
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbEXcel" Content="Excel file" Horizonta
</StackPanel>
<CheckBox x:Name="chkBoxTranslateGUID" Content="Translate G
<Label x:Name="lblTempFolder" Content="CSV file destination" />
<TextBox x:Name="txtTempFolder" Margin="0,0,02,0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" >
<Button x:Name="btnGetTemplateFolder" Content="Change Fold
</StackPanel>
</StackPanel>
</GroupBox>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,0">
<GroupBox x:Name="gBoxRdbScan" Header="Objects to scan" Horizont
<StackPanel Orientation="Vertical" Margin="0,0">
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbScanOU" Content="OUs" HorizontalA
<RadioButton x:Name="rdbScanContainer" Content="Containers"
<RadioButton x:Name="rdbScanAll" Content="All Objects" Horizo
<RadioButton x:Name="rdbGPO" Content="GPOs" HorizontalAlig
</StackPanel>
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="rdbScanFilter" Content="" HorizontalAlign
<TextBox x:Name="txtCustomFilter" Text="(objectClass=*)" Horiz
</StackPanel>
</StackPanel>
</GroupBox>
<GroupBox x:Name="gBoxReportOpt" Header="View in report" Horizonta
<StackPanel Orientation="Vertical" Margin="0,0">
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="chkBoxGetOwner" Content="View Owner" H
<CheckBox x:Name="chkBoxACLSize" Content="DACL Size" Ho
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,0,0.2,0" Height="35
<CheckBox x:Name="chkInheritedPerm" Content="Inherited

<CheckBox x:Name="chkBoxGetOUProtected" Content="Inherita
</StackPanel>
<StackPanel Orientation="Horizontal" Height="35" Margin="0,0,0.2,0
<CheckBox x:Name="chkBoxDefaultPerm" Content="Skip Defaul
<CheckBox x:Name="chkBoxReplMeta" Content="SD Modified da
</StackPanel>
<StackPanel Orientation="Horizontal" Height="35" Margin="0,0,0.2,0
<CheckBox x:Name="chkBoxSkipProtectedPerm" Content="Skip
<CheckBox x:Name="chkBoxObjType" Content="ObjectClass" Ho
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,0,0,0">
<StackPanel Orientation="Horizontal" Height="19" Margin="0,0,0.
<CheckBox x:Name="chkBoxUseCanonicalName" Content="C
<CheckBox x:Name="chkBoxSDDLView" Content="SDDL" Hor
</StackPanel>
<Label x:Name="lblReturnObjectType" Content="Filter report on s
<ComboBox x:Name="combReturnObjectType" HorizontalAlignm
</StackPanel>
</StackPanel>
</GroupBox>
</StackPanel>
</StackPanel>
<GroupBox x:Name="gBoxExclude" Header="Excluded Path (matching string
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtBoxExcluded" HorizontalAlignment="Left" Heigh
<Button x:Name="btnClearExcludedBox" Content="Clear" Height="21
</StackPanel>
</StackPanel>
</GroupBox>
</StackPanel>
</Grid>
</TabItem>
<TabItem x:Name="tabFilter" Header="Filter">
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" Margin="0,0">
<CheckBox x:Name="chkBoxFilter" Content="Enable Filter" HorizontalAlign
<Label x:Name="lblAccessCtrl" Content="Filter by Access Type:(example: A
<StackPanel Orientation="Horizontal" Margin="0,0">
<CheckBox x:Name="chkBoxType" Content="" HorizontalAlignment="Lef
<ComboBox x:Name="combAccessCtrl" HorizontalAlignment="Left" Marg
</StackPanel>
<Label x:Name="lblFilterExpl" Content="Filter by Object: Examples:&#
<StackPanel Orientation="Horizontal" Margin="0,0">
<CheckBox x:Name="chkBoxObject" Content="" HorizontalAlignment="L
<TextBox x:Name="txtBoxObjectFilter" HorizontalAlignment="Left" Margi
</StackPanel>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="5,5,0,0" Width="320">
<Label x:Name="lblPermission" Content="Filter by permissions: Exam
<StackPanel Orientation="Horizontal" Margin="0,0">
<CheckBox x:Name="chkBoxPermission" Content="" HorizontalAlignmen
<TextBox x:Name="txtPermission" HorizontalAlignment="Left" Margin="5
</StackPanel>
<Label x:Name="lblFilterTrusteeExpl" Content="Filter by Trustee: Exam
<StackPanel Orientation="Horizontal" Margin="0,0">
<CheckBox x:Name="chkBoxTrustee" Content="" HorizontalAlignment="L
<TextBox x:Name="txtFilterTrustee" HorizontalAlignment="Left" Margin="
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,0">
<CheckBox x:Name="chkBoxFilterBuiltin" Content="" HorizontalAlignmen
<Label x:Name="lblFilterBuiltin" Content="Exclude all built-in security prin
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
</TabItem>
<TabItem x:Name="tabAssess" Header="Assessment">
<Grid >
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" Margin="0,0">
<GroupBox x:Name="gBoxdCriticals" Header="Assessment Options" Horizo
<StackPanel>
<Label x:Name="lblFilterServerity" Content="Filter by Severity" />
<StackPanel Orientation="Horizontal" Margin="0,0">
<CheckBox x:Name="chkBoxSeverity" Content="" HorizontalAlignm
<ComboBox x:Name="combServerity" HorizontalAlignment="Left" M
</StackPanel>
<Label x:Name="lblRecursiveFind" Content="Perform a recursive searc
<StackPanel Orientation="Horizontal" Margin="0,0">
<CheckBox x:Name="chkBoxRecursiveFind" Content="" HorizontalA
<ComboBox x:Name="combRecursiveFind" HorizontalAlignment="L
</StackPanel>
</StackPanel>
</GroupBox>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="5,5">
<GroupBox x:Name="gBoxCriticality" Header="Access Rights Criticality" Ho
<StackPanel Orientation="Vertical" Margin="0,0">
<CheckBox x:Name="chkBoxEffectiveRightsColor" Content="Show co
<Label x:Name="lblEffectiveRightsColor" Content="Use colors in repor
<Button x:Name="btnViewLegend" Content="View Color Legend" Hori
</StackPanel>
</GroupBox>
</StackPanel>
</StackPanel>
</Grid>
</TabItem>
<TabItem x:Name="tabEffectiveR" Header="Effective Rights">
<Grid >
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" Margin="0,0">
<CheckBox x:Name="chkBoxEffectiveRights" Content="Enable Effective Ri
<Label x:Name="lblEffectiveDescText" Content="Effective Access allows yo
<Label x:Name="lblEffectiveText" Content="Type the account name (samAc
<Label x:Name="lblSelectPrincipalDom" Content=":" />
<TextBox x:Name="txtBoxSelectPrincipal" IsEnabled="False" />
<StackPanel Orientation="Horizontal" Margin="0,0">
<Button x:Name="btnGetSPAccount" Content="Get Account" Margin="5,
<Button x:Name="btnListLocations" Content="Locations..." Margin="50,0
</StackPanel>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="5,5,0,0" Width="320">
<StackPanel Orientation="Vertical" Margin="0,0" >
<GroupBox x:Name="gBoxEffectiveSelUser" Header="Selected Security
<StackPanel Orientation="Vertical" Margin="0,0">
<Label x:Name="lblEffectiveSelUser" Content="" />
</StackPanel>
</GroupBox>
<Button x:Name="btnGETSPNReport" HorizontalAlignment="Left" Conte
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
</TabItem>
<TabItem x:Name="tabCompare" Header="Compare">
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" Margin="0,0" HorizontalAlignment="Left">
<CheckBox x:Name="chkBoxCompare" Content="Enable Compare" Horizo
<Label x:Name="lblCompareDescText" Content="You can compare the cur
<Label x:Name="lblCompareTemplate" Content="CSV Template File" />
<TextBox x:Name="txtCompareTemplate" Margin="2,0,0,0" Width="275" IsE
<Button x:Name="btnGetCompareInput" Content="Select Template" Horizo
<StackPanel Orientation="Horizontal" Margin="5,5,0,0">
<Label x:Name="lblReturn" Content="Return:" />
<ComboBox x:Name="combReturns" HorizontalAlignment="Left" Margin=
</StackPanel>
<StackPanel Orientation="Vertical">
<CheckBox x:Name="chkBoxTemplateNodes" Content="Use nodes from
<CheckBox x:Name="chkBoxScanUsingUSN" Content="Faster compare
</StackPanel>
</StackPanel>
<StackPanel Orientation="Vertical" Width="300">
<Label x:Name="lblReplaceDN" Content="Replace DN in file with current do
<TextBox x:Name="txtReplaceDN" Margin="2,0,0,0" Width="250" IsEnabled
<Label x:Name="lblReplaceNetbios" Content="Replace principals prefixed d
<TextBox x:Name="txtReplaceNetbios" Margin="2,0,0,0" Width="250" IsEna
<Label x:Name="lblDownloadCSVDefACLs" Content="Download CSV temp
<Button x:Name="btnDownloadCSVDefACLs" Content="Download CSV Te
</StackPanel>
</StackPanel>
</Grid>
</TabItem>
<TabItem x:Name="tabOther" Header="Default SD">
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" Margin="0,0,0,-40">
<GroupBox x:Name="gBoxdDefSecDesc" Header="Output Format" Horizon
<StackPanel Orientation="Horizontal" Margin="0,0">
<RadioButton x:Name="rdbDefSD_Access" Content="DACL" Horizont
<RadioButton x:Name="rdbDefSD_SDDL" Content="SDDL" Horizonta
</StackPanel>
</GroupBox>
<CheckBox x:Name="chkModifedDefSD" Content="Only modified defaultSe
<Label x:Name="lblObjectDefSD" Content="Select objects to scan:" />
<StackPanel Orientation="Horizontal" Margin="0,0">
<ComboBox x:Name="combObjectDefSD" HorizontalAlignment="Left" M
<Button x:Name="btnScanDefSD" Content="Run Scan" HorizontalAlignm
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,0">
<Button x:Name="btnGetSchemaClass" Content="Load all classSchema
<Button x:Name="btnExportDefSD" Content="Export to CSV" HorizontalA
</StackPanel>
</StackPanel>
<GroupBox x:Name="gBoxdDefSecDescCompare" Header="Compare" Horizo
<StackPanel Margin="0,0">
<Label x:Name="lblCompareDefSDText" Content="You can compare the
<Label x:Name="lblCompareDefSDTemplate" Content="CSV Template F
<TextBox x:Name="txtCompareDefSDTemplate" Margin="2,0,0,0" Width=
<Button x:Name="btnGetCompareDefSDInput" Content="Select Templat
<Button x:Name="btnCompDefSD" Content="Run Compare" HorizontalA
<Label x:Name="lblDownloadCSVDefSD" Content="Download CSV temp
<Button x:Name="btnDownloadCSVDefSD" Content="Download CSV Te
</StackPanel>
</GroupBox>
</StackPanel>
</Grid>
</TabItem>
<TabItem x:Name="tabOfflineScan" Header="Additional Options">
<Grid>
<StackPanel>
<GroupBox x:Name="gBoxImportCSV" Header="CSV to HTML" HorizontalAlig
<StackPanel Orientation="Vertical" Margin="0,0">
<Label x:Name="lblCSVImport" Content="This file will be converted HTM
<TextBox x:Name="txtCSVImport"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="btnGetCSVFile" Content="Select CSV" />
</StackPanel>
<CheckBox x:Name="chkBoxTranslateGUIDinCSV" Content="CSV file d
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="btnCreateHTML" Content="Create HTML View" />
</StackPanel>
</StackPanel>
</GroupBox>
<GroupBox x:Name="gBoxProgress" Header="Progress Bar" HorizontalAlignm
<StackPanel Orientation="Vertical" Margin="0,0">
<CheckBox x:Name="chkBoxSkipProgressBar" Content="Use Progress B
<Label x:Name="lblSkipProgressBar" Content="For increased speed, tur
</StackPanel>
</GroupBox>
</StackPanel>
</Grid>
</TabItem>
</TabControl>
<StackPanel Orientation="Horizontal" Margin="5,5">
<Button x:Name="btnScan" Content="Run Scan" HorizontalAlignment="Left" Height="
<Button x:Name="btnExit" Content="Exit" HorizontalAlignment="Left" Margin="100,0,0
<Button x:Name="btnSupport" Height="23" Tag="Support Statement" Margin="270,0,
<TextBlock TextDecorations="Underline" Text="{Binding Path=Tag, RelativeSource
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<ContentPresenter />
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
</StackPanel>
</StackPanel>
<StackPanel >
</StackPanel>
</StackPanel>
</Grid>
</ScrollViewer>
</Window>
"@
[XML] $XAML = $xamlBase
$xaml.Window.RemoveAttribute("x:Class")
#for paged search, the response for paged search result control - we will need a cookie from res
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using range
$colResults = $response.Entries
■ foreach ($objResult in $colResults)
■ {
■■ [void]$arrSchemaObjects.Add($objResult.attributes.name[0])
}
if($global:PageSize -gt 0) {
if ($prrc.Cookie.Length -eq 0) {
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
} else {
#exit the processing for non-paged search
break;
}
}#End While
$arrSchemaObjects.Sort()
foreach ($object in $arrSchemaObjects)
{
[void]$combObjectDefSD.Items.Add($object)
}
$global:observableCollection.Insert(0,(LogMessage -strMessage "All classSchema collected!" -strT
$object = $null
Remove-Variable object
$arrSchemaObjects = $null
Remove-Variable arrSchemaObjects
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Connect to your naming context
}
})
$btnExportDefSD.add_Click(
{
$global:bolProgressBar = $chkBoxSkipProgressBar.IsChecked
if ($global:bolConnected -eq $true)
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Scanning..." -strType "Info" -Dat
$strFileCSV = $txtTempFolder.Text + "\" +$global:strDomainShortName + "_DefaultSecDescriptor
Write-DefaultSDCSV -fileout $strFileCSV -CREDS $CREDS
$global:observableCollection.Insert(0,(LogMessage -strMessage "Finished" -strType "Info" -DateS
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Connect to your naming context
}
})
$btnCompDefSD.add_Click(
{
$global:bolProgressBar = $chkBoxSkipProgressBar.IsChecked
if ($global:bolConnected -eq $true)
{
})
$btnGETSPNReport.add_Click(
{
If(($global:strEffectiveRightSP -ne "") -and ($global:tokens.count -gt 0))
{
DisplayLegend
})
$btnGetSPAccount.add_Click(
{
if ($global:bolConnected -eq $true)
{
If (!($txtBoxSelectPrincipal.Text -eq ""))
{
GetEffectiveRightSP $txtBoxSelectPrincipal.Text $global:strDomainPrinDNName -CREDS $CR
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Enter a principal name!" -strT
}
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Connect to your naming context
}
})
$btnListDdomain.add_Click(
{
GenerateDomainPicker
$txtBoxDomainConnect.Text = $global:strDomainSelect
})
$btnListLocations.add_Click(
{
if ($global:bolConnected -eq $true)
{
GenerateTrustedDomainPicker -CREDS $CREDS
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Connect to your naming context
}
})
$chkBoxScanUsingUSN.add_Click(
{
If($chkBoxScanUsingUSN.IsChecked)
{
$global:bolTempValue_chkBoxReplMeta = $chkBoxReplMeta.IsChecked
$chkBoxReplMeta.IsChecked = $true
}
else
{
if ($null -ne $global:bolTempValue_chkBoxReplMeta)
{
$chkBoxReplMeta.IsChecked = $global:bolTempValue_chkBoxReplMeta
}
}
})
$chkBoxCompare.add_Click(
{
If($chkBoxCompare.IsChecked)
{
if ($null -ne $global:bolTempValue_InhertiedChkBox)
{
$chkInheritedPerm.IsChecked = $global:bolTempValue_InhertiedChkBox
}
}
else
{
#Deactivate Compare Objects
$txtCompareTemplate.IsEnabled = $false
$combReturns.IsEnabled = $false
$chkBoxTemplateNodes.IsEnabled = $false
$chkBoxScanUsingUSN.IsEnabled = $false
$btnGetCompareInput.IsEnabled = $false
$txtReplaceDN.IsEnabled = $false
$txtReplaceNetbios.IsEnabled = $false
}
})
$chkBoxEffectiveRights.add_Click(
{
If($chkBoxEffectiveRights.IsChecked)
{
$global:bolTempValue_InhertiedChkBox = $chkInheritedPerm.IsChecked
$global:bolTempValue_chkBoxGetOwner = $chkBoxGetOwner.IsChecked
$chkBoxFilter.IsChecked = $false
#Deactivate Compare Objects
$chkBoxCompare.IsChecked = $false
$txtCompareTemplate.IsEnabled = $false
$combReturns.IsEnabled = $false
$chkBoxTemplateNodes.IsEnabled = $false
$chkBoxScanUsingUSN.IsEnabled = $false
$btnGetCompareInput.IsEnabled = $false
$txtReplaceDN.IsEnabled = $false
$txtReplaceNetbios.IsEnabled = $false
$txtBoxSelectPrincipal.IsEnabled = $true
$btnGetSPAccount.IsEnabled = $true
$btnListLocations.IsEnabled = $true
$btnGETSPNReport.IsEnabled = $true
$chkInheritedPerm.IsEnabled = $false
$chkInheritedPerm.IsChecked = $true
$chkBoxGetOwner.IsEnabled = $false
$chkBoxGetOwner.IsChecked= $true
$chkBoxType.IsEnabled = $false
$chkBoxObject.IsEnabled = $false
$chkBoxTrustee.IsEnabled = $false
$chkBoxPermission.IsEnabled = $false
$chkBoxPermission.IsChecked = $false
$txtPermission.IsEnabled = $false
$chkBoxType.IsChecked = $false
$chkBoxObject.IsChecked = $false
$chkBoxFilterBuiltin.IsChecked = $false
$txtBoxObjectFilter.IsEnabled = $false
$txtFilterTrustee.IsEnabled = $false
$combAccessCtrl.IsEnabled = $false
}
else
{
$txtBoxSelectPrincipal.IsEnabled = $false
$btnGetSPAccount.IsEnabled = $false
$btnListLocations.IsEnabled = $false
$btnGETSPNReport.IsEnabled = $false
$chkInheritedPerm.IsEnabled = $true
$chkInheritedPerm.IsChecked = $global:bolTempValue_InhertiedChkBox
$chkBoxGetOwner.IsEnabled = $true
$chkBoxGetOwner.IsChecked = $global:bolTempValue_chkBoxGetOwner
}
})
$chkBoxSeverity.add_Click(
{
If($chkBoxSeverity.IsChecked -eq $true)
{
$combServerity.IsEnabled = $true
}
else
{
$combServerity.IsEnabled = $false
}
})
$chkBoxRecursiveFind.add_Click(
{
If($chkBoxRecursiveFind.IsChecked -eq $true)
{
$combRecursiveFind.IsEnabled = $true
}
else
{
$combRecursiveFind.IsEnabled = $false
}
})
$chkBoxFilter.add_Click(
{
If($chkBoxFilter.IsChecked -eq $true)
{
#Deactivate Compare Objects
$chkBoxCompare.IsChecked = $false
$txtCompareTemplate.IsEnabled = $false
$combReturns.IsEnabled = $false
$chkBoxTemplateNodes.IsEnabled = $false
$chkBoxScanUsingUSN.IsEnabled = $false
$btnGetCompareInput.IsEnabled = $false
$txtReplaceDN.IsEnabled = $false
$txtReplaceNetbios.IsEnabled = $false
$chkBoxEffectiveRights.IsChecked = $false
$chkBoxType.IsEnabled = $true
$chkBoxObject.IsEnabled = $true
$chkBoxTrustee.IsEnabled = $true
$chkBoxPermission.IsEnabled = $true
$txtPermission.IsEnabled = $true
$chkBoxFilterBuiltin.IsEnabled = $true
$txtBoxObjectFilter.IsEnabled = $true
$txtFilterTrustee.IsEnabled = $true
$combAccessCtrl.IsEnabled = $true
$txtBoxSelectPrincipal.IsEnabled = $false
$btnGetSPAccount.IsEnabled = $false
$btnListLocations.IsEnabled = $false
$btnGETSPNReport.IsEnabled = $false
$chkInheritedPerm.IsEnabled = $true
$chkInheritedPerm.IsChecked = $global:bolTempValue_InhertiedChkBox
$chkBoxGetOwner.IsEnabled = $true
if ($null -ne $global:bolTempValue_chkBoxGetOwner)
{
$chkBoxGetOwner.IsChecked = $global:bolTempValue_chkBoxGetOwner
}
}
else
{
$chkBoxType.IsEnabled = $false
$chkBoxObject.IsEnabled = $false
$chkBoxTrustee.IsEnabled = $false
$chkBoxPermission.IsEnabled = $false
$chkBoxPermission.IsChecked = $false
$txtPermission.IsEnabled = $false
$chkBoxFilterBuiltin.IsEnabled = $false
$chkBoxType.IsChecked = $false
$chkBoxObject.IsChecked = $false
$txtBoxObjectFilter.IsEnabled = $false
$txtFilterTrustee.IsEnabled = $false
$combAccessCtrl.IsEnabled = $false
}
})
$rdbDSSchm.add_Click(
{
If($rdbCustomNC.IsChecked -eq $true)
{
$txtBoxDomainConnect.IsEnabled = $true
$btnListDdomain.IsEnabled = $false
if (($txtBoxDomainConnect.Text -eq "rootDSE") -or ($txtBoxDomainConnect.Text -eq "config") -or
{
$txtBoxDomainConnect.Text = ""
}
}
else
{
$btnListDdomain.IsEnabled = $false
If($rdbDSdef.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = $global:strDomainSelect
$btnListDdomain.IsEnabled = $true
$txtBdoxDSServerPort.IsEnabled = $false
$txtBdoxDSServer.IsEnabled = $false
}
If($rdbDSConf.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "config"
$txtBdoxDSServerPort.IsEnabled = $false
$txtBdoxDSServer.IsEnabled = $false
}
If($rdbDSSchm.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "schema"
$txtBdoxDSServerPort.IsEnabled = $false
$txtBdoxDSServer.IsEnabled = $false
}
$txtBoxDomainConnect.IsEnabled = $false
}
})
$rdbDSConf.add_Click(
{
If($rdbCustomNC.IsChecked -eq $true)
{
$txtBoxDomainConnect.IsEnabled = $true
$btnListDdomain.IsEnabled = $false
if (($txtBoxDomainConnect.Text -eq "rootDSE") -or ($txtBoxDomainConnect.Text -eq "config") -or
{
$txtBoxDomainConnect.Text = ""
}
}
else
{
$btnListDdomain.IsEnabled = $false
If($rdbDSdef.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = $global:strDommainSelect
$btnListDdomain.IsEnabled = $true
$txtBdoxDSServerPort.IsEnabled = $false
$txtBdoxDSServer.IsEnabled = $false
}
If($rdbDSConf.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "config"
$txtBdoxDSServerPort.IsEnabled = $false
$txtBdoxDSServer.IsEnabled = $false
}
If($rdbDSSchm.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "schema"
$txtBdoxDSServerPort.IsEnabled = $false
$txtBdoxDSServer.IsEnabled = $false
}
$txtBoxDomainConnect.IsEnabled = $false
}
})
$rdbDSdef.add_Click(
{
If($rdbCustomNC.IsChecked -eq $true)
{
$txtBoxDomainConnect.IsEnabled = $true
$btnListDdomain.IsEnabled = $false
if (($txtBoxDomainConnect.Text -eq "rootDSE") -or ($txtBoxDomainConnect.Text -eq "config") -or
{
$txtBoxDomainConnect.Text = ""
}
}
else
{
$btnListDdomain.IsEnabled = $false
If($rdbDSdef.IsChecked -eq $true)
{
$txtBdoxDSServerPort.IsEnabled = $false
$txtBdoxDSServer.IsEnabled = $false
$txtBoxDomainConnect.Text = $global:strDomainSelect
$btnListDdomain.IsEnabled = $true
}
If($rdbDSConf.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "config"
}
If($rdbDSSchm.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "schema"
}
$txtBoxDomainConnect.IsEnabled = $false
}
})
$rdbCustomNC.add_Click(
{
If($rdbCustomNC.IsChecked -eq $true)
{
$txtBdoxDSServerPort.IsEnabled = $true
$txtBdoxDSServer.IsEnabled = $true
$txtBoxDomainConnect.IsEnabled = $true
$btnListDdomain.IsEnabled = $false
if (($txtBoxDomainConnect.Text -eq "rootDSE") -or ($txtBoxDomainConnect.Text -eq "config") -or
{
$txtBoxDomainConnect.Text = ""
}
}
else
{
$btnListDdomain.IsEnabled = $false
If($rdbDSdef.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = $global:strDommainSelect
$btnListDdomain.IsEnabled = $true
}
If($rdbDSConf.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "config"
}
If($rdbDSSchm.IsChecked -eq $true)
{
$txtBoxDomainConnect.Text = "schema"
}
$txtBoxDomainConnect.IsEnabled = $false
}
})
$btnGetTemplateFolder.add_Click(
{
$strFolderPath = Select-Folder
$txtTempFolder.Text = $strFolderPath
})
$btnGetCompareDefSDInput.add_Click(
{
$strFilePath = Select-File
$txtCompareDefSDTemplate.Text = $strFilePath
})
$btnGetCompareInput.add_Click(
{
$strFilePath = Select-File
$txtCompareTemplate.Text = $strFilePath
})
$btnGetCSVFile.add_Click(
{
$strFilePath = Select-File
$txtCSVImport.Text = $strFilePath
})
$btnDSConnect.add_Click(
{
if($chkBoxCreds.IsChecked)
{
$script:CREDS = Get-Credential -Message "Type User Name and Password"
$Window.Activate()
}
$global:bolRoot = $true
$NCSelect = $false
$global:DSType = ""
$global:strDC = ""
$global:strDomainDNName = ""
$global:ConfigDN = ""
$global:SchemaDN = ""
$global:ForestRootDomainDN = ""
$global:IS_GC = ""
$txtDC.text = ""
$txtdefaultnamingcontext.text = ""
$txtconfigurationnamingcontext.text = ""
$txtschemanamingcontext.text = ""
$txtrootdomainnamingcontext.text = ""
■If ($rdbDSdef.IsChecked)
■{
if (!($txtBoxDomainConnect.Text -eq "rootDSE"))
{
if ($null -eq $global:TempDC)
{
$strNamingContextDN = $txtBoxDomainConnect.Text
If(CheckDNExist -sADobjectName $strNamingContextDN -strDC "" -CREDS $CREDS)
{
$root = New-Object system.directoryservices.directoryEntry("LDAP://"+$strNamingContextDN
$global:strDomainDNName = $root.distinguishedName.tostring()
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainLongName = $global:strDomainDNName.Replace("DC=","")
$global:strDomainLongName = $global:strDomainLongName.Replace(",",".")
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$global
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$global:strDC = $($ojbDomain.FindDomainController()).name
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($glob
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectCla
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainDN = $response.Entries[0].attributes.rootdomainnamingcontext[
$global:SchemaDN = $response.Entries[0].attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].attributes.configurationnamingcontext[0]
$global:strDomainDNName = $response.Entries[0].attributes.defaultnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
}
$global:DirContext = Get-DirContext $global:strDC -CREDS $CREDS
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDNNam
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestRootD
$global:DSType = "AD DS"
$global:bolADDSType = $true
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
$NCSelect = $true
$strNamingContextDN = $global:strDomainDNName
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
$global:bolConnected = $false
}
}
else
{
$strNamingContextDN = $txtBoxDomainConnect.Text
If(CheckDNExist -sADobjectName $strNamingContextDN -strDC "$global:TempDC" -CREDS
{
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$global
$global:TempDC = $null
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$global:strDC = $($ojbDomain.FindDomainController()).name
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($glob
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectCla
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainDN = $response.Entries[0].attributes.rootdomainnamingcontext[
$global:SchemaDN = $response.Entries[0].attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].attributes.configurationnamingcontext[0]
$global:strDomainDNName = $response.Entries[0].attributes.defaultnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
}
$global:DirContext = Get-DirContext $global:strDC $CREDS
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDNNam
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestRootD
$global:DSType = "AD DS"
$global:bolADDSType = $true
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
$NCSelect = $true
$strNamingContextDN = $global:strDomainDNName
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
$global:bolConnected = $false
}
}
}
else
{
if ($global:bolRoot -eq $true)
{
$LDAPConnection = $null
$request = $null
$response = $null
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection("")
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectCla
[void]$request.Attributes.Add("defaultnamingcontext")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext[0]
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
■ }
if($global:bolLDAPConnection)
{
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainLongName = $global:strDomainDNName.Replace("DC=","")
$global:strDomainLongName = $global:strDomainLongName.Replace(",",".")
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$glob
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$global:strDC = $($ojbDomain.FindDomainController()).name
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($g
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectC
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does n
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainDN = $response.Entries[0].attributes.rootdomainnamingconte
$global:SchemaDN = $response.Entries[0].attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].attributes.configurationnamingcontext[0]
$global:strDomainDNName = $response.Entries[0].attributes.defaultnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
}
$global:DirContext = Get-DirContext $global:strDC $CREDS
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDNN
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestRoo
$global:DSType = "AD DS"
$global:bolADDSType = $true
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
$NCSelect = $true
$strNamingContextDN = $global:strDomainDNName
}
}
}
■}
#Connect to Config Naming Context
■If ($rdbDSConf.IsChecked)
■{
if ($global:bolRoot -eq $true)
{
if($global:strDomainSelect.Contains("."))
{
$global:TempDC = $global:strDomainSelect
$strSelectedDomain = "DC=" + $global:strDomainSelect.Replace(".",",DC=")
}
if ($null -eq $global:TempDC)
{
$LDAPConnection = $null
$request = $null
$response = $null
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection("")
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectCla
[void]$request.Attributes.Add("defaultnamingcontext")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:strDomainDNName = $response.Entries[0].attributes.defaultnamingcontext[0]
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
}
if($global:bolLDAPConnection)
{
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainLongName = $global:strDomainDNName.Replace("DC=","")
$global:strDomainLongName = $global:strDomainLongName.Replace(",",".")
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$glob
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$global:strDC = $($ojbDomain.FindDomainController()).name
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($g
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectC
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does n
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainDN = $response.Entries[0].attributes.rootdomainnamingconte
$global:SchemaDN = $response.Entries[0].attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].attributes.configurationnamingcontext[0]
$global:strDomainDNName = $response.Entries[0].attributes.defaultnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
}
$global:DirContext = Get-DirContext $global:strDC -CREDS $CREDS
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDNN
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestRoo
$global:DSType = "AD DS"
$global:bolADDSType = $true
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
$NCSelect = $true
$strNamingContextDN = $global:ConfigDN
}
}
else
{
$strNamingContextDN = $global:strDomainSelect
If(CheckDNExist -sADobjectName $strNamingContextDN -strDC $global:TempDC -CREDS $
{
$root = New-Object system.directoryservices.directoryEntry("LDAP://"+$strNamingContextDN
$global:strDomainDNName = $root.distinguishedName.tostring()
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainLongName = $global:strDomainDNName.Replace("DC=","")
$global:strDomainLongName = $global:strDomainLongName.Replace(",",".")
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$global
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$global:strDC = $($ojbDomain.FindDomainController()).name
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($glob
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectCla
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainDN = $response.Entries[0].attributes.rootdomainnamingcontext[
$global:SchemaDN = $response.Entries[0].attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].attributes.configurationnamingcontext[0]
$global:strDomainDNName = $response.Entries[0].attributes.defaultnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
}
$global:DirContext = Get-DirContext $global:strDC -CREDS $CREDS
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDNNam
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestRootD
$global:DSType = "AD DS"
$global:bolADDSType = $true
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
$NCSelect = $true
$strNamingContextDN = $global:ConfigDN
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
$global:bolConnected = $false
}
}
}
■}
#Connect to Schema Naming Context
■If ($rdbDSSchm.IsChecked)
■{
if ($global:bolRoot -eq $true)
{
$LDAPConnection = $null
$request = $null
$response = $null
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection("")
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectClass
[void]$request.Attributes.Add("defaultnamingcontext")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext[0]
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not ex
}
if($global:bolLDAPConnection)
{
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainLongName = $global:strDomainDNName.Replace("DC=","")
$global:strDomainLongName = $global:strDomainLongName.Replace(",",".")
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$global
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$global:strDC = $($ojbDomain.FindDomainController()).name
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($glob
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($null, "(objectCla
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainDN = $response.Entries[0].attributes.rootdomainnamingcontext[
$global:SchemaDN = $response.Entries[0].attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].attributes.configurationnamingcontext[0]
$global:strDomainDNName = $response.Entries[0].attributes.defaultnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
}
$global:DirContext = Get-DirContext $global:strDC $CREDS
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDNNam
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestRootD
$global:DSType = "AD DS"
$global:bolADDSType = $true
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
$NCSelect = $true
$strNamingContextDN = $global:SchemaDN
}
}
■}
#Connect to Custom Naming Context■
If ($rdbCustomNC.IsChecked)
■{
if (($txtBoxDomainConnect.Text.Length -gt 0) -or ($txtBdoxDSServer.Text.Length -gt 0) -or ($txtBd
{
$strNamingContextDN = $txtBoxDomainConnect.Text
if($txtBdoxDSServer.Text -eq "")
{
if($txtBdoxDSServerPort.Text -eq "")
{
$global:strDC = ""
}
else
{
$global:strDC = "localhost:" +$txtBdoxDSServerPort.text
}
}
else
{
$global:strDC = $txtBdoxDSServer.Text +":" +$txtBdoxDSServerPort.text
if($txtBdoxDSServerPort.Text -eq "")
{
$global:strDC = $txtBdoxDSServer.Text
}
else
{
$global:strDC = $txtBdoxDSServer.Text +":" +$txtBdoxDSServerPort.text
}
}
$global:bolLDAPConnection = $false
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($g
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest("", "(objectCla
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.Directory
}
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
■ try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does n
■ }
if($global:bolLDAPConnection -eq $true)
{
$strPrimaryCapability= $response.Entries[0].attributes.supportedcapabilities[0]
Switch ($strPrimaryCapability)
{
"1.2.840.113556.1.4.1851"
{
$global:DSType = "AD LDS"
$global:bolADDSType = $false
$global:strDomainDNName = $response.Entries[0].Attributes.namingcontexts[-1]
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
if($txtBdoxDSServerPort.Text -eq "")
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
}
else
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" +$txtBdo
}
}
}
"1.2.840.113556.1.4.800"
{
$global:DSType = "AD DS"
$global:bolADDSType = $true
$global:ForestRootDomainDN = $response.Entries[0].Attributes.rootdomainnaming
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
if($txtBdoxDSServerPort.Text -eq "")
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
}
else
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" +$txtBdo
}
}
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDoma
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:Fo
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
}
default
{
$global:ForestRootDomainDN = $response.Entries[0].Attributes.rootdomainnaming
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
if($txtBdoxDSServerPort.Text -eq "")
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
else
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" +$txtBdoxD
}
}
}
if($strNamingContextDN -eq "")
{
$strNamingContextDN = $global:strDomainDNName
}
If(CheckDNExist -sADobjectName $strNamingContextDN -strDC $global:strDC -CREDS
{
$NCSelect = $true
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain doe
$global:bolConnected = $false
}
}#bolLDAPConnection
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! No naming context or
$global:bolConnected = $false
}
■}
If ($NCSelect -eq $true)
{
■ If (!($strLastCacheGuidsDom -eq $global:strDomainDNName))
■ {
■ $global:dicRightsGuids = @{"Seed" = "xxx"}
■ CacheRightsGuids -CREDS $CREDS
■ $strLastCacheGuidsDom = $global:strDomainDNName
■ }
#Check Directory Service type
$global:DSType = ""
$global:bolADDSType = $false
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:st
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest("", "(objectClass=*)", "
$response = $LDAPConnection.SendRequest($request)
$strPrimaryCapability= $response.Entries[0].attributes.supportedcapabilities[0]
Switch ($strPrimaryCapability)
{
"1.2.840.113556.1.4.1851"
{
$global:DSType = "AD LDS"
}
"1.2.840.113556.1.4.800"
{
$global:DSType = "AD DS"
$global:bolADDSType = $true
}
default
{
$global:DSType = "Unknown"
}
}
$global:observableCollection.Insert(0,(LogMessage -strMessage "Connected to directory service
#Plaing with AD LDS Locally
$global:TreeViewRootPath = $strNamingContextDN
$xml = Get-XMLDomainOUTree $global:TreeViewRootPath -CREDS $CREDS
# Change XML Document, XPath and Refresh
$xmlprov.Document = $xml
$xmlProv.XPath = "/DomainRoot"
$xmlProv.Refresh()
$global:bolConnected = $true
If (!(Test-Path ($env:temp + "\OU.png")))
{
$IconFilePath = $env:temp + "\OU.png"
$bytes = [Convert]::FromBase64String($OUpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\Expand.png")))
{
$IconFilePath = $env:temp + "\Expand.png"
$bytes = [Convert]::FromBase64String($Expandpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\User.png")))
{
$IconFilePath = $env:temp + "\User.png"
$bytes = [Convert]::FromBase64String($Userpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\Group.png")))
{
$IconFilePath = $env:temp + "\Group.png"
$bytes = [Convert]::FromBase64String($Grouppng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\Computer.png")))
{
$IconFilePath = $env:temp + "\Computer.png"
$bytes = [Convert]::FromBase64String($Computerpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\Container.png")))
{
$IconFilePath = $env:temp + "\Container.png"
$bytes = [Convert]::FromBase64String($Containerpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\DomainDNS.png")))
{
$IconFilePath = $env:temp + "\DomainDNS.png"
$bytes = [Convert]::FromBase64String($DomainDNSpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\Other.png")))
{
$IconFilePath = $env:temp + "\Other.png"
$bytes = [Convert]::FromBase64String($Otherpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\refresh.png")))
{
$IconFilePath = $env:temp + "\refresh.png"
$bytes = [Convert]::FromBase64String($refreshpng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
If (!(Test-Path ($env:temp + "\exclude.png")))
{
$IconFilePath = $env:temp + "\exclude.png"
$bytes = [Convert]::FromBase64String($excludepng)
[IO.File]::WriteAllBytes($IconFilePath, $bytes)
}
#Test PS Version DeleteCommand requries PS 3.0 and above
if ($PSVersionTable.PSVersion -gt "2.0")
{
try
■{
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■}
■catch
■{
■■$global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not exist or
■}
if($global:bolLDAPConnection -eq $true)
{
$global:DomainSID = GetSidStringFromSidByte $response.Entries[0].attributes.objectsid.GetValue
}
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not exist
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainSID = GetSidStringFromSidByte $response.Entries[0].attributes.obje
}
}
else
{
$global:strForestDC = $global:strDC
$global:ForestRootDomainSID = $global:DomainSID
}
}
})
$chkBoxCreds.add_UnChecked({
$script:CREDS = $null
})
$btnScan.add_Click(
{
$UseCanonicalName = $chkBoxUseCanonicalName.IsChecked
$Protected = $chkBoxGetOUProtected.IsChecked
If($chkBoxCompare.IsChecked)
{
RunCompare -CREDS $script:CREDS
}
else
{
RunScan -CREDS $script:CREDS
}
})
$btnCreateHTML.add_Click(
{
if ($txtCSVImport.Text -eq "")
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "No Template CSV file selected!" -s
}
else
{
#if ($global:bolConnected -eq $true)
#{
ConvertCSVtoHTM $txtCSVImport.Text $chkBoxTranslateGUIDinCSV.isChecked -CREDS $CRED
#}
#else
#{
#$global:observableCollection.Insert(0,(LogMessage -strMessage "You need to connect to a director
#}
}
})
$btnSupport.add_Click(
{
GenerateSupportStatement
})
$btnExit.add_Click(
{
#TODO: Place custom script here
#$ErrorActionPreference = "SilentlyContinue"
$bolConnected= $null
$bolTempValue_InhertiedChkBox= $null
$dicDCSpecialSids= $null
$dicNameToSchemaIDGUIDs= $null
$dicRightsGuids= $null
$dicSchemaIDGUIDs= $null
$dicSidToName= $null
$dicWellKnownSids= $null
$myPID= $null
$observableCollection= $null
$strDomainPrinDNName= $null
$strDomainSelect= $null
$strEffectiveRightAccount= $null
$strEffectiveRightSP= $null
$strPinDomDC= $null
$strPrincipalDN= $null
$strPrinDomAttr= $null
$strPrinDomDir= $null
$strPrinDomFlat= $null
$strSPNobjectClass= $null
$tokens= $null
$strDC = $null
$strDomainDNName = $null
$strDomainLongName = $null
$strDomainShortName = $null
$strOwner = $null
#$CREDS = $null
#remove-variable -name "CREDS"
remove-variable -name "bolConnected" -Scope Global
remove-variable -name "bolTempValue_InhertiedChkBox" -Scope Global
remove-variable -name "dicDCSpecialSids" -Scope Global
remove-variable -name "dicNameToSchemaIDGUIDs" -Scope Global
remove-variable -name "dicRightsGuids" -Scope Global
remove-variable -name "dicSchemaIDGUIDs" -Scope Global
remove-variable -name "dicSidToName" -Scope Global
remove-variable -name "dicWellKnownSids" -Scope Global
remove-variable -name "myPID" -Scope Global
remove-variable -name "observableCollection" -Scope Global
remove-variable -name "strDomainPrinDNName" -Scope Global
remove-variable -name "strDomainSelect" -Scope Global
remove-variable -name "strEffectiveRightAccount" -Scope Global
remove-variable -name "strEffectiveRightSP" -Scope Global
remove-variable -name "strPinDomDC" -Scope Global
remove-variable -name "strPrincipalDN" -Scope Global
remove-variable -name "strPrinDomAttr" -Scope Global
remove-variable -name "strPrinDomDir" -Scope Global
remove-variable -name "strPrinDomFlat" -Scope Global
remove-variable -name "strSPNobjectClass" -Scope Global
remove-variable -name "tokens" -Scope Global
$ErrorActionPreference = "SilentlyContinue"
&{#Try
$xmlDoc = $null
remove-variable -name "xmlDoc" -Scope Global
}
Trap [SystemException]
{
SilentlyContinue
}
$ErrorActionPreference = "Continue"
$Window.close()
})
$treeView1.add_SelectedItemChanged({
$txtBoxSelected.Text = (Get-XMLPath -xmlElement ($this.SelectedItem))
if ($this.SelectedItem.Tag -eq "NotEnumerated")
{
$xmlNode = $global:xmlDoc
$NodeDNPath = $($this.SelectedItem.ParentNode.Text.toString())
[void]$this.SelectedItem.ParentNode.removeChild($this.SelectedItem);
$Mynodes = $xmlNode.SelectNodes("//OU[@Text='$NodeDNPath']")
$treeNodePath = $NodeDNPath
}
else
{
#Set the bolean to true so connection will be performed unless an error occur
$bolContinue = $true
if($global:csvHistACLs[0].Object)
{
$strOUcol = $global:csvHistACLs[0].Object
}
else
{
$strOUcol = $global:csvHistACLs[0].OU
}
if($strOUcol.Contains("<DOMAIN-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<DOMAIN-DN>",$global:strDomainDNName)
}
if($strOUcol.Contains("<ROOT-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<ROOT-DN>",$global:ForestRootDomainDN)
if($global:strDomainDNName -ne $global:ForestRootDomainDN)
{
if($global:IS_GC -eq "TRUE")
{
$MsgBox = [System.Windows.Forms.MessageBox]::Show("You are not connecte
if($MsgBox -eq "Yes")
{
if($global:strDC.contains(":"))
{
$global:strDC = $global:strDC.split(":")[0] + ":3268"
}
else
{
$global:strDC = $global:strDC + ":3268"
}
}
else
{
$bolContinue = $false
}
}
else
{
$MsgBox = [System.Windows.Forms.MessageBox]::Show("You are not connecte
$bolContinue = $false
}
}
}
if($txtReplaceDN.text.Length -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace $txtReplaceDN.text,$global:strDomainDNName)
}
$sADobjectName = $strOUcol
#Verify if the connection can be done
if($bolContinue)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnectio
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.Dire
}
$request.DistinguishedName = $sADobjectName
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("name")
$response = $LDAPConnection.SendRequest($request)
$ADobject = $response.Entries[0]
$strNode = fixfilename $ADobject.attributes.name[0]
}
else
{
#Set the node to empty , no connection will be done
$strNode = ""
}
}
#if not is empty continue
if($strNode -ne "")
{
$bolTranslateGUIDStoObject = $false
$date= get-date -uformat %Y%m%d_%H%M%S
$strNode = fixfilename $strNode
■ $strFileCSV = $txtTempFolder.Text + "\" +$strNode + "_" + $global:strDomainShortName
$strFileEXCEL = $txtTempFolder.Text + "\" +$strNode + "_" + $global:strDomainShortNa
$strFileHTA = $env:temp + "\"+$global:ACLHTMLFileName+".hta"
$strFileHTM = $env:temp + "\"+"$global:strDomainShortName-$strNode-$global:Session
if(!($bolCSV))
{■■
if(!($rdbEXcel.IsChecked))
{■■ ■
if ($chkBoxFilter.IsChecked)
{
■■ CreateHTA "$global:strDomainShortName-$strNode Filtered" $strFileHTA $strFile
■■ CreateHTM "$global:strDomainShortName-$strNode Filtered" $strFileHTM■
}
else
{
CreateHTA "$global:strDomainShortName-$strNode" $strFileHTA $strFileHTM $
■■ CreateHTM "$global:strDomainShortName-$strNode" $strFileHTM■
}
■ InitiateHTM $strFileHTA $strNode $txtBoxSelected.Text.ToString() $chkBoxReplMe
■ InitiateHTM $strFileHTM $strNode $txtBoxSelected.Text.ToString() $chkBoxReplMe
$Format = "HTML"
$Show = $true
}
else
{
$Format = "EXCEL"
$Show = $false
}
}
else
{
if($rdbOnlyCSV.IsChecked)
{
$Format = "CSV"
}
if($rdbOnlyCSVTEMPLATE.IsChecked)
{
$Format = "CSVTEMPLATE"
}
$Show = $false
}
If (($txtBoxSelected.Text.ToString().Length -gt 0) -or (($chkBoxTemplateNodes.IsCheck
{
#Select type of scope
■■ If ($rdbBase.IsChecked -eq $False)
■■ {
If ($rdbSubtree.IsChecked -eq $true)
■■ {
■■■ if($rdbScanFilter.IsChecked -eq $true)
{
$allSubOU = GetAllChildNodes -firstnode $txtBoxSelected.Text -scope "subtre
}
else
{
$allSubOU = GetAllChildNodes -firstnode $txtBoxSelected.Text -scope "subtre
}
}
else
{
■■■ if($rdbScanFilter.IsChecked -eq $true)
{
$allSubOU = GetAllChildNodes -firstnode $txtBoxSelected.Text -scope "onele
}
else
{
$allSubOU = GetAllChildNodes -firstnode $txtBoxSelected.Text -scope "onelev
}
}■
}
■■ else
■■ {
■■■ $allSubOU = @($txtBoxSelected.Text)
■■ }
#if any objects found compare ACLs
if($allSubOU.count -gt 0)
{■■■
$TemplateFilter = $combReturns.SelectedItem
$bolToFile = $true
#Used from comand line only
$FilterBuiltin = $false
Get-PermCompare $allSubOU $BolSkipDefPerm $BolSkipProtectedPerm $chkBox
}■
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "No objects return
}
■■ $global:observableCollection.Insert(0,(LogMessage -strMessage "Finished" -strType "In
■ }# End If txtBoxSelected or chkBoxTemplateNodes
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Could not connect to $
}#End if not is empty
}#else if test column names exist
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "CSV file got wrong for
} #End if test column names exist
} # End If Verify that a successful CSV import is performed before continue
}#End If $chkBoxEffectiveRights.isChecked -or $chkBoxFilter.isChecked
}#End If Test-Path
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "CSV file not found!" -strType
}#End If Test-Path Else
}# End If
#Restore the DC string to its original
$global:strDC = $global:ResetDCvalue
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "No object selected!" -strType "E
}
$allSubOU = ""
$strFileCSV = ""
$strFileHTA = ""
$strFileHTM = ""
$sADobjectName = ""
$date= ""
}
function RunScan
{
param(
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
if($rdbGPO.isChecked)
{
$GPO = $true
}
if($chkBoxSeverity.isChecked -or $chkBoxEffectiveRightsColor.isChecked)
{
$bolShowCriticalityColor = $true
}
else
{
$bolShowCriticalityColor = $false
}
$bolPreChecks = $true
If ($txtBoxSelected.Text)
{
If(($chkBoxFilter.IsChecked -eq $true) -and (($chkBoxType.IsChecked -eq $false) -and ($chkBoxOb
{
$response = $LDAPConnection.SendRequest($request)
$ADobject = $response.Entries[0]
#Verify that attributes can be read
if($null -ne $ADobject.distinguishedName)
{
if($null -ne $ADobject.Attributes.name)
{
$strNode = $ADobject.Attributes.name[0]
}
else
{
$strNode = $ADobject.distinguishedName
}
■ if($GPO)
{
$strNode = $strNode + "_GPOs"
}
$bolTranslateGUIDStoObject = $false
$date= get-date -uformat %Y%m%d_%H%M%S
$strNode = fixfilename $strNode
■ $strFileCSV = $txtTempFolder.Text + "\" +$strNode + "_" + $global:strDomainShortName + "_ad
$strFileEXCEL = $txtTempFolder.Text + "\" +$strNode + "_" + $global:strDomainShortName + "
■ $strFileHTA = $env:temp + "\"+$global:ACLHTMLFileName+".hta"
■ $strFileHTM = $env:temp + "\"+"$global:strDomainShortName-$strNode-$global:SessionID"+".ht
if(!($bolCSV))
{■■
if(!($rdbEXcel.IsChecked))
{■■ ■
if ($chkBoxFilter.IsChecked)
{
■■ CreateHTA "$global:strDomainShortName-$strNode Filtered" $strFileHTA $strFileHTM $
■■ CreateHTM "$global:strDomainShortName-$strNode Filtered" $strFileHTM■
}
else
{
CreateHTA "$global:strDomainShortName-$strNode" $strFileHTA $strFileHTM $Current
■■ CreateHTM "$global:strDomainShortName-$strNode" $strFileHTM■
}
■ InitiateHTM $strFileHTA $strNode $txtBoxSelected.Text.ToString() $chkBoxReplMeta.IsChe
■ InitiateHTM $strFileHTM $strNode $txtBoxSelected.Text.ToString() $chkBoxReplMeta.IsCh
$Format = "HTML"
$Show = $true
}
else
{
$Format = "EXCEL"
$Show = $false
}
}
else
{
if($rdbOnlyCSV.IsChecked)
{
$Format = "CSV"
}
if($rdbOnlyCSVTEMPLATE.IsChecked)
{
$Format = "CSVTEMPLATE"
}
$Show = $false
} ■■
■ If ($txtBoxSelected.Text.ToString().Length -gt 0)
{
#Select type of scope
■■ If ($rdbBase.IsChecked -eq $true)
■■ {
$Scope = "base"
}
If ($rdbOneLevel.IsChecked -eq $true)
■■ {
■■■ $Scope = "onelevel"
}
If ($rdbSubtree.IsChecked -eq $true)
■■ {
■■■ $Scope = "subtree"
}
$IncludeInherited = $chkInheritedPerm.IsChecked
■$strFilterOUCont = "(&(|(objectClass=organizationalUnit)(objectClass=container)(objectClass=domain
■$strFilterAll = "(objectClass=*)"
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.DirectoryControl" -
}
$request.DistinguishedName = $ADSObject
# Single line Directory searcher
# set a filter
■If ($rdbBrowseAll.IsChecked -eq $true)
■{
■$request.Filter = $strFilterAll
■■
■}
■else
■{
■$request.Filter = $strFilterOUCont
■}
# set search scope
$request.Scope = "OneLevel"
[void]$request.Attributes.Add("name")
[void]$request.Attributes.Add("objectclass")
#for paged search, the response for paged search result control - we will need a cookie from res
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using range
$colResults = $response.Entries
■ foreach ($objResult in $colResults)
■ {
■■ $NewOUNode = $global:xmlDoc.createElement("OU");
if ($objResult.attributes.Count -ne 0)
{
# Add an Attribute for the Name
if (($null -ne $($objResult.attributes.name[0])))
■■ {
# Add an Attribute for the Name
$OUName = "$($objResult.attributes.name[0])"
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Name" -value $OUName
$DNName = $objResult.distinguishedname
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Text" -value $DNName
Switch ($objResult.attributes.objectclass[$objResult.attributes.objectclass.count-1])
{
"domainDNS"
{
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Img" -value "$env:temp\Doma
}
"OrganizationalUnit"
{
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Img" -value "$env:temp\OU.pn
}
"user"
{
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Img" -value "$env:temp\User.
}
"group"
{
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Img" -value "$env:temp\Group
}
"computer"
{
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Img" -value "$env:temp\Comp
}
"container"
{
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Img" -value "$env:temp\Conta
}
default
{
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Img" -value "$env:temp\Other.
}
}
AddXMLAttribute -node ([ref]$NewOUNode) -szName "Tag" -value "Enumerated"
$child = $node.appendChild($NewOUNode);
ProcessOUTreeStep2OnlyShow -node $NewOUNode -DNName $DNName -CREDS $C
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Could not read object
}
}
else
{
if ($null -ne $objResult.distinguishedname)
■■ {
# Add an Attribute for the Name
$DNName = $objResult.distinguishedname
$OUName = $DNName.toString().Split(",")[0]
if($OUName -match "=")
{
$OUName = $OUName.Split("=")[1]
}
#for paged search, the response for paged search result control - we will need a cookie from resul
if($global:PageSize -gt 0)
{
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged r
$colResults = $response.Entries
■ foreach ($objResult in $colResults)
■ {
if($intStop -eq 0)
{
$global:DirSrchResults = $objResult
if ($null -ne $global:DirSrchResults.attributes)
{
■■
# Add an Attribute for the Name
$NewOUNode = $global:xmlDoc.createElement("OU");
# Add an Attribute for the Name
}
else
{
$node = $global:xmlDoc.documentElement;
#Process the OU tree
ProcessOUTree -node $node -ADSObject $treeNodePath -CREDS $CREDS
return $global:xmlDoc
}
$global:dicRightsGuids = @{"Seed" = "xxx"}
$global:dicSidToName = @{"Seed" = "xxx"}
$global:dicSidToObject = @{"Seed" = "xxx"}
$global:dicDCSpecialSids =@{"BUILTIN\Incoming Forest Trust Builders"="S-1-5-32-557";`
"BUILTIN\Account Operators"="S-1-5-32-548";`
"BUILTIN\Server Operators"="S-1-5-32-549";`
"BUILTIN\Pre-Windows 2000 Compatible Access"="S-1-5-32-554";`
"BUILTIN\Terminal Server License Servers"="S-1-5-32-561";`
"BUILTIN\Windows Authorization Access Group"="S-1-5-32-560"}
$global:dicWellKnownSids = @{"S-1-0"="Null Authority";`
"S-1-0-0"="Nobody";`
"S-1-1"="World Authority";`
"S-1-1-0"="Everyone";`
"S-1-2"="Local Authority";`
"S-1-2-0"="Local ";`
"S-1-2-1"="Console Logon ";`
"S-1-3"="Creator Authority";`
"S-1-3-0"="Creator Owner";`
"S-1-3-1"="Creator Group";`
"S-1-3-2"="Creator Owner Server";`
"S-1-3-3"="Creator Group Server";`
"S-1-3-4"="Owner Rights";`
"S-1-4"="Non-unique Authority";`
"S-1-5"="NT Authority";`
"S-1-5-1"="Dialup";`
"S-1-5-2"="Network";`
"S-1-5-3"="Batch";`
"S-1-5-4"="Interactive";`
"S-1-5-6"="Service";`
"S-1-5-7"="Anonymous";`
"S-1-5-8"="Proxy";`
"S-1-5-9"="Enterprise Domain Controllers";`
"S-1-5-10"="Principal Self";`
"S-1-5-11"="Authenticated Users";`
"S-1-5-12"="Restricted Code";`
"S-1-5-13"="Terminal Server Users";`
"S-1-5-14"="Remote Interactive Logon";`
"S-1-5-15"="This Organization";`
"S-1-5-17"="IUSR";`
"S-1-5-18"="Local System";`
"S-1-5-19"="NT Authority";`
"S-1-5-20"="NT Authority";`
"S-1-5-22"="ENTERPRISE READ-ONLY DOMAIN CONTROLLERS BETA";`
"S-1-5-32-544"="Administrators";`
"S-1-5-32-545"="Users";`
"S-1-5-32-546"="Guests";`
"S-1-5-32-547"="Power Users";`
"S-1-5-32-548"="BUILTIN\Account Operators";`
"S-1-5-32-549"="Server Operators";`
"S-1-5-32-550"="Print Operators";`
"S-1-5-32-551"="Backup Operators";`
"S-1-5-32-552"="Replicator";`
"S-1-5-32-554"="BUILTIN\Pre-Windows 2000 Compatible Access";`
"S-1-5-32-555"="BUILTIN\Remote Desktop Users";`
"S-1-5-32-556"="BUILTIN\Network Configuration Operators";`
"S-1-5-32-557"="BUILTIN\Incoming Forest Trust Builders";`
"S-1-5-32-558"="BUILTIN\Performance Monitor Users";`
"S-1-5-32-559"="BUILTIN\Performance Log Users";`
"S-1-5-32-560"="BUILTIN\Windows Authorization Access Group";`
"S-1-5-32-561"="BUILTIN\Terminal Server License Servers";`
"S-1-5-32-562"="BUILTIN\Distributed COM Users";`
"S-1-5-32-568"="BUILTIN\IIS_IUSRS";`
"S-1-5-32-569"="BUILTIN\Cryptographic Operators";`
"S-1-5-32-573"="BUILTIN\Event Log Readers ";`
"S-1-5-32-574"="BUILTIN\Certificate Service DCOM Access";`
"S-1-5-32-575"="BUILTIN\RDS Remote Access Servers";`
"S-1-5-32-576"="BUILTIN\RDS Endpoint Servers";`
"S-1-5-32-577"="BUILTIN\RDS Management Servers";`
"S-1-5-32-578"="BUILTIN\Hyper-V Administrators";`
"S-1-5-32-579"="BUILTIN\Access Control Assistance Operators";`
"S-1-5-32-580"="BUILTIN\Remote Management Users";`
"S-1-5-33"="Write Restricted Code";`
"S-1-5-64-10"="NTLM Authentication";`
"S-1-5-64-14"="SChannel Authentication";`
"S-1-5-64-21"="Digest Authentication";`
"S-1-5-65-1"="This Organization Certificate";`
"S-1-5-80"="NT Service";`
"S-1-5-84-0-0-0-0-0"="User Mode Drivers";`
"S-1-5-113"="Local Account";`
"S-1-5-114"="Local Account And Member Of Administrators Group";`
"S-1-5-1000"="Other Organization";`
"S-1-15-2-1"="All App Packages";`
"S-1-16-0"="Untrusted Mandatory Level";`
"S-1-16-4096"="Low Mandatory Level";`
"S-1-16-8192"="Medium Mandatory Level";`
"S-1-16-8448"="Medium Plus Mandatory Level";`
"S-1-16-12288"="High Mandatory Level";`
"S-1-16-16384"="System Mandatory Level";`
"S-1-16-20480"="Protected Process Mandatory Level";`
"S-1-16-28672"="Secure Process Mandatory Level";`
"S-1-18-1"="Authentication Authority Asserted Identityl";`
"S-1-18-2"="Service Asserted Identity"}
# Function■■: Create-CanonicalName
# Arguments : [string] distinguishedName
# Returns ■: [string] CanonicalName
# Description : This function will create a canonical name of a distinguishedName string
#
#==========================================================================
Function Create-CanonicalName
{
param (
[Parameter(Mandatory=$True)]
[System.Array]$distinguishedname
)
$stringlistReversed = @()
$stringSplitted = $distinguishedname.Split(',')
$Counter = $stringSplitted.Count
$domainstring = ''
$intC = 0
for($i = 0; $i -le $stringSplitted.count; $i++)
{
if($stringSplitted[$i] -match "dc=")
{
if($intC -gt 0)
{
$domainstring += "." + $stringSplitted[$i].tostring().remove(0,3)
}
else
{
$domainstring += $stringSplitted[$i].tostring().remove(0,3)
}
$intC++
}
}
$stringReversed = ''
while ($Counter -gt 0) {
if($stringSplitted[$Counter-1] -match "dc=")
{
$Counter = $Counter-1
}
else
{
$stringReversed += $stringSplitted[$Counter-1].tostring().remove(0,3)
$Counter = $Counter-1
if ($Counter -gt 0) {
$stringReversed += '/'
}
}
}
$stringlistReversed = $domainstring + "/" + $stringReversed
return $stringlistReversed
}
#==========================================================================
# Function■■: Get-LargeNestedADGroup
# Arguments : DC name, DN of Group, Object type, Array of Members
# Returns ■: Array of Members
# Description : This function will enumerate large groups and returns direct and recusive members
#
#==========================================================================
Function Get-LargeNestedADGroup
{
Param (
# Domain Controller
[Parameter(Mandatory=$false)]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[string]$strDC,
# DistinguishedName of the group
[Parameter(Mandatory=$false)]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[string]$GroupDN,
# Returns members of type
[Parameter(Mandatory=$false)]
[ValidateSet("*", "User", "Group", "Computer")]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[String]
$Output = "*",
[System.Collections.ArrayList]
$MembersExpanded,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS
)
begin
{
$null = Add-Type -AssemblyName System.DirectoryServices.Protocols
if(-not($MembersExpanded))
{
$MembersExpanded = New-Object System.Collections.ArrayList
}
}
Process
{
# Use ADO to search entire domain.
if($CREDS)
{
$Root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$strDC/$GroupDN",$($CRED
$($CREDS.GetNetworkCredential().password ),
[System.DirectoryServices.AuthenticationTypes]::Secure )
}
else
{
$Root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$strDC/$GroupDN")
}
$ADS_SECURE_AUTHENTICATION = 1
$ADS_USE_SIGNING = 64
$ADS_SERVER_BIND = 512
$adoConnection = New-Object -comObject "ADODB.Connection"
$adoConnection.Provider = "ADsDSOObject"
if($CREDS)
{
$adoConnection.Properties("User ID") = $($CREDS.UserName)
$adoConnection.Properties("Password") = $($CREDS.GetNetworkCredential().password )
$adoConnection.Properties("Encrypt Password") = "True"
}
$adoConnection.Properties("ADSI Flag") = $ADS_SERVER_BIND -bor $ADS_SECURE_AUTHENTICA
$adoCommand = New-Object -comObject "ADODB.Command"
#$adoConnection.Open("Provider=ADsDSOObject;")
$adoConnection.Open("Active Directory Provider")
$adoCommand.ActiveConnection = $adoConnection
$adoCommand.Properties.Item("Page Size") = 200
$adoCommand.Properties.Item("Timeout") = 30
$adoCommand.Properties.Item("Cache Results") = $False
$Base = $Root.distinguishedName
$Scope = "base"
$Filter = "(objectCategory=group)"
# Setup range limits.
$Last = $False
$RangeStep = 1499
$LowRange = 0
$HighRange = $LowRange + $RangeStep
$Total = 0
$ExitFlag = $False
Do
{
If ($Last -eq $True)
{
# Retrieve remaining members (less than 1000).
$Attributes = "member;range=$LowRange-*"
}
Else
{
# Retrieve 1000 members.
$Attributes = "member;range=$LowRange-$HighRange"
}
$Query = "<LDAP://$strDC/$Base>;$Filter;$Attributes;$Scope"
$adoCommand.CommandText = $Query
$adoRecordset = $adoCommand.Execute()
$Count = 0
$Members = $adoRecordset.Fields.Item("$Attributes").Value
If ($Members -eq $Null)
{
$Last = $True
}
Else
{
# If $Members is not an array, no members were retrieved.
If ($Members.GetType().Name -eq "Object[]")
{
ForEach ($Member In $Members)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($strD
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = $Member
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("objectclass")
[void]$request.Attributes.Add("member")
Try{
$response = $LDAPConnection.SendRequest($request)
}
catch
{
Write-Verbose "Error - Could not read objectClass $Member";
continue;
}
$ADObject = $response.Entries[0]
Try{
$ObjectClass =$ADObject.attributes.objectclass[$ADObject.attributes.objectclass.count-1]
}
catch
{
Write-Verbose "Error - Could not read objectClass $Member";
continue;
}
if ($ObjectClass -eq "Group")
{
if(($ADObject.Attributes.AttributeNames -contains "member;range=0-1499") -or ($ADObjec
{
if (($global:colOfGroupMembersExpanded -notcontains $Member) -and ($GroupDN -ne
{
$MembersExpanded = @(Get-LargeNestedADGroup $strDC $Member $Output $Mem
[void]$global:GroupMembersExpanded.insert(0, $Member)
}
}
}
# Output the distinguished name of each direct member of the group.
if (($Output -eq "*") -or ($ObjectClass -eq $Output))
{
if ($MembersExpanded -notcontains $Member)
{
[void]$MembersExpanded.add($Member)
}
}
$Count = $Count + 1
}
}
}
$adoRecordset.Close()
$Total = $Total + $Count
# If this is the last query, exit the Do loop.
If ($Last -eq $True) {$ExitFlag = $True}
Else
{
# If the previous query returned no members, the query failed.
# Perform one more query to retrieve remaining members (less than 1000).
If ($Count -eq 0) {$Last = $True}
Else
{
# Retrieve the next 1000 members.
$LowRange = $HighRange + 1
$HighRange = $LowRange + $RangeStep
}
}
} Until ($ExitFlag -eq $True)
}
End
{
$adoConnection.Close()
return $MembersExpanded
}
}
#==========================================================================
# Function■■: Test-ResolveDNS
# Arguments : DNS Name, DNS Server
# Returns ■: boolean
# Description : This function try to resolve a dns record and retruns true or false
#
#==========================================================================
Function Test-ResolveDNS
{
param
(
$strDNS,
$strDNSServer = ""
)
$bolResolved = $false
$global:bolDNSSuccess = $true
$global:DNSrslt = $null
try
{
if($strDNSServer-eq "")
{
$global:DNSrslt = Resolve-DnsName -Type ALL -Name $strDNS -ErrorAction Stop
}
else
{
$global:DNSrslt = Resolve-DnsName -Type ALL -Name $strDNS -ErrorAction Stop -Server $str
}
}
catch
{
$global:bolDNSSuccess = $false
}
if($global:bolDNSSuccess)
{
if(($global:DNSrslt)[0].IPAddress -ne $null)
{
$bolResolved = $true
}
}
Remove-Variable bolDNSSuccess -Scope global
Remove-Variable DNSrslt -Scope global
return $bolResolved
}
#==========================================================================
# Function■■: LogMessage
# Arguments : Type of message, message, date stamping
# Returns ■: Custom psObject with two properties, type and message
# Description : This function creates a custom object that is used as input to an ListBox for logging pur
#
#==========================================================================
function LogMessage
{
param (
[Parameter(
Mandatory = $true
)][String[]] $strType ,
[Parameter(
Mandatory = $true
)][String[]] $strMessage ,
[Parameter(
Mandatory = $false
)][switch]$DateStamp
)
process {
if ($DateStamp)
{
$newMessageObject = New-Object PSObject -Property @{Type="$strType";Message="[$(
}
else
{
$newMessageObject = New-Object PSObject -Property @{Type="$strType";Message="$s
}
return $newMessageObject
}
}
#==========================================================================
# Function■■: ConvertTo-ObjectArrayListFromPsCustomObject
# Arguments : Defined Object
# Returns ■: Custom Object List
# Description : Convert a defined object to a custom, this will help you if you got a read-only object
#
#==========================================================================
function ConvertTo-ObjectArrayListFromPsCustomObject
{
param (
[Parameter(
Position = 0,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)] $psCustomObject
);
process {
}
catch
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not exist or ca
}
#If connection established list partitions
if($response)
{
$colResults = $response.Entries
foreach ($objResult in $colResults)
{
[void] $arrPartitions.add($objResult.attributes.dnsroot[0])
[void] $objListBoxDomainList.Items.Add($objResult.attributes.ncname[0])
}
}
#Get all incoming and bidirectional trusts
$request = New-Object System.directoryServices.Protocols.SearchRequest("CN=System,$global:strDo
[void]$request.Attributes.Add("trustpartner")
try
{
$response = $LDAPConnection.SendRequest($request)
}
catch
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! Domain does not exist or ca
}
#If connection established list partitions
if($response)
{
$colResults = $response.Entries
foreach ($objResult in $colResults)
{
$bolPartitionMatch = $false
foreach ($strPartition in $arrPartitions)
{
if($strPartition -eq $objResult.attributes.trustpartner[0])
{
$bolPartitionMatch = $true
}
}
if(!($bolPartitionMatch))
{
[void] $objListBoxDomainList.Items.Add($objResult.attributes.trustpartner[0])
}
}
}
if($objListBoxDomainList.Items.count -gt 0)
{
$DomainPickerGui.ShowDialog()
}
}
#==========================================================================
# Function■■: Get-SchemaData
# Arguments :
# Returns ■: string
# Description : Returns Schema Version
#==========================================================================
function Get-SchemaData
{
Param([System.Management.Automation.PSCredential] $CREDS)
■# Retrieve schema
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest("$global:SchemaDN", "(CN
[void]$request.Attributes.Add("rangeupper")
$response = $LDAPConnection.SendRequest($request)
$adObject = $response.Entries
if(($null -ne $adObject) -and ($adobject.Count -ne 0 ))
{
foreach ($entry in $response.Entries)
{
■try
■{
■■[int] $ExchangeVersion = $entry.Attributes.rangeupper[0]
■■■■■
■■if ( $global:SchemaHashExchange.ContainsKey($ExchangeVersion) )
■■{
■■■$txtBoxExSchema.Text = $global:SchemaHashExchange[$ExchangeVersion]
■■}
■■else
■■{
■■■$txtBoxExSchema.Text = "Unknown"
■■}
■}
■catch
■{
■■$txtBoxExSchema.Text = "Not Found"
■}
}
}
else
{
■$txtBoxExSchema.Text = "Not Found"
}
$request = New-Object System.directoryServices.Protocols.SearchRequest("$global:SchemaDN", "(CN
[void]$request.Attributes.Add("rangeupper")
$response = $LDAPConnection.SendRequest($request)
$adObject = $response.Entries
if(($null -ne $adObject) -and ($adobject.Count -ne 0 ))
{
foreach ($entry in $response.Entries)
{
■try
■{
■■[int] $LyncVersion = $entry.Attributes.rangeupper[0]
■■■■■
■■if ( $global:SchemaHashLync.ContainsKey($LyncVersion) )
■■{
■■■$txtBoxLyncSchema.Text = $global:SchemaHashLync[$LyncVersion]
■■}
■■else
■■{
■■■$txtBoxLyncSchema.Text = "Unknown"
■■}
■}
■catch
■{
■■$txtBoxLyncSchema.Text = "Not Found"
■}
}
}
else
{
■$txtBoxLyncSchema.Text = "Not Found"
}
$request = New-Object System.directoryServices.Protocols.SearchRequest("$global:SchemaDN", "(CN
[void]$request.Attributes.Add("objectversion")
$response = $LDAPConnection.SendRequest($request)
$adObject = $response.Entries
if(($null -ne $adObject) -and ($adobject.Count -ne 0 ))
{
foreach ($entry in $response.Entries)
{
■try
■{
■■$ADSchemaVersion = $entry.Attributes.objectversion[0]
■■■■■
■■if ( $global:SchemaHashAD.ContainsKey([int]$ADSchemaVersion) )
■■{
■■■$txtBoxADSchema.Text = $global:SchemaHashAD[[int]$ADSchemaVersion]
■■}
■■else
■■{
■■■$txtBoxADSchema.Text = $ADSchemaVersion
■■}
■}
■catch
■{
■■$txtBoxADSchema.Text = "Not Found"
■}
}
}
else
{
■$txtBoxADSchema.Text = "Not Found"
}
$request = New-Object System.directoryServices.Protocols.SearchRequest("$global:strDomainDNNam
[void]$request.Attributes.Add("msds-behavior-version")
$response = $LDAPConnection.SendRequest($request)
$adObject = $response.Entries
if(($null -ne $adObject) -and ($adobject.Count -ne 0 ))
{
foreach ($entry in $response.Entries)
{
■try
■{
■■$ADDFL = $entry.Attributes.'msds-behavior-version'[0]
■■■■■
■■if ( $global:DomainFLHashAD.ContainsKey([int]$ADDFL) )
■■{
■■■$txtBoxDFL.Text = $global:DomainFLHashAD[[int]$ADDFL]
■■}
■■else
■■{
■■■$txtBoxDFL.Text = "Unknown"
■■}
■}
■catch
■{
■■$txtBoxDFL.Text = "Not Found"
■}
}
}
else
{
■$txtBoxDFL.Text = "Not Found"
}
$request = New-Object System.directoryServices.Protocols.SearchRequest("CN=Partitions,CN=Config
[void]$request.Attributes.Add("msds-behavior-version")
$response = $LDAPConnection.SendRequest($request)
$adObject = $response.Entries
if(($null -ne $adObject) -and ($adobject.Count -ne 0 ))
{
foreach ($entry in $response.Entries)
{
■try
■{
■■$ADFFL = $entry.Attributes.'msds-behavior-version'[0]
■■■■■
■■if ( $global:ForestFLHashAD.ContainsKey([int]$ADFFL) )
■■{
■■■$txtBoxFFL.Text = $global:ForestFLHashAD[[int]$ADFFL]
■■}
■■else
■■{
■■■$txtBoxFFL.Text = "Unknown"
■■}
■}
■catch
■{
■■$txtBoxFFL.Text = "Not Found"
■}
}
}
else
{
■$txtBoxFFL.Text = "Not Found"
}
$request = New-Object System.directoryServices.Protocols.SearchRequest("CN=Directory Service,CN
[void]$request.Attributes.Add("dsheuristics")
$response = $LDAPConnection.SendRequest($request)
$adObject = $response.Entries
if(($null -ne $adObject) -and ($adobject.Count -ne 0 ))
{
foreach ($entry in $response.Entries)
{
■try
■{
■■$DSHeuristics = $entry.Attributes.dsheuristics[0]
■■■■■
■■if ($DSHeuristics.Substring(2,1) -eq "1")
■■{
■■■$txtListObjectMode.Text = "Enabled"
■■}
■■else
■■{
■■■$txtListObjectMode.Text = "Disabled"
■■}
■}
■catch
■{
■■$txtListObjectMode.Text = "Not Found"
■}
}
}
else
{
■$txtListObjectMode.Text = "Disabled"
}
}
#==========================================================================
# Function■■: Get-HighestNetFrameWorkVer
# Arguments :
# Returns ■: string
# Description : Returns Highest .Net Framework Version
#==========================================================================
Function Get-HighestNetFrameWorkVer
{
$arrDotNetFrameWorkVersions = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup
Get-ItemProperty -name Version,Release -EA 0 |
Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
Select-Object Version
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 4.6} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
else{
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 4.5} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
else{
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 4.0} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
else{
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 3.5} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
else{
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 3.0} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
else{
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 2.0} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
else{
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 1.1} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
else{
$DotNetVer = $arrDotNetFrameWorkVersions | where-object{$_.version -ge 1.0} | Select-Object -Last 1
if($DotNetVer){$HighestDotNetFrmVer = $DotNetVer.Version}
}}}}}}}
Remove-variable DotNetVer,arrDotNetFrameWorkVersions
return $HighestDotNetFrmVer
}
#==========================================================================
# Function■■: GetDomainController
# Arguments : Domain FQDN,bol using creds, PSCredential
# Returns ■: Domain Controller
# Description : Locate a domain controller in a specified domain
#==========================================================================
Function GetDomainController
{
Param([string] $strDomainFQDN,
[bool] $bolCreds,
[parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential] $DCCREDS)
$strDomainController = ""
if ($bolCreds -eq $true)
{
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$strDomainF
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$strDomainController = $($ojbDomain.FindDomainController()).name
}
else
{
$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$strDomainF
$ojbDomain = [DirectoryServices.ActiveDirectory.Domain]::GetDomain($Context)
$strDomainController = $($ojbDomain.FindDomainController()).name
}
return $strDomainController
}
#==========================================================================
# Function■■: Get-DirContext
# Arguments : string domain controller,credentials
# Returns ■: Directory context
# Description : Get Directory Context
#==========================================================================
function Get-DirContext
{
Param($DomainController,
[System.Management.Automation.PSCredential] $CREDS)
■if($CREDS)
■■{
■■$Context = new-object DirectoryServices.ActiveDirectory.DirectoryContext("DirectoryServer",$Doma
■}
■else
■{
■■$Context = New-Object DirectoryServices.ActiveDirectory.DirectoryContext("DirectoryServer",$Dom
■}
■
return $Context
}
#==========================================================================
# Function■■: TestCreds
# Arguments : System.Management.Automation.PSCredential
# Returns ■: Boolean
# Description : Check If username and password is valid
#==========================================================================
Function TestCreds
{
Param([System.Management.Automation.PSCredential] $psCred)
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
if ($psCred.UserName -match "\\")
{
If ($psCred.UserName.split("\")[0] -eq "")
{
[directoryservices.directoryEntry]$root = (New-Object system.directoryservices.directoryEntry)
$ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.Dire
}
else
{
$PrincipalDN,
[bool]
$bolCreds,
[parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential]
$GetTokenCreds,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS
)
$script:bolErr = $false
$tokenGroups = New-Object System.Collections.ArrayList
$tokenGroups.Clear()
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($PrincipalDom
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = $PrincipalDN
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("tokengroups")
[void]$request.Attributes.Add("tokengroupsglobalanduniversal")
[void]$request.Attributes.Add("objectsid")
$response = $LDAPConnection.SendRequest($request)
$ADobject = $response.Entries[0]
if ( $global:strDomainPrinDNName -eq $global:strDomainDNName )
{
$SIDs = $ADobject.Attributes.tokengroups
}
else
{
$SIDs = $ADobject.Attributes.tokengroupsglobalanduniversal
}
#Get selected principal SID
$ownerSIDs = (New-Object System.Security.Principal.SecurityIdentifier $ADobject.Attributes.objectsid[0
# Add selected principal SID to tokenGroups
[void]$tokenGroups.Add($ownerSIDs)
$arrForeignSecGroups = FindForeignSecPrinMemberships $(GenerateSearchAbleSID $ownerSIDs) $C
foreach ($ForeignMemb in $arrForeignSecGroups)
{
if($null -ne $ForeignMemb)
{
if($ForeignMemb.tostring().length -gt 0 )
{
[void]$tokenGroups.add($ForeignMemb)
}
}
}
# Populate hash table with security group memberships.
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($PrincipalDom
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = "CN=ForeignSecurityPrincipals,$global:strDomainDNName"
$request.Filter = "(CN=S-1-5-11)"
$request.Scope = "onelevel"
[void]$request.Attributes.Add("objectsid")
$response = $LDAPConnection.SendRequest($request)
$colResults = $response.Entries
foreach ($objResult in $colResults)
{
■
[byte[]] $byte = $objResult.Attributes.objectsid.GetValues([byte[]])[0]
$ForeignDefaultWellKnownSIDs = (New-Object System.Security.Principal.SecurityIdentifier($byte, 0)
$arrForeignSecGroups = FindForeignSecPrinMemberships $(GenerateSearchAbleSID $ForeignDefa
foreach ($ForeignMemb in $arrForeignSecGroups)
{
if($null -ne $ForeignMemb)
{
if($ForeignMemb.tostring().length -gt 0 )
{
[void]$tokenGroups.add($ForeignMemb)
}
}
}
}
#Add SID string to tokenGroups
ForEach ($Value In $SIDs)
{
$SID = New-Object System.Security.Principal.SecurityIdentifier $Value, 0
[void]$tokenGroups.Add($SID.Value)
}
#Add Everyone
[void]$tokenGroups.Add("S-1-1-0")
#Add Authenticated Users
[void]$tokenGroups.Add("S-1-5-11")
if(($global:strPrinDomAttr -eq 14) -or ($global:strPrinDomAttr -eq 18) -or ($global:strPrinDomAttr -eq "5C
{
#Add Other Organization
[void]$tokenGroups.Add("S-1-5-1000")
}
else
{
#Add This Organization
[void]$tokenGroups.Add("S-1-5-15")
}
#Remove duplicate
$tokenGroups = $tokenGroups | Select-Object -Unique
Return $tokenGroups
}
#==========================================================================
# Function■■: GenerateSearchAbleSID
# Arguments : SID Decimal form Value as string
# Returns ■: SID in String format for LDAP searcheds
# Description : Convert SID from decimal to hex with "\" for searching with LDAP
#==========================================================================
Function GenerateSearchAbleSID
{
Param([String] $SidValue)
# Create SID .NET object using SID string provided
$sid = New-Object system.Security.Principal.SecurityIdentifier $SidValue
# Create a byte array of the proper length
$sidBytes = New-Object byte[] $sid.BinaryLength
$SidDec = $sid.GetBinaryForm( $sidBytes, 0 )
#$SidDec =$sidBytes.tostring().split("")
Foreach ($intSID in $sidBytes)
{
[string] $SIDHex = "{0:X2}" -f [int] $intSID
$strSIDHextString = $strSIDHextString + "\" + $SIDHex
}
return $strSIDHextString
}
#==========================================================================
# Function■■: FindForeignSecPrinMemberships
# Arguments : SID Decimal form Value as string
# Returns ■: Group names
# Description : Searching for ForeignSecurityPrinicpals and return memberhsip
#==========================================================================
Function FindForeignSecPrinMemberships
{
Param([string] $strSearchAbleSID,
[System.Management.Automation.PSCredential] $ForeignCREDS)
$arrForeignMembership = New-Object System.Collections.ArrayList
[void]$arrForeignMembership.clear()
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = "CN=ForeignSecurityPrincipals,$global:strDomainDNName"
$request.Filter = "(&(objectSID=$strSearchAbleSID))"
$request.Scope = "Subtree"
[void]$request.Attributes.Add("memberof")
$response = $LDAPConnection.SendRequest($request)
Foreach ( $obj in $response.Entries)
{
$index = 0
while($index -le $obj.Attributes.memberof.count -1)
{
$member = $obj.Attributes.memberof[$index]
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:st
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = $member
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("objectsid")
$response = $LDAPConnection.SendRequest($request)
$ADobject = $response.Entries[0]
$strPrinName = New-Object System.Security.Principal.SecurityIdentifier $($ADobject.Attributes.ob
[void]$arrForeignMembership.add($strPrinName.Value)
$index++
}
}
return $arrForeignMembership
}
#==========================================================================
# Function■■: GetSidStringFromSidByte
# Arguments : SID Value in Byte[]
# Returns ■: SID in String format
# Description : Convert SID from Byte[] to String
#==========================================================================
Function GetSidStringFromSidByte
{
Param([byte[]] $SidByte)
$objectSid = [byte[]]$SidByte
$sid = New-Object System.Security.Principal.SecurityIdentifier($objectSid,0)
$sidString = ($sid.value).ToString()
return $sidString
}
#==========================================================================
# Function■■: GetSecPrinDN
# Arguments : samAccountName
# Returns ■: DistinguishedName
# Description : Search Security Principal and Return DistinguishedName
#==========================================================================
Function GetSecPrinDN
{
Param([string] $samAccountName,
[string] $strDomainDC,
[bool] $bolCreds,
[parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential] $CREDS)
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($strDomainDC
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.Filter = "(name=*)"
$request.Scope = "Base"
$response = $LDAPConnection.SendRequest($request)
$strPrinDomDefNC = $response.Entries[0].Attributes.defaultnamingcontext[0]
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($strDomainDC
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = $strPrinDomDefNC
$request.Filter = "(&(samAccountName=$samAccountName))"
$request.Scope = "Subtree"
[void]$request.Attributes.Add("name")
$response = $LDAPConnection.SendRequest($request)
$ADobject = $response.Entries[0]
if($ADobject.Attributes.Count -gt 0)
{
■$global:strPrincipalDN = $ADobject.distinguishedname
}
else
{
$global:strPrincipalDN = ""
}
return $global:strPrincipalDN
}
#==========================================================================
# Function■■: GetSchemaObjectGUID
# Arguments : Object Guid or Rights Guid
# Returns ■: LDAPDisplayName or DisplayName
# Description : Searches in the dictionaries(Hash) dicRightsGuids and $global:dicSchemaIDGUIDs an
#■■■■for the name of the object or Extended Right, if found in Schema the dicRightsGuids is updated
#■■■■Then the functions return the name(LDAPDisplayName or DisplayName).
#==========================================================================
Function GetSchemaObjectGUID
{
Param(
[string]
$Domain,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
■[string] $strOut =""
■[string] $strLDAPname = ""
BuildSchemaDic
#for paged search, the response for paged search result control - we will need a cookie from resul
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged r
$colResults = $response.Entries
■ foreach ($objResult in $colResults)
■ {
■■ $strLDAPname = $objResult.attributes.ldapdisplayname[0]
■■ $guidGUID = [System.GUID] $objResult.attributes.schemaidguid[0]
$strGUID = $guidGUID.toString().toUpper()
■■ If (!($global:dicSchemaIDGUIDs.ContainsKey($strGUID)))
{
$global:dicSchemaIDGUIDs.Add($strGUID,$strLDAPname)
$global:dicNameToSchemaIDGUIDs.Add($strLDAPname,$strGUID)
}
■■■■
■ }
if($global:PageSize -gt 0) {
if ($prrc.Cookie.Length -eq 0) {
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
} else {
#exit the processing for non-paged search
break;
}
}
■
■return $strOut
}
#==========================================================================
# Function■■: CheckDNExist
# Arguments : string distinguishedName, string directory server
# Returns ■: Boolean
# Description : Check If distinguishedName exist
#==========================================================================
function CheckDNExist
{
Param (
$sADobjectName,
[string]
$strDC,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS
)
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($strDC, $CR
#$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.DirectoryControl" -
}
$request.DistinguishedName = $sADobjectName
$request.Filter = "(name=*)"
$request.Scope = "Base"
■try
■{
$response = $LDAPConnection.SendRequest($request)
■}
■catch
■{
■■return $false
■}
if($response.Entries.count -gt 0)
{
$ADobject = $response.Entries[0]
If($null -eq $ADobject.distinguishedname)
{return $false}
else
{return $true}
}
}
#==========================================================================
# Function■■: TestCSVColumnsDefaultSD
# Arguments : CSV import for Default Security descriptor
# Returns ■: Boolean
# Description : Search for all requried column names in CSV and return true or false
#==========================================================================
function TestCSVColumnsDefaultSD
{
param($CSVImport)
$bolColumExist = $false
$colHeaders = ( $CSVImport | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandPrope
$bolName = $false
$boldistinguishedName = $false
$bolVersion = $false
$bolModifiedDate = $false
$bolSDDL = $false
Foreach ($ColumnName in $colHeaders )
{
if($ColumnName.Trim() -eq "Name")
{
$bolName = $true
}
if($ColumnName.Trim() -eq "distinguishedName")
{
$boldistinguishedName = $true
}
if($ColumnName.Trim() -eq "Version")
{
$bolVersion = $true
}
if($ColumnName.Trim() -eq "ModifiedDate")
{
$bolModifiedDate = $true
}
if($ColumnName.Trim() -eq "SDDL")
{
$bolSDDL = $true
}
}
#if test column names exist
if($bolName -and $boldistinguishedName -and $bolVersion -and $bolModifiedDate -and $bolSDDL)
{
$bolColumExist = $true
}
return $bolColumExist
}
#==========================================================================
# Function■■: TestCSVColumns
# Arguments : CSV import
# Returns ■: Boolean
# Description : Search for all requried column names in CSV and return true or false
#==========================================================================
function TestCSVColumns
{
param($CSVImport)
$bolColumExist = $false
$colHeaders = ( $CSVImport | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandPrope
$bolAccessControlType = $false
$bolActiveDirectoryRights = $false
$bolIdentityReference = $false
$bolInheritanceFlags = $false
$bolInheritanceType = $false
$bolInheritedObjectType = $false
$bolInvocationID = $false
$bolIsInherited = $false
$bolObjectFlags= $false
$bolObjectType = $false
$bolOrgUSN= $false
$bolOU = $false
$bolPropagationFlags = $false
$bolSDDate = $false
Foreach ($ColumnName in $colHeaders )
{
if($ColumnName.Trim() -eq "AccessControlType")
{
$bolAccessControlType = $true
}
if($ColumnName.Trim() -eq "ActiveDirectoryRights")
{
$bolActiveDirectoryRights = $true
}
if($ColumnName.Trim() -eq "IdentityReference")
{
$bolIdentityReference = $true
}
if($ColumnName.Trim() -eq "InheritanceFlags")
{
$bolInheritanceFlags = $true
}
if($ColumnName.Trim() -eq "InheritanceType")
{
$bolInheritanceType = $true
}
if($ColumnName.Trim() -eq "InheritedObjectType")
{
$bolInheritedObjectType = $true
}
if($ColumnName.Trim() -eq "InvocationID")
{
$bolInvocationID = $true
}
if($ColumnName.Trim() -eq "IsInherited")
{
$bolIsInherited = $true
}
}
}
else
{
$nodelist += $firstnode
}
}
}#End if Scope = onelevel
$request.filter = $ReqFilter
if($ExcludedDNs)
{
$arrExcludedDN = $ExcludedDNs.split(";")
while ($true)
{
try
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$glob
}
catch
{
if($_.Exception.Message.tostring() -match "The search filter is invalid")
{
$global:SearchFailed = $true
if($global:bolCMD)
{
Write-host "The search filter is invalid"
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "The search filter is invali
}
break
}
}
#for paged search, the response for paged search result control - we will need a cookie from result la
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged retr
$colResults = $response.Entries
$intTotalSearch = $colResults.Count
$intNomatch = 0
■foreach ($objResult in $colResults)
■{
$bolInclude = $true
Foreach( $strExcludeDN in $arrExcludedDN)
{
if(!($objResult.distinguishedName -notmatch $strExcludeDN ))
{
$bolInclude = $false
break
}
}
#Add objects with distinguihsedname not matching string
if($bolInclude)
{
#Reverse string to be able to sort output
$nodelist += $objResult.distinguishedName
$intNomatch++
}
}
if($global:PageSize -gt 0) {
if ($prrc.Cookie.Length -eq 0) {
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
} else {
#exit the processing for non-paged search
break;
}
} #End While
#Caclulate number of objects exluded in search
$global:intObjExluced = $intTotalSearch - $intNomatch
# Log information about skipped objects
if($global:bolCMD)
{
Write-host "Number of objects excluded: $global:intObjExluced"
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Number of objects excluded: $g
}
}
# If no string in Excluded String box
else
{
$colResults = @()
while ($true)
{
try
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$global
}
catch
{
if($_.Exception.Message.tostring() -match "The search filter is invalid")
{
$global:SearchFailed = $true
if($global:bolCMD)
{
Write-host "The search filter is invalid"
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "The search filter is invali
}
break
}
}
#for paged search, the response for paged search result control - we will need a cookie from resul
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged r
if($GPO)
{
$colResults = $response.Entries
■ foreach ($objResult in $colResults)
■ {
$gplink = $objResult.attributes.gplink[0]
$arrLinks = @($gplink.split("["))
return $ReturnShortName
}
#==========================================================================
# Function■■: Get-ProtectedPerm
# Arguments :
# Returns ■: ArrayList
# Description : Creates the Security Descriptor with the Protect object from accidental deleations ACE
#==========================================================================
Function Get-ProtectedPerm
{
$sdProtectedDeletion = New-Object System.Collections.ArrayList
$sdProtectedDeletion.clear()
$protectedDeletionsACE1 = New-Object PSObject -Property @{ActiveDirectoryRights="DeleteChild";In
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="None";AccessControl
InheritanceFlags="None";PropagationFlags="None"}
[void]$sdProtectedDeletion.insert(0,$protectedDeletionsACE)
$protectedDeletionsACE2 = New-Object PSObject -Property @{ActiveDirectoryRights="DeleteChild, De
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="ObjectAceTypePresen
InheritanceFlags="None";PropagationFlags="None"}
$protectedDeletionsACE3 = New-Object PSObject -Property @{ActiveDirectoryRights="DeleteTree, De
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="None";AccessControl
InheritanceFlags="None";PropagationFlags="None"}
[void]$sdProtectedDeletion.insert(0,@($protectedDeletionsACE1,$protectedDeletionsACE2,$protected
return $sdProtectedDeletion
}
#==========================================================================
# Function■■: Get-DefaultPermissions
# Arguments : Object Class, Trustee Name
# Returns ■: ArrayList
# Description : Fetch the Default Security Descriptor with the Default
#==========================================================================
Function Get-DefaultPermissions
{
Param(
$strObjectClass,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
$sdOUDef = New-Object System.Collections.ArrayList
$sdOUDef.clear()
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest("$global:SchemaDN", "(lda
[void]$request.Attributes.Add("defaultsecuritydescriptor")
$response = $LDAPConnection.SendRequest($request)
$colResults = $response.Entries
foreach ($entry in $response.Entries)
{
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
$defSD = ""
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
Try{
$sec.SetSecurityDescriptorSddlForm($entry.Attributes.defaultsecuritydescriptor[0])
}
catch
{
if($bolCMD)
{
Write-host "The SDDL string contains an invalid sid or a sid that cannot be translated." -Foreg
Write-host "Only domain-joined computers can translate some sids." -ForegroundColor Red
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "The SDDL string contains a
$global:observableCollection.Insert(0,(LogMessage -strMessage "Only domain-joined compu
}
}
}
$defSD = $sec.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier])
$sec = $null
}
if($null -ne $defSD){
$(ConvertTo-ObjectArrayListFromPsCustomObject $defSD)| ForEach-Object{[void]$sdOUDef.add($_)
$defSD = $null
if ($strObjectClass -eq "computer")
{
if($global:intObjeComputer -eq 0)
{
$global:additionalComputerACE1 = New-Object PSObject -Property @{ActiveDirectoryRights="De
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="None";AccessCo
InheritanceFlags="None";PropagationFlags="None"}
#[void]$sdOUDef.insert(0,$global:additionalComputerACE)
$global:additionalComputerACE2 = New-Object PSObject -Property @{ActiveDirectoryRights="Wr
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="ObjectAceTypeP
InheritanceFlags="None";PropagationFlags="None"}
#[void]$sdOUDef.insert(0,$global:additionalComputerACE)
$global:additionalComputerACE3 = New-Object PSObject -Property @{ActiveDirectoryRights="Wr
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="ObjectAceTypeP
InheritanceFlags="None";PropagationFlags="None"}
#[void]$sdOUDef.insert(0,$global:additionalComputerACE)
$global:additionalComputerACE4 = New-Object PSObject -Property @{ActiveDirectoryRights="Wr
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="ObjectAceTypeP
InheritanceFlags="None";PropagationFlags="None"}
#[void]$sdOUDef.insert(0,$global:additionalComputerACE)
$global:additionalComputerACE5 = New-Object PSObject -Property @{ActiveDirectoryRights="Wr
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="ObjectAceTypeP
InheritanceFlags="None";PropagationFlags="None"}
#[void]$sdOUDef.insert(0,$global:additionalComputerACE)
$global:additionalComputerACE6 = New-Object PSObject -Property @{ActiveDirectoryRights="Wr
InheritedObjectType="00000000-0000-0000-0000-000000000000";ObjectFlags="ObjectAceTypeP
InheritanceFlags="None";PropagationFlags="None"}
#[void]$sdOUDef.insert(0,$global:additionalComputerACE)
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
■[string] $strOut = $strGUIDAsString
■[string] $strLDAPname = ""
■If ($strGUIDAsString -eq "")
■{
■ Break
■}
■$strGUIDAsString = $strGUIDAsString.toUpper()
■if ($global:dicRightsGuids.ContainsKey($strGUIDAsString))
■{
■■$strOut =$global:dicRightsGuids.Item($strGUIDAsString)
■}
■If ($strOut -eq $strGUIDAsString)
■{ #Didn't find a match in extended rights
■■If ($global:dicSchemaIDGUIDs.ContainsKey($strGUIDAsString))
■■{
■■■$strOut =$global:dicSchemaIDGUIDs.Item($strGUIDAsString)
■■}
■■else
■■{
■■
■■ if ($strGUIDAsString -match("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0
■■ {
■■ ■
■■■$ConvertGUID = ConvertGUID($strGUIDAsString)
■■
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$searcher = New-Object System.directoryServices.Protocols.SearchRequest
$searcher.DistinguishedName = $global:SchemaDN
[void]$searcher.Attributes.Add("cn")
[void]$searcher.Attributes.Add("name")
[void]$searcher.Attributes.Add("ldapdisplayname")
■■■$searcher.filter = "(&(schemaIDGUID=$ConvertGUID))"
$searcherSent = $LDAPConnection.SendRequest($searcher)
$objSchemaObject = $searcherSent.Entries[0]
■■■ if ($objSchemaObject)
■■■ {
■■■■$strLDAPname =$objSchemaObject.attributes.ldapdisplayname[0]
■■■■$global:dicSchemaIDGUIDs.Add($strGUIDAsString.toUpper(),$strLDAPname)
■■■■$strOut=$strLDAPname
■■■■
■■■ }
■■}
■ }
■}
■return $strOut
}
#==========================================================================
# Function■■: ConvertGUID
# Arguments : Object Guid or Rights Guid
# Returns ■: AD Searchable GUID String
# Description : Convert a GUID to a string
#==========================================================================
Function ConvertGUID
{
Param($guid)
■ $test = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})"
■ $pattern = '"\$4\$3\$2\$1\$6\$5\$8\$7\$9\$10\$11\$12\$13\$14\$15\$16"'
■ $ConvertGUID = [regex]::Replace($guid.replace("-",""), $test, $pattern).Replace("`"","")
■ return $ConvertGUID
}
#==========================================================================
# Function■■: fixfilename
# Arguments : Text for naming text file
# Returns ■: Text with replace special characters
# Description : Replace characters that be contained in a file name.
#==========================================================================
function fixfilename
{
Param([string] $strFileName)
$strFileName = $strFileName.Replace("*","#")
$strFileName = $strFileName.Replace("/","#")
$strFileName = $strFileName.Replace("\","#")
$strFileName = $strFileName.Replace(":","#")
$strFileName = $strFileName.Replace("<","#")
$strFileName = $strFileName.Replace(">","#")
$strFileName = $strFileName.Replace("|","#")
$strFileName = $strFileName.Replace('"',"#")
$strFileName = $strFileName.Replace('?',"#")
return $strFileName
}
#==========================================================================
# Function■■: WritePermCSV
# Arguments : Security Descriptor, OU distinguishedName, Ou put text file
# Returns ■: n/a
# Description : Writes the SD to a text file.
#==========================================================================
function WritePermCSV
{
Param($sd,[string]$object,[string]$canonical,[string]$objType,[string] $fileout, [bool] $ACLMeta,[string
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
$sd | foreach {
#Convert SID to Names for lookups
$strPrincipalName = $_.IdentityReference.toString()
■ If ($strPrincipalName -match "S-1-")
■ {
■ $strPrincipalName = ConvertSidToName -server $global:strDomainLongName -Sid $strPrincipal
■ }
# Add Translated object GUID information to output
if($TranslateGUID -eq $True)
{
■ if($($_.InheritedObjectType.toString()) -ne "00000000-0000-0000-0000-000000000000" )
{
if($compare)
{
Add-Member -InputObject $objCSVLine -MemberType NoteProperty -Name "State" -value $_.S
}
if($Outfile)
{
export-csv -InputObject $objCSVLine -Path $fileout -Encoding UTF8 -NoClobber -NoTypeInform
}
else
{
return $objCSVLine
}
}
}
#==========================================================================
# Function■■: GetObjectTypeFromSid
# Arguments : SID string
# Returns ■: Object type of Security Object
# Description : Try to get the object of a SID
#==========================================================================
function GetObjectTypeFromSid
{
Param($server,$sid,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
$strObjectType = $null
$ID = New-Object System.Security.Principal.SecurityIdentifier($sid)
If ($global:dicSidToObject.ContainsKey($sid))
{
■$strObjectType =$global:dicSidToObject.Item($sid)
}
else
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strD
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.DirectoryControl" -
}
$request.DistinguishedName = "<SID=$sid>"
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("objectclass")
try
{
$response = $LDAPConnection.SendRequest($request)
$result = $response.Entries[0]
■ $strObjectType = $result.attributes.objectclass[-1]
}
catch
{
}
if($null -ne $strObjectType )
{
$global:dicSidToObject.Add($sid,$strObjectType)
}
}
return $strObjectType
}
#==========================================================================
# Function■■: ConvertSidToName
# Arguments : SID string
# Returns ■: Friendly Name of Security Object
# Description : Try to translate the SID if it fails it try to match a Well-Known.
#==========================================================================
function ConvertSidToName
{
Param($server,$sid,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
$global:strAccNameTranslation = ""
$ID = New-Object System.Security.Principal.SecurityIdentifier($sid)
&{#Try
■$User = $ID.Translate( [System.Security.Principal.NTAccount])
■$global:strAccNameTranslation = $User.Value
}
Trap [SystemException]
{
■If ($global:dicWellKnownSids.ContainsKey($sid))
■{
■■$global:strAccNameTranslation = $global:dicWellKnownSids.Item($sid)
■■return $global:strAccNameTranslation
■}
■;Continue
}
if ($global:strAccNameTranslation -eq "")
{
If ($global:dicSidToName.ContainsKey($sid))
{
■ $global:strAccNameTranslation =$global:dicSidToName.Item($sid)
}
else
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:st
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.DirectoryControl
}
$request.DistinguishedName = "<SID=$sid>"
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("samaccountname")
$response = $LDAPConnection.SendRequest($request)
$result = $response.Entries[0]
try
{
■ $global:strAccNameTranslation = $global:strDomainShortName + "\" + $result.attributes.samacc
}
catch
{
}
■ if(!($global:strAccNameTranslation))
{
$global:strAccNameTranslation = $result.distinguishedname
}
$global:dicSidToName.Add($sid,$global:strAccNameTranslation)
}
}
If (($global:strAccNameTranslation -eq $nul) -or ($global:strAccNameTranslation -eq ""))
{
■$global:strAccNameTranslation =$sid
}
return $global:strAccNameTranslation
}
#==========================================================================
# Function■■: Get-Criticality
# Arguments : $objRights,$objAccess,$objFlags,$objInheritanceType
# Returns ■: Integer
# Description : Check criticality and returns number for rating
#==========================================================================
Function Get-Criticality
{
Param($Returns="Filter",$objIdentity,$objRights,$objAccess,$objFlags,$objInheritanceType,$objObje
$intCriticalityLevel = 0
Switch ($objRights)
{
"ListChildren"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 0
}
}
"Read permissions, Modify permissions"
{
$intCriticalityLevel = 4
}
"Modify permissions"
{
$intCriticalityLevel = 4
}
{($_ -match "WriteDacl") -or ($_ -match "WriteOwner")}
{
$intCriticalityLevel = 4
}
"DeleteChild, DeleteTree, Delete"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 3
}
}
"Delete"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 3
}
}
"GenericRead"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 1
■}
}
"CreateChild"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 3
■}
}
"DeleteChild"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 3
■}
}
"ExtendedRight"
{
If ($objAccess -eq "Allow")
{
Switch ($objObjectType)
{
# Domain Administer Server =
"ab721a52-1e2f-11d0-9819-00aa0040529b"
{
$intCriticalityLevel = 4
}
# Change Password =
"ab721a53-1e2f-11d0-9819-00aa0040529b"
{
$intCriticalityLevel = 1
}
# Reset Password =
"00299570-246d-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Send As =
"ab721a54-1e2f-11d0-9819-00aa0040529b"
{
$intCriticalityLevel = 4
}
# Receive As =
"ab721a56-1e2f-11d0-9819-00aa0040529b"
{
$intCriticalityLevel = 4
}
# Send To =
"ab721a55-1e2f-11d0-9819-00aa0040529b"
{
$intCriticalityLevel = 4
}
# Open Address List =
"a1990816-4298-11d1-ade2-00c04fd8d5cd"
{
$intCriticalityLevel = 1
}
# Replicating Directory Changes =
"1131f6aa-9c07-11d1-f79f-00c04fc2dcd2"
{
$intCriticalityLevel = 4
}
# Replication Synchronization =
"1131f6ab-9c07-11d1-f79f-00c04fc2dcd2"
{
$intCriticalityLevel = 4
}
# Manage Replication Topology =
"1131f6ac-9c07-11d1-f79f-00c04fc2dcd2"
{
$intCriticalityLevel = 4
}
# Change Schema Master =
"e12b56b6-0a95-11d1-adbb-00c04fd8d5cd"
{
$intCriticalityLevel = 4
}
# Change Rid Master =
"d58d5f36-0a98-11d1-adbb-00c04fd8d5cd"
{
$intCriticalityLevel = 4
}
# Do Garbage Collection =
"fec364e0-0a98-11d1-adbb-00c04fd8d5cd"
{
$intCriticalityLevel = 4
}
# Recalculate Hierarchy =
"0bc1554e-0a99-11d1-adbb-00c04fd8d5cd"
{
$intCriticalityLevel = 4
}
# Allocate Rids =
"1abd7cf8-0a99-11d1-adbb-00c04fd8d5cd"
{
$intCriticalityLevel = 4
}
# Change PDC =
"bae50096-4752-11d1-9052-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Add GUID =
"440820ad-65b4-11d1-a3da-0000f875ae0d"
{
$intCriticalityLevel = 4
}
# Change Domain Master =
"014bf69c-7b3b-11d1-85f6-08002be74fab"
{
$intCriticalityLevel = 4
}
# Receive Dead Letter =
"4b6e08c0-df3c-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Peek Dead Letter =
"4b6e08c1-df3c-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Receive Computer Journal =
"4b6e08c2-df3c-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Peek Computer Journal =
"4b6e08c3-df3c-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Receive Message =
"06bd3200-df3e-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Peek Message =
"06bd3201-df3e-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Send Message =
"06bd3202-df3e-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Receive Journal =
"06bd3203-df3e-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Open Connector Queue =
"b4e60130-df3f-11d1-9c86-006008764d0e"
{
$intCriticalityLevel = 1
}
# Apply Group Policy =
"edacfd8f-ffb3-11d1-b41d-00a0c968f939"
{
$intCriticalityLevel = 1
}
# Add/Remove Replica In Domain =
"9923a32a-3607-11d2-b9be-0000f87a36b2"
{
$intCriticalityLevel = 4
}
# Change Infrastructure Master =
"cc17b1fb-33d9-11d2-97d4-00c04fd8d5cd"
{
$intCriticalityLevel = 4
}
# Update Schema Cache =
"be2bb760-7f46-11d2-b9ad-00c04f79f805"
{
$intCriticalityLevel = 4
}
# Recalculate Security Inheritance =
"62dd28a8-7f46-11d2-b9ad-00c04f79f805"
{
$intCriticalityLevel = 4
}
# Check Stale Phantoms =
"69ae6200-7f46-11d2-b9ad-00c04f79f805"
{
$intCriticalityLevel = 4
}
# Enroll =
"0e10c968-78fb-11d2-90d4-00c04f79dc55"
{
$intCriticalityLevel = 1
}
# Generate Resultant Set of Policy (Planning) =
"b7b1b3dd-ab09-4242-9e30-9980e5d322f7"
{
$intCriticalityLevel = 1
}
# Refresh Group Cache for Logons =
"9432c620-033c-4db7-8b58-14ef6d0bf477"
{
$intCriticalityLevel = 4
}
# Enumerate Entire SAM Domain =
"91d67418-0135-4acc-8d79-c08e857cfbec"
{
$intCriticalityLevel = 4
}
# Generate Resultant Set of Policy (Logging) =
"b7b1b3de-ab09-4242-9e30-9980e5d322f7"
{
$intCriticalityLevel = 1
}
# Create Inbound Forest Trust =
"e2a36dc9-ae17-47c3-b58b-be34c55ba633"
{
$intCriticalityLevel = 4
}
# Replicating Directory Changes All =
"1131f6ad-9c07-11d1-f79f-00c04fc2dcd2"
{
$intCriticalityLevel = 4
}
# Migrate SID History =
"BA33815A-4F93-4c76-87F3-57574BFF8109"
{
$intCriticalityLevel = 4
}
# Reanimate Tombstones =
"45EC5156-DB7E-47bb-B53F-DBEB2D03C40F"
{
$intCriticalityLevel = 4
}
# Allowed to Authenticate =
"68B1D179-0D15-4d4f-AB71-46152E79A7BC"
{
$intCriticalityLevel = 1
}
# Execute Forest Update Script =
"2f16c4a5-b98e-432c-952a-cb388ba33f2e"
{
$intCriticalityLevel = 4
}
# Monitor Active Directory Replication =
"f98340fb-7c5b-4cdb-a00b-2ebdfa115a96"
{
$intCriticalityLevel = 3
}
# Update Password Not Required Bit =
"280f369c-67c7-438e-ae98-1d46f3c6f541"
{
$intCriticalityLevel = 1
}
# Unexpire Password =
"ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501"
{
$intCriticalityLevel = 1
}
# Enable Per User Reversibly Encrypted Password =
"05c74c5e-4deb-43b4-bd9f-86664c2a7fd5"
{
$intCriticalityLevel = 1
}
# Query Self Quota =
"4ecc03fe-ffc0-4947-b630-eb672a8a9dbc"
{
$intCriticalityLevel = 1
}
# Read Only Replication Secret Synchronization =
"1131f6ae-9c07-11d1-f79f-00c04fc2dcd2"
{
$intCriticalityLevel = 4
}
# Reload SSL/TLS Certificate =
"1a60ea8d-58a6-4b20-bcdc-fb71eb8a9ff8"
{
$intCriticalityLevel = 4
}
# Replicating Directory Changes In Filtered Set =
"89e95b76-444d-4c62-991a-0facbeda640c"
{
$intCriticalityLevel = 4
}
# Run Protect Admin Groups Task =
"7726b9d5-a4b4-4288-a6b2-dce952e80a7f"
{
$intCriticalityLevel = 4
}
# Manage Optional Features for Active Directory =
"7c0e2a7c-a419-48e4-a995-10180aad54dd"
{
$intCriticalityLevel = 4
}
# Allow a DC to create a clone of itself =
"3e0f7e18-2c7a-4c10-ba82-4d926db99a3e"
{
$intCriticalityLevel = 4
}
# AutoEnrollment =
"a05b8cc2-17bc-4802-a710-e7c15ab866a2"
{
$intCriticalityLevel = 1
}
# Set Owner of an object during creation. =
"4125c71f-7fac-4ff0-bcb7-f09a41325286"
{
$intCriticalityLevel = 1
}
# Bypass the quota restrictions during creation. =
"88a9933e-e5c8-4f2a-9dd7-2527416b8092"
{
$intCriticalityLevel = 4
}
# Read secret attributes of objects in a Partition. =
"084c93a2-620d-4879-a836-f0ae47de0e89"
{
$intCriticalityLevel = 4
}
# Write secret attributes of objects in a Partition. =
"94825A8D-B171-4116-8146-1E34D8F54401"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 1
}
}
}
}
"GenericAll"
{
If ($objAccess -eq "Allow")
{
Switch ($objInheritanceType)
■ {
"All"
{
Switch ($objObjectType)
{
# Any = 4
"00000000-0000-0000-0000-000000000000"
{
$intCriticalityLevel = 4
}
# Privat-Information = 3
"91e647de-d96f-4b70-9557-d63ff4f3ccd8"
{
$intCriticalityLevel = 3
}
# Password Reset = 4
"00299570-246d-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 3
}
}
}
■ ■ "None"
■■ {
$intCriticalityLevel = 4
}
"Children"
■ {
}
"Descendents"
{
Switch ($objInheritedObjectType)
{
# Any = 4
"00000000-0000-0000-0000-000000000000"
{
$intCriticalityLevel = 4
}
# User = 4
"bf967aba-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Group = 4
"bf967a9c-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Computer = 4
"bf967a86-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# ms-DS-Managed-Service-Account = 4
"ce206244-5827-4a86-ba1c-1c0c386c1b64"
{
$intCriticalityLevel = 4
}
# msDS-Group-Managed-Service-Account = 4
"7b8b558a-93a5-4af7-adca-c017e67f1057"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 3
}
}
}
■ default
■ {
$intCriticalityLevel = 3
}
}#End switch
■}
}
"CreateChild, DeleteChild"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 3
■}
}
"ReadProperty"
{
If ($objAccess -eq "Allow")
{
$intCriticalityLevel = 1
Switch ($objInheritanceType)
{
■ "None"
■ {
}
"Children"
■ {
}
"Descendents"
{
}
■ default
■ {
}
}#End switch
}
}
{$_ -match "WriteProperty"}
{
If ($objAccess -eq "Allow")
{
Switch ($objInheritanceType)
■ {
{($_ -match "All") -or ($_ -match "None")}
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
Switch ($objObjectType)
{
# msDS-KeyCredentialLink = 4
"5b47d60f-6090-40b2-9f37-2a4de88f3063"
{
$intCriticalityLevel = 4
}
# Domain Password & Lockout Policies = 4
"c7407360-20bf-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Public Information = 4
"e48d0154-bcf8-11d1-8702-00c04fb96050"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 1
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
}
default
{
$intCriticalityLevel = 3
}
}#End switch
}
"Children"
■ {
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
Switch ($objObjectType)
{
# Domain Password & Lockout Policies = 4
"c7407360-20bf-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
Switch ($objInheritedObjectType)
{
# User = 4 ,Group = 4,Computer = 4
{($_ -eq "bf967aba-0de6-11d0-a285-00aa003049e2") -or ($_ -eq "bf967a9c-0de6-1
{
Switch ($objObjectType)
{
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
default
{
$intCriticalityLevel = 3
}
}
}
"InheritedObjectAceTypePresent"
{
Switch ($objInheritedObjectType)
{
# User = 4 ,Group = 4,Computer = 4
{($_ -eq "bf967aba-0de6-11d0-a285-00aa003049e2") -or ($_ -eq "bf967a9c-0de6-1
{
Switch ($objObjectType)
{
# All
"00000000-0000-0000-0000-000000000000"
{
$intCriticalityLevel = 4
}
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
default
{
$intCriticalityLevel = 3
}
}
}
"None"
{
Switch ($objObjectType)
{
# All
"00000000-0000-0000-0000-000000000000"
{
$intCriticalityLevel = 4
}
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
default
{
}
}#End switch
}
"Descendents"
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
Switch ($objObjectType)
{
# Domain Password & Lockout Policies = 4
"c7407360-20bf-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
Switch ($objInheritedObjectType)
{
# User = 4 ,Group = 4,Computer = 4
{($_ -eq "bf967aba-0de6-11d0-a285-00aa003049e2") -or ($_ -eq "bf967a9c-0de6-1
{
Switch ($objObjectType)
{
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
default
{
$intCriticalityLevel = 3
}
}
}
"InheritedObjectAceTypePresent"
{
Switch ($objInheritedObjectType)
{
# User = 4 ,Group = 4,Computer = 4
{($_ -eq "bf967aba-0de6-11d0-a285-00aa003049e2") -or ($_ -eq "bf967a9c-0de6-1
{
Switch ($objObjectType)
{
# All
"00000000-0000-0000-0000-000000000000"
{
$intCriticalityLevel = 4
}
# Account Restrictions = 4
"4c164200-20c0-11d0-a768-00aa006e0529"
{
$intCriticalityLevel = 4
}
# Group Membership = 4
"bc0ac240-79a9-11d0-9020-00c04fc2d4cf"
{
$intCriticalityLevel = 4
}
# Email-Information = 0
"E45795B2-9455-11d1-AEBD-0000F80367C1"
{
$intCriticalityLevel = 0
}
# Web-Information = 2
"E45795B3-9455-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# Personal-Information = 2
"77B5B886-944A-11d1-AEBD-0000F80367C1"
{
#If it SELF then = 1
if($objIdentity -eq "NT AUTHORITY\SELF")
{
$intCriticalityLevel = 1
}
else
{
$intCriticalityLevel = 2
}
}
# User-Account-Control = 4
"bf967a68-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
# Service-Principal-Name = 4
"f3a64788-5306-11d1-a9c5-0000f80367c1"
{
$intCriticalityLevel = 4
}
# Is-Member-Of-DL = 4
"bf967991-0de6-11d0-a285-00aa003049e2"
{
$intCriticalityLevel = 4
}
default
{
$intCriticalityLevel = 2
}
}
}
default
{
$intCriticalityLevel = 3
}
}
}
default
{
}
}#End switch
}
■ default
■ {
$intCriticalityLevel = 3
}
}#End switch
}#End if Allow
}
{($_ -match "WriteDacl") -or ($_ -match "WriteOwner")}
{
$intCriticalityLevel = 4
}
default
{
If ($objAccess -eq "Allow")
{
if($objRights -match "Write")
{
$intCriticalityLevel = 2
}
if($objRights -match "Create")
{
$intCriticalityLevel = 3
}
if($objRights -match "Delete")
{
$intCriticalityLevel = 3
}
if($objRights -match "ExtendedRight")
{
$intCriticalityLevel = 3
}
if($objRights -match "WriteDacl")
{
$intCriticalityLevel = 4
}
if($objRights -match "WriteOwner")
{
$intCriticalityLevel = 4
}
}
}
}# End Switch
if($Returns -eq "Filter")
{
if ($intCriticalityLevel -ge $CriticalityFilter)
{
Return $True
}
else
{
Return $false
}
}
else
{
Return $intCriticalityLevel
}
}
#==========================================================================
#==========================================================================
# Function■■: WriteOUT
# Arguments : Security Descriptor, OU dn string, Output htm file or other format
# Returns ■: n/a
# Description : Wites the SD info to a HTM table or other format, it appends info if the file exist
#==========================================================================
function WriteOUT
{
Param([bool] $bolACLExist,$sd,[string]$DSObject,[string]$Canonical,[bool] $OUHeader,[string] $strC
[string]$strSDDL,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
if($Type -eq "HTML")
{
$htm = $true
$fileout = $htmfileout
}
if($HTM)
{
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
if ($bolCriticalityLevel -eq $true)
{
$strLegendColor =@"
bgcolor="#A4A4A4"
"@
}
else
{
$strLegendColor = ""
}
$strLegendColorInfo=@"
bgcolor="#A4A4A4"
"@
$strLegendColorLow =@"
bgcolor="#0099FF"
"@
$strLegendColorMedium=@"
bgcolor="#FFFF00"
"@
$strLegendColorWarning=@"
bgcolor="#FFD700"
"@
$strLegendColorCritical=@"
bgcolor="#DF0101"
"@
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontRights =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
If ($OUHeader -eq $true)
{
if ($GPO)
{
$strHTMLText =@"
$strHTMLText
<TR bgcolor="$strTHOUColor"><TD><b>$strFontOU $GPOdisplayname</b>
"@
}
else
{
$strHTMLText =@"
$strHTMLText
<TR bgcolor="$strTHOUColor">
"@
}
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $DSObject</b>
"@
if ($Canonical)
{
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $Canonical</b>
"@
}
if ($bolObjClass -eq $true)
{
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $strObjClass</b>
"@
}
if ($boolReplMetaDate -eq $true)
{
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $strReplMetaDate</b>
"@
}
if ($boolACLSize -eq $true)
{
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $strACLSize bytes</b>
"@
}
if ($boolOUProtected -eq $true)
{
if ($bolOUProtected -eq $true)
{
$strHTMLText =@"
$strHTMLText
<TD bgcolor="FF0000"><b>$strFontOU $bolOUProtected</b>
"@
}
else
{
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $bolOUProtected</b>
"@
}
}
$strHTMLText =@"
$strHTMLText
</TR>
"@
}
Switch ($strColorTemp)
{
"1"
■{
■$strColor = "DDDDDD"
■$strColorTemp = "2"
■}
"2"
■{
■$strColor = "AAAAAA"
■$strColorTemp = "1"
■}■■
"3"
■{
■$strColor = "FF1111"
}
"4"
■{
■$strColor = "00FFAA"
}
"5"
■{
■$strColor = "FFFF00"
}
■}# End Switch
}#End if HTM
if ($bolACLExist)
{
■$sd | foreach{
if($null -ne $_.AccessControlType)
{
$objAccess = $($_.AccessControlType.toString())
}
else
{
$objAccess = $($_.AuditFlags.toString())
}
■$objFlags = $($_.ObjectFlags.toString())
■$objType = $($_.ObjectType.toString())
$objIsInheried = $($_.IsInherited.toString())
■$objInheritedType = $($_.InheritedObjectType.toString())
■$objRights = $($_.ActiveDirectoryRights.toString())
$objInheritanceType = $($_.InheritanceType.toString())
Switch ($objRights)
{
"Self"
{
#Self right are never express in gui it's a validated write ( 0x00000008 ACTRL_DS_SELF)
$objRights = ""
}
"GenericRead"
{
$objRights = "Read Permissions,List Contents,Read All Properties,List"
}
"CreateChild"
{
$objRights = "Create"■
}
"DeleteChild"
{
$objRights = "Delete Child"■■
}
"GenericAll"
{
$objRights = "Full Control"■■
}
"CreateChild, DeleteChild"
{
$objRights = "Create/Delete"■■
}
"ReadProperty"
{
Switch ($objInheritanceType)
■ {
■ ■ "None"
■■ {
Switch ($objFlags)
■ ■ {
■■ ■ "ObjectAceTypePresent"
{
$objRights = "Read"■
}
■■ ■ "ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Read"■
}
default
■■ {$objRights = "Read All Properties"■}
}#End switch
}
"Children"
■■ {
Switch ($objFlags)
■ ■ {
■■ ■ "ObjectAceTypePresent"
{
$objRights = "Read"■
}
■■ ■ "ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Read"■
}
default
■■ {$objRights = "Read All Properties"■}
}#End switch
}
"Descendents"
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Read"■
}
■
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Read"■
}
default
{$objRights = "Read All Properties"■}
}#End switch
}
default
{$objRights = "Read All Properties"■}
}#End switch
}
"ReadProperty, WriteProperty"
{
$objRights = "Read All Properties;Write All Properties"■■■
}
"WriteProperty"
{
Switch ($objInheritanceType)
■ {
■ ■ "None"
■■ {
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Write"■
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Write"■
}
default
{
$objRights = "Write All Properties"■
}
}#End switch
}
"Children"
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Write"■
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Write"■
}
default
{
$objRights = "Write All Properties"■
}
}#End switch
}
"Descendents"
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Write"■
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Write"■
}
default
{
$objRights = "Write All Properties"■
}
}#End switch
}
default
{
$objRights = "Write All Properties"
}
}#End switch■■
}
default
{
}
}# End Switch
if($bolShowCriticalityColor)
{
$intCriticalityValue = Get-Criticality -Returns "Color" $_.IdentityReference.toString() $_.ActiveDirec
Switch ($intCriticalityValue)
{
0 {$strLegendText = "Info";$strLegendColor = $strLegendColorInfo}
1 {$strLegendText = "Low";$strLegendColor = $strLegendColorLow}
2 {$strLegendText = "Medium";$strLegendColor = $strLegendColorMedium}
3 {$strLegendText = "Warning";$strLegendColor = $strLegendColorWarning}
4 {$strLegendText = "Critical";$strLegendColor = $strLegendColorCritical}
}
$strLegendTextVal = $strLegendText
if($intCriticalityValue -gt $global:intShowCriticalityLevel)
{
$global:intShowCriticalityLevel = $intCriticalityValue
}
}
■$IdentityReference = $($_.IdentityReference.toString())
If ($IdentityReference.contains("S-1-"))
■{
$strNTAccount = ConvertSidToName -server $global:strDomainLongName -Sid $IdentityReferenc
■}
else
{
$strNTAccount = $IdentityReference
}
Switch ($strColorTemp)
{
"1"
■{
■$strColor = "DDDDDD"
■$strColorTemp = "2"
■}
■"2"
■{
■$strColor = "AAAAAA"
■$strColorTemp = "1"
■}■■
"3"
■{
■$strColor = "FF1111"
}
"4"
■{
■$strColor = "00FFAA"
}
"5"
■{
■$strColor = "FFFF00"
}
■}# End Switch
■ Switch ($objInheritanceType)
■{
■ ■"All"
■ ■{
■ ■■Switch ($objFlags)
■ ■{
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "This object and all child objects"
$strPerm = "$objRights $(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatc
■■ ■} ■
■■ ■"ObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "This object and all child objects"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■} ■ ■
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo ="This object and all child objects"
$strPerm = "$objRights"
■■ ■}
■■ ■■default
■ ■■ {
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 1K"
■■ ■} ■
■
■■ }# End Switch
■ ■■
■ ■}
■ ■"Descendents"
■ ■{
■
■ ■■Switch ($objFlags)
■ ■{
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■ $strApplyTo = "Descendant $(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMa
$strPerm = "$objRights"
■■ ■}
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "Child Objects Only"
$strPerm = "$objRights"
■■ ■} ■ ■
■■ ■"ObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "Child Objects Only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo =■"$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm =■"$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■default
■ ■■■{
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 2K"
■■ ■} ■
■
■■ } ■■
■ ■}
■ ■"None"
■ ■{
■ ■■Switch ($objFlags)
■ ■{
■■ ■"ObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "This Object Only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "This Object Only"
$strPerm = "$objRights"
■■ ■}
■■ ■■default
■ ■■ {
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 4K"
■■ ■} ■
■
■■■}
■ ■}
■ ■"SelfAndChildren"
■ ■{
■ ■ ■■Switch ($objFlags)
■ ■{
■■ ■"ObjectAceTypePresent"
■ ■■{
■■ ■■$strApplyTo = "This object and all child objects within this container only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "This object and all child objects within this container only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatch
■■ ■}
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■} ■ ■
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "This object and all child objects"
$strPerm = "$objRights"
■■ ■} ■
■■ ■default
■ ■■ {
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 5K"
■■ ■} ■
■
■■■} ■
■ ■} ■
■ ■"Children"
■ ■{
■ ■ ■■Switch ($objFlags)
■ ■{
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "Descendant $(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMa
$strPerm = "$objRights"
■■ ■}
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "Children within this container only"
$strPerm = "$objRights"
■■ ■} ■ ■
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■ ■■{
■■ ■■$strApplyTo = "$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm = "$(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingName -strGUIDA
■■ ■} ■
■■ ■"ObjectAceTypePresent"
■ ■■{
■■ ■■$strApplyTo = "Children within this container only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■} ■■ ■
■■ ■default
■ ■■■{
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 6K"
■■ ■} ■
■
■ ■■}
■ ■}
■ ■default
■ ■{
■■ $strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 7K"
■■} ■
■}# End Switch
##
if($Type -eq "Object")
{
$objhashtableACE = [pscustomobject][ordered]@{
Object = $DSObject ;`
ObjectClass = $strObjClass}
if($strSDDL)
{
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "SDDL" -Value $
}
else
{
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "IdentityReferen
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "Trustee" -Value
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "Access" -Value
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "Inherited" -Valu
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "Apply To" -Valu
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "Permission" -Va
}
if($Canonical)
{
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "CanonicalName
$objhashtableACE = $objhashtableACE | Select-Object -Property Object,CanonicalName,* -Error
}
if($GPO)
{
add-member -InputObject $objhashtableACE -MemberType NoteProperty -Name "GPO" -Value $G
$objhashtableACE = $objhashtableACE | Select-Object -Property GPO,* -ErrorAction SilentlyCon
}
if($boolOUProtected)
{
$objhashtableACE | Add-Member NoteProperty "Inheritance Disabled" $bolOUProtected.toString()
}
if($boolReplMetaDate)
{
$objhashtableACE | Add-Member NoteProperty "Security Descriptor Modified" $strReplMetaDate
}
if($CompareMode)
{
$objhashtableACE | Add-Member NoteProperty State $($_.State.toString())
}
if ($bolCriticalityLevel -or $bolShowCriticalityColor)
{
$objhashtableACE | Add-Member NoteProperty 'Criticality Level' $strLegendTextVal
}
[VOID]$global:ArrayAllACE.Add($objhashtableACE)
}
If($HTM)
{
if ($GPO)
{
$strACLHTMLText =@"
$strACLHTMLText
<TR bgcolor="$strColor"><TD>$strFont $GPOdisplayname</TD>
"@
}
else
{
$strACLHTMLText =@"
$strACLHTMLText
<TR bgcolor="$strColor">
"@
}
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $DSObject</TD>
"@
if ($Canonical)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $Canonical</TD>
"@
}
if ($bolObjClass -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strObjClass</TD>
"@
}
if ($boolReplMetaDate -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strReplMetaDate</TD>
"@
}
if ($boolACLSize -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strACLSize bytes</TD>
"@
}
if ($boolOUProtected -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $bolOUPRotected </TD>
"@
}
if($strSDDL)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strSDDL</TD>
"@
}
else
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont <a href="#web" onclick="GetGroupDN('$strNTAccount')">$strNTAccount</a></TD>
<TD>$strFont $objAccess</TD>
<TD>$strFont $objIsInheried </TD>
<TD>$strFont $strApplyTo</TD>
<TD $strLegendColor>$strFontRights $strPerm</TD>
"@
}
if($CompareMode)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $($_.State.toString())</TD>
"@
}
if ($bolCriticalityLevel -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD $strLegendColor>$strFont $strLegendTextVal</TD>
"@
}
}#End If HTM
}# End Foreach
■
}
else
{
if($HTM)
{
if ($OUHeader -eq $false)
{
if ($FilterMode)
{
if ($boolReplMetaDate -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strReplMetaDate</TD>
"@
}
if ($boolACLSize -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strACLSize bytes</TD>
"@
}
if ($boolOUProtected -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $bolOUPRotected </TD>
"@
}
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont No Matching Permissions Set</TD>
"@
if ($bolCriticalityLevel -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD $strLegendColor>$strFont $strLegendTextVal</TD>
"@
}
}
else
{
if ($boolReplMetaDate -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strReplMetaDate</TD>
"@
}
if ($boolACLSize -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strACLSize bytes</TD>
"@
}
if ($boolOUProtected -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $bolOUPRotected </TD>
"@
}
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont No Permissions Set</TD>
"@
if ($bolCriticalityLevel -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD $strLegendColor>$strFont $strLegendTextVal</TD>
"@
}
}# End If
}#end If OUHeader false
}#End if HTM
} #End if bolACLExist
if($HTM)
{
$strACLHTMLText =@"
$strACLHTMLText
</TR>
"@
#end ifelse OUHEader
$strHTMLText = $strHTMLText + $strACLHTMLText
Out-File -InputObject $strHTMLText -Append -FilePath $fileout
Out-File -InputObject $strHTMLText -Append -FilePath $strFileHTM
$strHTMLText = $null
$strACLHTMLText = $null
Remove-Variable -Name "strHTMLText"
Remove-Variable -Name "strACLHTMLText"
}#End if HTM
}
#==========================================================================
# Function■■: WriteDefSDAccessHTM
# Arguments : Security Descriptor, OU dn string, Output htm file
# Returns ■: n/a
# Description : Wites the SD info to a HTM table, it appends info if the file exist
#==========================================================================
function WriteDefSDAccessHTM
{
Param([bool]$bolACLExist, $sd, [bool]$bolObjClass,[string]$strObjectClass, [string]$strColorTemp,[s
if($Type -eq "HTML")
{
$htm = $true
$fileout = $htmfileout
}
if($Type -eq "EXCEL")
{
$EXCEL = $true
$fileout = $xlsxout
}
if($HTM)
{
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
if ($bolCriticalityLevel -eq $true)
{
$strLegendColor =@"
bgcolor="#A4A4A4"
"@
}
else
{
$strLegendColor = ""
}
$strLegendColorInfo=@"
bgcolor="#A4A4A4"
"@
$strLegendColorLow =@"
bgcolor="#0099FF"
"@
$strLegendColorMedium=@"
bgcolor="#FFFF00"
"@
$strLegendColorWarning=@"
bgcolor="#FFD700"
"@
$strLegendColorCritical=@"
bgcolor="#DF0101"
"@
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontRights =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
If ($OUHeader -eq $true)
{
$strHTMLText =@"
$strHTMLText
<TR bgcolor="$strTHOUColor">
"@
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $strObjectClass</b>
"@
if ($boolReplMetaDate -eq $true)
{
$strHTMLText =@"
$strHTMLText
<TD><b>$strFontOU $strReplMetaDate</b>
<TD><b>$strFontOU $strReplMetaVer</b>
"@
}
$strHTMLText =@"
$strHTMLText
</TR>
"@
}
Switch ($strColorTemp)
{
"1"
■{
■$strColor = "DDDDDD"
■$strColorTemp = "2"
■}
"2"
■{
■$strColor = "AAAAAA"
■$strColorTemp = "1"
■}■■
"3"
■{
■$strColor = "FF1111"
}
"4"
■{
■$strColor = "00FFAA"
}
"5"
■{
■$strColor = "FFFF00"
}
■}# End Switch
}#End if HTM
if ($bolACLExist)
{
■$sd | foreach{
if($null -ne $_.AccessControlType)
{
$objAccess = $($_.AccessControlType.toString())
}
else
{
$objAccess = $($_.AuditFlags.toString())
}
■$objFlags = $($_.ObjectFlags.toString())
■$objType = $($_.ObjectType.toString())
$objIsInheried = $($_.IsInherited.toString())
■$objInheritedType = $($_.InheritedObjectType.toString())
■$objRights = $($_.ActiveDirectoryRights.toString())
$objInheritanceType = $($_.InheritanceType.toString())
Switch ($objRights)
{
"Self"
{
#Self right are never express in gui it's a validated write ( 0x00000008 ACTRL_DS_SELF)
$objRights = ""
}
"GenericRead"
{
$objRights = "Read Permissions,List Contents,Read All Properties,List"
}
"CreateChild"
{
$objRights = "Create"■
}
"DeleteChild"
{
$objRights = "Delete Child"■■
}
"GenericAll"
{
$objRights = "Full Control"■■
}
"CreateChild, DeleteChild"
{
$objRights = "Create/Delete"■■
}
"ReadProperty"
{
Switch ($objInheritanceType)
■ {
■ ■ "None"
■■ {
Switch ($objFlags)
■ ■ {
■■ ■ "ObjectAceTypePresent"
{
$objRights = "Read"■
}
■■ ■ "ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Read"■
}
default
■■ {$objRights = "Read All Properties"■}
}#End switch
}
"Children"
■■ {
Switch ($objFlags)
■ ■ {
■■ ■ "ObjectAceTypePresent"
{
$objRights = "Read"■
}
■■ ■ "ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Read"■
}
default
■■ {$objRights = "Read All Properties"■}
}#End switch
}
"Descendents"
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Read"■
}
■
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Read"■
}
default
{$objRights = "Read All Properties"■}
}#End switch
}
default
{$objRights = "Read All Properties"■}
}#End switch
}
"ReadProperty, WriteProperty"
{
$objRights = "Read All Properties;Write All Properties"■■■
}
"WriteProperty"
{
Switch ($objInheritanceType)
■ {
■ ■ "None"
■■ {
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Write"■
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Write"■
}
default
{
$objRights = "Write All Properties"■
}
}#End switch
}
"Children"
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Write"■
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Write"■
}
default
{
$objRights = "Write All Properties"■
}
}#End switch
}
"Descendents"
{
Switch ($objFlags)
{
"ObjectAceTypePresent"
{
$objRights = "Write"■
}
"ObjectAceTypePresent, InheritedObjectAceTypePresent"
{
$objRights = "Write"■
}
default
{
$objRights = "Write All Properties"■
}
}#End switch
}
default
{
$objRights = "Write All Properties"
}
}#End switch■■
}
default
{
}
}# End Switch
if($bolShowCriticalityColor)
{
$intCriticalityValue = Get-Criticality -Returns "Color" $_.IdentityReference.toString() $_.ActiveDirec
Switch ($intCriticalityValue)
{
0 {$strLegendText = "Info";$strLegendColor = $strLegendColorInfo}
1 {$strLegendText = "Low";$strLegendColor = $strLegendColorLow}
2 {$strLegendText = "Medium";$strLegendColor = $strLegendColorMedium}
3 {$strLegendText = "Warning";$strLegendColor = $strLegendColorWarning}
4 {$strLegendText = "Critical";$strLegendColor = $strLegendColorCritical}
}
$strLegendTextVal = $strLegendText
if($intCriticalityValue -gt $global:intShowCriticalityLevel)
{
$global:intShowCriticalityLevel = $intCriticalityValue
}
}
■$IdentityReference = $($_.IdentityReference.toString())
If ($IdentityReference.contains("S-1-"))
■{
■ $strNTAccount = ConvertSidToName -server $global:strDomainLongName -Sid $IdentityReference -
■}
else
{
$strNTAccount = $IdentityReference
}
Switch ($strColorTemp)
{
"1"
■{
■$strColor = "DDDDDD"
■$strColorTemp = "2"
■}
■"2"
■{
■$strColor = "AAAAAA"
■$strColorTemp = "1"
■}■■
"3"
■{
■$strColor = "FF1111"
}
"4"
■{
■$strColor = "00FFAA"
}
"5"
■{
■$strColor = "FFFF00"
}
■}# End Switch
■ Switch ($objInheritanceType)
■{
■ ■"All"
■ ■{
■ ■■Switch ($objFlags)
■ ■{
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "This object and all child objects"
$strPerm = "$objRights $(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatc
■■ ■} ■
■■ ■"ObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "This object and all child objects"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■} ■ ■
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo ="This object and all child objects"
$strPerm = "$objRights"
■■ ■}
■■ ■■default
■ ■■ {
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 1K"
■■ ■} ■
■
■■ }# End Switch
■ ■■
■ ■}
■ ■"Descendents"
■ ■{
■
■ ■■Switch ($objFlags)
■ ■{
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■ $strApplyTo = "$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm = "$objRights"
■■ ■}
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "Child Objects Only"
$strPerm = "$objRights"
■■ ■} ■ ■
■■ ■"ObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "Child Objects Only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo =■"$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm =■"$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■default
■ ■■■{
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 2K"
■■ ■} ■
■
■■ } ■■
■ ■}
■ ■"None"
■ ■{
■ ■■Switch ($objFlags)
■ ■{
■■ ■"ObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "This Object Only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "This Object Only"
$strPerm = "$objRights"
■■ ■}
■■ ■■default
■ ■■ {
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 4K"
■■ ■} ■
■
■■■}
■ ■}
■ ■"SelfAndChildren"
■ ■{
■ ■ ■■Switch ($objFlags)
■ ■{
■■ ■"ObjectAceTypePresent"
■ ■■{
■■ ■■$strApplyTo = "This object and all child objects within this container only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■}
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "Children within this container only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatch
■■ ■}
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■} ■ ■
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "This object and all child objects"
$strPerm = "$objRights"
■■ ■} ■
■■ ■default
■ ■■ {
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 5K"
■■ ■} ■
■
■■■} ■
■ ■} ■
■ ■"Children"
■ ■{
■ ■ ■■Switch ($objFlags)
■ ■{
■■ ■"InheritedObjectAceTypePresent"
■■ ■{
■■ ■■$strApplyTo = "Children within this container only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatch
■■ ■}
■■ ■"None"
■■ ■{
■■ ■■$strApplyTo = "Children within this container only"
$strPerm = "$objRights"
■■ ■} ■ ■
■■ ■"ObjectAceTypePresent, InheritedObjectAceTypePresent"
■ ■■{
■■ ■■$strApplyTo = "$(if($bolTranslateGUID){$objInheritedType}else{MapGUIDToMatchingName
$strPerm = "$(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingName -strGUIDA
■■ ■} ■
■■ ■"ObjectAceTypePresent"
■ ■■{
■■ ■■$strApplyTo = "Children within this container only"
$strPerm = "$objRights $(if($bolTranslateGUID){$objType}else{MapGUIDToMatchingNam
■■ ■} ■■ ■
■■ ■default
■ ■■■{
■■ ■■$strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 6K"
■■ ■} ■
■
■ ■■}
■ ■}
■ ■default
■ ■{
■■ $strApplyTo = "Error"
$strPerm = "Error: Failed to display permissions 7K"
■■} ■
■}# End Switch
If($Excel)
{
$objhashtableACE = [pscustomobject][ordered]@{
ObjectClass = $strObjectClass}
if($boolReplMetaDate)
{
$objhashtableACE | Add-Member NoteProperty "Security Descriptor Modified" $strReplMetaDate
$objhashtableACE | Add-Member NoteProperty "Version" $strReplMetaVer
}
$objhashtableACE | Add-Member NoteProperty "IdentityReference" $IdentityReference.toString()
$objhashtableACE | Add-Member NoteProperty "Trustee" $strNTAccount.toString()
$objhashtableACE | Add-Member NoteProperty "Access" $objAccess.toString()
$objhashtableACE | Add-Member NoteProperty "Inherited" $objIsInheried.toString()
$objhashtableACE | Add-Member NoteProperty "Apply To" $strApplyTo.toString()
$objhashtableACE | Add-Member NoteProperty "Permission" $strPerm.toString()
if($boolOUProtected)
{
$objhashtableACE | Add-Member NoteProperty "Inheritance Disabled" $bolOUProtected.toString()
}
if ($bolCriticalityLevel -eq $true)
{
$objhashtableACE | Add-Member NoteProperty "Criticality Level" $strLegendTextVal.toString()
}
if($CompareMode)
{
$objhashtableACE | Add-Member NoteProperty State $($_.State.toString())
}
[VOID]$global:ArrayAllACE.Add($objhashtableACE)
}
If($HTM)
{
$strACLHTMLText =@"
$strACLHTMLText
<TR bgcolor="$strColor">
"@
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strObjectClass</TD>
"@
if ($boolReplMetaDate -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strReplMetaDate</TD>
<TD>$strFont $strReplMetaVer</TD>
"@
}
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont <a href="#web" onclick="GetGroupDN('$strNTAccount')">$strNTAccount</a></TD>
<TD>$strFont $objAccess</TD>
<TD>$strFont $objIsInheried </TD>
<TD>$strFont $strApplyTo</TD>
<TD $strLegendColor>$strFontRights $strPerm</TD>
"@
if($CompareMode)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $($_.State.toString())</TD>
"@
}
if ($bolCriticalityLevel -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD $strLegendColor>$strFont $strLegendTextVal</TD>
"@
}
}#End If HTM
}# End Foreach
■
}
else
{
if($HTM)
{
if ($OUHeader -eq $false)
{
if ($FilterMode)
{
if ($boolReplMetaDate -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strReplMetaDate</TD>
"@
}
if ($boolACLSize -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strACLSize bytes</TD>
"@
}
if ($boolOUProtected -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $bolOUPRotected </TD>
"@
}
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont No Matching Permissions Set</TD>
"@
if ($bolCriticalityLevel -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD $strLegendColor>$strFont $strLegendTextVal</TD>
"@
}
}
else
{
if ($boolReplMetaDate -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strReplMetaDate</TD>
"@
}
if ($boolACLSize -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $strACLSize bytes</TD>
"@
}
if ($boolOUProtected -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont $bolOUPRotected </TD>
"@
}
$strACLHTMLText =@"
$strACLHTMLText
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont N/A</TD>
<TD>$strFont No Permissions Set</TD>
"@
if ($bolCriticalityLevel -eq $true)
{
$strACLHTMLText =@"
$strACLHTMLText
<TD $strLegendColor>$strFont $strLegendTextVal</TD>
"@
}
}# End If
}#end If OUHeader false
}#End if HTM
} #End if bolACLExist
if($HTM)
{
$strACLHTMLText =@"
$strACLHTMLText
</TR>
"@
#end ifelse OUHEader
$strHTMLText = $strHTMLText + $strACLHTMLText
Out-File -InputObject $strHTMLText -Append -FilePath $fileout
Out-File -InputObject $strHTMLText -Append -FilePath $strFileHTM
$strHTMLText = $null
$strACLHTMLText = $null
Remove-Variable -Name "strHTMLText"
Remove-Variable -Name "strACLHTMLText"
}#End if HTM
}
#==========================================================================
# Function■■: InitiateDefSDAccessHTM
# Arguments : Output htm file
# Returns ■: n/a
# Description : Wites base HTM table syntax, it appends info if the file exist
#==========================================================================
Function InitiateDefSDAccessHTM
{
Param([string] $htmfileout,
[string]$strStartingPoint,
$RepMetaDate,
[bool]$bolCompare,
[string] $strComparefile,
[bool]$bolCriticaltiy)
$strACLTypeHeader = "Access"
If($bolCompare)
{
$strHTMLText =@"
<h1 style="color: #79A0E0;text-align: center;">Default Security Descriptor COMPARE REPORT - $($st
<h3 style="color: #191010;text-align: center;">
Template: $strComparefile
</h3>
"@
}
else
{
$strHTMLText =@"
<h1 style="color: #79A0E0;text-align: center;">Default Security Descriptor REPORT - $($strStartingPoin
"@
}
$strHTMLText =@"
$strHTMLText
<TABLE BORDER=1>
"@
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH ObjectClass</font></th>
"@
if ($RepMetaDate -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Security Descriptor Modified</font><th bgcolor="$strTHColor">$
"@
}
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Trustee</font></th><th bgcolor="$strTHColor">$strFontTH $str
"@
if ($bolCompare -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH State</font></th>
"@
}
if ($bolCriticaltiy -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Criticality Level</font></th>
"@
}
Out-File -InputObject $strHTMLText -Append -FilePath $htmfileout
$strHTMLText = $null
$strTHOUColor = $null
$strTHColor = $null
Remove-Variable -Name "strHTMLText"
Remove-Variable -Name "strTHOUColor"
Remove-Variable -Name "strTHColor"
}
#==========================================================================
# Function■■: InitiateHTM
# Arguments : Output htm file
# Returns ■: n/a
# Description : Wites base HTM table syntax, it appends info if the file exist
#==========================================================================
Function InitiateHTM
{
Param([string] $htmfileout,[string]$strStartingPoint,[string]$strDN,[bool]$RepMetaDate ,[bool]$ACLSi
If($rdbSACL.IsChecked)
{
$strACLTypeHeader = "Audit"
}
else
{
$strACLTypeHeader = "Access"
}
If($bolCompare)
{
$strHTMLText =@"
<h1 style="color: #79A0E0;text-align: center;">COMPARE REPORT - $($strStartingPoint.ToUpper())</h
<h3 style="color: #191010;text-align: center;">
Template: $strComparefile
</h3>
"@
}
else
{
If($bolFilter)
{
$strHTMLText =@"
<h1 style="color: #79A0E0;text-align: center;">FILTERED REPORT - $($strStartingPoint.ToUpper())</h
"@
}
else
{
If($bolEffectiveRights)
{
$strHTMLText =@"
<h1 style="color: #79A0E0;text-align: center;">EFFECTIVE RIGHTS REPORT <br>
Service Principal: $($global:strEffectiveRightAccount.ToUpper())</h1>
"@
}
else
{
$strHTMLText =@"
<h1 style="color: #79A0E0;text-align: center;">ACL REPORT - $($strStartingPoint.ToUpper())</h1>
"@
}
}
}
If($bolCriticaltiy)
{
$strHTMLText =@"
$strHTMLText
<div style="text-align: center;font-weight: bold}">
<FONT size="6" color= "#79A0E0">Highest Criticality Level:</FONT> 20141220T02111105659400201
</div>
"@
}
$strHTMLText =@"
$strHTMLText
<h3 style="color: #191010;text-align: center;">$strDN<br>
Report Created: $(get-date -uformat "%Y-%m-%d %H:%M:%S")</h3>
"@
If($SkipDefACE)
{
$strHTMLText =@"
$strHTMLText
<h3 style="color: #191010;text-align: center;">Default permissions excluded</h3>
"@
}
If($SkipProtectDelACE)
{
$strHTMLText =@"
$strHTMLText
<h3 style="color: #191010;text-align: center;">Protected against accidental deletions permissions exclu
"@
}
$strHTMLText =@"
$strHTMLText
<TABLE BORDER=1>
"@
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
if ($GPO)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH GPO</font>
"@
}
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Object</font></th>
"@
if ($bolCanonical -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH CanonicalName</font>
"@
}
if ($bolObjType -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH ObjectClass</font>
"@
}
if ($RepMetaDate -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Security Descriptor Modified</font>
"@
}
if ($ACLSize -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH DACL Size</font>
"@
}
if ($bolACEOUProtected -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Inheritance Disabled</font>
"@
}
if($SDDL)
{
$strHTMLText =@"
$strHTMLText
</th><th bgcolor="$strTHColor">$strFontTH SDDL</font></th>
"@
}
else
{
$strHTMLText =@"
$strHTMLText
</th><th bgcolor="$strTHColor">$strFontTH Trustee</font></th><th bgcolor="$strTHColor">$strFontTH
"@
}
if ($bolCompare -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH State</font></th>
"@
}
if ($bolCriticaltiy -eq $true)
{
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Criticality Level</font></th>
"@
}
Out-File -InputObject $strHTMLText -Append -FilePath $htmfileout
$strHTMLText = $null
$strTHOUColor = $null
$strTHColor = $null
Remove-Variable -Name "strHTMLText"
Remove-Variable -Name "strTHOUColor"
Remove-Variable -Name "strTHColor"
}
#==========================================================================
# Function■■: CreateHTA
# Arguments : OU Name, Ou put HTA file
# Returns ■: n/a
# Description : Initiates a base HTA file with Export(Save As),Print and Exit buttons.
#==========================================================================
function CreateHTA
{
Param([string]$NodeName,[string]$htafileout,[string]$htmfileout,[string] $folder,[string] $strDomainDN
$strHTAText =@"
<html>
<head>
<hta:Application ID="hta"
ApplicationName="Report">
<title>Report on $NodeName</title>
<script type="text/vbscript">
Dim i
Dim strGroupMemberList
Dim dicSeenGroupMember
Dim strBGColor
Dim strBG1
Dim strBG2
Dim MaxResult
MaxResult = 500
set dicSeenGroupMember = CreateObject("Scripting.Dictionary")
i=0
strBG1 = "bgcolor=#AAAAAA"
strBG2 = "bgcolor=#DDDDDD"
Function ListMembers (strGroupADsPath, dicSeenGroupMember, strRDN)
Dim objGroup, objMember
set objGroup = GetObject(strGroupADsPath)
for each objMember In objGroup.Members
if i < MaxResult Then
■ If strGroupMemberList = "" Then
■■ strBGColor = strBG1
■■ strGroupMemberList = "<TR "&strBGColor&"><TD>" & objMember.Get("cn") & "</TD><TD>" & ob
■ Else
■■ If strBGColor = strBG1 Then
■■■ strBGColor = strBG2
■■ Else
■■■ strBGColor = strBG1
■■ End If
■ strGroupMemberList = strGroupMemberList & vbCrlf & "<TR "&strBGColor&"><TD>" & objMember
■ End If
i=i+1
if objMember.Class = "group" then
if dicSeenGroupMember.Exists(objMember.ADsPath) then
else
dicSeenGroupMember.Add objMember.ADsPath, 1
ListMembers objMember.ADsPath, dicSeenGroupMember, strRDN
end if
end if
else
if Not i > MaxResult Then
strGroupMemberList = strGroupMemberList & vbCrlf & "<TR "&strBGColor&"><TD>Reached Max
end if
i=i+1
exit for
end if
next
End Function
Sub DisplayMembers(strMemberTable,strGroupName,strGroupDN)
On Error Resume Next
Dim objDialogWindow
dim wshShell
Set objDialogWindow = window.Open("about:blank","AboutWindow","height=400,width=800,left=100,to
objDialogWindow.Focus()
strHTML = "<html><title>Direct Members</title>" &_
"<body>" &_
"<h1 style='color: #79A0E0;text-align: center;'>" & strGroupName &"</h1>" &_
"<h3 style='color: #191010;text-align: center;'>" & strGroupDN &"</h3>"
if Not strMemberTable = "" Then
strHTML = strHTML & "<TABLE BORDER=1>" &_
"<th bgcolor=#EFAC00> Member</th><th bgcolor=#EFAC00>DN</th>" &_
strMemberTable &_
"</table></body></html>"
else
strHTML = strHTML &"<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAA
TkSuQmCC' />" &_
"</body></html>"
end if
objDialogWindow.document.write strHTML
End Sub
Function GetGroupDN(strRDN)
Dim oConnection
Dim oRecordset
Dim oCmd
Dim strQuery
Set oConnection = CreateObject("ADODB.Connection")
Set oRecordset = CreateObject("ADODB.Recordset")
Set oCmd = CReateObject("ADODB.Command")
oConnection.Provider = "ADsDSOObject"
oConnection.Open "ADs Provider"
Set oCmd.ActiveConnection = oConnection
oCmd.Properties("Page Size") = 20
strGroupText = Split(strRDN,"\")
If (ubound(strGroupText) > 0) Then
■strRDN = strGroupText(1)
End IF
strQuery = "<LDAP://$strDC/$strDomainDN>;(&(samaccountname="&strRDN&")(|(objectClass=group)(
oCmd.CommandText = strQuery
Set oRecordSet = oCmd.Execute
If oRecordset.EOF And oRecordset.BOF Then
■■MsgBox "Could not find group"
Else
■While Not oRecordset.EOF
■■GetGroupDN = oRecordset.Fields("distinguishedName")
Set objGroupAD = GetObject("LDAP://" & GetGroupDN)
■■oRecordset.MoveNext
i=0
strGroupMemberList = ""
if objGroupAD.Class = "group" Then
strRDN = "MEMBERS OF - " & strRDN
ListMembers "LDAP://" & GetGroupDN, dicSeenGroupMember, strRDN
If Not i = 0 Then
■ DisplayMembers strGroupMemberList,strRDN,GetGroupDN
Else
strGroupMemberList = "<TR "&strBGColor&"><TD>Group Empty</TD><TD></TD></TR>"
DisplayMembers strGroupMemberList,strRDN,GetGroupDN
End IF■
else
strRDN = "User Object - " & strRDN
■ DisplayMembers strGroupMemberList,strRDN,GetGroupDN
end if
■Wend
End If
Set oConnection = Nothing
Set oRecordset = Nothing
Set oCmd = Nothing
End Function
Sub ExportToCSV()
Dim objFSO,objFile,objNewFile,oShell,oEnv
Set oShell=CreateObject("wscript.shell")
Set oEnv=oShell.Environment("System")
strTemp=oShell.ExpandEnvironmentStrings("%USERPROFILE%")
strTempFile="$htmfileout"
strOutputFolder="$folder"
strFile=SaveAs("$NodeName.htm",strOutputFolder)
If strFile="" Then Exit Sub
Set objFSO=CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile strTempFile,strFile, true
MsgBox "Finished exporting to " & strFile,vbOKOnly+vbInformation,"Export"
End Sub
Function SaveAs(strFile,strOutFolder)
Dim objDialog
SaveAs=InputBox("Enter the filename and path."&vbCrlf&vbCrlf&"Example: "&strOutFolder&"\CONTOS
End Function
</script>
</head>
<body>
<input type="button" value="Export" onclick="ExportToCSV" tabindex="9">
<input id="print_button" type="button" value="Print" name="Print_button" class="Hide" onClick="Window
<input type="button" value="Exit" onclick=self.close name="B3" tabindex="1" class="btn">
"@
Out-File -InputObject $strHTAText -Force -FilePath $htafileout
}
#==========================================================================
# Function■■: WriteSPNHTM
# Arguments : Security Principal Name, Output htm file
# Returns ■: n/a
# Description : Wites the account membership info to a HTM table, it appends info if the file exist
#==========================================================================
function WriteSPNHTM
{
Param([string] $strSPN,$tokens,[string]$objType,[int]$intMemberOf,[string] $strColorTemp,[string] $h
#$strHTMLText ="<TABLE BORDER=1>"
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
$strHTMLText =@"
$strHTMLText
<TR bgcolor="$strTHOUColor"><TD><b>$strFontOU $strSPN</b><TD><b>$strFontOU $objType</b><
"@
$strHTMLText =@"
$strHTMLText
<TR bgcolor="$strTHColor"><TD><b>$strFontTH Groups</b></TD><TD></TD><TD></TD></TR>
"@
$tokens | foreach{
If ($_.contains("S-1-"))
{
■$strNTAccount = ConvertSidToName -server $global:strDomainLongName -Sid $_ -CREDS $CREDS
}
if ($($strNTAccount.toString()) -ne $strSPN)
{
Switch ($strColorTemp)
{
"1"
■{
■$strColor = "DDDDDD"
■$strColorTemp = "2"
■}
"2"
■{
■$strColor = "AAAAAA"
■$strColorTemp = "1"
■}■■
"3"
■{
■$strColor = "FF1111"
}
"4"
■{
■$strColor = "00FFAA"
}
"5"
■{
■$strColor = "FFFF00"
}
■}# End Switch
$strGroupText=$strGroupText+@"
<TR bgcolor="$strColor"><TD>
$strFont $($strNTAccount.toString())</TD></TR>
"@
}
}
$strHTMLText = $strHTMLText + $strGroupText
Out-File -InputObject $strHTMLText -Append -FilePath $htafileout
Out-File -InputObject $strHTMLText -Append -FilePath $htmfileout
$strHTMLText = ""
}
#==========================================================================
# Function■■: WriteDefSDSDDLHTM
# Arguments : Security Principal Name, Output htm file
# Returns ■: n/a
# Description : Wites the account membership info to a HTM table, it appends info if the file exist
#==========================================================================
function WriteDefSDSDDLHTM
{
Param([string] $strColorTemp,[string] $htafileout,[string] $htmfileout,[string]$strObjectClass,[string]$s
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
$strHTMLText =@"
$strHTMLText
<TR bgcolor="$strTHOUColor"><TD><b>$strFontOU $strObjectClass</b>
<TD><b>$strFontOU $strDefSDVer</b>
<TD><b>$strFontOU $strDefSDDate</b>
"@
$strHTMLText =@"
$strHTMLText
</TR>
"@
Switch ($strColorTemp)
{
"1"
■ {
■ $strColor = "DDDDDD"
■ $strColorTemp = "2"
■ }
"2"
■ {
■ $strColor = "AAAAAA"
■ $strColorTemp = "1"
■ }■■
"3"
■ {
■ $strColor = "FF1111"
}
"4"
■ {
■ $strColor = "00FFAA"
}
"5"
■ {
■ $strColor = "FFFF00"
}
}# End Switch
$strGroupText=$strGroupText+@"
<TR bgcolor="$strColor"><TD> $strFont $strObjectClass</TD><TD> $strFont $strDefSDVer</TD><TD
"@
$strHTMLText = $strHTMLText + $strGroupText
Out-File -InputObject $strHTMLText -Append -FilePath $htafileout
Out-File -InputObject $strHTMLText -Append -FilePath $htmfileout
$strHTMLText = ""
}
#==========================================================================
# Function■■: CreateDefaultSDReportHTA
# Arguments : Forest Name, Output HTA file
# Returns ■: n/a
# Description : Initiates a base HTA file with Export(Save As),Print and Exit buttons.
#==========================================================================
function CreateDefaultSDReportHTA
{
Param([string]$Forest,[string]$htafileout,[string]$htmfileout,[string] $folder)
$strHTAText =@"
<html>
<head>
<hta:Application ID="hta"
ApplicationName="Report">
<title>defaultSecurityDescriptor Report on $Forest</title>
<script type="text/vbscript">
Sub ExportToCSV()
Dim objFSO,objFile,objNewFile,oShell,oEnv
Set oShell=CreateObject("wscript.shell")
Set oEnv=oShell.Environment("System")
strTemp=oShell.ExpandEnvironmentStrings("%USERPROFILE%")
strTempFile="$htmfileout"
strOutputFolder="$folder"
strFile=SaveAs("$($Forest.Split("\")[-1]).htm",strOutputFolder)
If strFile="" Then Exit Sub
Set objFSO=CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile strTempFile,strFile, true
MsgBox "Finished exporting to " & strFile,vbOKOnly+vbInformation,"Export"
End Sub
Function SaveAs(strFile,strOutFolder)
Dim objDialog
SaveAs=InputBox("Enter the filename and path."&vbCrlf&vbCrlf&"Example: "&strOutFolder&"\CONTOS
End Function
</script>
</head>
<body>
<input type="button" value="Export" onclick="ExportToCSV" tabindex="9">
<input id="print_button" type="button" value="Print" name="Print_button" class="Hide" onClick="Window
<input type="button" value="Exit" onclick=self.close name="B3" tabindex="1" class="btn">
"@
Out-File -InputObject $strHTAText -Force -FilePath $htafileout
}
#==========================================================================
# Function■■: CreateSPNHTM
# Arguments : OU Name, Ou put HTM file
# Returns ■: n/a
# Description : Initiates a base HTM file with Export(Save As),Print and Exit buttons.
#==========================================================================
function CreateDefSDHTM
{
Param([string]$SPN,[string]$htmfileout)
$strHTAText =@"
<html>
<head[string]$SPN
<title>Default Security Descritor Report on $SPN</title>
"@
Out-File -InputObject $strHTAText -Force -FilePath $htmfileout
}
#==========================================================================
# Function■■: InitiateSPNHTM
# Arguments : Output htm file
# Returns ■: n/a
# Description : Wites base HTM table syntax, it appends info if the file exist
#==========================================================================
Function InitiateDefSDHTM
{
Param([string] $htmfileout,[string] $strStartingPoint)
$strHTMLText =@"
<h1 style="color: #79A0E0;text-align: center;">Default Security Descriptor REPORT - $($strStartingPoin
"@
$strHTMLText =$strHTMLText +"<TABLE BORDER=1>"
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Object</font></th><th bgcolor="$strTHColor">$strFontTH Versi
"@
Out-File -InputObject $strHTMLText -Append -FilePath $htmfileout
}
#==========================================================================
# Function■■: CreateServicePrincipalReportHTA
# Arguments : OU Name, Ou put HTA file
# Returns ■: n/a
# Description : Initiates a base HTA file with Export(Save As),Print and Exit buttons.
#==========================================================================
function CreateServicePrincipalReportHTA
{
Param([string]$SPN,[string]$htafileout,[string]$htmfileout,[string] $folder)
$strHTAText =@"
<html>
<head>
<hta:Application ID="hta"
ApplicationName="Report">
<title>Membership Report on $SPN</title>
<script type="text/vbscript">
Sub ExportToCSV()
Dim objFSO,objFile,objNewFile,oShell,oEnv
Set oShell=CreateObject("wscript.shell")
Set oEnv=oShell.Environment("System")
strTemp=oShell.ExpandEnvironmentStrings("%USERPROFILE%")
strTempFile="$htmfileout"
strOutputFolder="$folder"
strFile=SaveAs("$($SPN.Split("\")[-1]).htm",strOutputFolder)
If strFile="" Then Exit Sub
Set objFSO=CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile strTempFile,strFile, true
MsgBox "Finished exporting to " & strFile,vbOKOnly+vbInformation,"Export"
End Sub
Function SaveAs(strFile,strOutFolder)
Dim objDialog
SaveAs=InputBox("Enter the filename and path."&vbCrlf&vbCrlf&"Example: "&strOutFolder&"\CONTOS
End Function
</script>
</head>
<body>
<input type="button" value="Export" onclick="ExportToCSV" tabindex="9">
<input id="print_button" type="button" value="Print" name="Print_button" class="Hide" onClick="Window
<input type="button" value="Exit" onclick=self.close name="B3" tabindex="1" class="btn">
"@
Out-File -InputObject $strHTAText -Force -FilePath $htafileout
}
#==========================================================================
# Function■■: CreateSPNHTM
# Arguments : OU Name, Ou put HTM file
# Returns ■: n/a
# Description : Initiates a base HTM file with Export(Save As),Print and Exit buttons.
#==========================================================================
function CreateSPNHTM
{
Param([string]$SPN,[string]$htmfileout)
$strHTAText =@"
<html>
<head[string]$SPN
<title>Membership Report on $SPN</title>
"@
Out-File -InputObject $strHTAText -Force -FilePath $htmfileout
}
#==========================================================================
# Function■■: InitiateSPNHTM
# Arguments : Output htm file
# Returns ■: n/a
# Description : Wites base HTM table syntax, it appends info if the file exist
#==========================================================================
Function InitiateSPNHTM
{
Param([string] $htmfileout)
$strHTMLText ="<TABLE BORDER=1>"
$strTHOUColor = "E5CF00"
$strTHColor = "EFAC00"
$strFont =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontOU =@"
<FONT size="1" face="verdana, hevetica, arial">
"@
$strFontTH =@"
<FONT size="2" face="verdana, hevetica, arial">
"@
$strHTMLText =@"
$strHTMLText
<th bgcolor="$strTHColor">$strFontTH Account Name</font></th><th bgcolor="$strTHColor">$strFontT
"@
Out-File -InputObject $strHTMLText -Append -FilePath $htmfileout
}
#==========================================================================
# Function■■: CreateHTM
# Arguments : OU Name, Ou put HTM file
# Returns ■: n/a
# Description : Initiates a base HTM file with Export(Save As),Print and Exit buttons.
#==========================================================================
function CreateHTM
{
Param([string]$NodeName,[string]$htmfileout)
$strHTAText =@"
<html>
<head>
<title>Report on $NodeName</title>
"@
Out-File -InputObject $strHTAText -Force -FilePath $htmfileout
}
#==========================================================================
# Function■■: Select-File
# Arguments : n/a
# Returns ■: folder path
# Description : Dialogbox for selecting a file
#==========================================================================
function Select-File
{
param (
[System.String]$Title = "Select Template File",
[System.String]$InitialDirectory = $CurrentFSPath,
[System.String]$Filter = "All Files(*.csv)|*.csv"
)
)
$bolCompare = $false
$bolACLExist = $true
$global:strOwner = ""
$strACLSize = ""
$bolOUProtected = $false
$aclcount = 0
$sdOUProtect = ""
$global:ArrayAllACE = New-Object System.Collections.ArrayList
if(($OutType -eq "EXCEL") -or ($OutType -eq "CSV"))
{
$WriteOut = "Object"
}
else
{
$WriteOut = "HTML"
}
if(($OutType -eq "CSVTEMPLATE") -or ($OutType -eq "CSV"))
{
$bolCSV = $true
■If ((Test-Path $strFileCSV) -eq $true)
■{
■ Remove-Item $strFileCSV
■}
}
else
{
$bolCSV = $false
}
$count = 0
$i = 0
$intCSV = 0
if($global:bolCMD)
{
$intTot = 0
#calculate percentage
$intTot = $AllObjectDn.count
}
else
{
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$intTot = 0
#calculate percentage
$intTot = $AllObjectDn.count
if ($intTot -gt 0)
{
LoadProgressBar
}
}
}
while($count -le $AllObjectDn.count -1)
{
if($GPO)
{
$ADObjDN = $AllObjectDn[$count].Split(";")[0]
$GPOTarget = $AllObjectDn[$count].Split(";")[1]
if($GPO)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:st
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = $ADObjDN
$request.Filter = "(objectClass=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("displayname")
$response = $LDAPConnection.SendRequest($request)
$result = $response.Entries[0]
try
{
$GPOdisplayname = $result.attributes.displayname[0]
}
catch
{
}
}
}
else
{
$ADObjDN = $($AllObjectDn[$count])
}
$global:secd = ""
$bolACLExist = $true
$global:GetSecErr = $false
if(($global:bolCMD) -and ($global:bolProgressBar))
{
$i++
[int]$pct = ($i/$intTot)*100
Write-Progress -Activity "Collecting objects" -Status "Currently scanning $i of $intTot objects" -Id 0 -C
}
else
{
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$i++
[int]$pct = ($i/$intTot)*100
#Update the progress bar
}
}
$sd = New-Object System.Collections.ArrayList
$GetOwnerEna = $bolGetOwnerEna
if ($rdbDACL.IsChecked)
{
$SecurityMasks = [System.DirectoryServices.Protocols.SecurityMasks]'Owner' -bor [System.Director
$control = New-Object System.DirectoryServices.Protocols.SecurityDescriptorFlagControl($SecurityM
[void]$request.Controls.Add($control)
$response = $LDAPConnection.SendRequest($request)
$DSobject = $response.Entries[0]
#Check if any NTsecuritydescr
if($null -ne $DSobject.Attributes.ntsecuritydescriptor)
{
if($null -ne $DSobject.Attributes.objectclass)
{
$strObjectClass = $DSobject.Attributes.objectclass[$DSobject.Attributes.objectclass.count-1]
}
else
{
$strObjectClass = "unknown"
}
if($SDDL)
{
[string]$strSDDL = ""
$objSd = $DSobject.Attributes.ntsecuritydescriptor[0]
if ($objSD -is [Byte[]]) {
$SDDLSec = New-Object System.Security.AccessControl.RawSecurityDescriptor @($objS
} elseif ($objSD -is [string]) {
$SDDLSec = New-Object System.Security.AccessControl.RawSecurityDescriptor @($objS
}
if(!($IncludeInherited))
{
$arrSDDL = @(($SDDLSec.GetSddlForm('Access,Owner')).split(")") | ?{$_ -notmatch "ID;"})
if($arrSDDL.count -gt 0)
{
for($IntCount=0;$IntCount -lt $($arrSDDL.count -1);$IntCount++)
{
$strSDDL +="$($arrSDDL[$IntCount]))"
}
}
}
else
{
$strSDDL = $SDDLSec.GetSddlForm('Access,Owner')
}
}
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($chkBoxRAWSDDL.IsChecked)
{
$secSDDL = New-Object System.DirectoryServices.ActiveDirectorySecurity
$objSd = $DSobject.Attributes.ntsecuritydescriptor[0]
if ($objSD -is [Byte[]]) {
$SDDLSec = New-Object System.Security.AccessControl.RawSecurityDescriptor @($objS
} elseif ($objSD -is [string]) {
$SDDLSec = New-Object System.Security.AccessControl.RawSecurityDescriptor @($objS
}
$strSDDLForm = $SDDLSec.GetSddlForm('Access,Owner')
$arrSplitedSDDL = $strSDDLForm.Split("(")
$intI = 0
Foreach ($strSDDLPart in $arrSplitedSDDL)
{
if($intI -gt 0)
{
if($sec.Owner -eq $null)
{
$sec.SetSecurityDescriptorSDDLForm("$($arrSplitedSDDL[0])($strSDDLPart")
}
else
{
if(!($IncludeInherited))
{
if(($strSDDLPart.split(";")[1] -ne "CIID") -and ($strSDDLPart.split(";")[1] -ne "CIIOID"))
{
$secSDDL.SetSecurityDescriptorSDDLForm("$($arrSplitedSDDL[0])($strSDDLPart
$sec.AddAccessRule($secSDDL.Access[0])
}
}
else
{
$secSDDL.SetSecurityDescriptorSDDLForm("$($arrSplitedSDDL[0])($strSDDLPart")
$sec.AddAccessRule($secSDDL.Access[0])
}
}
}
$intI++
}
}
else
{
$sec.SetSecurityDescriptorBinaryForm($DSobject.Attributes.ntsecuritydescriptor[0])
}
&{#Try
$global:secd = $sec.GetAccessRules($true, $IncludeInherited, [System.Security.Principal.Secur
}
Trap [SystemException]
{
if($bolCMD)
{
Write-host "Failed to translate identity:$ADObjDN" -ForegroundColor red
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to translate identity:$
}
$global:GetSecErr = $true
Continue
}
}
else
{
#Fail futher scan when NTsecurityDescriptor is null
$global:GetSecErr = $true
}
}
else
{
$SecurityMasks = [System.DirectoryServices.Protocols.SecurityMasks]'Owner' -bor [System.Director
$control = New-Object System.DirectoryServices.Protocols.SecurityDescriptorFlagControl($SecurityM
[void]$request.Controls.Add($control)
$response = $LDAPConnection.SendRequest($request)
$DSobject = $response.Entries[0]
if($null -ne $DSobject.Attributes.objectclass)
{
$strObjectClass = $DSobject.Attributes.objectclass[$DSobject.Attributes.objectclass.count-1]
}
else
{
$strObjectClass = "unknown"
}
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
$sec.SetSecurityDescriptorBinaryForm($DSobject.Attributes.ntsecuritydescriptor[0])
&{#Try
$global:secd = $sec.GetAuditRules($true, $IncludeInherited, [System.Security.Principal.SecurityId
}
Trap [SystemException]
{
if($bolCMD)
{
Write-host "Failed to translate identity:$ADObjDN" -ForegroundColor red
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to translate identity:$AD
}
$global:GetSecErr = $true
Continue
}
}
if(($global:GetSecErr -ne $true) -or ($global:secd -ne ""))
{
$sd.clear()
if($null -ne $global:secd){
$(ConvertTo-ObjectArrayListFromPsCustomObject $global:secd)| ForEach-Object{[void]$sd.add(
}
If ($GetOwnerEna -eq $true)
{
&{#Try
$global:strOwner = $sec.GetOwner([System.Security.Principal.SecurityIdentifier]).value
}
Trap [SystemException]
{
if($global:bolADDSType)
{
if($bolCMD)
{
Write-host "Failed to translate owner identity:$ADObjDN" -ForegroundColor red
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to translate owner
}
}
Continue
}
$newSdOwnerObject = New-Object PSObject -Property @{ActiveDirectoryRights="Read permissi
InheritedObjectType="None";ObjectFlags="None";AccessControlType="Owner";IdentityReference
InheritanceFlags="None";PropagationFlags="None"}
[void]$sd.insert(0,$newSdOwnerObject)
}
■If ($SkipDefaultPerm)
■{
If ($GetOwnerEna -eq $false)
{
&{#Try
$global:strOwner = $sec.GetOwner([System.Security.Principal.SecurityIdentifier]).value
}
Trap [SystemException]
{
if($bolCMD)
{
Write-host "Failed to translate owner identity:$ADObjDN" -ForegroundColor red
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to translate owner
}
Continue
}
}
}
if ($bolACLsize -eq $true)
{
$strACLSize = $sec.GetSecurityDescriptorBinaryForm().length
}
if ($bolGetOUProtected -eq $true)
{
$bolOUProtected = $sec.AreAccessRulesProtected
}
if ($bolReplMeta -eq $true)
{
}
if($ApplyTo.Split("|") -contains "*")
{
$sd = @($sd | Where-Object{(($_.ObjectType -match $ApplyToString) -or ($_.InheritedO
}
else
{
$sd = @($sd | Where-Object{($_.ObjectType -match $ApplyToString) -or ($_.InheritedO
}
}
else
{
if($ApplyTo -contains "*")
{
$sd = @($sd | Where-Object{(($_.ObjectType -eq "00000000-0000-0000-0000-0000000
}
else
{
$sd = @($sd | Where-Object{($_.ObjectType -eq $global:dicNameToSchemaIDGUIDs.It
}
}
}
}
If ($BolACLPermissionFilter)
{
If ($ACLPermissionFilter)
{
if ($ACLPermissionFilter.Length -gt 0)
{
$sd = @($sd | Where-Object{$_.ActiveDirectoryRights -match $ACLPermissionFilter})
}
}
}
}
if($FilterBuiltin)
{
# Filter out default and built-in security principals
$sd = @($sd | Where-Object{`
($_.IdentityReference -match "S-1-5-21-") -and `
($_.IdentityReference -notmatch $("^"+$domainsid+"-5\d{2}$")) -and
($_.IdentityReference -notmatch $("^"+$domainsid+"-4\d{2}$"))
})
}
if($RecursiveFind)
{
$RecursiveData = new-object System.Collections.ArrayList
foreach($ace in $sd)
{
[Void]$RecursiveData.add($ace)
$SID_DN = ""
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = "<SID=$($ace.IdentityReference)>"
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("objectClass")
[void]$request.Attributes.Add("member")
try
{
$response = $LDAPConnection.SendRequest($request)
$result = $response.Entries[0]
■ $SID_DN = $result.distinguishedName
$ObjectClass =$result.attributes.objectclass[$result.attributes.objectclass.count-1]
}
catch
{
Write-Verbose "Could not resolve $sid"
}
if($SID_DN)
{
if($ObjectClass -eq "Group")
{
if(($result.Attributes.AttributeNames -contains "member;range=0-1499") -or ($result.Attribu
{
$global:GroupMembersExpanded = New-Object System.Collections.ArrayList
$NetstedResult = Get-LargeNestedADGroup $global:strDC $SID_DN $RecursiveObject
if($NetstedResult)
{
foreach($NestedObject in $NetstedResult)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConne
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = $NestedObject
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("objectsid")
[void]$request.Attributes.Add("msds-principalname")
$response = $LDAPConnection.SendRequest($request)
$ADObject = $response.Entries[0]
$recursiveobject = new-object psobject
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Ide
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Act
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Inh
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Ob
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Inh
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Ob
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Acc
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "IsIn
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Inh
add-member -inputobject $recursiveobject -MemberType NoteProperty -Name "Pro
[Void]$RecursiveData.add($recursiveobject)
$recursiveobject = $null
}
}
}
}
}
$SD = $RecursiveData | Sort-Object -Property InheritedObjectType,ObjectType,IdentityReference
$RecursiveData = $null
}
If (($FilterEna -eq $true) -and ($bolEffectiveR -eq $false))
{
If ($FilterForTrustee)
{
if ($FilterTrustee.Length -gt 0)
{
$sd = @($sd | Where-Object{if($_.IdentityReference -like "S-1-*"){`
$(ConvertSidToName -server $global:strDomainLongName -Sid $_.IdentityReference -CRED
else{$_.IdentityReference -like $FilterTrustee}})
}
}
}
if($ReturnObjectType)
{
if($ReturnObjectType -ne "*")
{
$sd = @($sd | Where-Object{(GetObjectTypeFromSid -server $global:strDC -Sid $_.IdentityRefe
}
}
If ($bolAssess)
{
Switch ($AssessLevel)
{
"Info" {$CriticalityFilter = 0}
"Low" {$CriticalityFilter = 1}
"Medium" {$CriticalityFilter = 2}
"Warning" {$CriticalityFilter = 3}
"Critical" {$CriticalityFilter = 4}
}
$sd = @($sd | Where-Object{Get-Criticality -Returns "Filter" $_.IdentityReference.toString() $_.Act
}
if ($bolEffectiveR -eq $true)
{
if ($global:tokens.count -gt 0)
{
$sdtemp2 = New-Object System.Collections.ArrayList
$sdtemp = ""
$sdtemp = $sd | Where-Object{$_.IdentityReference -eq $tok}
if($sdtemp)
{
[void]$sdtemp2.Add( $sdtemp)
}
}
$sd = $sdtemp2
}
}
$intSDCount = $sd.count
If (!($bolCSVO))
{
$bolACLExist = $false
if (($permcount -eq 0) -and ($index -gt 0))
{
$bolOUHeader = $true
■ WriteOUT $bolACLExist $sd $strDistinguishedName $CanonicalName $bolOUHeader "1" $str
$aclcount++
}# End If
}# End if bolCSVOnly
}
}#End $global:GetSecErr
■$count++
}# End while
$global:ProgressBarWindow.Window.Dispatcher.invoke([action]{$global:ProgressBarWindow
}
}
if($bolCSV)
{
if($OutType -eq "CSVTEMPLATE")
{
if($bolCMD)
{
if($bolToFile)
{
Write-host "Report saved in: $strFileCSV" -ForegroundColor Yellow
Write-output $strFileCSV
}
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFileCS
}
#If Get-Perm was called with Show then open the CSV file.
if($Show)
{
■ Invoke-Item $strFileCSV
}
}
else
{
if($bolCMD)
{
if($bolToFile)
{
$global:ArrayAllACE | export-csv -Path $strFileCSV -NoTypeInformation -NoClobber
Write-host "Report saved in: $strFileCSV" -ForegroundColor Yellow
Write-output $strFileCSV
}
else
{
$global:ArrayAllACE
}
}
else
{
$global:ArrayAllACE | export-csv -Path $strFileCSV -NoTypeInformation -NoClobber
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFileCS
}
#If Get-Perm was called with Show then open the CSV file.
if($Show)
{
■ Invoke-Item $strFileCSV
}
}
}
else
{
#If excel output
if($OutType -eq "EXCEL")
{
$tablename = $($strNode+"acltbl") -replace '[^a-zA-Z]+',''
if($bolShowCriticalityColor)
{
# Array with alphabet characters
$ExcelColumnAlphabet = @()
for ([byte]$c = [char]'A'; $c -le [char]'Z'; $c++)
{
$ExcelColumnAlphabet += [char]$c
}
}
}
}
while($count -le $AllObjectDn.count -1)
{
$global:GetSecErr = $false
$global:secd = ""
if(($global:bolCMD) -and ($global:bolProgressBar))
{
$i++
[int]$pct = ($i/$intTot)*100
Write-Progress -Activity "Collecting objects" -Status "Currently scanning $i of $intTot objects" -Id 0
}
else
{
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$i++
[int]$pct = ($i/$intTot)*100
#Update the progress bar
while(($null -eq $global:ProgressBarWindow.Window.IsInitialized) -and ($intLoop -lt 20))
{
Start-Sleep -Milliseconds 1
$cc++
}
if ($global:ProgressBarWindow.Window.IsInitialized -eq $true)
{
Update-ProgressBar "Currently scanning $i of $intTot objects" $pct
}
}
}
$OUMatchResultOverall = $false
$sd = New-Object System.Collections.ArrayList
$GetOwnerEna = $bolGetOwnerEna
if($GPO)
{
$ADObjDN = $AllObjectDn[$count].Split(";")[0]
$GPOTarget = $AllObjectDn[$count].Split(";")[1]
if($GPO)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
$request.DistinguishedName = $ADObjDN
$request.Filter = "(objectClass=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("displayname")
$response = $LDAPConnection.SendRequest($request)
$result = $response.Entries[0]
try
{
$GPOdisplayname = $result.attributes.displayname[0]
}
catch
{
}
}
}
else
{
$ADObjDN = $($AllObjectDn[$count])
}
$OUdnorgDN = $ADObjDN
#Counter used for fitlerout Nodes with only defaultpermissions configured
$intAclOccurence = 0
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strD
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest("$ADObjDN", "(name=*)
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.DirectoryControl" -
}
[void]$request.Attributes.Add("objectclass")
if($UseCanonicalName)
{
[void]$request.Attributes.Add("canonicalname")
}
[void]$request.Attributes.Add("ntsecuritydescriptor")
$response = $null
$DSobject = $null
if ($rdbDACL.IsChecked)
{
$SecurityMasks = [System.DirectoryServices.Protocols.SecurityMasks]'Owner' -bor [System.Direc
$control = New-Object System.DirectoryServices.Protocols.SecurityDescriptorFlagControl($Securi
[void]$request.Controls.Add($control)
$SendRequest = $false
try
{
$response = $LDAPConnection.SendRequest($request)
$SendRequest = $true
}
catch
{
if($global:bolCMD)
{
Write-host "Failed to connect to:$ADObjDN"
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to connect to:$ADOb
}
}
if($SendRequest)
{
$DSobject = $response.Entries[0]
if($GPO)
{
$strDistinguishedName = $GPOTarget
}
else
{
$strDistinguishedName = $DSobject.distinguishedname.toString()
}
#Check if any NTsecuritydescr
if($null -ne $DSobject.Attributes.ntsecuritydescriptor)
{
if($null -ne $DSobject.Attributes.objectclass)
{
$strObjectClass = $DSobject.Attributes.objectclass[$DSobject.Attributes.objectclass.count-1]
}
else
{
$strObjectClass = "unknown"
}
if($UseCanonicalName)
{
if($DSobject.attributes.canonicalname)
{
$CanonicalName = $DSobject.attributes.canonicalname[0]
}
else
{
$CanonicalName = Create-CanonicalName $DSobject.distinguishedname.toString()
}
}
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($chkBoxRAWSDDL.IsChecked)
{
}
else
{
$SecurityMasks = [System.DirectoryServices.Protocols.SecurityMasks]'Owner' -bor [System.Direc
$control = New-Object System.DirectoryServices.Protocols.SecurityDescriptorFlagControl($Securi
[void]$request.Controls.Add($control)
$response = $LDAPConnection.SendRequest($request)
$DSobject = $response.Entries[0]
if($null -ne $DSobject.Attributes.objectclass)
{
$strObjectClass = $DSobject.Attributes.objectclass[$DSobject.Attributes.objectclass.count-1]
}
else
{
$strObjectClass = "unknown"
}
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
$sec.SetSecurityDescriptorBinaryForm($DSobject.Attributes.ntsecuritydescriptor[0])
&{#Try
#$DSobject.psbase.Options.SecurityMasks = [System.DirectoryServices.SecurityMasks]'Owner
$global:secd = $sec.GetAuditRules($true, $chkInheritedPerm.IsChecked, [System.Security.Prin
}
Trap [SystemException]
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to translate identity:$AD
&{#Try
$global:secd = $sec.GetAuditRules($true, $chkInheritedPerm.IsChecked, [System.Security.P
}
Trap [SystemException]
{
$global:GetSecErr = $true
Continue
}
Continue
}
}
if($DSobject.attributes.count -gt 0)
{
if(($global:GetSecErr -ne $true) -or ($global:secd -ne ""))
{
$sd.clear()
if($null -ne $global:secd){
$(ConvertTo-ObjectArrayListFromPsCustomObject $global:secd)| ForEach-Object{[void]$sd.ad
}
If ($GetOwnerEna -eq $true)
{
&{#Try
$global:strOwner = $sec.GetOwner([System.Security.Principal.SecurityIdentifier]).value
}
Trap [SystemException]
{
if($global:bolADDSType)
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to translate owner
}
$global:strOwner = $sec.GetOwner([System.Security.Principal.SecurityIdentifier]).value
Continue
}
$newSdOwnerObject = New-Object PSObject -Property @{ActiveDirectoryRights="Read permis
InheritedObjectType="None";ObjectFlags="None";AccessControlType="Owner";IdentityReferen
InheritanceFlags="None";PropagationFlags="None"}
[void]$sd.insert(0,$newSdOwnerObject)
}
■ If ($SkipDefaultPerm)
■ {
If ($GetOwnerEna -eq $false)
{
&{#Try
$global:strOwner = $sec.GetOwner([System.Security.Principal.SecurityIdentifier]).value
}
Trap [SystemException]
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to translate owner
$global:strOwner = $sec.GetOwner([System.Security.Principal.SecurityIdentifier]).value
Continue
}
}
}
If ($bolAssess)
{
Switch ($AssessLevel)
{
"Info" {$CriticalityFilter = 0}
"Low" {$CriticalityFilter = 1}
"Medium" {$CriticalityFilter = 2}
"Warning" {$CriticalityFilter = 3}
"Critical" {$CriticalityFilter = 4}
}
$sd = @($sd | Where-Object{Get-Criticality -Returns "Filter" $_.IdentityReference.toString() $_.A
}
if ($bolACLsize -eq $true)
{
#$strACLSize = $sec.GetSecurityDescriptorBinaryForm().length
$strACLSize = $SDDLSec.BinaryLength
}
if ($bolGetOUProtected -eq $true)
{
$bolOUProtected = $sec.AreAccessRulesProtected
}
if ($bolReplMeta -eq $true)
{
$SDUsnNew = $true
if ($SDUsnCheck -eq $true)
{
■
while($index -le $arrUSNCheckList.count -1)
{
$SDHistResult = $false
if($arrUSNCheckList[$index].Object)
{
$strOUcol = $arrUSNCheckList[$index].Object
}
else
{
$strOUcol = $arrUSNCheckList[$index].OU
}
if($strOUcol.Contains("<DOMAIN-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<DOMAIN-DN>",$global:strDomainDNName)
}
if($strOUcol.Contains("<ROOT-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<ROOT-DN>",$global:ForestRootDomainDN)
}
if($txtReplaceDN.text.Length -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace $txtReplaceDN.text,$global:strDomainDNName)
}
■■■ if ($OUdnorgDN -eq $strOUcol )
■■■ {
$OUMatchResult = $true
$SDResult = $true
if($strOrigUSN -eq $arrUSNCheckList[$index].OrgUSN)
{
$aclcount++
foreach($sdObject in $sd)
■ {
}
$bolOUHeader = $false
WriteOUT $true $newSdObject $strDistinguishedname $CanonicalName $b
}#End !$bolCSVOnly
}#End Returns
}
$SDUsnNew = $false
break
}
else
{
$aclcount++
$SDUsnNew = $true
break
}
}
$index++
}
}
If (($SDUsnCheck -eq $false) -or ($SDUsnNew -eq $true))
{
■ foreach($sdObject in $sd)
■ {
$bolMatchDef = $false
$bolMatchprotected = $false
$strIdentityReference= $sdObject.IdentityReference.toString()
■ If ($strIdentityReference.contains("S-1-"))
■ {
■ $strNTAccount = ConvertSidToName -server $global:strDomainLongName -Sid $strIdentity
■ }
#Remove Default Permissions if SkipDefaultPerm selected
if($SkipDefaultPerm)
{
if($strObjectClass -ne $strTemoObjectClass)
{
$sdOUDef = Get-DefaultPermissions -strObjectClass $strObjectClass -CREDS $CREDS
}
$strTemoObjectClass = $strObjectClass
$indexDef=0
while($indexDef -le $sdOUDef.count -1) {
■■■ if (($sdOUDef[$indexDef].IdentityReference -eq $sdObject.IdentityReference) -and ($
■■■ {
■■■ $bolMatchDef = $true
■■■ } #End If
$indexDef++
} #End While
}
if($bolMatchDef)
■■■■{
■■■■}
else
{
#Remove Protect Against Accidental Deletaions Permissions if SkipProtectedPerm selecte
if($SkipProtectedPerm)
{
if($sdOUProtect -eq "")
{
$sdOUProtect = Get-ProtectedPerm
}
$indexProtected=0
while($indexProtected -le $sdOUProtect.count -1)
{
■■■ if (($sdOUProtect[$indexProtected].IdentityReference -eq $sdObject.IdentityReference)
eq $sdObject.InheritedObjectType))
■■■ {
■■■ $bolMatchprotected = $true
■■■ }#End If
$indexProtected++
} #End While
}
if($bolMatchprotected)
■■■■ {
■■■■ }
■■■■ else
■■■■ {
■■ $index = 0
■■ $SDResult = $false
$OUMatchResult = $false
$aclcount++
if($null -ne $sdObject.AccessControlType)
{
$ACEType = $sdObject.AccessControlType
}
else
{
$ACEType = $sdObject.AuditFlags
}
$newSdObject = New-Object PSObject -Property @{ActiveDirectoryRights=$sdObject.A
InheritedObjectType=$sdObject.InheritedObjectType;ObjectFlags=$sdObject.ObjectFlag
InheritanceFlags=$sdObject.InheritanceFlags;PropagationFlags=$sdObject.Propagation
■■ while($index -le $global:csvHistACLs.count -1)
■■ {
if($global:csvHistACLs[$index].Object)
{
$strOUcol = $global:csvHistACLs[$index].Object
}
else
{
$strOUcol = $global:csvHistACLs[$index].OU
}
if($strOUcol.Contains("<DOMAIN-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<DOMAIN-DN>",$global:strDomainDNName)
}
if($strOUcol.Contains("<ROOT-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<ROOT-DN>",$global:ForestRootDomainDN)
}
if($txtReplaceDN.text.Length -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace $txtReplaceDN.text,$global:strDomainDNName)
}
■■■ if ($OUdnorgDN -eq $strOUcol )
■■■ {
$OUMatchResult = $true
$OUMatchResultOverall = $true
■■■■ $strPrincipalName = $global:csvHistACLs[$index].PrincipalName
if($strPrincipalName.Contains("<DOMAIN-NETBIOS>"))
{
■■ $strPrincipalName = ($strPrincipalName -Replace "<DOMAIN-NETBIOS>",$globa
}
if($strPrincipalName.Contains("<ROOT-NETBIOS>"))
{
■■ $strPrincipalName = ($strPrincipalName -Replace "<ROOT-NETBIOS>",$global:s
}
if($strPrincipalName.Contains("<DOMAINSID>"))
{
■■ $strPrincipalName = ($strPrincipalName -Replace "<DOMAINSID>",$global:Doma
}
if($strPrincipalName.Contains("<ROOTDOMAINSID>"))
{
■■ $strPrincipalName = ($strPrincipalName -Replace "<ROOTDOMAINSID>",$global
}
■ If ($strPrincipalName.contains("S-1-"))
■ {
■ $strPrincipalName = ConvertSidToName -server $global:strDomainLongName -S
■ }
if($txtReplaceNetbios.text.Length -gt 0)
{
■■ $strPrincipalName = ($strPrincipalName -Replace $txtReplaceNetbios.text,$globa
}
■■■■ $strTmpActiveDirectoryRights = $global:csvHistACLs[$index].ActiveDirectoryRights■■
■■■■ $strTmpInheritanceType = $global:csvHistACLs[$index].InheritanceType■■■
■■■■ $strTmpObjectTypeGUID = $global:csvHistACLs[$index].ObjectType
■■■■ $strTmpInheritedObjectTypeGUID = $global:csvHistACLs[$index].InheritedObjectType
■■■■ $strTmpAccessControlType = $global:csvHistACLs[$index].AccessControlType
if ($strTmpAccessControlType -eq "Owner" )
{
$global:strOwnerTemplate = $strPrincipalName
}
If (($newSdObject.PrincipalName -eq $strPrincipalName) -and ($newSdObject.Acti
■■ ■■ {
■■■■■ $SDResult = $true
■■ ■■ }
■■ ■ }
■■■ $index++
■■ }# End While
if(($TemplateFilter -eq "MATCH") -or ($TemplateFilter -eq "ALL"))
{
if ($SDResult)
{
$intReturned++
■■■■■ If ($bolCSV)
■■■■■ {
$intCSV++
if($OutType -eq "CSVTEMPLATE")
{
■■■■ ■■ WritePermCSV $newSdObject $strDistinguishedname $CanonicalName $strObjectClas
}
else
{
$bolOUHeader = $false
WriteOUT $true $newSdObject $strDistinguishedname $CanonicalName $bolOUH
}
■■■■ ■ }# End If
Else
{
if ($intAclOccurence -eq 0)
{
$intAclOccurence++
$bolOUHeader = $true
WriteOUT $false $sd $strDistinguishedname $CanonicalName $bolOUHeader $str
}
$bolOUHeader = $false
WriteOUT $true $newSdObject $strDistinguishedname $CanonicalName $bolOUHea
}#End !$bolCSVOnly
}
}#End Retrunrs
■■ If ($OUMatchResult -And !($SDResult))
■■ {
if(($TemplateFilter -eq "NEW") -or ($TemplateFilter -eq "ALL"))
{
$newSdObject.State = "New"
$intReturned++
If ($bolCSV)
■■■■■ {
$intCSV++
if($OutType -eq "CSVTEMPLATE")
{
■■■■ ■■ WritePermCSV $newSdObject $strDistinguishedname $CanonicalName $strObjectClas
}
else
{
$bolOUHeader = $false
WriteOUT $true $newSdObject $strDistinguishedname $CanonicalName $bolOUH
}
■■■■ ■ }# End If
Else
{
if ($intAclOccurence -eq 0)
{
$intAclOccurence++
$bolOUHeader = $true
WriteOUT $false $sd $strDistinguishedname $CanonicalName $bolOUHeader $str
}
$bolOUHeader = $false
WriteOUT $true $newSdObject $strDistinguishedname $CanonicalName $bolOUHea
}#End !$bolCSVO
}#End Returns
}
}# End If SkipProtectedPerm
}# End If SkipDefaultPerm
■ }
} # if $SDUsnCheck -eq $true
If (($SDUsnCheck -eq $false) -or ($SDUsnNew -eq $true))
{
$index = 0
while($index -le $global:csvHistACLs.count -1)
{
$SDHistResult = $false
if($global:csvHistACLs[$index].Object)
{
$strOUcol = $global:csvHistACLs[$index].Object
}
else
{
$strOUcol = $global:csvHistACLs[$index].OU
}
if($strOUcol.Contains("<DOMAIN-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<DOMAIN-DN>",$global:strDomainDNName)
}
if($strOUcol.Contains("<ROOT-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<ROOT-DN>",$global:ForestRootDomainDN)
}
if($txtReplaceDN.text.Length -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace $txtReplaceDN.text,$global:strDomainDNName)
}
■■■ if ($OUdnorgDN -eq $strOUcol )
■■■ {
$OUMatchResult = $true
■■■■ $strIdentityReference = $global:csvHistACLs[$index].IdentityReference
if($strIdentityReference.Contains("<DOMAIN-NETBIOS>"))
{
■■ $strIdentityReference = ($strIdentityReference -Replace "<DOMAIN-NETBIOS>",$global:s
}
if($strIdentityReference.Contains("<ROOT-NETBIOS>"))
{
■■ $strIdentityReference = ($strIdentityReference -Replace "<ROOT-NETBIOS>",$global:strR
}
if($strIdentityReference.Contains("<DOMAINSID>"))
{
■■ $strIdentityReference = ($strIdentityReference -Replace "<DOMAINSID>",$global:Domain
}
if($strIdentityReference.Contains("<ROOTDOMAINSID>"))
{
■■ $strIdentityReference = ($strIdentityReference -Replace "<ROOTDOMAINSID>",$global:F
}
if($txtReplaceNetbios.text.Length -gt 0)
{
■■ $strIdentityReference = ($strIdentityReference -Replace $txtReplaceNetbios.text,$global:s
}
■■■■ $strTmpActiveDirectoryRights = $global:csvHistACLs[$index].ActiveDirectoryRights■■■
■■■■ $strTmpInheritanceType = $global:csvHistACLs[$index].InheritanceType■■■■
■■■■ $strTmpObjectTypeGUID = $global:csvHistACLs[$index].ObjectType
■■■■ $strTmpInheritedObjectTypeGUID = $global:csvHistACLs[$index].InheritedObjectType
■■■■ $strTmpAccessControlType = $global:csvHistACLs[$index].AccessControlType
if ($strTmpAccessControlType -eq "Owner" )
{
$global:strOwnerTemplate = $strIdentityReference
}
}#End If $newSdObject
else
{
$MissingOUSdObject = New-Object PSObject -Property @{ActiveDirectoryRights=$sd
InheritedObjectType=$sdObject.InheritedObjectType;ObjectFlags=$sdObject.ObjectF
InheritanceFlags=$sdObject.InheritanceFlags;PropagationFlags=$sdObject.Propagat
$intReturned++
■■■■ If ($bolCSV)
■■■■■ {
$intCSV++
■■■■ ■■
if($OutType -eq "CSVTEMPLATE")
{
■■■■ WritePermCSV $MissingOUSdObject $strDistinguishedname $CanonicalName $str
}
else
{
$bolOUHeader = $false
WriteOUT $true $MissingOUSdObject $OUdn $CanonicalName $bolOUHeader
}
■■■■ ■ }# End If
Else
{
if ($intAclOccurence -eq 0)
{
$intAclOccurence++
$bolOUHeader = $true
WriteOUT $false $sd $strDistinguishedname $CanonicalName $bolOUHeader $
}
$bolOUHeader = $false
WriteOUT $true $MissingOUSdObject $OUdn $CanonicalName $bolOUHeader "5"
}#End !$bolCSVOnly
}
}
else
{
if($SDUsnCheck -eq $false)
{
$strDelegationNotation = "Node not in file"
$global:ProgressBarWindow.Window.Dispatcher.invoke([action]{$global:ProgressBarWindow
}
}
if ($aclcount -eq 0)
{
[System.Windows.Forms.MessageBox]::Show("No Permissions found!" , "Status")
}
else
{
if($intReturned -gt 0)
{
if($bolCSV)
{
if($OutType -eq "CSVTEMPLATE")
{
if($bolCMD)
{
if($bolToFile)
{
Write-host "Report saved in: $strFileCSV" -ForegroundColor Yellow
Write-output $strFileCSV
}
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFi
}
#If Get-Perm was called with Show then open the CSV file.
if($Show)
{
■ Invoke-Item $strFileCSV
}
}
else
{
if($bolCMD)
{
if($bolToFile)
{
$global:ArrayAllACE | export-csv -Path $strFileCSV -NoTypeInformation -NoClobber
Write-host "Report saved in: $strFileCSV" -ForegroundColor Yellow
Write-output $strFileCSV
}
else
{
$global:ArrayAllACE
}
}
else
{
$global:ArrayAllACE | export-csv -Path $strFileCSV -NoTypeInformation -NoClobber
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFi
}
#If Get-Perm was called with Show then open the CSV file.
if($Show)
{
■ Invoke-Item $strFileCSV
}
}
}
else
{
#If excel output
if($OutType -eq "EXCEL")
{
# Array with alphabet characters
$ExcelColumnAlphabet = @()
for ([byte]$c = [char]'A'; $c -le [char]'Z'; $c++)
{
$ExcelColumnAlphabet += [char]$c
}
if($bolShowCriticalityColor)
{
if($bolCMD)
{
Write-host "Report saved in: $strFileEXCEL" -ForegroundColor Yellow
Write-output $strFileEXCEL
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFileE
}
}#End if EXCEL
else
{
if($bolShowCriticalityColor)
{
Switch ($global:intShowCriticalityLevel)
{
0
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT
}
1
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT
}
2
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT
}
3
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT
}
4
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT
}
}
}
#If Get-Perm was called with Show then open the HTA file.
if($Show)
{
try
{
Invoke-Item $strFileHTA
}
catch
{
if($bolCMD)
{
Write-host "Failed to launch MSHTA.exe" -ForegroundColor Red
Write-host "Instead opening the following file directly: $strFileHTM" -ForegroundColor
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to launch MS
$global:observableCollection.Insert(0,(LogMessage -strMessage "Instead opening the
}
invoke-item $strFileHTM
}
}
}
}
}
else
{
if($bolCMD)
{
Write-host "No results" -ForegroundColor Red
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "No results" -strType "Error" -D
}
}
}# End If
}
else
{
[System.Windows.Forms.MessageBox]::Show("No objects found!" , "Status")
}
}#End if ExitCompare
}# End Try
$histSDObject = ""
$sdObject = ""
$MissingOUSdObject = ""
$newSdObject = ""
$DSobject = ""
$global:strOwner = ""
$global:csvHistACLs = ""
$secd = $null
Remove-Variable -Name "secd" -Scope Global
}
#==========================================================================
# Function■■: ConvertCSVtoHTM
# Arguments : Fle Path
# Returns ■: N/A
# Description : Convert CSV file to HTM Output
#==========================================================================
Function ConvertCSVtoHTM
{
Param($CSVInput,[boolean] $bolGUIDtoText,[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
$OutType = "HTML"
$bolReplMeta = $false
if($chkBoxSeverity.isChecked -or $chkBoxEffectiveRightsColor.isChecked)
{
$bolShowCriticalityColor = $true
}
else
{
$bolShowCriticalityColor = $false
}
If(Test-Path $CSVInput)
{
$fileName = $(Get-ChildItem $CSVInput).BaseName
■$strFileHTA = $env:temp + "\"+$global:ACLHTMLFileName+".hta"
■$strFileHTM = $env:temp + "\"+"$fileName"+".htm" ■
$global:csvHistACLs = import-Csv $CSVInput
#Test CSV file format
if(TestCSVColumns $global:csvHistACLs)
{
If ($global:csvHistACLs[0].SDDate.length -gt 1)
{
$bolReplMeta = $true
}
$colHeaders = ( $global:csvHistACLs| Get-member -MemberType 'NoteProperty' | Select-Object -E
$bolObjType = $false
Foreach ($ColumnName in $colHeaders )
{
if($ColumnName.Trim() -eq "ObjectClass")
{
$bolObjType = $true
}
}
CreateHTM $fileName $strFileHTM
CreateHTA $fileName $strFileHTA $strFileHTM $CurrentFSPath $global:strDomainDNName $glob
■ $UseCanonicalName = $chkBoxUseCanonicalName.IsChecked
InitiateHTM $strFileHTM $fileName $fileName $bolReplMeta $false $Protected $bolShowCriticality
■ InitiateHTM $strFileHTA $fileName $fileName $bolReplMeta $false $Protected $bolShowCriticalityC
$tmpOU = ""
$index = 0
while($index -le $global:csvHistACLs.count -1)
{
■
if($global:csvHistACLs[$index].Object)
{
$strOUcol = $global:csvHistACLs[$index].Object
}
else
{
$strOUcol = $global:csvHistACLs[$index].OU
}
if($strOUcol.Contains("<DOMAIN-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<DOMAIN-DN>",$global:strDomainDNName)
}
if($strOUcol.Contains("<ROOT-DN>") -gt 0)
{
■■ $strOUcol = ($strOUcol -Replace "<ROOT-DN>",$global:ForestRootDomainDN)■
}
■■ $strOU = $strOUcol
■■ $strTrustee = $global:csvHistACLs[$index].IdentityReference
■■ $strRights = $global:csvHistACLs[$index].ActiveDirectoryRights■■■■
■■ $strInheritanceType = $global:csvHistACLs[$index].InheritanceType■■■■
■■ $strObjectTypeGUID = $global:csvHistACLs[$index].ObjectType
■■ $strInheritedObjectTypeGUID = $global:csvHistACLs[$index].InheritedObjectType
■■ $strObjectFlags = $global:csvHistACLs[$index].ObjectFlags
■■ $strAccessControlType = $global:csvHistACLs[$index].AccessControlType
■■ $strIsInherited = $global:csvHistACLs[$index].IsInherited
■■ $strInheritedFlags = $global:csvHistACLs[$index].InheritanceFlags
■■ $strPropFlags = $global:csvHistACLs[$index].PropagationFlags
If ($bolReplMeta -eq $true)
{
$strTmpACLDate = $global:csvHistACLs[$index].SDDate
}
If ($UseCanonicalName -eq $true)
{
$CanonicalName = $global:csvHistACLs[$index].CanonicalName
}
$bolOUHeader = $true
WriteOUT $true $txtSdObject $strOU $CanonicalName $bolOUHeader $strColorTemp $strFi
$tmpOU = $strOU
}
else
{
$bolOUHeader = $false
WriteOUT $true $txtSdObject $strOU $CanonicalName $bolOUHeader $strColorTemp $strFi
}
■■■
$index++
■■■■
}#End While
if($bolShowCriticalityColor)
{
Switch ($global:intShowCriticalityLevel)
{
0
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT size
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT size
}
1
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT size
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT size
}
2
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT size
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT size
}
3
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT size
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT size
}
4
{
(Get-Content $strFileHTA) -replace "20141220T021111056594002014122000", '<FONT size
(Get-Content $strFileHTM) -replace "20141220T021111056594002014122000", '<FONT size
}
}
}
Invoke-Item $strFileHTA
}#else if test column names exist
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "CSV file got wrong format! File:
} #End if test column names exist
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed! $CSVInput does not exist!"
}
}# End Function
#==========================================================================
# Function■■: GetACLMeta
# Arguments : Domain Controller, AD Object DN
# Returns ■: Semi-colon separated string
# Description : Get AD Replication Meta data LastOriginatingChange, LastOriginatingDsaInvocationID
# usnOriginatingChange and returns as string
#==========================================================================
Function GetACLMeta
{
Param($DomainController,$objDN,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($objDN, "(name=*)", "base
$SecurityMasks = [System.DirectoryServices.Protocols.SecurityMasks]'Owner' -bor [System.DirectoryS
$control = New-Object System.DirectoryServices.Protocols.SecurityDescriptorFlagControl($SecurityMa
[void]$request.Controls.Add($control)
[void]$request.Attributes.Add("ntsecuritydescriptor")
[void]$request.Attributes.Add("name")
[void]$request.Attributes.Add("msDS-ReplAttributeMetaData")
$response = $LDAPConnection.SendRequest($request)
foreach ($entry in $response.Entries)
{
$index = 0
while($index -le $entry.attributes.'msds-replattributemetadata'.count -1)
{
$childMember = $entry.attributes.'msds-replattributemetadata'[$index]
$childMember = $childMember.replace("$($childMember[-1])","")
If ($([xml]$childMember).DS_REPL_ATTR_META_DATA.pszAttributeName -eq "nTSecurityDes
{
$strLastChangeDate = $([xml]$childMember).DS_REPL_ATTR_META_DATA.ftimeLastOrigin
$strInvocationID = $([xml]$childMember).DS_REPL_ATTR_META_DATA.uuidLastOriginating
$strOriginatingChange = $([xml]$childMember).DS_REPL_ATTR_META_DATA.usnOriginatin
}
$index++
}
}
if ($strLastChangeDate -eq $nul)
{
$ACLdate = $(get-date "1601-01-01" -UFormat "%Y-%m-%d %H:%M:%S")
$strInvocationID = "00000000-0000-0000-0000-000000000000"
$strOriginatingChange = "000000"
}
else
{
$ACLdate = $(get-date $strLastChangeDate -UFormat "%Y-%m-%d %H:%M:%S")
}
return "$ACLdate;$strInvocationID;$strOriginatingChange"
}
#==========================================================================
# Function■■: Get-DefaultSD
# Arguments : string ObjectClass
# Returns ■:
# Description : Create report of default Security Descriptor
#==========================================================================
Function Get-DefaultSD
{
Param( [String[]] $strObjectClass,[bool] $bolChangedDefSD,[bool]$bolSDDL,[string]$File,
[boolean]$Show,[string] $OutType,[bool]$bolShowCriticalityColor,[bool]$Assess,[string]$Criticality,[bo
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
if($OutType -eq "CSV")
{
$ToFile = $true
■If ((Test-Path $File) -eq $true)
■{
■ Remove-Item $File
■}
}
else
{
$ToFile = $false
}
$bolOUHeader = $true
$bolCompare = $false
$intNumberofDefSDFound = 0
$global:ArrayAllACE = New-Object System.Collections.ArrayList
$strColorTemp = 1
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:SchemaDN, "(&(ob
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object System.Dire
$request.Controls.Add($pagedRqc) | Out-Null
[void]$request.Attributes.Add("defaultsecuritydescriptor")
[void]$request.Attributes.Add("name")
[void]$request.Attributes.Add("msds-replattributemetadata")
$CountadObject = 0
while ($true)
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$global:Ti
#for paged search, the response for paged search result control - we will need a cookie from result la
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged retr
$CountadObject = $CountadObject + $response.Entries.Count
if($global:PageSize -gt 0)
{
if ($prrc.Cookie.Length -eq 0)
{
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
}
else
{
#exit the processing for non-paged search
break;
}
}#End While
#Load Progressbar
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$intTot = 0
#calculate percentage
$intTot = $CountadObject
if ($intTot -gt 0)
{
LoadProgressBar
}
}
$response = $null
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:SchemaDN, "(&(ob
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object System.Dire
$request.Controls.Add($pagedRqc) | Out-Null
[void]$request.Attributes.Add("defaultsecuritydescriptor")
[void]$request.Attributes.Add("name")
[void]$request.Attributes.Add("msds-replattributemetadata")
while ($true)
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$global:Ti
#for paged search, the response for paged search result control - we will need a cookie from result la
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged retr
foreach ($entry in $response.Entries)
{
#Update Progressbar
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$i++
[int]$pct = ($i/$intTot)*100
#Update the progress bar
while(($null -eq $global:ProgressBarWindow.Window.IsInitialized) -and ($intLoop -lt 20))
{
Start-Sleep -Milliseconds 1
$cc++
}
if ($global:ProgressBarWindow.Window.IsInitialized -eq $true)
{
Update-ProgressBar "Currently scanning $i of $intTot objects" $pct
}
}
$index = 0
while($index -le $entry.attributes.'msds-replattributemetadata'.count -1)
{
$childMember = $entry.attributes.'msds-replattributemetadata'[$index]
$childMember = $childMember.replace("$($childMember[-1])","")
If ($([xml]$childMember).DS_REPL_ATTR_META_DATA.pszAttributeName -eq "defaultSecurity
{
$strLastChangeDate = $([xml]$childMember).DS_REPL_ATTR_META_DATA.ftimeLastOrigin
$strVersion = $([xml]$childMember).DS_REPL_ATTR_META_DATA.dwVersion
if ($strLastChangeDate -eq $nul)
{
$strLastChangeDate = $(get-date "1601-01-01" -UFormat "%Y-%m-%d %H:%M:%S")
}
else
{
$strLastChangeDate = $(get-date $strLastChangeDate -UFormat "%Y-%m-%d %H:%M:%S")
}
}
$index++
}
if($bolChangedDefSD -eq $true)
{
if($strVersion -gt 1)
{
$strObjectClassName = $entry.Attributes.name[0]
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($bolSDDL -eq $true)
{
$strSDDL = ""
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$strSDDL = $entry.Attributes.defaultsecuritydescriptor[0]
}
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
WriteDefSDSDDLHTM $strColorTemp $strFileDefSDHTA $strFileDefSDHTM $strObjectClas
Switch ($strColorTemp)
{
"1"
■ {
■ $strColorTemp = "2"
■ }
"2"
■ {
■ $strColorTemp = "1"
■ }■
}
}
else
{
$sd = ""
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$sec.SetSecurityDescriptorSddlForm($entry.Attributes.defaultsecuritydescriptor[0])
}
$sd = $sec.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier])
if($FilterBuiltin)
{
# Filter out default and built-in security principals
$sd = @($sd | Where-Object{`
($_.IdentityReference -match "S-1-5-21-") -and `
($_.IdentityReference -notmatch $("^"+$domainsid+"-5\d{2}$")) -and
($_.IdentityReference -notmatch $("^"+$domainsid+"-4\d{2}$"))
})
}
If ($Assess)
{
Switch ($Criticality)
{
"Info" {$CriticalityFilter = 0}
"Low" {$CriticalityFilter = 1}
"Medium" {$CriticalityFilter = 2}
"Warning" {$CriticalityFilter = 3}
"Critical" {$CriticalityFilter = 4}
}
$sd = @($sd | Where-Object{Get-Criticality -Returns "Filter" $_.IdentityReference.toString(
}
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
if (($OutType -eq "CSV") -or ($OutType -eq ""))
{
WriteDefSDPermCSV $sd $entry.distinguishedName $strObjectClassName $File $bolRep
}
else
{
WriteDefSDAccessHTM $true $sd $true $strObjectClassName $strColorTemp $strFileDefS
}
}
}
}
else
{
$strObjectClassName = $entry.Attributes.name[0]
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($bolSDDL -eq $true)
{
$strSDDL = ""
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$strSDDL = $entry.Attributes.defaultsecuritydescriptor[0]
}
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
WriteDefSDSDDLHTM $strColorTemp $strFileDefSDHTA $strFileDefSDHTM $strObjectClas
Switch ($strColorTemp)
{
"1"
■ {
■ $strColorTemp = "2"
■ }
"2"
■ {
■ $strColorTemp = "1"
■ }■
}
}
else
{
$sd = ""
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
Try{
$sec.SetSecurityDescriptorSddlForm($entry.Attributes.defaultsecuritydescriptor[0])
}
catch
{
if($bolCMD)
{
Write-host "The SDDL string contains an invalid sid or a sid that cannot be translated.
Write-host "Only domain-joined computers can translate some sids." -ForegroundColo
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "The SDDL string co
$global:observableCollection.Insert(0,(LogMessage -strMessage "Only domain-joined
}
}
}
#If any access has been added report it
if($sec.access.count -gt 0)
{
$sd = $sec.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier])
if($FilterBuiltin)
{
# Filter out default and built-in security principals
$sd = @($sd | Where-Object{`
($_.IdentityReference -match "S-1-5-21-") -and `
($_.IdentityReference -notmatch $("^"+$domainsid+"-5\d{2}$")) -and
($_.IdentityReference -notmatch $("^"+$domainsid+"-4\d{2}$"))
})
}
If ($Assess)
{
Switch ($Criticality)
{
"Info" {$CriticalityFilter = 0}
"Low" {$CriticalityFilter = 1}
"Medium" {$CriticalityFilter = 2}
"Warning" {$CriticalityFilter = 3}
"Critical" {$CriticalityFilter = 4}
}
$sd = @($sd | Where-Object{Get-Criticality -Returns "Filter" $_.IdentityReference.toStrin
}
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
if (($OutType -eq "CSV") -or ($OutType -eq ""))
{
WriteDefSDPermCSV $sd $entry.distinguishedName $strObjectClassName $File $bolR
}
else
{
WriteDefSDAccessHTM $true $sd $true $strObjectClassName $strColorTemp $strFileD
}
}#End if $sec
}
}
}
if($global:PageSize -gt 0)
{
if ($prrc.Cookie.Length -eq 0)
{
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
}
else
{
#exit the processing for non-paged search
break;
}
}#End While
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$global:ProgressBarWindow.Window.Dispatcher.invoke([action]{$global:ProgressBarWindow.Window
$ProgressBarWindow = $null
Remove-Variable -Name "ProgressBarWindow" -Scope Global
}
if($intNumberofDefSDFound -gt 0)
{
if($ToFile )
{
if($bolCMD)
{
Write-host "Report saved in: $strFileCSV" -ForegroundColor Yellow
Write-output $strFileCSV
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFileCSV"
}
#If Get-Perm was called with Show then open the CSV file.
if($Show)
{
■ #Invoke-Item $strFileCSV
}
}
else
{
#If excel output
if($OutType -eq "EXCEL")
{
$global:ArrayAllACE
#| Export-Excel -path $strFileEXCEL -WorkSheetname "DefaultSD" -BoldTopRow -TableStyle M
if($bolCMD)
{
Write-host "Report saved in: $strFileEXCEL" -ForegroundColor Yellow
Write-output $strFileEXCEL
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFileEX
}
if($Show)
{
If (test-path HKLM:SOFTWARE\Classes\Excel.Application)
{
■ Invoke-Item $strFileEXCEL
}
}
}#End if EXCEL
else
{
if($bolCMD)
{
Write-host "Report saved in: $strFileDefSDHTM" -ForegroundColor Yellow
Write-output $strFileDefSDHTM
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $strFileDe
}
#If Get-Perm was called with Show then open the HTA file.
if($Show)
{
■ try
{
Invoke-Item $strFileDefSDHTA
}
catch
{
if($bolCMD)
{
Write-host "Failed to launch MSHTA.exe" -ForegroundColor Red
Write-host "Instead opening the following file directly: $strFileDefSDHTM" -ForegroundC
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Failed to launch MSHT
$global:observableCollection.Insert(0,(LogMessage -strMessage "Instead opening the fo
}
Invoke-Item $strFileDefSDHTM
}
}
}
}
}
else
{
if($bolCMD)
{
Write-host "No defaultsecuritydescriptor found!" -ForegroundColor Yellow
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "No defaultsecuritydescriptor fou
}
}
}
#==========================================================================
# Function■■: Get-DefaultSDCompare
# Arguments : string ObjectClass
# Returns ■:
# Description : Compare the default Security Descriptor
#==========================================================================
Function Get-DefaultSDCompare
{
Param( [String[]] $strObjectClass="*",
[string] $strTemplate,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS
)
$strFileDefSDHTA = $env:temp + "\"+$global:ModifiedDefSDAccessFileName+".hta"
$strFileDefSDHTM = $env:temp + "\"+$global:ModifiedDefSDAccessFileName+".htm"
$bolOUHeader = $true
$bolReplMeta = $true
$bolCompare = $true
#Indicator that a defaultsecuritydescriptor was found
$intNumberofDefSDFound = 0
CreateHTM "strObjectClass" $strFileDefSDHTM■■■■■
CreateHTA "$strObjectClass" $strFileDefSDHTA $strFileDefSDHTM $CurrentFSPath $global:strDomai
InitiateDefSDAccessHTM $strFileDefSDHTA $strObjectClass $bolReplMeta $true $strTemplate
InitiateDefSDAccessHTM $strFileDefSDHTM $strObjectClass $bolReplMeta $true $strTemplate
#Default color
$strColorTemp = 1
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:SchemaDN, "(&(ob
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object System.Dire
$request.Controls.Add($pagedRqc) | Out-Null
[void]$request.Attributes.Add("defaultsecuritydescriptor")
[void]$request.Attributes.Add("name")
[void]$request.Attributes.Add("msds-replattributemetadata")
$CountadObject = 0
while ($true)
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$global:Ti
#for paged search, the response for paged search result control - we will need a cookie from result la
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged retr
$CountadObject = $CountadObject + $response.Entries.Count
if($global:PageSize -gt 0)
{
if ($prrc.Cookie.Length -eq 0)
{
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
}
else
{
#exit the processing for non-paged search
break;
}
}#End While
#Load Progressbar
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$intTot = 0
#calculate percentage
$intTot = $CountadObject
if ($intTot -gt 0)
{
LoadProgressBar
}
}
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:SchemaDN, "(&(ob
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object System.Dire
$request.Controls.Add($pagedRqc) | Out-Null
[void]$request.Attributes.Add("defaultsecuritydescriptor")
[void]$request.Attributes.Add("name")
[void]$request.Attributes.Add("msds-replattributemetadata")
while ($true)
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$global:Ti
#for paged search, the response for paged search result control - we will need a cookie from result la
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged retr
foreach ($entry in $response.Entries)
{
$ObjectMatchResult = $false
#Update Progressbar
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$i++
[int]$pct = ($i/$intTot)*100
#Update the progress bar
while(($null -eq $global:ProgressBarWindow.Window.IsInitialized) -and ($intLoop -lt 20))
{
Start-Sleep -Milliseconds 1
$cc++
}
if ($global:ProgressBarWindow.Window.IsInitialized -eq $true)
{
Update-ProgressBar "Currently scanning $i of $intTot objects" $pct
}
}
#Counter for Metadata
$index = 0
#Get metadata for defaultSecurityDescriptor
while($index -le $entry.attributes.'msds-replattributemetadata'.count -1)
{
$childMember = $entry.attributes.'msds-replattributemetadata'[$index]
$childMember = $childMember.replace("$($childMember[-1])","")
If ($([xml]$childMember).DS_REPL_ATTR_META_DATA.pszAttributeName -eq "defaultSecurity
{
$strLastChangeDate = $([xml]$childMember).DS_REPL_ATTR_META_DATA.ftimeLastOrigin
$strVersion = $([xml]$childMember).DS_REPL_ATTR_META_DATA.dwVersion
if ($strLastChangeDate -eq $nul)
{
$strLastChangeDate = $(get-date "1601-01-01" -UFormat "%Y-%m-%d %H:%M:%S")
}
else
{
$strLastChangeDate = $(get-date $strLastChangeDate -UFormat "%Y-%m-%d %H:%M:%
}
}
$index++
}
#Get object name
$strObjectClassName = $entry.Attributes.name[0]
#Make sure strSDDL is empty
$strSDDL = ""
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$strSDDL = $entry.Attributes.defaultsecuritydescriptor[0]
}
$index = 0
#Enumerate template file
$ObjectMatchResult = $false
while($index -le $global:csvdefSDTemplate.count -1)
■ {
$strNamecol = $global:csvdefSDTemplate[$index].Name
#Check for matching object names
■■ if ($strObjectClassName -eq $strNamecol )
■■ {
$ObjectMatchResult = $true
$strSDDLcol = $global:csvdefSDTemplate[$index].SDDL
#Replace any <ROOT-DOAMIN> strngs with Forest Root Domain SID
if($strSDDLcol.Contains("<ROOT-DOMAIN>"))
{
if($global:ForestRootDomainSID -gt "")
{
$strSDDLcol = $strSDDLcol.Replace("<ROOT-DOMAIN>",$global:ForestRootDomainS
}
}
#Compare SDDL
if($strSDDL -eq $strSDDLcol)
{
$sd = ""
#Create ad security object
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$sec.SetSecurityDescriptorSddlForm($entry.Attributes.defaultsecuritydescriptor[0])
}
$sd = $sec.GetAccessRules($true, $false, [System.Security.Principal.NTAccount])
#Count ACE for applying header on fist
$intACEcount = 0
foreach($ObjectDefSD in $sd)
{
$strNTAccount = $ObjectDefSD.IdentityReference.toString()
■ If ($strNTAccount.contains("S-1-"))
■ {
■ $strNTAccount = ConvertSidToName -server $global:strDomainLongName -Sid $strNTA
■ }
$newObjectDefSD = New-Object PSObject -Property @{ActiveDirectoryRights=$ObjectD
InheritedObjectType=$ObjectDefSD.InheritedObjectType;ObjectFlags=$ObjectDefSD.O
InheritanceFlags=$ObjectDefSD.InheritanceFlags;PropagationFlags=$ObjectDefSD.Pro
#Matching color "green"
$strColorTemp = 4
#If first ACE add header
if ($intACEcount -eq 0)
■■■■ ■ {
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
$bolOUHeader = $true
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $st
}
else
{
$bolOUHeader = $false
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $st
}
#Count ACE to not ad a header
$intACEcount++
}
$newObjectDefSD = $null
$sd = $null
$sec = $null
}
else
{
$sd = ""
#Create ad security object
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$sec.SetSecurityDescriptorSddlForm($entry.Attributes.defaultsecuritydescriptor[0])
}
$sd = $sec.GetAccessRules($true, $false, [System.Security.Principal.NTAccount])
#Count ACE for applying header on fist
$intACEcount = 0
#Comare DefaultSecurityDesriptor in schema with template looking for matching and new A
foreach($ObjectDefSD in $sd)
{
#Check if matchin ACE exits, FALSE until found
$SDCompareResult = $false
$strNTAccount = $ObjectDefSD.IdentityReference.toString()
■ If ($strNTAccount.contains("S-1-"))
■ {
■ $strNTAccount = ConvertSidToName -server $global:strDomainLongName -Sid $strNTA
■ }
$newObjectDefSD = New-Object PSObject -Property @{ActiveDirectoryRights=$ObjectD
InheritedObjectType=$ObjectDefSD.InheritedObjectType;ObjectFlags=$ObjectDefSD.O
InheritanceFlags=$ObjectDefSD.InheritanceFlags;PropagationFlags=$ObjectDefSD.Pro
$sdFile = ""
#Create ad security object
$secFile = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($null -ne $strSDDLcol)
{
$secFile.SetSecurityDescriptorSddlForm($strSDDLcol)
}
$sdFile = $secFile.GetAccessRules($true, $false, [System.Security.Principal.NTAccount
foreach($ObjectDefSDFile in $sdFile)
{
If (($newObjectDefSD.IdentityReference -eq $ObjectDefSDFile.IdentityReference)
ype))
■■ ■■ {
■■■■■ $SDCompareResult = $true
■■ ■■ }
}
if ($SDCompareResult)
{
#Change from New to Match
$newObjectDefSD.State = "Match"
#Match color "Green"
$strColorTemp = 4
#If first ACE add header
if ($intACEcount -eq 0)
■■■■ ■ {
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
$bolOUHeader = $true
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $
}
else
{
$bolOUHeader = $false
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $
}
#Count ACE to not ad a header
$intACEcount++
}
else
{
#New color "Yellow"
$strColorTemp = 5
#If first ACE add header
if ($intACEcount -eq 0)
■■■■ ■ {
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
$bolOUHeader = $true
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $
}
else
{
$bolOUHeader = $false
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $
}
#Count ACE to not ad a header
$intACEcount++
}
}
$newObjectDefSD = $null
#Comare DefaultSecurityDesriptor in template with schema looking for missing ACE's
$secFile = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($null -ne $strSDDLcol)
{
$secFile.SetSecurityDescriptorSddlForm($strSDDLcol)
}
$sdFile = $secFile.GetAccessRules($true, $false, [System.Security.Principal.NTAccount])
foreach($ObjectDefSDFromFile in $sdFile)
{
#Check if matchin ACE missing, TRUE until found
$SDMissingResult = $true
$ObjectDefSDFile = New-Object PSObject -Property @{ActiveDirectoryRights=$ObjectD
InheritedObjectType=$ObjectDefSDFromFile.InheritedObjectType;ObjectFlags=$Object
InheritanceFlags=$ObjectDefSDFromFile.InheritanceFlags;PropagationFlags=$ObjectD
foreach($ObjectDefSD in $sd)
{
If (($ObjectDefSD.IdentityReference -eq $ObjectDefSDFile.IdentityReference) -and ($
■■ ■■ {
■■■■■ $SDMissingResult = $false
■■ ■■ }
}
if ($SDMissingResult)
{
#Missig´ng color "Red"
$strColorTemp = 3
#If first ACE add header
if ($intACEcount -eq 0)
■■■■ ■ {
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
$bolOUHeader = $true
WriteDefSDAccessHTM $ObjectDefSDFile $strObjectClassName $strColorTemp $
}
else
{
$bolOUHeader = $false
WriteDefSDAccessHTM $ObjectDefSDFile $strObjectClassName $strColorTemp $
}
#Count ACE to not ad a header
$intACEcount++
}
}
$secFile = $null
$sdFile = $null
$ObjectDefSDFile = $null
$ObjectDefSDFromFile = $null
$ObjectDefSD = $null
$sd = $null
$sec = $null
}#End matchin SDDL
}#End matching object name
$index++
}#End while
#Check if the schema object does not exist in template
if($ObjectMatchResult -eq $false)
{
$sd = ""
#Create ad security object
$sec = New-Object System.DirectoryServices.ActiveDirectorySecurity
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$sec.SetSecurityDescriptorSddlForm($entry.Attributes.defaultsecuritydescriptor[0])
}
$sd = $sec.GetAccessRules($true, $false, [System.Security.Principal.NTAccount])
#Count ACE for applying header on fist
$intACEcount = 0
foreach($ObjectDefSD in $sd)
{
$newObjectDefSD = New-Object PSObject -Property @{ActiveDirectoryRights=$ObjectDefSD
InheritedObjectType=$ObjectDefSD.InheritedObjectType;ObjectFlags=$ObjectDefSD.Object
InheritanceFlags=$ObjectDefSD.InheritanceFlags;PropagationFlags=$ObjectDefSD.Propaga
#Matching color "green"
$strColorTemp = 5
#If first ACE add header
if ($intACEcount -eq 0)
■■■ {
$bolOUHeader = $true
#Indicate that a defaultsecuritydescriptor was found
$intNumberofDefSDFound++
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $strFileD
}
else
{
$bolOUHeader = $false
WriteDefSDAccessHTM $newObjectDefSD $strObjectClassName $strColorTemp $strFileD
}
#Count ACE to not ad a header
$intACEcount++
}
$newObjectDefSD = $null
$sd = $null
}
}#End foreach
if($global:PageSize -gt 0)
{
if ($prrc.Cookie.Length -eq 0)
{
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
}
else
{
#exit the processing for non-paged search
break;
}
}#End While
if (($PSVersionTable.PSVersion -ne "2.0") -and ($global:bolProgressBar))
{
$global:ProgressBarWindow.Window.Dispatcher.invoke([action]{$global:ProgressBarWindow.Window
$ProgressBarWindow = $null
Remove-Variable -Name "ProgressBarWindow" -Scope Global
}
if($intNumberofDefSDFound -gt 0)
{
Invoke-Item $strFileDefSDHTA
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "No defaultsecuritydescriptor found
}
}
#==========================================================================
# Function■■: Write-DefaultSDCSV
# Arguments : string ObjectClass
# Returns ■:
# Description : Write the default Security Descriptor to a CSV
#==========================================================================
Function Write-DefaultSDCSV
{
Param(
[string]
$fileout,
$strObjectClass="*",
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
#Number of columns in CSV import
$strCSVHeaderDefsd = @"
"Name","distinguishedName","Version","ModifiedDate","SDDL"
"@
If ((Test-Path $fileout) -eq $true)
{
Remove-Item $fileout
}
$strCSVHeaderDefsd | Out-File -FilePath $fileout -Encoding UTF8
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strDC,
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:SchemaDN, "(&(ob
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object System.Dire
$request.Controls.Add($pagedRqc) | Out-Null
[void]$request.Attributes.Add("defaultsecuritydescriptor")
[void]$request.Attributes.Add("name")
[void]$request.Attributes.Add("msds-replattributemetadata")
while ($true)
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$global:Ti
#for paged search, the response for paged search result control - we will need a cookie from result la
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged retr
foreach ($entry in $response.Entries)
{
$index = 0
while($index -le $entry.attributes.'msds-replattributemetadata'.count -1)
{
$childMember = $entry.attributes.'msds-replattributemetadata'[$index]
$childMember = $childMember.replace("$($childMember[-1])","")
If ($([xml]$childMember).DS_REPL_ATTR_META_DATA.pszAttributeName -eq "defaultSecurity
{
$strLastChangeDate = $([xml]$childMember).DS_REPL_ATTR_META_DATA.ftimeLastOrigin
$strVersion = $([xml]$childMember).DS_REPL_ATTR_META_DATA.dwVersion
if ($strLastChangeDate -eq $nul)
{
$strLastChangeDate = $(get-date "1601-01-01" -UFormat "%Y-%m-%d %H:%M:%S")
}
else
{
$strLastChangeDate = $(get-date $strLastChangeDate -UFormat "%Y-%m-%d %H:%M:%S")
}
}
$index++
}
$strSDDL = ""
if($null -ne $entry.Attributes.defaultsecuritydescriptor)
{
$strSDDL = $entry.Attributes.defaultsecuritydescriptor[0]
}
$strName = $entry.Attributes.name[0]
$strDistinguishedName = $entry.distinguishedname
#Write to file
[char]34+$strName+[char]34+","+[char]34+`
$strDistinguishedName+[char]34+","+[char]34+`
$strVersion+[char]34+","+[char]34+`
$strLastChangeDate+[char]34+","+[char]34+`
$strSDDL+[char]34 | Out-File -Append -FilePath $fileout -Encoding UTF8
}
if($global:PageSize -gt 0)
{
if ($prrc.Cookie.Length -eq 0)
{
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
}
else
{
#exit the processing for non-paged search
break;
}
}#End While
$global:observableCollection.Insert(0,(LogMessage -strMessage "Report saved in $fileout" -strType "W
}
#==========================================================================
# Function■■: GetEffectiveRightSP
# Arguments :
# Returns ■:
# Description : Rs
#==========================================================================
Function GetEffectiveRightSP
{
param(
[string] $strPrincipal,
[string] $strDomainDistinguishedName,
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS
)
$global:strEffectiveRightSP = ""
$global:strEffectiveRightAccount = ""
$global:strSPNobjectClass = ""
$global:strPrincipalDN = ""
$strPrinName = ""
$SPFound = $false
if ($global:strPrinDomDir -eq 2)
{
&{#Try
$Script:CredsExt = $host.ui.PromptForCredential("Need credentials", "Please enter your user name a
$Window.Activate()
}
Trap [SystemException]
{
continue
}
$h = (get-process -id $global:myPID).MainWindowHandle # just one notepad must be opened!
[SFW]::SetForegroundWindow($h)
if($null -ne $Script:CredsExt.UserName)
{
if (TestCreds $CredsExt)
{
$global:strPinDomDC = $(GetDomainController $global:strDomainPrinDNName $true $Script:C
$global:strPrincipalDN = (GetSecPrinDN $strPrincipal $global:strPinDomDC $true -CREDS $Sc
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Bad user name or password!
$lblEffectiveSelUser.Content = ""
}
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Faild to insert credentials!" -strT
}
}
else
{
if ( $global:strDomainPrinDNName -eq $global:strDomainDNName )
{
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
$global:strPinDomDC = $global:strDC
$global:strPrincipalDN = (GetSecPrinDN $strPrincipal $global:strPinDomDC $false -CREDS $CRE
}
else
{
$global:strPinDomDC = $global:strDC
$global:strPrincipalDN = (GetSecPrinDN $strPrincipal $global:strPinDomDC $false -CREDS $CRE
}
}
if ($global:strPrincipalDN -eq "")
{
if($global:bolCMD)
{
Write-host "Could not find $strPrincipal!" -ForegroundColor Red
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Could not find $strPrincipal!" -str
$lblEffectiveSelUser.Content = ""
}
}
else
{
$SPFound = $true
$global:strEffectiveRightAccount = $strPrincipal
if($global:bolCMD)
{
#Write-host "Found security principal"
}
else
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Found security principal" -strTyp
}
if ($global:strPrinDomDir -eq 2)
{
[System.Collections.ArrayList] $global:tokens = @(GetTokenGroups -PrincipalDomDC $global:strP
if($CREDS)
{
$objADPrinipal = new-object DirectoryServices.DirectoryEntry("LDAP://$global:strPinDomDC/$g
}
else
{
$objADPrinipal = new-object DirectoryServices.DirectoryEntry("LDAP://$global:strPinDomDC/$g
}
$objADPrinipal.psbase.RefreshCache("msDS-PrincipalName")
$strPrinName = $($objADPrinipal.psbase.Properties.Item("msDS-PrincipalName"))
$global:strSPNobjectClass = $($objADPrinipal.psbase.Properties.Item("objectClass"))[$($objADPr
if (($strPrinName -eq "") -or ($null -eq $strPrinName))
{
$strPrinName = "$global:strPrinDomFlat\$($objADPrinipal.psbase.Properties.Item("samAccount
}
$global:strEffectiveRightSP = $strPrinName
$lblEffectiveSelUser.Content = $strPrinName
}
else
{
[System.Collections.ArrayList] $global:tokens = @(GetTokenGroups -PrincipalDomDC $global:strP
if($CREDS)
{
$objADPrinipal = new-object DirectoryServices.DirectoryEntry("LDAP://$global:strPinDomDC/$g
}
else
{
$objADPrinipal = new-object DirectoryServices.DirectoryEntry("LDAP://$global:strPinDomDC/$g
}
$objADPrinipal.psbase.RefreshCache("msDS-PrincipalName")
$strPrinName = $($objADPrinipal.psbase.Properties.Item("msDS-PrincipalName"))
$global:strSPNobjectClass = $($objADPrinipal.psbase.Properties.Item("objectClass"))[$($objADPr
if (($strPrinName -eq "") -or ($null -eq $strPrinName))
{
$strPrinName = "$global:strPrinDomFlat\$($objADPrinipal.psbase.Properties.Item("samAccount
}
$global:strEffectiveRightSP = $strPrinName
$lblEffectiveSelUser.Content = $strPrinName
}
}
return $SPFound
}
#==========================================================================
# Function■■: LoadProgressBar
# Arguments : n/a
# Returns ■: n/a
# Description : Open up a progress bar in a XAML window
#==========================================================================
Function LoadProgressBar
{
$global:ProgressBarWindow = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("global:ProgressBarWindow",$global:ProgressBarWind
$psCmd = [PowerShell]::Create().AddScript({
[xml]$xamlProgressBar = @"
<Window x:Class="WpfApplication1.StatusBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window" Title="Scanning..." WindowStartupLocation = "CenterScreen"
Width = "350" Height = "150" ShowInTaskbar = "True" ResizeMode="NoResize" WindowStyle="To
<Grid>
<StackPanel >
<Label x:Name="lblProgressBarInfo" Foreground="white" Content="Currently scanning 0 of 0 ob
<ProgressBar x:Name = "ProgressBar" HorizontalAlignment="Left" Height="23" Margin="10,0,0
<ProgressBar.Foreground>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="#FF237026"/>
<GradientStop Color="#FF0BF815" Offset="1"/>
<GradientStop Color="#FF0BF815" Offset="1"/>
</LinearGradientBrush>
</ProgressBar.Foreground>
</ProgressBar>
<Label x:Name="lblSkipProgressBar" Content="For increased speed, turn off the progress bar.&
</StackPanel>
</Grid>
</Window>
"@
$xamlProgressBar.Window.RemoveAttribute("x:Class")
$reader=(New-Object System.Xml.XmlNodeReader $xamlProgressBar)
$global:ProgressBarWindow.Window=[Windows.Markup.XamlReader]::Load( $reader )
$global:ProgressBarWindow.lblProgressBarInfo = $global:ProgressBarWindow.window.FindName("lb
$global:ProgressBarWindow.ProgressBar = $global:ProgressBarWindow.window.FindName("Progre
$global:ProgressBarWindow.ProgressBar.Value = 0
$global:ProgressBarWindow.Window.ShowDialog() | Out-Null
$global:ProgressBarWindow.Error = $Error
})
$psCmd.Runspace = $newRunspace
[void]$psCmd.BeginInvoke()
}
#==========================================================================
# Function■■: Update-ProgressBar
# Arguments : n/a
# Returns ■: n/a
# Description : Update progress bar in a XAML window
#==========================================================================
Function Update-ProgressBar
{
Param ($txtlabel,$valProgress)
&{#Try
$global:ProgressBarWindow.ProgressBar.Dispatcher.invoke([action]{ $global:ProgressBarWindo
}
Trap [SystemException]
{
$global:observableCollection.Insert(0,(LogMessage -strMessage "Progressbar Failed!" -strType
}
}
#==========================================================================
# Function■■: Find-RiskyTemplates
# Arguments : Configuration partition distinguishedname
# Returns ■: An array of distinguishednames for templates that are published
# Description : Find and returns an array of distinguishednames for templates that are published and h
#==========================================================================
Function Find-RiskyTemplates
{
Param(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=0,
ParameterSetName='Default')]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[String]
$ConfigurationDN="",
[Parameter(Mandatory=$false)]
[pscredential]
$CREDS)
#array Published templates names
$arrPublishedPKITemplates = New-Object System.Collections.ArrayList
#array Published templates DN
$arrPublishedTemplatesDN = New-Object System.Collections.ArrayList
# Search published for PKI templates
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global:strD
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$SearchFilter = "(objectClass=pKIEnrollmentService)"
$request = New-Object System.directoryServices.Protocols.SearchRequest("CN=Enrollment Service
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object System.D
$request.Controls.Add($pagedRqc) | Out-Null
[void]$request.Attributes.Add("certificatetemplates")
while ($true)
{
$response = $LdapConnection.SendRequest($request, (new-object System.Timespan(0,0,$global
#for paged search, the response for paged search result control - we will need a cookie from resul
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilter"
}
}
#now process the returned list of distinguishedNames and fetch required properties using ranged r
$colResults = $response.Entries
■ foreach ($objResult in $colResults)
■ {
■■ for($i=0;$i -lt $objResult.attributes.certificatetemplates.count;$i++)
{
[void]$arrPublishedPKITemplates.Add($objResult.attributes.certificatetemplates[$i])
}
}
if($global:PageSize -gt 0) {
if ($prrc.Cookie.Length -eq 0) {
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
} else {
#exit the processing for non-paged search
break;
}
}#End While
#if any results found in published template names continue to a search for the object
if($arrPublishedPKITemplates)
{
# For each template name searc for the object
Foreach($PublishedTemplate in $arrPublishedPKITemplates)
{
# Search for PKI templates objects
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$SearchFilter = "(&(objectClass=pKICertificateTemplate)(cn=$PublishedTemplate)(!(mspki-enro
$request = New-Object System.directoryServices.Protocols.SearchRequest("CN=Certificate Tem
[System.DirectoryServices.Protocols.PageResultRequestControl]$pagedRqc = new-object Syst
$request.Controls.Add($pagedRqc) | Out-Null
[void]$request.Attributes.Add("mspki-enrollment-flag")
#for paged search, the response for paged search result control - we will need a cookie from
if($global:PageSize -gt 0) {
[System.DirectoryServices.Protocols.PageResultResponseControl] $prrc=$null;
if ($response.Controls.Length -gt 0)
{
foreach ($ctrl in $response.Controls)
{
if ($ctrl -is [System.DirectoryServices.Protocols.PageResultResponseControl])
{
$prrc = $ctrl;
break;
}
}
}
if($null -eq $prrc) {
#server was unable to process paged search
throw "Find-LdapObject: Server failed to return paged response for request $SearchFilte
}
}
#now process the returned list of distinguishedNames and fetch required properties using ran
$colResults = $response.Entries
■ foreach ($objResult in $colResults)
■ {
■■ for($i=0;$i -le $objResult.attributes.certificatetemplates.count;$i++)
{
$strEnrollmentFlag = $(GetEnrollmentFlag $objResult.attributes.'mspki-enrollment-flag'[0
if(($strEnrollmentFlag -eq "") -or (-not($strEnrollmentFlag -match "CT_FLAG_PEND_AL
{
[void]$arrPublishedTemplatesDN.Add($objResult.distinguishedname)
}
}
}
if($global:PageSize -gt 0) {
if ($prrc.Cookie.Length -eq 0) {
#last page --> we're done
break;
}
#pass the search cookie back to server in next paged request
$pagedRqc.Cookie = $prrc.Cookie;
} else {
#exit the processing for non-paged search
break;
}
}#End While
}
}
}
#==========================================================================
# Function■■: GetEnrollmentFlag
# Arguments : Enrollment flags of a certificate template
# Returns ■: String of the translated values
# Description : Returns a certificate enrollment flag status
#==========================================================================
Function GetEnrollmentFlag ($EnrollmentFlag)
{
[string] $strStatus = ""
if ($EnrollmentFlag -band 0x00000001)
{ $strStatus = $strStatus + ",CT_FLAG_INCLUDE_SYMMETRIC_ALGORITHMS"}
if ($EnrollmentFlag -band 0x00000002)
{ $strStatus = $strStatus + ",CT_FLAG_PEND_ALL_REQUESTS"}
if ($EnrollmentFlag -band 0x00000004)
{ $strStatus = $strStatus + ",CT_FLAG_PUBLISH_TO_KRA_CONTAINER"}
if ($EnrollmentFlag -band 0x00000008)
{ $strStatus = $strStatus + ",CT_FLAG_PUBLISH_TO_DS"}
if ($EnrollmentFlag -band 0x00000010)
{ $strStatus = $strStatus + ",CT_FLAG_AUTO_ENROLLMENT_CHECK_USER_DS_CERTIFICATE"}
if ($EnrollmentFlag -band 0x00000020)
{ $strStatus = $strStatus + ",CT_FLAG_AUTO_ENROLLMENT"}
if ($EnrollmentFlag -band 0x00000040)
{ $strStatus = $strStatus + ",CT_FLAG_PREVIOUS_APPROVAL_VALIDATE_REENROLLMENT"}
if ($EnrollmentFlag -band 0x00000100)
{ $strStatus = $strStatus + ",CT_FLAG_USER_INTERACTION_REQUIRED"}
if ($EnrollmentFlag -band 0x00000400)
{ $strStatus = $strStatus + ",CT_FLAG_REMOVE_INVALID_CERTIFICATE_FROM_PERSONAL_STO
if ($EnrollmentFlag -band 0x00000800)
{ $strStatus = $strStatus + ",CT_FLAG_ALLOW_ENROLL_ON_BEHALF_OF"}
if ($EnrollmentFlag -band 0x00001000)
{ $strStatus = $strStatus + ",CT_FLAG_ADD_OCSP_NOCHECK"}
if ($EnrollmentFlag -band 0x00002000)
{ $strStatus = $strStatus + ",CT_FLAG_ENABLE_KEY_REUSE_ON_NT_TOKEN_KEYSET_STORAGE
if ($EnrollmentFlag -band 0x00004000)
{ $strStatus = $strStatus + ",CT_FLAG_NOREVOCATIONINFOINISSUEDCERTS"}
if ($EnrollmentFlag -band 0x00008000)
{ $strStatus = $strStatus + ",CT_FLAG_INCLUDE_BASIC_CONSTRAINTS_FOR_EE_CERTS"}
if ($EnrollmentFlag -band 0x00010000)
{ $strStatus = $strStatus + ",CT_FLAG_ALLOW_PREVIOUS_APPROVAL_KEYBASEDRENEWAL_VA
if ($EnrollmentFlag -band 0x00020000)
{ $strStatus = $strStatus + ",CT_FLAG_ISSUANCE_POLICIES_FROM_REQUEST"}
if ($EnrollmentFlag -band 0x00040000)
{ $strStatus = $strStatus + ",CT_FLAG_SKIP_AUTO_RENEWAL"}
[int] $index = $strStatus.IndexOf(",")
If($index -eq 0)
{
$strStatus = $strStatus.substring($strStatus.IndexOf(",") + 1, $strStatus.Length -1 )
}
return $strStatus
}#End function
#Number of columns in CSV import
$strCSVHeader = @"
"Object","ObjectClass","IdentityReference","PrincipalName","ActiveDirectoryRights","InheritanceType","
"@
$strCSVCompareHeader = @"
"Object","ObjectClass","IdentityReference","PrincipalName","ActiveDirectoryRights","InheritanceType","
"@
$global:myPID = $PID
$global:csvHistACLs = New-Object System.Collections.ArrayList
$strLastCacheGuidsDom = ""
$sd = ""
$global:intObjeComputer = 0
$null = Add-Type -AssemblyName System.DirectoryServices.Protocols
if($base -or $GPO)
{
# Display script info
Write-Host $ADACLScanVersion
$CREDS = $null
if($credentials)
{
$CREDS = $Credentials
}
if($Criticality)
{
$ShowCriticalityColor = $true
}
if($Output -eq "")
{
$Show = $false
}
if($AccessType.Length -gt 0)
{
$AccessFilter = $true
}
else
{
$AccessFilter = $false
}
if($ApplyTo.Length -gt 0)
{
$ACLObjectFilter = $true
}
else
{
$ACLObjectFilter = $false
}
if($FilterTrustee.Length -gt 0)
{
$FilterForTrustee = $true
}
else
{
$FilterForTrustee = $false
}
if($Permission.Length -gt 0)
{
$BolACLPermissionFilter = $true
}
else
{
$BolACLPermissionFilter = $false
}
if($FilterForTrustee -or $ACLObjectFilter -or $AccessFilter -or $Permission)
{
$ACLFilter = $True
}
else
{
$ACLFilter= $False
}
if($ShowProgressBar)
{
$global:bolProgressBar = $true
}
else
{
$global:bolProgressBar = $false
}
#Connect to Custom Naming Context
$global:bolCMD = $true
■ try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
$global:bolConnected = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
$global:bolConnected = $false
Write-host "Failed! Domain does not exist or can not be connected: $($_.Exception.InnerExcept
■ }
if($global:bolLDAPConnection -eq $true)
{
$strPrimaryCapability= $response.Entries[0].attributes.supportedcapabilities[0]
Switch ($strPrimaryCapability)
{
"1.2.840.113556.1.4.1851"
{
$global:DSType = "AD LDS"
$global:bolADDSType = $false
$global:strDomainDNName = $response.Entries[0].Attributes.namingcontexts[-1]
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
if($Port -eq "")
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
}
else
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" + $Port
}
}
}
"1.2.840.113556.1.4.800"
{
$global:DSType = "AD DS"
$global:bolADDSType = $true
$global:ForestRootDomainDN = $response.Entries[0].Attributes.rootdomainnamingcontext
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext[0]
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
if($Port -eq "")
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
}
else
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" + $Port
}
}
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDNN
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestRoo
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
}
default
{
$global:ForestRootDomainDN = $response.Entries[0].Attributes.rootdomainnamingcontext
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext[0]
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
if($Port -eq "")
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
else
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" + $Port
}
}
}
if($strNamingContextDN -eq "")
{
$strNamingContextDN = $global:strDomainDNName
}
If(CheckDNExist -sADobjectName $strNamingContextDN -strDC $global:strDC -CREDS $CRED
{
$NCSelect = $true
}
else
{
Write-Output "Failed to connect to $base"
$global:bolConnected = $false
}
}#bolLDAPConnection
} # End If D lenght
else
{
$global:bolConnected = $false
}
$bolEffective = $false
if($EffectiveRightsPrincipal.Length -gt 0)
{
if($(GetEffectiveRightSP $EffectiveRightsPrincipal $global:strDomainDNName -CREDS $CREDS)
{
$bolEffective = $true
$IncludeInherited = $true
}
else
{
break;
}
}
#Check if a naming context is selected
If ($NCSelect -eq $true)
{
■ If (!($strLastCacheGuidsDom -eq $global:strDomainDNName))
■ {
■ $global:dicRightsGuids = @{"Seed" = "xxx"}
■ CacheRightsGuids -CREDS $CREDS
■ $strLastCacheGuidsDom = $global:strDomainDNName
■ }
#Get Forest Root Domain ObjectSID
if ($global:bolADDSType)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:strDomainD
[void]$request.Attributes.Add("objectsid")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
Write-host "Failed! Domain does not exist or can not be connected: $($_.Exception.InnerExce
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:DomainSID = GetSidStringFromSidByte $response.Entries[0].attributes.objectsid.Get
}
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
Write-host "Failed! Domain does not exist or can not be connected: $($_.Exception.InnerEx
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainSID = GetSidStringFromSidByte $response.Entries[0].attributes
}
}
else
{
$global:strForestDC = $global:strDC
$global:ForestRootDomainSID = $global:DomainSID
}
}
#Verify that you could connect to the naming context
if($Global:bolLDAPConnection)
{
if($GPO -or ($base -eq "RootDSE"))
{
if(($base -eq "") -or ($base -eq "RootDSE"))
{
$base = $global:strDomainDNName
}
}
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($global
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($base, "(objectClas
[void]$request.Attributes.Add("name")
try
{
$response = $LDAPConnection.SendRequest($request)
#Set search base as the name of the output file
$strNode = fixfilename $response.Entries[0].Attributes.name[0]
}
catch
{
}
if($GPO)
{
$strNode = $strNode + "_GPOs"
}
############### COMPARE THINGS ##########
if($Template)
{
if ($(Test-Path $Template) -eq $true)
{
$global:bolCSVLoaded = $false
$strCompareFile = $Template
&{#Try
$global:bolCSVLoaded = $true
$global:csvHistACLs = import-Csv $strCompareFile
}
Trap [SystemException]
{
$strCSVErr = $_.Exception.Message
Write-Host "Failed to load CSV. $strCSVErr" -ForegroundColor Red
$global:bolCSVLoaded = $false
continue
}
#Verify that a successful CSV import is performed before continue
if($global:bolCSVLoaded)
{
#Test CSV file format
if(TestCSVColumns $global:csvHistACLs)
{
$bolContinue = $true
if($global:csvHistACLs[0].Object)
{
$strOUcol = $global:csvHistACLs[0].Object
}
else
{
$strOUcol = $global:csvHistACLs[0].OU
}
if($strOUcol.Contains("<DOMAIN-DN>") -gt 0)
{
$strOUcol = ($strOUcol -Replace "<DOMAIN-DN>",$global:strDomainDNName)
}
if($strOUcol.Contains("<ROOT-DN>") -gt 0)
{
$strOUcol = ($strOUcol -Replace "<ROOT-DN>",$global:ForestRootDomainDN)
if($global:strDomainDNName -ne $global:ForestRootDomainDN)
{
if($global:IS_GC -eq "TRUE")
{
Write-Host "You are not connected to the forest root domain: $global:ForestRo
$a = Read-Host "Do you want to continue? Press Y[Yes] or N[NO]:"
if($a -eq "Y")
{
if($global:strDC.contains(":"))
{
$global:strDC = $global:strDC.split(":")[0] + ":3268"
}
else
{
$global:strDC = $global:strDC + ":3268"
}
}
else
{
$bolContinue = $false
}
}
else
{
Write-host "You are not connected to the forest root domain: $global:ForestRo
$bolContinue = $false
}
}
}
if($txtReplaceDN.text.Length -gt 0)
{
$strOUcol = ($strOUcol -Replace $txtReplaceDN.text,$global:strDomainDNName)
}
$sADobjectName = $strOUcol
#Verify if the connection can be done
if($bolContinue)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConne
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.D
}
$request.DistinguishedName = $sADobjectName
$request.Filter = "(name=*)"
$request.Scope = "Base"
[void]$request.Attributes.Add("name")
$response = $LDAPConnection.SendRequest($request)
$ADobject = $response.Entries[0]
$strNode = fixfilename $ADobject.attributes.name[0]
}
else
{
#Set the node to empty , no connection will be done
$strNode = ""
}
}
else
{
Write-host "Wrong format in: $Template" -ForegroundColor Red
exit
}
}
}
else
{
Write-host "File not found $Template" -ForegroundColor Red
exit
}
}
############### COMPARE THINGS ##########
if($ACLObjectFilter)
{
GetSchemaObjectGUID -Domain $global:strDomainDNName -CREDS $CREDS
}
if($Targets)
{
if($Targets -eq "RiskyTemplates")
{
$allSubOU = Find-RiskyTemplates -ConfigurationDN $global:ConfigDN -CREDS $CREDS
}
}
else
{
if(-not($GPO))
{
#Get all LDAP objects to read ACL's on
$allSubOU = @(GetAllChildNodes -firstnode $base -Scope $Scope -CustomFilter $LDAPF
}
else
{
#Get all LDAP objects to read ACL's on
$allSubOU = @(GetAllChildNodes -firstnode $base -Scope $Scope -CustomFilter "(&(|(obj
}
}
if($CanonicalNames)
{
$UseCanonicalName = $true
}
else
{
$UseCanonicalName = $false
}
#If more than 0 objects returned send it to Get-Perm to read ACL's
if($allSubOU.count -gt 0)
{
#Set the path for the CSV file name
if($OutputFolder -gt "")
{
#Check if foler exist if not use current folder
if(Test-Path $OutputFolder)
{
$strFileCSV = $OutputFolder + "\" +$strNode + "_" + $global:strDomainShortName + "_a
}
else
{
Write-host "Path:$OutputFolder was not found! Writting to current folder." -ForegroundC
$strFileCSV = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomainShortName + "
}
}
else
{
$strFileCSV = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomainShortName + "_a
}
$bolAssess = if($Criticality){$true}else{$false}
if(($Output -eq "CSV") -or ($Output -eq "CSVTEMPLATE") -or ($Output -eq "HTML") -or ($O
{
$file = $true
# Check if HTML switch is selected , creates a HTML file
Switch ($Output)
{
"HTML"
{■■■
$bolCSV = $false
$strFileHTA = $env:temp + "\"+$global:ACLHTMLFileName+".hta"
#Set the path for the HTM file name
if($OutputFolder -gt "")
{
#Check if foler exist if not use current folder
if(Test-Path $OutputFolder)
{
$strFileHTM = $OutputFolder + "\"+"$global:strDomainShortName-$strNode-$glo
}
else
{
Write-host "Path:$OutputFolder was not found! Writting to current folder." -Foreg
$strFileHTM = $CurrentFSPath + "\"+"$global:strDomainShortName-$strNode-$g
}
}
else
{
$strFileHTM = $CurrentFSPath + "\"+"$global:strDomainShortName-$strNode-$glo
}
CreateHTA "$global:strDomainShortName-$strNode" $strFileHTA $strFileHTM $Curre
CreateHTM "$global:strDomainShortName-$strNode" $strFileHTM■
if($Template)
{
InitiateHTM $strFileHTA $strNode $Base $SDDate $false $Protected $ShowCritica
InitiateHTM $strFileHTM $strNode $Base $SDDate $false $Protected $ShowCritica
}
else
{
InitiateHTM $strFileHTA $strNode $Base $SDDate $false $Protected $ShowCriticality
InitiateHTM $strFileHTM $strNode $Base $SDDate $false $Protected $ShowCriticality
}
if($Template)
{
Get-PermCompare $allSubOU $SkipDefaults $SkipProtected $false $Owner $bolCSV
}
else
{
Get-Perm -AllObjectDn $allSubOU -DomainNetbiosName $global:strDomainShortNam
icalityColor -GPO $GPO -FilterBuiltin $SkipBuiltIn -TranslateGUID $Translate -RecursiveFind $Recursiv
}
Write-host "Report saved in: $strFileHTM" -ForegroundColor Yellow
Write-output $strFileHTM
}
"EXCEL"
{■
$bolCSV = $false
$ExcelModuleExist = $true
if(!$(get-module ImportExcel))
{
Write-Host "Checking for ImportExcel PowerShell Module..."
if(!$(get-module -ListAvailable | Where-Object name -eq "ImportExcel"))
{
write-host "You need to install the PowerShell module ImportExcel found in the P
$ExcelModuleExist = $false
}
else
{
Import-Module ImportExcel
$ExcelModuleExist = $true
}
}
if($ExcelModuleExist)
{
if($ExcelFile -eq "")
{
#Set the path for the Excel file name■■
if($OutputFolder -gt "")
{
#Check if foler exist if not use current folder
if(Test-Path $OutputFolder)
{
$strFileEXCEL = $OutputFolder + "\" +$strNode + "_" + $global:strDomainS
}
else
{
Write-host "Path:$OutputFolder was not found! Writting to current folder." -F
$strFileEXCEL = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomain
}
}
else
{
$strFileEXCEL = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomainSh
}
}
else
{
$strFileEXCEL = $ExcelFile
}
if($Template)
{
Get-PermCompare $allSubOU $SkipDefaults $SkipProtected $SDDate $Owner
}
else
{
Get-Perm -AllObjectDn $allSubOU -DomainNetbiosName $global:strDomainSho
$ShowCriticalityColor -GPO $GPO -FilterBuiltin $SkipBuiltIn -TranslateGUID $Translate -RecursiveFind
}
}
}
"CSVTEMPLATE"
{
$bolCSV = $true
if($Template)
{
Get-PermCompare $allSubOU $SkipDefaults $SkipProtected $false $Owner $bolC
}
else
{
Get-Perm -AllObjectDn $allSubOU -DomainNetbiosName $global:strDomainShortN
r $ShowCriticalityColor -GPO $GPO -FilterBuiltin $SkipBuiltIn -TranslateGUID $Translate -RecursiveFin
}
}
default
{
$bolCSV = $true
if($Template)
{
Get-PermCompare $allSubOU $SkipDefaults $SkipProtected $false $Owner $bolC
}
else
{
Get-Perm -AllObjectDn $allSubOU -DomainNetbiosName $global:strDomainShortN
riticalityColor -GPO $GPO -FilterBuiltin $SkipBuiltIn -TranslateGUID $Translate -RecursiveFind $Recur
}
}
}
else
{
if($RAW)
{
$bolCSV = $true
$file = $false
if($Template)
{
Get-PermCompare $allSubOU $SkipDefaults $SkipProtected $false $Owner $bolCSV
}
else
{
if($Criticality)
{
$ShowCriticalityColor = $true
}
else
{
$ShowCriticalityColor = $false
}
if($Criticality)
{
$CriticalitySelected = $true
}
else
{
$CriticalitySelected = $false
}
$global:bolLDAPConnection = $false
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection("")
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest("", "(objectClass=*)", "
if($global:bolShowDeleted)
{
[string] $LDAP_SERVER_SHOW_DELETED_OID = "1.2.840.113556.1.4.417"
[void]$request.Controls.Add((New-Object "System.DirectoryServices.Protocols.DirectoryControl
}
[void]$request.Attributes.Add("dnshostname")
[void]$request.Attributes.Add("supportedcapabilities")
[void]$request.Attributes.Add("namingcontexts")
[void]$request.Attributes.Add("defaultnamingcontext")
[void]$request.Attributes.Add("schemanamingcontext")
[void]$request.Attributes.Add("configurationnamingcontext")
[void]$request.Attributes.Add("rootdomainnamingcontext")
[void]$request.Attributes.Add("isGlobalCatalogReady")
■ try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
Write-host "Failed! Domain does not exist or can not be connected: $($_.Exception.InnerExcept
■ }
if($global:bolLDAPConnection -eq $true)
{
$strPrimaryCapability= $response.Entries[0].attributes.supportedcapabilities[0]
Switch ($strPrimaryCapability)
{
"1.2.840.113556.1.4.1851"
{
$global:DSType = "AD LDS"
$global:bolADDSType = $false
$global:strDomainDNName = $response.Entries[0].Attributes.namingcontexts[-1]
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
if($Port -eq "")
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
}
else
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" + $Port
}
}
}
"1.2.840.113556.1.4.800"
{
$global:DSType = "AD DS"
$global:bolADDSType = $true
$global:ForestRootDomainDN = $response.Entries[0].Attributes.rootdomainnamingconte
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext[0]
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
if($Port -eq "")
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
}
else
{
if(Test-ResolveDNS $response.Entries[0].Attributes.dnshostname[0])
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" + $Port
}
}
$global:strDomainPrinDNName = $global:strDomainDNName
$global:strDomainShortName = GetDomainShortName -strDomain $global:strDomainDN
$global:strRootDomainShortName = GetDomainShortName -strDomain $global:ForestR
$lblSelectPrincipalDom.Content = $global:strDomainShortName+":"
}
default
{
$global:ForestRootDomainDN = $response.Entries[0].Attributes.rootdomainnamingconte
$global:strDomainDNName = $response.Entries[0].Attributes.defaultnamingcontext[0]
$global:SchemaDN = $response.Entries[0].Attributes.schemanamingcontext[0]
$global:ConfigDN = $response.Entries[0].Attributes.configurationnamingcontext[0]
$global:IS_GC = $response.Entries[0].Attributes.isglobalcatalogready[0]
if($Port -eq "")
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0]
}
else
{
$global:strDC = $response.Entries[0].Attributes.dnshostname[0] +":" + $Port
}
}
}
if($strNamingContextDN -eq "")
{
$strNamingContextDN = $global:strDomainDNName
}
If(CheckDNExist -sADobjectName $strNamingContextDN -strDC $global:strDC -CREDS $CRED
{
$NCSelect = $true
}
else
{
Write-Output "Failed to connect to $base"
$global:bolConnected = $false
}
}#bolLDAPConnection
If ($NCSelect -eq $true)
{
■ If (!($strLastCacheGuidsDom -eq $global:strDomainDNName))
■ {
■ $global:dicRightsGuids = @{"Seed" = "xxx"}
■ CacheRightsGuids -CREDS $CREDS
■ $strLastCacheGuidsDom = $global:strDomainDNName
■ }
#Get Forest Root Domain ObjectSID
if ($global:bolADDSType)
{
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection($glob
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:strDoma
[void]$request.Attributes.Add("objectsid")
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
Write-host "Failed! Domain does not exist or can not be connected: $($_.Exception.InnerEx
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:DomainSID = GetSidStringFromSidByte $response.Entries[0].attributes.objectsid.G
}
try
■ {
$response = $LDAPConnection.SendRequest($request)
$global:bolLDAPConnection = $true
■ }
■ catch
■ {
■■ $global:bolLDAPConnection = $false
Write-host "Failed! Domain does not exist or can not be connected: $($_.Exception.Inne
■ }
if($global:bolLDAPConnection -eq $true)
{
$global:ForestRootDomainSID = GetSidStringFromSidByte $response.Entries[0].attribut
}
}
else
{
$global:strForestDC = $global:strDC
$global:ForestRootDomainSID = $global:DomainSID
}
}
$LDAPConnection = New-Object System.DirectoryServices.Protocols.LDAPConnection("")
$LDAPConnection.SessionOptions.ReferralChasing = "None"
$request = New-Object System.directoryServices.Protocols.SearchRequest($global:SchemaDN
[void]$request.Attributes.Add("name")
$response = $LDAPConnection.SendRequest($request)
#Set search base as the name of the output file
$strNode = fixfilename $response.Entries[0].Attributes.name[0]
if($SchemaObjectName -ne "*")
{
$strNode = $SchemaObjectName
}
#Get current date
$date= get-date -uformat %Y%m%d_%H%M%S
Switch ($Output)
{
"HTML"
{
#Set the path for the HTM file name
if($OutputFolder -gt "")
{
#Check if foler exist if not use current folder
if(Test-Path $OutputFolder)
{
$strFileDefSDHTM = $OutputFolder + "\"+"$global:strDomainShortName-$strNode-$g
}
else
{
Write-host "Path:$OutputFolder was not found! Writting to current folder." -Foreground
$strFileDefSDHTM = $CurrentFSPath + "\"+"$global:strDomainShortName-$strNode-
}
}
else
{
$strFileDefSDHTM = $CurrentFSPath + "\"+"$global:strDomainShortName-$strNode-$g
}
$strFileDefSDHTA = $env:temp + "\"+$global:ACLHTMLFileName+".hta"
if($bolSDDL -eq $true)
{
CreateDefaultSDReportHTA $global:strDomainLongName $strFileDefSDHTA $strFile
CreateDefSDHTM $global:strDomainLongName $strFileDefSDHTM
InitiateDefSDHTM $strFileDefSDHTM $strObjectClass
InitiateDefSDHTM $strFileDefSDHTA $strObjectClass
}
else
{
CreateHTM $strNode $strFileDefSDHTM■■■■■
CreateHTA $strNode $strFileDefSDHTA $strFileDefSDHTM $CurrentFSPath $global:str
InitiateDefSDAccessHTM $strFileDefSDHTA $strObjectClass $bolReplMeta $false "" $S
InitiateDefSDAccessHTM $strFileDefSDHTM $strObjectClass $bolReplMeta $false "" $S
}
Get-DefaultSD -strObjectClass $SchemaObjectName -bolChangedDefSD $OnlyModified -
}
"EXCEL"
{
$bolCSV = $false
$ExcelModuleExist = $true
if(!$(get-module ImportExcel))
{
Write-Host "Checking for ImportExcel PowerShell Module..."
if(!$(get-module -ListAvailable | Where-Object name -eq "ImportExcel"))
{
write-host "You need to install the PowerShell module ImportExcel found in the PSGa
$ExcelModuleExist = $false
}
else
{
Import-Module ImportExcel
$ExcelModuleExist = $true
}
}
if($ExcelModuleExist)
{ ■■
if($ExcelFile -eq "")
{
#Set the path for the Excel file name
if($OutputFolder -gt "")
{
#Check if foler exist if not use current folder
if(Test-Path $OutputFolder)
{
$strFileEXCEL = $OutputFolder + "\" +$strNode + "_" + $global:strDomainShortN
}
else
{
Write-host "Path:$OutputFolder was not found! Writting to current folder." -Foreg
$strFileEXCEL = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomainShor
}
}
else
{
$strFileEXCEL = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomainShortN
}
}
else
{
$strFileEXCEL = $ExcelFile
}
#$rslt = Get-DefaultSD -strObjectClass "*" -bolChangedDefSD $true -bolSDDL $false -S
Get-DefaultSD -strObjectClass $SchemaObjectName -bolChangedDefSD $OnlyModified
}
}
default
{
#Set the path for the CSV file name
if($OutputFolder -gt "")
{
#Check if foler exist if not use current folder
if(Test-Path $OutputFolder)
{
$strFileCSV = $OutputFolder + "\" +$strNode + "_" + $global:strDomainShortName +
}
else
{
Write-host "Path:$OutputFolder was not found! Writting to current folder." -Foreground
$strFileCSV = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomainShortName
}
}
else
{
$strFileCSV = $CurrentFSPath + "\" +$strNode + "_" + $global:strDomainShortName + "
}
Get-DefaultSD -strObjectClass $SchemaObjectName -bolChangedDefSD $OnlyModified -
}
}
}#End if $NCSelect
}# End if D
else # Else GUI will open
{
$global:bolCMD = $false
[void]$Window.ShowDialog()
}
}