Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

win_service failing with permission issue in ansible 2.10.2 (works in 2.9.9) #118

Closed
Kollibri opened this issue Oct 28, 2020 · 11 comments · Fixed by #149
Closed

win_service failing with permission issue in ansible 2.10.2 (works in 2.9.9) #118

Kollibri opened this issue Oct 28, 2020 · 11 comments · Fixed by #149

Comments

@Kollibri
Copy link

SUMMARY

I have a simple task that runs through a list of windows services and disables them. It was working in ansible 2.9.9 without any issue, but in ansible 2.10.2 it is failing on two of the services with the following error:

Task:

- name: disable non-essential services
  win_service:
    name: "{{ item }}"
    state: stopped
    start_mode: disabled
  loop:
    - AxInstSV
    - AJRouter
    - ALG
    - bthserv
    - dmwappushservice
    - MapsBroker
    - lfsvc
    - SharedAccess
    - lltdsvc
    - wlidsvc
    - CDPSvc
    - NcbService
    - PhoneSvc
    - Spooler
    - PrintNotify
    - PcaSvc
    - QWAVE
    - RmSvc
    - SensorDataService
    - SensrSvc
    - SensorService
    - ShellHWDetection
    - ScDeviceEnum
    - SSDPSRV
    - WiaRpc
    - TabletInputService
    - upnphost
    - WalletService
    - Audiosrv
    - AudioEndpointBuilder
    - FrameServer
    - stisvc
    - wisvc
    - icssvc
    - WpnService

Error for the "RmSvc" service:

Unhandled exception while executing module: Cannot convert value "RmSvc" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service ''RmSvc'' (Access is denied, Win32ErrorCode 5 - 0x00000005)"

Error for the "ScDeviceEnum" service:

Unhandled exception while executing module: Cannot convert value "ScDeviceEnum" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service ''ScDeviceEnum'' (Access is denied, Win32ErrorCode 5 - 0x00000005)"

All the other services are disabled without issue.

If I roll back to ansible 2.9.9, it works as expected.

ISSUE TYPE
  • Bug Report
COMPONENT NAME

win_service

ANSIBLE VERSION
ansible 2.10.2
  config file = /builder/.ansible.cfg
  configured module search path = ['/builder/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]
CONFIGURATION
ANSIBLE_FORCE_COLOR(/builder/.ansible.cfg) = True
DEFAULT_CALLBACK_PLUGIN_PATH(/builder/.ansible.cfg) = ['/usr/local/lib/python3.6/site-packages/ansible/plugins/callback']
DEFAULT_LOAD_CALLBACK_PLUGINS(/builder/.ansible.cfg) = True
DEFAULT_STDOUT_CALLBACK(/builder/.ansible.cfg) = yaml
DISPLAY_ARGS_TO_STDOUT(/builder/.ansible.cfg) = False
LOCALHOST_WARNING(/builder/.ansible.cfg) = False
SYSTEM_WARNINGS(/builder/.ansible.cfg) = False
OS / ENVIRONMENT

Tested targeted Windows 2016 and Windows 2019, problem occurs on both.

STEPS TO REPRODUCE

Run the example task below against a basic windows 2016 or windows 2019 server.
It will fail on the services "RmSvc" and "ScDeviceEnum".

- name: disable non-essential services
  win_service:
    name: "{{ item }}"
    state: stopped
    start_mode: disabled
  loop:
    - AxInstSV
    - AJRouter
    - ALG
    - bthserv
    - dmwappushservice
    - MapsBroker
    - lfsvc
    - SharedAccess
    - lltdsvc
    - wlidsvc
    - CDPSvc
    - NcbService
    - PhoneSvc
    - Spooler
    - PrintNotify
    - PcaSvc
    - QWAVE
    - RmSvc
    - SensorDataService
    - SensrSvc
    - SensorService
    - ShellHWDetection
    - ScDeviceEnum
    - SSDPSRV
    - WiaRpc
    - TabletInputService
    - upnphost
    - WalletService
    - Audiosrv
    - AudioEndpointBuilder
    - FrameServer
    - stisvc
    - wisvc
    - icssvc
    - WpnService
EXPECTED RESULTS

Expect all services to be disabled without error.

ACTUAL RESULTS

Errors on services "RmSvc" and "SvDeviceEnum".

    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=AxInstSV)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=AxInstSV)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=AJRouter)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=AJRouter)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=ALG)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=bthserv)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=ALG)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=dmwappushservice)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=bthserv)

	TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=MapsBroker)
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=lfsvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=dmwappushservice)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=SharedAccess)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=MapsBroker)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=lltdsvc)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=wlidsvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=lfsvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=CDPSvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=SharedAccess)

    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=NcbService)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=lltdsvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=PhoneSvc)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=Spooler)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=wlidsvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=PrintNotify)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=NcbService)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=PcaSvc)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=QWAVE)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=PhoneSvc)

	TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    An exception occurred during task execution. To see the full traceback, use -vvv. The error was:    at System.Management.Automation.CommandProcessor.ProcessRecord()
    failed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] (item=RmSvc) => changed=false 
      ansible_loop_var: item
      item: RmSvc
      msg: 'Unhandled exception while executing module: Cannot convert value "RmSvc" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service ''RmSvc'' (Access is denied, Win32ErrorCode 5 - 0x00000005)"'
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=Spooler)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=SensorDataService)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=SensrSvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=PrintNotify)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=SensorService)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=PcaSvc)

	TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=ShellHWDetection)
    An exception occurred during task execution. To see the full traceback, use -vvv. The error was:    at System.Management.Automation.CommandProcessor.ProcessRecord()
    failed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] (item=ScDeviceEnum) => changed=false 
      ansible_loop_var: item
      item: ScDeviceEnum
      msg: 'Unhandled exception while executing module: Cannot convert value "ScDeviceEnum" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service ''ScDeviceEnum'' (Access is denied, Win32ErrorCode 5 - 0x00000005)"'
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=QWAVE)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=SSDPSRV)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    An exception occurred during task execution. To see the full traceback, use -vvv. The error was:    at System.Management.Automation.CommandProcessor.ProcessRecord()
    failed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] (item=RmSvc) => changed=false 
      ansible_loop_var: item
      item: RmSvc
      msg: 'Unhandled exception while executing module: Cannot convert value "RmSvc" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service ''RmSvc'' (Access is denied, Win32ErrorCode 5 - 0x00000005)"'
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=WiaRpc)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=TabletInputService)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=SensorDataService)

	TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=upnphost)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=SensrSvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=WalletService)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=SensorService)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=Audiosrv)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=AudioEndpointBuilder)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=ShellHWDetection)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=FrameServer)

	TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    An exception occurred during task execution. To see the full traceback, use -vvv. The error was:    at System.Management.Automation.CommandProcessor.ProcessRecord()
    failed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] (item=ScDeviceEnum) => changed=false 
      ansible_loop_var: item
      item: ScDeviceEnum
      msg: 'Unhandled exception while executing module: Cannot convert value "ScDeviceEnum" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service ''ScDeviceEnum'' (Access is denied, Win32ErrorCode 5 - 0x00000005)"'
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=stisvc)
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=wisvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=SSDPSRV)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    ok: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=icssvc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=WiaRpc)
    
    TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1] => (item=WpnService)

	TASK [ansible-role-som-ts-configure-services-standard : disable non-essential services] ***
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=TabletInputService)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=upnphost)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=WalletService)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=Audiosrv)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=AudioEndpointBuilder)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=FrameServer)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=stisvc)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=wisvc)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=icssvc)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=WpnService)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=XblAuthManager)
    changed: [ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1] => (item=XblGameSave)
    
    PLAY RECAP *********************************************************************
    ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2016-1 : ok=2    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
    ts-configure-services-standard.0.1.5-pullrequest0363-0004.5025-win2019-1 : ok=2    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0    
@johnbui423
Copy link

johnbui423 commented Nov 5, 2020

I have a similar issue.

Test playbook:

---

- hosts: windows

  tasks:
    - name: Check if a service is installed
      win_service:
        name: SepMasterService

Ansible 2.9.11 results:

$ ansible-playbook test_winservice.yml -v
[...]
TASK [Check if a service is installed] **********************************************************************************************************************
ok: [192.168.0.12] => {"can_pause_and_continue": false, "changed": false, "depended_by": [], "dependencies": ["RpcSs"], "description": "Provides malware and threat protection for Symantec Endpoint Protection", "desktop_interact": false, "display_name": "Symantec Endpoint Protection", "exists": true, "name": "SepMasterService", "path": "\"C:\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\14.2.4814.1101.105\\Bin\\ccSvcHst.exe\" /s \"Symantec Endpoint Protection\" /m \"C:\\Program Files (x86)\\Symantec\\Symantec Endpoint Protection\\14.2.4814.1101.105\\Bin\\sms.dll\" /prefetch:1", "start_mode": "auto", "state": "running", "username": "LocalSystem"}

Ansible 2.10.3 with ansible.windows 1.2.0 results:

$ ansible-playbook test_winservice.yml -vvv
[...]
TASK [Check if a service is installed] **********************************************************************************************************************
[...]
<192.168.0.12> ESTABLISH WINRM CONNECTION FOR USER: ansible on PORT 5986 TO 192.168.0.12
EXEC (via pipeline wrapper)
The full traceback is:
Cannot convert value "SepMasterService" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)"
At line:884 char:46
+ ... ame $name | ForEach-Object { [Ansible.Windows.SCManager.Service]$_.Se ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ForEach-Object], RuntimeException
    + FullyQualifiedErrorId : InvalidCastConstructorException,Microsoft.PowerShell.Commands.ForEachObjectCommand

ScriptStackTrace:
at <ScriptBlock>, <No file>: line 884
at Get-ServiceFromName, <No file>: line 259
at <ScriptBlock>, <No file>: line 884

System.Management.Automation.RuntimeException: Cannot convert value "SepMasterService" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)" ---> System.Management.Automation.PSInvalidCastException: Cannot convert value "SepMasterService" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)" ---> ansible_collections.ansible.windows.plugins.module_utils.SCManager.ServiceManagerException: Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)
   at ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service..ctor(String name, ServiceRights access, SCMRights scmAccess) in c:\Users\ansible\AppData\Local\Temp\wqapb5co.1.cs:line 1178
   at lambda_method(Closure , Object )
   at System.Management.Automation.LanguagePrimitives.ConvertViaConstructor.Convert(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
   --- End of inner exception stack trace ---
   at System.Management.Automation.LanguagePrimitives.ConvertViaConstructor.Convert(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.ScriptBlock.InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, Boolean createLocalScope, Dictionary`2 functionsToDefine, List`1 variablesToDefine, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, Object[] args)
   at System.Management.Automation.ScriptBlock.<>c__DisplayClass57_0.<InvokeWithPipe>b__0()
   at System.Management.Automation.Runspaces.RunspaceBase.RunActionIfNoRunningPipelinesWithThreadCheck(Action action)
   at System.Management.Automation.ScriptBlock.InvokeWithPipe(Boolean useLocalScope, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, Boolean propagateAllExceptionsToTop, List`1 variablesToDefine, Dictionary`2 functionsToDefine, Object[] args)
   at System.Management.Automation.ScriptBlock.InvokeUsingCmdlet(Cmdlet contextCmdlet, Boolean useLocalScope, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Object[] args)
   at Microsoft.PowerShell.Commands.ForEachObjectCommand.ProcessRecord()
   at System.Management.Automation.CommandProcessor.ProcessRecord()
fatal: [192.168.0.12]: FAILED! => {
    "changed": false,
    "msg": "Unhandled exception while executing module: Cannot convert value \"SepMasterService\" to type \"ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service\". Error: \"Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)\""
}

EDIT: Adding results for ScDeviceEnum

Test playbook:

---

- hosts: windows

  tasks:
    - name: Check if a service is installed
      win_service:
        name: ScDeviceEnum

Ansible 2.9.11 results:

$ ansible-playbook test_playbooks/test_winservice.yml -v
[...]
TASK [Check if a service is installed] **********************************************************************************************************************
ok: [192.168.0.12] => {"can_pause_and_continue": false, "changed": false, "depended_by": [], "dependencies": [], "description": "Creates software device nodes for all smart card readers accessible to a given session. If this service is disabled, WinRT APIs will not be able to enumerate smart card readers.", "desktop_interact": false, "display_name": "Smart Card Device Enumeration Service", "exists": true, "name": "ScDeviceEnum", "path": "C:\\WINDOWS\\system32\\svchost.exe -k LocalSystemNetworkRestricted", "start_mode": "manual", "state": "stopped", "username": "LocalSystem"}

Ansible 2.10.3 with ansible.windows 1.2.0 results:

$ ansible-playbook test_winservice.yml -vvv
[...]
TASK [Check if a service is installed] **********************************************************************************************************************
[...]
<192.168.0.12> ESTABLISH WINRM CONNECTION FOR USER: ansible on PORT 5986 TO 192.168.0.12
EXEC (via pipeline wrapper)
The full traceback is:
Cannot convert value "ScDeviceEnum" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service 'ScDeviceEnum' (Access is denied, Win32ErrorCode 5 - 0x00000005)"
At line:884 char:46
+ ... ame $name | ForEach-Object { [Ansible.Windows.SCManager.Service]$_.Se ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ForEach-Object], RuntimeException
    + FullyQualifiedErrorId : InvalidCastConstructorException,Microsoft.PowerShell.Commands.ForEachObjectCommand

ScriptStackTrace:
at <ScriptBlock>, <No file>: line 884
at Get-ServiceFromName, <No file>: line 259
at <ScriptBlock>, <No file>: line 884

System.Management.Automation.RuntimeException: Cannot convert value "ScDeviceEnum" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service 'ScDeviceEnum' (Access is denied, Win32ErrorCode 5 - 0x00000005)" ---> System.Management.Automation.PSInvalidCastException: Cannot convert value "ScDeviceEnum" to type "ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service". Error: "Failed to open service 'ScDeviceEnum' (Access is denied, Win32ErrorCode 5 - 0x00000005)" ---> ansible_collections.ansible.windows.plugins.module_utils.SCManager.ServiceManagerException: Failed to open service 'ScDeviceEnum' (Access is denied, Win32ErrorCode 5 - 0x00000005)
   at ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service..ctor(String name, ServiceRights access, SCMRights scmAccess) in c:\Users\ansible\AppData\Local\Temp\5nqfuhkg.1.cs:line 1178
   at lambda_method(Closure , Object )
   at System.Management.Automation.LanguagePrimitives.ConvertViaConstructor.Convert(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
   --- End of inner exception stack trace ---
   at System.Management.Automation.LanguagePrimitives.ConvertViaConstructor.Convert(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.ScriptBlock.InvokeWithPipeImpl(ScriptBlockClauseToInvoke clauseToInvoke, Boolean createLocalScope, Dictionary`2 functionsToDefine, List`1 variablesToDefine, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, Object[] args)
   at System.Management.Automation.ScriptBlock.<>c__DisplayClass57_0.<InvokeWithPipe>b__0()
   at System.Management.Automation.Runspaces.RunspaceBase.RunActionIfNoRunningPipelinesWithThreadCheck(Action action)
   at System.Management.Automation.ScriptBlock.InvokeWithPipe(Boolean useLocalScope, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Pipe outputPipe, InvocationInfo invocationInfo, Boolean propagateAllExceptionsToTop, List`1 variablesToDefine, Dictionary`2 functionsToDefine, Object[] args)
   at System.Management.Automation.ScriptBlock.InvokeUsingCmdlet(Cmdlet contextCmdlet, Boolean useLocalScope, ErrorHandlingBehavior errorHandlingBehavior, Object dollarUnder, Object input, Object scriptThis, Object[] args)
   at Microsoft.PowerShell.Commands.ForEachObjectCommand.ProcessRecord()
   at System.Management.Automation.CommandProcessor.ProcessRecord()
fatal: [192.168.0.12]: FAILED! => {
    "changed": false,
    "msg": "Unhandled exception while executing module: Cannot convert value \"ScDeviceEnum\" to type \"ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service\". Error: \"Failed to open service 'ScDeviceEnum' (Access is denied, Win32ErrorCode 5 - 0x00000005)\""
}

Let me know if I can provide additional information.

@jborean93
Copy link
Collaborator

Thanks for the report, the module went through a massive rewrite in 2.10 and it looks like we are requesting some permissions we may not actually need for the task at hand. Currently when we open a handle to the service we request the AllAccess rights which seems to be unavailable for certain services.

We will need to fix up the code to be a bit more flexible in this regard as clearly we could achieve the same this with lesser permission in 2.9 and earlier.

@jborean93
Copy link
Collaborator

The PR #149 uses a restricted set of privileged when opening a service. When testing with some of the examples shared here the changes fix the problems reported.

@johnbui423
Copy link

I confirm that with that patch my test playbook works fine with ScDeviceEnum . However, SepMasterService now seems to have a new problem:

TASK [Check if a service is installed]
[...]
<192.168.0.12> ESTABLISH WINRM CONNECTION FOR USER: ansible on PORT 5986 TO 192.168.0.12
EXEC (via pipeline wrapper)
The full traceback is:
Exception calling ".ctor" with "2" argument(s): "Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)"
At line:919 char:5
+     New-Object -TypeName Ansible.Windows.SCManager.Service -ArgumentL ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

ScriptStackTrace:
at <ScriptBlock>, <No file>: line 919
at Get-ServiceFromName, <No file>: line 274
at <ScriptBlock>, <No file>: line 918

System.Management.Automation.MethodInvocationException: Exception calling ".ctor" with "2" argument(s): "Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)" ---> ansible_collections.ansible.windows.plugins.module_utils.SCManager.ServiceManagerException: Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)
   at ansible_collections.ansible.windows.plugins.module_utils.SCManager.Service..ctor(String name, ServiceRights access, SCMRights scmAccess) in c:\Users\ansible\AppData\Local\Temp\2lqzi21g.0.cs:line 1178
   --- End of inner exception stack trace ---
   at System.Management.Automation.DotNetAdapter.AuxiliaryConstructorInvoke(MethodInformation methodInformation, Object[] arguments, Object[] originalArguments)
   at System.Management.Automation.DotNetAdapter.ConstructorInvokeDotNet(Type type, ConstructorInfo[] constructors, Object[] arguments)
   at Microsoft.PowerShell.Commands.NewObjectCommand.CallConstructor(Type type, ConstructorInfo[] constructors, Object[] args)
fatal: [192.168.0.12]: FAILED! => {
    "changed": false,
    "msg": "Unhandled exception while executing module: Exception calling \".ctor\" with \"2\" argument(s): \"Failed to open service 'SepMasterService' (Access is denied, Win32ErrorCode 5 - 0x00000005)\""
}

@jborean93
Copy link
Collaborator

Thanks for testing it out, would you be able to run the following and share your output:

# https://docs.microsoft.com/en-us/windows/win32/services/service-security-and-access-rights
Add-Type -TypeDefinition @'
using System;

namespace SCManager
{
    [Flags]
    public enum AccessMask
    {
        UNKNOWN = 0x00000000,
        SERVICE_ALL_ACCESS = 0x000F01FF,
        SERVICE_CHANGE_CONFIG = 0x00000002,
        SERVICE_ENUMERATE_DEPENDENTS = 0x00000008,
        SERVICE_INTERROGATE = 0x00000080,
        SERVICE_PAUSE_CONTINUE = 0x00000040,
        SERVICE_QUERY_CONFIG = 0x00000001,
        SERVICE_QUERY_STATUS = 0x00000004,
        SERVICE_START = 0x00000010,
        SERVICE_STOP = 0x00000020,
        SERVICE_USER_DEFINED_CONTROL = 0x00000100,
        ACCESS_SYSTEM_SECURITY = 0x01000000,
        DELETE = 0x00010000,
        READ_CONTROL = 0x00020000,
        WRITE_DAC = 0x00040000,
        WRITE_OWNER = 0x00080000,
        STANDARD_RIGHTS_REQUIRED = 0x000F0000,
        STANDARD_RIGHTS_READ = 0x00020000,
        STANDARD_RIGHTS_WRITE = 0x00020000,
        STANDARD_RIGHTS_EXECUTE = 0x00020000,
        GENERIC_READ = STANDARD_RIGHTS_READ |
            SERVICE_QUERY_CONFIG |
            SERVICE_QUERY_STATUS |
            SERVICE_INTERROGATE |
            SERVICE_ENUMERATE_DEPENDENTS,
        GENERIC_WRITE = STANDARD_RIGHTS_WRITE |
            SERVICE_CHANGE_CONFIG,
        GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE |
            SERVICE_START |
            SERVICE_STOP |
            SERVICE_PAUSE_CONTINUE |
            SERVICE_USER_DEFINED_CONTROL,
    }
}
'@

Function Get-ServiceAcl {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [String]
        $Name
    )
    
    $sddl = ((sc.exe sdshow $Name) -join "").Trim()
    $sd = ConvertFrom-SddlString -Sddl $sddl
    $sd.RawDescriptor.DiscretionaryAcl | ForEach-Object {
        $sid = $_.SecurityIdentifier
        try {
            $account = $sid.Translate([Security.Principal.NTAccount])
        } catch [Security.Principal.IdentityNotMappedException] {
            $account = $sid
        }
        
        try {
            $access = [SCManager.AccessMask]$_.AccessMask
        } catch [Management.Automation.PSInvalidCastException] {
            $access = [SCManager.AccessMask]::UNKNOWN
        }
        
        [PSCustomObject]@{
            Account = $account
            Access = $access
            AccessMask = '0x{0:X8}' -f $_.AccessMask
            AceType = $_.AceType
        }
    }
}

Get-ServiceAcl -Name SepMasterService | Format-List

This will get the SDDL of the service and convert it to a human readable output of the DACL of the service. If that fails in any way then sc.exe sdshow SepMasterService by itself would be good to see.

Just to confirm you are trying to just get the info from the service right? The default rights for win_service in this case will be QueryConfig, QueryStatus, EnumerateDependents, ChangeConfig and my guess is you don't have access to ChangeConfig. We could potentially optionally add ChangeConfig if any of the other properties were specified but first I want to verify that will help in your use case.

@johnbui423
Copy link

johnbui423 commented Dec 9, 2020

Sure, here you go:

From administrative and normal command prompt (no difference):

>powershell.exe -ExecutionPolicy Bypass -File test.ps1

Account    : NT AUTHORITY\INTERACTIVE
Access     : SERVICE_USER_DEFINED_CONTROL, GENERIC_READ
AccessMask : 0x0002018D
AceType    : AccessAllowed

Account    : NT AUTHORITY\SERVICE
Access     : SERVICE_USER_DEFINED_CONTROL, GENERIC_READ
AccessMask : 0x0002018D
AceType    : AccessAllowed

Account    : NT AUTHORITY\Authenticated Users
Access     : SERVICE_START, GENERIC_READ
AccessMask : 0x0002009D
AceType    : AccessAllowed

Account    : NT AUTHORITY\SYSTEM
Access     : SERVICE_START, GENERIC_READ
AccessMask : 0x0002009D
AceType    : AccessAllowed

Account    : BUILTIN\Administrators
Access     : SERVICE_START, SERVICE_USER_DEFINED_CONTROL, GENERIC_READ, WRITE_DAC, WRITE_OWNER
AccessMask : 0x000E019D
AceType    : AccessAllowed

Account    : BUILTIN\Power Users
Access     : SERVICE_START, GENERIC_READ
AccessMask : 0x0002009D
AceType    : AccessAllowed

From administrative cmd prompt:

>sc.exe sdshow SepMasterService

D:P(A;;CCLCSWRPLORC;;;SY)(A;;CCLCSWRPLOCRRCWDWO;;;BA)(A;;CCLCSWRPLORC;;;AU)(A;;CCLCSWRPLORC;;;PU)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

From 'normal' command prompt:

D:P(A;;CCLCSWRPLORC;;;SY)(A;;CCLCSWRPLOCRRCWDWO;;;BA)(A;;CCLCSWRPLORC;;;AU)(A;;CCLCSWRPLORC;;;PU)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)

I am running the test playbook listed above:

---

- hosts: windows

  tasks:
    - name: Check if a service is installed
      win_service:
        name: SepMasterService

@jborean93
Copy link
Collaborator

Thanks for the confirmation, looking like the Administrators group does not have SERVICE_CHANGE_CONFIG so that's why we are failing to open the handle to the service. I can probably fix up the code to make that conditional and only add it when any of the other module parameters have been specified. This does mean you won't be able to edit this particular service though, but that's an issue you should have today anyway.

Another alternative that will work for you today is to use win_service_info which is designed to get the stats on a service and not make any changes.

@johnbui423
Copy link

OK, thanks. I agree that win_service_info would actually be a better choice in these specific uses cases. Will try that.

Indeed, I guess it is 'normal' that an endpoint protection service (SepMasterService refers to the Symantec Endpoint Protection client) can indeed not easily be changed.

Perhaps it would be a good idea to translate this into a more user friendly error? In hindsight the information is there ("Access denied"), but I did not understand it. And/or an additional explanation in the win_service documentation on this restriction?

@jborean93
Copy link
Collaborator

The current problem is an issue because we are requesting more rights than we actually need so we can fix that bug. The issue with your SepMasterService is that even the admin doesn't have enough rights to modify the service, the 2.9 behaviour meant that you didn't need the change config right unless you actually made a change. I need to tweak the PR to preserve this behaviour but ultimately if you are just wanting the service info then using win_service_info is the better option going forward.

Perhaps it would be a good idea to translate this into a more user friendly error?

I'm not sure how much more user friendly we could make the error message. If it's saying access is denied then it means exactly that, you don't have the rights to access/modify the service. You wouldn't document that you need delete permissions to delete a file as it's just something that is just implicit knowledge. Also documenting how to view the existing rights is unfortunately not that simple. The code I gave you is not really something we can easily add into an example and is really information that most people don't need to know about.

@johnbui423
Copy link

Perhaps it would be a good idea to translate this into a more user friendly error?

I'm not sure how much more user friendly we could make the error message. If it's saying access is denied then it means exactly that, you don't have the rights to access/modify the service. You wouldn't document that you need delete permissions to delete a file as it's just something that is just implicit knowledge. Also documenting how to view the existing rights is unfortunately not that simple. The code I gave you is not really something we can easily add into an example and is really information that most people don't need to know about.

OK, I indeed do not have a suggestion to make this better, and agree the current error contains the necessary info. Thanks for the help!

@jborean93
Copy link
Collaborator

I was having a look at the module and based on how it is structured it's really difficult to determine if the SERVICE_CHANGE_CONFIG right will be required or not. There are a few options that are always set by default and we can't really determine if a change needs to occur without first opening the service and seeing if we need to make a change in the first place. To keep the rights consistent between the various permutations I think the base rights should stay as SERVICE_CHANGE_CONFIG | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS which convers the basic use cases of this module itself. I've added these rights to the module docs just to make sure we do explicitly state this requirement.

For your particular use case I would recommend using ansible.windows.win_service_info as it designed to require less access rights than this module and just reports the information about service(s) which is what you are looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants