Scripts
I mostly created this page to play around with some tools that are supposed to auto-format script code with pretty HTML colors. The powershell code is formated with the Powershell ISE extension, IsePack, Copy-ColoredAsHtml function. You'd think it would be plug-n-play but I ran into some issues as IsePack support seems to be abandoned.
I wrote a small php class to pull each script source code from my private GitLab server via HTTP/S. The main con to this method is the overhead of the web server having to request the code from multiple externally hosted pages before generating and returning this page. Additionally, the source code blocks will not be populated if this webserver cannot contact my GitLab server for whatever reason. The benefit of this method, however, is that the source code is always current with the GitLab repositories without having to manually sync via a method like git from this web server. I might introduce a caching-like functionality to the php code as a fallback.
Fix Hyper-V VM Permissions v1
This script came about because of an interesting facet of Hyper-V's NTFS file system access control restrictions to a virtual machine's files. Hyper V creates a unique Window's SID for each VM upon creation and then assigns that SID permissions to the necessary files (like the .vhd) on the host system. In Windows, all identities, such as user accounts, are assigned a unique 'security identifier' (SID) that will remain static for the life of that identity. A running virtual machine will be accessing its associated .vhd and config files from the context of its specific SID.
The problem with Hyper-V's permission scheme is if the file system permissions get lost/reset, (like from copying the files to another storage drive/system as a crude backup) the restored virtual machine will no longer be able to start. It is necessary to set the files as read/write for everyone or lookup the correct SID and apply it via the command line (the SID will not be found in the GUI). This script uses the later method and is to be executed once the virtual machine is imported into Hyper-V's registry.
Write-Host "`nFix Hyper-V VM Permissions v1 `n`nThis interactive script allows you replace the VM specific NTFS permissions on each VM's resourse files.`n`n" -ForegroundColor Yellow
function Import_Dependencies(){
try{
Import-Module Hyper-V;
} catch {
Write-Host "Powershell could not import the required Hyper-V module. Please ensure Hyper-V is installed on this machine.";
Read-Host "Press any key to exit..."
Exit;
}
}
function Confirm_Admin_Privilege(){
#Test if the script is being run as Administrator and exit if false.
If (-Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')){
Write-Host "You do not have rights to run this script! Please re-run this script as an Administrator!";
Read-Host "Press any key to exit..."
Exit;
}
}
function Expand_VHD_Parent_Paths(){
param(
[Parameter(Mandatory=$true)]
[String]$path
)
$parentPath = (Get-VHD -Path $path -ErrorAction Stop).ParentPath;
$pathTree = New-Object System.Collections.Generic.List[System.String];
$pathTree.Add($path);
while(-not [String]::IsNullOrEmpty($parentPath)){
$pathTree.Add($parentPath);
$parentPath = (Get-VHD -Path $parentPath).ParentPath;
}
return $pathTree.ToArray();
}
function Build_VM_List(){
$vms = New-Object System.Collections.Generic.List[System.Object];
foreach($vm in $(Get-VM)) {
$harddrives = New-Object System.Collections.Generic.List[System.Array];
foreach($drivePath in $($vm | Select -ExpandProperty HardDrives | select -property Path)){
$harddrives.Add((Expand_VHD_Parent_Paths -Path $drivePath.path));
}
$harddrives = $harddrives.ToArray();
$vms.Add( [PSCustomObject]@{
'Name' = $vm.VMName;
'ID' = $vm.VMId;
'HDDs' = $harddrives;
}
)
}
return $vms.ToArray();
}
function Add_Permissions(){
param(
[Parameter(Mandatory=$true)]
[Array]$virtualMachineList
)
Write-Host "`nBeginning to process registered virtual machines:`n"
foreach($vm in $virtualMachineList){
Write-Host $vm.Name;
foreach($drive in $vm.HDDs){
foreach($path in $drive){
try{
$null = Invoke-Expression -Command:"icacls '$path' /grant 'NT VIRTUAL MACHINE\$($vm.ID):(F)'";
$account = New-Object System.Security.Principal.NTAccount($vm.ID);
$acl = Get-Acl -Path $path;
$acl.SetOwner($account);
Set-Acl -Path $path -AclObject $acl;
}
catch{
Write-Host $Error[0].Exception.GetType().FullName $Error[0] -ForegroundColor Red;
}
}
}
}
return;
}
#Call functions to begin execution
Confirm_Admin_Privilege;
Import_Dependencies;
Add_Permissions -virtualMachineList $(Build_VM_List);
Exit;
Poll AD Users v6
Write-Host "`nPoll AD Users v6 `n`nThis script queries all user accounts in Active Directory and generates a CSV listing STIG pertinent attributes.`n`n"
function Test_If_Admin(){ <#Test if the script is being run as Administrator and exit if false. #>
If (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')){
return true;
}Else{
Write-Host "You do not have rights to run this script! Please re-run this script as an Administrator!"
Read-Host "Press Enter to exit..."
Exit;
}
}
function Poll_Users(){
#Create an array to store the custom objects that will be created below
$output = @()
#Get the full AD user list with all attributes (properties)
$users = Get-ADUser -filter * -Properties *
$userCount = $users.Count
$WACount=0
$SACount=0
$DACount=0
$EACount=0
$MTAAllowCount=0
$MTABlockCount=0
$smartcardCount=0
$passExpiredCount=0
$passNeverExpiresCount=0
$enabledCount=0
$lockedCount=0
$disableAccounts=$false
$response=''
#Iterate through each AD user to test the associated individual properties
foreach($user in $users)
{
$isWA = ''
$isSA = ''
$isDA = ''
$isEA = ''
$isMTA = ''
$isNotMTA = ''
$smartcardLogonRequired = ''
$passExpired = ''
$passNeverExpires = ''
$enabled = ''
$locked = ''
if(($user | where memberof -like '*Workstation_Admin*') -or ($user | where PrimaryGroup -like '*Workstation Admins*')){
$isWA = $true
$WACount++
}
if(($user | where memberof -like '*Server_Admin*') -or ($user | where PrimaryGroup -like '*Server Admins*')){
$isSA = $true
$SACount++
}
if(($user | where memberof -like '*Domain Admins*') -or ($user | where PrimaryGroup -like '*Domain Admins*')){
$isDA = $true
$DACount++
}
if(($user | where memberof -like '*Enterprise Admins*') -or ($user | where PrimaryGroup -like '*Enterprise Admins*')){
$isEA = $true
$EACount++
}
if(($user | where memberof -like '*MTA-DTA_Allow*') -or ($user | where PrimaryGroup -like '*MTA-DTA_Allow*')){
$isMTA = $true
$MTAAllowCount++
}
if(($user | where memberof -like '*MTA-DTA_Block*') -or ($user | where PrimaryGroup -like '*MTA-DTA_Block*')){
$isNotMTA = $true
$MTABlockCount++
}
if(($user.SmartCardLogonRequired)){
$smartcardLogonRequired = $true
$smartcardCount++
}
if(($user.PasswordExpired)){
$passExpired = $true
$passExpiredCount++
}
if(($user.PasswordNeverExpires)){
$passNeverExpires = $true
$passNeverExpiresCount++
}
if(($user.Enabled)){
$enabled = $true
$enabledCount++
}
if(($user.LockedOut)){
$locked = $true
$lockedCount++
}
#Creates a PSCustomObject of the resulting user attributes and adds it to $output array list
$output += [PSCustomObject]@{
'Account Name'=$user.SamAccountName
'UserPrincipalName'=$user.UserPrincipalName
'Enabled'=$enabled
'LockedOut'=$locked
'MTA-DTA_Allow'=$isMTA
'MTA-DTA_Block'=$isNotMTA
'Workstation Admin'=$isWA
'Server Admin'=$isSA
'Domain Admin'=$isDA
'Enterprise Admin'=$isEA
'SmartCardLogonRequired'=$smartcardLogonRequired
'PasswordExpired'=$passExpired
'PasswordNeverExpires'=$passNeverExpires
'PasswordLastSet'=$user.PasswordLastSet
'LastLogonDate*DC1 Only*'=$user.LastLogonDate
}
}
#Add the total counts
$output += [PSCustomObject]@{
'Account Name'=$userCount
'UserPrincipalName'=''
'Enabled'=$enabledCount
'LockedOut'=$lockedCount
'MTA-DTA_Allow'=$MTAAllowCount
'MTA-DTA_Block'=$MTABlockCount
'Workstation Admin'=$WACount
'Server Admin'=$SACount
'Domain Admin'=$DACount
'Enterprise Admin'=$EACount
'SmartCardLogonRequired'=$smartcardCount
'PasswordExpired'=$passExpiredCount
'PasswordNeverExpires'=$passNeverExpiresCount
'PasswordLastSet'=''
'LastLogonDate*DC1 Only*'=''
}
#Uncomment the line below to see the output inside the console
#$($output) | Format-Table -AutoSize
#Save the output as a tab-delimited csv file for export to excel
$($output) | export-csv "$env:USERPROFILE\Documents\AD_USER_LIST_$(Get-Date -format 'MMddyyyy_HHmmss').csv"
Write-Host "The CSV has been generated at $env:USERPROFILE\Documents\AD_USER_LIST_$(Get-Date -format 'MMddyyyy_HHmmss').csv"
}
#Comment out the below line if Administrator permissions are not required to query AD user fields in your environment
Test_If_Admin;
Poll_Users;
Read-Host "Press Enter to exit..."
Exit;