Share the main implementation code for the C operation memory accessor method
- 2020-05-19 05:32:54
- OfStack
using System.Runtime.InteropServices;
using System.Text;
publicclass Function
{
//C# Manipulate memory accessors
publicstaticbyte PtrToByte( int Ptr )
{
byte b = Marshal.ReadByte( ( IntPtr ) Ptr );
return b;
}
publicstaticchar PtrToChar( int Ptr )
{
byte b = Marshal.ReadByte( ( IntPtr ) Ptr );
return ( char ) b;
}
publicstaticshort PtrToShort( int Ptr )
{
short b = Marshal.ReadInt16( ( IntPtr ) Ptr );
return b;
}
//C# Manipulate memory accessors
publicstaticushort PtrToUShort( int Ptr )
{
ushort b = ( ushort ) Marshal.ReadInt16( ( IntPtr ) Ptr );
return b;
}
publicstaticint PtrToInt( int Ptr )
{
int b = Marshal.ReadInt32( ( IntPtr ) Ptr );
return b;
}
publicstaticuint PtrToUInt( int Ptr )
{
uint b = ( uint ) Marshal.ReadInt32( ( IntPtr ) Ptr );
return b;
}
publicstaticlong PtrToLong( int Ptr )
{
long b = Marshal.ReadInt64( ( IntPtr ) Ptr );
return b;
} //C# Manipulate memory accessors
publicstaticulong PtrToULong( int Ptr )
{
ulong b = ( ulong ) Marshal.ReadInt64( ( IntPtr ) Ptr );
return b;
}
// Convert an ip address stored an address to equivalent string value
publicstaticstring GetPtrToIpAddr(int intPtr, int varlen)
{
int i = 0;
StringBuilder sb = new StringBuilder(0,varlen*4);
byte[] byx = newbyte[varlen];
// ip address cann't have zero value C# Manipulate memory accessors
// ip address cann't have zero length C# Manipulate memory accessors
if( ( intPtr == 0 ) || ( varlen == 0 ) ) return"";
Marshal.Copy( ( IntPtr ) intPtr , byx , 0 , varlen );
for( i = 0; i < varlen - 1; i ++ )
{
sb.Append(byx[i]);
sb.Append('.');
}
sb.Append(byx[varlen - 1]);
return sb.ToString();
}
}
BOOL ReadProcessMemory( HANDLE hProcess, PVOID pvAddressRemote, PVOID pvBufferLocal, DWORD dwSize, PDWORD pdwNumBytesRead);
parameter
hProcess is the handle to the remote process
pvAddressRemote is used to specify the address in the remote process
pvBufferLocal is the memory address in the local process
dwSize is the number of bytes to be transferred
pdwNumBytesRead and pdwNumBytesWritten are used to indicate the number of bytes actually sent. When the function returns, you can view the values of these two parameters.
ReadProcessMemory reads the data, one more privilege. The following way of opening a process has query read and write permissions
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, 0, ProcessId)
Then it is necessary to combine the above procedures to search. Read memory only when it is in the occupied state and ignore memory in the idle state. I'm not going to write the program here, it's pretty much the same as the one above. dwTotalCommit = dwTotalCommit + mi.RegionSize is replaced by a function that reads memory and searches for this block of memory.
1. Read the handle to the form through FindWindow
2. Read the PID value of the process to find the form handle by GetWindowThreadProcessId
3. Use OpenProcess(PROCESS_QUERY_Or PROCESS_VM_OPERATION Or PROCESS_VM_READ Or PROCESS_VM_WRITE, 0, ProcessId) to open the process that finds the PID value
4.ReadProcessMemory reads the specified memory address data
//C# Read memory example
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Management;
publicclass key
{
constuint PROCESS_ALL_ACCESS =0x001F0FFF;
constuint KEYEVENTF_EXTENDEDKEY =0x1;
constuint KEYEVENTF_KEYUP =0x2;
privatereadonlyint MOUSEEVENTF_LEFTDOWN =0x2;
privatereadonlyint MOUSEEVENTF_LEFTUP =0x4;
constuint KBC_KEY_CMD =0x64;
constuint KBC_KEY_DATA =0x60;
// Function that gets the window handle ,FindWindow The function returns the class name that matches the specified class name ( ClassName ) And the window name ( WindowTitle ) Window handle
[DllImport("user32.dll", CharSet = CharSet.Auto)]
publicstaticextern IntPtr FindWindow(
string lpClassName, // pointer to class name
string lpWindowName // pointer to window name
);
[DllImport("user32.dll")]
privatestaticexternint GetWindowThreadProcessId(IntPtr id, int pid);
[DllImport("kernel32.dll")]
privatestaticexternvoid CloseHandle
(
uint hObject //Handle to object
);
// A function that reads process memory
[DllImport("kernel32.dll")]
staticexternbool ReadProcessMemory(uint hProcess, IntPtr lpBaseAddress,
IntPtr lpBuffer, uint nSize, refuint lpNumberOfBytesRead);
// The function that gets the target process handle
[DllImport("kernel32.dll")]
publicstaticexternuint OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
// Mouse event declaration
[DllImport("user32.dll")]
staticexternbool setcursorpos(int x, int y);
[DllImport("user32.dll")]
staticexternvoid mouse_event(mouseeventflag flags, int dx, int dy, uint data, UIntPtr extrainfo);
// Keyboard event declaration
[DllImport("user32.dll")]
staticexternbyte MapVirtualKey(byte wCode, int wMap);
[DllImport("user32.dll")]
staticexternshort GetKeyState(int nVirtKey);
[DllImport("user32.dll")]
staticexternvoid keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
// Keyboard event declaration winio
[DllImport("winio.dll")]
publicstaticexternbool InitializeWinIo();
[DllImport("winio.dll")]
publicstaticexternbool GetPortVal(IntPtr wPortAddr, outint pdwPortVal, byte bSize);
[DllImport("winio.dll")]
publicstaticexternbool SetPortVal(uint wPortAddr, IntPtr dwPortVal, byte bSize);
[DllImport("winio.dll")]
publicstaticexternbyte MapPhysToLin(byte pbPhysAddr, uint dwPhysSize, IntPtr PhysicalMemoryHandle);
[DllImport("winio.dll")]
publicstaticexternbool UnmapPhysicalMemory(IntPtr PhysicalMemoryHandle, byte pbLinAddr);
[DllImport("winio.dll")]
publicstaticexternbool GetPhysLong(IntPtr pbPhysAddr, byte pdwPhysVal);
[DllImport("winio.dll")]
publicstaticexternbool SetPhysLong(IntPtr pbPhysAddr, byte dwPhysVal);
[DllImport("winio.dll")]
publicstaticexternvoid ShutdownWinIo();
///<summary>
/// Acquisition process pid
///</summary>
///<param name="name"></param>
///<returns></returns>
privateint pid(String name)
{
try
{
ObjectQuery oQuery =new ObjectQuery("select * from Win32_Process where Name='"+ name +"'");
ManagementObjectSearcher oSearcher =new ManagementObjectSearcher(oQuery);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
string pid ="";
string cmdLine;
StringBuilder sb =new StringBuilder();
foreach (ManagementObject oReturn in oReturnCollection)
{
pid = oReturn.GetPropertyValue("ProcessId").ToString();
//cmdLine = (string)oReturn.GetPropertyvalue("CommandLine");
//string pattern = "-ap \"(.*)\"";
//Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
// Match match = regex.Match(cmdLine);
//string appPoolName = match.Groups[1].ToString();
//sb.AppendFormat("W3WP.exe PID: {0} AppPoolId:{1}\r\n", pid, appPoolName);
}
return Convert.ToInt32(pid);
}
catch (Exception ss)
{ return0; }
}
privateint pid(IntPtr id)
{
int pid =0;
pid = GetWindowThreadProcessId(id, pid);
return260;
}
///<summary>
/// Read memory value
///</summary>
///<param name="name"> process id</param>
///<param name="dizhi"> The memory address read </param>
///<returns></returns>
//public String getread(String QEC,String EC, IntPtr dizhi, uint size)
//{
// Byte bt = new Byte();
// IntPtr id=FindWindow(QEC, EC);
// uint hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid(id));
// IntPtr fanhui = new IntPtr();
// String gg = null;
// if (hProcess == 0)
// {
//// gg = ReadProcessMemory(hProcess, dizhi, fanhui, size, 0);
//// CloseHandle(hProcess);
// }
// return gg;
//}
public String getread(String jincheng, String EC, IntPtr dizhi, uint size)
{
byte[] vBuffer =newbyte[4];
IntPtr vBytesAddress = Marshal.UnsafeAddrOfPinnedArrayElement(vBuffer, 0); // Get the address of the buffer
uint vNumberOfBytesRead =0;
Byte bt =new Byte();
//IntPtr id = FindWindow(QEC, EC);
uint hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid(jincheng));
//pid(0);
IntPtr fanhui =new IntPtr();
String gg =null;
//if (hProcess == 0)
//{
if (ReadProcessMemory(hProcess, dizhi, vBytesAddress, (uint)vBuffer.Length, ref hProcess))
{
CloseHandle(hProcess);
}
else
{
CloseHandle(hProcess);
}
// }
int vInt = Marshal.ReadInt32(vBytesAddress);
return vInt.ToString();
}
///<summary>
/// Get keyboard status
///</summary>
///<param name="Key"></param>
///<returns></returns>
publicbool GetState(VirtualKeys Key)
{
return (GetKeyState((int)Key) ==1);
}
///<summary>
/// Send keyboard events
///</summary>
///<returns></returns>
publicvoid Send(VirtualKeys Key, bool State)
{
if (State != GetState(Key))
{
byte a = MapVirtualKey((byte)Key, 0);
keybd_event((byte)Key, MapVirtualKey((byte)Key, 0), 0, 0);
System.Threading.Thread.Sleep(1000);
keybd_event((byte)Key, MapVirtualKey((byte)Key, 0), KEYEVENTF_KEYUP, 0);
}
}
///<summary>
/// Initialize the winio
///</summary>
publicvoid sendwinio()
{
if (InitializeWinIo())
{
KBCWait4IBE();
}
}
privatevoid KBCWait4IBE() // Wait for the keyboard buffer to be empty
{
//int[] dwVal = new int[] { 0 };
int dwVal =0;
do
{
// This means from &H64 Port to read 1 Bytes and put the read data into variables dwVal In the
//GetPortVal The function is used GetPortVal The port number , A variable that holds read data , The length of the read in
bool flag = GetPortVal((IntPtr)0x64, out dwVal, 1);
}
while ((dwVal &0x2) >0);
}
///<summary>
/// Press the simulated keyboard TAB
///</summary>
///<param name="vKeyCoad"></param>
publicvoid MykeyDown(int vKeyCoad)
{
int btScancode =0;
btScancode = MapVirtualKey((byte)vKeyCoad, 0);
// btScancode = vKeyCoad;
KBCWait4IBE(); // ' You should wait for the keyboard buffer to be empty before sending data
SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1);// ' Send the keyboard write command
//SetPortVal The write () function is used to write data to a port SetPortVal The port number , The data to be written, the length of the data to be written
KBCWait4IBE();
SetPortVal(KBC_KEY_DATA, (IntPtr)0xe2, 1);// ' Write key information , Press the button
KBCWait4IBE(); // ' You should wait for the keyboard buffer to be empty before sending data
SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1);// ' Send the keyboard write command
//SetPortVal The write () function is used to write data to a port SetPortVal The port number , The data to be written, the length of the data to be written
KBCWait4IBE();
SetPortVal(KBC_KEY_DATA, (IntPtr)btScancode, 1);// ' Write key information , Press the button
}
///<summary>
/// Simulated keyboard popup
///</summary>
///<param name="vKeyCoad"></param>
publicvoid MykeyUp(int vKeyCoad)
{
int btScancode =0;
btScancode = MapVirtualKey((byte)vKeyCoad, 0);
//btScancode = vKeyCoad;
KBCWait4IBE(); // ' You should wait for the keyboard buffer to be empty before sending data
SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1); //' Send the keyboard write command
KBCWait4IBE();
SetPortVal(KBC_KEY_DATA, (IntPtr)0xe0, 1);// ' Write key information, release key
KBCWait4IBE(); // ' You should wait for the keyboard buffer to be empty before sending data
SetPortVal(KBC_KEY_CMD, (IntPtr)0xD2, 1); //' Send the keyboard write command
KBCWait4IBE();
SetPortVal(KBC_KEY_DATA, (IntPtr)btScancode, 1);// ' Write key information, release key
}
///<summary>
/// Simulate mouse down
///</summary>
///<param name="vKeyCoad"></param>
publicvoid MyMouseDown(int vKeyCoad)
{
int btScancode =0;
btScancode = MapVirtualKey((byte)vKeyCoad, 0);
//btScancode = vKeyCoad;
KBCWait4IBE(); // ' You should wait for the keyboard buffer to be empty before sending data
SetPortVal(KBC_KEY_CMD, (IntPtr)0xD3, 1);// ' Send the keyboard write command
//SetPortVal The write () function is used to write data to a port SetPortVal The port number , The data to be written, the length of the data to be written
KBCWait4IBE();
SetPortVal(KBC_KEY_DATA, (IntPtr)(btScancode |0x80), 1);// ' Write key information , Press the button
}
///<summary>
/// Simulated mouse popup
///</summary>
///<param name="vKeyCoad"></param>
publicvoid MyMouseUp(int vKeyCoad)
{
int btScancode =0;
btScancode = MapVirtualKey((byte)vKeyCoad, 0);
// btScancode = vKeyCoad;
KBCWait4IBE(); // ' You should wait for the keyboard buffer to be empty before sending data
SetPortVal(KBC_KEY_CMD, (IntPtr)0xD3, 1); //' Send the keyboard write command
KBCWait4IBE();
SetPortVal(KBC_KEY_DATA, (IntPtr)(btScancode |0x80), 1);// ' Write key information, release key
}
///<summary>
/// Send mouse events
///</summary>
///<returns></returns>
publicvoid SendMouse()
{
}
///<summary>
/// Mouse action enumeration
///</summary>
publicenum mouseeventflag : uint
{
move =0x0001,
leftdown =0x0002,
leftup =0x0004,
rightdown =0x0008,
rightup =0x0010,
middledown =0x0020,
middleup =0x0040,
xdown =0x0080,
xup =0x0100,
wheel =0x0800,
virtualdesk =0x4000,
absolute =0x8000
}
///<summary>
/// Keyboard action enumeration
///</summary>
publicenum VirtualKeys : byte
{
//VK_NUMLOCK = 0x90, // Number lock key
//VK_SCROLL = 0x91, // Scroll lock
//VK_CAPITAL = 0x14, // Case lock
//VK_A = 62, // The keyboard A
VK_LBUTTON =1, // The left mouse button
VK_RBUTTON =2, // The right mouse button
VK_CANCEL =3, //Ctrl+Break( Usually you don't have to deal with it )
VK_MBUTTON =4, // Middle mouse button
VK_BACK =8, //Backspace
VK_TAB =9, //Tab
VK_CLEAR =12, //Num Lock Turn off the numeric keypad 5
VK_RETURN =13, //Enter( Or the other 1 a )
VK_SHIFT =16, //Shift( Or the other 1 a )
VK_CONTROL =17, //Ctrl( Or the other 1 A)
VK_MENU =18, //Alt( Or the other 1 a )
VK_PAUSE =19, //Pause
VK_CAPITAL =20, //Caps Lock
VK_ESCAPE =27, //Esc
VK_SPACE =32, //Spacebar
VK_PRIOR =33, //Page Up
VK_NEXT =34, //Page Down
VK_END =35, //End
VK_HOME =36, //Home
VK_LEFT =37, // The left arrow
VK_UP =38, // The arrow on the
VK_RIGHT =39, // Right arrow
VK_DOWN =40, // The arrow
VK_SELECT =41, // optional
VK_PRINT =42, // optional
VK_EXECUTE =43, // optional
VK_SNAPSHOT =44, //Print Screen
VK_INSERT =45, //Insert
VK_DELETE =46, //Delete
VK_HELP =47, // optional
VK_NUM0 =48, //0
VK_NUM1 =49, //1
VK_NUM2 =50, //2
VK_NUM3 =51, //3
VK_NUM4 =52, //4
VK_NUM5 =53, //5
VK_NUM6 =54, //6
VK_NUM7 =55, //7
VK_NUM8 =56, //8
VK_NUM9 =57, //9
VK_A =65, //A
VK_B =66, //B
VK_C =67, //C
VK_D =68, //D
VK_E =69, //E
VK_F =70, //F
VK_G =71, //G
VK_H =72, //H
VK_I =73, //I
VK_J =74, //J
VK_K =75, //K
VK_L =76, //L
VK_M =77, //M
VK_N =78, //N
VK_O =79, //O
VK_P =80, //P
VK_Q =81, //Q
VK_R =82, //R
VK_S =83, //S
VK_T =84, //T
VK_U =85, //U
VK_V =86, //V
VK_W =87, //W
VK_X =88, //X
VK_Y =89, //Y
VK_Z =90, //Z
VK_NUMPAD0 =96, //0
VK_NUMPAD1 =97, //1
VK_NUMPAD2 =98, //2
VK_NUMPAD3 =99, //3
VK_NUMPAD4 =100, //4
VK_NUMPAD5 =101, //5
VK_NUMPAD6 =102, //6
VK_NUMPAD7 =103, //7
VK_NUMPAD8 =104, //8
VK_NUMPAD9 =105, //9
VK_NULTIPLY =106, // On the number pad *
VK_ADD =107, // On the number pad +
VK_SEPARATOR =108, // optional
VK_SUBTRACT =109, // On the number pad -
VK_DECIMAL =110, // On the number pad .
VK_DIVIDE =111, // On the number pad /
VK_F1 =112,
VK_F2 =113,
VK_F3 =114,
VK_F4 =115,
VK_F5 =116,
VK_F6 =117,
VK_F7 =118,
VK_F8 =119,
VK_F9 =120,
VK_F10 =121,
VK_F11 =122,
VK_F12 =123,
VK_NUMLOCK =144, //Num Lock
VK_SCROLL =145 // Scroll Lock
}
}
Note :using System.Management needs to add a reference to System.Management, otherwise compilation is prone to errors