3

I have C# Windows service class:

class MyService : ServiceBase
{
    private void InitializeComponent() {
       //some other code ...
       SafeHandle sHandle = this.ServiceHandle; // I want to do this but this fails.
       SetServiceObjectSecurity(sHandle, secInfo, binaryDescriptor);
       //some more code ...
    }
}

How to convert an IntPtr (like this.ServiceHandle) to a "System.Runtime.InteropServices.SafeHandle"? so that I can use that in the function call "SetServiceObjectSecurity()"? My ultimate aim is to give admin permission to the Service.

Arnoj
  • 79
  • 8
  • I would have thought you wouldn't need to go into pinvoke-land at all. Are you sure the security functions you require are not already in some managed code library? e.g. https://msdn.microsoft.com/en-us/library/system.security.accesscontrol(v=vs.110).aspx – Neil Apr 13 '17 at 09:52
  • 2
    ServiceBase.ServiceHandle is a plain IntPtr, not a SafeHandle. There just wasn't any point in making it a safe handle, a service always has a handle and it remains valid until the service terminates. And there is no cleanup that needs to be safe, it just winks out of existence. Simply fix your pinvoke declaration and make the first argument an IntPtr as well. – Hans Passant Apr 13 '17 at 11:06
  • @Neil: these classes are usable, but do require some effort. In particular, there are no `ServiceSecurity` or `ServiceAccessRule` classes out of the box. These are about 50 lines of code in total (mostly boilerplate). On the plus side, it means you don't have to muck around with security descriptors or unmanaged calls. – Jeroen Mostert Apr 14 '17 at 09:46

1 Answers1

1

Have you tried using SafeHandle.SetHandle(IntPtr handle) as explained here https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.safehandle.sethandle(v=vs.110).aspx and see if that works for you?

EDIT: Since SafeHandle.SetHandle(IntPtr handle) is a protected method, you could create a derived class like this:

public class SafeHandleExtended : SafeHandle
{
    public void SetHandleExtended(IntPtr handle)
    {
        this.SetHandle(handle);
    }

    // .. SafeHandle's abstract methods etc. that you need to implement
}

Although I have not tested this for correctness, so I do not know if this works the way you want it to.

Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65
  • I am not getting access to SetHandle() method from either SafeHandle instance like this: "SafeHandle sHandle; sHandle.SetHandle();" or directly using "SafeHandle.SetHandle();" – Arnoj Apr 13 '17 at 10:37
  • @Arnoj oh I am sorry, I just saw that it is a `protected` method so it is correct that you cannot use it. I am looking up alternatives now. – Thomas Flinkow Apr 13 '17 at 10:39