Tuesday, 30 December 2014

Start, Stop and Restart Windows Service using C#

You can start, stop and restart a windows service programmatically in C# using .NET build-in class ServiceController. To use ServiceController class, you need to add the namespace "System.ServiceProcess".

Summary:

Start Windows Service using C#

Use the below C# method to start a service by passing service name as argument. This function start the given windows service and waits until the service is running or until given timeout occurs.
public static void StartService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    // Wait Timeout to get running status
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Running)
    {
        // Start Service
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }
    else
    {
        // Service already started;
    }
}

Stop Windows Service using C#

Use the below C# method to stop a service by passing service name as argument. This function stop the given windows service and waits until the service is stopped or until given timeout occurs.
public static void StopService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    // Wait Timeout to get stopped status
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Stopped)
    {
        // Stop Service
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    else
    {
        // Service already stopped;
    }
}

Restart Windows Service using C#

There is no direct C# function to restart a service, so, we need do it by two step process, first stop the given service and start the service again. Use the below C# method to restart a service by passing service name as argument. You can give some extra timeout if your service takes more time to stop or start.
public static void RestartService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    TimeSpan timeout = TimeSpan.FromMinutes(1);
    if (service.Status != ServiceControllerStatus.Stopped)
    {
        // Stop Service
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    }
    //Restart service
    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}

Monday, 29 December 2014

Start, Stop and Restart Windows Service using Powershell

In Powershell, we have dedicated cmdlets for every operations to manage Windows Services like Start, Stop, Restart and to display information of a Windows Service and you can even easily manage Services from Remote Computer.

Summary:

Start Windows Service using Powershell

You can start a windows service by using Start-Service cmdlet.
Start-Service <service-name> -PassThru
The parameter -PassThru force the command to wait until service started and displays its running status.
Start-Service "RemoteRegistry" -PassThru
Start, Stop and Restart Windows Service using Powershell
If you want to start a service by its display name, you can do it by simply passing display name with the argument -displayname.
Start-Service -displayname <service-display-name> -PassThru
Below command start the RemoteRegistry service by using its -display name "Remote Registry".
Start-Service -displayname "Remote Registry" -PassThru

Stop Windows Service using Powershell

You can stop a windows service by using the Powershell cmdlet Stop-Service.
Stop-Service <service-name> -PassThru
Here, The parameter -PassThru force the command to wait until service stopped and displays status.
Stop-Service "RemoteRegistry" -PassThru

Restart Windows Service using Powershell

You can restart a windows service by using the Powershell cmdlet Restart-Service.
Restart-Service <service-name> -PassThru
Here, the parameter -PassThru force the command to wait until the service get restarted completed and displays its running status.
Restart-Service "RemoteRegistry" -PassThru
Start, Stop and Restart Windows Service using Powershell

Start, Stop and Restart Windows Service in Remote Computer

If you want to start, stop and restart a service in Remote machine, you can do it by using two Powershell cmdlets Get-Service and any one of the manage service cmdlet. First, you can get the windows service object from remote computer by using Get-Service cmdlet and you can do any action like Start,Stop and Restart by using Remote Service object.
Get-Service <service-name> -ComputerName <remote-pc-name> | Start-Service -PassThru
Start the RemoteRegistry service in Win7-PC by using below command:
Get-Service "RemoteRegistry" -ComputerName "Win7-PC" | Start-Service -PassThru
Restart the RemoteRegistry service in Win7-PC by using below command:
Get-Service "RemoteRegistry" -ComputerName "Win7-PC" | Restart-Service -PassThru
Stop the RemoteRegistry service in Win7-PC by using below command:
Get-Service "RemoteRegistry" -ComputerName "Win7-PC" | Stop-Service -PassThru

List all Windows Services and its running status

You can list all the services with display name and running status by using Powershell cmdlet Get-Service.
Get-Service
Start, Stop and Restart Windows Service using Powershell
Pass service name, if you want to get status of a single windows service.
Get-Service "RemoteRegistry"

Group Policy Fix : Add operation failed. Unable to extract deployment information from the package.

Hi, I ran into this error below when trying to add a package to my Group Policy for Software Installation:
Add operation failed.  Unable to extract deployment information from the package.  Run validation on the package to ensure that the package is correct.
Then I started to analyze through event log and found the error event 103 with below message:
Event ID:      103
Description:   Software Installation failed to deploy package MySoftwareSetup.msi.  The following error was encountered: Logon Failure: The target account name is incorrect.
From these two inputs, I have started my analyze work and most of solutions are suggested, it could be a permission issue on the Group Policy Template object.

Fix/Solution: Add operation failed. Unable to extract deployment information from the package

Browse the Sysvol directory (\\domainname\Sysvol\) from Start\Run. then you will get below error message. .
\\mydomain.local\Sysvol is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions.

Logon Failure: The target account name is incorrect.
If you got this error message, you are facing the same problem that I faced. Then try to browse the Sysvol directory by Domain Controller name or FQDN (\\DC1\Sysvol\) instead of domain name from Start\Run. now you can access the sysvol without any problem, so the ultimate cause for this issue is Name Resolution/Network Connectivity problem. The root cause of the Name Resolution will differs for every environment.

In my environment, I have fixed the Name Resolution issue by following below steps:

- Checked Name Resolution by Ping command (Ping YourDomain.local)
- Ping result shows, it is trying to connect wrong IP address instead of IP of current DC, and ensured the wrong IP address is nothing but the IP of my another DC which is not active.

Finally, I have confirmed this is the root cause for my problem, the IP address of inactive DC is cached in DNS entries for the domain name, Now, I started that DC and confirmed everything is working fine now.

Note: Name Resolution/Network Connectivity problem is generic DNS problem, so please try to resolve DNS cache issue as per your own need.

Sunday, 28 December 2014

Event ID 1000 Application Error - Fix/Solutions

This is a very generic error and it doesn't tell much about what caused it. Some applications may fail with this error when the system is left unstable by another faulty program. Usually, a reboot is recommended when this type of error is showing up. If the error is persistent, then one can start digging further (i.e. update the application that is listed in the event), install latest hot fixes, check for viruses and so on.

In my case, I got this Application Error with the Event ID 1000 for Microsoft Security Client with below error:
Log Name:      Application
Source:        Application Error
Date:          11/27/2014 10:50:06 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      hp-PC
Description:
Faulting application name: NisSrv.exe, version: 4.4.304.0, time stamp: 0x52684559
Faulting module name: NisSrv.exe, version: 4.4.304.0, time stamp: 0x52684559
Exception code: 0xc0000005
Fault offset: 0x0001375c
Faulting process id: 0xacc
Faulting application start time: 0x01d00a509b208965
Faulting application path: c:\Program Files\Microsoft Security Client\NisSrv.exe
Faulting module path: c:\Program Files\Microsoft Security Client\NisSrv.exe
Report Id: a14524e0-7659-11e4-bc20-002713d4e5ed
After I have analyzed some time, found the following useful resources that are related with Application Error with the Event ID 1000 for Microsoft Security Client.

https://forums.malwarebytes.org/index.php?/topic/162710-would-love-some-help/
http://forums.techguy.org/virus-other-malware-removal/1138545-browser-infected.html
http://www.spywareinfoforum.com/topic/136083-malware-and-unwanted-ad-ons/
http://www.cybertechhelp.com/forums/showthread.php?t=216537
http://www.dslreports.com/forum/r29587231-Strange-Music-Web-Browsing

Other useful resources related with generic Application Error with Event 1000:

http://www.applicationerror.net/event-id1000-applicationerror.php
http://www.reginout.com/Learn-to-fix-event-id-1000-download-repair-tool.html
http://www.sevenforums.com/bsod-help-support/224016-random-application-error-event-1000-a.html
http://forums.iis.net/t/1215020.aspx?Server+crashing+with+Error+event+1000+application+Error

How Replication works in Active Directory?

What is Replication

In Active Directory, objects are distributed among all domain controllers in a forest, and all domain controllers can be updated directly. Active Directory replication is the process by which the changes that originate on one domain controller are automatically transferred to other domain controllers that store the same data. For example, when an user’s telephone number is modified, it must be communicated throughout the organization ensuring up-to-date in every domain controller. This is accomplished through a mechanism called replication.

Replication in Active Directory

Active Directory uses a multi-master approach for the replication of directory data. As the name suggests, in the multi-master approach, each domain controller acts as a master and can replicate data to the other domain controllers.

Replication across the three different directory partitions- Schema partition,Configuration partition and Domain partition are carried out differently. Schema container holds definitions about objects and object attributes and is ubiquitous in nature. Any update to the schema is replicated forest wide. Configuration container contains physical layout of sites. Similar to Schema data, configuration data is also replicated throughout the forest. On the contrary, domain controllers residing in different domains, house different set of data that are domain confined. Thus to facilitate dispersion of data throughout an organization, the data in each domain controller is completely replicated to every other domain controller in the domain and partially replicated to the global catalog server.

How Replication Works?

Now that we know how replication occurs at three levels of directory partition, it is essential to understand that Active Directory replication is attribute based. To understand this lets take this example:

DC1- AD Domain Controller 1
DC2- AD Domain Controller 2
U1- an AD user with telephone number: xxxxxx90

Now, telephone number of the user U1 is same in both the DCs. If you change telephone number of U1 in DC1 as xxxxxx91, only the change in the telephone number is replicated to all the domain controllers and not the entire object. This replication process occurs based on the attribute usnChanged attribute. Yes, every object contains the attribute usnChanged which holds the corresponding object's Last Update Sequence Number (USN). When an object is created, by default a USN is assigned to them. Whenever a change is elicited these USNs are incremented making every other USN in other domain controllers go out of date for that object. To ensure that only the most recent changes are replicated, only the highest USN is stored and displayed. Thus changes are monitored and recorded with the help of USN in Active Directory.

Saturday, 27 December 2014

GPO Software Deployment Failed - The error was : %%1274 and %%2

I'm trying to deploy an MSI setup via Group Policy using Software Installation Policy. I have followed a Software Deployment manual and configured the GPO Software_Deployment_GPO and updated GPO settings by gpupdate/force command and restarted the machine. But when I login into system, I have noticed the software was not installed and found the following events in the System Event log (Event 101 with error %%1274 and Event 103 with error %%2).

Event ID 101:
Source:        Application Management Group Policy
Event ID:      101
Level:         Warning
Description:  The assignment of application MyMSISetup from policy Software_Deployment_GPO failed.  The error was : %%1274
Event ID 103:
Source:        Application Management Group Policy
Event ID:      103
Level:         Error
Description: The removal of the assignment of application MyMSISetup from policy Software_Deployment_GPO failed.  The error was : %%2
After analyzed some time, found the problem for this issue is insufficient wait time to apply Group Policy.

Fix/Solution for GPO Software Deployment Error : %%1274 and %%2

Follow the below steps to increase policy processing wait time.

1. Open Software Installation Policy applied GPO (In my case: Software_Deployment_GPO) in Edit mode.
2. Navigate to "Computer Configuration > Policies > Administrative Templates > System > Group Policy"
3. In right-hand side, search and double-click the setting "Startup policy processing wait time."

GPO Software Deployment Failed - The error was : %%1274 and %%2

4. Enable the setting and set "Amount of time to wait (in seconds)" to a reasonable value for your environment, for instance "60". Now click the Apply button to apply settings.

GPO Software Deployment Failed - The error was : %%1274 and %%2

5. Update the GPO by running the command gpupdate/force and restart computer to check install the software on machine startup.

Friday, 26 December 2014

VBScript: Start and Stop Windows Service

You can manage Windows Service through VBScript easily by using WMI Services. You can use the WMI class Win32_Service to get complete information of Windows Service. In this article, I am going write VBScript samples to Start, Stop, and Restart Windows Service.

Summary:

VBScript to Stop Windows Service using WMI

1. Copy the below example vbscript code and paste it in notepad or a VBScript editor.
2. Change the value strService into your own windows service name.
3. If you want to stop a service in Remote machine, set the Remote computer name in the variable strComputer instead of  "." (local machine).
4. Save the file with a .vbs extension, for example: StopService.vbs
5. Double-click the vbscript file (or Run this file from command window) to stop the given windows service.
' StopService.vbs
' Sample vbscript script to Stop Windows Service
' -------------------------------------------------------' 
Option Explicit
Dim objWMIService, objService
Dim strService,strComputer
strService="RemoteRegistry"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
For Each objService In objWMIService.ExecQuery("Select * from Win32_Service Where Name = '"_
&strService&"'")
    objService.StopService
Next
WScript.Echo "Your "& strService & " service has stopped" 
WScript.Quit

Start Windows Service using VBScript and WMI

1. Copy the below example vbscript code and paste it in notepad or a VBScript editor.
2. Change the value strService into your own windows service name.
3. If you want to start a service in Remote machine, set the Remote computer name in the variable strComputer instead of "." (local machine).
4. Save the file with a .vbs extension, for example: StarService.vbs
5. Double-click the vbscript file (or Run this file from command window) to start the given windows service.
' StartService.vbs
' Sample vbscript script to Start Windows Service
' -------------------------------------------------------' 
Option Explicit
Dim objWMIService, objService
Dim strService,strComputer
strService="RemoteRegistry"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
For Each objService In objWMIService.ExecQuery("Select * from Win32_Service Where Name = '"_
&strService&"'")
    objService.StartService
Next
WScript.Echo "Your "& strService & " service has started" 
WScript.Quit

Restart Windows Service using VBScript and WMI

1. Copy the below example vbscript code and paste it in notepad or a VBScript editor.
2. Change the value strService into your own windows service name.
3. Change the value waitTime to increase time interval between Stop and Start the Windows Service.
4. If you want to restart a windows service in Remote machine, set the Remote computer name in the variable strComputer instead of "." (localmachine).
5. Save the file with a .vbs extension, for example: StarService.vbs
6. Double-click the vbscript file (or Run this file from command window) to start the given windows service.
' RestartService.vbs
' Sample vbscript script to Restart Windows Service
' -------------------------------------------------------' 
Option Explicit
Dim objWMIService, objService
Dim strService,strComputer,waitTime
strService="RemoteRegistry"
strComputer = "."
waitTime=10000
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
For Each objService In objWMIService.ExecQuery("Select * from Win32_Service Where Name = '"_
&strService&"'")
objService.StopService()
   WSCript.Sleep waitTime
objService.StartService()
Next
WScript.Echo "Your "& strService & " service has restarted" 
WScript.Quit

List all Windows Services and Running Status using VBScript

1. Copy the below example vbscript code and paste it in notepad or a VBScript editor.
2. Save the file with a .vbs extension, for example: ListService.vbs
3. Run this file from command window using cscript utility to list running status of all the windows services.
' ListServices.vbs
' Sample vbscript script to list all Windows Services
' -------------------------------------------------------' 
Option Explicit
Dim objWMIService, objService, strComputer
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
For Each objService In objWMIService.ExecQuery("Select * from Win32_Service")
Wscript.Echo objService.DisplayName  & " : "& objService.State
Next
WScript.Quit

CMD usage to run vbscript using cscript:
C:\> cscript ListServices.vbs
Start, Stop and Restart Windows Service using VBScript

Thursday, 25 December 2014

How to find which program uses or blocks port in Windows

There are many ways and more tools find which process is using specific TCP port. In this article, I am going to explain how to find listing TCP ports and the associated process using netstat command and Resource Monitor tool.

Find what process is using a TCP port by NETSTAT command

Netstat is a command line utility, it displays active TCP connections, ports on which the computer is listening, Ethernet statistics, the IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6 statistics (for the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols).

Use the below command to list active TCP connections and the associated program.
netstat -a -b -n
-a Displays all connections and listening ports.
-b Displays the executable involved in creating each connection or listening port
-n Stops resolving ip address into host name to give fast results
Note: Run the command prompt with elevated privilege (Run as Administrator)

How to find which application uses or blocks port in Windows 

From the above image, you can clearly find the port 1025 is being used by the process wininit.exe. In some cases, well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached.

In another way, You can combine the commands netstat and tasklist to determine what process is using a TCP port. The following command lists the active TCP connection and the associated process id.
netstat -a -n -o
-o Displays the process ID (PID) for each connection. You can find the application based on the PID on the Processes tab in Windows Task Manager.

How to find which process uses or blocks port in Windows


Now, you can get the process ID (PID) for the port which you want to track the process and you can find the associated application based on the PID value on the Processes tab in Windows Task Manager.

For quick result, you can use the command line tool tasklist to find the associated process name from the process ID (PID). Use below command to get process name for the process ID 948.
tasklist /svc /FI "PID eq 948"
How to find what program uses or blocks port in Windows

Find which application is using or blocks a TCP port by Resource Monitor

You can also find the listing TCP ports and the associated process by using native GUI tool Resource Monitor. Follow the below steps to find listing (using) TCP ports using Resource Monitor.

1. Open the Resource Monitor tool by running the command resmon.exe in run Window (or you can open through this shortcut: Start->All Programs->Accessories->System Tools->Resource Monitor).

2. Click the Network tab and expand the panel Listing Ports.

How to find what process uses or blocks port in Windows

3. Now, you can find listing port and associated process name under the column Image.

Tuesday, 23 December 2014

What is the use of krbtgt account in Active Directory?

The krbtgt account is nothing but the Key Distribution Center Service Account (KDC) and it is responsible to grant Kerberos authentication ticket (TGT) from Active Directory. The Kerberos authentication protocol uses session tickets that are encrypted with a symmetric key derived from the password of the server or service to which a Windows user requests access.

At the beginning of the day when a user sits down at his workstation and enters his domain username and password, the workstation contacts the logon DC (Logon Server) and requests a ticket-granting ticket TGT to the Kerberos Key Distribution Center (KDC) service. All Windows users get a TGT from the KDC at the start of their Windows login session after they successfully authenticate to the KDC by using their password.

The KDC encrypts a user's TGT with a key it derives from the password of the krbtgt AD domain account. The krbtgt account and its password are shared between the KDC services of all DCs in a domain. The krbtgt account is automatically created as part of the dcpromo AD installation process on the first DC in a domain. It will be located under the Users container in Active Directory Users and Computers and is disabled by default. Unlike other AD user accounts, the krbtgt account can't be used to log on interactively to the domain. Because it's a built-in account, krbtgt also can't be renamed.

If you already familiar with the logon audit event logs, you could see the krbtgt account as service in the event 4768.

Event 4768: A Kerberos authentication ticket request
A Kerberos authentication ticket (TGT) was requested.

Account Information:

   Account Name: Morgan
   Supplied Realm Name: testdomain
   User ID: TESTDOMAIN\administrator

Service Information:

   Service Name: krbtgt
   Service ID: TESTDOMAIN\krbtgt

Network Information:

   Client Address: 103.187.1.13
   Client Port: 0

Additional Information:

   Ticket Options: 0x40810010
   Result Code: 0x0
   Ticket Encryption Type: 0x12
   Pre-Authentication Type: 2

Sunday, 21 December 2014

Group Policy: Account logon vs Logon events

Both are Logon Audit Polices in Group Policy. In Active Directory based domain system, Logon , Logoff and Logon Failures events are controlled by these two security policy settings.

Audit Logon events (Client Events)

  • The Audit logon events policy records all attempts to log on to the local computer, whether by using a domain account or a local account.
  • On Domain Controller, this policy records attempts to access the DC only.
  • It records both Logon and Logoff events whereas Account Logon logs only Logon events.
  • By using these events we can track user's logon duration by mapping logon and logoff events with user's Logon ID which is unique between user's logon and logoff . (Refer this article: Tracking User Logon Activity using Logon and Logoff Events)
  • Refer this article: Steps to enable Audit Logon events (client events) to configure the Logon and Logoff events.

Audit account logon events (DC Events)

  • Account logon events are generated when a domain user account is authenticated on a domain controller.
  • These events will be logged in Domain Controller's security log.
  • If you enable this policy on a workstation or member server, it will record any attempts to log on by using a local account stored in that computer’s SAM
  • This is a authentication event, so it logs only Logon events, it means, logs the event whenever a user authenticated by Domain Controller.
  • Refer this article: Steps to enable Account Logon events (DC events) to configure Account Logon events.

Difference between SHA256CryptoServiceProvider and SHA256Managed

Both are used to generate hash data and both classes generate same hash. The .Net SHA256Managed class is supported in all framework versions while the SHA256CryptoServiceProvider class is only supported from framework 3.5 and above. SHA256CryptoServiceProvider uses the FIPS 140-2 validated (FIPS = Federal Information Processing Standards) Crypto Service Provider (CSP) while SHA256Managed does not. SHA256Managed is a pure managed implementation while SHA256CryptoServiceProvider does presumably the same thing but wraps the CryptoAPI.

Summary:

  • Both classes generate same hash key.
  • SHA256CryptoServiceProvider uses the FIPS 140-2 validated Crypto Service Provider (CSP) while SHA256Managed does not.
  • The .Net SHA256Managed class is supported in all framework versions while the SHA256CryptoServiceProvider class is only supported from framework 3.5 and above.

How to develop a software to support FIPS Compliance

When you develop a software, you need to use SHA256CryptoServiceProvider for hashing, otherwise, you will get the following error when you run the application in FIPS compliant enabled system:
Error: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms

Saturday, 20 December 2014

Powershell : Convert SecureString to Plain Text

You can force user to enter password from Powershell script using Read-Host cmdlet, and you can mask the password string by setting a parameter -asSecureString.
$password = Read-Host "Enter Password" -asSecureString
You can use this Secure String password wherever the password is needed as Secure String password, but you can not pass this SecureString value where the password required as Plain Text. This below powershell script converts a System.Security.SecureString object (secure string) to Plain Text (actual password string).
#SecureStringToPlainText.ps1
$password = Read-Host "Enter Password" -asSecureString
# Create a "password pointer"
$PwdPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
# Get the plain text version of the password.
$PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto($PwdPointer)
# Free the pointer.
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($PwdPointer)
"Your have entered this password: " + $PlainTextPassword
Convert SecureString to Plain Text in Powershell

How to pass arguments to PowerShell script

In this article, I am going to explain about how to pass arguments into Powershell script and how to get input values dynamically from Powershell script. You can pass parameters in different ways either by unnamed parameters, named parameters and you can even force the user to enter specific parameter value.

Pass arguments by unnamed parameters:

You can just pass any no of values into script with separated by space, within a script you can refer unnamed arguments using the $args array and referring to the position (first, second..) of each argument.
#UnnamedArgs.ps1
#Usage:PS C:\Scripts> .\UnnamedArgs.ps1 arg1 arg2
"Your 1st argument is: " + $Args[0]
"Your 2nd argument is: " + $Args[1]

Pass arguments by named parameters:

In unnamed parameters method, you cannot have more control with inputs and powershel script itself look unclear to understand the process. To overcome this, you can pass arguments by named parameter. To get arguments by name, we need to use param statement.
#NamedArgs.ps1
#Usage:PS C:\Scripts> .\NamedArgs.ps1 -Name "Morgan" -City "Arlington"
param($Name, $City)
  "User name: " + $Name
  "City: " + $City
You can set default value for any argument, this default value will be taken as actual value if user doesn't pass the value for this argument.
#PassArgs.ps1
param($Name, $City="Los Angeles")
  "User name: " + $Name
  "City: " + $City

How to pass arguments to PowerShell script

You can set an argument as Mandatory parameter to force user to enter the specific argument to run script.
#MandatoryArgs.ps1
param( [Parameter(Mandatory=$true)] $Name, $City="Los Angeles" )
 "User name: " + $Name
 "City: " + $City

Ask dynamic arguments within Powershell script:

You can force user to enter input values dynamically from inside part of Powershell script using Read-Host cmdlet with respect to your dynamic need.
#DynamicArgs.ps1
param( $Name)
If ($Name -eq "Morgan") {
    $mobileno = Read-Host "Enter your mobile no"
}
else{
    $email = Read-Host "Enter your email"
}
Ask dynamic arguments within Powershell script

Ask password from user in Powershell script:

You can force user to enter password from inside part of Powershell script using Read-Host cmdlet, and you can mask the password string by setting a parameter -asSecureString in Read-Host cmdlet.
#PasswordArgs.ps1
param( $Name)
"Hi, " + $Name
$password = Read-Host "Enter Password" -asSecureString
$PwdPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
# Get the plain text version of the password.
$PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto($PwdPointer)
# Free the pointer.
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($PwdPointer)
"Your have entered this password: " + $PlainTextPassword
Ask password from user in Powershell script

MMC cannot open the file C:\WINDOWS\system32\gpmc.msc

Today I have got the below error when I try open Group Policy Management Console by running the command the gpmc.msc. I've been using it for long time, it is not working only now.
MMC cannot open the file C:\WINDOWS\system32\gpmc.msc.This may be because the file does not exist, is not an MMC console, or was created by a later version of MMC. This may also be because you do not have sufficient access rights to the file."
mmc cannot open the file c windows system32 gpmc msc

Fix/Solution for MMC cannot open the file gpmc.msc

After I have analyzed some time, found the reason for the error is the gpmc template file is corrupted under user's appdata location: %APPDATA%\Microsoft\MMC

To fix this issue, we need to correct the corrupted gpmc template file, but this would be hard task, don't worry you can just rename the corrupted template file and it will automatically created when you open Group Policy Management Console by running the command the gpmc.msc.

1. Open the Run command window, type the path %APPDATA%\Microsoft\MMC and click OK.

MMC cannot open the file C:\WINDOWS\system32\gpmc.msc

2. Rename the corrupted gpmc template file into gpmc-backup. Now you can open Group Policy Management Console by running the command the gpmc.msc.
mmc cannot open the file c windows system32 gpmc msc

Friday, 19 December 2014

whenChanged vs usnChanged - Active Directory

Description:

In this article, I am going to explain about the Active Directory attributes whenChanged and usnChanged. Both attributes hold the information of AD object's latest change point in different format. Both attributes are very useful to track Active Directory object changes.

Summary:

  • WhenChanged is a date time attribute which holds an AD object's latest changed time and it is Non-Replicable attribute. 
  • uSNChanged is a integer attribute and it will be updated when the object is changed.
  • Both are Non-Replicable attributes but that doesn't mean every domain controller holds very different value like lastLogon attrbute. Yes, both are non-replicable attributes but it will be updated in all DCs for every AD change.

How whenChanged attribute value get updated in all DCs?

Before explain this, I would like to explain what is Active Directory Replication?. In Active Directory, objects are distributed among all domain controllers in a forest, and all domain controllers can be updated directly. Active Directory replication is the process by which the changes that originate on one domain controller are automatically transferred to other domain controllers that store the same data.

So, AD replication ensures same data in all DCs by transferring every change automatically to other DC,

Consider this scenario:

If you change the value for description attribute of any object as "test", it will be updated in all other DC but here you have not changed either whenChanged or uSNChanged then how it gets updated in your own DC?.
You know whenChanged is system attribute and it will be automatically updated for every change. So the description attribute change indirectly force the whenChanged attribute to set latest time. Like this, the replication change on every DC will automatically force the whenChanged attribute to set the particular DC's latest time. So, the value of  whenChanged attribute may or may not be identical in all DCs depends upon the replication interval.

For more clarity, consider this scenario:

DC1-  AD Domain Controller 1
DC2-  AD Domain Controller 2
U1-     an AD user

Replication Interval: 15 secs

If you change the user U1's description value in DC1 at 10:10:00 AM, the whenChanged attribute gets updated as 10:10:00 AM in DC1. Since the replication interval is 15 secs, the description value will be replicated into DC2 at 10:10:15 AM and it automatically updates the whenChanged attribute as 10:10:15 AM in DC2. So depends upon the replication interval the value of whenChanged attribute may or may not be identical in all domain controllers but it holds the updated value.

How usnChanged attribute value get updated?

When a domain controller modifies an object, it increments the highestCommittedUSN attribute value. When the increment occurs, the domain controller also sets the uSNChanged attribute for that object to the new value. In this process, each change to an object in Active Directory is stamped with a unique and monotonic value. Therefore, a program can obtain the most recent changes to an object on a domain controller by finding the object that has the largest uSNChanged attribute value. Similarly, the second largest uSNChanged attribute value corresponds to the second most recently changed object, and this process is repeated.

For more clarity, consider this scenario:

DC1-  AD Domain Controller and its highestCommittedUSN value = 10000
U1-     an AD user and its uSNChanged value = 3000
U2-     an AD user and its uSNChanged value = 4000


If you change the user U1's description value through DC1. First, DC1 will increment its highestCommittedUSN attribute value into 10001 and update this value into user U1's uSNChanged attribute. So, now U1's uSNChanged value becomes 10001. Now, if you change U2's description value through DC1, now DC1 will increment its highestCommittedUSN attribute value into 10002 and update this value into user U2's uSNChanged attribute. So, now U2's uSNChanged value will be changed from 4000 to 10002. In this way, the Domain Controller always keeps the latest change object record. This mechanism will be very useful to track Active Director changes using Polling method.

Refer this article: http://msdn.microsoft.com/en-us/library/ms677627(v=vs.85).aspx to track AD changes using uSNChanged attribute

Wednesday, 17 December 2014

How to enable FIPS Compliant algorithms in Windows

What is FIPS Compliance

The FIPS (Federal Information Processing Standard) compliance is the United States Government standard that provide a benchmark for implementing cryptographic software. For the Schannel Security Service Provider (SSP), this security setting disables the weaker SSL protocols and supports only the TLS protocols. If this setting is enabled, the TLS/SSL Security Provider uses only the FIPS 140 approved cryptographic algorithms: 3DES and AES for encryption, RSA or ECC public key cryptography for the TLS key exchange and authentication, and only the Secure Hashing Algorithm (SHA1, SHA256, SHA384, and SHA512) for the TLS hashing requirements.

Summary:

Enable FIPS Compliant algorithms via Registry

You can force the FIPS Compliance into every software by the changing the value 0 to 1 in below registry key
HKLM\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled

Enable FIPS Compliant algorithms via Local Security Policy

You can alternatively force FIPS Compliance via Local Security Policy. Follow the below steps to configure FIPS compliant in Local Computer.

1. Open Local Security Policy by running the command secpol.msc.

How to enable FIPS Compliant algorithms in Windows

2. In the Local Security Policy Editor, under the Local Polices node, click Security Options.

3. In the right-hand side, search the setting System cryptography: Use FIPS-compliant algorithms for encryption, hashing, and signing

Steps to enable FIPS Compliant algorithms

4. Double-click the policy setting System cryptography: Use FIPS-compliant algorithms for encryption, hashing, and signing, click Enable and click the button Apply to complete FIPS Compliance configuration.

Steps to enable FIPS Compliance algorithms

How to develop a software to support FIPS Compliance

When we develop a software, we need to use FIPS validated cryptographic algorithms for encryption, hashing, and signing. Otherwise, you will get the following error when you run the application in FIPS compliant enabled system:
Error: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms

Fix for RijindaelManaged algorithms:

The RijindaelManaged class is NOT FIPS complaint supported class. Instead you can use the AesCryptoServiceProvider class which is an FIPS equivalent of RijindaelManaged.

Refer this link: http://blogs.msdn.com/b/winsdk/archive/2009/11/04/is-rijndaelmanaged-class-fips-complaint.aspx

Fix for SHA256Managed algorithms:

The SHA256Managed class is NOT FIPS complaint supported class. Instead you can use the SHA256CryptoServiceProvider class which is an FIPS equivalent of SHA256Managed.

Tuesday, 16 December 2014

Add start menu shortcut via Group Policy

In this article I am going to explain about how to add shortcut icon in start menu to open file/folder or start application through Group Policy. This is a very common task in any GPO based Active Directory domain environment for either all of your user’s computer or to a certain group of user’s computer depending on your needs. You can do it easily via Group Policy's User Preferences setting Shortcuts (Default Domain Policy\User Configuration\Preferences\Shortcuts).

Note: If you want to Pin a Program in Start Menu, Refer this article: How to Pin a Program to Start menu via Group Policy

Steps to add start menu shortcut via Group Policy

1. Open the Group Policy Management console by running the command gpmc.msc.

2.  Expand the tree and right-click on the OU you want this policy to be applied to. Now, I am going to apply users who are under the OU ManagementTeam. so Right-click the OU ManagementTeam, and click Create a GPO in this domain, and Link it here...

Add start menu shortcut via Group Policy

3. Give the new policy name and click OK. Here, I am giving the policy name start-menu-shortcut-policy
  
Add start menu shortcut via Group Policy

4. Now Right-click on the newly created gpo start-menu-shortcut-policyand click edit.

Add start menu shortcut icon via Group Policy

5. In the Group Policy Management Editor window, expand User Configuration and go to the node Shortcuts (User Configuration/Preferences/Windows Settings/Shortcuts).

6. Right-click in the white space empty area, click New and then select Shortcut.

Create start menu shortcut via GPO

7. In the General tab, fill the following details:
      Name: My Shortcut File (this is the name that will show up on the shortcut in the user's start menu)
      Target type: File System Object
      Location: Start Menu
      Target path: D:\OfficeFiles\MyFile.txt

Note:Here, I have given the file path of MyFile.txt, you can give your own file or folder path which you want to create start menu shortcut.
Create start menu shortcut via GPO

8. Click on the Common tab.
Select Remove this item when it is no longer applied and select OK to the prompt about changing the Action field to ‘Replace’.What this will do is remove the shortcut from start menu if we delete this policy, or if the user falls out of the OU structure that has this policy applied to it.

Add start menu shortcut via GPO

9. In the Description field, write the description as easy way to understand what is this policy, click Apply, and OK.
Create start menu shortcut for a file via GPO

10. Now update the GPO by running the command gpupdate /force

Create start menu shortcut for a folder via GPO

11. That's all. Now we have successfully created start menu shortcut icon of the file MyFile.txt for the users who are under OU ManagementTeam. You can see that shortcut under star menu by logging into any of the user's desktop who are under ManagementTeam OU

Add start menu shortcut icon via Group Policy

Now, you can create your own GPO, and create add shortcut icon into start menu via Group Policy as per your wish.......

Related Articles:

Add Environment Variable via Group Policy
Add desktop shortcut icon through Group Policy
Pin Program to Taskbar via Group Policy
How to Pin a Program to Start menu via Group Policy

Sunday, 14 December 2014

Powershell Script to Get Disk Space Usage Report

We can easily list the Size and Free Space of all Disks using WMI class Win32_LogicalDisk. The class is a Win32_LogicalDisk which represents a data source that resolves to an actual local storage device on a computer system running Windows. In this article, I am going write Powershell scripts to get Disk Space usage in Local Machine and Remote Computer.

Summary:


Get Disk Space Usage in Local Machine

You can get the Disk Space Usage report from Local Machine by using following Powershell script. Here, I have used the filter DriveType -eq 3 to list only local hard disks and the below query displays size and free space in unit of GB, you can change it if you want as any other unit. (i.e To display in MB, you need to change this format query -f ($_.FreeSpace/1GB) into -f ($_.FreeSpace/1MB)).
Get-WmiObject -Class Win32_LogicalDisk |
Where-Object {$_.DriveType -eq 3} |
Select-Object DeviceID, Description,`
    @{"Label"="DiskSize(GB)";"Expression"={"{0:N}" -f ($_.Size/1GB) -as [float]}}, `
    @{"Label"="FreeSpace(GB)";"Expression"={"{0:N}" -f ($_.FreeSpace/1GB) -as [float]}} |
FT -AutoSize
Powershell Script to Get Disk Space Usage Report

Get Disk Space Usage from Remote Machine using Powershell

You can get disk's free space usage report from Remote Computer by giving name of the remote computer through argument syntax -ComputerName in the existing Powershell script.
Get-WmiObject -Class Win32_LogicalDisk -ComputerName "hp-pc" | 
Where-Object {$_.DriveType -eq 3} |
Select-Object DeviceID, Description,`
    @{"Label"="DiskSize(GB)";"Expression"={"{0:N}" -f ($_.Size/1GB) -as [float]}}, `
    @{"Label"="FreeSpace(GB)";"Expression"={"{0:N}" -f ($_.FreeSpace/1GB) -as [float]}} |
FT -AutoSize

Export Disk Space Usage Report to CSV using Powershell

You can export the Disk Space Usage into CSV using Powershell's Export-CSV cmdlet. The following script exports the remoter computer's disk free space usage report to CSV file.
Get-WmiObject -Class Win32_LogicalDisk -ComputerName "hp-pc" | 
Where-Object {$_.DriveType -eq 3} |
Select-Object DeviceID, Description,`
    @{"Label"="DiskSize(GB)";"Expression"={"{0:N}" -f ($_.Size/1GB) -as [float]}}, `
    @{"Label"="FreeSpace(GB)";"Expression"={"{0:N}" -f ($_.FreeSpace/1GB) -as [float]}} |
 Export-CSV 'C:\DiskSpaceUsage .csv' -noType
CSV Output of Disk Free Space Usage:

Export Disk Space Usage Report to CSV using Powershell

Saturday, 13 December 2014

Install and Uninstall Windows Service using Command Prompt

This article is explaining about how to Install/Create and Delete/Remove a Windows Service using Command Prompt. You can use the Service Control Manager's utility command sc to Install and Delete Windows Service.

Note: Run the command prompt with elevated privileges(Run as administrator) to use the command sc.

Install Windows Service using Command Prompt

Use the below command to install a Windows Service.
sc create [service-name] binpath= [servic-file-path]
service-name : Name of new Windows Service.
servic-file-path : File path of Windows Service file
sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"

Install and Remove Windows Service using Command Prompt

Delete Windows Service using Command Prompt

Use the below command to uninstall a Windows Service.
sc delete "MorganTechService"
Delete Windows Service using Command Prompt

Run PowerShell script from Task Scheduler

We can easily execute commands from powershell command window whenever we want to do some task. But for regular task, it would be great if we run powershell script as Scheduled Task. You can create a scheduled task to run Powershell script using Windows Task Scheduler. Follow the below steps to create daily schedule to run a Powershell script file.

Steps to Create Schedule Task to Run Powershell script

1. Open the Windows Task Scheduler : Go to > Start > Administrative Tools and select Task Scheduler.

How to Schedule Powershell Script to run in Task Scheduler

4. In the Task Scheduler, select the Create Task... option under the Actions menu.

How to Schedule Powershell Script to run in Task Scheduler

5. Enter a name for the task, and give it a description (the description is optional and not required).
6. Under Security options section, you can specify different user account that the task should be run under and select the option 'Run whether user logged on or not' so that the task will run even if the user is not logged.

Create Schedule Task to run Powershell Script

7. Then, select the Triggers tab, and click New to add a new trigger for the scheduled task. This new task should use the On a schedule option. The start date can be set to a desired time, and the frequency and duration of the task can be set based on your specific needs and click OK. Here, I have configured a daily schedule to run the Powershell script on daily basis.

Create Schedule Task to run Powershell Script

8. Then, go to the Actions tab and click New to set the action for this task to run. Set the Action to Start a program.
9. In the Program/script box enter Powershell
10. In the Add arguments (optional) box enter the complete script file path. For example, if your Powershell Script is named "test-script.ps1" and placed under "C:\Scripts". then you have to enter path like: "C:\Scripts\test-script.ps1.ps1"

Steps to Create Schedule Task to run Powershell Script

11. That's all, we completed the new schedule task configuration and click OK to complete process.

Steps to Create Schedule Task to run Powershell Script

12. Under Task Scheduler Library, You can check daily task run status of your task and you can also run the task whenever you want by right-click on the task and click Run.

Steps to Create Schedule Task to run Powershell Script

Thursday, 11 December 2014

What is a Cluster File System?

A clustered file system is a file system where the data is distributed on multiple nodes (machines) that appear to the clients as a single storage system (a cluster). There are several approaches to clustering, most of which do not employ a clustered file system (only direct attached storage for each node). Clustered file systems can provide features like location-independent addressing and redundancy which improve reliability or reduce the complexity of the other parts of the cluster. Parallel file systems are a type of clustered file system that spread data across multiple storage nodes, usually for redundancy or performance.

Distributed vs Clustered File System

Both the File Systems provide a unified view, global namespace, whatever you want to call it. The difference lies in the model used for the underlying block storage. In a cluster file system, all of the nodes connect to the same block storage, with access mediated by locks or other synchronization primitives. In a distributed file system, each server has its own private block storage, which is only unified at a higher level.

Cluster Filesystems have mostly fallen out of fashion, primarily because their storage model requires a relatively expensive external (e.g. FC/iSCSI) disk subsystem plus switches, adapters, etc. The up side is that this allows disk failures to be handled on the external subsystem, and the same-ness of the underlying storage can ease handling of server failures as well.

Distributed Filesystems, on the other hand, can be and usually are built using cheaper SATA/SAS disks through on-board controllers. (Note that they can be built on top of SANs, except in environments such as AWS where such things don't exist.) While such filesystems can easily beat their cluster cousins in terms of throughput per dollar, they often do so at the cost of worse latency and greater complexity to provide data availability across separate pools of storage.

Since the latency issues can be addressed with smarter caching/replication, which - along with the other kinds of complexity - is just a one-time development issue, I believe that distributed filesystems will eventually displace cluster filesystems entirely. Right now, though, there are use cases such as virtual-machine image storage or databases that are probably better served by Cluster Filesystems.

Find Logon Failure Reason for Logon Type 7 - Event 4625

Finding root cause of the frequent Bad Password Attempts or other Login Failure is a hard task now a days since many applications are using cached password methods. This article explains how to Trace and Find Account Lockout Source and Logon Failure Reason of an AD User for Logon Type 7.

Root cause of AD User Lockout for Logon Type 7

As for as I know there are two possibilities for logon failure with Logon type 7.

- In most cases, this logon type occurs when a user unlock the password protected workstation screen, Windows treats this logon as logon type 7. If your entered valid password, the event 4624 logged in workstation event log with logon type 7 and if you entered wrong password, the event 4625 will be logged with logon type 7.

- There may be a possibility to get account locked by Cached Active Directory Password.

Logon Type 7 event info for Login failure when unlock the workstation screen:
Description:
An account failed to log on.

Logon Type:   7

Failure Information:
 Failure Reason:  Unknown user name or bad password.

Process Information:
 Caller Process ID: 0x1d3
 Caller Process Name: C:\Windows\System32\winlogon.exe
Logon Type 7 event for other login failure like cached cached credentials:
Description:
An account failed to log on.

Logon Type:   7

Failure Information:
 Failure Reason:  An error occurred during logon.

Process Information:
 Caller Process ID: 0x1f4
 Caller Process Name: C:\Windows\System32\lsass.exe

Monday, 1 December 2014

Find Account Lockout Source for Logon Type 8

Finding root cause of the frequent Bad Password Attempts or other Login Failure is a hard task now a days since many applications are using cached password methods. As a Administrator, you can have more control on top layer of the Network Security. Because in this layer most of the works are done by you but when it comes to end-user side, it always gives the head-ache for us and moreover tracing root cause of an end-user's login failure or account lockout source is more equally to diagnosing disease through body by a doctor. In this article, I am going explain how to Trace and Find Account Lockout Source and Logon Failure Reason of an AD User for Logon Type 8.

How to Find AD User Logon Failure Reason for Logon Type 8

The logon type 8 occurs when the password was sent over the network in the clear text. Basic authentication in IIS is most possible cause for this kind of login failure. As for as I know there are five commonly used Microsoft IIS based services with Basic Authentication by end users via either by their Desktop or Mobile device, such are OWA client, MS Exchange ActiveSync, Outlook Anywhere, FTP client and SharePoint server.

When an end-user connect the Basic authentication enabled OWA client from their desktop-pc/mobile device with wrong passwords, the event 4625 with logon type 8 will be logged in Exchange Server which hosts the OWA.

Consider the following scenario:
DC1   - Active Directory Domain Controller 
ExchSvr    - Exchange Server integrated with AD with OWA and DC1 as Authentication Server
Morgan-PC/Mobile   - End user computer/mobile device
Now, when the user morgan tries to connect the OWA client from his desktop “Morgan-PC” with wrong password,
  • The logon failure event 4625 with logon type 8 will be logged in ExchSvr, and this event will points the Morgan-PC as Source Machine. 
  • Any one of these Authentication failure logon event (4768/4771/4776) will be logged in DC1 depends upon the authentication mechanism configured in AD, and this event will points the machine ExchSvr as Source Machine.
Logon Failure Event 4625 in IIS Server:
Event ID:      4625
Computer:      ExchSVR.TestDomain.Com
Description: An account failed to log on.

Logon Type:   8

Account For Which Logon Failed:
  Account Name:  Morgan
  Account Domain:  TestDomain

Failure Information:
  Failure Reason:  Unknown user name or bad password.
  Status:   0xc000006d
  Sub Status:  0xc000006a

Process Information:
  Caller Process ID: 0xce4
  Caller Process Name: C:\Windows\System32\inetsrv\w3wp.exe

Network Information:
  Workstation Name: ExchSVR
  Source Network Address: 212.158.1.110 (Morgan-PC)
  Source Port:  40977
Logon Failure Event 4771 in Domain Controller:
Event ID:      4771
Task Category: Kerberos Authentication Service
Computer:      DC1.TestDomain.local
Description:
Kerberos pre-authentication failed.

Account Information:
 Security ID:  TESTDOMAIN\Morgan
 Account Name:  Morgan

Service Information:
 Service Name:  krbtgt/testdomain

Network Information:
 Client Address:  212.158.1.54 (ExchSVR)
 Client Port:  0

Additional Information:
 Ticket Options:  0x40810010
 Failure Code:  0x18
 Pre-Authentication Type: 2
To track the starting point of this logon failure, we need to read events from two machines DC1 and ExchSVR.
  • By DC1 event, we can conclude the failure is triggered from ExchSVR
  • And then from ExchSVR event , we can conclude the actual failure was triggered from Morgan-PC (Source Network Address).

Sunday, 30 November 2014

Find Account Lockout Source for Logon Type 3

Finding root cause of the frequent Bad Password Attempts of Active Directory User is a cumbersome task now a days. Unlike other normal logon types (Logon Type 2 -Interactive Logon and Logon Type 10 -Remote Logon), we can’t easily track the failure reason for the Logon Type 3, because most of the time, the failures surrounded with this logon type are triggered or initiated by either cached credentials or through third party tools. In this article, I am going to explain about how to Find Account Lockout Source and Login Failure reason for Logon Type 3.

How to Find Logon Failure Reason for Logon Type 3

This logon type occurs due to accessing a computer from elsewhere on the network (i.e Remote Desktop sharing tool), or accessing other resources like Network Share from elsewhere on the network by passing credentials. One of the most common sources of logon events with Logon type 3 is connections to shared folders or printers. But also other over-the-network logons are classed as logon type 3 as well as most logons to IIS except Basic authentication.

Consider following scenario:
DC1         - Active Directory Domain Controller 
Morgan-PC    - End user desktop computer
Now, when a user or any other applications tries to access resources like Network Share from Morgan-PC with wrong credentials, we will get the logon failure event 4625 with logon type 3 in DC1 and it will points the machine Morgan-PC as Source Machine.

 Event 4625 for Logon Type 3:
Computer:      DC1.TestDomain.Com
Description:  An account failed to log on.

Logon Type:   3

Account For Which Logon Failed:
  Account Name:  Morgan
  Account Domain:  TESTDOMAIN

Failure Information:
  Failure Reason:  Unknown user name or bad password.
  Status:   0xc000006d
  Sub Status:  0xc000006a

Network Information:
  Workstation Name: Morgan-PC
  Source Network Address: 212.158.1.110
  Source Port:  51283

Consider another scenario:
DC1         - Active Directory Domain Controller 
Morgan-PC    - End user desktop computer
Now, when a user tries to login into DC1 from Morgan-PC via Remote Desktop sharing tool with bad password, we will get the logon failure event 4625 with logon type 3 in DC1 and it will points the machine Morgan-PC as Source Machine.

Thursday, 27 November 2014

whenChanged and modifyTimeStamp - Active Directory

Description:

In this article, I am going to explain about the Active Directory attributes whenChanged and modifyTimeStamp and how these attributes are updated in all Domain Controllers despite being a Non-Replicable attribute.

Summary:

  • WhenChanged is a date time attribute which holds an AD object's latest changed time and it is Non-Replicable attribute. 
  • ModifyTimeStamp is a computed attribute and it is also Non-Replicable attribute. 
  • Both are Non-Replicable attributes but that doesn't mean every domain controller holds very different value like lastLogon attrbute. Yes, both are non-replicable attributes but it will be updated in all DCs for every AD change.

How whenChanged attribute value get updated in all DCs?

Before explain this, I would like to explain what is Active Directory Replication?. In Active Directory, objects are distributed among all domain controllers in a forest, and all domain controllers can be updated directly. Active Directory replication is the process by which the changes that originate on one domain controller are automatically transferred to other domain controllers that store the same data.

So, AD replication ensures same data in all DCs by transferring every change automatically to other DC,

Consider this scenario:

If you change the value for description attribute of any object as "test", it will be updated in all other DC but here you have not changed either whenChanged or modifyTimeStamp then how it gets updated in your own DC?.
You know whenChanged is system attribute and it will be automatically updated for every change. So the description attribute change indirectly force the whenChanged attribute to set latest time. Like this, the replication change on every DC will automatically force the whenChanged attribute to set the particular DC's latest time. So, the value of  whenChanged attribute may or may not be identical in all DCs depends upon the replication interval.

For more clarity, consider this scenario:

DC1-  AD Domain Controller 1
DC2-  AD Domain Controller 2
U1-     an AD user

Replication Interval: 15 secs

If you change the user U1's description value in DC1 at 10:10:00 AM, the whenChanged attribute gets updated as 10:10:00 AM in DC1. Since the replication interval is 15 secs, the description value will be replicated into DC2 at 10:10:15 AM and it automatically updates the whenChanged attribute as 10:10:15 AM in DC2. So depends upon the replication interval the value of whenChanged attribute may or may not be identical in all domain controllers but it holds the updated value.