Author eryksun
Recipients eryksun, paul.moore, steve.dower, tim.golden, yan12125, zach.ware
Date 2015-12-28.15:06:06
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
Testing based on integrity level doesn't require creating a child process. I'm attaching a ctypes-based example that defines a context manager that temporarily sets the integrity level of the current thread's impersonation token. 

To get the impersonation token, I initially tried using ImpersonateSelf / RevertToSelf, but I was unhappy with how it fails for nested contexts since RevertToSelf always switches back to the process token. I opted to instead call OpenThreadToken / OpenProcessToken, DuplicateTokenEx, and SetThreadToken. 

I chose to use the WELL_KNOWN_SID_TYPE enum values to get the label SIDs via CreateWellKnownSid. Note that I omitted the GetLengthSid call when passing the size of the TOKEN_MANDATORY_LABEL to SetTokenInformation. It only needs the size of the primary buffer. The SID it points at is a sized structure (i.e. SubAuthorityCount). 


    import winreg

    subkey = r'SOFTWARE\Microsoft\SystemCertificates\CA'
    access = winreg.KEY_ALL_ACCESS

    >>> key = winreg.OpenKey(HKLM, subkey, 0, access)    
    >>> print(key)
    >>> key.Close()

Repeat with low integrity level:

    >>> with token_integrity_level('low'):
    ...      winreg.OpenKey(HKLM, subkey, 0, access)
    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
    PermissionError: [WinError 5] Access is denied 

A context manager like this could be added to the test helper module that was proposed in issue 22080. It could also add the ability to impersonate with a restricted copy of the process token -- like what UAC creates. psexec -l does this by calling CreateRestrictedToken followed by SetInformationToken for the TokenIntegrityLevel and TokenDefaultDacl.
Date User Action Args
2015-12-28 15:06:08eryksunsetrecipients: + eryksun, paul.moore, tim.golden, zach.ware, steve.dower, yan12125
2015-12-28 15:06:08eryksunsetmessageid: <>
2015-12-28 15:06:08eryksunlinkissue25939 messages
2015-12-28 15:06:08eryksuncreate