Go unsafe and cgo
The deliberate escape hatches from Go’s memory and type safety.
unsafe.Pointeranduintptrarithmetic,//go:linknameand cgo-linked C code reintroduce C-class bugs into a language that otherwise prevents them.
How it works
Safe Go pointers have no arithmetic, no conversion between pointer types and no cross-type comparison. Package unsafe removes those limits:
- Any
*Tconverts to and fromunsafe.Pointer, which works like C’svoid*. unsafe.Pointerconverts to and fromuintptr, anduintptrsupports arithmetic.Sizeof,OffsetofandAlignofgive layout information to compute addresses.
The Go docs say packages importing unsafe may be non-portable and fall outside the Go 1 compatibility promise. Snyk’s guidance is that unsafe combined with user data can let attackers break Go’s memory safety.
Patterns to look for
Reinterpreting memory
var i int8 = -1
k := *(*uint8)(unsafe.Pointer(&i)) // 255: raw bits, no conversionAny reinterpretation driven by attacker-controlled lengths, offsets or types is a memory-corruption candidate.
Writing unexported fields across packages
lang := (*string)(unsafe.Pointer(uintptr(unsafe.Pointer(&p)) +
unsafe.Sizeof(int(0)) + unsafe.Sizeof(string(""))))
*lang = "Golang"This hard-codes another package’s struct layout. A dependency upgrade that reorders fields turns it into a silent out-of-bounds write. It also bypasses any invariants the owning package enforces through its API.
Zero-copy string and []byte aliasing
The reflect.StringHeader/SliceHeader trick shares the backing array between a string and a slice. Strings are assumed immutable, so writing through the aliased []byte mutates a “constant” string. Any code that validated the string and then trusts it can be invalidated by a later write.
//go:linkname
This links to unexported runtime and stdlib symbols, for example reflect.typelinks and reflect.add. Trail of Bits uses it in test harnesses to reach unexported functions. In production code it is an unreviewed dependency on internals.
cgo
- cgo pulls arbitrary C into the process. As Snyk puts it, “the Go memory safety net is not there to save you” if that code has bugs or is malicious. Treat every
import "C"dependency as native code under review. - cgo is used implicitly.
net(resolver) andos/userhave cgo implementations, so importing them makes the binary dynamically linked against libc. This can happen through a transitive import. See Go Build and Deployment Hardening. CGO_ENABLED=0disables cgo entirely, and is usually safe because most modern Go libraries are pure Go. To keep pure-Gonet/os/userwhile allowing other cgo, use-tags netgo,osusergo.
Runtime-level exploitation
Go code with an arbitrary write is easy to turn into code execution. “Exploiting a Go Binary” overwrote a function pointer in the data segment, and because classic Go binaries had no address randomization, running the program twice was enough to learn the layout. A Go runtime race has also been used for heap corruption. This makes -buildmode=pie relevant for Go services that use unsafe or cgo. See Go Build and Deployment Hardening.
Review checklist
-
grep -rn 'unsafe\.\|//go:linkname\|import "C"'across the module and vendored dependencies - Every
uintptrarithmetic result is derived from trusted layout, never from input - No
StringHeader/SliceHeaderaliasing of data that is later mutated - cgo dependencies are inventoried and their C code reviewed or fuzzed; otherwise build with
CGO_ENABLED=0 - go vet and staticcheck run, since Trail of Bits lists unsafe pointer use among what they flag (see Go Security Testing Tools)
Related
- Go Security (hub) · Go Secure Coding Pitfalls · Go Build and Deployment Hardening · Go Security Testing Tools
- Remote Code Execution
Sources
- Understand unsafe in GoLang · original
- Go: What is the Unsafe Package? · original
- Go Security cheatsheet · original
- Security assessment techniques for Go projects · original
- Golang ASLR · original
- Statically compiling Go programs · original
- 50 Shades of Go: Traps, Gotchas, and Common Mistakes · original