Exemplo n.º 1
0
    def uninstall_driver(self):
        hService = None
        pServiceConfig = None
        # dwBytesNeeded = 0
        # cbBufSize = 0

        try:
            self.__stop_driver()

            hService = win32service.OpenService(
                self.hSCManager, 'WINIO', win32service.SERVICE_ALL_ACCESS)

            # If QueryServiceConfig() can not return a correct config, it will
            # throw exception!
            pServiceConfig = win32service.QueryServiceConfig(hService)

            # If service is set to load automatically, don't delete it!
            # dwStartType
            if (pServiceConfig[1] == win32service.SERVICE_DEMAND_START):
                win32service.DeleteService(hService)

        except pywintypes.error as e:
            if e.winerror == EC_SERVICE_NOT_INSTALLED:
                return

            raise
Exemplo n.º 2
0
	def ReloadData(self):
		service = self.GetSelService()
		self.listCtrl.SetRedraw(0)
		self.listCtrl.ResetContent()
		svcs = win32service.EnumServicesStatus(self.scm)
		i = 0
		self.data = []
		for svc in svcs:
			try:
				status = ('Unknown', 'Stopped', 'Starting', 'Stopping', 'Running',
					'Continuing', 'Pausing', 'Paused')[svc[2][1]]
			except:
				status = 'Unknown'
			s = win32service.OpenService(self.scm, svc[0], win32service.SERVICE_ALL_ACCESS)
			cfg = win32service.QueryServiceConfig(s)
			try:
				startup = ('Boot', 'System', 'Automatic', 'Manual', 'Disabled')[cfg[1]]
			except:
				startup = 'Unknown'
			win32service.CloseServiceHandle(s)

			# svc[2][2] control buttons
			pos = self.listCtrl.AddString(str(svc[1]) + '\t' + status + '\t' + startup)
			self.listCtrl.SetItemData(pos, i)
			self.data.append(tuple(svc[2]) + (svc[1], svc[0], ))
			i = i + 1

			if service and service[1] == svc[0]:
				self.listCtrl.SetCurSel(pos)
		self.OnListEvent(self.IDC_LIST, win32con.LBN_SELCHANGE)
		self.listCtrl.SetRedraw(1)
Exemplo n.º 3
0
    def get_services(self, services_loaded):
        scm = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE)
        svcs = win32service.EnumServicesStatus(scm)

        for svc in svcs:
            try:
                sh_query_config = win32service.OpenService(
                    scm, svc[0], win32service.SERVICE_QUERY_CONFIG)
                service_info = win32service.QueryServiceConfig(sh_query_config)
                short_name = svc[0]
                full_path = service_info[3]
                sv = self.check_if_service_already_loaded(
                    short_name, full_path, services_loaded)

                if sv:
                    sv.permissions = self.get_service_permissions(sv)

                if not sv:
                    sk = Service()
                    sk.name = short_name
                    sk.display_name = svc[1]
                    sk.full_path = full_path
                    sk.paths = get_path_info(full_path)
                    sk.permissions = self.get_service_permissions(sv)
                    services_loaded.append(sk)
            except:
                pass

        return services_loaded
Exemplo n.º 4
0
 def enable(self):
     if win32service.QueryServiceConfig(
             self._service_handle)[1] == win32service.SERVICE_DISABLED:
         win32service.ChangeServiceConfig(self._service_handle,
                                          win32service.SERVICE_NO_CHANGE,
                                          win32service.SERVICE_DEMAND_START,
                                          win32service.SERVICE_NO_CHANGE,
                                          None, None, 0, None, None, None,
                                          None)
Exemplo n.º 5
0
 def __get__(self, service, serviceType):
     info = win32service.QueryServiceConfig(service.handle)
     serviceType, startType, errorControl, binaryPathName, loadOrderGroup, \
             tagId, dependencies, name, displayName = info
     service.binaryPathName = str(binaryPathName)
     service.disabled = (startType == win32service.SERVICE_DISABLED)
     service.automatic = (startType == win32service.SERVICE_AUTO_START)
     service.manual = (startType == win32service.SERVICE_DEMAND_START)
     return getattr(service, self.attrName)
Exemplo n.º 6
0
    def get_service_info(self, n):
        if not self.service_info:
            try:
                self.service_info = win32service.QueryServiceConfig(self.get_sh_query_config())
            except:
                pass

        if self.service_info:
            return self.service_info[n]
        else:
            return "[unknown]"
Exemplo n.º 7
0
def QueryService(svc_name):
    """Query service and get its config."""
    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)
    result = None
    try:
        hs = win32serviceutil.SmartOpenService(hscm, svc_name,
                                               win32service.SERVICE_ALL_ACCESS)
        result = win32service.QueryServiceConfig(hs)
        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)

    return result
Exemplo n.º 8
0
    def __CreateFromExistingService(serviceConfigManagerHandle, serviceName):
        serviceHandle = None
        returnConfigs = {}
        try:
            serviceHandle = win32service.OpenService(serviceConfigManagerHandle,
                                                     serviceName.StringValue(),
                                                     win32service.SERVICE_QUERY_CONFIG)
            savedConfigs = win32service.QueryServiceConfig(serviceHandle)
            returnConfigs = {'ServiceName': serviceName}

            for key, value in ServiceConfigurations.indexesOfServiceConfig.iteritems():
                returnConfigs[key] = ConfigurationTypeFactory.CreateConfigurationType(key, savedConfigs[value], True)
        finally:
            if serviceHandle:
                win32service.CloseServiceHandle(serviceHandle)
        return returnConfigs
Exemplo n.º 9
0
    def enable(self):
        hSCM = safe_open_scmanager()

        try:
            hSvc = safe_open_service(hSCM, self.resource.service_name)

            if win32service.QueryServiceConfig(
                    hSvc)[1] == win32service.SERVICE_DISABLED:
                win32service.ChangeServiceConfig(
                    hSvc, win32service.SERVICE_NO_CHANGE,
                    win32service.SERVICE_DEMAND_START,
                    win32service.SERVICE_NO_CHANGE, None, None, 0, None, None,
                    None, None)
            win32service.CloseServiceHandle(hSvc)
        except win32api.error, details:
            raise Fail("Error enabling service {0}: {1}".format(
                self.resource.service_name, details.winerror))
Exemplo n.º 10
0
	def OnInitDialog(self):
		cfg = win32service.QueryServiceConfig(self.service)
		self.GetDlgItem(self.IDC_BOOT + cfg[1]).SetCheck(1)

		status = win32service.QueryServiceStatus(self.service)
		if ((status[0] & win32service.SERVICE_KERNEL_DRIVER) or
				(status[0] & win32service.SERVICE_FILE_SYSTEM_DRIVER)):
			# driver
			self.GetDlgItem(self.IDC_LABEL).SetWindowText('Device:')
		else:
			# service
			self.GetDlgItem(self.IDC_LABEL).SetWindowText('Service:')
			self.GetDlgItem(self.IDC_BOOT).EnableWindow(0)
			self.GetDlgItem(self.IDC_SYSTEM).EnableWindow(0)
		self.GetDlgItem(self.IDC_DEVICE).SetWindowText(str(self.name))

		return dialog.Dialog.OnInitDialog(self)
Exemplo n.º 11
0
 def query_service(self):
     """
 Query additional information about the service and store them into the
 object.
 """
     hService = winsvc.OpenService(self.scm_handle, self.ServiceName,
                                   winsvc.SERVICE_QUERY_CONFIG)
     lpServiceConfig = winsvc.QueryServiceConfig(hService)
     winsvc.CloseServiceHandle(hService)
     self.ServiceType = lpServiceConfig[0]
     self.StartType = lpServiceConfig[1]
     self.ErrorControl = lpServiceConfig[2]
     self.BinaryPathName = lpServiceConfig[3]
     self.LoadOrderGroup = lpServiceConfig[4]
     self.TagId = lpServiceConfig[5]
     self.Dependencies = lpServiceConfig[6]
     self.ServiceStartName = lpServiceConfig[7]
     self.DisplayName = lpServiceConfig[8]
Exemplo n.º 12
0
    def ConfigDict(self, service_name):
        config_dict = {}
        handle = self.makehandleService(service_name)
        try:
            config_list = win32service.QueryServiceConfig(handle)
            #debug(config_list = config_list)
        except:
            # debug(ERROR = traceback.format_exc())
            config_list = ()

        if config_list:
            config_dict.update({
                'name': service_name,
                'start': self.service_state.get(config_list[1]),
                'dependencies': config_list[6],
                'user': config_list[7],
                'display_name': config_list[8],
            })
        #debug(config_dict = config_dict)
        return config_dict
Exemplo n.º 13
0
    def svcStart(self, svc_name, svc_arg=None, machine=None):
        accessSCM = win32con.GENERIC_READ
        hscm = win32service.OpenSCManager(None, None, accessSCM)
        try:
            shandle = win32service.OpenService(hscm, svc_name, accessSCM)
            try:
                (service_type, start_type, error_control, path,
                 load_order_group, tag_id, dependencies, start_name,
                 display_name) = win32service.QueryServiceConfig(shandle)
                for service_name in dependencies:
                    if (self.svcStatus(service_name, machine) == STOPPED):
                        self.logger.info(
                            "Starting {} service because {} depends on it.".
                            format(service_name, svc_name))
                        self.svcStart(service_name)
            finally:
                win32service.CloseServiceHandle(shandle)
        finally:
            win32service.CloseServiceHandle(hscm)

        if not svc_arg is None:
            if isinstance(svc_arg, str):
                # win32service expects a list of string arguments
                svc_arg = [svc_arg]

        win32serviceutil.StartService(svc_name, svc_arg, machine)
        status = self.svcStatus(svc_name, machine)
        i = 0
        while status == STARTING:
            time.sleep(1)
            status = self.svcStatus(svc_name, machine)
            i = i + 1
            if i > 60:
                self.logger.info("Timeout starting %s service" % svc_name)
                raise TimeoutError

        return status
Exemplo n.º 14
0
    def analyze_all_services(self):
        try:

            df = pd.DataFrame(columns=[
                "Short Name", "Long Name", "Service Type", "Start Type",
                "Dependencies", "Full Command", "Bin Path", "ACLS",
                "Vulnerable Permissions", "Can Edit Binpath",
                "Is Unquoted Path"
            ])
            total_services = 0  # Total Number of services
            vuln_perms = 0  # Total number of services that have suspect/vulnerable permissions (ACLS)
            vuln_conf = 0  # Total number of services where we can change the binpath as a standard user.
            vuln_unquote = 0  # Total number of services with unquoted service paths
            vuln_services = [
            ]  # List of all services tht can potentially be exploited

            service_config_manager = win32service.OpenSCManager(
                "",
                None,
                win32service.SC_MANAGER_CONNECT
                | win32service.SC_MANAGER_ENUMERATE_SERVICE
                | win32service.SC_MANAGER_QUERY_LOCK_STATUS
                | win32service.SERVICE_QUERY_CONFIG,
            )
            service_manager = win32service.OpenSCManager(
                None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE)

            # Hacky way to get the total number of services
            for service in win32service.EnumServicesStatus(
                    service_manager,
                    win32service.SERVICE_WIN32,
                    win32service.SERVICE_STATE_ALL,
            ):
                total_services += 1

            pbar = tqdm(total=total_services)
            pbar.set_description("Analyzing Services")
            # For each service, enumerate its values and check ACL's / binpath edits.
            for service in win32service.EnumServicesStatus(
                    service_manager,
                    win32service.SERVICE_WIN32,
                    win32service.SERVICE_STATE_ALL,
            ):

                acls = ""  # Holds all ACL's obtained from filepaths.py
                conf_check = False  # Can we edit the current services configuration?
                unquote_check = False  # Check for unquoted service paths

                access = win32service.OpenService(
                    service_config_manager,
                    service[0],
                    win32service.SERVICE_QUERY_CONFIG,
                )
                config = win32service.QueryServiceConfig(access)

                service_short_name = str(service[0]).replace('"', "").strip()
                service_long_name = str(service[1]).replace('"', "").strip()
                service_type = self.__access_from_int(config[0])
                service_start_type = self.__windows_objects.START_TYPE[
                    config[2]]
                service_dependencies = str(config[6]).replace('"', "").strip()
                raw_bin_path = str(config[3])
                cleaned_bin_path = str(config[3]).replace('"', "").strip()

                # find and cleanup the bin path due to CLI argument being present.
                service_bin_path = re.findall(self.__windows_file_path,
                                              cleaned_bin_path)[0]

                service_bin_path = os.path.join(
                    service_bin_path[0] + ":\\",
                    service_bin_path[1] + service_bin_path[2])

                # Analyze ACL's for the Bin Path:
                #acl_list = fp.get_acl_list_return(service_bin_path)
                acl_dict = self.__perms.get_file_path_acl(service_bin_path)
                acl_list = acl_dict["acls"]
                for i, acl in enumerate(acl_list):

                    if i == (len(acl_list) - 1):
                        acls += acl
                    else:
                        acls += f"{acl}\n"

                # Check for bad ACL permissions:
                suspect_service = self.__analysis.analyze_acls_from_list(
                    acl_list)
                if suspect_service:
                    vuln_perms += 1
                    if service_short_name not in vuln_services:
                        vuln_services.append(service_short_name)

                # Check if we can change the config:
                try:
                    test = win32service.OpenService(
                        service_config_manager,
                        service[0],
                        win32service.SERVICE_CHANGE_CONFIG,
                    )
                    conf_check = True
                    vuln_conf += 1
                    if service_short_name not in vuln_services:
                        vuln_services.append(service_short_name)
                except:
                    pass

                # Check for unquoted service paths:
                if ("program files" in raw_bin_path.lower()
                        and '"' not in raw_bin_path.lower()):
                    unquote_check = True
                    vuln_unquote += 1
                    if service_short_name not in vuln_services:
                        vuln_services.append(service_short_name)

                # Write the final data to a file.

                data = {
                    "Short Name": service_short_name,
                    "Long Name": service_long_name,
                    "Service Type": f"{config[0]} {service_type}",
                    "Start Type": service_start_type,
                    "Dependencies": service_dependencies,
                    "Full Command": cleaned_bin_path,
                    "Bin Path": service_bin_path,
                    "ACLS": acls,
                    "Vulnerable Permissions": suspect_service,
                    "Can Edit Binpath": conf_check,
                    "Is Unquoted Path": unquote_check
                }

                df = df.append(data, ignore_index=True)
                pbar.update(1)

            return {
                "name": "Service Analysis",
                "description":
                "Analyze all services for weak ACLs, ability to change bin-path, and unquoted paths",
                "dataframe": df,
                "total_services": total_services,
                "vuln_perms": vuln_perms,
                "vuln_conf": vuln_conf,
                "vuln_unquote": vuln_unquote,
                "vuln_services": vuln_services
            }

        except Exception as e:
            self.__print_exception()
            exit(1)
Exemplo n.º 15
0
References:             
Prerequisites:          []
Development Status:     3 - Alpha, 5 - Production/Stable
Environment:            Console
Intended Audience:      System Administrators, Developers, End Users/Desktop
License:                Freeware, Freely Distributable
Natural Language:       English, Chinese (Simplified)
Operating System:       POSIX :: Linux, Microsoft :: Windows
Programming Language:   Python :: 2.6
Programming Language:   Python :: 2.7
Topic:                  Utilities
 """
import sys

import pywintypes
import win32service

try:
    scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
except pywintypes.error as e:
    for msg in (x.decode('gbk') if isinstance(x, str) else x for x in e):
        print(msg),
    sys.exit(1)
service_handle = win32service.OpenService(scm, 'XLServicePlatform', win32service.SC_MANAGER_ALL_ACCESS)

# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_status?redirectedfrom=MSDN
dwCurrentState = win32service.QueryServiceStatus(service_handle)[1]

currentServiceConfig = win32service.QueryServiceConfig(service_handle)
# http://timgolden.me.uk/pywin32-docs/win32service__ChangeServiceConfig_meth.html
Exemplo n.º 16
0
def folders_for_midax_services():
    resume = 0
    accessSCM = win32con.GENERIC_READ
    accessSrv = win32service.SC_MANAGER_ALL_ACCESS

    #Open Service Control Manager
    hscm = win32service.OpenSCManager(None, None, accessSCM)
    try:
        #Enumerate Service Control Manager DB
        typeFilter = win32service.SERVICE_WIN32
        stateFilter = win32service.SERVICE_STATE_ALL
        disabled = win32service.SERVICE_DISABLED

        statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)
        

        for (short_name, desc, status) in statuses:
            if desc.lower().startswith('midax'):
                shandle = win32service.OpenService(hscm, short_name, accessSCM)
                try:
                    (service_type, start_type, error_control, path, load_order_group, tag_id, dependencies, start_name, display_name) = win32service.QueryServiceConfig(shandle)
                    if '/SM' in path:
                        path = path.split('/SM', 1)[0] 
                    
                    path = path.strip('"')
                    
                    if start_type == disabled:
                        continue
                    
                    path = os.path.dirname(os.path.normcase(os.path.normpath(path)))                  

                    if os.path.isdir(path):                        
                        yield path, short_name
                finally:
                    win32service.CloseServiceHandle(shandle)
    finally:
        win32service.CloseServiceHandle(hscm)
Exemplo n.º 17
0
def info(name):
    '''
    Get information about a service on the system

    Args:
        name (str): The name of the service. This is not the display name. Use
            ``get_service_name`` to find the service name.

    Returns:
        dict: A dictionary containing information about the service.

    CLI Example:

    .. code-block:: bash

        salt '*' service.info spooler
    '''
    try:
        handle_scm = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_CONNECT)
    except pywintypes.error as exc:
        raise CommandExecutionError('Failed to connect to the SCM: {0}'.format(
            exc[2]))

    try:
        handle_svc = win32service.OpenService(
            handle_scm, name, win32service.SERVICE_ENUMERATE_DEPENDENTS
            | win32service.SERVICE_INTERROGATE
            | win32service.SERVICE_QUERY_CONFIG
            | win32service.SERVICE_QUERY_STATUS)
    except pywintypes.error as exc:
        raise CommandExecutionError('Failed To Open {0}: {1}'.format(
            name, exc[2]))

    try:
        config_info = win32service.QueryServiceConfig(handle_svc)
        status_info = win32service.QueryServiceStatusEx(handle_svc)

        try:
            description = win32service.QueryServiceConfig2(
                handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION)
        except pywintypes.error:
            description = 'Failed to get description'

        delayed_start = win32service.QueryServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO)
    finally:
        win32service.CloseServiceHandle(handle_scm)
        win32service.CloseServiceHandle(handle_svc)

    ret = dict()
    try:
        sid = win32security.LookupAccountName(
            '', 'NT Service\\{0}'.format(name))[0]
        ret['sid'] = win32security.ConvertSidToStringSid(sid)
    except pywintypes.error:
        ret['sid'] = 'Failed to get SID'

    ret['BinaryPath'] = config_info[3]
    ret['LoadOrderGroup'] = config_info[4]
    ret['TagID'] = config_info[5]
    ret['Dependencies'] = config_info[6]
    ret['ServiceAccount'] = config_info[7]
    ret['DisplayName'] = config_info[8]
    ret['Description'] = description
    ret['Status_ServiceCode'] = status_info['ServiceSpecificExitCode']
    ret['Status_CheckPoint'] = status_info['CheckPoint']
    ret['Status_WaitHint'] = status_info['WaitHint']
    ret['StartTypeDelayed'] = delayed_start

    flags = list()
    for bit in SERVICE_TYPE:
        if isinstance(bit, int):
            if config_info[0] & bit:
                flags.append(SERVICE_TYPE[bit])

    ret['ServiceType'] = flags if flags else config_info[0]

    flags = list()
    for bit in SERVICE_CONTROLS:
        if status_info['ControlsAccepted'] & bit:
            flags.append(SERVICE_CONTROLS[bit])

    ret['ControlsAccepted'] = flags if flags else status_info[
        'ControlsAccepted']

    try:
        ret['Status_ExitCode'] = SERVICE_ERRORS[status_info['Win32ExitCode']]
    except KeyError:
        ret['Status_ExitCode'] = status_info['Win32ExitCode']

    try:
        ret['StartType'] = SERVICE_START_TYPE[config_info[1]]
    except KeyError:
        ret['StartType'] = config_info[1]

    try:
        ret['ErrorControl'] = SERVICE_ERROR_CONTROL[config_info[2]]
    except KeyError:
        ret['ErrorControl'] = config_info[2]

    try:
        ret['Status'] = SERVICE_STATE[status_info['CurrentState']]
    except KeyError:
        ret['Status'] = status_info['CurrentState']

    return ret
Exemplo n.º 18
0
    def is_resolution_ok(self):

        try:
            height = None
            width = None
            scm = win32service.OpenSCManager('localhost', None, win32service.SC_MANAGER_CONNECT)
            s = win32service.OpenService(scm, 'Alyvix Background Service', win32service.SERVICE_QUERY_CONFIG)
            cfg = win32service.QueryServiceConfig(s)
            config_file = os.path.dirname(str(cfg[3]).replace("\"","")) + os.sep + "AlyvixBackgroundService.exe.config"

            lines = []
            with open(str(config_file)) as f:
                lines = f.readlines()

            for line in lines:
                if "height" in line:
                    height = line.replace("<add key=\"height\" value=\"","")
                    height = height.replace("\"/>", "")
                    height = height.replace(" ","")
                    height = height.replace("\t","")
                    height = int(height)

                if "width" in line:
                    width = line.replace("<add key=\"width\" value=\"", "")
                    width = width.replace("\"/>", "")
                    width = width.replace(" ", "")
                    width = width.replace("\t", "")
                    width = int(width)

            if height is not None and width is not None:
                hwnd = win32gui.GetDesktopWindow()
                wDC = win32gui.GetWindowDC(hwnd)
                dcObj = win32ui.CreateDCFromHandle(wDC)

                HORZRES = 8
                VERTRES = 10

                DESKTOPHORZRES = 118
                DESKTOPVERTRES = 117

                v_HORZRES = dcObj.GetDeviceCaps(HORZRES)
                v_VERTRES = dcObj.GetDeviceCaps(VERTRES)

                v_DESKTOPHORZRES = dcObj.GetDeviceCaps(DESKTOPHORZRES)
                v_DESKTOPVERTRES = dcObj.GetDeviceCaps(DESKTOPVERTRES)

                dcObj.DeleteDC()

                scaling = round(float(v_DESKTOPVERTRES) / float(v_VERTRES), 2)  # two decimal

                #if scaling >= 1.0:
                #    return False

                if width == 1366: #fix for the windows 7 bug with rdp and 1366x768 res
                    if v_DESKTOPHORZRES >= 1364 and v_DESKTOPHORZRES <= 1368\
                            and height == v_DESKTOPVERTRES:
                        return True
                    else:
                        return False
                elif height != v_DESKTOPVERTRES or width != v_DESKTOPHORZRES:
                    return False
        except:
            pass

        return True
Exemplo n.º 19
0
 def get_service_username(self, service_name):
     LOG.debug('Getting service username: %s', service_name)
     with self._get_service_handle(service_name) as hs:
         cfg = win32service.QueryServiceConfig(hs)
         return cfg[7]
Exemplo n.º 20
0
def modify(
    name,
    bin_path=None,
    exe_args=None,
    display_name=None,
    description=None,
    service_type=None,
    start_type=None,
    start_delayed=None,
    error_control=None,
    load_order_group=None,
    dependencies=None,
    account_name=None,
    account_password=None,
    run_interactive=None,
):
    # pylint: disable=anomalous-backslash-in-string
    """
    Modify a service's parameters. Changes will not be made for parameters that
    are not passed.

    .. versionadded:: 2016.11.0

    Args:
        name (str):
            The name of the service. Can be found using the
            ``service.get_service_name`` function

        bin_path (str):
            The path to the service executable. Backslashes must be escaped, eg:
            ``C:\\path\\to\\binary.exe``

        exe_args (str):
            Any arguments required by the service executable

        display_name (str):
            The name to display in the service manager

        description (str):
            The description to display for 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: 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.

        error_control (str):
            The severity of the error, and action taken, if this service fails
            to start. Valid options are as follows:

            - 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 of changes made

    CLI Example:

    .. code-block:: bash

        salt '*' service.modify spooler start_type=disabled

    """
    # pylint: enable=anomalous-backslash-in-string
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681988(v-vs.85).aspx
    handle_scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT)

    try:
        handle_svc = win32service.OpenService(
            handle_scm,
            name,
            win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG,
        )
    except pywintypes.error as exc:
        raise CommandExecutionError("Failed To Open {}: {}".format(name, exc.strerror))

    config_info = win32service.QueryServiceConfig(handle_svc)

    changes = dict()

    # Input Validation
    if bin_path is not None:
        # 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)
        changes["BinaryPath"] = bin_path

    if service_type is not None:
        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))
    else:
        if run_interactive is True:
            service_type = config_info[0] | win32service.SERVICE_INTERACTIVE_PROCESS
        elif run_interactive is False:
            service_type = config_info[0] ^ win32service.SERVICE_INTERACTIVE_PROCESS
        else:
            service_type = win32service.SERVICE_NO_CHANGE

    if service_type is not win32service.SERVICE_NO_CHANGE:
        flags = list()
        for bit in SERVICE_TYPE:
            if isinstance(bit, int) and service_type & bit:
                flags.append(SERVICE_TYPE[bit])

        changes["ServiceType"] = flags if flags else service_type

    if start_type is not None:
        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))
        changes["StartType"] = SERVICE_START_TYPE[start_type]
    else:
        start_type = win32service.SERVICE_NO_CHANGE

    if error_control is not None:
        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)
            )
        changes["ErrorControl"] = SERVICE_ERROR_CONTROL[error_control]
    else:
        error_control = win32service.SERVICE_NO_CHANGE

    if account_name is not None:
        changes["ServiceAccount"] = account_name
    if account_name in ["LocalSystem", "LocalService", "NetworkService"]:
        account_password = ""

    if account_password is not None:
        changes["ServiceAccountPassword"] = "******"

    if load_order_group is not None:
        changes["LoadOrderGroup"] = load_order_group

    if dependencies is not None:
        changes["Dependencies"] = dependencies

    if display_name is not None:
        changes["DisplayName"] = display_name

    win32service.ChangeServiceConfig(
        handle_svc,
        service_type,
        start_type,
        error_control,
        bin_path,
        load_order_group,
        0,
        dependencies,
        account_name,
        account_password,
        display_name,
    )

    if description is not None:
        win32service.ChangeServiceConfig2(
            handle_svc, win32service.SERVICE_CONFIG_DESCRIPTION, description
        )
        changes["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
        # Start type -1 is no change
        if (start_type == -1 and config_info[1] == 2) or start_type == 2:
            win32service.ChangeServiceConfig2(
                handle_svc,
                win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
                start_delayed,
            )
            changes["StartTypeDelayed"] = start_delayed
        else:
            changes["Warning"] = 'start_delayed: Requires start_type "auto"'

    win32service.CloseServiceHandle(handle_scm)
    win32service.CloseServiceHandle(handle_svc)

    return changes
Exemplo n.º 21
0
                        self.ctx.out(io2[0].strip())
                    else:
                        self.ctx.err("UNKNOWN!")
            if self._isWindows():
                # Print the OMERO server Windows service details
                hscm = win32service.OpenSCManager(
                    None, None, win32service.SC_MANAGER_ALL_ACCESS)
                services = win32service.EnumServicesStatus(hscm)
                omesvcs = tuple((sname, fname)
                                for sname, fname, status in services
                                if "OMERO" in fname)
                for sname, fname in omesvcs:
                    item("Server", fname)
                    hsc = win32service.OpenService(
                        hscm, sname, win32service.SC_MANAGER_ALL_ACCESS)
                    logonuser = win32service.QueryServiceConfig(hsc)[7]
                    if win32service.QueryServiceStatus(hsc)[1] == \
                            win32service.SERVICE_RUNNING:
                        self.ctx.out("active (running as %s)" % logonuser)
                    else:
                        self.ctx.out("inactive")
                    win32service.CloseServiceHandle(hsc)
                win32service.CloseServiceHandle(hscm)

            # List SSL & TCP ports of deployed applications
            self.ctx.out("")
            p = self.ctx.popen(self._cmd("-e", "application list"))  # popen
            rv = p.wait()
            io = p.communicate()
            if rv != 0:
                self.ctx.out("Cannot list deployed applications.")