1+ import ctypes as ctypes
2+ from ctypes import wintypes as wintypes
3+ import os
4+ import sys
5+
6+
7+ kernel32 = ctypes .WinDLL ('kernel32' , use_last_error = True )
8+ advapi32 = ctypes .WinDLL ('advapi32' , use_last_error = True )
9+
10+ ERROR_INVALID_FUNCTION = 0x0001
11+ ERROR_FILE_NOT_FOUND = 0x0002
12+ ERROR_PATH_NOT_FOUND = 0x0003
13+ ERROR_ACCESS_DENIED = 0x0005
14+ ERROR_SHARING_VIOLATION = 0x0020
15+
16+ SE_FILE_OBJECT = 1
17+ OWNER_SECURITY_INFORMATION = 0x00000001
18+ GROUP_SECURITY_INFORMATION = 0x00000002
19+ DACL_SECURITY_INFORMATION = 0x00000004
20+ SACL_SECURITY_INFORMATION = 0x00000008
21+ LABEL_SECURITY_INFORMATION = 0x00000010
22+
23+ _DEFAULT_SECURITY_INFORMATION = (OWNER_SECURITY_INFORMATION |
24+ GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION |
25+ LABEL_SECURITY_INFORMATION )
26+
27+ LPDWORD = ctypes .POINTER (wintypes .DWORD )
28+ SE_OBJECT_TYPE = wintypes .DWORD
29+ SECURITY_INFORMATION = wintypes .DWORD
30+
31+ class SID_NAME_USE (wintypes .DWORD ):
32+ _sid_types = dict (enumerate ('''
33+ User Group Domain Alias WellKnownGroup DeletedAccount
34+ Invalid Unknown Computer Label''' .split (), 1 ))
35+
36+ def __init__ (self , value = None ):
37+ if value is not None :
38+ if value not in self .sid_types :
39+ raise ValueError ('invalid SID type' )
40+ wintypes .DWORD .__init__ (value )
41+
42+ def __str__ (self ):
43+ if self .value not in self ._sid_types :
44+ raise ValueError ('invalid SID type' )
45+ return self ._sid_types [self .value ]
46+
47+ def __repr__ (self ):
48+ return 'SID_NAME_USE(%s)' % self .value
49+
50+ PSID_NAME_USE = ctypes .POINTER (SID_NAME_USE )
51+
52+ class PLOCAL (wintypes .LPVOID ):
53+ _needs_free = False
54+ def __init__ (self , value = None , needs_free = False ):
55+ super (PLOCAL , self ).__init__ (value )
56+ self ._needs_free = needs_free
57+
58+ def __del__ (self ):
59+ if self and self ._needs_free :
60+ kernel32 .LocalFree (self )
61+ self ._needs_free = False
62+
63+ PACL = PLOCAL
64+
65+ class PSID (PLOCAL ):
66+ def __init__ (self , value = None , needs_free = False ):
67+ super (PSID , self ).__init__ (value , needs_free )
68+
69+ def __str__ (self ):
70+ if not self :
71+ raise ValueError ('NULL pointer access' )
72+ sid = wintypes .LPWSTR ()
73+ advapi32 .ConvertSidToStringSidW (self , ctypes .byref (sid ))
74+ try :
75+ return sid .value
76+ finally :
77+ if sid :
78+ kernel32 .LocalFree (sid )
79+
80+ class PSECURITY_DESCRIPTOR (PLOCAL ):
81+ def __init__ (self , value = None , needs_free = False ):
82+ super (PSECURITY_DESCRIPTOR , self ).__init__ (value , needs_free )
83+ self .pOwner = PSID ()
84+ self .pGroup = PSID ()
85+ self .pDacl = PACL ()
86+ self .pSacl = PACL ()
87+ # back references to keep this object alive
88+ self .pOwner ._SD = self
89+ self .pGroup ._SD = self
90+ self .pDacl ._SD = self
91+ self .pSacl ._SD = self
92+
93+ def get_owner (self , system_name = None ):
94+ if not self or not self .pOwner :
95+ raise ValueError ('NULL pointer access' )
96+ return look_up_account_sid (self .pOwner , system_name )
97+
98+ def get_group (self , system_name = None ):
99+ if not self or not self .pGroup :
100+ raise ValueError ('NULL pointer access' )
101+ return look_up_account_sid (self .pGroup , system_name )
102+
103+ def _check_bool (result , func , args ):
104+ if not result :
105+ raise ctypes .WinError (ctypes .get_last_error ())
106+ return args
107+
108+ # msdn.microsoft.com/en-us/library/aa376399
109+ advapi32 .ConvertSidToStringSidW .errcheck = _check_bool
110+ advapi32 .ConvertSidToStringSidW .argtypes = (
111+ PSID , # _In_ Sid
112+ ctypes .POINTER (wintypes .LPWSTR )) # _Out_ StringSid
113+
114+ # msdn.microsoft.com/en-us/library/aa379166
115+ advapi32 .LookupAccountSidW .errcheck = _check_bool
116+ advapi32 .LookupAccountSidW .argtypes = (
117+ wintypes .LPCWSTR , # _In_opt_ lpSystemName
118+ PSID , # _In_ lpSid
119+ wintypes .LPCWSTR , # _Out_opt_ lpName
120+ LPDWORD , # _Inout_ cchName
121+ wintypes .LPCWSTR , # _Out_opt_ lpReferencedDomainName
122+ LPDWORD , # _Inout_ cchReferencedDomainName
123+ PSID_NAME_USE ) # _Out_ peUse
124+
125+ # msdn.microsoft.com/en-us/library/aa446645
126+ advapi32 .GetNamedSecurityInfoW .restype = wintypes .DWORD
127+ advapi32 .GetNamedSecurityInfoW .argtypes = (
128+ wintypes .LPWSTR , # _In_ pObjectName
129+ SE_OBJECT_TYPE , # _In_ ObjectType
130+ SECURITY_INFORMATION , # _In_ SecurityInfo
131+ ctypes .POINTER (PSID ), # _Out_opt_ ppsidOwner
132+ ctypes .POINTER (PSID ), # _Out_opt_ ppsidGroup
133+ ctypes .POINTER (PACL ), # _Out_opt_ ppDacl
134+ ctypes .POINTER (PACL ), # _Out_opt_ ppSacl
135+ ctypes .POINTER (PSECURITY_DESCRIPTOR )) # _Out_opt_ ppSecurityDescriptor
136+
137+ def look_up_account_sid (sid , system_name = None ):
138+ SIZE = 256
139+ name = ctypes .create_unicode_buffer (SIZE )
140+ domain = ctypes .create_unicode_buffer (SIZE )
141+ cch_name = wintypes .DWORD (SIZE )
142+ cch_domain = wintypes .DWORD (SIZE )
143+ sid_type = SID_NAME_USE ()
144+ advapi32 .LookupAccountSidW (system_name , sid , name , ctypes .byref (cch_name ),
145+ domain , ctypes .byref (cch_domain ), ctypes .byref (sid_type ))
146+ return name .value , domain .value , sid_type
147+
148+ def get_file_security (filename , request = _DEFAULT_SECURITY_INFORMATION ):
149+ # N.B. This query may fail with ERROR_INVALID_FUNCTION
150+ # for some filesystems.
151+ pSD = PSECURITY_DESCRIPTOR (needs_free = True )
152+ error = advapi32 .GetNamedSecurityInfoW (filename , SE_FILE_OBJECT , request ,
153+ ctypes .byref (pSD .pOwner ), ctypes .byref (pSD .pGroup ),
154+ ctypes .byref (pSD .pDacl ), ctypes .byref (pSD .pSacl ),
155+ ctypes .byref (pSD ))
156+ if error != 0 :
157+ raise ctypes .WinError (error )
158+ return pSD
159+
160+ def get_author (filename ):
161+ if isinstance (filename , bytes ):
162+ if hasattr (os , 'fsdecode' ):
163+ filename = os .fsdecode (filename )
164+ else :
165+ filename = filename .decode (sys .getfilesystemencoding ())
166+
167+ pSD = get_file_security (filename )
168+ owner_name , owner_domain , owner_sid_type = pSD .get_owner ()
169+ if owner_domain :
170+ owner_name = '{}\\ {}' .format (owner_domain , owner_name )
171+ return owner_name
0 commit comments