Git Product home page Git Product logo

gobfuscate's Introduction

gobfuscate

When you compile a Go binary, it contains a lot of information about your source code: field names, strings, package paths, etc. If you want to ship a binary without leaking this kind of information, what are you to do?

With gobfuscate, you can compile a Go binary from obfuscated source code. This makes a lot of information difficult or impossible to decipher from the binary.

How to use

go get -u github.com/unixpickle/gobfuscate
gobfuscate [flags] pkg_name out_path

pkg_name is the path relative from your $GOPATH/src to the package to obfuscate (typically something like domain.tld/user/repo)

out_path is the path where the binary will be written to

Flags

Usage: gobfuscate [flags] pkg_name out_path
  -keeptests
    	keep _test.go files
  -noencrypt
    	no encrypted package name for go build command (works when main package has CGO code)
  -nostatic
    	do not statically link
  -outdir
    	output a full GOPATH
  -padding string
    	use a custom padding for hashing sensitive information (otherwise a random padding will be used)
  -tags string
    	tags are passed to the go compiler
  -verbose
    	verbose mode
  -winhide
    	hide windows GUI

What it does

Currently, gobfuscate manipulates package names, global variable and function names, type names, method names, and strings.

Package name obfuscation

When gobfuscate builds your program, it constructs a copy of a subset of your GOPATH. It then refactors this GOPATH by hashing package names and paths. As a result, a package like "github.com/unixpickle/deleteme" becomes something like "jiikegpkifenppiphdhi/igijfdokiaecdkihheha/jhiofoppieegdaif". This helps get rid of things like Github usernames from the executable.

Limitation: currently, packages which use CGO cannot be renamed. I suspect this is due to a bug in Go's refactoring API.

Global names

Gobfuscate hashes the names of global vars, consts, and funcs. It also hashes the names of any newly-defined types.

Due to restrictions in the refactoring API, this does not work for packages which contain assembly files or use CGO. It also does not work for names which appear multiple times because of build constraints.

Struct methods

Gobfuscate hashes the names of most struct methods. However, it does not rename methods whose names match methods of any imported interfaces. This is mostly due to internal constraints from the refactoring engine. Theoretically, most interfaces could be obfuscated as well (except for those in the standard library).

Due to restrictions in the refactoring API, this does not work for packages which contain assembly files or use CGO. It also does not work for names which appear multiple times because of build constraints.

Strings

Strings are obfuscated by replacing them with functions. A string will be turned into an expression like the following:

(func() string {
	mask := []byte{33, 15, 199}
	maskedStr := []byte{73, 106, 190}
	res := make([]byte, 3)
	for i, m := range mask {
		res[i] = m ^ maskedStr[i]
	}
	return string(res)
}())

Since const declarations cannot include function calls, gobfuscate tries to change any const strings into vars. It works for declarations like any of the following:

const MyStr = "hello"
const MyStr1 = MyStr + "yoyo"
const MyStr2 = MyStr + (MyStr1 + "hello1")

const (
  MyStr3 = "hey there"
  MyStr4 = MyStr1 + "yo"
)

However, it does not work for mixed const/int blocks:

const (
  MyStr = "hey there"
  MyNum = 3
)

License

This is under a BSD 2-clause license. See LICENSE.

gobfuscate's People

Contributors

davhau avatar dli357 avatar hacker-volodya avatar hazcod avatar karagenc avatar lu4p avatar martinbaillie avatar rszyma avatar unixpickle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gobfuscate's Issues

Issue with files that start with a comment

Not sure if there is actually anything you can do about it, because it looks like the error comes from go/parser

Failed to obfuscate symbols: top-level renames: xdump-obf/src/mcalodeikclcopcladod/ejggkljlicdjkmhkomai/kfobgnhmomgeflkpijbo/ogfhilbeboaennjhmkjk/oikmklfdjgmolobbdckd/table.go:1:1: expected 'package', found '/'

Exclude "main" package

My go project file structure is like the following:

src/main/main.go
src/package1/...
src/package2/..

However gobfuscate processed all packages, so I had to rename it back to main and build it.

Can you add an argument to exclude certain package names?

Error : flag provided but not defined: -trimpath

I install gobfuscate in the following way : go get -u github.com/unixpickle/gobfuscate
I run the following command : /home/user/go/bin/gobfuscate -tags GOOS=windows -verbose -tags GOARCH=amd64 mydir outdir

And, Ihave the following error :

Error : flag provided but not defined: -trimpath
usage: build [-o output] [-i] [build flags] [packages]
Run 'go help build' for details.
Failed to compile: exit status 2

What is wrong with the trimpath option ?

we need option to execlude some packages

I have medium project which import small packages i made and also import: golang.org/x/text
I need to cancel golang.org/x/text from obfuscation to accelerate the operation.
after searching in the code i found that when you transfer package to $GOROOT it will not include
in the obfuscation but I receive error from function
func interfaceMethods(gopath string) (map[string]bool, error){}
cannot import golang.org/x/tools/go/ssa/ssautil

I temporary solve the problem by write continue when the program cannot import a package because actually
this package I am not using and I didn't need to obfuscate it

pkg, err := ctx.Import(pkgName, gopath, 0)
if err != nil {
continue
//return nil, fmt.Errorf("import %s: %s", pkgName, err)
}

Gobfuscate not able to create tmp file

I'm having a few issues getting gobfuscate to run properly for me. The first issue I ran into was that gobfuscate was not able to find my golang code in my GOPATH and made me put it into my GOROOT.

image

Now that I've done that it is unable to create a tmp directory, even when running as root.

image

Not quite sure what is causing both of these issues. I used to be able to run it without any problems. Are there any examples out there of others using this tool?

Reversing

Does it possible to create reverse mapping map, so when you have binary and this map,restore original names?
For example to use with go panics

Having a hard time using this to build without documentation

I've tried many variations as well as reading over the code to figure out what I'm doing wrong. My project folder is in /Users/user/go/enc (which is the default GOPATH used in the source) with enc.go in the folder and i get:
Failed to build import graph: enc

Off By One Error When Removing DO NOT EDIT

When replacing the "DO NOT EDIT" comments, the function removeDoNotEdit allocates one less character, thus slicing one of forward slashes off of the comment.

See lines 297-300 in symbols.go:

data := make([]byte, comment.End()-comment.Pos())
start := int(comment.Pos())
end := start + len(data)
data = content[start:end]

Instead, line 298 should be:

start := int(comment.Pos()) - 1

To reproduce, I tried obfuscating github.com/miekg/dns. There are some other issues there with parsing annotation tags in switch statements, but that should probably be its own separate issue.

This looks like the same problem experienced in #30

Does not work if struct is defined after use

gobfuscate does not work with the following code (shortened):

package main

import (
	"fmt"
)

type Test1 struct {
	data map[int]pathInfo
}

type pathInfo struct {
	name string
}

func main() {
	fmt.Println("Hello There!")
}

It complains with XXX has no member "pathInfo". The only solution is to modify the source code and move pathInfo definition above Test1 structure.

Can you fix it?

Can't load package eventhough it's there

I'm having this error and as you can see my GOPATH is copied and changed to /tmp/random.
I can see that the files are in the /tmp files but still I'm getting this, no idea why...

[unkn0wn@unkn0wn-pc gobfuscate]$ ./gobfuscate -verbose github.com/brimstone/go-shellcode /home/unkn0wn/test
2019/09/09 08:24:51 Copying GOPATH...
2019/09/09 08:24:52 Obfuscating package names...
2019/09/09 08:24:53 Obfuscating strings...
2019/09/09 08:24:53 Obfuscating symbols...

[Verbose] Temporary path: /tmp/064222581
[Verbose] Go build command: go build -ldflags=-s -w -extldflags "-static" -o /home/unkn0wn/test pngifcmecdidbeljejdf/docfeloaijbdnmfecioi/gbljnboigijdlafjfghg
[Verbose] Environment variables:
GOROOT=/usr/lib/go
GOARCH=amd64
GOOS=linux
GOPATH=/tmp/064222581
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl
GOCACHE=/tmp/064222581/cache

can't load package: package pngifcmecdidbeljejdf/docfeloaijbdnmfecioi/gbljnboigijdlafjfghg: cannot find package "pngifcmecdidbeljejdf/docfeloaijbdnmfecioi/gbljnboigijdlafjfghg" in any of:
	/usr/lib/go/src/pngifcmecdidbeljejdf/docfeloaijbdnmfecioi/gbljnboigijdlafjfghg (from $GOROOT)
	/tmp/064222581/src/pngifcmecdidbeljejdf/docfeloaijbdnmfecioi/gbljnboigijdlafjfghg (from $GOPATH)
Failed to compile: exit status 1

Failed to copy into a new GOPATH: package main not found

if i set GO111MODULE to off

Failed to copy into a new GOPATH: cannot find package "main" in any of:
        C:\Program Files\Go\src\main (from $GOROOT)
        C:\Users\xiaocai\go\src\main (from $GOPATH)

if set it to on

2023/01/03 21:39:38 Copying GOPATH...
Failed to copy into a new GOPATH: package main not found
Note: Setting GO111MODULE env variable to `off` may resolve the above error.```

Error happens when renaming a build-tags specific symbol

A demo package like follows,
main.go

package main

func main() {
   Test()
}

a.go

// +build TagA

package main
import "fmt"
var A = "A"
func Test() {
  fmt.Println("I'm tag ", A)
}

b.go

// +build !TagA
 
package main
func Test() {
  fmt.Println("I'm not A")
}

When try to obfuscate this package, it will report an error like top-level renaming: package "xxxxx" has no member "A".

flag provided but not defined

Hi!

While trying the tool I simply executed:

gobfuscate test ./
and the output was:

2020/02/02 15:22:05 Copying GOPATH...
2020/02/02 15:22:13 Obfuscating package names...
2020/02/02 15:22:13 Obfuscating strings...
2020/02/02 15:22:13 Obfuscating symbols...
Renamed 4 occurrences in 1 file in 1 package.
flag provided but not defined: -ldflags "-s -w -extldflags '-static'"
usage: go build [-o output] [-i] [build flags] [packages]
Run 'go help build' for details.
Failed to compile: exit status 2
exit status 1

I've read that the issue could be due to a regression in Golang 1.13 due to flag.Parse() called before the flags initialization, so I stripped, in main.go

func main() {
	pkgName := "test"
	outPath := "./"

	if !obfuscate(pkgName, outPath) {
		os.Exit(1)
	}
}

But the output is the same of above.
Go version is: go1.13.7 linux/amd64

main.go is:

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello World!")
}

Does not support -tags and "+build XXX" flag

I have two go source files that have duplicated variables. With gobfuscate I got errors like:

xx.go: XXXX redeclared in this block
yy.go:    other declaration of XXXX

With go cli I selectively build the binary with -tags=XXX command line option and add build options in go source files, e.g

// +build XXX

Can you add a flag that support "Additional golang options"? I need to add -tags=XXX flag

I can't find how to use gobfuscate

Hi.

I'm new to Go. I'm working on a CTF project and would like to obfuscate my binary using your tool.

When I run ./gobfuscate botnet ./out, I get:

2018/09/06 00:33:50 Copying GOPATH...
Failed to re-build import graph: botnet

My GOPATH contains /home/ax/go:/usr/share/go/1.9/contrib and my program is in /home/ax/go/src/botnet/. The only source code in this folder is botnet.go, the package name inside the file is botnet and it contains func main.

I tried to run it on other packages like keylogger which I have in /home/ax/go/src/github.com/MarinX/keylogger/, in this case it would return Failed to build import graph: keylogger.

What am I doing wrong? I don't know how to get it right.

Thank you

has no member WMIQueryWithContext

Hello.

2019/02/19 15:32:02 Copying GOPATH...
2019/02/19 15:32:04 Obfuscating package names...
Renamed 2 occurrences in 1 file in 1 package.
Renamed 4 occurrences in 1 file in 1 package.
Renamed 11 occurrences in 1 file in 1 package.
Renamed 27 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 7 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 10 occurrences in 1 file in 1 package.
Renamed 19 occurrences in 1 file in 1 package.
Renamed 3 occurrences in 1 file in 1 package.
Renamed 7 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 4 occurrences in 1 file in 1 package.
Renamed 5 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 3 occurrences in 1 file in 1 package.
Renamed 6 occurrences in 1 file in 1 package.
Renamed 3 occurrences in 1 file in 1 package.
Renamed 101 occurrences in 1 file in 1 package.
Renamed 3 occurrences in 1 file in 1 package.
Renamed 18 occurrences in 1 file in 1 package.
Renamed 8 occurrences in 1 file in 1 package.
Renamed 4 occurrences in 1 file in 1 package.
Renamed 4 occurrences in 1 file in 1 package.
Renamed 8 occurrences in 1 file in 1 package.
Renamed 3 occurrences in 1 file in 1 package.
Renamed 6 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
2019/02/19 15:33:12 Obfuscating strings...
2019/02/19 15:33:13 Obfuscating symbols...
Renamed 7 occurrences in 3 files in 1 package.
Renamed 4 occurrences in 1 file in 1 package.
Renamed 9 occurrences in 3 files in 1 package.
Renamed 5 occurrences in 2 files in 1 package.
Failed to obfuscate symbols: top-level renaming: package "ngkaacfgmhlhcfclfljn/ciifklokeaihipcagdmn/ackiippempgojdcnmgbo/npadneehnehfmpagblnl/lccgonnblbodpgobmabj" has no member "WMIQueryWithContext"

Package:
https://github.com/shirou/gopsutil/tree/master/internal/common

WMIQueryWithContext exist only in the file common_windows.go

Package not found

I'm trying to obfuscate the dnscrypt-proxy for, well, reasons that aren't important. I've placed it in:
C:\Users\kevin\go\src\github.com\DNSCrpt\dnscrypt-proxy and it builds fine.
go build -ldflags="-s -w" -mod vendor

Now I try to gobfuscate it:
C:\Users\kevin\go\src>gobfuscate github.com\DNSCrpt\dnscrypt-proxy outxxx
2020/07/07 13:36:14 Copying GOPATH...
Failed to copy into a new GOPATH: package github.com\DNSCrpt\dnscrypt-proxy not found

GOPATH seems ok:
C:\Users\kevin\go\src>set gopath
GOPATH=C:\Users\kevin\go

I used filename completion to ensure I didn't make any typos, but here's a dir:

C:\Users\kevin\go\src>dir github.com\DNSCrpt\dnscrypt-proxy
Volume in drive C is OS
Volume Serial Number is 080E-F589

Directory of C:\Users\kevin\go\src\github.com\DNSCrpt\dnscrypt-proxy

07/07/2020 01:34 PM

.
07/07/2020 01:34 PM ..
07/07/2020 01:18 PM testdata
07/06/2020 11:19 AM 3,736 common.go
07/06/2020 11:19 AM 32,561 config.go
(and so on)

I suspect stupid user error on my part, but I'm befuddled.

[Bug] Obfuscating strings with predefined variables

When obfuscating strings inside a function that already has len or make defined as variables.
Go throws the following error:

cannot call non-function len

Example code:

package main

import "fmt"

func main() {
	var len = 5
	var str = "Hello, World!"
	fmt.Println(str[:len])
}

This issue appears in most of the golang.org/x/sys/unix/syscall code.

One solution would be to detect when the variables are in use and to use a different method to obfuscate strings in that function.

Usage instructions unclear

1

go get -u github.com/unixpickle/gobfuscate

Worked.

2

gobfuscate ./src ./bin

'gobfuscate' is not recognized as an internal or external command,
operable program or batch file.

Tried using the compiled binary via go install:

C:\Users\0\Desktop$\dev\Go\Gobfuscate> .\gobfuscate ./src ./bin
2023/03/27 21:48:07 Copying GOPATH...
Failed to copy into a new GOPATH: import "./src": import relative to unknown directory
Note: Setting GO111MODULE env variable to off may resolve the above error.

Set the GO111MODULE to off via set GO111MODULE=off

C:\Users\0\Desktop$\dev\Go\Gobfuscate> .\gobfuscate ./src ./bin
2023/03/27 21:48:07 Copying GOPATH...
Failed to copy into a new GOPATH: import "./src": import relative to unknown directory
Note: Setting GO111MODULE env variable to off may resolve the above error.

How?

Error: Compile for different OSs and Arch

Tried to edit the code to be able to compile other archs and OSs but I get an Error
(same with the forked code of @felipe-linar : https://github.com/felipe-linares/gobfuscate). I'd be grateful if someone can provide help or any clue on how I should proceed.

/tmp/233866000/src/.../rawconn.go:79:14: undefined: ojbfleohedefbdcegche
/tmp/233866000/src/.../rawconn.go:98:11: undefined: kgegcafbopgcbgghnbdh
/tmp/233866000/src/.../rawconn_msg.go:17:8: undefined: ggjhbgfjjdpgjmefchjj
/tmp/233866000/src/.../rawconn_msg.go:18:15: undefined: jjkfgdlgkidppgjeabfb
/tmp/233866000/src/.../rawconn_msg.go:29:21: undefined: folenbikieafphihhndc
/tmp/233866000/src/.../rawconn_msg.go:35:14: undefined: hbnbpnbdfihgjnhobkhp
/tmp/233866000/src/.../rawconn_msg.go:86:8: undefined: ggjhbgfjjdpgjmefchjj
/tmp/233866000/src/.../rawconn_msg.go:87:15: undefined: jjkfgdlgkidppgjeabfb
/tmp/233866000/src/.../rawconn_msg.go:96:14: undefined: ebbkjikmbmkebpmnhoin
/tmp/233866000/src/.../socket.go:167:9: undefined: chpjeioadiedgmfcjdhd
/tmp/233866000/src/.../socket.go:167:9: too many errors
Failed to compile: exit status 2

gomvpkg does not support move destinations whose base names are not valid go identifiers

GOPATH: E:\go\src
My Application: E:\go\src\HelloWorld
Working Directory: E:\go\src\

E:\go\src:> go get -u github.com/unixpickle/gobfuscate
E:\go\src:> gobfuscate obfus /ob

2019/08/02 22:07:09 Copying GOPATH... 2019/08/02 22:07:36 Obfuscating package names... Failed to obfuscate package names: package move: invalid move destination: aagdegjpdjopofdlagpg\opfcoehbinlaindbngkp; gomvpkg does not support move destinations whose base names are not valid go identifiers

Couldn't get what's wrong.

In memory obfuscation

I am currently trying to load all files to memory and obfuscate them there for further speedups

invalid identifier "_"

Not sure what this means,

Renamed 1 occurrence in 1 file in 1 package.
Renamed 5 occurrences in 2 files in 1 package.
Failed to obfuscate symbols: top-level renaming: -from: invalid identifier "_"

Can you help?

panic on obfuscation

% ~/Source/go/bin/gobfuscate -verbose -winhide foo fooobfuscated     
2021/01/07 12:34:08 Copying GOPATH...
2021/01/07 12:34:11 Obfuscating package names...
2021/01/07 12:34:14 Obfuscating strings...
2021/01/07 12:34:14 Obfuscating symbols...
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 3 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 4 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 3 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 13 occurrences in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 15 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 7 occurrences in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 5 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.
Renamed 2 occurrences in 1 file in 1 package.

[Verbose] Temporary path: /var/folders/vg/39v449yj7rq8t72dl5gh20r00000gn/T/886489203
[Verbose] Go build command: go build -ldflags -s -w -H=windowsgui -extldflags '-static' -tags  -o fooobfuscated lfdhelhkhpoolioahefm

# lfdhelhkhpoolioahefm
adddynlib: unsupported binary format
adddynlib: unsupported binary format
adddynlib: unsupported binary format
runtime.firstmoduledata: unreachable sym in relocation: .rel
panic: should never happen

goroutine 1 [running]:
cmd/link/internal/ld.addToTextp(0xc00006f880)
	/usr/local/Cellar/go/1.15.6/libexec/src/cmd/link/internal/ld/lib.go:2823 +0x225
cmd/link/internal/ld.(*Link).loadlibfull(0xc00006f880, 0xc000ea2000, 0x101df, 0x101df, 0x200001)
	/usr/local/Cellar/go/1.15.6/libexec/src/cmd/link/internal/ld/lib.go:2853 +0x17d
cmd/link/internal/ld.Main(0x14729e0, 0x20, 0x20, 0x1, 0x7, 0x10, 0x0, 0x0, 0x12d8822, 0x1b, ...)
	/usr/local/Cellar/go/1.15.6/libexec/src/cmd/link/internal/ld/main.go:341 +0x18cc
main.main()
	/usr/local/Cellar/go/1.15.6/libexec/src/cmd/link/main.go:68 +0x1dc
Failed to compile: exit status 2

expects import "golang.org/x/sys/unix"

I got the following error with gobfuscate:

2019/03/09 03:55:25 Obfuscating symbols...
Renamed 2 occurrences in 2 files in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 1 occurrence in 1 file in 1 package.
Renamed 2 occurrences in 2 files in 2 packages.
Renamed 2 occurrences in 2 files in 2 packages.
/tmp/613618656/src/ehincglpolcljoeojneb/args.go:4:2: code in directory /tmp/613618656/src/afnacmagbfmgjmnmffin/ikihhbconjooebdgogkp/cmmkiannaflaadabloef/unix expects import "golang.org/x/sys/unix"
Failed to compile: exit status 1

How can I debug this?

Is it possible to just obfuscate string constants and/or string variables

Hello,

I am trying to understand this tool better. Currently, I have a single file go program within my golang workspace and I have some string constants I would like to obfuscate. I tried running the tool a number of different ways such as:

gobfuscate program ./out
gobfuscate -noencrypt program ./out
etc.

And the primary problem I am getting is some of my packages could not be imported (cannot find package). It seems like these third party libraries are the problem when all I want to do is obfuscate a few global string constants which seems like it should not be that hard.

Is there an example I can use to do this, or is this not supported, or maybe I am just missing something. Any suggestions would be nice.

Thanks

fix for (s *stringObfuscator) Obfuscate()

hey, i had to fix a small bug in the mentioned method.

The fix is

	if lastIndex < len(data) {
		result.Write(data[lastIndex:])
	}

The test program is trying to obfuscate itself and bugs with a panic: runtime error: slice bounds out of range

package main

var Appname = ""

func main() {
	log.Fatal(processPackage())
}

func processPackage() error {
	var opts packageProcessOpts

	flag.StringVar(&opts.Tag, "tag", Appname, "the output build tag of the generated files")

	flag.Parse()

	pkgpath := flag.Arg(0)

	if pkgpath == "" {
		return fmt.Errorf("invalid options, missing package. command line is %v <opt> <package>", Appname)
	}

	var conf loader.Config
	conf.Import(pkgpath)

	prog, err := conf.Load()
	if err != nil {
		return err
	}

	pkg := prog.Package(pkgpath)
	if pkg == nil {
		return fmt.Errorf("package %q not found in loaded program", pkgpath)
	}
	//-
	for _, f := range pkg.Files {
		b := new(bytes.Buffer)
		fset := token.NewFileSet()
		printer.Fprint(b, fset, f)

		obfuscator := &stringObfuscator{Contents: b.Bytes()}
		for _, decl := range f.Decls {
			ast.Walk(obfuscator, decl)
		}
		newCode, err := obfuscator.Obfuscate()
		if err != nil {
			return err
		}
		os.Stdout.Write(newCode)
		return nil
	}
	return nil
}

type stringObfuscator struct {
	Contents []byte
	Nodes    []*ast.BasicLit
}

func (s *stringObfuscator) Visit(n ast.Node) ast.Visitor {
	if lit, ok := n.(*ast.BasicLit); ok {
		if lit.Kind == token.STRING {
			s.Nodes = append(s.Nodes, lit)
		}
		return nil
	} else if decl, ok := n.(*ast.GenDecl); ok {
		if decl.Tok == token.CONST || decl.Tok == token.IMPORT {
			return nil
		}
	} else if _, ok := n.(*ast.StructType); ok {
		// Avoid messing with annotation strings.
		return nil
	}
	return s
}

func (s *stringObfuscator) Obfuscate() ([]byte, error) {
	sort.Sort(s)

	parsed := make([]string, s.Len())
	for i, n := range s.Nodes {
		var err error
		parsed[i], err = strconv.Unquote(n.Value)
		if err != nil {
			return nil, err
		}
	}

	var lastIndex int
	var result bytes.Buffer
	data := s.Contents
	for i, node := range s.Nodes {
		strVal := parsed[i]
		startIdx := node.Pos() - 1
		endIdx := node.End() - 1
		result.Write(data[lastIndex:startIdx])
		result.Write(obfuscatedStringCode(strVal))
		lastIndex = int(endIdx)
	}
	// if lastIndex < len(data) {
		result.Write(data[lastIndex:])
	// }
	return result.Bytes(), nil
}

func (s *stringObfuscator) Len() int {
	return len(s.Nodes)
}

func (s *stringObfuscator) Swap(i, j int) {
	s.Nodes[i], s.Nodes[j] = s.Nodes[j], s.Nodes[i]
}

func (s *stringObfuscator) Less(i, j int) bool {
	return s.Nodes[i].Pos() < s.Nodes[j].Pos()
}

func obfuscatedStringCode(str string) []byte {
	var res bytes.Buffer
	res.WriteString("(func() string {\n")
	res.WriteString("mask := []byte(\"")
	mask := make([]byte, len(str))
	for i := range mask {
		mask[i] = byte(rand.Intn(256))
		res.WriteString(fmt.Sprintf("\\x%02x", mask[i]))
	}
	res.WriteString("\")\nmaskedStr := []byte(\"")
	for i, x := range []byte(str) {
		res.WriteString(fmt.Sprintf("\\x%02x", x^mask[i]))
	}
	res.WriteString("\")\nres := make([]byte, ")
	res.WriteString(strconv.Itoa(len(mask)))
	res.WriteString(`)
        for i, m := range mask {
            res[i] = m ^ maskedStr[i]
        }
        return string(res)
        }())`)
	return res.Bytes()
}

Auto-remove created directory in tmp

Hello! While my code is running, a new directory is created in tmp but when my code is completed directory removes. What am i doing wrong?

$ gobfuscate -verbose main/cmd /home/usr/trash

2023/05/29 23:21:13 Copying GOPATH...
2023/05/29 23:21:16 Obfuscating package names...
2023/05/29 23:21:23 Obfuscating strings...
2023/05/29 23:21:23 Obfuscating symbols...
Renamed 2 occurrences in 2 files in 2 packages.

[Verbose] Temporary path: /tmp/1839736580
[Verbose] Go build command: go build -trimpath -ldflags -s -w -extldflags '-static' -tags  -o /home/usr/trash cfkfigmeokpclafjihmk/epcebkljdhffppecbgko
[Verbose] Environment variables:
GO111MODULE=off
GOROOT=/home/usr
GOARCH=amd64
GOOS=linux
GOPATH=/tmp/1839736580
PATH=/home/usr/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin:/home/usr/goworkspace/bin
GOCACHE=/tmp/1839736580/cache

$

json.Number issue

The strings obfuscator currently breaks for json.Number symbols.

Ex. https://github.com/auto-program/vendor/blob/9351d5081b8149a1d03a783dae10cf054146ed16/github.com/gocraft/dbr/types.go#L106

// UnmarshalJSON correctly deserializes a NullInt64 from JSON
func (n *NullInt64) UnmarshalJSON(b []byte) error {
	var s json.Number
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	if s == "" {
		return n.Scan(nil)
	}
	return n.Scan(s)
}
func (n *NullInt64) UnmarshalJSON(b []byte) error {
	var s json.Number
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	if s == (func() string {
mask := []byte("")
maskedStr := []byte("")
res := make([]byte, 0)
        for i, m := range mask {
            res[i] = m ^ maskedStr[i]
        }
        return string(res)
        }()) {
		return n.Scan(nil)
	}
	return n.Scan(s)
}

cannot compare s == ((func() string literal)()) (mismatched types json.Number and string)

Obfuscate Import paths more

Currently import paths obfuscated but the folder structure stays the same e.g.
$GOPATH/src/obfuscatedgithub/obfuscateduser/obfuscatedrepo
$GOPATH/src/obfuscatedgithub/obfusanotheruser/obfusanotherrepo
which would maybe allow to do some analysis.

It would be better to move all packages to the the root of $GOPATH/src e.g.
$GOPATH/src/somerandompackagename
$GOPATH/src/anotherrandompackagename

Should use dynamic GO path

I've compiled gobfuscate with go 1.12.6 on Mac. When I updated go to 1.12.7, the compiled binary is still looking at the old path:

could not import errors (cannot find package "errors" in any of:
	/usr/local/homebrew/Cellar/go/1.12.6/libexec/src/errors (from $GOROOT)

Looks like the only solution is recompile gobfuscate, was it a bug?

Module project structure

Hello, first of all, awesome project! Now, Is there any chance for the project to adopt a structure like the one mentioned here? This because without manual modification of the files, like renaming package main to package gobfuscate, the project can't be used as a module in other tools.

Apart of using this project as a module, others advantages of approaching this are:

  • Users can provide their own obfuscated string generators
  • Users can add support for other vanilla data types of Go
  • Users can add obfuscation support for specific custom data types
  • Maybe in the future add support for CGO

Maybe by putting anything that can be used by someone else into pkg/ and the main.go file inside cmd/

How does this work?

Maybe provide an example, because I have a project sitting in my gopath and I just get "failed to build import graph" each time

How do I manually import gobfuscate?

I am unable to import gobfuscate import github.com/unixpickle/gobfuscate is a program, not a importable package.

I would like to call specific functions within the source code so I can selectively use it's features in my EXOCET-AV-Evasion project. Specifically, to modify the template go file my repo makes before it is cross-compiled.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.