Last active
February 12, 2016 00:48
-
-
Save chrono-meter/35bd0df724fa05ecc56a to your computer and use it in GitHub Desktop.
Windows SID on pywin32
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!python3 | |
import struct | |
from win32security import SID, ConvertStringSidToSid, ConvertSidToStringSid | |
from pywintypes import SIDType | |
def CopySID(sid: SIDType) -> SIDType: | |
"""Alternative way: ConvertStringSidToSid(ConvertSidToStringSid(sid)) | |
""" | |
result = SID() | |
result.Initialize(sid.GetSidIdentifierAuthority(), sid.GetSubAuthorityCount()) | |
for i in range(sid.GetSubAuthorityCount()): | |
result.SetSubAuthority(i, sid.GetSubAuthority(i)) | |
return result | |
def ConvertBytesToSid(b: bytes) -> SIDType: | |
# https://blogs.msdn.microsoft.com/oldnewthing/20040315-00/?p=40253 | |
assert 8 <= len(b) and len(b) == 8 + b[1] * 4, 'wrong length, %d bytes' % len(b) | |
assert b[0] == 1, 'Unknown SID revision, %d' % b[0] | |
result = SID() | |
result.Initialize(tuple(b[2:8]), b[1]) | |
for i in range(b[1]): | |
result.SetSubAuthority(i, struct.unpack('<L', b[8 + 4 * i:8 + 4 * (i + 1)])[0]) | |
return result | |
if __name__ == '__main__': | |
# str -> SID -> str | |
assert ConvertSidToStringSid(ConvertStringSidToSid('S-1-5-21-2127521184-1604012920-1887927527-72713')) == 'S-1-5-21-2127521184-1604012920-1887927527-72713' | |
# bytes -> SID -> str | |
assert ConvertSidToStringSid(ConvertBytesToSid(b'\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xA0\x65\xCF\x7E\x78\x4B\x9B\x5F\xE7\x7C\x87\x70\x09\x1C\x01\x00')) == 'S-1-5-21-2127521184-1604012920-1887927527-72713' | |
# str -> SID -> bytes | |
assert bytes(ConvertStringSidToSid('S-1-5-21-2127521184-1604012920-1887927527-72713')) == b'\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xA0\x65\xCF\x7E\x78\x4B\x9B\x5F\xE7\x7C\x87\x70\x09\x1C\x01\x00' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment