How to run commands using SYSTEM account

INTRODUCTION

This is a process I use whenever I get an “Access Denied” message. One example of this is when I do not have access to SQL Server directly, only administrative rights to the actual server.

PROCESS

1) Download PsExec which is part of the PsTools suite

2) Extract PsTools.zip to a convenient location. I usually copy PsExec.exe to the System32 folder. This allows PsExec.exe to be executed from any folders without specifying the full path.

3) Execute the following command

PsExec.exe -s -i -d CMD.exe

4) From within this new command prompt, everything you open will open as the SYSTEM account.

EXAMPLES

Viewing NT Secrets

Open Regedit.exe and you will be able to see content of HKEY_LOCAL_MACHINE\SECURITY

  • This allows you to view passwords that were stored as NT Secrets

Opening SQL Server Management Studio as SYSTEM

Open SQL Management Studio and you will be able to log on with SYSTEM

  • This allows you to access SQL without directly having been granted SQL right yet you have administrative rights to SQL Server

You will be able to browse to any folder that only allows SYSTEM account

  • You can export permissions with SetACL/ICACLS to folders that administrators group might have been removed on
  • Kill processes that give error Access Denied when you try to terminate it with normal Administrator rights

WinDirStat/TreeSize etc.

Running something like TreeSize as SYSTEM will actually give you a better view and understanding of what is using space because you will get less access denials

Some others…

  • Simulate GPO start scripts
  • Simulate GPO based MSI installation
  • Diagnose why scheduled tasks that run as SYSTEM don’t run as intended
  • Start/stop protected services

CONCLUSION

Using this process, (or one similar) will allow you to start processes as the SYSTEM account allowing you to access parts of files system, registry and application not accessible with normal Administrative rights.

How to manage local account passwords from Active Directory without LAPS

Introduction

Active Directory provided a mechanism to set account password via GPO preferences. Unfortunately this was done with an encrypted cpassword value for which the decryption key was published and subsequently the functionality was blocked.

Later, Local Administrator Password Solution (LAPS), was adopted by Microsoft and it is well suited for the task.

The approach described in this article is an alternative method to LAPS which can be used if the schema extension requirement of LAPS cannot be done. It also allows for multiple account management.

For this solution you will need:

  • File Share
  • SQL Server
  • Group Policy
  • PasswordImporter
  • PasswordViewer

Both PasswordImport and PasswordViewer is available within the same download here

Create share

Create a folder on a server which will hold the passwords reset output files from computers that get the GPO.

It is important to only allow administrators to view files within this folder. Everyone (authenticated users) should only have create/write permission (as shown below). The reason for this is that password will be stored here in clear-text until the PasswordImporter
tool processed it.

Create GPO

Create a GPO and filter it to the computer objects for the computers you wish to manage passwords for.

 

The startup script needs to be set to save password text files to the share created in an earlier step.

Create SQL Table

Use the following SQL script to create a table within SQL to store passwords. Assign a group to this group to SQL and grant it SELECT rights on the Passwords table. Add all your administrators and support personnel into this group.

CREATE TABLE [dbo].[Passwords](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ComputerName] [varchar](255) NOT NULL,
[Password] [varchar](255) NOT NULL,
CONSTRAINT [PK_Passwords] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Below is an example of the passwords stored encrypted within SQL

Setup PasswordImporter

PasswordImporter is an application that reads password files from the share and import is, encrypted, into SQL. After a successful import, the password file is deleted.

Open Configurator and specify Location, ConnectionString and LogFile values. Note that Location and ConnectionString needs to be encrypted with encryption key wL!PIQj%EeWj%L^e$nEpdjFzL0d9%Y1#

 

Schedule this application to run every few minutes to import passwords to SQL database

Setup PasswordViewer

PasswordViewer is an application that shows the specified computers password. This application should be distributed to all administrators and support personnel.

Open Configurator and specify FQDN, NetBIOS and ConnectionString values. Note that ConnectionString needs to provide placeholder values for Domain, Username and
Password, for example:

Data source=YOURSQLSERVER;initial catalog=YOURDATABASE;Integrated Security=SSPI; User Id = [DOMAINNAME\USERNAME]; Password = [PASSWORD]

Phasing in a Group Policy

Group policies can be applied selectively to specific devices with the help of groups. Utilising this, it is possible to phase-in group policies, over a period of time, by randomly adding non-members user or computers at a set interval, to a group filtering a group policy.

Introduction

 

Some settings, especially security related, are postponed indefinitely because no built in phase-in mechanism exists. Sure you can apply a GPO via a group but you have to remember to keep adding members to it and even then, you will
probably not add members in randomly. The process below tackles these issues by automating the GPO phase-in process.

 

Please note: The process below is intended to be configured on the group that is configured as a security filter on a GPO

 

Implementation

 

1) Download and extract ADRandomAddToGroup.zip (here is VirusTotal scan) to a folder of your choice, on the computer which it will be scheduled to run on.

 

2) Get group DN

 

 

3) Run Configurator.exe (Configurator Editor).

 

All configuration is stored within the ADRandomAddToGroup.ConsoleApp.exe file and can be either edited directly or with my Configuration Editor tool.

 

a) On the Settings tab, enter the Group’s distinguished name (DN), recorded in Step 2.

b) Configure whether users or computers should be randomly added, and how many to add at a time. For this example, users are added randomly, five at a time.

 

 

c) On the userExcludedDNs tab, add distinguished names of OUs that contains objects that should never be added to this group. (Use +/-/Insert/Delete/Spacebar to manage entries.)

 

 

d) On the userIncludedDNs tab, add distinguished names of OUs that contains objects that should be added to this group. (Use +/-/Insert/Delete/Spacebar to manage entries.)

 

e) Similarly, included and excluded distinguished names can be configured for computer objects.

f) Save the configuration file and close Configuration Editor.

 

This is how the XML file look for the above setting if you choose to edit it manually.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="userExcludedDNs" type="System.Configuration.NameValueSectionHandler" />
<section name="userIncludedDNs" type="System.Configuration.NameValueSectionHandler" />
<section name="computerExcludedDNs" type="System.Configuration.NameValueSectionHandler" />
<section name="computerIncludedDNs" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<userExcludedDNs>
<add key="35206bba-ff72-40da-ba30-26c93e29470b" value="CN=Account Operators,CN=Builtin,DC=dundermifflin,DC=com" />
<add key="7f8e789c-0978-4378-b718-08501995a307" value="CN=Users,DC=dundermifflin,DC=com" />
</userExcludedDNs>
<userIncludedDNs>
<add key="UserExclusion2" value="CN=Users,DC=dundermifflin,DC=com" />
<add key="091bb899-58b4-427d-a5a9-da29dde49f0a" value="OU=Test Users,OU=Accounts,OU=Dunder Mifflin,DC=dundermifflin,DC=com" />
</userIncludedDNs>
<computerExcludedDNs />
<computerIncludedDNs />
<appSettings>
<add key="groupDN" value="CN=DG-Tier2Users,OU=Delegation Groups,OU=Groups,OU=Dunder Mifflin,DC=dundermifflin,DC=com" />
<add key="userAddToGroup" value="true" />
<add key="userAddToGroupLimit" value="5" />
<add key="computerAddToGroup" value="false" />
<add key="computerAddToGroupLimit" value="0" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

Demo Execution

 

1) Output for the ADRandomAddToGroup.ConsoleApp.exe command

 

 

2) Random members added to group after first execution

 

 

3) Random members added to group after second execution

 

 

CODE

 

Here is the section in the code that manages the Random Group Members.

try
{
if (string.IsNullOrEmpty(domainFQDN))
{
domainFQDN = ActiveDirectory.GetFQDN(groupDN);
}

DirectoryEntry group;
if (!string.IsNullOrEmpty(domainUserName))
{
group = new DirectoryEntry("LDAP://" + domainFQDN + "/" + groupDN, domainUserName, domainPassword);
}
else
{
group = new DirectoryEntry("LDAP://" + domainFQDN + "/" + groupDN);
}

//Connect to domain
DirectoryEntry de = new DirectoryEntry("LDAP://" + domainFQDN, domainUserName, domainPassword);
if (!string.IsNullOrEmpty(domainUserName))
{
de = new DirectoryEntry("LDAP://" + domainFQDN, domainUserName, domainPassword);
}
else
{
de = new DirectoryEntry("LDAP://" + domainFQDN);
}

if (userAddToGroup)
{
//Loop through users
try
{                      
using (DirectorySearcher ds = new DirectorySearcher())
{
SortOption sortOption = new SortOption("objectGUID", SortDirection.Ascending);

ds.SearchRoot = de;
ds.PageSize = 1000;
ds.Filter = "(&(objectCategory=person)(objectClass=user))";
ds.PropertiesToLoad.Add("memberOf");
ds.PropertiesToLoad.Add("distinguishedName");
ds.PropertiesToLoad.Add("description");
ds.PropertiesToLoad.Add("userAccountControl");
ds.PropertiesToLoad.Add("lastLogonTimestamp");
ds.PropertiesToLoad.Add("lastLogon");
ds.PropertiesToLoad.Add("pwdLastSet");
ds.PropertiesToLoad.Add("whenCreated");
ds.PropertiesToLoad.Add("objectGUID");
ds.SearchScope = SearchScope.Subtree;
ds.Sort = sortOption;

SearchResultCollection result = ds.FindAll();

int userAddToGroupCount = 0;

foreach (SearchResult sr in result)
{
try
{
string distinguishedName = "";
if (sr.Properties.Contains("distinguishedName"))
{
distinguishedName = sr.Properties["distinguishedName"][0].ToString();
}

DirectoryEntry user = sr.GetDirectoryEntry();
if ((!ActiveDirectory.EntryInDN(user, userExcludedDNs)) && (ActiveDirectory.EntryInDN(user, userIncludedDNs)))
{
if (userAddToGroupCount < userAddToGroupLimit)
{
if (ActiveDirectory.AddToGroup(group, distinguishedName))
{
//Increase count
userAddToGroupCount++;

//Log and display
Logging.LogAndDisplay("Informational", "Added user '" + distinguishedName + "' to group '" + groupDN + "'", logFile);
}
}
//else
//{
//    //Verbose
//    Logging.LogAndDisplay("Informational", "[NOT REAL] Added user '" + distinguishedName + "' to group '" + groupDN + "'", logFile);
//}
}
}
catch(Exception ex)
{
//Item error
Logging.LogAndDisplay("Warning", ex.Message, logFile);
}
}
}
}
catch(Exception ex)
{
//Catch global user error
Logging.LogAndDisplay("Error", ex.Message, logFile);
}
}

if (computerAddToGroup)
{
//Loop through computers
try
{
using (DirectorySearcher ds = new DirectorySearcher())
{
SortOption sortOption = new SortOption("objectGUID", SortDirection.Ascending);

ds.SearchRoot = de;
ds.PageSize = 1000;
ds.Filter = "(objectCategory=computer)";
ds.PropertiesToLoad.Add("memberOf");
ds.PropertiesToLoad.Add("distinguishedName");
ds.PropertiesToLoad.Add("description");
ds.PropertiesToLoad.Add("userAccountControl");
ds.PropertiesToLoad.Add("lastLogonTimestamp");
ds.PropertiesToLoad.Add("lastLogon");
ds.PropertiesToLoad.Add("pwdLastSet");
ds.PropertiesToLoad.Add("whenCreated");
ds.PropertiesToLoad.Add("objectGUID");
ds.SearchScope = SearchScope.Subtree;
ds.Sort = sortOption;

SearchResultCollection result = ds.FindAll();

int computerAddToGroupCount = 0;

foreach (SearchResult sr in result)
{
try
{
string distinguishedName = "";
if (sr.Properties.Contains("distinguishedName"))
{
distinguishedName = sr.Properties["distinguishedName"][0].ToString();
}

DirectoryEntry computer = sr.GetDirectoryEntry();
if ((!ActiveDirectory.EntryInDN(computer, computerExcludedDNs)) && (ActiveDirectory.EntryInDN(computer, computerIncludedDNs)))
{
if (computerAddToGroupCount < computerAddToGroupLimit)
{
if (ActiveDirectory.AddToGroup(group, distinguishedName))
{
//Increase count
computerAddToGroupCount++;

//Log and display
Logging.LogAndDisplay("Informational", "Added computer '" + distinguishedName + "' to group '" + groupDN + "'", logFile);
}
}
//else
//{
//    //Verbose
//    Logging.LogAndDisplay("Informational", "[NOT REAL] Added computer '" + distinguishedName + "' to group '" + groupDN + "'", logFile);
//}
}
}
catch (Exception ex)
{
//Item error
Logging.LogAndDisplay("Warning", ex.Message, logFile);
}
}
}
}
catch(Exception ex)
{
//Catch global computer error
Logging.LogAndDisplay("Error", ex.Message, logFile);
}
}
}
catch(Exception ex)
{
//Catch global group error
Logging.LogAndDisplay("Error", ex.Message, logFile);
}

 

Conclusion

 

Using this process, it is easy to set and forget a GPO so that it randomly adds to the scope of management without manual intervention.

 

 

How to thread single-threaded applications

Introduction

CommandThreader is a command line tool that runs commands, line by line, but instead of it running only one at a time, it executes a batch of them so as one closes, it automatically starts a new command. The list of commands is provided via an input file
and the number of simultaneous running commands is specified as a number of allowed threads.

Implementation

Download and extract CommandThreader.zip (VirusTotal Scan Result) to a folder of your choice, on the computer that it will be scheduled to run on.

Demo Execution

In this demo, I execute a dummy application called DummyApp.exe. All this application does is delay for a random number of seconds and as a return code returns this numbers of seconds that it delays. This can
be any application that takes a long time to complete but is not resources intensive.

Input File

C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|false|true|60
...

 

Input File breakdown

C:\Temp\DummyApp\DummyApp.exe|DummyArgument|C:\Temp\DummyApp|
false|true|
60

  • Command to run
  • Arguments for the command
  • Working folder
  • Execute command hidden
  • Wait for command to exit
  • Maximum amount of time that CommandThreader should wait before killing process

CommandThreader Command

With the command below a total of 5 threads will be maintained

CommandThreader.exe DummyInput.txt 5

 

CommandThreader Output

Conclusion

With CommandThreader, the time taken to run 100s long running processes can be drastically reduced.

Strategy to centrally manage Local Administrators group from Active Directory

Uncontrolled local administrators groups within any organisation pose a huge security risk. Because these groups are locally managed it becomes difficult to audit and maintain them.

Introduction

 

Active Directory does provide mechanisms such as Group Policy Preferences, Restricted Groups etc. which can manage groups centrally. The issue is that local Administrators groups can differ vastly from computer to computer and because of this it is difficult
to standardize settings within a policy. This leads to over permissions because these individual permissions are painful to define and a higher privileged than required is usually assigned.

 

To make it worse, in a mature environment you first need visibility on current members and chances are that you would need to rely on other parties to rectify or change these because of the initial requirements.

 

In this article, I explain my approach to centrally manage Local Administrators group from Active Directory using a custom developed application.

 

Definitions

 

Local Administrators group The local built-in Administrators group found on each computer.
AD Local Admin group An Active Directory group for each computer that is added to the Local Administrators group of the computer. Its purpose is to hold all the members intended to have Administrative permission to a particular computer.
Local Administrator Permission Referring to the actual permissions given to Administrators.

 

Process Flow

 

Computer OU Loop

Application enumerates computers in the computer OUs specified and adds them to a collection.

 

Computer Loop

Creates a computer AD Local Admin group for each computer if it doesn’t already exist.

 

Local Admin Member Loop

Add members of Local Administrators group to AD Local Admin group. If the member is already part of the AD Local Admin group, remove it from computer’s Local Administrators group. It is important to note that these
two actions will not occur within same execution to allow Kerberos tokens to update.

 

 

 

 

 

Benefits

 

  • Rebuilding computers with the same computer name will restore all administrators.
  • Enable auditing of users with local Administrators permissions without directly querying computer.
    • AD Local Admin group members can be queried directly from Active Directory without connecting to remote computers.
  • Enforce a stronger password policy for the user accounts with Administrator permission to certain computers.
    • Add required AD Local Admin group to a group defined in a fine-grained password policy
  • Remove dormant/orphaned entries.
  • Central management of local administrator permissions.
    • Simply add users or groups (preferably role groups) to the AD Local Admin group to give local Administrator permissions on computers.
  • Any new members will automatically be removed from Local Administrators group and added to the AD LocalAdmins group
  • After implementation, local administrator permission can be enforced via AD.

 

 

Implementation

 

1) Download and extract
AdminGroups.zip (here is VirusTotal scan)
to a folder of your choice on the computer on which it will be scheduled to run.

2) Create a location in Active Directory to create AD Local Admin groups in and record the distinguished name (DN).

 

 

3) Record all the Computer OU’s distinguished name (DN) for the computers that AD Local Admin groups need to be created for. These can be workstations or servers but generally this in only done for servers.

 

 

4) Run

Configurator.exe (Configurator Editor).

 

All configuration is stored within the AdminGroups.ConsoleApp.exe.config file and can be either edited directly or with my Configuration Editor tool.

 

a) On the Settings tab, enter the Admin Group OU’s distinguished name (DN), recorded in Step 2.

b) Enter the prefix that should be used when creating AD Local Admin Group.

c) Enter the suffix that should be used when creating AD Local Admin Group.

d) Optionally add a Group Name to add the computer account to on execution. This is useful if you want other policies to trigger or if you want to see process of the AdminGroups tool.

 

 

e) On the RemoveUsersFromLocalAdmins tab, enter usernames of local accounts that you want to automatically remove from the Local Administrators group.
Use this if redundant local user account with Administrators rights exist, perhaps accounts created as part of the imaging/build process. (Use +/-/Insert/Delete/Spacebar to manage entries.)

 

 

f) On the ComputerOUs tab, enter the Computer OU’s distinguished name (DN), recorded in Step 3. (Use +/-/Insert/Delete/Spacebar to manage entries.)

 

 

g) Add any groups that should not be automatically synced and removed from the AD Local Admins groups, for example, Global Admins. (Use +/-/Insert/Delete/Spacebar to manage entries.)

 

 

h) Save configuration file and close Configuration Editor.

 

This is how the XML file look for the above setting if you choose to edit it manually.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="RemoveUsersFromLocalAdmins" type="System.Configuration.NameValueSectionHandler" />
<section name="ComputerOUs" type="System.Configuration.NameValueSectionHandler" />
<section name="ExcludedDomainGroups" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<ComputerOUs>
<add key="e91e156f-22fe-4b45-8c9e-0863b448cf6f" value="OU=Servers,OU=Computers,OU=Dunder Mifflin,DC=dundermifflin,DC=com" />
<add key="f21a460b-fd05-4790-ae74-9fb4562d6d0b" value="OU=Workstations,OU=Computers,OU=Dunder Mifflin,DC=dundermifflin,DC=com" />
</ComputerOUs>
<RemoveUsersFromLocalAdmins />
<ExcludedDomainGroups>
<add key="c23fa115-91c4-407c-926b-7946430f93df" value="DG-GlobalServerAdmins" />
<add key="38184183-4d32-4554-a343-bb1c333faef3" value="DG-GlobalWorkstationAdmins" />
</ExcludedDomainGroups>
<appSettings>
<add key="AdminGroupOU" value="OU=Admin Groups,OU=Delegation Groups,OU=Groups,OU=Dunder Mifflin,DC=dundermifflin,DC=com" />
<add key="Prefix" value="DG-" />
<add key="Suffix" value="_LocalAdmins" />
<add key="AddComputerToADGroup" value="" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

 

i) Schedule AdminGroups.ConsoleApp.exe to run one every day. Remember to set the running account to an account with rights

 

Demo Execution

 

1) Below is screenshots of my three demo computers’ Local Administrators groups pre-execution.

 

Windows 7 original Local Administrators Group

Windows 10 original Local Administrators Group

Windows 2016 original Local Administrators Group


2) Below are screenshots of AdminGroup output and my three demo computers’ Local Administrators groups after first execution

 

AdminGroups output after first execution

Windows 7 Local Administrators Group after first execution

Windows 10 Local Administrators Group after first execution

Windows 2016 Local Administrators Group after first execution

 

3) Below is screenshots of AdminGroup output and my three demo computers’ Local Administrators groups after second execution.

 

AdminGroups output after second execution

Windows 7 Local Administrators Group after second execution

Windows 10 Local Administrators Group after second execution

Windows 2016 Local Administrators Group after second execution

 

Where did members go? They are now safely within the AD Local Admins groups.

 

Windows 7 AD Local Admins Group

Windows 10 AD Local Admins Group

Windows 2016 AD Local Admins Group

 

Code

 

Here is the section in code that manages the AD Local Admin Groups.

public static bool CreateAdminGroup(string DomainName, Models.Computer Computer, string AdminGroupOU, string AdminGroupName, List < string > ExcludedDomainGroups, out string Message) {
	Message = "";
	string message = "";
	try {
		//If this fails, no point in continueing
		if (ActiveDirectory.CreateActiveDirectoryGroup(AdminGroupOU, AdminGroupName, out message)) {
			//Add command output to return message
			Message = Message + System.Environment.NewLine + message;

			//If this fails, no point in continueing
			if (ActiveDirectory.RemotelyAddDomainGroupToLocalGroup(Computer.ComputerName, DomainName, AdminGroupName, "administrators", out message)) {
				//Add command output to return message
				Message = Message + System.Environment.NewLine + message;

				List < Models.GroupMember > groupMembers = new List < Models.GroupMember > ();

				//If this fails, no point in continueing
				if (ActiveDirectory.RemotelyGetLocalGroupMembers(Computer.ComputerName, "Administrators", true, false, ref groupMembers, out message)) {
					//Add command output to return message
					Message = Message + System.Environment.NewLine + message;

					foreach(Models.GroupMember groupMember in groupMembers) {
						//Handle excluded domain groups
						if ((!AdminGroupName.EndsWith(groupMember.GroupMemberName)) && (groupMember.GroupMemberName != "Domain Admins") && (!ExcludedDomainGroups.Contains(groupMember.GroupMemberName))) {
							if (ActiveDirectory.AddMemberToActiveDirectoryGroup(AdminGroupOU, AdminGroupName, groupMember.GroupMemberName, out message)) {
								//Add command output to return message
								Message = Message + System.Environment.NewLine + message;

								if (message.EndsWith("Group already exists")) {
									ActiveDirectory.RemotelyRemoveDomainGroupFromLocalGroup(Computer.ComputerName, DomainName, groupMember.GroupMemberName, "administrators", out message);

									//Add command output to return message
									Message = Message + System.Environment.NewLine + message;
								}
							} else {
								//Add command output to return message
								Message = Message + System.Environment.NewLine + message;
							}
						}
					}
				} else {
					//Add command output to return message
					Message = Message + System.Environment.NewLine + message;
				}
			} else {
				//Add command output to return message
				Message = Message + System.Environment.NewLine + message;
			}
		} else {
			//Add command output to return message
			Message = Message + System.Environment.NewLine + message;
		}

		return true;
	} catch (Exception ex) {
		Message = Message + System.Environment.NewLine + ex.Message;
		return false;
	}
}

 

Conclusion

 

Using this process, or one similar will give better visibility on existing users with Local Administrators permissions and the ability to better manage them.

 

 

How to extract hashes from IFM backup

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed.
Methods exist to extract hashes directly for a live domain however this article describes a process to extract user data, including hashes from an IFM backup.

1) Overview

Overpermission and weak/reused passwords are probably the most common security issues found in Active Directory. To address the password issues, it is important to do regular password audits, to address over permissions, see my article about Active Directory delegation.

 

2) Password Hashes

Passwords are stored in Active Directory (NTDS.dit encrypted with a boot key) as an unsalted MD4 hash and as such, to check for password reuse it is a simple case of checking for duplicate hashes in the extracted hashes list.

 

Finding weak passwords are a little trickier. You need to lookup hashes against a rainbow table to ensure you do not have any weak/compromised hashes within your environment.

 

Both of these are out-of-scope for this article, this article focuses on extracting password hashes.

 

3) Extracting Password Hashes

a) On a Domain Controller

 

Start an elevated command prompt and run:

 

ntdsutil
activate instance ntds
ifm
create sysvol full C:\Temp\Backups\IFM\

 

Command Output

IFM Files

 

b) On Administrative Computer

 

Copy the IFM folder and run the following PowerShell script elevated (just copy and paste):

 

//Download DSInternals from PowerShell Gallery https://www.powershellgallery.com/packages/DSInternals
Save-Module -Name DSInternals -path 'C:\temp\DSInternals'


//Install DSInternals
Install-Module -Name DSInternals


//Import DSInternals Module
Import-Module DSInternals


//Get Boot Key from Registry section of the IFM. If Boot Key is blank, Get-ADDBAccount will still return usernames
$key = Get-BootKey -SystemHivePath 'C:\Temp\Backups\IFM\registry\SYSTEM'


//Store objects data
$hashes = Get-ADDBAccount -All -DBPath 'C:\Temp\Backups\IFM\Active Directory\ntds.dit' -BootKey $key


//Convert object data to the desired format
$hashes | Format-Custom -View Ophcrack | Out-File C:\Temp\Backups\Hashes.txt

 

Hashes.txt File

 

 

Weak Passwords Found (Getting password from hashes out-of-scope for this article)

 

 

Securing Active Directory Administrators Groups

A hard and fast method for reducing Active Directory Administrators members.

Introduction

Anyone that has gone through any security hardening process can confirm that simply saying something was done incorrectly does not mean that you can just apply suggested remediation steps, especially in a mature environment.

 

Take recommendation Appendix E, F and G from the AD DS Operations Best Practices for Securing Active Directory for example, even though I agree with all of the points, just removing user accounts from the Administrators groups (Enterprise Admins, Domain Admins or Administrators) without addressing the application requirement could have a significant impact on
daily operations.

 

Based on my experience, the biggest reason why user and service accounts were added to Domain Admins and the like was that default delegation model in Active Directory lacks an appropriate group that just gives server/workstation administrative rights.

 

This article describes the process of creating these delegation groups so that members of Domain Admins etc. can be removed without any impact, drastically increasing Active Directory overall security. It must be stressed that this is an intermediate
process, the lesser of two evils if you will and that these other issues will be addressed in future articles.

 

Creating Global Administrators Delegation

1) WMI Filters

Create WMI filter that will identify the three device types. In the article two of these, All Servers except Domain Controllers and All Workstations will be used. This allows
delegation policy to apply to the correct device type dynamically.

 

a) Create an All Workstations WMI filter according to company naming convention

Select * from WIN32_OperatingSystem where ProductType=1

 

 

b) Create an All Domain Controllers WMI filter according to company naming convention

Select * from WIN32_OperatingSystem where ProductType=2

 

 

c) Create an All Servers except Domain Controllers WMI filter according to company naming convention

Select * from WIN32_OperatingSystem where ProductType=3

 

 

2) Groups

Create a group for each device type and a group that will have rights to all device types. These will contain the administrators for each device type.

 

a) Create Global Server Administrators group, Global Workstations Administrators group and Global Administrators group according to company naming convention.

 

 

b) Add Global Administrators group as a member of both Global Server Administrators group and Global Workstations Administrators group.

 

 

3) Group Policies

Create a group policy for each device type. It should filter based on the device types and will contain the delegation settings.

 

3.1) Global Server Administrators Group Policy

 

a) Create new GPO and name it according to company naming convention. It will contain the configuration of the Global Server Administrators group.

 

 

b) Ensure group policy is linked from domain root and that it is enforced. Link the All Servers except Domain Controllers WMI filter to group policy.

 

 

c) Add Administrators group to Restricted Groups and add Global Server Administrators group as a member. This is mainly done for legacy devices.

 

 

d) Add Administrators (built-in) group to Local Users and Groups preference update item and add Global Server Administrators group as a member.

 

3.2) Global Workstations Administrators Group Policy

 

a) Create new GPO and name it according to company naming convention. It will contain the configuration of the Global Workstation Administrators group.

 

 

b) Ensure group policy is linked from domain root and that it is enforced. Link the All Workstations WMI filter to group policy.

 

 

c) Add Administrators group to Restricted Groups and add Global Workstation Administrators group as a member. This is mainly done for legacy devices.

 

 

d) Add Administrators (built-in) group to Local Users and Groups preference update item and add Global Workstation Administrators group as a member.

 

4) Remove User/Service Accounts

At this point, everything is ready to start removing accounts from Administrators groups by following the following logic:

 

Account Requirement Action
Account requires AD rights Remove from Administrators groups (Enterprise Admins, Domain Admins or Administrators) and temporarily into Account Operators group until correct rights can be determined
Account requires Administrators rights to all devices Remove from Administrators groups (Enterprise Admins, Domain Admins or Administrators) and add to Global Administrators group
Account requires Administrators rights to servers Remove from Administrators groups (Enterprise Admins, Domain Admins or Administrators) and add to Global Server Administrators group
Account requires Administrators rights to workstations Remove from Administrators groups (Enterprise Admins, Domain Admins or Administrators) and add to Global Workstation Administrators group

 

Please note: It is best to add these user/service accounts to role groups as explained in this article:

https://www.experts-exchange.com/articles/29366/Delegation-the-proper-way.html

 

Conclusion

Adding user accounts to Administrators groups (Enterprise Admins, Domain Admins or Administrators) puts the environment at a significant risk because these user accounts can dump all the Active Directory hashes, bypassing all security and auditing mechanisms.
The above process can be used to drastically reduce the number of Admin members.

 

The hash extraction process is explained d in this article:

 https://www.experts-exchange.com/articles/29569/How-to-extract-hashes-from-IFM-backup.html

 

 

 

 

How to connect Arduino Uno WiFi to ThingSpeak

I took on this little project as a proof of concept for IoT devices. My main goals were to find the easiest, cheapest way to stream data to the cloud. This article describes how to stream telemetry data to ThingSpeak via REST API. This can also be done with Azure IoT hub with a local gateway.

1) What you need

DHT22 – Temperature/Humidity Sensor

MH-RD – Snow/Raindrop Detection Sensor

YL-69 – Soil Moisture Sensor

Arduino UNO WiFi connected to WiFI with internet access

Resistor 10k Ohm

Battery Pack

ThingSpeak Account with a channel configured

Arduino IDE

Any waterproof enclosure big enough to fit components

 

2) Fritzing Diagram

 

 

3) Sketch

a) After connecting all the sensors and cables as per the diagram above, open the Arduino IDE and copy and paste this into a new sketch.

 

#include <Wire.h>
#include <DHT.h>
#include <UnoWiFiDevEd.h>

#define CONNECTOR     "rest"
#define SERVER_ADDR   "api.thingspeak.com"
#define APIKEY_THINGSPEAK  "****************" //Insert your API Key

void setup() {
  Ciao.begin();
}

void loop() {
  DHT dht;
  dht.setup(2);

  String uri = "/update?api_key=";
  uri += APIKEY_THINGSPEAK;
  uri += "&field1=";
  uri += String(dht.getHumidity());
  uri += "&field2=";
  uri += String(dht.getTemperature());
  uri += "&field3=";
  uri += String(analogRead(A0));
  uri += "&field4=";
  uri += String(analogRead(A1));

  Ciao.println("Sending data on ThingSpeak Channel");
  CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, uri);

  if (!data.isEmpty()){
    Ciao.println( "State: " + String (data.get(1)) );
    Ciao.println( "Response: " + String (data.get(2)) );
  }
  else{
    Ciao.println("Write Error");
  }
  delay(900000);
}

b) Change the ThingSpeak API to you channel API

c) Plug in Arduino Uno and hit CTRL+U to upload sketch to device

 

4) End Result

As data is streamed to ThingSpeak the online dashboard will populate these values to the graphs, here’s mine http://thingspeak.com/channels/265283

Screenshot of ThingSpeak dashboard

Enclosure and soil moisture sensor

 

 

Closeup of enclosure

 

 

Closeup of soil moisture sensor

 

 

 

How to restore Active Directory Group Policy with only SYSVOL data

Always backup Domain, SYSVOL etc.using processes according to Microsoft Best Practices. This is meant as a disaster recovery process for small environments that did not implement backup processes and did not run a secondary domain controller that need to recover Group Policies from files

1) Create new, blank Group Policy

Using GPMC.msc create a new, blank GPO with the same name as the original.

 

 

2) Overwrite Group Policy Data

a) Record the Unique ID that was assigned to GPO created in Step 1

 

 

b) Copy Machine, User and GPT data from original GPO

 

 

c) Paste data (overwrite) into the folder assigned to GPO created in Step 1. The folder is named the same as the Unique ID recorded in Step 2a

 

 

3) Fixing Group Policy Settings Preview

Note that after completing Step 1 and Step 2, even though the GPO settings are available within Edit, the Settings Preview shows No settings defined

 

 

a) Edit GPO, browse to any unconfigured setting and open it. Tick and untick Define this policy setting and click OK

 

 

b) If your GPO contains any Preferences browse to any one of them and simply open it and click OK

 

 

Settings Preview should show settings

 

4) Fixing Group Policy Permission

Unfortunately following this process does not restore the original permissions, this has to be added back manually.

 

 

 

How to deploy a WordPress Site in Azure

This article shows the steps required to install WordPress on Azure.

Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan.
WordPress is no exception and requires an App Service Plan and Database to install

1) Create App Service Plan

From Azure Portal,

Click New

Search for App Service Plan

Click App Service Plan in Results

Click Create

 

 

Provide the required information such as Subscription, Resource Group etc.

 

2) Create MySQL Database

From Azure Portal,

Click New

Search for MySQL

Click MySQL Database in Results

Click Create

 

 

Provide the required information such as Subscription, Resource Group etc.

 

 

Review EULA and opt-in to provider offers if you like to

 

3) Create WordPress Site

From Azure Portal,

Click New

Search for WordPress

Click WordPress in Results

Click Create

 

 

Provide the required information such as Subscription, Resource Group etc.

Select the App Service Plan and Database created in step 1 and 2

 

 

4) Configure WordPress Site

Browse to WordPress site and configure as you would any new WordPress installation