Friday, 29 November 2013

Cannot drop database because it is currently in use in MS SQL Server

Description:

In this article, I am going to give Fix/Solution for the error 'Cannot drop database because it is currently in use' in MS SQL Server.. This error occurs when we try Delete or Drop database while the database connection is used by other users or other resources. So we need to close existing connections first then we need to Drop or Delete the database.

Summary:


Fix/Solution: Cannot drop database because it is currently in use in MS SQL Server

USE [MorganDB]
GO
/****** Object:  Database [MorganDB]    Script Date: 11/29/2013 13:29:16 ******/
DROP DATABASE [MorganDB]
GO
When you run above script, you will get an error message
'Msg 3702, Level 16, State 4, Line 2 Cannot drop database "MorganDB" because it is currently in use. ' because here we are using USE [MorganDB] as source DB to delete itself, so we need to change it to USE [master].

Fix/Solution:

USE [master]
GO
/****** Object:  Database [MorganDB]    Script Date: 11/29/2013 13:29:16 ******/
DROP DATABASE [MorganDB]
GO
Perfect Fix/Solution:

After changing source database as master, the script should works successfully. But sometimes connection may be opened by any other user. So, in that case, we also need to close existing open connections.

USE [master]
GO
ALTER DATABASE [MorganDB] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [MorganDB]    Script Date: 11/29/2013 13:40:36 ******/
DROP DATABASE [MorganDB]
GO

Fix/Solution in C#: Cannot drop database because it is currently in use in MS SQL Server

You can use the following C# code to close existing database connections and Drop or Delete Database in MS Sql Server.
public static void DeleteDataBase()
{
    using (SqlConnection sqlconnection = new
        SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=SSPI;"))
    {
        sqlconnection.Open();
        // if you used master db as Initial Catalog, there is no need to change database
        sqlconnection.ChangeDatabase("master");

        string rollbackCommand = @"ALTER DATABASE [MorganDB] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE";

        SqlCommand deletecommand = new SqlCommand(rollbackCommand, sqlconnection);

        deletecommand.ExecuteNonQuery();

        string deleteCommand = @"DROP DATABASE [MorganDB]";

        deletecommand = new SqlCommand(deleteCommand, sqlconnection);

        deletecommand.ExecuteNonQuery();
    }
}


Fix/Solution in Sql Server Management Studio for the error 'Cannot drop database because it is currently in use' in MS SQL Server

If you try to dropping a database in Sql Server Management Studio UI when an user connected to the SQL Server Database you will receive the below mentioned error message.

Cannot drop database because it is currently in use in MS SQL Server


 You can avoid this error by checking the option Close existing connections.

Cannot drop database because it is currently in use- Close existing connections


Thanks,
Morgan
Software Developer

Thursday, 28 November 2013

Convert Image to Byte Array and Byte Array to Image in c#

Description:

In this article, I am going to give C# code examples to Convert Image to Byte Array and Byte Array to Image using ImageConverter and MemoryStream.

Summary:


Convert Image File into Byte Array in C#

public static byte[] ImageToByteArrayFromFilePath(string imagefilePath)
    {
        byte[] imageArray = File.ReadAllBytes(imagefilePath);
        return imageArray;
    }

Convert Image to Byte Array in C# using ImageConverter

Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing
public static byte[] ImageToByteArray(string imagefilePath)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath);
    byte[] imageByte = ImageToByteArraybyImageConverter(image);
    return imageByte;
}

private static byte[] ImageToByteArraybyImageConverter(System.Drawing.Image image)
{
    ImageConverter imageConverter = new ImageConverter();
    byte[] imageByte = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
    return imageByte;
}

Convert Image to Byte Array in C# using MemoryStream

Note: To use the classes ImageConverter and Image, you need to add the reference System.Drawing;
public static byte[] ImageToByteArray(string imagefilePath)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath);
    byte[] imageByte = ImageToByteArraybyMemoryStream(image);
    return imageByte;
}

private static byte[] ImageToByteArraybyMemoryStream(Image image)
{
    MemoryStream ms = new MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return ms.ToArray();
}


Convert Byte Array to Image in C# using MemoryStream

public static Image ByteArrayToImagebyMemoryStream(byte[] imageByte)
{
    MemoryStream ms = new MemoryStream(imageByte);
    Image image = Image.FromStream(ms);
    return image;
}

Convert Byte Array to Image File in C# using MemoryStream

public static void ByteArrayToImageFilebyMemoryStream(byte[] imageByte)
{
    MemoryStream ms = new MemoryStream(imageByte);
    Image image = Image.FromStream(ms);
    image.Save(@"C:\Users\Administrator\Desktop\imageTest.png");
}

Monday, 25 November 2013

VBScript to Disable Active Directory User Account

Description:

In this article, I am going to explain and write vbscript  code to Disable Active Directory user account using user's objectguid, samAccountName and distinguishedname and also Disable Bulk AD Users from CSV File using vbscript.

Note: You should run this vbscript code on a machine with windows Active Directory domain.

Summary:


VBScript to Disable Active Directory user by DistinguishedName

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserDN with your own user's DN which you are going to disable.
3. Save the file with a .vbs extension, for example: Disable-AD-User.vbs
4. Double-click the vb script file (or Run this file from command window) to disable AD user.
' Disable-AD-User.vbs
' Sample VBScript to disable Active Directory user
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserDN
Dim objUser 

strUserDN= "CN=TestUser,OU=TestOU1,DC=MyDomain,DC=Com"
Set objUser = GetObject("LDAP://"& strUserDN) 
objUser.AccountDisabled = True
objUser.SetInfo

MsgBox("AD user disabled successfully using VBScript code.")

WScript.Quit 

VBScript to Disable Active Directory user using by ObjectGUID

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserGUID with your own user's ObjectGUID string which you are going to disable.
3. Save the file with a .vbs extension, for example: DisableADUserWithGUID.vbs
4. Double-click the vb script file (or Run this file from command window) to disable AD user.
' DisableADUserWithGUID.vbs
' Sample VBScript to disable AD user with ObjectGUID
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserGUID
Dim objUser 

strUserGUID= "A777394D-0B5C-4FD2-BDDC-B12DDFB570A4"
Set objUser = GetObject("LDAP://<guid="& struserguid&">")
objUser.AccountDisabled = True
objUser.SetInfo

MsgBox("AD user disabled successfully using VBScript code.")

WScript.Quit 

VBScript to Disable AD User Account by samAccountName

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserName with your own user's samAccountName which you are going to disable.
3. Save the file with a .vbs extension, for example: DisableADUserWithsamAccountName.vbs
4. Double-click the vb script file (or Run this file from command window) to disable AD user.
' DisableADUserWithsamAccountName.vbs
' Sample VBScript to disable AD user .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset,strUserDN
Dim strSamAccountName,objUser

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

strSamAccountName="Test"

' Filter on user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(samaccountname="& strSamAccountName &"))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF
    ' Retrieve values and display.
    strUserDN = adoRecordset.Fields("distinguishedname").value
    Set objUser = GetObject("LDAP://"& strUserDN) 
        objUser.AccountDisabled = True
        objUser.SetInfo

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

  If strUserDN = "" then
      Msgbox "No user found with the name '"& strSamAccountName &"'"
    Else  Msgbox "The user '"& strSamAccountName &"' disabled successfully..."
   end if

' close ado connections.
adoRecordset.Close
adoConnection.Close

VBScript to Disable Bulk AD users From CSV File

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: DisableBulkADUsersFromCSV.vbs
3. Change the CSV file path C:\Users\Administrator\Desktop\All_Users.csv with your own file path.
4. Double-click the VBScript file (or Run this file from command window) to disable Bulk AD users from CSV file.

Note: Your CSV file (All_Users.csv)  should contains the column objectguid as a first column, otherwise you need to change the index value 0 to other value ---> csvUserFields(0)... which depends on your column index of objectguid in CSV file

VBScript to Disable Bulk AD users From CSV File using VBScript
' DisableBulkADUsersFromCSV.vbs
' Sample VBScript to Disable AD Users from CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

Dim strUserGUID,objUser 

' Variables needed for CSV File Information
Dim varFileName,objFSO,objFile,csvUserFields
Const ForReading = 1

' Specify the csv file full path.
varFileName = "C:\Users\Administrator\Desktop\All_Users.csv"

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(varFileName, ForReading)

' Read the first line - csv columns -not needed for our proceess
objFile.ReadLine

' Skip the error if the user doesn't exist.....
on error resume next

' Read the file and create new user.
Do Until objFile.AtEndOfStream
    ' Splits prioperty values.
    csvUserFields = Split(objFile.ReadLine,",")

' All_Users.csv file should contains the column objectguid as first column
' Otherwise you need change the index value 0 to other value here...csvUserFields(0)...
' which depends on your column index of objectguid in CSV file.

     strUserGUID =  csvUserFields(0)
 Set objUser = GetObject("LDAP://<GUID="& strUserGUID &">")
     objUser.AccountDisabled = True
     objUser.SetInfo
Loop

MsgBox("Bulk AD Users Disabled from CSV file using VBScript.")

WScript.Quit 

Sunday, 24 November 2013

Set Logon As A Service right to User by Powershell, C#, CMD and VBScript

Description:

In this article, I am going to explain about how to set or grant user Logon As A Service permission/privilege using Local Security Policy, VBScript, Powershell, C# and Command Line tool.

Summary:


Set Logon As A Service right to user using Local Security Policy

Follow the below steps to set Log on As Service right via Local Security Policy

1. Open the Run window by pressing 'Windows' + 'R'  keys.
2. Type the command secpol.msc in the text box and click OK.

Set Logon As A Service right to User by Command Prompt, C#, Powershell and VBScript
3. Now the Local Security Policy window will be open, in that window navigate to the node User Rights Assignment (Security Settings -> Local Polices ->User Rights Assignment). In right side pane, search and select the policy Log on as a service.


Set Logon As A Service rights to User by Command Line, C#, Powershell and VBScript

4. Double-click on the policy Log on as a service, in the opened windows click the button Add User or Group, select the user which you want to set logon as a service right and click OK, and click Apply button to finish.

Set Log on As A Service right to User by Powershell, Command Prompt, C# and VBScript


Set or Grant User Logon As A Service right via Powershell

 We can set the Logon As A Service right to user in Powershell by importing the third party DLL ( Carbon ).  Before you run the below script you need to the download latest Carbon files from here Download Carbon DLL.

Steps to follow to set Logon As A Service right via Powershell :

  1. Download latest Carbon files from here Download Carbon DLL.
  2. If you have downloaded the files, extract the zip file and you could see the Carbon DLL inside bin folder (In my case: C:\Users\Administrator\Downloads\Carbon\bin\Carbon.dll).
  3. Copy the below Powershell script commands and place it notepad or textfile.
  4. Now you can replace your Carbon DLL path in following script for the variable $CarbonDllPath
  5. You can also replace the user identity that you are going to set logon as service right in the variable $Identity
  6. Now run as Powershell window with Admin Privilege (Run as Administrator)
  7. Copy the edited Powershell script and Run it in Powershell to set logon as a service right.

$Identity = "DomainName\Administrator"
$privilege = "SeServiceLogonRight"

$CarbonDllPath = "C:\Users\Administrator\Downloads\Carbon\bin\Carbon.dll"

[Reflection.Assembly]::LoadFile($CarbonDllPath)

[Carbon.Lsa]::GrantPrivileges( $Identity , $privilege)


Powershell output :

Set Logon As A Service right to User by Powershell


Other web site links for Carbon DLL:
 https://bitbucket.org/splatteredbits/carbon/downloads
 http://pshdo.com/
 http://get-carbon.org/help/Grant-Privilege.html

Set or Grant User Logon As A Service right/permission to user using C#

You can use the function GrantUserLogOnAsAService to set Logon as a Service right to user using C# code. This function uses the class LsaWrapper.

static void GrantUserLogOnAsAService(string userName)
{
    try
    {
        LsaWrapper lsaUtility = new LsaWrapper();

        lsaUtility.SetRight(userName, "SeServiceLogonRight");

        Console.WriteLine("Logon as a Service right is granted successfully to " + userName);
    }            
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
LsaWrapper class file
public class LsaWrapper
{
// Import the LSA functions

[DllImport("advapi32.dll", PreserveSig = true)]
private static extern UInt32 LsaOpenPolicy(
    ref LSA_UNICODE_STRING SystemName,
    ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
    Int32 DesiredAccess,
    out IntPtr PolicyHandle
    );

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern long LsaAddAccountRights(
    IntPtr PolicyHandle,
    IntPtr AccountSid,
    LSA_UNICODE_STRING[] UserRights,
    long CountOfRights);

[DllImport("advapi32")]
public static extern void FreeSid(IntPtr pSid);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, PreserveSig = true)]
private static extern bool LookupAccountName(
    string lpSystemName, string lpAccountName,
    IntPtr psid,
    ref int cbsid,
    StringBuilder domainName, ref int cbdomainLength, ref int use);

[DllImport("advapi32.dll")]
private static extern bool IsValidSid(IntPtr pSid);

[DllImport("advapi32.dll")]
private static extern long LsaClose(IntPtr ObjectHandle);

[DllImport("kernel32.dll")]
private static extern int GetLastError();

[DllImport("advapi32.dll")]
private static extern long LsaNtStatusToWinError(long status);

// define the structures

private enum LSA_AccessPolicy : long
{
    POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
    POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
    POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
    POLICY_TRUST_ADMIN = 0x00000008L,
    POLICY_CREATE_ACCOUNT = 0x00000010L,
    POLICY_CREATE_SECRET = 0x00000020L,
    POLICY_CREATE_PRIVILEGE = 0x00000040L,
    POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
    POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
    POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
    POLICY_SERVER_ADMIN = 0x00000400L,
    POLICY_LOOKUP_NAMES = 0x00000800L,
    POLICY_NOTIFICATION = 0x00001000L
}

[StructLayout(LayoutKind.Sequential)]
private struct LSA_OBJECT_ATTRIBUTES
{
    public int Length;
    public IntPtr RootDirectory;
    public readonly LSA_UNICODE_STRING ObjectName;
    public UInt32 Attributes;
    public IntPtr SecurityDescriptor;
    public IntPtr SecurityQualityOfService;
}

[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
    public UInt16 Length;
    public UInt16 MaximumLength;
    public IntPtr Buffer;
}
/// 
//Adds a privilege to an account

/// Name of an account - "domain\account" or only "account"
/// Name ofthe privilege
/// The windows error code returned by LsaAddAccountRights
public long SetRight(String accountName, String privilegeName)
{
    long winErrorCode = 0; //contains the last error

    //pointer an size for the SID
    IntPtr sid = IntPtr.Zero;
    int sidSize = 0;
    //StringBuilder and size for the domain name
    var domainName = new StringBuilder();
    int nameSize = 0;
    //account-type variable for lookup
    int accountType = 0;

    //get required buffer size
    LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

    //allocate buffers
    domainName = new StringBuilder(nameSize);
    sid = Marshal.AllocHGlobal(sidSize);

    //lookup the SID for the account
    bool result = LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize,
                                    ref accountType);

    //say what you're doing
    Console.WriteLine("LookupAccountName result = " + result);
    Console.WriteLine("IsValidSid: " + IsValidSid(sid));
    Console.WriteLine("LookupAccountName domainName: " + domainName);

    if (!result)
    {
        winErrorCode = GetLastError();
        Console.WriteLine("LookupAccountName failed: " + winErrorCode);
    }
    else
    {
        //initialize an empty unicode-string
        var systemName = new LSA_UNICODE_STRING();
        //combine all policies
        var access = (int) (
                                LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                                LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                                LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                                LSA_AccessPolicy.POLICY_CREATE_SECRET |
                                LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                                LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                                LSA_AccessPolicy.POLICY_NOTIFICATION |
                                LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                                LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                                LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                                LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                                LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                                LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                            );
        //initialize a pointer for the policy handle
        IntPtr policyHandle = IntPtr.Zero;

        //these attributes are not used, but LsaOpenPolicy wants them to exists
        var ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
        ObjectAttributes.Length = 0;
        ObjectAttributes.RootDirectory = IntPtr.Zero;
        ObjectAttributes.Attributes = 0;
        ObjectAttributes.SecurityDescriptor = IntPtr.Zero;
        ObjectAttributes.SecurityQualityOfService = IntPtr.Zero;

        //get a policy handle
        uint resultPolicy = LsaOpenPolicy(ref systemName, ref ObjectAttributes, access, out policyHandle);
        winErrorCode = LsaNtStatusToWinError(resultPolicy);

        if (winErrorCode != 0)
        {
            Console.WriteLine("OpenPolicy failed: " + winErrorCode);
        }
        else
        {
            //Now that we have the SID an the policy,
            //we can add rights to the account.

            //initialize an unicode-string for the privilege name
            var userRights = new LSA_UNICODE_STRING[1];
            userRights[0] = new LSA_UNICODE_STRING();
            userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName);
            userRights[0].Length = (UInt16) (privilegeName.Length*UnicodeEncoding.CharSize);
            userRights[0].MaximumLength = (UInt16) ((privilegeName.Length + 1)*UnicodeEncoding.CharSize);

            //add the right to the account
            long res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
            winErrorCode = LsaNtStatusToWinError(res);
            if (winErrorCode != 0)
            {
                Console.WriteLine("LsaAddAccountRights failed: " + winErrorCode);
            }

            LsaClose(policyHandle);
        }
        FreeSid(sid);
    }

    return winErrorCode;
}    
}





Set Logon As A Service right to user via Command Line

You can use the NTRights.exe utility to grant or deny user rights to users and groups from a command line or a batch file. The NTRights.exe utility is included in the Windows NT Server 4.0 Resource Kit Supplement 3. Refer: http://support.microsoft.com/kb/266280

Set Logon As A Service right
ntrights +r SeServiceLogonRight -u "Domain\Administrator"
Revoke Logon As A Service right
ntrights -r SeServiceLogonRight -u "Domain\Administrator"

Set or Grant Logon As Service right/privilege to user via VBScript

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserName if you want to give your own name otherwise simply leave it.
3. Save the file with a .vbs extension, for example: SetLogonAsAServiceRight.vbs
4. Double-click the VBScript file (or Run this file from command window) to Set Logon As Service right/permission to user.

' SetLogonAsAServiceRight.vbs
' Sample VBScript to set or grant Logon As A Service Right.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Dim strUserName,ConfigFileName,OrgStr,RepStr,inputFile,strInputFile,outputFile,obj 
strUserName = "work2008\DevUser"
Dim oShell 
Set oShell = CreateObject ("WScript.Shell")
oShell.Run "secedit /export /cfg config.inf", 0, true 
oShell.Run "secedit /import /cfg config.inf /db database.sdb", 0, true

ConfigFileName = "config.inf"
OrgStr = "SeServiceLogonRight ="
RepStr = "SeServiceLogonRight = " & strUserName & ","
Set inputFile = CreateObject("Scripting.FileSystemObject").OpenTextFile("config.inf", 1,1,-1)
strInputFile = inputFile.ReadAll
inputFile.Close
Set inputFile = Nothing

Set outputFile =   CreateObject("Scripting.FileSystemObject").OpenTextFile("config.inf",2,1,-1)
outputFile.Write (Replace(strInputFile,OrgStr,RepStr))
outputFile.Close
Set outputFile = Nothing

oShell.Run "secedit /configure /db database.sdb /cfg config.inf",0,true
set oShell= Nothing

Set obj = CreateObject("Scripting.FileSystemObject")
obj.DeleteFile("config.inf") 
obj.DeleteFile("database.sdb")

Msgbox "Logon As A Service Right granted to user '"& strUserName &"' using Vbscript code"

Thanks,
Morgan
Software Developer
---------------------

Saturday, 23 November 2013

Event ID 5136 - Active Directory Object Change Event

In this article, I am going to explain about the Active Directory change audit Event ID 5136, how to enable or configure Event ID 5136 through Default Domain Controller Policy GPO and Auditpol.exe, and how to disable Event ID 5136.

Summary:


Event ID 5136 Source: Old Value (Deleted Attribute Value)

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          23/11/2013 1:30:42 PM
Event ID:      5136
Task Category: Directory Service Changes
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      myDC.myDomain.com
Description:
A directory service object was modified.
 
Subject:
 Security ID:  myDomain\Administrator
 Account Name:  Administrator
 Account Domain:  myDomain
 Logon ID:  0x2c8f4

Directory Service:
 Name: myDomain.local
 Type: Active Directory Domain Services
 
Object:
 DN: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 GUID: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 Class: user
 
Attribute:
 LDAP Display Name: physicalDeliveryOfficeName
 Syntax (OID): 2.5.5.12
 Value: TechPark
 
Operation:
 Type: Value Deleted
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -

Event ID 5136 Source: New Value (Added Attribute Value)

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          23/11/2013 1:30:42 PM
Event ID:      5136
Task Category: Directory Service Changes
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      myDC.myDomain.Com
Description:
A directory service object was modified.
 
Subject:
 Security ID:  myDomain\Administrator
 Account Name:  Administrator
 Account Domain:  myDomain
 Logon ID:  0x2c8f4

Directory Service:
 Name: myDomain.com
 Type: Active Directory Domain Services
 
Object:
 DN: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 GUID: CN=TestUser,OU=Test,DC=myDomain,DC=Com
 Class: user
 
Attribute:
 LDAP Display Name: physicalDeliveryOfficeName
 Syntax (OID): 2.5.5.12
 Value: TechZone
 
Operation:
 Type: Value Added
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -

Mapping 5136 Old Value Event and New Value Event

Any Active Directory object's attribute change will logs the two 5136 events for Deleted attribute value and Added attribute value. You can find the old value (deleted value) for the corresponding new value (added value) by mapping these two events.

You can find the field section Operation:  in both events
In Old Value Event:
 Type: Value Deleted
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -
In New Value Event:
Operation:
 Type: Value Added
 Correlation ID: {cd1aa2fa-7d62-43c5-8c95-3ba03569a4f2}
 Application Correlation ID: -

Here, you could see the field Type: which tells Value Added or Deleted and Correlation ID which is unique between two events. So you can map these two events by using the value of Correlation ID.

After mapping the events, you can find changed attribute name from the field LDAP Display Name:. From the above event source, we can conclude the value of physicalDeliveryOfficeName (Office) attribute is changed from 'TechPark' to 'TechZone' for the user 'TestUser'

Enable Active Directory Change Event 5136 via Group Policy

    To enable event id 5136  in every Domain Controller, We need to configure audit settings in Default Domain Controllers Policy, or you can create new GPO and links it to the Domain Controllers OU via GPMC console, or else you can configure the corresponding policies on Local Security Policy of each and every Domain Controller..

Follow the below steps to enable Active Directory change audit event 5136 via Default Domain Controllers Policy.

    1. Press the key 'Window' + 'R'
    2. Type the command gpmc.msc, and click OK.
         Note: Skip the above steps by clicking Start -->Administrative Tools -->Group Policy                            Management.
    3. Expand the domain node and Domain Controllers OU,  right-click on the Default Domain Controllers Policy, then click Edit. - refer the below image.

Enable Active Directory Change Audit Event ID 5136


    4. Expand Computer Configuration node and Security Settings and navigate to the node DS Access (Computer Configuration->Policies->Windows Settings->Security Settings-> Advanced Audit Policy Configuration -> Audit Policies->DS Access).

    5. Now edit Audit Directory Service Changes as Success to enable active directory change audit event 5136. - refer the below image.

Enable Active Directory Change Audit Event ID 5136


    6. Run the command gpupdate /force from command prompt to update group policy settings.

Enable Object Level Security Audit (SACL): 

    This event is also controlled by the access control entry (ACE) in the SACL requiring attribute modifications to be logged, even if the Directory Service Changes subcategory is enabled, no change auditing events are logged. For example, if there is no ACE in a SACL requiring Write Property access on the physicalDeliveryOfficeName attribute of a user object to be audited, no auditing events are generated when the physicalDeliveryOfficeName attribute is modified, even if the subcategory Directory Service Changes is enabled..

Follow the below steps to enable SACL for full Domain.

Note: You can also configure SACL for particular OU or User instead of full Domain.

   1. Press the key 'Window' + 'R'
   2. Type the command dsa.msc, and click OK.
       Note: Skip the above steps by clicking Start -->Administrative Tools -->Active Directory Users and Computers.
   3. Right-click the Domain object, and click the properties
   4. Click the Security tab.
        Note: If the Security tab is not available, Ensure the option Advanced Features is checked                       under the View menu.
   5. Click the button Advanced, and select the tab Auditing.
   6. Click the button Add, find the user Everyone, and click OK.
   7.  Check the Successful auditing for Write all properties. -refer below image.

Enable Active Directory Change Audit Event ID 5136


    8. Click the button OK, and click Apply.


Enable Event ID 5136 via Auditpol

Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions.

By using Auditpol, we can get/set Audit Security settings per user level and computer level.

Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable Event ID 5136 through Directory Service Changes subcategory by using the following command
auditpol /set /subcategory:"Directory Service Changes" /success:enable
To update or refresh GPO settings, run the command gpupdate/force

How to disable/stop Event ID 5136

You can disable or stop the audit Event ID 5136 by removing success audit of Directory Service Changes subcategory by using the following command.
auditpol /set /subcategory:"Directory Service Changes" /success:disable
You can also stop this event by removing the success setting from the Default Domain Controller Policy in the setting path (Computer Configuration->Policies->Windows Settings->Security Settings-> Advanced Audit Policy Configuration -> Audit Policies->DS Access->Audit Directory Service Changes)


Note: This article is applies to only Windows Server 2008 R2, Windows Server 2012, Windows 7 and Windows 8

Thanks,
Morgan
Software Developer

Friday, 22 November 2013

Enable and Disable Active Directory User in C#

Description:

In this article, I am going to give C# code examples to Enable Active Directory user and Disable Active Directory user account in C# with two methods.

Summary:


Enable Active Directory User Account via userAccountControl using C#

To use DirectoryEntry class, you need to add reference System.DirectoryServices.ActiveDirectory
private static void EnableADUserUsingUserAccountControl(string username)
     {
        try
        {
            DirectoryEntry domainEntry = Domain.GetCurrentDomain().GetDirectoryEntry();
            // ldap filter
            string searchFilter = string.Format(@"(&(objectCategory=person)(objectClass=user)
                    (!sAMAccountType=805306370)(|(userPrincipalName={0})(sAMAccountName={0})))", username);

            DirectorySearcher searcher = new DirectorySearcher(domainEntry, searchFilter);
            SearchResult searchResult = searcher.FindOne();
            if (searcher != null)
            {
                DirectoryEntry userEntry = searchResult.GetDirectoryEntry();

                int old_UAC=(int)userEntry.Properties["userAccountControl"][0];

                // AD user account disable flag
                int ADS_UF_ACCOUNTDISABLE = 2;

                // To enable an ad user account, we need to clear the disable bit/flag:
                userEntry.Properties["userAccountControl"][0] = (old_UAC & ~ADS_UF_ACCOUNTDISABLE);
                userEntry.CommitChanges();

                Console.WriteLine("Active Director User Account Enabled successfully 
                                          through userAccountControl property");
            }
            else
            {
                //AD User Not Found
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


Disable Active Directory User Account via userAccountControl using C#

private static void DisableADUserUsingUserAccountControl(string username)
    {
        try
        {
            DirectoryEntry domainEntry = Domain.GetCurrentDomain().GetDirectoryEntry();
            // ldap filter
            string searchFilter = string.Format(@"(&(objectCategory=person)(objectClass=user)
                  (!sAMAccountType=805306370)(|(userPrincipalName={0})(sAMAccountName={0})))", username);

            DirectorySearcher searcher = new DirectorySearcher(domainEntry, searchFilter);
            SearchResult searchResult = searcher.FindOne();
            if (searcher != null)
            {
                DirectoryEntry userEntry = searchResult.GetDirectoryEntry();

                int old_UAC = (int)userEntry.Properties["userAccountControl"][0];

                // AD user account disable flag
                int ADS_UF_ACCOUNTDISABLE = 2;

                // To disable an ad user account, we need to set the disable bit/flag:
                userEntry.Properties["userAccountControl"][0] = (old_UAC | ADS_UF_ACCOUNTDISABLE);
                userEntry.CommitChanges();

                Console.WriteLine("Active Director User Account Disabled successfully 
                                    through userAccountControl property");
            }
            else
            {
                //AD User Not Found
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


Enable AD User Account via UserPrincipal using C#

To use PrincipalContext class, you need add reference System.DirectoryServices.AccountManagement which is available only from .NET 3.5;
private static void EnableADUserUsingUserPrincipal(string username)
    {
        try
        {                
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                    (principalContext, username);

            userPrincipal.Enabled = true;

            userPrincipal.Save();

            Console.WriteLine("Active Director User Account Enabled successfully through UserPrincipal");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


Disable AD User Account via UserPrincipal using C#

 private static void DiableADUserUsingUserPrincipal(string username)
    {
        try
        {
            // To use this class, you need add reference System.DirectoryServices.AccountManagement which 
is available only from .NET 3.5;
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                    (principalContext, username);

            userPrincipal.Enabled = false;

            userPrincipal.Save();

            Console.WriteLine("Active Director User Account Disabled successfully through UserPrincipal");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
Note : This article is applies to Windows Server 2003, Windows Server 2008,Windows Server 2008 R2 and Windows Server 2012.

Thanks,
Morgan
Software Developer

Wednesday, 20 November 2013

Get current Date time in JQuery

Description:

  In this article, I am going to write JQuery code examples to get current DateTime, UTC DateTime, current Date, current Date with specific date time format.

Summary:

  1. Get current local Date Time in JQuery
  2. Get current UTC (Universal) Date Time in JQuery
  3. Get current Date in JQuery (without time part)

Get current local Date Time in JQuery

Note: We need add 1 with return value dNow.getMonth(), because the getMonth() method returns the month (from 0 to 11), January is 0, February is 1, and so on.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
function ShowLocalDate()
{
var dNow = new Date();
var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
$('#currentDate').text(localdate)
}

</script>
</head>
<body>

<h1>Get current local Date in JQuery</h1>
<label id="currentDate">This is current local Date Time in JQuery</p>
<button type="button" onclick="ShowLocalDate()">Show Local DateTime</button>

</body>
</html> 


Get current UTC (Universal) Date Time in JQuery

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>

<script>

function ShowUTCDate()
{
var dNow = new Date();
var utc = new Date(dNow.getTime() + dNow.getTimezoneOffset() * 60000)
var utcdate= (utc.getMonth()+1) + '/' + utc.getDate() + '/' + utc.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes();
$('#currentDate').text(utcdate)
}

</script>
</head>
<body>

<h1>Get UTC DateTime in JQuery</h1>
<label id="currentDate">This is UTC DateTime in JQuery</p>
<button type="button" onclick="ShowUTCDate()">Show UTC DateTime</button>

</body>
</html>


Get current Date in JQuery (without time part)

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>

function ShowDate()
{
var dNow = new Date();
var utcdate= (dNow.getMonth()+ 1) + '/' + dNow.getDate() + '/' + dNow.getFullYear();
$('#currentDate').text(utcdate)
}

</script>
</head>
<body>

<h1>Get current Date in JQuery</h1>
<label id="currentDate">This is current Date in JQuery</p>
<button type="button" onclick="ShowDate()">Show current Date</button>

</body>
</html> 

Event ID 4985 - The state of a transaction has changed

In this article, I am going to explain about the Event ID 4985, how to enable Event ID 4985 using Local Security Policy and Auditpol.exe, and how to disable or stop the Event 4985.

Summary:


Event ID 4985 Source:

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          20/11/2013 11:11:01 AM
Event ID:      4985
Task Category: File System
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      myPC.myDomain.local
Description:
The state of a transaction has changed.

Subject:
 Security ID:  SYSTEM
 Account Name:  myPC$
 Account Domain:  myDomain
 Logon ID:  0x3e7

Transaction Information:
 RM Transaction ID: {32c25d18-4a8b-11e3-a6ca-00155d011a07}
 New State:  56
 Resource Manager: {fec2d846-237a-19e1-976f-ef16c05d3ca3}

Process Information:
 Process ID:  0x390
 Process Name:  C:\Windows\System32\svchost.exe

How to enable Event ID 4985 by Local Security Policy

1. Open the Local Security Policy by running the command secpol.msc.
2. Go to the node Audit Policy (Security Settings->Local Policy->Audit Policy).
3. In the right side pane, select the policy Audit object access and configure Success setting.



4. In Window 7/Windows Server 2008 R2 and later versions, you can also configure through Advanced Audit Policy Configuration. Go to the node Object Access (Security Settings->Advanced Audit Policy Configuration->System Audit Polices->Object Access).

5. In the right side pane, select the policy Audit File System configure Success setting.



How to enable Event ID 4985 by Auditpol.exe

Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions.

By using Auditpol, we can get/set Audit Security settings per user level and computer level.

Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable Event ID 4985 through File System subcategory by using the following command
auditpol /set /subcategory:"File System" /success:enable
To update or refresh GPO settings, run the command gpupdate/force

How to disable/stop Event 4985

You can disable or stop the audit Event ID 4985 by removing success audit in File System subcategory by using the following command.
auditpol /set /subcategory:"File System" /success:disable
You can also stop this event by removing the success setting from the Local Security Policy in the setting path Security Settings->Advanced Audit Policy Configuration->System Audit Polices->Object Access->Audit File System.

Tuesday, 19 November 2013

The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration


Description:

   Hi, I got the error The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration while installing my ASP.NET Web application in Windows Server 2008 32 Bit machine with .NET Framework 4.0. But when I install this ASP.NET Web Application in 64 Bit operating system it is working fine.

My Web Config file source:
<configuration>
<runtime>
    <assemblybinding appliesto="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentassembly>
        <assemblyidentity name="System.Web.Extensions" publickeytoken="31bf3856ad364e35">
        <bindingredirect newversion="3.5.0.0" oldversion="1.0.0.0-1.1.0.0">
      </bindingredirect></assemblyidentity></dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Extensions.Design" publickeytoken="31bf3856ad364e35">
        <bindingredirect newversion="3.5.0.0" oldversion="1.0.0.0-1.1.0.0">
      </bindingredirect></assemblyidentity></dependentassembly>
    </assemblybinding>
  </runtime>
  <system .web.extensions="">
    <scripting>
      <webservices>
        <jsonserialization maxjsonlength="2147483647">
      </jsonserialization></webservices>
    </scripting>
  </system>
</configuration>


I have googled some time to find the solution for the issue The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration. many solutions asked me to check the Application Pool version, whether Application Pool uses the 4.0 version or not?.. after I have checked my ApplicationPool, confirmed my application pool is running 4.0 version, so that is not an issue. Then finally I got the following solution.

Solution: The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration

After googled some time, the following solution was worked for me.
Yes, I have added the following config setting in my webconfig file that resolved my issue
<configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>

My Resolved Web Config file source:
<configuration>
<configsections>
<sectiongroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <sectiongroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
        <section allowdefinition="MachineToApplication" name="scriptResourceHandler" requirepermission="false" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
        <sectiongroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
          <section allowdefinition="Everywhere" name="jsonSerialization" requirepermission="false" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
        </section></sectiongroup>
      </section></sectiongroup>
    </sectiongroup>
</configsections>
<runtime>
    <assemblybinding appliesto="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentassembly>
        <assemblyidentity name="System.Web.Extensions" publickeytoken="31bf3856ad364e35">
        <bindingredirect newversion="3.5.0.0" oldversion="1.0.0.0-1.1.0.0">
      </bindingredirect></assemblyidentity></dependentassembly>
      <dependentassembly>
        <assemblyidentity name="System.Web.Extensions.Design" publickeytoken="31bf3856ad364e35">
        <bindingredirect newversion="3.5.0.0" oldversion="1.0.0.0-1.1.0.0">
      </bindingredirect></assemblyidentity></dependentassembly>
    </assemblybinding>
  </runtime>
  <system .web.extensions="">
    <scripting>
      <webservices>
        <jsonserialization maxjsonlength="2147483647">
      </jsonserialization></webservices>
    </scripting>
  </system>
</configuration>

Wednesday, 13 November 2013

Enable File Access Auditing in Windows

In this article I am going to explain about File System Access Auditing and how to enable File System Access Auditing in Windows environment. Here, in some places we will refer File Access Auditing as File Server Access AuditingFile System Change Auditing and File Share Change Auditing, all the terms are equally interchangeable.

Summary:

  1. File System/File Server Access Auditing Introduction
  2. File System Access Audit Event IDs 
  3. Steps to Enable File Access Auditing Event IDs via new Group Policy
  4. Enable File Access Auditing to Specific File Servers
  5. Steps to Enable File Access Security Audit
  6. Steps to Enable File Access Auditing using Auditpol command line tool

File Access/File Share Access Auditing Introduction:

  In an every Organisation, sharing files and documents to their users through Network Environment is inevitable. For the security purpose we should give permission to access some kind of files and folders only to the specific set of users. However we can't give perfect permission to perfect users, in that case auditing file or folder access is inevitable for any organisation. the possible accesses are File Create/Add, File Delete, File Open, File Copy, File Rename, File Move, File Access, and File Permission change, and File Access failures. We can easily track these accesses by File Share Audit Event IDs which are controlled by the Audit Policy and File Security Audit. So to get these event logs you need to Enable Object Access Audit Policy and File Access Security Audit.

File Access Audit Event IDs:

File Access Auditing is controlled by the following event IDs

4656: This is the first event logged when an user attempts to access the file, this event gives information about what type of access was requested by the user and it will not give info about what type access actually made by user (which is given by the Event ID 4663), 4656 is controlled by the audit policy subcategory settings Handle Manipulation and File System.

4663: This event gives the info of what type actual operation is done by user on a file.

4658: This event get logged when user close the file, it helps to determine how long the file was open correlating this Event ID with earlier Event ID 4656 with the same handle ID.

4660: This event logged when an user delete the file or folder

4990: This event logged when an user opens a file .

4670: This event logged when user changes the permission of the file (security control list).  The event contains the information, who changed the permissions, old and new permissions.

5145: This is a Advanced Detailed File Share event which is available only from Windows 7/ Windows Server 2008 R2 and later versions,  5145 is equivalent event id of 4656, it contains extra information like user's client machine (source machine) address and share path (network path) of accessed file.

Steps to Enable File System Change Audit Event IDs  via new Group Policy:

Follow the below steps to configure File Share Access Auditing Events:

     Note: You should also configure File Access Audit Security settings on the Folder which you are going to audit accesses.

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

2. Expand the domain node, select and right-click on the OU which contains all the file servers (here I have selected OU File Servers), then click Create a GPO in this domain, and link it here...


Enable File System Change Auditing Event IDs

3. Type the new GPO name and click OK (Ex: File System Audit Policy).

How to Enable File System Access Audit Event IDs

4. Right-click on the newly created GPO, then click Edit.

How to Enable File System Change Audit Event IDs

5. Expand the Computer Configuration, and go to the node Audit Policy(Computer Configuration->Polices->Windows Settings->Security Settings->Local Polices->Audit Policy).

6. In the left side pane, select Object Access, then double-click on this Setting.

Enable File System Change Auditing Event IDs

7. In the opened window, check the values Success and Failure, the click Apply.

How to Enable File System Access Audit Event IDs

8. In Windows Server R2 and later versions, You can also configure this settings through Advanced Audit Policy Configuration. go to the node Advanced Audit Policy Configuration (Computer Configuration->Polices->Windows Settings->Security Settings->Advanced Audit Policy Configuration)

9. Expand this node, go to Object Access (Audit Polices->Object Access), then change the settings
Audit Detailed File Share, Audit File System and Audit Handle Manipulation.

Note: The Audit Handle Manipulation setting controls the event ID 4656, it may be the noisy event for you. so if you don't want event 4656, leave the setting Audit Handle Manipulation as Not Configured.

How to Enable File System Access Audit Event IDs

10. Refresh or update the gpo by running the command GPUpdate/Force to apply this setting in the all the File Server which are inside OU File Servers.


Apply File Access Audit Policy to Specific File Servers:

    By the above steps, we have configured file access audit events for all the File Servers which are under OU File Servers, but in some cases, we may want to configure policy only for set of file servers. You can achieve this by Security Filtering of Group Policy.

1. Go to the tab scope, in Security Filtering section, select the entry Authenticated Users, and click Remove.

How to Enable File System Access Audit Event IDs

2. Click the Add button, click Object Types.. then check Computers, and select the computers (File Server Computer) which you want apply file system audit policy settings, and click OK to apply.

How to Enable File System Access Auditing Event IDs

4. Refresh or update the gpo by running the command GPUpdate/Force to apply this setting in the all the selected File Servers.

Steps to Enable File Access Security Audit:

1. Right-click on the Folder which you want to configure audit events, and click Properties.

Steps to Enable File System Change Auditing Event IDs

2. Select Security tab, and click Advanced button.

Steps to Enable File System Access Auditing Event IDs

3. Navigate to the tab Audit, and click Add button.

Steps to Enable File Access Auditing Event IDs

4. Select the account Everyone, and check Successful and Failed Audit options which are you want to audit, click the button OK, and click Apply. 

Steps to Enable File System Access Auditing Event IDs


Steps to Enable File Access Auditing using Auditpol command line tool:

    Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions. By using Auditpol, we can get/set Audit Security settings per user level and computer level.

   Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable file access audit success events (Event ID 5145, 4663,4660,4656,4658) by using following commands
Auditpol /set /subcategory:"Detailed File Share" /success:enable
Auditpol /set /subcategory:"File System" /success:enable
You can enable file access audit failure events (Event ID 5145, 4663,4660,4656,4658) by using following commands
Auditpol /set /subcategory:"Detailed File Share" /failure:enable
Auditpol /set /subcategory:"File System" /failure:enable
Note: to get event id 4656 you can also enable Handle Manipulation setting
Auditpol /set /subcategory:"Handle Manipulation" /success:enable
Note : This article is applies to Windows Server 2003, Windows Server 2008,Windows Server 2008 R2, Windows Server 2012, Windows 7 and Windows 8.

Thanks,
Morgan
Software Developer

Thursday, 7 November 2013

Get current Date time in Javascript

Description:

  In this article, I am going to write javascript code examples to get current DateTime, UTC DateTime, current Date, current Date with specific date time format.

Summary:

  1. Get current local Date Time in Javascript
  2. Get current UTC (Universal) Date Time in Javascript
  3. Get current Date in Javascript (without time part)

Get current Date Time in Javascript

Note: We need add 1 with return value dNow.getMonth(), because the getMonth() method returns the month (from 0 to 11), January is 0, February is 1, and so on.
<html>
<head>
<script>
function ShowLocalDate()
{
var dNow = new Date();
var localdate= (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
document.getElementById("currentDate").innerHTML=localdate;
}
</script>
</head>
<body>
<h1>Get current local Date in Javascript</h1>
<label id="currentDate">This is current local Date Time in Javascript</p>
<button type="button" onclick="ShowLocalDate()">Show Local DateTime</button>
</body>
</html> 

Get current UTC (Universal) Date Time in Javascript

<html>
<head>
<script>
function ShowUTCDate()
{
var dNow = new Date();
var utc = new Date(dNow.getTime() + dNow.getTimezoneOffset() * 60000)
var utcdate= (utc.getMonth()+1) + '/' + utc.getDate() + '/' + utc.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes();
document.getElementById("currentDate").innerHTML=utcdate;
}
</script>
</head>
<body>
<h1>Get UTC DateTime in Javascript</h1>
<label id="currentDate">This is UTC DateTime in Javascript</p>
<button type="button" onclick="ShowUTCDate()">Show UTC DateTime</button>
</body>
</html> 

Get current Date in Javascript (without time part)

<html>
<head>
<script>
function ShowDate()
{
var dNow = new Date();
var utcdate= (dNow.getMonth()+ 1) + '/' + dNow.getDate() + '/' + dNow.getFullYear();
document.getElementById("currentDate").innerHTML=utcdate;
}
</script>
</head>
<body>
<h1>Get current Date in Javascript</h1>
<label id="currentDate">This is current Date in Javascript</p>
<button type="button" onclick="ShowDate()">Show current Date</button>
</body>
</html> 

Event ID 4634 logoff - An account was logged off

    In this article I am going to explain about the Active Directory user's Logoff  Event ID 4634, how to enable this event via group policy, how to enable this event via auditpol, and how to track user's logon duration from logon 4624 and logoff 4634 events.

Refer this article Tracking User Logon Activity using Logon and Logoff Events to know about how to track user's logon duration from logon 4624 and logoff 4634 events.

Summary:

  1. Event ID 4634 Log Source
  2. How to enable Logoff event 4634 through Group Policy
  3. How to enable Logoff event 4634 using Auditpol
  4. How to stop/disable logoff event 4634

Event ID 4634 Log Source

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          11/5/2013 2:28:53 PM
Event ID:      4634
Task Category: Logoff
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      myPC.myDomain.com
Description:
An account was logged off.

Subject:
 Security ID:  SYSTEM
 Account Name:  myPC$
 Account Domain:  myDomain
 Logon ID:  0x1F759B

Logon Type:   3

This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.

How to enable Logoff event 4634 through Group Policy

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

2. Expand the domain node,  then right-click on the Default Domain Policy, and click Edit option

Event ID 4634


3. Expand the Computer Configuration node, go to the node Audit Policy(Computer Configuration->Policies->Windows Settings->Security Settings->Local Policies->Audit Policy).

4. Navigate to the right side pane, select the policy Audit logon events, and set the success audit value.

Enable Event ID 4634 logoff - An account was logged off


5. In Windows 7/Server 2008 R2 and later versions, you can enable Event ID 4634 also through Advanced Audit Policy Configuration.  Expand the Computer Configuration, and go to the node Advanced Audit Policy Configuration (Computer Configuration->Polices->Windows Settings->Security Settings->Advanced Audit Policy Configuration)

6. Expand this node, go to Logon/Logoff (Audit Polices-> Logon/Logoff ), then select the Setting
Audit Logoff, and set its value as Success


Enable Event ID 4634


8. Run the command GPUpdate /force to apply this setting in all the all the Computers


How to enable Logoff Event ID 4634 using Auditpol

     Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions. By using Auditpol, we can get/set Audit Security settings per user level and computer level.

   Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable audit Event ID 4634 by using the following command
Auditpol /set /subcategory:"Logoff" /success:enable

How to stop/disable Event ID 4634

You can disable success audit Event ID 4634 by using the following command
Auditpol /set /subcategory:"Logoff" /success:disable
You can also stop this event by removing the success setting from the GPO in the setting path  Computer Configuration->Polices->Windows Settings->Security Settings->Advanced Audit Policy Configuration->Audit Polices->Logon/Logoff->Audit Logoff.

 Note: You need to refresh/update GPO for every change by running the command GPUpdate/force.

Note : This article is applies to Windows Server 2008,Windows Server 2008 R2, Windows Server 2012, Windows 7 and Windows 8.

Thanks,
Morgan
Software Developer

Monday, 4 November 2013

Event ID 4740 - A user account was locked out

  In this article I am going to explain about the Active Directory user account locked out event 4740. It also includes the steps to enable event 4740 and disable 4740 account locked out event. This event comes under the Account Management category/User Account Management subcategory of Security Audit. Equivalent event of 4740 in server 2003/xp based machine is 644.

NextTrack root cause of AD Account Lockout

Summary:

  1. Event 4740 Example source
  2. How to enable 4740 event through Default Domain Controllers Group Policy
  3. How to enable 4740 Account locked out event via Auditpol
  4. How to disable/stop 4740 Account locked out event

Event 4740 Example source

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          31/10/2013 5:02:05 PM
Event ID:      4740
Task Category: User Account Management
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      myServer.myDomain.com
Description:
A user account was locked out.

Subject:
 Security ID:  SYSTEM
 Account Name:  myServer$
 Account Domain:  myDomain
 Logon ID:  0x3e7

Account That Was Locked Out:
 Security ID:  myDomain\testuser
 Account Name:  testUser

Additional Information:
 Caller Computer Name: my-PC

How to enable 4740 event through Default Domain Controllers Group Policy

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

2. Expand the domain node, expand the Domain Controllers OU, then Right-click on the Default Domain Controllers Policy, and click the Edit option

Event ID 4740 - A user account was locked out


3. Expand the Computer Configuration node, go to the node Audit Policy(Computer Configuration->Policies->Windows Settings->Security Settings->Local Policies->Audit Policy).

4. Navigate to the right side pane, select the policy Audit account management, and set the success audit value.

Event ID 4740 - Active Directory user account was locked out

5. To update or refresh GPO settings, run the command gpupdate/force


How to enable 4740 Account locked out event via Auditpol

Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions.

By using Auditpol, we can get/set Audit Security settings per user level and computer level.

Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable Active Directory Account Lockout audit event (Event ID 4740) through User Account Management subcategory by using the following command
auditpol /set /subcategory:"User Account Management" /success:enable
To update or refresh GPO settings, run the command gpupdate/force


How to disable/stop 4740 Account locked out event

You can disable or stop Active Directory Account Lockout audit event (Event ID 4740) by removing success audit in User Account Management subcategory by using the following command.
auditpol /set /subcategory:"User Account Management" /success:disable
You can also stop this event by removing the success setting from the Default Domain Controllers GPO in the setting path Computer Configuration->Polices->Windows Settings->Security Settings->Audit Policy->Account Management

Note : This article is applies to Windows Server 2008,Windows Server 2008 R2, Windows Server 2012, Windows 7 and Windows 8.

Thanks,
Morgan
Software Developer