Wednesday, 29 January 2020

Extract AD Group Member Info




# Name Of the Groups, where we need to pull the Group information.

$GroupNames = Get-Content C:\temp\Server.txt

# Check each group once at time.

    foreach ($ADGroup in $GroupNames){

    # Check If Group having Members, if Group contains members will process the If block.

    If ((Get-ADGroupMember $ADGroup ).length -ne 0){

    Get-ADGroupMember -Identity $ADGroup | select @{Name="GroupName";expression={$ADGroup}},name,objectClass  |Out-File -Append C:\temp\Gropinfo.csv

    }

    Else {

    # If Group is empty, else block will process.

    "$ADGroup Member Value is Empty" |Out-File -Append C:\temp\Gropinfo.csv

}
}  

Tuesday, 28 January 2020

Compare Active Directory Group Members from One User To Other User

# Reference User

$Refernceuser = Get-ADUser -Identity User1 -Properties * | Select-Object MemberOf -ExpandProperty Memberof | Get-ADGroup -Properties * | Select-Object -ExpandProperty Name

# User Who need similar access to Refernce User

$User = Get-ADUser -Identity User2 -Properties * | Select-Object MemberOf -ExpandProperty Memberof | Get-ADGroup -Properties * | Select-Object -ExpandProperty Name

# Compare Group MemberInfo

Compare-Object -ReferenceObject $Refernceuser -DifferenceObject $User | Where-Object {$_.SideIndicator -eq "<=" -and $_.Inputobject -like "*Grou*"}

Check Server Group Info and Add Object To AD Group V1

          Many Scenario we push GPO, based on Server Group Member Info. The below Scrips will help us to Add Servers into Specific ADGroup. 

# Specify list of OU followed by Comma Separator.
$OUs = "OU=DomainServer,OU=DomainObjects,DC=lab,DC=local","OU=DomainAdmin,OU=DomainObjects,DC=lab,DC=local"

# Active Directory Group
$ADGroup = "CN=GroupA,OU=DomainGroup,OU=DomainObjects,DC=lab,DC=local"

# Check each OU One at time
foreach ($OU in $OUs){

# Store All Servers in each OU
$Servers = Get-Adcomputer -Filter * -SearchBase $OU

# Check each Server in Specifiy OU
foreach ($Server in $Servers){

# Collecting Server Group Memberof Information
$ServerGroupInfo = Get-ADComputer -Identity $Server -Properties * | Select-Object MemberOF -ExpandProperty MemberOF

# Check if Server is Memberof  AD Group
If($ServerGroupInfo -contains $ADGroup){

# IF Server is MemberOf ADGroup, update Log
$Log =  "$Server is MemberOF $ADGroup" |Out-File -Append ".\Report.log"
}else{
# If Server not Memberof ADGroup, Add Server object into ADGroup

Add-ADPrincipalGroupMembership -Identity $Server -MemberOf $ADGroup
# Finally Update log
$Log = "$Server is Added to $ADGroup" | Out-File -Append ".\Report.log"
}
}

}

Check Server Group Info and Add Object To AD Group

            Many Scenario we push GPO, based on Server Group Member Info. The below Scrips will help us to Add Servers into Specific ADGroup. 

# Name of The OU, where we are going to take Input Object

$OU = "OU=DomainServer,OU=DomainObjects,DC=lab,DC=local"

# Active Directory Group,

$ADGroup = "CN=GroupA,OU=DomainGroup,OU=DomainObjects,DC=lab,DC=local"

# Get Server Information

$Servers = Get-ADComputer -Filter * -SearchBase $OU

# Check each Servers if they are part of GroupA.

foreach ($Srv in $Servers){

# Checking Server Group information

   $ServerGroupMemberof = Get-ADComputer -Identity $Srv -Properties * | Select-Object MemberOf -ExpandProperty MemberOf

# Check If Server Memberof contains ADGroup

If ($ServerGroupMemberof -contains $ADGroup){

# If Server MemberShip Contains AD Group Log the Result.

$Log= "Server $Srv MembeorOf $ADGroup" |out-file -Append ".\Result.txt"

}
# IF server does not have Group Member info, it will add Group.
else {

# Adding Servers into Group

Add-ADPrincipalGroupMembership -Identity $Srv -MemberOf $ADGroup

# Storing the result in logs.
$Log = "Server $Srv Has benn MemberOF $ADGroup"|Out-File -Append ".\Result.txt"
}
}

Simple Script To Check, if Client using Correct TimeSource

# Collecting All Active Directory server Information

$ADServers = (Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ } | Select-Object name -ExpandProperty name

# Checking Local time Source from Client Computer

$Windowstime = w32tm /query /source

# Took Only hostname from Windows Time

$ClientTimeSourceHostName=$Windowstime.Split(".")[0]

# Checking If Client having current AD Server as TimeSource.

If ($ClientTimeSourceHostName -in $ADServers){
Write-Host "Computer having correct time source"

}else{
Write-Host "Computer not Using Correct TimeSource"
}

Script To Collect Os Info and Check Server State before run Commands.

# The Script combine multiple commands and combine the Result to Single output.
# Also this script check the target server before RUN commands.

function Get-LocalSysteminfo {
    param (
        $computername= (Read-Host "Enter-ComputerName")
    )

# Passing each server once at a time, to collect the data.

    foreach ($Server in $computername) {

# Before Passing Server into Script, Checking the server is online status, if server is online, data will be collect.

    $PingResult = Test-Connection $Server -Quiet
   
    If ($PingResult -eq $true){
           
    $OS = Get-WmiObject -Class Win32_operatingsystem -ComputerName $Server
    $bios = Get-wmiobject -Class Win32_bios -ComputerName $Server
    $disk = Get-wmiobject -Class win32_logicaldisk -ComputerName $Server

# Creating New PowerShell Object to Store the above information

    $obj = New-Object -TypeName psobject

    $obj | Add-Member -MemberType NoteProperty -Name Computername -Value $Server
    $obj | Add-Member -MemberType NoteProperty -Name OSVersion -Value $OS.Version
    $obj | Add-Member -MemberType NoteProperty -Name BiosSerial -Value $bios.serialnumber
    $obj | Add-Member -MemberType NoteProperty -Name disksize -Value $disk.size
    write-output $obj
    }
# If Server Unresponsive, Script will Return the name of the server. 
    else {
    Write-Host "Server is not Responding Ping $Server"
    }
}
}
Get-LocalSysteminfo no2,localhost,localhost,no5 |Format-Table -AutoSize

Tuesday, 31 December 2019

Dynamic Password Solution for Service Accounts

Dynamic Password Solution for Service Accounts


Service Accounts: -

          Service Accounts are typical User Account in AD, managing this account are quite complex then regular accounts, unlike the normal accounts this service account, have some special delegation value to perform some task on infrastructure like service, schedule task etc. with high privileges, Kerberos delegation and exception from the company password policy. Hence, the accounts do not have options to update their credentials on regular biases, if credentials manually updated by administrators, there is possibility to interrupt the respective service, so we normally do not update this credential on regular basis due to the service availability. This lead, company security threat or misplace service account credentials details. To solve this issue, Microsoft provided solution to manage such service by using MSA / gMSA.

Managed Service Accounts (MSA): -

After considering all the above challenges Microsoft has introduced Managed Service Accounts on windows server 2008 R2. However, one managed service accounts only can use with one computer. When there are operation requirements which required to share same service account in multiple hosts, MSA do not support it.

Group Managed Service Accounts (gMSA): -

Group Managed service accounts provides the same functionalities as managed service accounts, but it extends its capabilities to host the account in multiple servers. This feature has been introduced in windows server 2012. Although, gMSA is one of the Active Directory Account, the account has various feature which is currently does not have regular NETID account.

Features of Group Managed Service Accounts: -
  • Automatic Password Management.
  • Strong Password around 120 Characters, (MS TechNet info about the password, MSA’s, like computers, do not observe domain or fine-grained password policies. MSA’s use a complex, automatically generated password (240 bytes, which is 120 characters, and cryptographically random). MSA’s cannot be locked out and cannot perform interactive logons. Administrators can set an MSA password to a known value, although there’s ordinarily no justifiable reason).
  • Password unknown to any person. 
  • A single Service Account can install multiple servers. 
  • Account Support Schedule Task.  
  • Service Account password change every 30days during computer account password renewal. (This can be controlled – just like a computer’s password – with the following two DWORD Values:HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesNetLogonParameters
DisablePasswordChange = [0 or 1, default if value name does not exist is 0]
MaximumPasswordAge = [1-1,000,000 in days, default if value name does not exist is 30]).
  • Application Automatically pick the password changes, does not required to restart service / process. 
  • Automatically manage Service Principle names. 
  • While configuring the service account, we don’t need password the account, instead password field can be leave as blank. The system detects its gMSA accounts.
  • It uses Microsoft Key Distribution Service (KDS) to create and manage password for gMSA.
Schema Extension for gMSA: - 

Microsoft has introduced couple of new schema class for gMSA in windows server 2012, let’s have look.
  • MSDS-GroupManagedServiceAccount: - its derived from computer class with five additional attributes.  
  • MSDS-GroupMSAMembership: - attribute governs which computer or group of computers can retrieve gMSA password.
  • MSDS-ManagedPassword:- attribute would hold current and previous password and password change interval.
  • MSDS-ManagedPasswordInterval: - attribute will determines how often the gMSA password must change. 
  • MSDS-ManagedPasswordID: - attribute will be used by Key distribution service (KDS) to generate current password. 
  • MSDS-ManagedPasswordPreviousID: - attribute will be used to identify previous password.
Prerequisites: -

                gMSA concept to manage password dynamically, hence while service account password renewed all other domain controller must receive this update. 
  • If your domain is Windows Server 2008 R2 functional level, automatic passwords and SPN management will work.
  • If your domain is less than Windows Server 2008 R2 Domain Functional Level, automatic passwords will work. Automatic SPN management will not work, and SPN’s will have to be maintained by administrators
  • Widows server 2012 or higher domain member servers.
  • PowerShell command to manage gMSA.
  • Create a KDS root key is required for the domain controller to retrieve the gMSA password when a server request it.
KDSRootKey, Provisioning, Deprovisioning and Managing gMSA.
Generate KDS Root Key: -
Create KDS root key, this is used by KDC service on domain controller to generate password.
Add-KDSrootkey -effectiveimmediately. (default 10 hours we must wait for the replication)
Add-KDSRootKey -EffectiveTime ((get-date).addhours(-10)) (the following command will take immediate effect, however for production do not use it)
Once KDS Root key created, verify the key created successfully and enabled on domain controller.
Provisioning gMSA Service Accounts: -

Before we create gMSA, define the usage of Service Account, if account has to be installed multiple servers, create Security Group gl-gMSA-WebApp in Active Directory and add the desired servers’ objects into Group.  Managing this computer over the security group would give more administrative flexibility, in my lab S-gMSA-WebApp is the service account and server1.lab.local is the FQDN of the server.

New-ADServiceAccount -name S-gMSA-WebApp -DNSHostName Server1.lab.local -PrincipalsAllowedToRetrieveManagedPassword gl-gMSA-WebApp (If we are going to install same service account on multiple servers, add servers into gl-gMSA-WebApp group to retrieve password).
Unlike the regular NETID, the service account has default container, when you create account the account will create automatically below locations.


Once the service account is created, let’s associate it with host machine, which is called Server1.


Ok, now let’s install the gMSA account in Server1, by using Install-ADServiceaccount powershell CMDlets, by default this powershell module does not available in server, hence we need Active Directory powershell module on the server.


Once powershell module has been installed, now we shall run the below command to install the service account.
Ok so for so good, lets test our account by configuring any service to validate the functionality.


This warning quite expected, once you passed account information, account will automatically be added to your local security policy Log on as service.  


If all look good, the service will accept gMSA credentials and service will move running state, wow!...
 



After you have configured service accounts, the specific service logon option would be grayed out like above. To regain control, we need to reset the service property which associates it with a managed account.
Run the below command as an administrator
SC Managedaccount ADAM_instance1 false



Once the command completed, the service log option will become previous state as regular service.

Ok, finally the service account has been fully come to production and the service moved to running state and password will be managed domain controllers.



Configuring the gMSA for Schedule task: -
              
gMSA can be also used to configure Scheduled task, however there functional limitation, the task manager does not have option to pass our gMSA account, hence we must use PowerShell CLI instead of GUI.
            Before create schedule task via powershell, we must do some prework to configure scheduled task, lets prepare.

$Action= New-ScheduledTaskAction “c:\temp\service.bat” (What action you are going to perform, for the testing purpose I am trying to restart my custom service)

$Trigger=New-ScheduledTaskTrigger -AT 22:00 -daily
$principal = New-ScheduledTaskPrincipal -userid lab\S-gMSA-WebApp$ -logontype password (the password is not actual password; Scheduled task automatically retrieve it from DC)
Now contract the variable to configure the schedule task.
 Register-ScheduledTask LDSServiceRestart -Action $Action -Trigger $trigger -principal $principal



By using the same gMSA account, I have created another task on same server, now the gMSA account has been configured as multipurpose.

Manage GMSA Password: -

When Administrator required to troubleshoot Service account, if they required to validate the account state or password consistence, how come administrator retrieve the password, typically we all know the gMSA credentials managed by Active Directory, so there is no direct way to retrieve the password in AD, let have look how to retrieve them Reference.

Delegate password Management: -
            Now you might be understood why we created Active Directory Group and granted permission to retrieve password.



Once we granted permissions to user account, now account have elevated permissions to retrieve the password.
            As discussed, schema attributes in initial post, all passwords are stored in MSDS-ManagedPasswordID. The password is serios of encrypted binary format.

Ok, lets try to decrypt the result by using DSInternals and convert them to use for human readable format.

Oh! The dsinternals retrieved the password but the password is not like our regular NETID account, lets copy the password and test the credentials.

The account successfully authenticated with the current password😊

*********Happy Learning***********