none
OpenProcessToken error in managed .NET

    Question


  • Hi

    I'm trying to develop network monitor plugin as part of software
    I'm working for my company. I have reason to use function below.

    Problem is that the same code in C++ works fine, and when rewritten
    to C# it fails. Function OpenProcessToken fails and return ErrorCode=6,
    message is Descriptor is not valid. I don't know how to carry on and
    where the problem lies.

    Then I thought.. it is actually posible to try something like that in
    managed code?

    Thanks for help
    Martin

    [code]
    public void EnableDebugPriv ( )
    {
    UInt32 hToken = 0 ;
    LUID sedebugnameValue = new LUID();
    TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES ();
    TOKEN_PRIVILEGES ptkp = new TOKEN_PRIVILEGES ( );

    UInt32 cp_id = GetCurrentProcessId();

    if ( ! OpenProcessToken( cp_id , TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref hToken ) )
    // if (!OpenProcessToken ( cp_id, TOKEN_ALL_ACCESS, ref hToken ))
    {
    string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
    Console.WriteLine ("OPT() failed, gle = " + GetLastError().ToString () + "\r\n" +
    errorMessage + " \r\nSeDebugPrivilege is not available.");
    return;
    }

    if ( ! LookupPrivilegeValue( null, SE_DEBUG_NAME, ref sedebugnameValue ) )
    {
    string errorMessage = new Win32Exception ( Marshal.GetLastWin32Error ( ) ).Message;
    Console.WriteLine ( "LPT() failed, gle = " + GetLastError ( ).ToString ( ) + "\r\n" +
    errorMessage + " \r\nSeDebugPrivilege is not available." );
    return;
    }

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = sedebugnameValue;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    if (!AdjustTokenPrivileges ( hToken, 0, ref tkp, 1024, ref ptkp, 0 ))
    Console.WriteLine ("ATP() failed, gle = " + GetLastError() +
    " SeDebugPrivilege is not available.");

    CloseHandle( hToken );
    }

    [/code]
    Friday, March 7, 2008 12:11 PM