Order Now
Programming - Scripting for Security

Programming - Scripting for Security

  • 31st Aug, 2021
  • 16:19 PM


PowerShell is one of the most exciting new products to come out of Microsoft in a long
time. It is both a new scripting language and a command-line shell. People who have seen
the demos have been extremely impressed by the power it brings to admins to automate
and customize their regular tasks. PowerShell will be used as the basis for all Windows
administrative scripting in the future, starting with Exchange 2007 and Vista. IT Pros have
been hungering for whatever PowerShell information they can get their hands on. 

Recently, PowerShell 7 was released with a set of new exciting features. PowerShell 7 is the
latest major update to PowerShell, a cross-platform (Windows, Linux, and macOS)
automation tool and configuration framework optimized for dealing with structured data
(e.g. JSON, CSV, XML, etc.), REST APIs, and object models. PowerShell includes a command-
line shell, object-oriented scripting language, and a set of tools for executing scripts/cmdlets
and managing modules.

Three years ago, PowerShell Core 6 was announced as a completely new edition of
PowerShell. Built on top of .NET Core, PowerShell Core introduced cross-platform support
across Windows, macOS, and Linux, SSH-based PowerShell Remoting, massively improved
support for REST and JSON, official Docker containers, and more. Additionally, it was the
first release of PowerShell made under an open-source license (MIT), encouraging long-time
PowerShell enthusiasts and complete newcomers alike to contribute directly to the source
code, tests, and documentation.

After three successful releases of PowerShell Core, PowerShell 7 released, the next chapter
of PowerShell’s ongoing development. With PowerShell 7, in addition to the usual slew of
new cmdlets/APIs and bug fixes, we’re introducing a number of new features, including:

? Pipeline parallelization with ForEach-Object -Parallel
? New operators:
? Ternary operator: a? b: c
? Pipeline chain operators: || and &&

? Null coalescing operators: ?? and ??=
? A simplified and dynamic error view and Get-Error cmdlet for easier investigation of
? A compatibility layer that enables users to import modules in an implicit Windows
PowerShell session
? Automatic new version notifications
? The ability to invoke to invoke DSC resources directly from PowerShell 7

The shift from PowerShell Core 6.x to 7.0 also marks our move from .NET Core 2.x to 3.1.
.NET Core 3.1 brings back a host of .NET Framework APIs (especially on Windows), enabling
significantly more backwards compatibility with existing Windows PowerShell modules. This
includes many modules on Windows that require GUI functionality like Out-
GridView and Show-Command, as well as many role management modules that ship as part
of Windows.

PowerShell 7 supports the following operating systems on x64, including:

? Windows 7, 8.1, and 10
? Windows Server 2008 R2, 2012, 2012 R2, 2016, and 2019
? macOS 10.13+
? Red Hat Enterprise Linux (RHEL) / CentOS 7+
? Fedora 29+
? Debian 9+
? Ubuntu 16.04+
? openSUSE 15+
? Alpine Linux 3.8+

Any module that is already supported by PowerShell Core 6.x is also supported in
PowerShell 7

On Windows, added a -UseWindowsPowerShell switch to Import-Module to ease the
transition to PowerShell 7 for those using still incompatible modules. This switch creates a
proxy module in PowerShell 7 that uses a local Windows PowerShell process to implicitly
run any cmdlets contained in that module.

For those modules still incompatible, we’re working with a number of teams to add native
PowerShell 7 support, including Microsoft Graph, Office 365, and more.

Azure Cloud Shell has already been updated to use PowerShell 7, and others like the .NET
Core SDK Docker container images and Azure Functions will be updated soon.

PowerShell and HVC

If you want to interact with your virtual machine running on Windows 10, you can use the
Hyper-V Manager and the console to interact with the operating system directly. However,
there are also two other options that allow you to manage and access the VMs using the
command line. PowerShell Direct lets you create a PowerShell remoting session to the
virtual machine using the VM Bus, so no networking is required. The same applies to Linux
virtual machines and the HVC tool, which allows you to create an SSH connection directly
into the VM. Both options also allow you to copy files to and from virtual machines. This is
extremely handy if you set up some automation, and you need to run some commands
within the virtual machine.

Security Log Analysis

A script for analysing security log on Windows was prepared.
#export the security events to mentioned csv file
get-wmiobject -query "Select * from Win32_NTLogEvent Where Logfile = 'Security'" | export-csv
securityevents.csv -NoTypeInformation
#variable declaration
$totalAuditCount = 0
$successAuditCount = 0
$failureAuditCount = 0
#array declaration to store the event id's
#import the csv file with its all the columns

Import-CSV $filepath -Header
enerated,TimeWritten,Type,User | Foreach-Object{
      #counter increment to get total events count
     #if type of event is Success
      If ($_.Type -eq "Audit Success") {
          $successAuditCount=$successAuditCount+1 #increment the success event counter
          $successEventCode+=$_.EventIdentifier #add event code to array
      ElseIf($_.Type -eq "Audit Failure") {
          $failureAuditCount=$failureAuditCount+1 #increment the failure event counter
          $failueEventCode+=$_.EventIdentifier #add event code to array
#get the most common success event from the array
$mostCommonSuccessEvent = $successEventCode | Group-Object | Sort-Object Count -
descending | Select-Object -First 1
#get the most common failure event from the array
$mostCommonFailureEvent = $failueEventCode | Group-Object | Sort-Object Count -descending
| Select-Object -First 1
#print the following required messages
Write-Host "Number of Audit Failures:" $failureAuditCount " Failures of " $totalAuditCount
Write-Host "Most common Event ID:" $mostCommonFailureEvent.Name
Write-Host "Number of Audit Successes:" $successAuditCount " Successes of " $totalAuditCount
Write-Host "Most common Event ID:" $mostCommonSuccessEvent.Name

First thing the script does is exporting the system security events to a csv file on the
filesystem. This is done through Windows Management Instrumentation object with a
corresponding query passed as a parameter to Get-WmiObject. Then the result of the query
execution is piped to the Export-CSV cmdlet.

The Get-WmiObject cmdlet gets instances of Windows Management Instrumentation (WMI)
classes or information about the available WMI classes. To specify a remote computer, use
the ComputerName parameter. If the List parameter is specified, the cmdlet gets
information about the WMI classes that are available in a specified namespace. If the Query
parameter is specified, the cmdlet runs a WMI query language (WQL) statement.

The Export-CSV cmdlet creates a CSV file of the objects that you submit. Each object is
represented as a line or row of the CSV. The row consists of a comma-separated list of the
values of object properties. You can use this cmdlet to create spreadsheets and share data
with programs that take CSV files as input.

After a block of code with variable declaration, the next action is to import the csv file file
generated before. That’s done by Import-CSV cmdlet with specified path to the csvfile and
the list of headers.

The Import-Csv cmdlet creates table-like custom objects from the items in CSV files. Each
column in the CSV file becomes a property of the custom object and the items in rows
become the property values. Import-Csv works on any CSV file, including files that are
generated by the Export-Csv cmdlet.

All records of the csv file are piped to the ForEach-Object to do operations on the csv file
records. The script analyses Type property of the current object ($_). Then the script records
how many Audit Success and Audit Failure events are out there along with the
corresponding event codes.

To calculate the most common success and failure events, the script uses the Group-Object
cmdlet the it sorts the groups and returns the most common ones and stores them in a
variable in memory stack.

The Group-Object cmdlet displays objects in groups based on the value of a specified
property. Group-Object returns a table with one row for each property value and a column
that displays the number of items with that value.

The Sort-Object cmdlet sorts objects in ascending or descending order based on the values
of properties of the object.

The Select-Object cmdlet selects specified properties of an object or set of objects. It can
also select unique objects, a specified number of objects, or objects in a specified position in
an array.

Finally, the stats of the collected events is displayed using the Write-Host cmdlet. The Write-
Host cmdlet customizes output. You can specify the color of text by using the
ForegroundColor parameter, and you can specify the background color by using the
BackgroundColor parameter. The Separator parameter lets you specify a string to use to
separate displayed objects. The particular result depends on the program that is hosting
Windows PowerShell.

Share this post

assignment helpassignment helperassignment expertsassignment writing services