LoginSignup
0
0

More than 1 year has passed since last update.

cscの作法 その279

Last updated at Posted at 2022-09-22

概要

cscの作法、調べてみた。
練習問題やってみた。

練習問題

shellcodeを実装せよ。

参考にしたページ

方針

win32apiを使う。
VirtualAllocでメモリー確保。
Marshal.Copyでshellcodeを転送。
Marshal.GetDelegateForFunctionPointerで実行。

サンプルコード

using System;
using System.Runtime.InteropServices;

class Program {
	[DllImport("kernel32.dll", SetLastError = true)]
	static extern IntPtr VirtualAlloc(IntPtr lpAddress, int dwSize, int flAllocationType, int flProtect);
	[DllImport("kernel32.dll", SetLastError = true)]
	static extern bool VirtualFree(IntPtr lpAddress, int dwSize, int dwFreeType);
	[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
	delegate int Delg(int a, int b);
	const int MEM_COMMIT = 0x1000;
	const int MEM_RELEASE = 0x8000;
	const int PAGE_EXECUTE_READWRITE = 0x40;
	static byte[] codes = {
 		//MOV RAX, RCX ; 
		0x48, 0x89, 0xc8,
    	//ADD RAX, RDX ; 
		0x48, 0x01, 0xd0,
    	//RET          ; 
		0xc3
	};
	static void Main(string[] args) {
		int buflen = codes.Length;
		IntPtr p = VirtualAlloc(IntPtr.Zero, buflen, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
		Marshal.Copy(codes, 0, p, buflen);
		Delg f = Marshal.GetDelegateForFunctionPointer(p, typeof(Delg)) as Delg;
		Console.WriteLine("3 + 4 = {0}", f(3, 4));
		VirtualFree(p, 0, MEM_RELEASE);
	}
}



実行結果

>3 + 4 = 7

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0