Last active
February 25, 2016 19:20
-
-
Save haginara/730103979edc08235519 to your computer and use it in GitHub Desktop.
LookupAccountNameA function using ctypes
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
# coding: utf-8 | |
import ctypes | |
from ctypes.wintypes import * | |
LPVOID = ctypes.c_void_p | |
PVOID = LPVOID | |
PSID = PVOID | |
LPDWORD = ctypes.POINTER(DWORD) | |
def ConvertSidtoStringSidA(Sid): | |
# BOOL ConvertSidToStringSid( | |
# __in PSID Sid, | |
# __out LPTSTR *StringSid | |
# ); | |
_ConvertSidToStringSidA = ctypes.windll.advapi32.ConvertSidToStringSidA | |
_ConvertSidToStringSidA.argtypes = [PSID, ctypes.POINTER(LPSTR)] | |
_ConvertSidToStringSidA.restype = bool | |
#_ConvertSidToStringSidA.errcheck = RaiseIfZero | |
pStringSid = LPSTR() | |
success = _ConvertSidToStringSidA(Sid, ctypes.byref(pStringSid)) | |
if not success: | |
error = ctypes.windll.kernel32.GetLastError() | |
raise(ctypes.WinError(error)) | |
try: | |
StringSid = pStringSid.value | |
finally: | |
ctypes.windll.kernel32.LocalFree(pStringSid) | |
return StringSid | |
def LookupAccountNameA(lpSystemName, lpAccountName): | |
# BOOL WINAPI LookupAccountName( | |
# __in_opt LPCTSTR lpSystemName, | |
# __in LPCTSTR lpAccountName, | |
# __out_opt PSID Sid, | |
# __inout LPDWORD cbSid, | |
# __out_opt LPTSTR ReferencedDomainName, | |
# __inout LPDWORD cchReferencedDomainName, | |
# __out PSID_NAME_USE peUse | |
# ); | |
_LookupAccountNameA = ctypes.windll.advapi32.LookupAccountNameA | |
_LookupAccountNameA.argtypes = [LPCSTR, LPCSTR, LPVOID, LPDWORD, LPSTR, LPDWORD, LPDWORD] | |
_LookupAccountNameA.restype = BOOL | |
cbSid = DWORD(0) | |
cchReferencedDomainName = DWORD(0) | |
peUse = DWORD(0) | |
_LookupAccountNameA(lpSystemName, lpAccountName, None, ctypes.byref(cbSid), None, ctypes.byref(cchReferencedDomainName), ctypes.byref(peUse)) | |
error = ctypes.windll.kernel32.GetLastError() | |
if error != 122: | |
raise(ctypes.WinError(error)) | |
sid = ctypes.create_string_buffer('', cbSid.value) | |
psid = ctypes.cast(ctypes.pointer(sid), PSID) | |
lpReferencedDomainName = ctypes.create_string_buffer('', cchReferencedDomainName.value + 1) | |
success = _LookupAccountNameA(lpSystemName, lpAccountName, psid, ctypes.byref(cbSid), lpReferencedDomainName, ctypes.byref(cchReferencedDomainName), ctypes.byref(peUse)) | |
if not success: | |
raise ctypes.WinError() | |
return psid, lpReferencedDomainName.value, peUse.value | |
if __name__ == "__main__": | |
psid, domain, peUse = LookupAccountNameA("", "haginara") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment