def WinStationRename(hServer, oldName, newName): if hServer is None: hServer = win32ts.WTS_CURRENT_SERVER_HANDLE res = winsta.WinStationRenameW(HANDLE(hServer), LPWSTR(oldName), LPWSTR(newName)) if res != 1: raise Win32Error(func="WinStationRename")
def _get_oem_encoding(): """Get Windows OEM codepage.""" hkey = HKEY() windll.advapi32.RegOpenKeyExW( HKEY_LOCAL_MACHINE, LPWSTR(u"SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"), DWORD(0), DWORD(KEY_QUERY_VALUE), byref(hkey)) strval = ctypes.create_unicode_buffer(255) # key HKLM SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage value OEMCP size = DWORD(0) windll.advapi32.RegQueryValueExW(hkey, LPWSTR(u"OEMCP"), DWORD(0), None, None, byref(size)) windll.advapi32.RegQueryValueExW(hkey, LPWSTR(u"OEMCP"), DWORD(0), None, byref(strval), byref(size)) windll.advapi32.RegCloseKey(hkey) return 'cp' + strval.value
def WlanGetProfile(hClientHandle, pInterfaceGuid, profileName): """ The WlanGetProfile function retrieves all information about a specified wireless profile. DWORD WINAPI WlanGetProfile( _In_ HANDLE hClientHandle, _In_ const GUID *pInterfaceGuid, _In_ LPCWSTR strProfileName, _Reserved_ PVOID pReserved, _Out_ LPWSTR *pstrProfileXml, _Inout_opt_ DWORD *pdwFlags, _Out_opt_ PDWORD pdwGrantedAccess ); """ func_ref = wlanapi.WlanGetProfile func_ref.argtypes = [ HANDLE, POINTER(GUID), LPCWSTR, c_void_p, POINTER(LPWSTR), POINTER(DWORD), POINTER(DWORD) ] func_ref.restype = DWORD pdw_granted_access = DWORD() xml = LPWSTR() flags = DWORD(WLAN_PROFILE_GET_PLAINTEXT_KEY) result = func_ref(hClientHandle, byref(pInterfaceGuid), profileName, None, byref(xml), byref(flags), byref(pdw_granted_access)) if result != ERROR_SUCCESS: raise Exception("WlanGetProfile failed.") return xml
def FormatError(code=None): """ A replacement for ctypes.FormtError, but always returns the string encoded in CP1252 (ANSI Code Page). """ if code is None: code = GetLastError() lpMsgBuf = LPWSTR() numChars = _kernel32.FormatMessageW( ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS ), None, code, 0, byref(lpMsgBuf), 0, None ) if numChars == 0: return "No error message available." #raise Exception("FormatMessage failed on 0x%X with 0x%X" % (code & 0xFFFFFFFF, GetLastError())) message = lpMsgBuf.value.strip() _kernel32.LocalFree(lpMsgBuf) return message.encode("CP1252", 'backslashreplace')
def get_final_path(path): """ For a given path, determine the ultimate location of that path. Useful for resolving symlink targets. This functions wraps the GetFinalPathNameByHandle from the Windows SDK. Note, this function fails if a handle cannot be obtained (such as for C:\Pagefile.sys on a stock windows system). Consider using trace_symlink_target instead. """ hFile = CreateFile( path, NULL, # desired access FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, # share mode LPSECURITY_ATTRIBUTES(), # NULL pointer OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL, ) if hFile == INVALID_HANDLE_VALUE: raise WindowsError() buf_size = GetFinalPathNameByHandle(hFile, LPWSTR(), 0, VOLUME_NAME_DOS) handle_nonzero_success(buf_size) buf = create_unicode_buffer(buf_size) result_length = GetFinalPathNameByHandle(hFile, buf, len(buf), VOLUME_NAME_DOS) assert result_length < len(buf) handle_nonzero_success(result_length) handle_nonzero_success(CloseHandle(hFile)) return buf[:result_length]
def detect_autoconfig_url_nt(): if not WinHttpDetectAutoProxyConfigUrl: return None url = LPWSTR() if WinHttpDetectAutoProxyConfigUrl(3, byref(url)): result = str(url.value) GlobalFree(url) return result
def _get(uuid: UUID) -> Path: guid = _GUID(uuid) path = LPWSTR() if _GetFolderPath(byref(guid), 0, HANDLE(0), byref(path)) < 0: raise FileNotFoundError(f"Could not find guid with GUID {uuid}") try: return Path(path.value) finally: _CoTaskMemFree(path)
def get_error_str(error_code): if error_code == 0: return '[0] No error' bufptr = LPWSTR() FormatMessage( (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ALLOCATE_BUFFER), 0, error_code, 0, byref(bufptr), 0, 0) s = bufptr.value.strip() return '[%d] %s' % (error_code, s)
def FormatMessageSystem(message_id, langid=LCID_ENGLISH): from xpra.platform.win32.constants import FORMAT_MESSAGE_ALLOCATE_BUFFER, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS sys_flag = FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS bufptr = LPWSTR() chars = kernel32.FormatMessageW(sys_flag, None, message_id, langid, byref(bufptr), 0, None) if not chars: chars = FormatMessageW(sys_flag, None, message_id, LCID_NEUTRAL, byref(bufptr), 0, None) if not chars: return str(message_id) val = bufptr.value[:chars] LocalFree(bufptr) return val
def CreateFile(filename, access, sharemode, attributes, creation, flags, template_file): # attributes and template_file ignored, kept for backward compat with # win32file return _FileHandle(HANDLE(ctypes.windll.kernel32.CreateFileW( LPWSTR(filename), DWORD(access), DWORD(sharemode), LPSECURITY_ATTRIBUTES(NULL), DWORD(creation), DWORD(flags), HANDLE(NULL))))
def create_item(self, logo, service, username, password, notes): cred_flags = DWORD(0) cred_type = self.CRED_TYPE_GENERIC # I make this the target_name because otherwise users with multiple # accounts on the same service won't be able to create those # credentials. They would end up just overwriting the same # credential for the service each time a new account is added. cred_target_name = LPWSTR(repr((service, username))) cred_comment = LPWSTR('') cred_last_written = FILETIME(0, 0) blob = repr((password, notes)) cred_blob = ctypes.create_unicode_buffer(blob) cred_blob_size = ctypes.sizeof(cred_blob) cred_blob = LPBYTE(cred_blob) cred_persist = self.CRED_PERSIST_LOCAL_MACHINE cred_attribute_count = DWORD(1) logo_value = ctypes.cast(LPWSTR(logo), LPBYTE) cred_attributes = CredAttribute(LPWSTR(service + '_logo'), DWORD(0), ctypes.sizeof(logo_value), logo_value) cred_attributes = ctypes.pointer(cred_attributes) # I keep this alias to mark which credentials are created using # PassMan, the ones that aren't, won't be displayed. cred_target_alias = LPWSTR(self.alias) cred_username = LPWSTR(username) cred = Credential(cred_flags, cred_type, cred_target_name, cred_comment, cred_last_written, cred_blob_size, cred_blob, cred_persist, cred_attribute_count, cred_attributes, cred_target_alias, cred_username) self.advapi32.CredWriteW(ctypes.byref(cred), 0) item = CredItem(service, username) self.collection.items.append(item) return item
def get_short_pathname(native_path): """Return Windows short path name or None if not available.""" try: length = _GetShortPathName(native_path, LPWSTR(0), DWORD(0)) wbuffer = ctypes.create_unicode_buffer(length) _GetShortPathName(native_path, wbuffer, DWORD(length)) except Exception as e: # something went wrong - this should be a WindowsError which is an OSError # but not clear return None else: # can also be None in wbuffer.value if error return wbuffer.value
def WinStationConnect(hServer, SessionID, TargetSessionID, Password="", Wait=False): if hServer is None: hServer = win32ts.WTS_CURRENT_SERVER_HANDLE if SessionID is None: SessionID = win32ts.WTS_CURRENT_SESSION if TargetSessionID is None: TargetSessionID = win32ts.WTS_CURRENT_SESSION res = winsta.WinStationConnectW(HANDLE(hServer), ULONG(SessionID), ULONG(TargetSessionID), LPWSTR(Password or ""), BOOL(Wait)) if res != 1: raise Win32Error(func="WinStationConnect")
def _CreateOrOpenAppContainer(name: str): """Creates or opens a Windows app container. Args: name: Name of the app container. Returns: A `PySID` representing the SID of the AppContainer. Raises: Error: On failure. """ with contextlib.ExitStack() as stack: psid = PSID() try: res = CreateAppContainerProfile(name, name, name, None, 0, ctypes.byref(psid)) if res != winerror.S_OK: raise Error(f"CreateAppContainerProfile returned: {res}") stack.callback(FreeSid, psid) except OSError as e: if e.winerror != winerror.HRESULT_FROM_WIN32( winerror.ERROR_ALREADY_EXISTS): raise res = DeriveAppContainerSidFromAppContainerName( name, ctypes.byref(psid)) if res != winerror.S_OK: raise Error( f"DeriveAppContainerSidFromAppContainerName returned: {res}" ) stack.callback(FreeSid, psid) str_sid = LPWSTR() res = ConvertSidToStringSidW(psid, ctypes.byref(str_sid)) if res == 0: raise Error(f"ConvertSidToStringSidW failed: {res}") stack.callback(LocalFree, str_sid) return win32security.ConvertStringSidToSid(str_sid.value)
def unMapDrive(cls, name): m = LPWSTR(" " * 80) ok = cls._unMapDrive(LPWSTR(name), m) return ok, m.value
def mapDrive(cls, name, path, username, password): m = LPWSTR(" " * 80) ok = cls._mapDrive(LPWSTR(name), LPWSTR(path), LPWSTR(username), LPWSTR(password), m) return ok, m.value