[python-win32] Vista, _winreg and "Access denied"

Tim Golden mail at timgolden.me.uk
Fri Jun 6 22:09:03 CEST 2008


le dahut wrote:
> To complete this, the application is launched at logon (via Userinit 
> registry key). It rewrites paths to StartMenu and Desktop according to 
> the type of logon (Domain or Local).
> Actually it only rewrites when it is a local session and user IsAnAdmin. 
> The application as to re-run itself using ShellExecute so it has to know 
> if it already runs elevated or not.
> 
> To do this I must use :
> GetTokenInformation(
>                     hToken,
>                     TokenElevationType
>             )
> 
> Unfortunately win32security.TokenElevationType (18) is not available. 
> And GetTokenInformation(hToken, 18) returns
>  >>> win32security.GetTokenInformation(hToken, 18)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> pywintypes.error: (87, 'GetTokenInformation - size call', 'The parameter 
> is incorrect')
> 
> 
> Is it possible to do this using ctypes ? How ?

I'm not running Vista, so I can only go so far with this, but
with the latest pywin32 v211, this works:

<code>
import win32api
import win32security

hToken = win32security.OpenProcessToken (
   win32api.GetCurrentProcess (),
   win32security.TOKEN_QUERY
)
print win32security.GetTokenInformation (
   hToken,
   win32security.TokenType
)

print win32security.TokenElevationType

</code>

That last bit is in there just to show that the
constant is available, even if my XP box can't
make use of it. Assuming that there may be some
kind of bug in the pywin32 code, that last call
could be done in ctypes like this:

<code>
import ctypes
from ctypes.wintypes import HANDLE
import win32api
import win32security

hToken = win32security.OpenProcessToken (
   win32api.GetCurrentProcess (),
   win32security.TOKEN_QUERY
)

token_information = ctypes.c_uint (0)
return_length = ctypes.c_uint (0)

GetTokenInformation = ctypes.windll.advapi32.GetTokenInformation
GetTokenInformation (
   HANDLE (int (hToken)),
   win32security.TokenType,
   ctypes.byref (token_information),
   ctypes.sizeof (token_information),
   ctypes.byref (return_length)
)

print token_information
#
# Should print 1, representing primary token
#
</code>

TJG

[
BTW I consider it a testimony to the developers and
maintainers of the pywin32 and ctypes extensions that:
(a) this code works at all
(b) it worked first time even though I'd typed it
up directly in an email
(c) it remains remarkably readable, in spite of calling
the Windows API directly.
]


More information about the python-win32 mailing list