Check Email Addresses Listed in Active Directory

One of the tasks that administrators often need to perform is to verify that each active directory user account has a valid email address. This is important for ensuring that users can receive notifications, access online services, and communicate with other users. There are different ways to verify the email addresses of active directory users, but in this article, we will focus on one method that uses PowerShell.

PowerShell is a scripting language that allows administrators to automate tasks and manage systems. PowerShell can interact with active directory through the ActiveDirectory module, which provides cmdlets for querying and modifying objects in the directory. To use PowerShell to verify the email addresses of active directory users, we need to follow these steps:

Continue reading “Check Email Addresses Listed in Active Directory”

How to Detect a New Domain Controller in Your Network

Some malware can create a Domain Controller to infect your network and steal data. DCShadow is a late-stage kill chain attack that allows an attacker with compromised privileged credentials to register a rogue Active Directory (AD) domain controller (DC). Then the adversary can push any changes they like via replication — including changes that grant them elevated rights and create persistence. It can be extremely difficult to detect a new Domain Controller, so you need to know how to find one if you suspect an infection.

Overview

A domain controller is a server that manages the security and authentication of users and computers in a domain. A domain is a logical grouping of network resources that share a common name and directory database. A new domain controller can be added to a domain for various reasons, such as increasing redundancy, improving performance, or expanding the network.

However, a new domain controller can also pose a security risk if it is not authorized or configured properly. An unauthorized domain controller can compromise the security of the entire domain by granting access to unauthorized users or computers, or by intercepting and modifying network traffic. Therefore, it is important to detect and monitor any new domain controllers in your network.

In this blog post, we will show you how to detect a new domain controller in your network using some simple tools and techniques. We will assume that you have administrative privileges on your network and that you are familiar with basic Windows commands and PowerShell.

Use the Netdom Command

The netdom command is a Windows command-line tool that can be used to manage domains and trust relationships. One of the functions of the netdom command is to list all the domain controllers in a domain. To use the netdom command, you need to open a command prompt as an administrator and type the following command:

netdom query dc

This command will display all the domain controllers in your current domain. You can also specify a different domain name after the dc parameter if you want to query another domain. For example:

netdom query dc example.com

The output of this command will look something like this:

List of domain controllers with accounts in the domain:

DC1DC2DC3The command completed successfully.

You can compare this output with your previous records or expectations to see if there is any new or unexpected domain controller in your domain. If you find one, you should investigate further to determine its origin and purpose.

Use the Get-ADDomainController PowerShell Cmdlet

The Get-ADDomainController PowerShell cmdlet is another tool that can be used to retrieve information about domain controllers in a domain. To use this cmdlet, you need to open a PowerShell window as an administrator and type the following command:

Get-ADDomainController -Filter *

This command will display all the domain controllers in your current domain along with some additional information, such as their name, site, operating system, IP address, and roles. You can also specify a different domain name after the -Server parameter if you want to query another domain. For example:

Get-ADDomainController -Filter * -Server example.com

The output of this command will look something like this:

DistinguishedName : CN=DC1,OU=Domain Controllers,DC=eexample, DC comDNSHostName : DC1.example.comEnabled : TrueName : DC1ObjectClass : computerObjectGUID : 12345678-1234-1234-1234-123456789012SamAccountName : DC1$SID : S-1-5-21-1234567890-1234567890-1234567890-1000Site : Default-First-Site-NameOperatingSystem : Windows Server 2019OperatingSystemVersion : 10.0 (17763)Forest : example.comDomain : example.comIPv4Address : 192.168.1.1IPv6Address : fe80::1234:5678:90ab:cdef%12IsGlobalCatalog : TrueIsReadOnly : FalseIsSeized : FalseRoles : {PDCEmulator, RIDMaster, InfrastructureMaster, SchemaMaster...}DistinguishedName : CN=DC2,OU=Domain Controllers,DC=example, DC ComDNSHostName : DC2.example.comEnabled : TrueName : DC2ObjectClass : computerObjectGUID : 23456789-2345-2345-2345-234567890123SamAccountName : DC2$SID : S-1-5-21-2345678901-2345678901-2345678901-1000Site : Default-First-Site-NameOperatingSystem : Windows Server 2019OperatingSystemVersion : 10.0 (17763)Forest : example.comDomain : example.comIPv4Address : 192.168.1.2IPv6Address : fe80::1235:5678:90ac:cdef%12IsGlobalCatalog : TrueIsReadOnly : FalseIsSeized : FalseRoles : {PDCEmulator, RIDMaster, InfrastructureMaster, SchemaMaster...}

You can also use Event ID 4742 in your Security log to monitor the changes to your registered Domain Controllers. This event shows which user initiated the change, so you know which Domain Administrator account is being used to perform the attack.

Active Directory Security Overview

Active Directory (AD) is a directory service that manages the identities and access rights of users and devices in a network. AD security settings are the policies and configurations that define how AD objects, such as users, groups, computers, and organizational units, are protected from unauthorized access or modification.

AD security settings are essential for any organization that uses AD as their directory service. They help protect the network from internal and external threats, comply with various regulations and standards, and optimize the network performance and management. However, not all AD security settings are equally important. Some settings have a greater impact on the security posture and compliance status of the network than others.

In this post, I will discuss the importance of the top 5 security settings in AD, namely:

  • Password policy
  • Account lockout policy
  • Group policy
  • Permissions and auditing
  • Kerberos policy

Password Policy

Password policy is the set of rules that govern how passwords are created, changed, and stored in AD. Password policy affects the security of user accounts and the authentication process. A strong password policy should enforce the following requirements:

  • Minimum password length
  • Password complexity
  • Password history
  • Password expiration
  • Password encryption

A strong password policy helps prevent password cracking, guessing, or phishing attacks by making passwords harder to break or steal. It also reduces the risk of password reuse or sharing by requiring users to change their passwords regularly and use different passwords for different accounts. You should look at minimum password length of 10-12 characters with complexity requirements enabled, remembering at least the last 5 passwords, etc.

Account Lockout Policy

Account lockout policy is the set of rules that govern how AD responds to failed logon attempts. Account lockout policy affects the security of user accounts and the authentication process. A reasonable account lockout policy should enforce the following requirements:

  • Account lockout threshold
  • Account lockout duration
  • Account lockout reset

A reasonable account lockout policy helps prevent brute force attacks by locking out accounts after a certain number of failed logon attempts. It also reduces the risk of denial-of-service attacks by unlocking accounts after a certain period of time or by allowing administrators to manually reset them. You should look at disabling a user account if they guess their password incorrectly 10 times in 30 minutes, and automatically enabling their account after it has been locked for 30 minutes.

Group Policy

Group policy is the set of rules that govern how AD objects are configured and managed. Group policy affects the security of users, devices, and data. A comprehensive group policy should enforce the following requirements:

  • Security settings
  • Software settings
  • Administrative templates
  • Preferences

A comprehensive group policy helps enforce consistent and secure configurations across the network by applying security settings to users, devices, and data. It also helps automate and simplify the deployment and management of software, policies, and preferences across the network.

You should minimize any GPOs linked at the root domain level as these policies will apply to all users and computers in the domain. You should also avoid blocking policy inheritance and policy enforcement.

Permissions and Auditing

Permissions and auditing are the set of rules that govern how AD objects are accessed and monitored. Permissions and auditing affect the security of users, devices, and data. A granular permissions and auditing policy should enforce the following requirements:

  • Least privilege principle
  • Role-based access control
  • Object ownership
  • Inheritance and propagation
  • Audit policy

A granular permissions and auditing policy helps ensure the confidentiality, integrity, and availability of AD objects by granting only the necessary access rights to authorized users or groups based on their roles and responsibilities. It also helps detect and deter unauthorized access or modification by recording and reporting any changes or activities on AD objects.

Kerberos Policy

Kerberos policy is the set of rules that govern how AD uses Kerberos as its primary authentication protocol. Kerberos policy affects the security of user accounts and the authentication process. A secure Kerberos policy should enforce the following requirements:

  • Ticket lifetime
  • Ticket renewal
  • Maximum tolerance for computer clock synchronization

A secure Kerberos policy helps prevent replay attacks by limiting the validity and renewability of Kerberos tickets. It also helps prevent man-in-the-middle attacks by requiring a close synchronization of computer clocks within the network. It’s advisable to set Maximum lifetime for service ticket to 600 minutes and Maximum lifetime for user ticket renewal to 7 days.

In conclusion, AD security settings are vital for any organization that uses AD as their directory service. Among them, password policy, account lockout policy, group policy, permissions and auditing, and Kerberos policy are the most important ones. They help protect the network from internal and external threats, comply with various regulations and standards, and optimize the network performance and management.

Common Active Directory Mistakes

Because of the need for Windows-based security, we commonly use Active Directory (AD) to manage user privileges. This also presents numerous challenges for administrators tasked with managing that environment and keeping critical business files safe and secure. Damage can be done by those accounts with elevated privileges, but sometimes vulnerabilities are introduced by administrators poorly managing AD. The best practices outlined by Sarbanes-Oxley and PCI audit requirements can help prevent some security issues, if you follow those best practices in a consistent and reliable way all the time. Sometime people make mistakes, and we have listed common mistakes:

  1. Users as domain administrators. Non-administrative users should not have administrative rights. Even administrative users should have a normal account that they use all the time, and a separate administrative account they only use when actually performing functions requiring elevated privileges. Ignoring the concept of least privilege is a major security issue.
  2. Accounts with elevated credentials. Most security aware organizations avoid this common mistake by giving users with elevated privileges, such as a domain administrators, a normal account to log onto their machine and a privileged account for elevated access. The main reason for the separation is to avoid security breaches such as a simple drive-by download or email attack. This also includes keeping the user accounts out of the local administrator account.
  3. Disable Object Protection. Make sure you do not disable simple warning asking you if you are sure you want to delete objects in AD. You don’t want to accidentally delete an object if it can be avoided. A better option would be to never turn off object protection.
  4. Keep obsolete accounts. Enabled user accounts that aren’t actively being used are one of biggest security threats in any organization. Develop a plan to disable and ultimately delete obsolete accounts within 60-90 days of inactivity. This can be accomplished with an automation script to third-party tools.
  5. Single Expert. A mistake many small organizations make when it comes to mission critical operations is having all their eggs in the basket of a single expert who is the only one that can make changes to AD.  You need to make sure at least two people understand, have access to, and can create and modify any AD settings in your environment.  This prevents the single point of failure in case the person who is the expert leaves the organization or is out of town for a few days and can’t be reached in an emergency.
  6. Poor Active Directory Design. Create a simple to understand and simple to maintain AD structure that is difficult to use incorrectly. Complexity breeds mistakes, so keep the structure and objects as simple as possible.
  7. No Incident Recovery plans. If someone deletes 10,000 directory objects today, how quickly can you recover AD back to normal? If an automated script improperly disables thousands of users, how do you plan to recover? Planning and testing recovery options are a must for all organizations to quickly recover from mistakes. Plan for the worse possible scenarios, and hope for the best. Have a written plan, and test different scenarios at least once per calendar year.
  8. Don’t modernize. Do not allow your core of network security to fall behind on technology. You may not want to upgrade your users to the latest version of Windows, but you should keep your AD environment up to date and never allow your environment to fall behind with the latest security improvements and features. Each and every security patch and Windows update needs to be tested and applied as a top priority.
  9. Share Accounts.  Each and every user should have their own network account. There should never be users sharing user accounts.
  10. No Password Changes. Users will never change their password if you don’t force them to change their passwords. You should force your users to change their password at least every 90 days, especially if your compliance rules require this setting.

You can get more information about Active Directory here.

Finding Last Login Date for an Active Directory User Account

You can check the Last Login Date information for a user account in Active Directory. The information for last login date is stored in an attribute called “lastLogonTimestamp”. You can check the value of “lastLogonTimestamp” using the Microsoft “ADSI Edit” tool.

  Continue reading “Finding Last Login Date for an Active Directory User Account”

Best Hacking Tools Of 2020: Bloodhound

BloodHound uses graph theory to reveal the hidden and often unintended relationships within an Active Directory environment so that an attacker can quickly understand your AD trust relationships. Attackers can use BloodHound to easily identify highly complex attack paths to find the quickest path to total dominmation, and defenders can use it to identify and eliminate those same attack paths before an attacker can compromise your network.

Enumeration Options

  • CollectionMethod – The collection method to use. This parameter accepts a comma separated list of values. Has the following potential values (Default: Default):
    • Default – Performs group membership collection, domain trust collection, local admin collection, and session collection
    • Group – Performs group membership collection
    • LocalAdmin – Performs local admin collection
    • RDP – Performs Remote Desktop Users collection
    • DCOM – Performs Distributed COM Users collection
    • GPOLocalGroup – Performs local admin collection using Group Policy Objects
    • Session – Performs session collection
    • ComputerOnly – Performs local admin, RDP, DCOM and session collection
    • LoggedOn – Performs privileged session collection (requires admin rights on target systems)
    • Trusts – Performs domain trust enumeration
    • ACL – Performs collection of ACLs
    • Container – Performs collection of Containers
    • ObjectProps – Collects object properties such as LastLogon and DisplayName
    • DcOnly – Performs collection using LDAP only. Includes Group, Trusts, ACL, ObjectProps, Container, and GPOLocalGroup.
    • All – Performs all Collection Methods except GPOLocalGroup
  • SearchForest – Search all the domains in the forest instead of just your current one
  • Domain – Search a particular domain. Uses your current domain if null (Default: null)
  • Stealth – Performs stealth collection methods. All stealth options are single threaded.
  • SkipGCDeconfliction – Skip Global Catalog deconfliction during session enumeration. This can speed up enumeration, but will result in possible inaccuracies in data.
  • ExcludeDc – Excludes domain controllers from enumeration (avoids Microsoft ATA flags 🙂 )
  • ComputerFile – Specify a file to load computer names/IPs from
  • OU – Specify which OU to enumerate

Continue reading “Best Hacking Tools Of 2020: Bloodhound”

Finding Last Password Changed for an Active Directory User Account

You can check the Last Password Changed information for a user account in Active Directory. The information for last password changed is stored in an attribute called “PwdLastSet”. You can check the value of “PwdLastSet” using the Microsoft “ADSI Edit” tool.

  Continue reading “Finding Last Password Changed for an Active Directory User Account”

Finding Last Password Changed for an Active Directory User Account

You can check the Last Password Changed information for a user account in Active Directory. The information for last password changed is stored in an attribute called “PwdLastSet”. You can check the value of “PwdLastSet” using the Microsoft “ADSI Edit” tool.

  Continue reading “Finding Last Password Changed for an Active Directory User Account”

Best Hacking Tools Of 2017: ADBrute

If you have an Active Directory environment, you want to make it as secure as possible. ADBrute allows you to test the security of your Active Directory users. When a users network account of a domain user expires or when the user account is locked due to incorrect login attempts, the domain administrator may reset the password to the default password based on company policy. If your users do not change their password after it has been reset by the administrator, it creates a major security hole in your security.

A malicious user could easily use the default password to login into the victim’s user accounts, delete, read and send mails or access other resources on the network.

ADBrute is simple to use:

  1. Run ADBrute.
  2. Enter the name of the domain controller and valid login credentials to connect to the Active Directory. The user can be any user on the domain.
  3. Click on Login and wait till the entire user list for your organization is populated from the AD.
  4. You can double click on a User to view additional information.
  5. Enter the default password for your organization and press the start button.
  6. Sit back until the program scans and enumerates users who use the default password.
  7. You can export both the lists, the entire user list as well as the weak user list to three different file formats, .csv, .txt and .xls.

You can get more information and download the tool here.

Tips and Tricks for Active Directory Management

Managing Active Directory is essential for your network security. Here are a few tips to help you better manage your Active Directory:

  1. Disable the default Guest Account – This is a security best practice recommended by Microsoft. Disabling the guest account can protect you from simple and very basic attacks. It is also an item that security auditors look for to verify you are using security best practices.
    1. Log on as a member of the Domain Admins group, and then open Active Directory Users and Computers.
    2. In the console tree (left pane), click Users.
    3. In the details pane (right pane), right-click Guest, and then click Rename.
    4. Type the fictitious first and last name and press Enter.
    5. Right-click the new name, and then click Properties.
    6. On the General tab, delete the Description “Built-in account for guest access to the computer/domain” and type in a description to resemble other user accounts (for many organizations, this will be blank).
    7. In the First name and Last name boxes, type the fictitious names.
    8. On the Account tab, type a new User logon name, using the same format you use for your other user accounts, for example, first initial and last name.
    9. Type this same new logon name in the User logon name (pre-Windows 2000) box, and then click OK.
    10. Verify that the account is disabled. The icon should appear with a red X over it. If it is enabled, right-click the new name, and then click Disable Account.
  2. Rename the default Administrator account – This is an essential security best practice. One of the first things a malicious user or hacker will do is look to compromise the default administrator account. You want to hide the default account by renaming it to something other than the default name. It is also an item that security auditors look for to verify you are using security best practices.
    1. Log on as a member of the Domain Admins group, and then open Active Directory Users and Computers.
    2. In the console tree (left pane), click Users.
    3. In the details pane (right pane), right-click Administrator, and then click Rename.               
    4. Type the fictitious first and last name and press Enter.
    5. In the Rename User dialog box, change the Full name, First name, Last name, Display name, User logon name, and User logon name (pre-Windows 2000) values to match your fictitious account name, and then click OK.                                                 
    6. In the details pane (right pane), right-click the new name, and then click Properties.
    7. On the General tab, delete the Description “Built-in account for administering the computer/domain” and type in a description to resemble other user accounts (for many organizations, this will be blank).                                                  
    8. On the Account tab, verify that the logon names are correct.
  3. Maintain Physical Security – People will often focus on system security when thinking about ways to secure your Active Directory, but physical security is also required. Make sure people can’t just walk up to your Domain Controllers and attempt to bypass your security. If there are places where you can’t prevent physical access then consider turning that instance into a Read-Only Domain Controller.
  4. Disaster Planning – Disasters will happen, and I’m not just talking about fires, hurricanes, earthquakes, and tornadoes. What will you do if you find out an entire OU, containing 100 users, was deleted by mistake last night? Do you have a plan on how to resolve that issue, or are you expecting to just know all 100 users names, security settings, etc. as well as making the time to contact each user and help them log into the network with their new password and verify their network security setting are resolved? This could take days to resolve and it would be a PR nightmare.
  5. Prohibit Shared Accounts – Never allow anybody to share accounts, especially if the account has administrator privileges. It is almost impossible to determine who performed what action if multiple people are sharing a network account. It also creates security problems when someone is terminated that might know the password.
  6. Documentation – You can’t allow the Active Directory structure to grow uncontrolled and without a plan. Document the system, and keep the document updated. By creating a structure with basic logic and control, you are less likely to allow random changes that make no sense and people will never understand. Use the description fields in the tool to make this easier, but also an external document that explains the current status and reason for the structure.
  7. Delegate Responsibilities – Don’t allow just one person to perform all the Active Directory work. Even if your backup resource is only available one or two days a week, at least they are familiar with your AD structure and corporate procedures. One day you will find that backup resource a safely net that could save the day.
  8. Single Purpose Servers – You Domain Controller should be used only for user authentication, which is Active Directory and even DNS. Don’t install other applications or utilities, including products that can lead to security vulnerabilities like Adobe Reader, Microsoft Office, and Java.
  9. Beware Storing Extra Data – There are many fields available in Active Directory, including fields like address, telephone numbers, etc. It can serve a business purpose to complete some of these fields, but you must be careful when making a decision about who should have access to this data to prevent privacy or security issues.
  10. Delay Changes – Never allow yourself or others to make changes to your Active Diretcory before the weekend. Unless it is a required change that must be made on a Friday afternoon (a user termination is a good example) then wait until Monday to make the change. It can take days for a mistake to be uncovered, and you would rather deal with those mistakes during the week than on your precious weekend.

Managing Active Directory with PowerShell

There are plenty of maintenance tasks that take a significant amount of time to manually perform. They are often avoided or left undone because there are usually more important tasks that must be completed using the limited resources available to the IT technicians.

In this article by Luca Sturlese, we see how many of these maintenance tasks can be completed using PowerShell scripts.

Inactive Users:

#requires -version 2<#.SYNOPSIS  Find and manage inactive Active Directory users..DESCRIPTION  This script allows you to specify the criteria required to identify inactive users within your AD environment. This script also allows  for the management of found users. Management of users includes one or more of the following options:- Reporting- Disabling Users- Deleting Users.PARAMETER SearchScope  Optional. Determines the search scope of what type of user you would like to include in the inactive user search. Options available are:   - All: Default option. All user types including all standard users, service accounts and never logged on accounts.   - OnlyInactiveUsers  : Only standard user accounts. This option excludes service accounts and never logged on accounts.   - OnlyServiceAccounts: Only server accounts. This option excludes standard user accounts and never logged on accounts.   - OnlyNeverLoggedOn  : Only never logged on accounts. This option excludes standard user accounts and service accounts.   - AllExceptServiceAccounts   : All user account types excluding service accounts.   - AllExceptNeverLoggedOn : All user account types excluding never logged on accounts.   Note: If not specified, the default search scope is All (i.e. all user accounts, service accounts and never logged on accounts)..PARAMETER DaysInactive  Optional. The number of days a user account hasn't logged into the domain for in order to classify it as inactive. The default option is 90  days, which means any user account that hasn't logged into the domain for 90 days or more is considered inactive and therefore managed by this  script..PARAMETER ServiceAccountIdentifier  Optional. The username prefix or postfix that is used to indetify a service account from a standard user account. The default option is 'svc'.  Determining whether an account is a service account is useful in order to be able to include or exclude service accounts from the search scope.  Note: For more information see the help information on the parameter SearchScope.   Example: All accounts with the prefix or postfix of svc (e.g. svc-MyAccount or MyAccount-svc) are identified as service accounts and can  therefore be included or exclueded from the search scope..PARAMETER ReportFilePath  Optional. This is the location where the report of inactive users will be saved to. If this parameter is not specified, the default location the  report is saved to is C:\InactiveUsers.csv.  Note: When specifying the file path, you MUST include the file name with the extension of .csv. Example: 'C:\MyReport.csv'..PARAMETER DisableUsers  Optional. If this parameter is specified, this script will disable the inactive users found based on the search scope specified.  Note: If this parameter is not specified, then by default this script WILL NOT disable any inactive users found..PARAMETER DeleteUsers  Optional. If this parameter is specified, this script will delete the inactive users found based on the search scope specified.  Note: If this parameter is not specified, then by default this script WILL NOT delete any inactive users found..INPUTS  None..OUTPUTS  Report of inactive users found. See ReportFilePath parameter for more information..NOTES  Version:1.0  Author: Luca Sturlese  Creation Date:  16.07.2016  Purpose/Change: Initial script development.EXAMPLE  Execution of script using default parameters. Default execution performs reporting of inactive AD user only, not disabling or deleting any accounts.  By default the report is saved in C:\.  .\Find-ADInactiveUsers.ps1.EXAMPLE  Reporting and disabling all user accounts, except never logged on accounts. Storing the report in C:\Reports.  .\Find-ADInactiveUsers.ps1 -SeachScope AllExceptNeverLoggedOn -ReportFilePath 'C:\Reports\DisabledUsers.csv' -DisableUsers.EXAMPLE  Find & delete all inactive users (not service accounts) that haven't logged in for the last 30 days. Include never logged on accounts in this search.  .\Find-ADInactiveUsers.ps1 -SeachScope AllExceptServiceAccounts -DaysInactive 30 -DeleteUsers.EXAMPLE  Delete all user accounts that have never been logged into. Store the report in C:\Reports.  .\Find-ADInactiveUsers.ps1 -SeachScope OnlyNeverLoggedOn -ReportFilePath 'C:\Reports\NotLoggedOnAccounts.csv' -DeleteUsers#>#---------------------------------------------------------[Script Parameters]------------------------------------------------------Param (  [Parameter(Mandatory = $false)][string][ValidateSet('All', 'OnlyInactiveUsers', 'OnlyServiceAccounts', 'OnlyNeverLoggedOn', 'AllExceptServiceAccounts', 'AllExceptNeverLoggedOn')]$SearchScope = 'All',  [Parameter(Mandatory = $false)][int]$DaysInactive = 90,  [Parameter(Mandatory = $false)][string]$ServiceAccountIdentifier = 'svc',  [Parameter(Mandatory = $false)][string]$ReportFilePath = 'C:\InactiveUsers.csv',  [Parameter(Mandatory = $false)][switch]$DisableUsers = $false,  [Parameter(Mandatory = $false)][switch]$DeleteUsers = $false)#---------------------------------------------------------[Initialisations]--------------------------------------------------------#Set Error Action to Silently Continue$ErrorActionPreference = 'SilentlyContinue'#Import Modules & Snap-insImport-Module ActiveDirectory#----------------------------------------------------------[Declarations]----------------------------------------------------------#Set Inactive Date:$InactiveDate = (Get-Date).Adddays(-($DaysInactive))#-----------------------------------------------------------[Functions]------------------------------------------------------------Function Find-Accounts {  Param ()  Begin {Write-Host "Finding inactive user accounts based on search scope specified [$SearchScope]..."  }  Process {Try {  #Set Service Account Identifier  $ServiceAccountIdentifier = '*' + $ServiceAccountIdentifier + '*'  Switch ($SearchScope) {'All' {  $global:Results = Get-ADUser -Filter { (LastLogonDate -lt $InactiveDate -or LastLogonDate -notlike "*") -and (Enabled -eq $true) } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression = {$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName}'OnlyInactiveUsers' {  $global:Results = Get-ADUser -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true -and SamAccountName -notlike $ServiceAccountIdentifier } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression = {$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName}'OnlyServiceAccounts' {  $global:Results = Get-ADUser -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true -and SamAccountName -like $ServiceAccountIdentifier } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression = {$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName}'OnlyNeverLoggedOn' {  $global:Results = Get-ADUser -Filter { LastLogonDate -notlike "*" -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression = {$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName}'AllExceptServiceAccounts' {  $global:Results = Get-ADUser -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true -and SamAccountName -notlike $ServiceAccountIdentifier -or LastLogonDate -notlike "*" } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression = {$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName}'AllExceptNeverLoggedOn' {  $global:Results = Get-ADUser -Filter { LastLogonDate -lt $InactiveDate -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression = {$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName}Default {  Write-Host -BackgroundColor Red "Error: An unknown error occcurred. Can't determine search scope. Exiting."  Break}  }}Catch {  Write-Host -BackgroundColor Red "Error: $($_.Exception)"  Break}End {  If ($?) {Write-Host 'Completed Successfully.'Write-Host ' '  }}  }}Function Create-Report {  Param ()  Begin {Write-Host "Creating report of inactive users in specified path [$ReportFilePath]..."  }  Process {Try {  #Check file path to ensure correct  If ($ReportFilePath -notlike '*.csv') {$ReportFilePath = Join-Path -Path $ReportFilePath -ChildPath '\InactiveUsers.csv'  }  # Create CSV report  $global:Results | Export-Csv $ReportFilePath -NoTypeInformation}Catch {  Write-Host -BackgroundColor Red "Error: $($_.Exception)"  Break}  }  End {If ($?) {  Write-Host 'Completed Successfully.'  Write-Host ' '}  }}Function Disable-Accounts {  Param ()  Begin {Write-Host 'Disabling inactive users...'  }  Process {Try {  ForEach ($Item in $global:Results){Disable-ADAccount -Identity $Item.DistinguishedNameWrite-Host "$($Item.Username) - Disabled"  }}Catch {  Write-Host -BackgroundColor Red "Error: $($_.Exception)"  Break}  }  End {If ($?) {  Write-Host 'Completed Successfully.'  Write-Host ' '}  }}Function Delete-Accounts {  Param ()  Begin {Write-Host 'Deleting inactive users...'  }  Process {Try {  ForEach ($Item in $global:Results){Remove-ADUser -Identity $Item.DistinguishedName -Confirm:$falseWrite-Host "$($Item.Username) - Deleted"  }}Catch {  Write-Host -BackgroundColor Red "Error: $($_.Exception)"  Break}  }  End {If ($?) {  Write-Host 'Completed Successfully.'  Write-Host ' '}  }}#-----------------------------------------------------------[Execution]------------------------------------------------------------Find-AccountsCreate-ReportIf ($DisableUsers) {  Disable-Accounts}If ($DeleteUsers) {  Delete-Accounts}

There are several more example scripts available here.

Why suser_name() might not reflect the correct AD name?

You have the ability to query the current user name in SQL Server using a basic Transact-SQL statement:

SELECT suser_name()

The problem you might eventually see is the incorrect name returned, if that users name was recently changed. Active Directory is a great product, but you might not understand why changing that persons name in AD (because of divorce, marriage, etc.) might not result in you seeing that new name in your SQL Server queries.

The explanation is simple, but it can be difficult to address.

The local security authority (LSA) caches the mapping between the SID and the user name in a local cache on the you SQL Server computer. The cached user name is not immediately synchronized with your domain controllers. The LSA on the SQL Server computer first queries the local SID cache. If an existing mapping is already in the local SID cache, the LSA returns the cached user name information instead of querying your domain controllers. This behavior is intended to improve performance.

The cache entries do time out, however chances are that recurring queries by applications keep the existing cache entry alive for the maximum lifetime of the cache entry.

If this turns out to be something that causing you issues in your environment, you can disable caching on your SQL Server instance, but you must also understand that will cause increased domain controller workload and network traffic.

To work around this issue, disable the local SID cache on the domain member computer. To do this, follow these steps:

  1. Open Registry Editor by typing regedit in the Start Search box, and then press ENTER.
  2. Locate and then right-click the following registry subkey:
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
  3. Point to New, and then click DWORD Value.
  4. Type LsaLookupCacheMaxSize, and then press ENTER.
  5. Right-click LsaLookupCacheMaxSize, and then click Modify.
  6. In the Value data box, type 0, and then click OK.
  7. Exit Registry Editor.

Provisioning SharePoint Server 2013 on Windows Azure – Part II

Problem

When you initially attempt to configure SharePoint 2013 on Azure, it will point you to a SharePoint 2013 trial in the template gallery. This is not the correct way to configure an instance of SharePoint on Azure. This template virtual image is not meant for a single standalone SharePoint Server 2013 installation. Microsoft intends for you to use SharePoint Online or Office 365, or if you wan more control you need to crate an on-premise installation.

Solution

You need to “manually” create a SharePoint environment in Azure. As a minimum, there are 4 steps (with multiple sub-steps) that you will need to complete to properly provision a SharePoint  2013 environment on Windows Azure. Your environment is unique to your needs, but this should help you understand the general steps required.

  1. Create and Configure Network components
  2. Install and Configure Domain Controller
  3. Install and Configure SQL Server
  4. Install and Configure SharePoint Server 2013

Let’s go through these steps and see what is required to successfully work our way through this configuration. You can refer to Part I to get through step 1 shown above. Several people have written articles on this subject, so I’ll attempt to just summarize here. If you need details, I hope you will seek out the details and read more on this subject.

The next step is to install and configure a domain controller.

  • Create Domain Controller VM – Go to “New Virtual Machine” and choose “Windows Server 2012 DataCenter” from the Azure Gallery. Select the size (I suggest as medium) to begin the configuration.
    • Configuring Domain Controller –  Once the Domain Controller is provisioned, click on the “Connect” button and RDP into the new instance. Click on “Add Roles and Features” and follow the basic procedures to create a domain controller.
      1. In the Server Roles section, choose “Active Directory Domain Services”.
      2. Click on “Add Features” and then on the “Confirmation” tab click on “Install”. Once this is done you may be required to restart the server. Restart and again RDP into the instance. Near “Manage this server” click on the yellow triangle and click on “Promote to Domain Controller”.
      3. Add a new Forest. Mention the domain name you want to use.
      4. You can ignore the DNS Options error about “Parent Zone”.
      5. Change the paths, if required, for the ADDS Database folder, log files folder, and SYSVOL folder.
      6. Once you click on “Install”, the prerequisites will be installed and your Domain Controllert is ready to add users.
  • Add new user accounts to the domain – This is just like on-premise installation, so we will create 4 users to this new domain:
    • “sp_farm” to manage the SharePoint farm
    • “sp_farm_db” to have sysadmin rights on SQL Server instances.
    • “sp_install” to have domain administration rights needed for installing roles and features
    • “sqlserver” to have an identity that SQL instances can run as
  • sp_install user configuration – All the users can just be added normally (“Action” –> “New” –> “User”), except sp_install. We will specifically walk through creating this user since there are some extra steps required to properly configure this user. The other 3 users are simple user creations.
    • Add “sp_install” to the Domain Admin Group
    • Go to “Domain” –> “Properties” –> “Security Tab” then click the “Advanced” button then select the “Principle” link then type “sp_install”.
    • Select “Read All Properties” and “Create Computer Objects” from the options.

You can read more on this topic here.

In future articles, we will continue to work our way through the process until we have a working SharePoint instance on Azure.

Integrating On-premises Identities with Azure Active Directory

Integrating your on-premises Active Directory with Azure Active Directory can make your users more productive by providing a common identity for accessing both cloud and on-premises network resources. With this integration users and organizations can take advantage of the following:

  • Organizations can provide users with a common hybrid identity across on-premises or cloud-based services leveraging Windows Server Active Directory and then connecting to Azure Active Directory.
  • Administrators can provide conditional access based on application resource, device and user identity, network location and multifactor authentication.
  • Users can leverage their common identity through accounts in Azure AD to Office 365, Intune, SaaS apps and third-party applications.
  • Developers can build applications that leverage the common identity model, integrating applications into Active Directory on-premises or Azure for cloud-based applications

Azure Active Directory Connect makes this integration easy and simplifies the management of your on-premises and cloud identity infrastructure. You can read more from Microsoft here and here.

 

Common Active Directory Mistakes

Because of the need for Windows-based security, we commonly use Active Directory (AD) to manage user privileges. This also presents numerous challenges for administrators tasked with managing that environment and keeping critical business files safe and secure. Damage can be done by those accounts with elevated privileges, but sometimes vulnerabilities are introduced by administrators poorly managing AD. The best practices outlined by Sarbanes-Oxle and PCI audit requirements can help prevent some security issues, if you follow those best practices is a consistent and reliable way all the time. Sometime people make mistakes, and we have listed common mistakes:

  1. Users as domain administrators. Non-administrative users should not have administrative rights. Even administrative users should have a normal account that they use all the time, and a separate administrative account they only use when actually performing functions requiring elevated privileges. Ignoring the concept of least privilege is a major security issue.
  2. Accounts with elevated credentials. Most security aware organizations avoid this common mistake by giving users with elevated privileges, such as a domain administrators, a normal account to log onto their machine and a privileged account for elevated access. The main reason for the separation is to avoid security breaches such as a simple drive-by download or email attack. This also includes keeping the user accounts out of the local administrator account.
  3. Disable Object Protection. Make sure you do not disable simple warning asking you if you are sure you want to delete objects in AD. You don’t want to accidentally delete an object if it can be avoided. A better option would be to never turn off object protection.
  4. Keep obsolete accounts. Enabled user accounts that aren’t actively being used are one of biggest security threats in any organization. Develop a plan to disable and ultimately delete obsolete accounts within 60-90 days of inactivity. This can be accomplished with an automation script to third-party tools.
  5. Single Expert. A mistake many small organizations make when it comes to mission critical operations is having all their eggs in the basket of a single expert who is the only one that can make changes to AD.  You need to make sure at least two people understand, have access to, and can create and modify any AD settings in your environment.  This prevents the single point of failure in case the person who is the expert leaves the organization or is out of town for a few days and can’t be reached in an emergency.
  6. Poor Active Directory Design. Create a simple to understand and simple to maintain AD structure that is difficult to use incorrectly. Complexity breeds mistakes, so keep the structure and objects as simple as possible.
  7. No Incident Recovery plans. If someone deletes 10,000 directory objects today, how quickly can you recover AD back to normal? If an automated script improperly disables thousands of users, how do you plan to recover? Planning and testing recovery options are a must for all organizations to quickly recover from mistakes. Plan for the worse possible scenarios, and hope for the best. Have a written plan, and test different scenarios at least once per calendar year.
  8. Don’t modernize. Do not allow you core of network security to fall behind on technology. You may not want to upgrade your users to the latest version of Windows, but you should keep your AD environment up to date and never allow your environment to fall behind with the latest security improvements and features. Each and every security patch and Windows update needs to be tested and applied as a top priority.
  9. Share Accounts.  Each and every user should have their own network account. There should never be users sharing user accounts.
  10. No Password Changes. Users will never change their password if you don’t force them to change their passwords. You should force your users to change their password at least every 90 days.

You can get more information about Active Directory here.

Query Active Directory Logins from SQL Server

If you are doing a security audit of you SQL Server logins, you might need to determine which Active Directory accounts have access to your databases.

I you have just a few database accounts and all other access is via Windows groups, you can use xp_logininfo to discover whether a windows user account had access to SQL Server – and via which groups.

exec xp_logininfo '[domain]\[username]','all'

You might also need to know what members belonged to which Active Directory group.

exec xp_logininfo '[domain]\[group]','members'

This will return all of the members in the Active Director global group (it doesn’t return information for universal groups).

You can read more information on the Microsoft site.

 

%d bloggers like this: