Tuesday, October 20, 2015

Export/Import OU's from Active Directory to LAB

This is a quick and dirty but works.


Here is a simple script to export and then import the OU structure from one AD to another, such as when you want to create a lab from a production AD.


To export the Prod OU's to a CSV, enter the following command:


 Get-ADOrganizationalUnit -Filter *|select name,@{n="Path";E={($_.DistinguishedName).replace("OU="+$_.name+",","") }} | ConvertTo-Csv -NoTypeInformation |out-file -FilePath Prod-OUS-4-Import.csv


Next,  edit the domain name in the CSV to change it to the new domain.
Also, clean up the file to remove any OU's that are out of scope. 


Third, run the following script using the CSV to import the names and Path of the OU's

# Command Line Parameters
Param(
 [Parameter(Mandatory=$false,HelpMessage='CSV FIle')][string]$Inputfile=".\Prod-OUS-4-Import.csv"
)

import-module activedirectory
# Read in data
$OUS = import-csv $InputFile
$ous |ft -a  #validate data on screen

# get current OUs for errorchecking
$currentous = get-adorganizationalunit -filter *

# Create ou for each line in CSV
foreach ($ou in $ous) {
 $error.clear()
 $path = "OU=$($ou.name),$($ou.path)"
 #write-host "$path"
 If ( $currentOUS | ?{$_.DistinguishedName -eq $path } ) {
  write-host  "Exists:  OU=$($ou.name),$($ou.path) already exists" -foregroundcolor yellow
 } else {
  new-ADOrganizationalUnit -name $ou.name -path $ou.path  -ProtectedFromAccidentalDeletion:$false  -ErrorAction:silentlycontinue
  if ($error.count -gt 0) {
   write-host "Failed:  OU=$($ou.name),$($ou.path)"  -foregroundcolor red
  } else {
   write-host "Created: OU=$($ou.name),$($ou.path)"  -foregroundcolor green
  }
 }
}




Examining GPO Health

I was recently asked to evaluate an Active Directory environment to determine it's health, specifically relating to GPO's and how they were being used.

I discovered that the number and configuration of the OU's, GPO's, and contents, were a clear indication that the administration of GPO's was not well understood by the committee of people who were managing them, and that there were clearly problems being self-inflicted due to these issues.

The question, however, was how can we quickly assess whether the management of GPO's was in trouble, and also how can we quantify the issue?

The first thing to understand is that there are Recommended Best Practices from Microsoft for how to manage GPO's.  See https://technet.microsoft.com/en-us/library/cc785903(v=ws.10).aspx

But how to quantify these subjective suggestions?



First,  "Minimize the Use of the Block Policy Inheritance Feature".  


You can determine the number of OU's that have Blocked Policy Inheritance with the follow PowerShell command:

Get-ADOrganizationalUnit -Filter * | Get-GPInheritance | Where-Object {$_.GPOInheritanceBlocked}| measure

After having seen a "bad" install, I believe that the number should be less than 5% of the total number of OU's.  Or perhaps a raw number of 10-15 might be allowed.



Second, "Minimize the Use of the Enforce Feature".

How do you determine how many GPO's have Enforce Enabled?  How do I know where these are linked?
One quick way is to list all Links that are Enforced.
Use the following command:
Get-ADOrganizationalUnit -Filter * | Get-GPInheritance | Foreach {$_.GPOLinks } | Where {$_.Enforced} |  select DisplayName,Enabled,Enforced,Target

Another is to list the full set of GPO's linked to a single OU.  Example: for the OU=Servers there
Get-ADOrganizationalUnit "ou=servers,ou=corp,dc=mydomain,dc=com" | Get-GPInheritance |%{ $_.inheritedgpolinks }

This command will list the same information that is displayed in the GPMC GUI under the "Group Policy Inheritance" tab.  Note that the Order property is the order of the source GPO order on the applied OU, not the resulting order in the reported OU.  The property is listed in the precedence order of execution (backwards of course).

To report all OUs, and all links in all OU's, requires a bit more work.
$OUs = Get-ADOrganizationalUnit -Filter * | select DistinguishedName,LinkedGroupPolicyObjects,Name
$OUs += Get-ADDomain
$report = foreach ($ou in $OUs) {
   if ($ou.LinkedGroupPolicyObjects) {
   $inher = Get-GPInheritance -target $ou.DistinguishedName
   $count = 0
     foreach ($link in $inher.inheritedGpoLinks) {
       $count += 1
       "" | select-Object -property @{n="ou";E={$inher.Path}},
    @{N="Order";E={$count}},
       @{n="GPOname";e={$link.Displayname}},
    @{N="Enabled";E={$link.enabled}},
    @{N="Enforced";E={$link.enforced}},
    @{N="Target";E={$link.Target}}
     }
   }
  }

$report |export-csv .\GPO-Links-cwInheritance.csv  -NoTypeInformation


Wednesday, June 17, 2015

Querying Event Logs using XML

I have been working for a little while on creating tools for an administrator to be able to manage an Active Directory for Least Privileges Principles, and to secure AD Access.

Specifically here, I will be talking about configuring Monitoring and Alerts for suspicious behavior in the administration of Active Directory.

The first activity to monitor and to generate an alert is a logon by a member of the Microsoft Privileged Groups.  It is assumed that you have read and are following the Microsoft Best Practice of normally having ZERO members of the Privileged Groups (Domain Admins, Enterprise Admins, etc).  Membership in these groups is only granted temporarily in order to perform a specific task.   The Intruder Attack Surface of your Ad is minimized by reducing the time that this elevation of privileges exist.

But what about abuse of privilege, or unauthorized role elevation?

By monitoring and alerting on every logon and logoff on any computer of anyone with this group membership, you are able to track the activities of the role, and able to detect unauthorized access.

Here is how it is done.

(see http://blogs.technet.com/b/askds/archive/2008/03/11/special-groups-auditing-via-group-policy-preferences.aspx for background on these instructions )
  • Configure a GPO that creates a Registry entry for "SpecialGroups".  
    1.   First, Document all of the SID's for the groups that you wish to monitor.  
      1. In PowerShell, import the Active Directory Module.
      2. For each group in scope, type a Get-ADGroup -id "Domain Admins", etc.
      3. Note the SID of that group.
    2. Create a GPO To distribute the Special Group Registry key
      1. GPMC -> Edit GPO -> Computer Configuration -> Preferences -> Windows Settings - Registry
      2. Create a new Registry Entry:
        Key Path: HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Audit
        Value Name: SpecialGroups
        Value Type: REG_SZ
        Value Data: S-1-5-21-3496112146-2253716704-1307938399-512;S-1-5-21-3496112146-2253716704-1307938399-519;S-1-5-32-544
        (Note: use the SID's that you documented in step 1, separated by ";"
    3. Apply the GPO to all computers that you want to monitor for "SpecialGroups" Logon.
    4. The final step is to set up monitoring of Event ID 4964.    (I will add a PowerShell script to run for this purpose...  Stay tuned.)

Monday, May 25, 2015

Securing Active Directory with the Least Privilege Principle

Securing AD with Least Privilege Principle

I have been working for the last number of weeks on a project to secure AD, and to reduce the Attack Surface of AD.

If you are not on board with why you need to secure AD from compromise, and to establish good security work habits, please view one or more of the following videos.  These show how incredibly easy it is for a hacker to break in to your systems.

From Microsoft Ignite 2015.

Next step is to review and become familiar with Microsoft's Best Practices for Securing AD.
http://www.microsoft.com/en-ca/download/details.aspx?id=38785

Some of the key components of these documents and video's are:
  • Set up your Active Directory so that there are normally ZERO members of the privileged groups.
    Use Role-Based "Least Privileged Principle" and elevate the role of your senior Admin to Domain Admins just for the duration required to perform the task.
  • Never assign a Service Account to the Privileged Groups (Domain Admin).
    It is easy for a hacker to ask a server what Service Accounts exist, and then they can focus their attack on those accounts.
  • Never log in to a workstation with a Domain Admin ID.
  • Set up Alerts for logins to workstations from any members of the AD Privileged groups.
  • Restrict access to back-end servers from anything but their corresponding front-end servers.
  • Enable Filewall and IPSEC rules to only allow access to important servers from trusted hosts using trusted ID's.  
  • ...

Saturday, March 14, 2015

How Anonymous Relay works in Exchange 2013


How Anonymous Relay works in Exchange 2013


Summary of commands:

$server = "LAB-EX2013"
$ReceiveConnector = "MyRelay"

New-ReceiveConnector -Name $ReceiveConnector -Usage 'Custom' -Bindings '0.0.0.0:25' -RemoteIPRanges '10.10.10.7' -Server $server -TransportRole FrontendTransport

Get-ReceiveConnector $ReceiveConnector | Add-ADPermission -User “NT AUTHORITY\ANONYMOUS LOGON” -ExtendedRights “Ms-Exch-SMTP-Accept-Any-Recipient”

Get-RecieveConnector $ReceiveConnector | select Tarp*,Conn*,Max*

Get-ReceiveConnector -Identity $ReceiveConnector | Set-ReceiveConnector -TarpitInterval 00:00:00 -ConnectionTimeout 00:30:00 -ConnectionInactivityTimeout 00:20:00 -MaxAcknowledgementDelay 00:00:00 -MaxInboundConnection 10000 -MaxInboundConnectionPercentagePerSource 100 -MaxInboundConnectionPerSource unlimited

Also see:

Monday, March 9, 2015

Installing Exchange 2013 CU's in a MultiSite,MultiServer environment

Installing Exchange 2013 CU's in a MultiSite,MultiServer environment.

I recently attempted to install Exchange 2013 CU7 in an environment with 4 Exchange servers spread across 2 Sites.  The servers were at Exchange 2013 SP1 (CU5?).

It did not start out well until I found this set of instructions from Paul Cunningham.
http://exchangeserverpro.com/exchange-2013-installing-cumulative-updates/

In summary, perform the following:
  1. Choose a server in the site that contains the AD FSMO Roles.
    (This may only apply to Exch2013 SP1, since there is a bug that CU7 fixes, in which you cannot launch ECP on a server that is in a remote site to the user's Mailbox.  I suspect this also applies to the FSMO role of PDC.
    The install initially failed the pre-requisite check with a bunch of nonsensical errors saying that the user ID was not a member of the required groups, etc.)
  2. Perform the following to prepare the Exchange Server for upgrade:
    $server = "ThisServer"
    Set-ServerComponentState $server -Component Hubtransport -state draining -Requester maintenance
    Set-ServerComponentState $server -Component ServerWideOffLine -state inactive -Requester maintenance
    Suspend-ClusterNode -name $server
    Set-MailboxServer $server -DatabaseCopyActivationDisabledAndMoveNow $true
    Get-MailboxServer $server | select databasec*
    Set-MailboxServer $server -DatabaseCopyAutoActivationPolicy blocked
    Set-ServerComponentState $server -Component ServerWideOffLine -state inactive -Requester maintenance

  3. Install the Cumulative update
  4. Perform the following to return the Exchange Server to service:
    Set-ServerComponentState $server -Component ServerWideOffLine -state active -Requester maintenance
    Resume-ClusterNode -name $server
    Set-MailboxServer $server -DatabaseCopyAutoActivationPolicy unrestricted
    Set-MailboxServer $server -DatabaseCopyActivationDisabledAndMoveNow $false
    Set-ServerComponentState $server -Component Hubtransport -state active -Requester maintenance

Thursday, January 22, 2015

How to recreate missing Arbitration User Accounts

Recreate and enable missing arbitration user accounts and mailboxes in Exchange Serve

These are a couple of article explaining the process of recreating and enable missing arbitration users and mailboxes.
It addresses the issue of lost or deleted system mailboxes and how to get them back.