示例#1
0
 def start(self, path):
     try:
         servicename = self.options.get("servicename", "CAPEService")
         servicedesc = self.options.get("servicedesc", "CAPE Service")
         arguments = self.options.get("arguments")
         path = check_file_extension(path, ".exe")
         binPath = f'"{path}"'
         if arguments:
             binPath += f" {arguments}"
         scm_handle = ADVAPI32.OpenSCManagerA(None, None,
                                              SC_MANAGER_ALL_ACCESS)
         if scm_handle == 0:
             log.info("Failed to open SCManager")
             log.info(ctypes.FormatError())
             return
         service_handle = ADVAPI32.CreateServiceA(
             scm_handle,
             servicename,
             servicedesc,
             SERVICE_ALL_ACCESS,
             SERVICE_WIN32_OWN_PROCESS,
             SERVICE_DEMAND_START,
             SERVICE_ERROR_IGNORE,
             binPath,
             None,
             None,
             None,
             None,
             None,
         )
         if service_handle == 0:
             log.info("Failed to create service")
             log.info(ctypes.FormatError())
             return
         log.info("Created service (handle: 0x%x)", service_handle)
         servproc = Process(options=self.options,
                            config=self.config,
                            pid=self.config.services_pid,
                            suspended=False)
         filepath = servproc.get_filepath()
         servproc.inject(injectmode=INJECT_QUEUEUSERAPC,
                         interest=filepath,
                         nosleepskip=True)
         servproc.close()
         KERNEL32.Sleep(500)
         service_launched = ADVAPI32.StartServiceA(service_handle, 0, None)
         if service_launched:
             log.info("Successfully started service")
         else:
             log.info(ctypes.FormatError())
             log.info("Failed to start service")
         ADVAPI32.CloseServiceHandle(service_handle)
         ADVAPI32.CloseServiceHandle(scm_handle)
         return
     except Exception as e:
         log.info(sys.exc_info()[0])
         log.info(e)
         log.info(e.__dict__)
         log.info(e.__class__)
         log.exception(e)
示例#2
0
    def __init__(self, result_ip, result_port, logserver_path):
        # Create the Named Pipe.
        sd = SECURITY_DESCRIPTOR()
        sa = SECURITY_ATTRIBUTES()
        ADVAPI32.InitializeSecurityDescriptor(byref(sd), 1)
        ADVAPI32.SetSecurityDescriptorDacl(byref(sd), True, None, False)
        sa.nLength = sizeof(SECURITY_ATTRIBUTES)
        sa.bInheritHandle = False
        sa.lpSecurityDescriptor = addressof(sd)

        h_pipe = KERNEL32.CreateNamedPipeW(
            logserver_path,
            PIPE_ACCESS_INBOUND,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            BUFSIZE,
            LOGBUFSIZE,
            0,
            byref(sa),
        )

        if h_pipe == INVALID_HANDLE_VALUE:
            log.warning("Unable to create log server pipe")
            return False

        logserver = LogServerThread(h_pipe, result_ip, result_port)
        logserver.daemon = True
        logserver.start()
示例#3
0
def pid_from_service_name(servicename):
    sc_handle = ADVAPI32.OpenSCManagerA(None, None, 0x0001)
    serv_handle = ADVAPI32.OpenServiceA(sc_handle, servicename, 0x0005)
    buf = create_string_buffer(36)
    needed = c_int(0)
    ADVAPI32.QueryServiceStatusEx(serv_handle, 0, buf, sizeof(buf), byref(needed))
    thepid = struct.unpack("IIIIIIIII", buf.raw)[7]
    ADVAPI32.CloseServiceHandle(serv_handle)
    ADVAPI32.CloseServiceHandle(sc_handle)
    return thepid
示例#4
0
def grant_debug_privilege(pid=None):
    """Grant debug privileges.
    @param pid: PID.
    @return: operation status.
    """
    ADVAPI32.OpenProcessToken.argtypes = (wintypes.HANDLE,
                                          wintypes.DWORD,
                                          POINTER(wintypes.HANDLE))

    ADVAPI32.LookupPrivilegeValueW.argtypes = (wintypes.LPWSTR,
                                               wintypes.LPWSTR,
                                               POINTER(LUID))

    ADVAPI32.AdjustTokenPrivileges.argtypes = (wintypes.HANDLE,
                                               wintypes.BOOL,
                                               POINTER(TOKEN_PRIVILEGES),
                                               wintypes.DWORD,
                                               POINTER(TOKEN_PRIVILEGES),
                                               POINTER(wintypes.DWORD))

    if pid is None:
        h_process = KERNEL32.GetCurrentProcess()
    else:
        h_process = KERNEL32.OpenProcess(PROCESS_ALL_ACCESS, False, pid)

    if not h_process:
        return False

    h_current_token = wintypes.HANDLE()
    if not ADVAPI32.OpenProcessToken(h_process,
                                     TOKEN_ALL_ACCESS,
                                     h_current_token):
        return False

    se_original_luid = LUID()
    if not ADVAPI32.LookupPrivilegeValueW(None,
                                          "SeDebugPrivilege",
                                          se_original_luid):
        return False

    luid_attributes = LUID_AND_ATTRIBUTES()
    luid_attributes.Luid = se_original_luid
    luid_attributes.Attributes = SE_PRIVILEGE_ENABLED
    token_privs = TOKEN_PRIVILEGES()
    token_privs.PrivilegeCount = 1
    token_privs.Privileges = luid_attributes

    if not ADVAPI32.AdjustTokenPrivileges(h_current_token, False, token_privs,
                                          0, None, None):
        return False

    KERNEL32.CloseHandle(h_current_token)
    KERNEL32.CloseHandle(h_process)
    return True
示例#5
0
    def run(self):
        while self.do_run:
            # Create the Named Pipe.
            sd = SECURITY_DESCRIPTOR()
            sa = SECURITY_ATTRIBUTES()
            ADVAPI32.InitializeSecurityDescriptor(byref(sd), 1)
            ADVAPI32.SetSecurityDescriptorDacl(byref(sd), True, None, False)
            sa.nLength = sizeof(SECURITY_ATTRIBUTES)
            sa.bInheritHandle = False
            sa.lpSecurityDescriptor = addressof(sd)
            # flags = FILE_FLAG_WRITE_THROUGH

            if self.message:
                pipe_handle = KERNEL32.CreateNamedPipeW(
                    self.pipe_name,
                    PIPE_ACCESS_DUPLEX,  # | flags,
                    PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
                    PIPE_UNLIMITED_INSTANCES,
                    BUFSIZE,
                    BUFSIZE,
                    0,
                    byref(sa),  # None,
                )
            else:
                pipe_handle = KERNEL32.CreateNamedPipeW(
                    self.pipe_name,
                    PIPE_ACCESS_INBOUND,  # | flags,
                    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                    PIPE_UNLIMITED_INSTANCES,
                    0,
                    BUFSIZE,
                    0,
                    byref(sa),  # None,
                )

            if pipe_handle == INVALID_HANDLE_VALUE:
                log.warning("Error opening logging pipe server")
                continue

            if KERNEL32.ConnectNamedPipe(
                    pipe_handle,
                    None) or KERNEL32.GetLastError() == ERROR_PIPE_CONNECTED:
                handler = self.pipe_handler(pipe_handle, **self.kwargs)
                handler.daemon = True
                handler.start()
                self.handlers.add(handler)
            else:
                KERNEL32.CloseHandle(pipe_handle)
示例#6
0
    def run(self):
        """Create and run PIPE server.
        @return: operation status.
        """
        try:
            while self.do_run:
                # Create the Named Pipe.
                sd = SECURITY_DESCRIPTOR()
                sa = SECURITY_ATTRIBUTES()
                ADVAPI32.InitializeSecurityDescriptor(byref(sd), 1)
                ADVAPI32.SetSecurityDescriptorDacl(byref(sd), True, None, False)
                sa.nLength = sizeof(SECURITY_ATTRIBUTES)
                sa.bInheritHandle = False
                sa.lpSecurityDescriptor = addressof(sd)

                h_pipe = KERNEL32.CreateNamedPipeA(self.pipe_name,
                                                   PIPE_ACCESS_DUPLEX,
                                                   PIPE_TYPE_MESSAGE |
                                                   PIPE_READMODE_MESSAGE |
                                                   PIPE_WAIT,
                                                   PIPE_UNLIMITED_INSTANCES,
                                                   BUFSIZE,
                                                   BUFSIZE,
                                                   0,
                                                   byref(sa))

                if h_pipe == INVALID_HANDLE_VALUE:
                    return False

                # If we receive a connection to the pipe, we invoke the handler.
                if KERNEL32.ConnectNamedPipe(h_pipe, None) or KERNEL32.GetLastError() == ERROR_PIPE_CONNECTED:
                    handler = PipeHandler(h_pipe, self.config, self.options)
                    handler.daemon = True
                    handler.start()
                else:
                    KERNEL32.CloseHandle(h_pipe)

            return True
        except Exception as e:
            error_exc = traceback.format_exc()
            log.exception(error_exc)
            return True
示例#7
0
    def start(self, path):

        try:
            sc = self.get_path("sc.exe")
            servicename = self.options.get("servicename", "CAPEService")
            servicedesc = self.options.get("servicedesc", "CAPE Service")
            arguments = self.options.get("arguments")

            if "." not in os.path.basename(path):
                new_path = path + ".exe"
                os.rename(path, new_path)
                path = new_path

            binPath = "\"{0}\"".format(path)
            if arguments:
                binPath += " {0}".format(arguments)

            scm_handle = ADVAPI32.OpenSCManagerA(None, None,
                                                 SC_MANAGER_ALL_ACCESS)
            if scm_handle == 0:
                log.info("Failed to open SCManager")
                log.info(ctypes.FormatError())
                return

            service_handle = ADVAPI32.CreateServiceA(
                scm_handle, servicename, servicedesc, SERVICE_ALL_ACCESS,
                SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START,
                SERVICE_ERROR_IGNORE, binPath, None, None, None, None, None)
            if service_handle == 0:
                log.info("Failed to create service")
                log.info(ctypes.FormatError())
                return

            log.info("Created service (handle: 0x%x)", service_handle)

            servproc = Process(options=self.options,
                               config=self.config,
                               pid=self.config.services_pid,
                               suspended=False)
            servproc.set_critical()
            filepath = servproc.get_filepath()
            is_64bit = servproc.is_64bit()
            if is_64bit:
                servproc.inject(injectmode=INJECT_QUEUEUSERAPC,
                                interest=filepath,
                                nosleepskip=True)
            else:
                servproc.inject(injectmode=INJECT_QUEUEUSERAPC,
                                interest=filepath,
                                nosleepskip=True)
            servproc.close()
            KERNEL32.Sleep(500)

            service_launched = ADVAPI32.StartServiceA(service_handle, 0, None)
            if service_launched == True:
                log.info("Successfully started service")
            else:
                log.info(ctypes.FormatError())
                log.info("Failed to start service")

            ADVAPI32.CloseServiceHandle(service_handle)
            ADVAPI32.CloseServiceHandle(scm_handle)

            return

        except Exception as e:
            log.info(sys.exc_info()[0])
            log.info(e)
            log.info(e.__dict__)
            log.info(e.__class__)
            log.exception(e)