homepage
Menu
Open menu
  • Training
    Go one level top Back

    Training

    • Courses

      Build cyber prowess with training from renowned experts

    • Hands-On Simulations

      Hands-on learning exercises keep you at the top of your cyber game

    • Certifications

      Demonstrate cybersecurity expertise with GIAC certifications

    • Ways to Train

      Multiple training options to best fit your schedule and preferred learning style

    • Training Events & Summits

      Expert-led training at locations around the world

    • Free Training Events

      Upcoming workshops, webinars and local events

    • Security Awareness

      Harden enterprise security with end-user and role-based training

    Featured: Solutions for Emerging Risks

    Discover tailored resources that translate emerging threats into actionable strategies

    Risk-Based Solutions

    Can't find what you are looking for?

    Let us help.
    Contact us
  • Learning Paths
    Go one level top Back

    Learning Paths

    • By Focus Area

      Chart your path to job-specific training courses

    • By NICE Framework

      Navigate cybersecurity training through NICE framework roles

    • DoDD 8140 Work Roles

      US DoD 8140 Directive Frameworks

    • By European Skills Framework

      Align your enterprise cyber skills with ECSF profiles

    • By Skills Roadmap

      Find the right training path based on critical skills

    • New to Cyber

      Give your cybersecurity career the right foundation for success

    • Leadership

      Training designed to help security leaders reduce organizational risk

    • Degree and Certificate Programs

      Gain the skills, certifications, and confidence to launch or advance your cybersecurity career.

    Featured

    New to Cyber resources

    Start your career
  • Community Resources
    Go one level top Back

    Community Resources

    Watch & Listen

    • Webinars
    • Live Streams
    • Podcasts

    Read

    • Blog
    • Newsletters
    • White Papers
    • Internet Storm Center

    Download

    • Open Source Tools
    • Posters & Cheat Sheets
    • Policy Templates
    • Summit Presentations
    • SANS Community Benefits

      Connect, learn, and share with other cybersecurity professionals

    • CISO Network

      Engage, challenge, and network with fellow CISOs in this exclusive community of security leaders

  • For Organizations
    Go one level top Back

    For Organizations

    Team Development

    • Why Partner with SANS
    • Group Purchasing
    • Skills & Talent Assessments
    • Private & Custom Training

    Leadership Development

    • Leadership Courses & Accreditation
    • Executive Cybersecurity Exercises
    • CISO Network

    Security Awareness

    • End-User Training
    • Phishing Simulation
    • Specialized Role-Based Training
    • Risk Assessments
    • Public Sector Partnerships

      Explore industry-specific programming and customized training solutions

    • Sponsorship Opportunities

      Sponsor a SANS event or research paper

    Interested in developing a training plan to fit your organization’s needs?

    We're here to help.
    Contact us
  • Talk with an expert
  • Log In
  • Join - it's free
  • Account
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. The PowerShell Tools I Use for Audit and Compliance Measurement
370x370_Clay-Risenhoover.jpg
Clay Risenhoover

The PowerShell Tools I Use for Audit and Compliance Measurement

This is Part 1 of a 3-part Series on Using PowerShell for Continuous Audit & Compliance Automation in Enterprise & Cloud

January 12, 2021

This is the first of a three-part series on using PowerShell for audit and compliance measurements. These blog posts supplement the material presented in the free webcast series "PowerShell for Audit, Compliance, and Security Automation and Visualization".

  • Read Part 2 of the Blog here

  • Read Part 3 of the Blog here

When I started performing IT audits in the early 2000s, it was a much simpler time! Physical servers were the norm. Administrators would manually configure each server and rack it up in the on-premise data center. If I asked "where are your Exchange servers?" they would take me to the data center and point out the physical machines.Back then, I could take the time to manually review the settings on each server, or I could take a week to perform a software audit without interfering with the development schedule. Then came virtualization, the cloud, agile, lean, Dev-Ops, site reliability engineering.

Today, I use scripting and automation wherever I can, just so I can keep up with the developers and administrators (or site reliability engineers). Whenever I can, I use PowerShell for my measurement scripts. It's more cross-platform than ever before, and it is designed for handling structured data formats like CSV, XML and JSON. PowerShell Core is the cross-platform version of the language. It's currently in version 7.1 and available for Windows, MacOS and many Linuxes. It's based on the .NET Core framework (which is different, and slightly less mature than the Windows .NET framework). In this series, I'll explore some of the PowerShell tools which have made me much more efficient in my audit and compliance work. The first of those tools is Pester.

The Pester Module

Pester describes itself as "the ubiquitous test and mock framework for PowerShell." Like the unit-testing frameworks your developers use, this module allows you to write suites of tests to run against a system.

Consider a simple example: The enterprise has decided to require certain local account settings on all Windows servers and workstations:

  • Blank passwords will not be allowed. The HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\LimitBlankPasswordUse registry key should be set to a value of 1.
  • The older LMHash format will not be used for local password hashes. The HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\NoLMHash key should be set to a value of 1.
  • Anonymous enumeration of accounts and shared will be disabled. The HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa:RestrictAnonymous key should be set to a value of 1.

I can write a set of Pester tests to validate these settings on a system. First, I will create a PowerShell script named "RegSettings.tests.ps1." The Pester test script will contain "Description" and "Context" blocks, which will contain groups of tests. The tests are implemented inside of "It" blocks. The script to perform tests for these three policy requirements might look like this

#Describe blocks hold groupings of context blocks. I often use the Describe
#block to hold all the tests for a particular policy
Describe "Local Account Policies" {
  #Context blocks are used to group related tests. Since all of our tests
  #are for registry settings related to the user policy, we'll use
  #a single Context block
  Context "Registry Settings" {
    #It blocks contain the individual tests. If you have a paragraph number from
    #a policy, you can include it in the test name
    It "Req 1 - Blank passwords are not allowed" {
      #Get the relevant setting
      $setting = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa").LimitBlankPasswordUse
      #Policy calls for a value of 1
      $setting | Should -Be 1
    }

    It "Req 2 - Disable LMHash" {
      $setting = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa").NoLMHash
      $setting | Should -Be 1
    }

    It "Req 3 - Restrict anonymous is enabled" {
      $setting = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa").RestrictAnonymous
      $setting | Should -Be 1
    }
  }
}

I can now use the Invoke-Pester PowerShell command to run the tests:

Invoke-Pester -Path .\RegSettings.tests.ps1
Blog1-0.png

Pester can provide a custom PowerShell object with contains information about the tests run. This is as simple as using the "Passthru" parameter on the command line when I run the tests. I can capture that output and import it into a dashboard or calculate the percentage of tests which failed.

Invoke-Pester -Path .\RegSettings.tests.ps1 -PassThru

Blog1-1.png

I can save the passed-through object from a Pester run into a variable to make it easier to process the results. If I wanted to see the percentage of tests which failed, I might do something like this:

#Save the results into a variable
$pesterResults = Invoke-Pester -Path .\RegSettings.tests.ps1 -PassThru
#Calculate the percentage of tests which failed
$failedPct = $pesterResults.FailedCount / $pesterResults.TotalCount * 100.0
#Output the results
$failedPct

Blog1-2.png

In my consulting practice, we run tests like this daily against all the systems in an environment and ingest the results into a time-series database like Graphite, so we can visualize the results over time. Notice that in the previous example I calculated the percentage of tests which failed. We always use larger numbers to represent higher risk, i.e. a fully-passed test would result in zero percent, and a fully-failed test would result in 100 percent. You could use compliance, rather than risk, as your yardstick and have higher numbers be better. The important thing is to present the data consistently across your visualizations. Color-coding the results and using threshold lines in your dashboard can help to make "good" and "bad" results more obvious to the consumers.

Pester can be run inside your continuous integration (CI) pipelines by passing it a configuration object which instructs Pester to save the results in NUint format for further analysis. The PesterConfiguration object sets the options for which test scripts to run and how to save the results. Using this configuration, Pester will save the results of the tests into a file called testResults.xml. That file can be ingested by most CI tools to fail a build if the tests fail. This couple of lines of PowerShell code would create the Pester configuration and then run the tests.

<p>$config = [PesterConfiguration]@{ 
  Run = @{ Exit = $false; Passthru = $true; Path = '.\RegSettings.tests.ps1'}; 
  TestResult = @{Enabled = $true}
}
Invoke-Pester -Configuration $config</p>

I can also use the XML results file to quickly generate an HTML report of the results of the test. For this, I use a tool called "ExtentReports" which converts the XML test results into two interactive HTML files.

Blog1-3.png

Loading the resulting index.html into my browser gives me a nice overview of the results. The failed test on the right side of the page is clickable and gives me more information about the test which failed.

Blog1-4.png

Blog1-5.png

Pester in Linux

Since PowerShell Core is cross-platform, I can use Pester to test compliance on my Linux systems as well. The syntax is exactly the same and native Linux tools are available in the tests. Imagine that your enterprise has mandated that its Linux servers will be configured this way:

  • The Linux distribution will be Ubuntu 20.04.1 LTS
  • The kernel version will be "5.4.0-52-generic"
  • The python 3 version will be "3.8.5"

I could write Pester tests to verify all these settings. Notice that the "BeLike" keyword allows for wildcard matches on values. For a list of all the tests available in Pester, check out their documentation.

Describe "Local Linux Tests" {
   Context "Linux Configuraton" {
     #The the distribution installed on the server
     It "Req 1 - distribution is Ubuntu 20.04.1 LTS" {
       #Get the relevant setting
       $distro = (lsb_release -d)
       $distro | Should -BeLike '*Ubuntu 20.04.1 LTS'
     }

     It "Req 2 - Kernel version is 5.4.0-52" {
       $kernel = (uname -r)
       $kernel | Should -Be '5.4.0-52-generic'
     }

     It "Req 3 - Python is correct version" {
       $pythonVersion = (python3 -V)
       $pythonVersion | Should -BeLike '*3.8.5'
     }
   }
 }

Blog1-6.png

Pester with Other Tools

It's not just my server and workstation operating systems that can be tested with Pester! If an API or PowerShell module exists for a product, I can wrap it with Pester tests to measure compliance of the system. In this final example, imagine that the enterprise is running VMWare ESXi version 6.5 in their datacenter. Side note for auditors and compliance professionals ESXi 6.5 is still supported, but if you are still using 6.5 instead of 6.7 or 7.0, it MAY indicate that your organization is using older hardware and can't use the newer versions. Management has mandated in policy:

  • The approved hypervisor software build numbers are 17167537 and 17097218
  • Each ESXi host will have MegaRAID software version number 4564106 (your research indicates that the full version information will be "VMW_bootbank_scsi-megaraid-sas_6.603.55.00-2vmw.650.0.0.4564106" )
  • Each host will be configured to use 10.50.7.2 as a DNS server

Armed with these requirements, I can write a series of tests to run against the server. These tests will use VMWare's PowerCLI PowerShell module, which is capable of managing and querying all the VMWare infrastructure devices on your network. I like PowerCLI so much, I'll cover it in its own blog post. For now, just know that I need to authenticate to the VMWare infrastructure - normally by connecting to a VCenter server - and then I can run commands against the servers. In this example, I also demonstrate the use of "BeforeAll" and "AfterAll" script blocks, which allow setup and teardown of the testing environment. For more information on "BeforeAll" and other commands in the Pester module, take a look at the online documentation.

Describe "ESXi Tests" {
   BeforeAll {
       #Retrieve the server credentails from an encrypted file
       $keyFile = ".\keyFile"
       $credFile = ".\esxiCreds"

       #Grab the key/token, decrypt the password and store it in a credentials object
       $key = Get-Content $keyFile
       $username = 'root'
       $securePwd = Get-Content $credFile
       $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username, ($securePwd | 
         ConvertTo-SecureString -Key $key)

       #Create a connection to the server being tested
       Connect-VIServer -server esxi1 -Credential $cred
   }

   AfterAll{
       #Close any remaining open connections
       Disconnect-VIServer * -Confirm:$false
   } 

   Context "Patching" {
       It "Version matches enterprise standard" {
           #List of approved build numbers for the enterprise
           $approvedBuilds = '17167537','17097218'
           $build = (Get-VMHost).Build
           $build -in $approvedBuilds | Should -be $true
       }


       It "MegaRAID software is correct version" {
           ((Get-ESXCli -Server esxi1).software.vib.list()).ID -contains `
             'VMW_bootbank_scsi-megaraid-sas_6.603.55.00-2vmw.650.0.0.4564106' | 
             Should -Be $true
       }
   }
   Context "Server Settings" {
       It "DNS servers are correct" {
           $dnsservers = (Get-VMHost).Extensiondata.Config.Network.DNSConfig | Select-Object -ExpandProperty address
           $dnsservers -contains '10.50.7.2' | Should -Be $true
       }
   }
}

Blog1-7.png

I recommend that all professionals tasked with verifying the security of their enterprise learn to use PowerShell and tools like Pester to automate and simplify their work. Please come back next week to learn about more of the PowerShell tools and techniques that will help you to keep up with your fast-moving enterprise.

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Cote D'ivoire
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Eswatini
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
North Macedonia
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania, United Republic Of
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City State
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Recommended Training

  • SEC401J: Security Essentials - Network, Endpoint, and Cloud™ (Japanese)
  • SEC549: Cloud Security Architecture
  • SEC480: AWS Secure Builder™

Tags:
  • Cloud Security
  • Cybersecurity Leadership

Related Content

Blog
SANS_Cloud_Security_340x340.png
Cloud Security
December 11, 2024
SANS Cloud Security Curriculum
The SANS Cloud Security Curriculum is growing fast – like the Cloud itself.
370x370_Frank-Kim.jpg
Frank Kim
read more
Blog
340x340.png
Cloud Security
September 30, 2024
A Visual Summary of SANS CloudSecNext Summit 2024
Check out these graphic recordings created in real-time throughout the event for SANS CloudSecNext Summit 2024
No Headshot Available
Alison Kim
read more
Blog
SEC540_Updated_340x340.png
Cloud Security
December 29, 2023
What is the SANS Cloud Flight Simulator?
Get ready for takeoff into the NEW SEC540!
Eric_Johnson_370x370.png
Eric Johnson
read more
  • Company
  • Mission
  • Instructors
  • About
  • FAQ
  • Press
  • Contact Us
  • Careers
  • Policies
  • Training Programs
  • Work Study
  • Academies & Scholarships
  • Public Sector Partnerships
  • Law Enforcement
  • SkillsFuture Singapore
  • Degree Programs
  • Get Involved
  • Join the Community
  • Become an Instructor
  • Become a Sponsor
  • Speak at a Summit
  • Join the CISO Network
  • Award Programs
  • Partner Portal
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Cote D'ivoire
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Eswatini
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
North Macedonia
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania, United Republic Of
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City State
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • Privacy Policy
  • Terms and Conditions
  • Do Not Sell/Share My Personal Information
  • Contact
  • Careers
© 2025 The Escal Institute of Advanced Technologies, Inc. d/b/a SANS Institute. Our Terms and Conditions detail our trademark and copyright rights. Any unauthorized use is expressly prohibited.
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn