______ Y ______

My own personal time capsule.

Category Archives: api

Universal Process Privilage Escalation

By adjusting process token its possible to elevate your current process privileges to enable certain functionality not available otherwise.

Basically steps we follow are :
1) Get current process handle
2) Get current process token
3) Resolve SeDebugPrivilege value
4) Created new Token with the resolved value from step 3
5) Adjust the token of the current process with new privilege
6) Close process handle

Following code demonstrates the principle.


print "[+] Universal Process Escalation by Y"
print "[+] contact : If you know me then give me a shout"

from ctypes import windll
import ctypes
from ctypes import *

class TOKEN_PRIVS(ctypes.Structure):
    _fields_ = (
        ("PrivilegeCount",    ULONG),
        ("Privileges",        ULONG * 3 )
    )

def get_debug_privs():
    # Adjust Current TOKEN
    token = HANDLE()
    print "\t[+] Getting Current Token"
    flags =  40 #  TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY
    windll.advapi32.OpenProcessToken(windll.kernel32.GetCurrentProcess(), 0x00000020, ctypes.byref(token))
    print "\t[+] Calculating Local SeDebugPrivilege"
    admin_priv_name = "SeDebugPrivilege" # we want this priv on the process
    pBytesReturned = ctypes.c_ulong() 
    windll.advapi32.LookupPrivilegeValueA(None,admin_priv_name,ctypes.byref(pBytesReturned))
    print "\t[+] Resolved SeDebugPrivilege as %d" % pBytesReturned.value
    print "\t[+] Modifying TOKEN Structure to enable Debug"
    privs = TOKEN_PRIVS()
    privs.PrivilegeCount = 1
    privs.Privileges = (pBytesReturned.value,0, 2) 
    print "\t[+] Adjusting Privileges of the current process"
    windll.advapi32.AdjustTokenPrivileges(token, 0, ctypes.byref(privs),0,0,0)
    print "\t[+] Closing current handle, almost done"
    windll.kernel32.CloseHandle(token)
    print "[+] Done, your process " , windll.kernel32.GetCurrentProcessId(), "has now admin privileges"
    ############ CURRENT TOKEN ADJUSTED ##################
	
get_debug_privs()

Privilage Escalation check on Drivers in Python

This code will query the WMI service in order to retrieve information about current drivers, their status and access rights. As you might be aware if drivers are not locked down properly, it may be possible to create nice rootkit loaded by the kernel and execute any code you might find useful. Furthermore it can be possible to override driver with your custom made stuff to elevate privileges from there.

print "[+] List System driver and Check file access permissions "
print "[+]                        By Y                          " 
print "[+] If you know me then give me a shout                  "
 
class driver():
	def getSystemDrivers(self):
        print "[+] Dumping System Drivers And Their Location"
        # function reference : http://msdn.microsoft.com/en-us/library/windows/desktop/aa394472%28v=vs.85%29.aspx
        strComputer = "."
        WmiServiceConnector = win32com.client.Dispatch("WbemScripting.SWbemLocator")
        objSWbemServices = WmiServiceConnector.ConnectServer(strComputer,"root\CIMV2")
        listOfDrivers = objSWbemServices.ExecQuery("SELECT * FROM Win32_SystemDriver")
        for objItem1 in listOfDrivers:
            print "\t[+] Dumping info for driver : " , objItem1.PathName
            if objItem1.PathName is not None:
                print "\t\tDriver Path : " , objItem1.PathName
            if objItem1.Description is not None:
                print "\t\tDescription : " , objItem1.Description
            if objItem1.InstallDate is not None:
                print "\t\tInstallation Date : ", objItem1.InstallDate
            if objItem1.ServiceType is not None:
                print "\t\tService Type : ", objItem1.ServiceType
            if objItem1.StartMode is not None:
                print "\t\tStart Mode : ", objItem1.StartMode
            if objItem1.DesktopInteract is not None:
                print "\t\tDesktop Interaction : ", objItem1.DesktopInteract
            if objItem1.Name is not None:
                print "\t\tDriver Name : ", objItem1.Name
            if objItem1.Started is not None:
                print "\t\tDriver started :" , objItem1.Started
            if objItem1.State is not None:
                print "\t\tCurrent Driver State : ",  objItem1.State
            if objItem1.ErrorControl is not None:
                print "\t\tErrorControl : ", objItem1.ErrorControl
            
            fileChecks().checkPermission(objItem1.PathName)
            fileChecks().getBasicInfo(objItem1.PathName)



class fileChecks():
    def checkPermission(self,filePath):
        # based on http://www.ibm.com/developerworks/aix/library/au-python/
        mode=stat.S_IMODE(os.lstat(filePath)[stat.ST_MODE])
        print "\t\t\t[+] Permissions for file ", filePath
        for level in "USR", "GRP", "OTH":
            for perm in "R", "W", "X":
                if mode & getattr(stat,"S_I"+perm+level):
                    print "\t\t\t\t",level, " has ", perm, " permission"
                else:
                    print "\t\t\t\t",level, " does NOT have ", perm, " permission"
    
    def getBasicInfo(self,file_name):
        time_format = "%m/%d/%Y %I:%M:%S %p"
        file_stats = os.stat(file_name)
        modification_time = time.strftime(time_format,time.localtime(file_stats[stat.ST_MTIME]))
        access_time = time.strftime(time_format,time.localtime(file_stats[stat.ST_ATIME]))
        creation_time = time.strftime(time_format,time.localtime(file_stats[stat.ST_CTIME]))
        print "\t\t\t[+] Basic File Information "
        print "\t\t\t\t Modification time: " , modification_time
        print "\t\t\t\t Access time: " , access_time
        print "\t\t\t\t Creation time: " , creation_time
        print "\t\t\t\t Owner UID : ", file_stats[stat.ST_UID]
        print "\t\t\t\t Owner GID : ",  file_stats[stat.ST_GID]   

drivers = driver()
drivers.getSystemDrivers()

PID Enumeration on Windows with pure python ctypes

Following code will enumerate process ID’s on the current system by calling EnumProcesses from psapi on Windows. Should for for majority of windows distributions that have psapi.dll in %systemroot%.


from ctypes import *

psapi = windll.psapi

print "[+] PID dumper by Y"
print "[+] contact : If you know me then give me a shout"

def getListOfProcesses():
    max_array = c_ulong * 4096 # define long array to capture all the processes
    pProcessIds = max_array() # array to store the list of processes
    pBytesReturned = c_ulong() # the number of bytes returned in the array
    #EnumProcess 
    psapi.EnumProcesses(byref(pProcessIds),
                        sizeof(pProcessIds),
                        byref(pBytesReturned))
 
    # get the number of returned processes
    nReturned = pBytesReturned.value/sizeof(c_ulong())
    pidProcessArray = [i for i in pProcessIds][:nReturned]
    for processes in pidProcessArray:
        print "[+] Running Process PID %d" % processes 

getListOfProcesses()

Dumping Drivers on Windows

Ever wonder how to list all the drivers on your windows machine ? Here is a quick answer coded in Python that hopefully can help some people.

from ctypes import *
#Windows modules loader
kernel32 =  windll.kernel32
psapi = windll.psapi

class drivers():
    def getAllDeviceDrivers(self):
        lpcbNeeded =          c_ulong(0)
        empty_init_array      = c_ulong * 1024
        lpImageBase           = empty_init_array()
        drivername_size       = c_long()
        drivername_size.value = 48
        if psapi.EnumDeviceDrivers(byref(lpImageBase),sizeof(c_void_p)*1024,byref(lpcbNeeded)):
            no_drivers = int(lpcbNeeded.value / sizeof(c_void_p))
            print "[*] EnumDeviceDrivers: %d modules detected" % no_drivers
            print "\t[+] Dumping all device drivers"
            for baseaddy in lpImageBase:
     
                drivername = c_char_p("\x00"*drivername_size.value)
                if baseaddy:
                    psapi.GetDeviceDriverBaseNameA(baseaddy, drivername, drivername_size.value)         
                             
                    driverpath = c_char_p("\x00"*drivername_size.value)
                    psapi.GetDeviceDriverFileNameA(baseaddy,driverpath,drivername_size.value)
                    # if we have drivers with addresses allocated within 0x80000000 and 0xFFFFFFFF they loaded directly kernel
                    if baseaddy > 2147483648 and baseaddy < 4294967295:  
                        print "\t\t [-] Kernel Driver",drivername.value.lower(),"is located on 0x%08x load path is %s" % (baseaddy,driverpath.value.lower())
                    else:
                        # user level drivers are within 0x00000000 and 0x7FFFFFFF
                        print "\t\t [-] User Driver",drivername.value.lower(),"is located on 0x%08x load path is %s" % (baseaddy,driverpath.value.lower())                 

drivers = drivers()
drivers.getAllDeviceDrivers()