Tuesday, December 29, 2015

Fix Trust Relationship if a simple Computer password reset is required

Fix Trust Relationship if a simple Computer password reset is required

http://blog.blksthl.com/2013/03/18/fix-the-trust-relationship-between-this-workstation-and-the-primary-domain-failed/

This is dead simple, but if you were not aware, you do not necessarily need to rejoin the domain if the trust relationship is broken with AD.  Just resetting the password is all .

Steps using Powershell:
  1. Login locally to the server
  2. Run the PowerShell command:
Reset-ComputerMachinePassword -Server -Credential

Restart-Computer


Thursday, December 24, 2015

Migrating Public Folders Exchang 2007 to 2013

There are lots of great blogs out there on how to do the overall migration of Public folders from previous versions of Exchange to 2013, but few of them detailed how to deal with a few choice issues that I encountered in a recent migration that I performed.


For a good, detailed, checklist of how to do the migration, see any of the following:






My migration was for 50,000 folders, and about 130GB of data.


The issues that I ran into were (but not limited to):

  •     Needing a System Attendant mailbox on each server hosting Public Folders
  •     Spaces at the end of the names of folders
  •     Invalid characters in the Alias attribute, and
  •     Invalid SMTP email addresses in Mail-Enabled Public Folders

Each of these had to be fixed before I could start the migration.


System Attendant Mailbox required

This is actually fairly well documented, but I had missed it and the symptoms in no way pointed me to the root cause of the problem.

Basically, each server that hosts a Public Folder requires this System Attendant mailbox.  In my case I had no Mailbox Databases on the PF servers.

The symptom is that in the detailed log of the PublicFolderMigrationRequest indicated "

Transient Error: MapiExceptionUnknownUser: Unable to make connection to the server. (hr=0x80004005, ec=1003)


This was resolved by creating a mailbox database on each server, and then also restarting the "Microsoft Exchange System Attendant" service.  That created the system attendant ID automatically.


Spaces at the end of a folder name


The first problem was identified when I ran the command


Get-PublicFolder -Recurse | Export-CSV C:\PFs\2010_PFStructure.csv -NoTypeInformation

  This was easy to fix following this article:


The issue with this simple script is that the script in this article runs against all folders.


Get-PublicFolder -Identity "\" -Recurse -ResultSize Unlimited | Foreach { Set-PublicFolder -Identity $_.Identity -Name $_.Name.Trim() }


To improve this, I modified the command to skip folders that did not need to be updated.  Speeds up the command significantly. I also added a log file entry for each folder being processed.

$Logfile = "Fix-Trimmed-Names-001.log"
Get-PublicFolder -Identity "\" -recurse -ResultSize Unlimited | %{
  write-host "Scanning $($_.identity)";
  add-content $logfile -value "Scanning $($_.identity)";
  if ($_.name -ne $_.name.trim() ) {
    write-host "fixing [$($_.name)]" -foregroundcolor yellow;
    add-content $logfile -value "fixing [$($_.name)]"
    Set-PublicFolder -Identity $_.Identity -name $_.name.trim()
  }
}


 Invalid characters in the Alias attribute

 The Alias property of a Public Folder cannot contain Spaces, Periods, Commas, @, and even an Apostrophe.   The following script removed these characters.  (Note that the script is a little rough, but you can figure it out).


[PS] >type .\Fix-Alias-001.ps1
$Names = get-mailpublicfolder -resultsize unlimited |?{$_.Alias -like "* *"}
#$Names = get-mailpublicfolder -resultsize unlimited |?{$_.Alias -like "*.*"}

foreach ($name in $Names) {
  $newAlias = $name.alias
  $newAlias = $newAlias.replace(" ","_")
  $newAlias = $newAlias.replace("@","&")
  $newAlias = $newAlias.replace("(","{")
  $newAlias = $newAlias.replace(")","}")
  $newAlias = $newAlias.replace(",","~")
  $newAlias = $newAlias.replace(".","~")
  $newAlias = $newAlias.replace("'","~")
  set-mailpublicfolder -identity $name.identity -alias "$newalias"
}


Invalid SMTP email addresses in Mail-Enabled Public Folders

 This seems to have occurred for reasons similar to the Alias issue.  I was told that the users did not intentionally create Public Folders as Email-Enabled, therefore, rather than dig into fixing each of the mailboxes to change teh SMTP name, we elected to simply run a "Disable-MailPublicFolder" against each of the mail-enabled public folders.   End of issue.

Tuesday, October 20, 2015

Disabling the Windows Server 2012 Lock Screen Timeout

Found this great article.

http://blog.scosby.com/post/2012/12/13/Disabling-Windows-Server-2012-Lock-Screen-Timeout.aspx

Disabling the Windows Server 2012 Lock Screen Timeout

In Server 2012 by default, the lock screen will put the monitors to sleep after 1 minute. I found myself waking the monitors too frequently. An initial web search led me to a MSDN forum post for Windows 8 that unlocked a missing Power Settings feature in Server 2012.   1.       Open the following registry key     a.       HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\7516b95f-f776-4464-8c53-06167f40cc99\8EC4B3A5-6868-48c2-BE75-4F3044BE88A7   2.       Set the following value     a.       Attributes => 2
  3.       Now open Control Panel>Power Options>Change Plan Settings>Change Advanced Power Settings     a.       The new Display section “Console lock display off timeout” is now available.     b.      Configure your “Plugged in” value accordingly (0 to disable) – I haven’t tested to see if the monitor sleep setting still applies when the screen is locked.



Also, to set the timeout in a GPO:

Configuring a Power Plan with Group Policy Preferences (by Alan Burchill)

FellTheForce@8


 

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.