public static extern LONG RegGetKeySecurity( HKEY hKey, // handle to key SECURITY_INFORMATION SecurityInformation, // request PSECURITY_DESCRIPTOR pSecurityDescriptor, // SD ref DWORD lpcbSecurityDescriptor // buffer size );
public static extern DWORD_PTR SHGetFileInfo(LPCTSTR pszPath, DWORD dwFileAttributes, ref SHFILEINFO psfi, UINT cbFileInfo, ShGetFileIconFlags uFlags);
unsafe public static extern HRESULT DwmGetWindowAttribute(HWND hwnd, DwmWindowAttribute dwAttribute, void* pvAttribute, DWORD cbAttribute);
/// <summary> /// Конвертирует значение DWORD в массив байтов /// </summary> /// <param name="Value">Значение</param> /// <returns></returns> public static byte[] ToBytes(DWORD Value) => BitConverter.GetBytes(Value);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE AddErrorRecord( /* [in] */ ERRORINFO *pErrorInfo, /* [in] */ DWORD dwLookupID, /* [in] */ DISPPARAMS *pdispparams, /* [in] */ IUnknown *punkCustomError, /* [in] */ DWORD dwDynamicErrorID) = 0;
public static extern void SetLastError(DWORD dwErrCode);
public RIO_BUFFERID RegisterBuffer([In] PCHAR DataBuffer, [In] DWORD DataLength) => registerBuffer(DataBuffer, DataLength);
public static extern LPVOID MapViewOfFile( HANDLE hFileMappingObject, DWORD dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, IntPtr dwNumBytesToMap);
public static extern HANDLE OpenFileMapping(DWORD dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName);
public static extern unsafe Boolean GetQueuedCompletionStatus(HANDLE CompletionPort, out DWORD lpNumberOfBytes, out ULONG_PTR lpCompletionKey, out OVERLAPPED* lpOverlapped, DWORD dwMilliseconds);
internal static extern unsafe Boolean VirtualFree([In] void* lpAddress, [In] SIZE_T dwSize, DWORD dwFreeType);
virtual HRESULT STDMETHODCALLTYPE GetHelpContext( /* [out] */ DWORD *pdwHelpContext) = 0;
public static extern BOOL GetKernelObjectSecurity( HANDLE Handle, // handle to object SECURITY_INFORMATION RequestedInformation, // request PSECURITY_DESCRIPTOR pSecurityDescriptor, // SD DWORD nLength, // size of SD out DWORD lpnLengthNeeded // required size of buffer );
public static extern BOOL GetSecurityDescriptorControl( PSECURITY_DESCRIPTOR pSecurityDescriptor, out SECURITY_DESCRIPTOR_CONTROL pControl, out DWORD lpdwRevision );
public static extern BOOL DebugActiveProcessStop(DWORD processID);
public static extern BOOL CopySid( DWORD nDestinationSidLength, PSID pDestinationSid, PSID pSourceSid );
public static extern BOOL ContinueDebugEvent(DWORD dwProcessId, DWORD dwThreadId, DWORD dwContinueStatus);
public RIO_CQ CreateCompletionQueue([In] DWORD QueueSize, [In] RIO_NOTIFICATION_COMPLETION NotificationCompletion) => createCompletionQueue(QueueSize, NotificationCompletion);
public static extern DWORD GetFinalPathNameByHandle(HANDLE hFile, LPTSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags);
public BOOL ResizeRequestQueue([In] RIO_RQ RQ, [In] DWORD MaxOutstandingReceive, [In] DWORD MaxOutstandingSend) => resizeRequestQueue(RQ, MaxOutstandingReceive, MaxOutstandingSend);
public static extern DWORD GetModuleFileNameEx(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize);
private static FIELD CreateNewField(BinaryReader br, int index, int fieldOffset, int dataOrDataOffset, GffFieldType fieldType) { FIELD data; switch (fieldType) { case GffFieldType.BYTE: data = new BYTE(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.CHAR: data = new CHAR(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.WORD: data = new WORD(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.SHORT: data = new SHORT(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.DWORD: data = new DWORD(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.INT: data = new INT(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.DWORD64: data = new DWORD64(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.INT64: data = new INT64(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.FLOAT: data = new FLOAT(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.DOUBLE: data = new DOUBLE(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.CExoString: data = new CExoString(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.ResRef: data = new ResRef(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.CExoLocString: data = new CExoLocString(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.VOID: data = new VOID(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.Struct: int lbl_index = br.ReadInt32(); data = new STRUCT(br, br.ReadInt32(), lbl_index); break; case GffFieldType.List: data = new LIST(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.Orientation: data = new Orientation(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.Vector: data = new Vector(br, fieldOffset + dataOrDataOffset * 12); break; case GffFieldType.StrRef: data = new StrRef(br, fieldOffset + dataOrDataOffset * 12); break; default: throw new Exception(string.Format("UNEXPECTED FIELD TYPE \"{0}\", IN STRUCT INDEX \"{1}\"", fieldType, index)); } return(data); }
public static extern DWORD GetProcessImageFileName(HANDLE hProcess, LPTSTR lpImageFileName, DWORD nSize);
public void MakeAbsolute() { if (IsNull) { return; } if (!IsSelfRelative) { return; } DWORD dwSD = 0, dwOwner = 0, dwGroup = 0, dwDacl = 0, dwSacl = 0; BOOL rc = Win32.MakeAbsoluteSD( _secDesc, IntPtr.Zero, ref dwSD, IntPtr.Zero, ref dwDacl, IntPtr.Zero, ref dwSacl, IntPtr.Zero, ref dwOwner, IntPtr.Zero, ref dwGroup); if (Marshal.GetLastWin32Error() != Win32.ERROR_INSUFFICIENT_BUFFER) { Win32.ThrowLastError(); } IntPtr secDesc = Win32.AllocGlobal(dwSD); try { IntPtr pDacl = Win32.AllocGlobal(dwDacl); try { IntPtr pSacl = Win32.AllocGlobal(dwSacl); try { IntPtr pOwner = Win32.AllocGlobal(dwOwner); try { IntPtr pGroup = Win32.AllocGlobal(dwGroup); try { rc = Win32.MakeAbsoluteSD( _secDesc, secDesc, ref dwSD, pDacl, ref dwDacl, pSacl, ref dwSacl, pOwner, ref dwOwner, pGroup, ref dwGroup); Win32.CheckCall(rc); Clear(); _secDesc = secDesc; } catch { Win32.FreeGlobal(pGroup); throw; } } catch { Win32.FreeGlobal(pOwner); throw; } } catch { Win32.FreeGlobal(pSacl); throw; } } catch { Win32.FreeGlobal(pDacl); throw; } } catch { Win32.FreeGlobal(secDesc); throw; } }
public static extern HANDLE OpenProcess(DWORD dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] BOOL bInheritHandle, DWORD dwProcessId);
internal static extern int RegGetValue( HKEY hkey, [MarshalAs(UnmanagedType.LPTStr)] LPCTSTR lpSubKey, [MarshalAs(UnmanagedType.LPTStr)] LPCTSTR lpValue, DWORD dwFlags, out DWORD pdwType, StringBuilder pvData, ref DWORD pcbData);
public static extern BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode);
public static extern BOOL EnumDisplaySettingsEx([MarshalAs(UnmanagedType.LPTStr)] LPCTSTR lpszDeviceName, DWORD iModeNum, [In, Out] DeviceMode lpDevMode, DWORD dwFlags);
public static extern BOOL WaitForDebugEventEx(out DEBUG_EVENT @event, DWORD milliseconds);
public static extern BOOL InitializeSecurityDescriptor(PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD dwRevision);
public static string GetFinalPathNameByHandle(HANDLE handle, DWORD dwFlags) { var pathLength = GetFinalPathNameByHandle(handle, null, 0, dwFlags); NativeMethods.CheckWin32(pathLength > 0); var pathBuilder = new StringBuilder((int)pathLength); pathBuilder.Length = (int)pathLength; NativeMethods.CheckWin32(GetFinalPathNameByHandle(handle, pathBuilder, pathLength, dwFlags) > 0); return pathBuilder.ToString(); }
public static extern BOOL MakeSelfRelativeSD( PSECURITY_DESCRIPTOR pAbsoluteSD, PSECURITY_DESCRIPTOR pSelfRelativeSD, ref DWORD lpdwBufferLength );
public static string GetFinalPathNameByHandle(SafeFileHandle safeHandle, DWORD dwFlags) { Contract.Requires(safeHandle != null); var rawHandle = safeHandle.DangerousGetHandle(); if (safeHandle.IsClosed || safeHandle.IsInvalid) throw new ArgumentException(); var pathLength = GetFinalPathNameByHandle(rawHandle, null, 0, dwFlags); NativeMethods.CheckWin32(pathLength > 0); var pathBuilder = new StringBuilder((int)pathLength); pathBuilder.Length = (int)pathLength; NativeMethods.CheckWin32(GetFinalPathNameByHandle(rawHandle, pathBuilder, pathLength, dwFlags) > 0); return pathBuilder.ToString(); }
public static extern BOOL AdjustTokenPrivileges(HANDLE TokenHandle, [MarshalAs(UnmanagedType.Bool)] BOOL DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, DWORD BufferLength, out TOKEN_PRIVILEGES PreviousState, out DWORD ReturnLength);
public static extern HANDLE OpenProcess(ProcessAccessType dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId);
public static extern BOOL AdjustTokenPrivileges(HANDLE TokenHandle, [MarshalAs(UnmanagedType.Bool)] BOOL DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, DWORD BufferLength, IntPtr PreviousState = default(IntPtr), IntPtr ReturnLength = default(IntPtr));
public BOOL Receive([In] RIO_RQ SocketQueue, [In] ref RIO_BUF pData, [In] ULONG DataBufferCount, [In] DWORD Flags, [In] PVOID RequestContext) => receive(SocketQueue, ref pData, DataBufferCount, Flags, RequestContext);
public static extern BOOL OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, [Out] out HANDLE TokenHandle);
public BOOL ResizeCompletionQueue([In] RIO_CQ CQ, [In] DWORD QueueSize) => resizeCompletionQueue(CQ, QueueSize);
private bool InitInlinedKeys(CryptoKey[] keys, MemoryStream ms) { // Key1 find routine var patKey1 = new Pattern.Byte[][] { Pattern.Transform("B8 ?? ?? 00 00 7E"), Pattern.Transform("BA ?? ?? 00 00 85"), }; long key1Offset = -1; for (int keyIndex = 0; keyIndex < patKey1.Length; keyIndex++) { if (Pattern.Find(_data, patKey1[keyIndex], out key1Offset, ms.Position, ms.Position + 500)) { ms.Position = key1Offset + 1; break; } } if (key1Offset == -1) { Console.WriteLine($"[TargetPE::InitInlinedKeys]: Unable to find key1."); return(false); } DWORD dword = ms.ReadStructure <DWORD>(); keys[0] = new CryptoKey((ms.Position - 4), (ushort)dword.sValue1, (long)Calculator.OffsetToVA((ulong)(ms.Position - 4))); // Key2 find routine // TODO(Gilad): Key got inlined by multiple asm instructions...Will need to implement algorithm to // calculate from instructions region of what's the key value (TryGettingInlinedKey2Value()). keys[1] = new CryptoKey(-1, 0xFFFF, -1); // Key3 find routine var patKey2 = new Pattern.Byte[][] { Pattern.Transform("8D 94 02 ?? ?? 00 00 7C"), Pattern.Transform("B8 ?? ?? 00 00 8D"), Pattern.Transform("B8 ?? ?? 00 00 2B"), }; long key2Offset = -1; for (int keyIndex = 0; keyIndex < patKey2.Length; keyIndex++) { if (Pattern.Find(_data, patKey2[keyIndex], out key2Offset, ms.Position, ms.Position + 700)) { ms.Position = key2Offset + (keyIndex == 0 ? 3 : 1); break; } } if (key2Offset == -1) { Console.WriteLine($"[TargetPE::InitInlinedKeys]: Unable to find key2."); return(false); } dword = ms.ReadStructure <DWORD>(); keys[2] = new CryptoKey((ms.Position - 4), (ushort)dword.sValue1, (long)Calculator.OffsetToVA((ulong)(ms.Position - 4))); return(true); }
public BOOL Send([In] RIO_RQ SocketQueue, [In] ref RIO_BUF pData, [In] DWORD DataBufferCount, [In] DWORD Flags, [In] PVOID RequestContext) => send(SocketQueue, ref pData, DataBufferCount, Flags, RequestContext);
public SendMessageCommand(String className, String windowName, DWORD msg, DWORD wParam, DWORD lParam) { ClassName = className; WindowName = windowName; Msg = (int)msg; WParam = (int)wParam; LParam = (int)lParam; }
private unsafe void UnsafeGetAccountAndDomainName() { // Already done... if (_accountName != null) { return; fixed(byte *psid = _psid) { IntPtr psidPtr = (IntPtr)psid; DWORD cchDLen = 0; DWORD cchALen = 0; SID_NAME_USE nameUse; // First, we ask for the length BOOL rc = Win32.LookupAccountSid( _machineName, psidPtr, null, ref cchALen, null, ref cchDLen, out nameUse); switch (Marshal.GetLastWin32Error()) { case Win32.SUCCESS: throw new ArgumentException("Can't get account name length (unexpected return code from LookupAccountSidW)"); case Win32.ERROR_NONE_MAPPED: _accountName = UnknownAccountName; _domainName = null; break; case Win32.ERROR_INSUFFICIENT_BUFFER: // Then we fetch the strings char[] DStr = new char[cchDLen]; char[] AStr = new char[cchALen]; rc = Win32.LookupAccountSid( _machineName, psidPtr, AStr, ref cchALen, DStr, ref cchDLen, out nameUse); Win32.CheckCall(rc); _domainName = new string(DStr, 0, (int)cchDLen); _accountName = new string(AStr, 0, (int)cchALen); break; default: Win32.ThrowLastError(); break; } if (_domainName == null) { _domainName = ""; } } }
public static extern HANDLE OpenThread(ThreadAccessType dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId);
internal static extern void DsFreeDomainControllerInfo( DWORD InfoLevel, DWORD cInfo, IntPtr pInfo );
public static extern BOOL OpenThreadToken(HANDLE ThreadHandle, DWORD DesiredAccess, BOOL OpenAsSelf, out HANDLE TokenHandle);
protected TExInfo addrOfExport(LONG e_lfanew) { var stream = reader.BaseStream; /* IMAGE_NT_HEADERS */ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680336.aspx stream.Seek(e_lfanew, SeekOrigin.Begin); char[] sig = new char[4]; reader.Read(sig, 0, sig.Length); // A 4-byte signature identifying the file as a PE image // The bytes are "PE\0\0" if (sig[0] != 'P' || sig[1] != 'E' || sig[2] != '\0' || sig[3] != '\0') { throw new PECorruptDataException(); } /* IMAGE_FILE_HEADER */ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680313.aspx byte[] IMAGE_FILE_HEADER = new byte[20]; reader.Read(IMAGE_FILE_HEADER, 0, IMAGE_FILE_HEADER.Length); dynamic ifh = NativeData ._(IMAGE_FILE_HEADER) .t <WORD, WORD>(null, "NumberOfSections") .align <DWORD>(3) .t <WORD, WORD>("SizeOfOptionalHeader") .Raw.Type; /* IMAGE_OPTIONAL_HEADER */ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680339.aspx // move to NumberOfRvaAndSizes if (ifh.SizeOfOptionalHeader == 0xE0) // IMAGE_OPTIONAL_HEADER32 { stream.Seek(0x5C, SeekOrigin.Current); } else if (ifh.SizeOfOptionalHeader == 0xF0) // IMAGE_OPTIONAL_HEADER64 { stream.Seek(0x6C, SeekOrigin.Current); } else { // also known 0 for object files throw new PECorruptDataException($"SizeOfOptionalHeader: {ifh.SizeOfOptionalHeader}"); } DWORD NumberOfRvaAndSizes = reader.ReadUInt32(); // The number of directory entries. /* IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; * * winnt.h Directory Entries: * #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 // Import Directory #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 // Resource Directory * ... */ /* DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] */ // IMAGE_DATA_DIRECTORY struct: https://msdn.microsoft.com/en-us/library/windows/desktop/ms680305.aspx byte[] DIRECTORY_EXPORT = new byte[8]; reader.Read(DIRECTORY_EXPORT, 0, DIRECTORY_EXPORT.Length); dynamic idd = NativeData ._(DIRECTORY_EXPORT) .t <DWORD>("VirtualAddress") .t <DWORD>("Size") .Raw.Type; // to the end of directories stream.Seek(8 * (NumberOfRvaAndSizes - 1), SeekOrigin.Current); return(new TExInfo() { VirtualAddress = idd.VirtualAddress, Size = idd.Size, NumberOfSections = ifh.NumberOfSections, }); }
public static extern BOOL GetTokenInformation( HANDLE TokenHandle, TokenInformationClass TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, out DWORD ReturnLength);
HWND FindHandle(DWORD dwThreadId, string wdwClass, long x, long y) { char buffer[256] = { 0 };
public static extern PDWORD GetSidSubAuthority(PSID pSid, DWORD nSubAuthority);
internal static extern int RegOpenKeyEx( HKEY hKey, [MarshalAs(UnmanagedType.LPTStr)] LPCTSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, out PHKEY phkResult);
public static extern BOOL InitializeAcl(PACL pAcl, DWORD nAclLength, DWORD dwAclRevision);
internal static extern void SetLastError(DWORD dwErrCode);
public static extern BOOL AddAce(PACL pAcl, DWORD dwAceRevision, DWORD dwStartingAceIndex, LPVOID pAceList, DWORD nAceListLength);
public static extern BOOL EnumDisplayDevices([MarshalAs(UnmanagedType.LPTStr)] LPCTSTR lpDevice, DWORD iDevNum, [In, Out] WindowsDisplayDevice lpDisplayDevice, DWORD dwFlags);
public static extern BOOL LookupPrivilegeName( string lpSystemName, [In] ref LUID lpLuid, [Out] char[] lpName, ref DWORD cbName);
HWND FindHandle(DWORD dwThreadId, string wdwClass, long x, long y) { char buffer[256] = {0};
public static extern BOOL GetFileSecurity( LPCTSTR lpFileName, SECURITY_INFORMATION RequestedInformation, PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD nLength, out DWORD lpnLengthNeeded );