def InstallDriver(driver_path, service_name, driver_display_name): """Loads a driver and start it.""" hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: win32service.CreateService( hscm, service_name, driver_display_name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, driver_path, None, # No load ordering 0, # No Tag identifier None, # Service deps None, # User name None) # Password win32serviceutil.StartService(service_name) except pywintypes.error as e: # The following errors are expected: if e[0] not in [ winerror.ERROR_SERVICE_EXISTS, winerror.ERROR_SERVICE_MARKED_FOR_DELETE ]: raise RuntimeError("StartService failure: {0}".format(e))
def install_driver(self, pszWinIoDriverPath, IsDemandLoaded): # Remove any previous instance of the driver self.uninstall_driver() # Install the driver if IsDemandLoaded is True: demand_flags = win32service.SERVICE_DEMAND_START else: demand_flags = win32service.SERVICE_SYSTEM_START try: win32service.CreateService( self.hSCManager, "WINIO", "WINIO", win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, demand_flags, win32service.SERVICE_ERROR_NORMAL, pszWinIoDriverPath, None, 0, None, None, None, ) except pywintypes.error as e: if e.winerror == EC_SERVICE_EXISTED: # Service existed! return True raise
def action_install(self): hSCM = safe_open_scmanager() self._fix_start_type() self._fix_user_name() try: hSvc = win32service.CreateService( hSCM, self.resource.service_name, self.resource.display_name, win32service.SERVICE_ALL_ACCESS, # desired access win32service.SERVICE_WIN32_OWN_PROCESS, # service type self.resource.start_type, win32service.SERVICE_ERROR_NORMAL, # error control type self.resource.exe_path, None, 0, None, self.resource.userName, self.resource.password) if self.resource.description: try: win32service.ChangeServiceConfig2( hSvc, win32service.SERVICE_CONFIG_DESCRIPTION, self.description) except NotImplementedError: pass ## ChangeServiceConfig2 and description do not exist on NT win32service.CloseServiceHandle(hSvc) except win32api.error, details: raise Fail("Error creating service {0}: {1}".format( self.resource.service_name, details.winerror))
def create(self): if not self.driver or not os.path.exists(self.driver): if self.debug: print "The driver does not exist at path: {0}".format(self.driver) return if self.debug: print "Trying to create service", self.service_name, self.driver try: if not self.service: self.service = win32service.CreateService( self.manager, self.service_name, self.service_name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, self.driver, None, 0, None, None, None) except win32service.error as e: if self.debug: print "Unable to create service: {0}".format(e) self.service = win32service.OpenService(self.manager, self.service_name, win32service.SERVICE_ALL_ACCESS) try: win32service.ControlService(self.service, win32service.SERVICE_CONTROL_STOP) except win32service.error: pass
def _CreateService(service_name: str, description: str, command_line: str) -> None: """Creates a Windows service.""" logging.info("Creating service '%s'.", service_name) with contextlib.ExitStack() as stack: hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) stack.callback(win32service.CloseServiceHandle, hscm) hs = win32service.CreateService( hscm, service_name, service_name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_AUTO_START, win32service.SERVICE_ERROR_NORMAL, command_line, None, 0, None, None, None) stack.callback(win32service.CloseServiceHandle, hs) service_failure_actions = { "ResetPeriod": SERVICE_RESET_FAIL_COUNT_DELAY_SEC, "RebootMsg": u"", "Command": u"", "Actions": [ (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC), (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC), (win32service.SC_ACTION_RESTART, SERVICE_RESTART_DELAY_MSEC), ] } win32service.ChangeServiceConfig2( hs, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, service_failure_actions) win32service.ChangeServiceConfig2( hs, win32service.SERVICE_CONFIG_DESCRIPTION, description) logging.info("Successfully created service '%s'.", service_name)
def load_driver(self): """Load the driver if possible.""" # Check the driver is somewhere accessible. if self.driver is None: # Valid values # http://superuser.com/questions/305901/possible-values-of-processor-architecture machine = platform.machine() if machine == "AMD64": driver = "winpmem_x64.sys" elif machine == "x86": driver = "winpmem_x86.sys" else: raise plugin.PluginError("Unsupported architecture") self.driver = rekall.get_resource("WinPmem/%s" % driver) # Try the local directory if self.driver is None: self.driver = os.path.join(os.getcwd(), "WinPmem", driver) self.session.logging.debug("Loading driver from %s", self.driver) if not os.access(self.driver, os.R_OK): raise plugin.PluginError("Driver file %s is not accessible." % self.driver) # Must have absolute path here. self.hScm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_CREATE_SERVICE) try: self.hSvc = win32service.CreateService( self.hScm, self.name, self.name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, self.driver, None, 0, None, None, None) self.session.logging.debug("Created service %s", self.name) # Remember to cleanup afterwards. self.we_started_service = True except win32service.error as e: # Service is already there, try to open it instead. self.hSvc = win32service.OpenService( self.hScm, self.name, win32service.SERVICE_ALL_ACCESS) # Make sure the service is stopped. try: win32service.ControlService(self.hSvc, win32service.SERVICE_CONTROL_STOP) except win32service.error: pass try: win32service.StartService(self.hSvc, []) except win32service.error, e: self.session.logging.debug("%s: will try to continue", e)
def InstallService(pythonClassString, serviceName, displayName, startType=None, errorControl=None, bRunInteractive=0, serviceDeps=None, userName=None, password=None, exeName=None, perfMonIni=None, perfMonDll=None, exeArgs=None, description=None): # Handle the default arguments. if startType is None: startType = win32service.SERVICE_DEMAND_START serviceType = win32service.SERVICE_WIN32_OWN_PROCESS if bRunInteractive: serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS if errorControl is None: errorControl = win32service.SERVICE_ERROR_NORMAL exeName = '"%s"' % LocatePythonServiceExe( exeName) # None here means use default PythonService.exe commandLine = _GetCommandLine(exeName, exeArgs) hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32service.CreateService( hscm, serviceName, displayName, win32service.SERVICE_ALL_ACCESS, # desired access serviceType, # service type startType, errorControl, # error control type commandLine, None, 0, serviceDeps, userName, password) if description is not None: try: win32service.ChangeServiceConfig2( hs, win32service.SERVICE_CONFIG_DESCRIPTION, description) except NotImplementedError: pass ## ChangeServiceConfig2 and description do not exist on NT win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) InstallPythonClassString(pythonClassString, serviceName) # If I have performance monitor info to install, do that. if perfMonIni is not None: InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
def create(self, start_driver): if not start_driver: return True self.show_warning() try: hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # SC_MANAGER_CREATE_SERVICE except win32service.error as err: _handle_winerror(err.args[1], err.args[2], err.args[0]) if logger().DEBUG: logger().log( "[helper] service control manager opened (handle = {})".format( hscm)) logger().log("[helper] driver path: '{}'".format( os.path.abspath(self.driver_path))) try: hs = win32service.CreateService( hscm, SERVICE_NAME, DISPLAY_NAME, (win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_START | win32service.SERVICE_STOP), win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, os.path.abspath(self.driver_path), None, 0, u"", None, None) if hs: if logger().DEBUG: logger().log( "[helper] service '{}' created (handle = 0x{:08X})". format(SERVICE_NAME, hs)) except win32service.error as err: if (winerror.ERROR_SERVICE_EXISTS == err.args[0]): if logger().DEBUG: logger().log( "[helper] service '{}' already exists: {} ({:d})". format(SERVICE_NAME, err.args[2], err.args[0])) try: hs = win32service.OpenService( hscm, SERVICE_NAME, (win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_START | win32service.SERVICE_STOP)) # SERVICE_ALL_ACCESS except win32service.error as err1: _handle_winerror(err1.args[1], err1.args[2], err1.args[0]) else: _handle_winerror(err.args[1], err.args[2], err.args[0]) finally: win32service.CloseServiceHandle(hs) win32service.CloseServiceHandle(hscm) return True
def Install(cls, startupMode="auto", username=None, password=None): print "Installing service %s" % (cls._svc_name_) # Configure master.xml, which drives the java subprocess32 java_path = get_java_exe_path() java_args = _build_master_java_args(username) config_file_path = _get_config_file_path() xmlFileContents = _MasterXml() xmlFileContents.service.id = EMBEDDED_HBASE_MASTER_SERVICE xmlFileContents.service.name = EMBEDDED_HBASE_MASTER_SERVICE xmlFileContents.service.description = "This service runs " + EMBEDDED_HBASE_MASTER_SERVICE xmlFileContents.service.executable = java_path xmlFileContents.service.arguments = java_args xmlFile = open(config_file_path, "w") xmlFile.write(str(xmlFileContents)) xmlFile.close() startType = cls._get_start_type(startupMode) serviceType = win32service.SERVICE_WIN32_OWN_PROCESS errorControl = win32service.SERVICE_ERROR_NORMAL commandLine = os.path.abspath(cls._exe_name_) hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: try: hs = win32service.CreateService( hscm, cls._svc_name_, cls._svc_display_name_, win32service.SERVICE_ALL_ACCESS, # desired access serviceType, # service type startType, errorControl, # error control type commandLine, None, 0, None, username, password) print "Service installed" win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) except win32service.error, exc: if exc.winerror == winerror.ERROR_SERVICE_EXISTS: cls.Update(username, password) else: print "Error installing service: %s (%d)" % (exc.strerror, exc.winerror) err = exc.winerror
def create(self, start_driver): if not start_driver: return True # check DRIVER_FILE_PATHS for the DRIVER_FILE_NAME self.driver_path = None for path in DRIVER_FILE_PATHS: driver_path = os.path.join(path, DRIVER_FILE_NAME) if os.path.isfile(driver_path): self.driver_path = driver_path if logger().DEBUG: logger().log("[helper] found driver in {}".format(driver_path)) if self.driver_path is None: if logger().DEBUG: logger().log("[helper] CHIPSEC Windows Driver Not Found") raise Exception("CHIPSEC Windows Driver Not Found") self.show_warning() try: hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # SC_MANAGER_CREATE_SERVICE except win32service.error as err: _handle_winerror(err.args[1], err.args[2], err.args[0]) if logger().DEBUG: logger().log( "[helper] service control manager opened (handle = {})".format(hscm) ) logger().log( "[helper] driver path: '{}'".format(os.path.abspath(self.driver_path)) ) try: hs = win32service.CreateService( hscm, SERVICE_NAME, DISPLAY_NAME, (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP), win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, os.path.abspath(self.driver_path), None, 0, u"", None, None ) if hs: if logger().DEBUG: logger().log( "[helper] service '{}' created (handle = 0x{:08X})".format(SERVICE_NAME,int(hs)) ) except win32service.error as err: if (winerror.ERROR_SERVICE_EXISTS == err.args[0]): if logger().DEBUG: logger().log( "[helper] service '{}' already exists: {} ({:d})".format(SERVICE_NAME, err.args[2], err.args[0]) ) try: hs = win32service.OpenService( hscm, SERVICE_NAME, (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP) ) # SERVICE_ALL_ACCESS except win32service.error as _err: _handle_winerror(_err.args[1], _err.args[2], _err.args[0]) else: _handle_winerror(err.args[1], err.args[2], err.args[0]) finally: win32service.CloseServiceHandle( hs ) win32service.CloseServiceHandle( hscm ) return True
def InstallService(serviceName, displayName, startType=win32service.SERVICE_DEMAND_START, serviceDeps=None, errorControl=win32service.SERVICE_ERROR_NORMAL, userName=None, password=None, description=None): """ This is a copy of a more advanced usecase. For chalmers serviceName and displayName are required and the defaults should be sufficient """ serviceType = win32service.SERVICE_WIN32_OWN_PROCESS script = abspath(service_script.__file__) if script.endswith('.pyc') or script.endswith('.pyo'): script = script[:-1] commandLine = "%s %s" % (sys.executable, script) hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32service.CreateService( hscm, serviceName, displayName, win32service.SERVICE_ALL_ACCESS, # desired access serviceType, # service type startType, errorControl, # error control type commandLine, None, 0, serviceDeps, userName, password) if description is not None: try: win32service.ChangeServiceConfig2( hs, win32service.SERVICE_CONFIG_DESCRIPTION, description) except NotImplementedError: pass # # ChangeServiceConfig2 and description do not exist on NT win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm)
def create(self): if not self.driver or not os.path.exists(self.driver): raise DetectorError( "The driver does not exist at path: {0}".format(self.driver)) try: if not self.service: self.service = win32service.CreateService( self.manager, self.service_name, self.service_name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, self.driver, None, 0, None, None, None) except Exception as e: raise DetectorError("Unable to create service: {0}".format(e))
def InstallService(self, name): ''' Installs the server as an NT service with the given name. @type name: string @param name: Name of the NT service to install. ''' # get handle to the service manager mgr = win32service.OpenSCManager( None, # local computer None, win32service.SC_MANAGER_ALL_ACCESS) if mgr == None: err = "Could not get handle to service manager." mainlog.critical(err) raise _EarlyServerExit # figure out what command to use if __file__.find("library.zip") > 0: # running as frozen executable cmd = sys.executable else: # running as native script cmd = sys.executable + sys.argv[0] for arg in sys.argv[1:]: if arg == "--service-install": continue cmd += " %s" % arg cmd += " --service-run" # create the service service = win32service.CreateService( mgr, self.ServiceName, self.ServiceName, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_AUTO_START, win32service.SERVICE_ERROR_NORMAL, cmd, None, None, None, None, None) if service == None: # failed to create the service mainlog.critical("Could not install the NT service.") win32service.CloseServiceHandle(mgr) raise _EarlyServerExit # clean up win32service.CloseServiceHandle(mgr) win32service.CloseServiceHandle(service)
def load_driver(self, name, path): """ Load a driver Returns: handle to the driver """ try: hsvc = win32service.CreateService( self.hscm, name, name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, path, None, 0, None, None, None) self.__managed_services[name] = hsvc except win32service.error: hsvc = self.get_service(name) return hsvc
def RegisterDriver(self): serviceManager = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) driverPath = os.path.join(os.environ['WINDIR'], 'system32\\drivers\\' + self.name + '.sys') try: serviceHandle = win32service.CreateService( serviceManager, self.name, self.name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, driverPath, None, 0, None, None, None) except: return False finally: win32service.CloseServiceHandle(serviceManager) win32service.CloseServiceHandle(serviceHandle) return True
def _SaveNewService(self, serviceConfigManagerHandle, serviceStartNamePassword=None): serviceHandle = None try: serviceHandle = win32service.CreateService(serviceConfigManagerHandle, self.configurations['ServiceName'].Win32Value(), self.configurations['DisplayName'].Win32Value(), win32service.SERVICE_ALL_ACCESS, # desired access self.configurations['ServiceType'].Win32Value(), self.configurations['StartType'].Win32Value(), self.configurations['ErrorControl'].Win32Value(), self.configurations['BinaryPathName'].Win32Value(), self.configurations['LoadOrderGroup'].Win32Value(), 0, self.configurations['Dependencies'].Win32Value(), self.configurations['ServiceStartName'].Win32Value(), serviceStartNamePassword) finally: if serviceHandle is not None: win32service.CloseServiceHandle(serviceHandle)
def create_driver_service(logger): """Creates the service for winpmem""" # Must have absolute path here. if hasattr(sys, "frozen"): driver = os.path.join(sys._MEIPASS, get_winpmem_name()) else: driver = os.path.join(os.getcwd(), get_winpmem_name()) h_scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CREATE_SERVICE) try: h_svc = win32service.CreateService(h_scm, "pmem", "pmem", win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, driver, None, 0, None, None, None) except win32service.error, e: logger.error(e) h_svc = win32service.OpenService(h_scm, "pmem", win32service.SERVICE_ALL_ACCESS)
def main(): """Load the driver and image the memory.""" # Check the driver is somewhere if not FLAGS.driver or not os.access(FLAGS.driver, os.R_OK): print("You must specify a valid driver file.") sys.exit(-1) # Must have absolute path here. driver = os.path.join(os.getcwd(), FLAGS.driver) hScm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CREATE_SERVICE) try: hSvc = win32service.CreateService(hScm, FLAGS.name, FLAGS.name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, driver, None, 0, None, None, None) except win32service.error as e: print(e) hSvc = win32service.OpenService(hScm, FLAGS.name, win32service.SERVICE_ALL_ACCESS) # Make sure the service is stopped. try: win32service.ControlService(hSvc, win32service.SERVICE_CONTROL_STOP) except win32service.error: pass if FLAGS.unload: print("unloaded winpmem driver.") return try: win32service.StartService(hSvc, []) except win32service.error, e: print("%s: will try to continue" % e)
def createService(serviceName, appName): # 获取“服务管理器”的句柄 scHandle = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) # 开始创建 hs = win32service.CreateService(scHandle, serviceName, serviceName, win32service.SERVICE_ALL_ACCESS, # desired access win32service.SERVICE_WIN32_OWN_PROCESS, # service type win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, # error control type appName, None, 0, None, None, None) # 释放所取得的所有句柄 win32service.CloseServiceHandle(hs) win32service.CloseServiceHandle(scHandle)
def main(): """Load the driver and image the memory.""" # Check the driver is somewhere if not FLAGS.driver or not os.access(FLAGS.driver, os.R_OK): print "You must specify a valid driver file." sys.exit(-1) # Must have absolute path here. driver = os.path.join(os.getcwd(), FLAGS.driver) hScm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CREATE_SERVICE) try: hSvc = win32service.CreateService(hScm, FLAGS.name, FLAGS.name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, driver, None, 0, None, None, None) except win32service.error, e: print e hSvc = win32service.OpenService(hScm, FLAGS.name, win32service.SERVICE_ALL_ACCESS)
driver_path = os.path.join(chipsec.file.get_main_dir(), "chipsec" , "helper" ,"win" ) driver_path = os.path.join( driver_path, self.win_ver , DRIVER_FILE_NAME ) if os.path.exists( driver_path ) and os.path.isfile( driver_path ): self.driver_path = driver_path if logger().VERBOSE: logger().log( "[helper] driver path: '%s'" % os.path.abspath(self.driver_path) ) else: logger().error( "could not locate driver file '%.256s'" % driver_path ) return False try: self.hs = win32service.CreateService( hscm, SERVICE_NAME, DISPLAY_NAME, (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP), # SERVICE_ALL_ACCESS, STANDARD_RIGHTS_REQUIRED, DELETE win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, os.path.abspath(driver_path), None, 0, u"", None, None ) if not self.hs: raise win32service.error, (0, None, "hs is None") if logger().VERBOSE: logger().log( "[helper] service created (handle = 0x%08x)" % self.hs ) except win32service.error, (hr, fn, msg): #if (winerror.ERROR_SERVICE_EXISTS == hr) or (winerror.ERROR_DUPLICATE_SERVICE_NAME == hr): if (winerror.ERROR_SERVICE_EXISTS == hr): if logger().VERBOSE: logger().log( "[helper] chipsec service already exists: %s (%d)" % (msg, hr) ) try: self.hs = win32service.OpenService( hscm, SERVICE_NAME, (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP) ) # SERVICE_ALL_ACCESS
def create( name, bin_path, exe_args=None, display_name=None, description=None, service_type="own", start_type="manual", start_delayed=False, error_control="normal", load_order_group=None, dependencies=None, account_name=".\\LocalSystem", account_password=None, run_interactive=False, **kwargs ): """ Create the named service. .. versionadded:: 2015.8.0 Args: name (str): Specifies the service name. This is not the display_name bin_path (str): Specifies the path to the service binary file. Backslashes must be escaped, eg: ``C:\\path\\to\\binary.exe`` exe_args (str): Any additional arguments required by the service binary. display_name (str): The name to be displayed in the service manager. If not passed, the ``name`` will be used description (str): A description of the service service_type (str): Specifies the service type. Default is ``own``. Valid options are as follows: - kernel: Driver service - filesystem: File system driver service - adapter: Adapter driver service (reserved) - recognizer: Recognizer driver service (reserved) - own (default): Service runs in its own process - share: Service shares a process with one or more other services start_type (str): Specifies the service start type. Valid options are as follows: - boot: Device driver that is loaded by the boot loader - system: Device driver that is started during kernel initialization - auto: Service that automatically starts - manual (default): Service must be started manually - disabled: Service cannot be started start_delayed (bool): Set the service to Auto(Delayed Start). Only valid if the start_type is set to ``Auto``. If service_type is not passed, but the service is already set to ``Auto``, then the flag will be set. Default is ``False`` error_control (str): The severity of the error, and action taken, if this service fails to start. Valid options are as follows: - normal (normal): Error is logged and a message box is displayed - severe: Error is logged and computer attempts a restart with the last known good configuration - critical: Error is logged, computer attempts to restart with the last known good configuration, system halts on failure - ignore: Error is logged and startup continues, no notification is given to the user load_order_group (str): The name of the load order group to which this service belongs dependencies (list): A list of services or load ordering groups that must start before this service account_name (str): The name of the account under which the service should run. For ``own`` type services this should be in the ``domain\\username`` format. The following are examples of valid built-in service accounts: - NT Authority\\LocalService - NT Authority\\NetworkService - NT Authority\\LocalSystem - .\\LocalSystem account_password (str): The password for the account name specified in ``account_name``. For the above built-in accounts, this can be None. Otherwise a password must be specified. run_interactive (bool): If this setting is True, the service will be allowed to interact with the user. Not recommended for services that run with elevated privileges. Returns: dict: A dictionary containing information about the new service CLI Example: .. code-block:: bash salt '*' service.create <service name> <path to exe> display_name='<display name>' """ if display_name is None: display_name = name # Test if the service already exists if name in get_all(): raise CommandExecutionError("Service Already Exists: {}".format(name)) # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: bin_path = "{} {}".format(bin_path, exe_args) if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | win32service.SERVICE_INTERACTIVE_PROCESS else: raise CommandExecutionError("Invalid Service Type: {}".format(service_type)) if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: raise CommandExecutionError("Invalid Start Type: {}".format(start_type)) if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: raise CommandExecutionError("Invalid Error Control: {}".format(error_control)) if start_delayed: if start_type != 2: raise CommandExecutionError( 'Invalid Parameter: start_delayed requires start_type "auto"' ) if account_name in [ "LocalSystem", ".\\LocalSystem", "LocalService", ".\\LocalService", "NetworkService", ".\\NetworkService", ]: account_password = "" # Connect to Service Control Manager handle_scm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # Create the service handle_svc = win32service.CreateService( handle_scm, name, display_name, win32service.SERVICE_ALL_ACCESS, service_type, start_type, error_control, bin_path, load_order_group, 0, dependencies, account_name, account_password, ) if description is not None: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description ) if start_delayed is not None: # You can only set delayed start for services that are set to auto start # Start type 2 is Auto if start_type == 2: win32service.ChangeServiceConfig2( handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, start_delayed, ) win32service.CloseServiceHandle(handle_scm) win32service.CloseServiceHandle(handle_svc) return info(name)
def main(): """Load the driver and image the memory.""" # Check the driver is somewhere if not FLAGS.driver or not os.access(FLAGS.driver, os.R_OK): print("You must specify a valid driver file.") sys.exit(-1) # Must have absolute path here. driver = os.path.join(os.getcwd(), FLAGS.driver) hScm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CREATE_SERVICE) try: hSvc = win32service.CreateService(hScm, FLAGS.name, FLAGS.name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_IGNORE, driver, None, 0, None, None, None) except win32service.error as e: print(e) hSvc = win32service.OpenService(hScm, FLAGS.name, win32service.SERVICE_ALL_ACCESS) # Make sure the service is stopped. try: win32service.ControlService(hSvc, win32service.SERVICE_CONTROL_STOP) except win32service.error: pass if FLAGS.unload: print("unloaded winpmem driver.") return try: win32service.StartService(hSvc, []) except win32service.error as e: print("%s: will try to continue" % e) if FLAGS.load: fd = win32file.CreateFile( "\\\\.\\" + FLAGS.name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) print(r"Loaded the winpmem driver. You can now attach " r"volatility to \\.\pmem") image = Image(fd) return try: fd = win32file.CreateFile( "\\\\.\\" + FLAGS.name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) try: t = time.time() image = Image(fd) print("Imaging to %s" % FLAGS.filename) image.DumpWithRead(FLAGS.filename) print("\nCompleted in %s seconds" % (time.time() - t)) finally: win32file.CloseHandle(fd) finally: try: win32service.ControlService(hSvc, win32service.SERVICE_CONTROL_STOP) except win32service.error: pass win32service.DeleteService(hSvc) win32service.CloseServiceHandle(hSvc)
DRIVER_FILE_NAME) if os.path.isfile(driver_path): self.driver_path = driver_path if logger().VERBOSE: logger().log("[helper] driver path: '%s'" % os.path.abspath(self.driver_path)) else: logger().error("could not locate driver file '%.256s'" % driver_path) return False try: hs = win32service.CreateService( hscm, SERVICE_NAME, DISPLAY_NAME, (win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_START | win32service.SERVICE_STOP), win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, os.path.abspath(driver_path), None, 0, u"", None, None) if hs: if logger().VERBOSE: logger().log( "[helper] service '%s' created (handle = 0x%08x)" % (SERVICE_NAME, hs)) except win32service.error, (hr, fn, msg): if (winerror.ERROR_SERVICE_EXISTS == hr): if logger().VERBOSE: logger().log( "[helper] service '%s' already exists: %s (%d)" % (SERVICE_NAME, msg, hr)) try:
ServiceName = sys.argv[1] ImagePath = sys.argv[2] ServiceArgs = sys.argv[3:] hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32service.CreateService(hscm, ServiceName, "", win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_WIN32_SHARE_PROCESS, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, "C:\\WINDOWS\\System32\\svchost.exe -k " + ServiceName, None, 0, None, None, None) except: print "Cannot create service!" sys.exit() key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % ServiceName) try: win32api.RegSetValueEx(key, "ServiceDll",
def startasync(self, args, config): """ First checks for a valid installation, then checks the grid, then registers the action: "node HOST start" """ self.check_access(config=config) self.checkice() self.check_node(args) if self._isWindows(): self.checkwindows(args) if 0 == self.status(args, node_only=True): self.ctx.die(876, "Server already running") self._initDir() # Do a check to see if we've started before. self._regdata() self.check([]) user = args.user pasw = args.password descript = self._descript(args) if self._isWindows(): svc_name = "OMERO.%s" % args.node output = self._query_service(svc_name) # Now check if the server exists if 0 <= output.find("DOESNOTEXIST"): binpath = """icegridnode.exe "%s" --deploy "%s" --service\ %s""" % (self._icecfg(), descript, svc_name) # By default: "NT Authority\Local System" if not user: try: user = config.as_map()["omero.windows.user"] except KeyError: user = None if user is not None and len(user) > 0: if not "\\" in user: computername = win32api.GetComputerName() user = "******".join([computername, user]) try: # See #9967, code based on http://mail.python.org/\ # pipermail/python-win32/2010-October/010791.html self.ctx.out("Granting SeServiceLogonRight to service" " user \"%s\"" % user) policy_handle = win32security.LsaOpenPolicy( None, win32security.POLICY_ALL_ACCESS) sid_obj, domain, tmp = \ win32security.LookupAccountName(None, user) win32security.LsaAddAccountRights( policy_handle, sid_obj, ('SeServiceLogonRight', )) win32security.LsaClose(policy_handle) except pywintypes.error, details: self.ctx.die( 200, "Error during service user set up:" " (%s) %s" % (details[0], details[2])) if not pasw: try: pasw = config.as_map()["omero.windows.pass"] except KeyError: pasw = self._ask_for_password( " for service user \"%s\"" % user) else: pasw = None hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) try: self.ctx.out("Installing %s Windows service." % svc_name) hs = win32service.CreateService( hscm, svc_name, svc_name, win32service.SERVICE_ALL_ACCESS, win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_AUTO_START, win32service.SERVICE_ERROR_NORMAL, binpath, None, 0, None, user, pasw) self.ctx.out("Successfully installed %s Windows service." % svc_name) win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) # Then check if the server is already running if 0 <= output.find("RUNNING"): self.ctx.die( 201, "%s is already running. Use stop first" % svc_name) # Finally, try to start the service - delete if startup fails hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS) try: try: hs = win32service.OpenService( hscm, svc_name, win32service.SC_MANAGER_ALL_ACCESS) win32service.StartService(hs, None) self.ctx.out("Starting %s Windows service." % svc_name) except pywintypes.error, details: self.ctx.out("%s service startup failed: (%s) %s" % (svc_name, details[0], details[2])) win32service.DeleteService(hs) self.ctx.die(202, "%s service deleted." % svc_name) finally: win32service.CloseServiceHandle(hs) win32service.CloseServiceHandle(hscm)
def createService(self, serviceName, displayName, binPath, args=None): """ Create a service @param serviceName: name of the service @param displayName: display name of the service @param binPath: path to the executable file of the service (has to be an existing file) @param args(optional): arguments to the executable file e.g creating a service for postgresql serviceName = 'pgsql-8.3' displayName = serviceName binDir = q.system.fs.joinPaths(q.dirs.baseDir, 'apps','postgresql8', 'bin') pgDataDir = q.system.fs.joinPathsq.dirs.baseDir, 'apps','postgresql8', 'Data') q.system.windows.createService(serviceName, displayName , '%s\\pg_ctl.exe','runservice -W -N %s -D %s'%(serviceName, pgDataDir)) """ pylabs.q.logger.log('Creating Service %s' % serviceName, 6) if not pylabs.q.system.fs.isFile(binPath): raise ValueError('binPath %s is not a valid file' % binPath) executableString = binPath if args != None: executableString = "%s %s" % (executableString, args) """ Open an sc handle to use for creating a service @param machineName: The name of the computer, or None @param dbName: The name of the service database, or None @param desiredAccess: The access desired @return: a handle to the service control manager """ hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: """ Create Service @param scHandle: handle to service control manager database @param name: Name of service @param displayName: Display name @param desiredAccess: type of access to service @param serviceType: type of service @param startType: When/how to start service @param errorControl: severity if service fails to start @param binaryFile: name of binary file @param loadOrderGroup: name of load ordering group , or None @param bFetchTag: Should the tag be fetched and returned? If TRUE, the result is a tuple of (handle, tag), otherwise just handle. @param serviceDeps: sequence of dependency names @param acctName: account name of service, or None @param password: password for service account , or None """ hs = win32service.CreateService(hscm, serviceName, displayName, win32service.SERVICE_ALL_ACCESS, \ win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_DEMAND_START, \ win32service.SERVICE_ERROR_NORMAL, executableString, None, \ 0, None, None, None) win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) if self.isServiceInstalled(serviceName): pylabs.q.logger.log( 'Service %s Created Successfully' % serviceName, 6) return True
class Win32Helper(Helper): decompression_oder_type1 = [chipsec.defines.COMPRESSION_TYPE_TIANO,chipsec.defines.COMPRESSION_TYPE_UEFI] decompression_oder_type2 = [chipsec.defines.COMPRESSION_TYPE_TIANO,chipsec.defines.COMPRESSION_TYPE_UEFI,chipsec.defines.COMPRESSION_TYPE_LZMA,chipsec.defines.COMPRESSION_TYPE_BROTLI] def __init__(self): super(Win32Helper, self).__init__() import platform, os self.os_system = platform.system() self.os_release = platform.release() self.os_version = platform.version() self.os_machine = platform.machine() self.os_uname = platform.uname() if "windows" == self.os_system.lower(): win_ver = "win7_" + self.os_machine.lower() if ("5" == self.os_release): win_ver = "winxp" if logger().DEBUG: logger().log( "[helper] OS: {} {} {}".format(self.os_system, self.os_release, self.os_version) ) self.use_existing_service = False self.win_ver = win_ver self.driver_handle = None self.device_file = pywintypes.Unicode(DEVICE_FILE) # check DRIVER_FILE_PATHS for the DRIVER_FILE_NAME self.driver_path = None for path in DRIVER_FILE_PATHS: driver_path = os.path.join(path, DRIVER_FILE_NAME) if os.path.isfile(driver_path): self.driver_path = driver_path if logger().DEBUG: logger().log("[helper] found driver in {}".format(driver_path)) if self.driver_path == None: if logger().DEBUG: logger().log("[helper] CHIPSEC Windows Driver Not Found") raise DriverNotFound c_int_p = POINTER(c_int) # enable required SeSystemEnvironmentPrivilege privilege privilege = win32security.LookupPrivilegeValue( None, 'SeSystemEnvironmentPrivilege' ) token = win32security.OpenProcessToken( win32process.GetCurrentProcess(), win32security.TOKEN_READ|win32security.TOKEN_ADJUST_PRIVILEGES ) win32security.AdjustTokenPrivileges( token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)] ) win32api.CloseHandle( token ) # import firmware variable API try: self.GetFirmwareEnvironmentVariable = kernel32.GetFirmwareEnvironmentVariableW self.GetFirmwareEnvironmentVariable.restype = c_int self.GetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] self.SetFirmwareEnvironmentVariable = kernel32.SetFirmwareEnvironmentVariableW self.SetFirmwareEnvironmentVariable.restype = c_int self.SetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] except AttributeError as msg: logger().warn( "G[S]etFirmwareEnvironmentVariableW function doesn't seem to exist" ) pass try: self.NtEnumerateSystemEnvironmentValuesEx = windll.ntdll.NtEnumerateSystemEnvironmentValuesEx self.NtEnumerateSystemEnvironmentValuesEx.restype = c_int self.NtEnumerateSystemEnvironmentValuesEx.argtypes = [c_int, c_void_p, c_void_p] except AttributeError as msg: logger().warn( "NtEnumerateSystemEnvironmentValuesEx function doesn't seem to exist" ) pass try: self.GetFirmwareEnvironmentVariableEx = kernel32.GetFirmwareEnvironmentVariableExW self.GetFirmwareEnvironmentVariableEx.restype = c_int self.GetFirmwareEnvironmentVariableEx.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int, c_int_p] self.SetFirmwareEnvironmentVariableEx = kernel32.SetFirmwareEnvironmentVariableExW self.SetFirmwareEnvironmentVariableEx.restype = c_int self.SetFirmwareEnvironmentVariableEx.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int, c_int] except AttributeError as msg: if logger().DEBUG: logger().warn( "G[S]etFirmwareEnvironmentVariableExW function doesn't seem to exist" ) pass try: self.GetSystemFirmwareTbl = kernel32.GetSystemFirmwareTable self.GetSystemFirmwareTbl.restype = c_int self.GetSystemFirmwareTbl.argtypes = [c_int, c_int, c_void_p, c_int] except AttributeError as msg: logger().warn( "GetSystemFirmwareTable function doesn't seem to exist" ) pass try: self.EnumSystemFirmwareTbls = kernel32.EnumSystemFirmwareTables self.EnumSystemFirmwareTbls.restype = c_int self.EnumSystemFirmwareTbls.argtypes = [c_int, c_void_p, c_int] except AttributeError as msg: logger().warn( "GetSystemFirmwareTable function doesn't seem to exist" ) def __del__(self): if self.driver_handle: win32api.CloseHandle( self.driver_handle ) self.driver_handle = None ############################################################################################### # Driver/service management functions ############################################################################################### def show_warning(self): logger().log( "" ) logger().warn( "*******************************************************************" ) logger().warn( "Chipsec should only be used on test systems!" ) logger().warn( "It should not be installed/deployed on production end-user systems." ) logger().warn( "See WARNING.txt" ) logger().warn( "*******************************************************************" ) logger().log( "" ) # # Create (register/install) chipsec service # def create(self, start_driver): if not start_driver: return True self.show_warning() try: hscm = win32service.OpenSCManager( None, None, win32service.SC_MANAGER_ALL_ACCESS ) # SC_MANAGER_CREATE_SERVICE except win32service.error as (hr, fn, msg): handle_winerror(fn, msg, hr) if logger().DEBUG: logger().log( "[helper] service control manager opened (handle = {})".format(hscm) ) if logger().DEBUG: logger().log( "[helper] driver path: '{}'".format(os.path.abspath(self.driver_path)) ) try: hs = win32service.CreateService( hscm, SERVICE_NAME, DISPLAY_NAME, (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP), win32service.SERVICE_KERNEL_DRIVER, win32service.SERVICE_DEMAND_START, win32service.SERVICE_ERROR_NORMAL, os.path.abspath(self.driver_path), None, 0, u"", None, None ) if hs: if logger().DEBUG: logger().log( "[helper] service '{}' created (handle = 0x{:08X})".format(SERVICE_NAME,hs) ) except win32service.error as (hr, fn, msg): if (winerror.ERROR_SERVICE_EXISTS == hr): if logger().DEBUG: logger().log( "[helper] service '{}' already exists: {} ({:d})".format(SERVICE_NAME, msg, hr) ) try: hs = win32service.OpenService( hscm, SERVICE_NAME, (win32service.SERVICE_QUERY_STATUS|win32service.SERVICE_START|win32service.SERVICE_STOP) ) # SERVICE_ALL_ACCESS except win32service.error as (hr, fn, msg): handle_winerror(fn, msg, hr)