-->

Sans Sec505 Degree Notes - Twenty-Four Hr Menstruum 1

Sans Sec505 Degree Notes - Twenty-Four Hr Menstruum 1

SEC505 - Securing Windows too PowerShell Automation videos

Security must live baked inwards from the beginning, too then continuously enforced too monitored afterwards!

26ZAGP7S2R86L8C

Set-MpPreference -DisableRealtimeMonitoring $true -force

Set-ExecutionPolicy -ExecutionPolicy Bypass -Force

- to take NTFS blocking tags ( downloaded files from the Internet amongst Chrome, IE or Edge, but non for Firefox):
dir *.ps1 | unblock-file

get-help set-*
get-help *loc*

get-help -full get-process
get-process
cls

get-help -showwindow get-service

get-help about*

get-alias
get-alias ps
new-alias nn notepad.exe
help about_alias

$Process = get-process -name lsass
$process.name
$process.id
$process.Company
$process.kill()   #but don't do it!!!

Object = Properties + Methods
Class = Type of Object (Blueprint)

- to demo properties, methods too bird type:
get-process | get-member

$x = get-item hklm:\
$x | get-member

- 'Drives' are to a greater extent than than only disk volumes:
get-psdrive

On your computer:
dir hkcu:\
dir variable:\
cd cert:\localmachine\ca

Environment Variables:
dir env:\

$env:PATH
$env:windir
$env:SYSTEMROOT

new-item env:\veryable -value "Flash Gordon"
set-item end:\veryable -value "Wonder Woman"
remove-item end:\VERYABLE


get-help get-*proc*
get-help *proc*

Your ain functions, aliases too variables inwards retention are temporary, they do non survice the closing of the PowerShell host process.

On your computer:
ise $Profile.CurrentUserAllHosts


$profile.allusersallhosts

$profile.alluserscurrenthost


$Profile scripts run automatically at launch!

get-help *service*

##################
Find cmdlets related to services
get-help *service*

Find cmdlets related to services inwards the graphical PowerShell ISE editor?
get-service

View the properties too methods of service objects:
get-service | get-member

What is 'gm' an alias for?
get-alias gm

Open your ain PS profile script inwards a novel PS ISE tab:
ise $profile.CurrentUserAllHosts

View a listing of the electrical flow "drives" available inwards PS:
get-psdrive

View the PATH surroundings variable:
$env:path

#####################
dir function:\
get-content function:\mkdir

Dot Sourcing:
. .\libraryscript.ps1


Module:
$env:PSModulePath -Split ";"

Get-Module -ListAvailable
Import-Module -Name AppLocker
Get-Command -Module Applocker

Check:
https://www.powershellgallery.com/
for PowerShell goodies!

PowerShell Remoting:
enable-psremoting -force

Enter-PSSession -Computername $env:Computername

WinRM service on TCP port 5985 too 5986 accessible!
Be a fellow member of the local Administrators group!


WSMan Protocol = spider web services for management
Open, DMTF protocol based on SOAP
WSMan implemented yesteryear the WinRM service on Windows!

Manually enable remoting on a customer OS:
Enable-PSRemoting -Force

Connect interactively similar Telnet:
Enter-PSSession -ComputerName Server47

Enter-PSSession -UserSSL -Computer box.sans.org

Exit-PSSession #when you lot are done!


Non-interactive commands or scripts (for scheduled tasks):
Invoke-Command -ScriptBlock {...} -Computer $Box

Invoke-Command -FilePath .\script.ps1 -Computer $Box

$Output = Invoke-Command -FilePath .\script.ps1


C:\SANS\Day1-PowerShell> $output = Invoke-Command -computername $env:COMPUTERNAME -ScriptBlock {ps}
C:\SANS\Day1-PowerShell> $output

- to execute a local script on a remote system, but encounter the output inwards the local shell:
Invoke-Command -computername Server7 -filepath .\somescript.ps1


###########  Fan-Out Remoting every bit Background job: ##############
$$Servers = @("Srvr47", "Srvr48","Srvr49")
Invoke-Command -FilePath .\script.ps1 -AsJob -Computer $Servers

Get-Job #query labor condition too instruct labor ID number

#The output volition live collated yesteryear figurer name:
$Output = Receive-Job -Keep -ID 6

C:\SANS\Day1-PowerShell> $output = Invoke-Command -computername $Servers -ScriptBlock {ps} -AsJob

C:\SANS\Day1-PowerShell> Invoke-Command -computername $Servers -ScriptBlock {ps} -AsJob

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                 
--     ----            -------------   -----         -----------     --------             -------                 
10     Job10           RemoteJob       Running       True            WIN2016SRV           ps                      

C:\SANS\Day1-PowerShell> Get-Job

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                 
--     ----            -------------   -----         -----------     --------             -------                 
8      Job8            RemoteJob       Completed     True            WIN2016SRV           ps                      
10     Job10           RemoteJob       Completed     True            WIN2016SRV           ps                      

$output = Receive-job -Id 22 -keep
$output


Remoting File Copy too Hyper-V Direct:

#Create a WSman Session to a remote host amongst PowerShell 5.0:
$Session = New-Session -ComputerName dc.testing.local

#Upload a file to the remote host (-ToSession):
copy -Path C:\LocalFolder\file.txt -Destination c:\RemoteFolder\file.txt -ToSession $Session

#Download a file from the remote host (-FromSession):
copy -Path C:\RemoteFolder\file.txt -Destination c:\LocalFolder\file.txt -FromSession $Session

#######################
1.4 Essential Command too Scripting Examples:
Setting upward our Training VM
PowerShell OverView too Tips
Modules, Functions too PowerShell Remoting
Essential Commands too Scripting Examples
Writing  your Own Functions too Scripts


Parameters, Arguments, Switches too Piping
get-member -inputobject $x -membertype holding -static
get-member -input $x -m holding -static
gm -i $x -m holding -s


A piped object becomes a parameter argument:
get-date "11/29/17" | gm -m holding -static

The -WhatIf switch for labor security...

> "dog" | .\Translate.ps1 -Language french

> get-help -Full Get-Process

- the  side yesteryear side ascendance volition delete anything within of the electrical flow folder you lot are in:
rm *.* -Recurse -Force

or
If you lot desire to utilisation the -WhatIf option:
rm *.* -Recurse -Force -WhatIf


"Hello World"

"Hello World" | out-default
"Hello World" | out-default | out-host


Format-List
- shows each holding on a split line
get-process | format-list *

Format-Table
- shows properties inwards columns, similar a spreadsheet
ps | format-table id, name, path -autosize


Display the properties that you lot desire to display:
ps | format-table name, id, path

- because the output higher upward gets truncated nosotros tin utilisation Format-List instead:
ps | format-list name, id, path


The OutPutters:
Out-Host
- displays text inwards shell

Out-File
- append
- encode

Out-GridView
- pops upward a GUI app
- PassThru

out-Printer
- Local or network-attached printer

Out-Null
-silently destroys information (and laughs)

Out-String
- converts objects to 'real' strings
- the entirely outputter amongst pipeable output, such every bit grep.exe


######################

>ps | Out-GridView

>ps | Out-OneNote

>ps | Out-String -Stream

>ps | Out-String -Stream | grep.exe

######################

Exporting, Importing too Converting Object Data
- properties locomote column headers, objects are rows:

get-service | export-csv -path services.csv
$data = import-csv -path services.csv
#What is within the $data array now? Text?

Export-CLIXML too Import-CLIXML

ConvertTo-JSON too ConvertFrom-JSON


>Invoke-WebRequest -Uri "http:/...." | ConvertFrom-Json
#Invoke-WebRequest is the powershell version of 'wget' or 'curl'

##########################

get-process | convertto-html -property Name,Path,ID -title "Process Report" -head "<h1>Process Report </h1>" -body "<h2> Report

Was Run:(get-date)</h2><hr>" | out-file -filepath \\server\share\report.html


PS C:\Users\LapDog> get-process | convertto-html -property Name,Path,ID -title "Process Report" -head "<h1>Process Report </h1>"

-body "<h2> Report Was Run:(get-date)</h2><hr>" | out-file -filepath c:\users\lapdog\Desktop\report.html

####################3
Please plough to the side yesteryear side practise on page 120!!!!

Remember: tab completion is your friend!


########################
Select-Object (Alias: Select)

Similar to "SELECT" inwards SQL queries:
get-process "powershell*" | select-object ProcessName, ID, Path | out-gridview


Extract first, terminal too unique items only:
get-service | select-object -first 5
get-hotfix | select -last 3
get-content users.txt | select -unique




Sort-Object (Alias:Sort)
Sort yesteryear ane or to a greater extent than properties:

dir *.exe, *.dll, *.sys | sort-object length, extension, cite -desc | select-object -first xx | format-table length, fullname -

autosize



Where-Object (Aliases: Where,?)
$_ is a temp variable for each object piped in.
{..} is a examine tha tmust evaluate to truthful or false.

get-service | where-object {$_.status -ne "running"}

dir hkcu:\ | where-object {$_.subkeycount -gt 2}

get-command | where {$_.name -like "*item*"}

get-hotfix | where {$_.description -math "^Secur."}

ps | ? {($_.id -ge 100) -and ($_.name -like "svc*")}

? - is used instead of 'where'

###################

Arrays are similar In-Memory Database Tables:

Creating Arrays:
$empty = @()
$one = @ ("SANS")
$x = @(1, "hi", 4.2, "bye")
$x += "AppendMoreStuff"
$big = @(0...50000)



Using Arrays:
$big.count

$x        #everything
$big [0]    #First
$big [1]    #Second
$big [-1]    Last

$d, $f = $nums [3,7]
$another = $nums [3...209]
$last5 = $big [-1..-5]

########################################

Capturing Command Output to An Array:

$output = get-history -count 50
$output = netstat.exe -ano
$output = python.exe myscript.py
$output = @(python.exe myscript.py)

$lines = @(get-content c:\file.txt)
$manylines = get-content *.txt, *.log, *.ini

$bytes = get-content worm.exe -encoding byte

@ - tells PowerShell that no affair how many lines of output, all those lines should locomote into an array.


###############3
On your computer:
- run the next commands
cd c:\sans\Day1-Powershell\Examples
ise .\Windows_Event-Logs.ps1
ise .\Nmap.ps1


###########################
Search Event Logs:

Get-WinEvent
- search local too remote lawsuit logs

- filtering performed at the remote server, non locally.

- tin enquiry archived log files off-line (*.evtx files).

- supports the XPath enquiry language:
Very flexible too precise enquiry syntax.
Build your XPath enquiry inwards Event Viewer.
Lots of XPath tutorials on the Internet.

eventvwr.msc  - the graphical lawsuit viewer!

Example from Manual:
get-winevent -listlog *

get-winevent -listlog s* -computer Server57

$logdata = get-winevent -logname system

get-winevent -logname safety -maxevents three | format-list *


###
$events  = get-winevent -log organization         -max 20
$events += get-winevent -log application     -max 20
$events += get-winevent -log safety         -max 20


$events | sort-object -property TimeCreated | format-table TimeCreated, ID, Level, Message -auto


########
Paste the xPath from the Windows EventViewer too run under:

$FromEventViewer = @'

......

'@

get-winevent -FilterXML $FromEventViewer | export-csv -path .\searchresults.csv

#####################

$dude = "Bryan"

"Hey There $Dude !"

- a double quote string is a ascendance inwards powershell to expect for a string at that location!
- field a unmarried quote is only beingness echoed!
'Hey There $Dude!"

#################################
Parsing Nmap XML Output
nmap.org
- tin position listening ports, service versions, operating fingerprints, too more.
- used for inventories too penetration testing.
- relieve your enterprise-wide port scans to XML files.

Parse-Nmap.ps1 Script:
.\parse-nmap.ps1 samplescan.xml -runstats dir *.xml | .\parse-nmap.ps1

- when nosotros utilisation amongst nmap the -runstats command, nosotros instruct all assort of information, such every bit ports scanned, hosts upward too down, sum

hosts scanned, version, how long it took to scan, etc.


Example from Manual:
nmap.exe -A -oX samplescan.xml 10.0.0.0/16

.\parse-nmap.ps1 -path samplescan.xml | select-object FQDN, IPv4, MAC, OS | convertto-html -title "$(get-date)" | out-file \

\server\sharedfolder\report.html

In existent life hackers too attackers scan thousands of machines at a fourth dimension to abide by vulnerable entry points!


Scanning for Windows XP machines:

.\parse-nmap.ps1 -path samplescan.xml | where {$_.OS -like "*Windows XP*"} |
 export-csv .\weblisteners.csv


$data = import-csv .\weblisteners.csv


$data | where {($_.IPv4 -like "10.57.*") -and ($_.Ports -match "open:tcp:22")}


#######################################

On your computer
cd c:\sans\Day1-PowerShell\example

ise .\If_FlowControl.ps1
ise .\While_FlowControl.ps1
ise .\Named_Parameters.ps1


#################

Flow Control: If-ElseIf-Else

If ($string -like "SANS*")
 { "It's truthful that it starts amongst SANS." }

ElseIf ($string -match "[FGH]IAC")
 {
    "It matches the regular appear pattern."
 }

Else
 {
    "We don't know what it is, thus we're giving up."
 }



Flow Control: While

$rabbits = 2
while ($rabbits -lt 10000) {            #-lt = less than
    "We at ane time conduct hold $rabbits rabbits!"
    $rabbits = $rabbits * 2

}


####
Flow Control: Do-While
$rabbits = 20000

Do {
    "We at ane time conduct hold $rabbits rabbits!"
    $rabbits *= 2
} While ($rabbits -lt 10000)


#######
Flow Control: ForEach, For too Switch

$services = get-service

ForEach ($x inwards $services)
{

$foo.name + " : " + $foo.status

}

get-service | ForEach { $_.name }


################

ps> 3+7
10

ps>"3" + "7"
37

>


###################
Functions:
Function = block of code amongst a name.
- tin convey goose egg or to a greater extent than input parameters.
- tin supply goose egg or to a greater extent than output objects.
- tin convey piped input, only similar a cmdlet.
- skillful agency organize code into manageable units.

Functions are kept inwards the function:\ drive.

dir function:\
get-item function:\man | format-list scriptblock


Create a constituent inwards PowerShell - example:
function hullo {"Hi there! "}

###################

Creating a novel function

function cite {<your code here}

function hullo {"Hi!"}

function fourth dimension {(get-date).TooLongTimeString() }


function edit-hostfile
{

notepad.exe $env:WinDir\System32\Drivers\Etc\hosts

}

###########

Passing inwards Named Parameters to a Function

function New-User ($UserName, $Password)
{
net.exe user $UserName "$Password" /add
}


new-user -username "Jill" -password "Sekrit"

new-user -u "Lori" -p "p@55vvord"


##################
Constraining a Function's Parameter Types

function eat-lunch ([Int] $number, [$String] $food)
{
"each 24-hour interval nosotros swallow $number $food pies!"
}

eat-lunch -number three -food pinkie


##################

Switch Parameters to Functions

- a switch parameter takes no arguments.
- a switch tin entirely live $True or $False (defaults to $False).

function show-folder ([Switch] $list) {
if ($list) {dir |format-list *}
else {dir |format-table fullname, length}

}

show-folder        #no switch, thus $list = $False
show-folder -list    #switch used, thus $list = $True

- switch parameters are yesteryear default False.

###################

Assigning Default Values to Function Parameters

function disable-admin
{

Param ($Password = "SEC505Gr8#4TV!")
net.exe user Administrator "$Password"
net.exe user Administrator /active:no
}

disable-admin
disable-admin -password "0ve3rr1d3n!"

######################
Passing Arguments Into Scripts


#ise .\Examples\PingWrapper.ps1
#to transcend arguments into the named
#parameters of a script, utilisation Param(...)

Param($computer = "localhost")

function pingwrapper ($ip) {ping.exe $ip }
pingwrapper -ip $computer



- below nosotros transcend an declaration of -computer too and then nosotros specify an IP address, but the programme already has a $computer argument, nosotros

just chose to alter it.
- also, -ip is a parameter.
- you lot tin entirely conduct hold ane 'param' telephone commutation too it needs to live at the top.

.\PingWrapper.ps1 -computer 8.8.8.8


Exercise:
Pass through a username too password, a drive letter, too a UNC path. Take ane of your tasks too do a constituent too param key,

just similar above.

#################

<#Congratulations!!! #>
$Today.Completed = $True

################################################ End of Day 1 ##################################

Blogger
Disqus
Pilih Sistem Komentar

No comments

Advertiser