# Go unsafe and cgo
> The deliberate escape hatches from Go's memory and type safety. `unsafe.Pointer` and `uintptr` arithmetic, `//go:linkname` and 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 `*T` converts to and from `unsafe.Pointer`, which works like C's `void*`.
- `unsafe.Pointer` converts to and from `uintptr`, and `uintptr` supports arithmetic.
- `Sizeof`, `Offsetof` and `Alignof` give 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
```go
var i int8 = -1
k := *(*uint8)(unsafe.Pointer(&i)) // 255: raw bits, no conversion
```
Any reinterpretation driven by attacker-controlled lengths, offsets or types is a memory-corruption candidate.
### Writing unexported fields across packages
```go
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) and `os/user` have 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=0` disables cgo entirely, and is usually safe because most modern Go libraries are pure Go. To keep pure-Go `net`/`os/user` while 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 `uintptr` arithmetic result is derived from trusted layout, never from input
- [ ] No `StringHeader`/`SliceHeader` aliasing 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
- [[raw/pixelstech.net/understand-unsafe-in-golang-pixelstech-net-1204|Understand unsafe in GoLang]]
- [[raw/link.medium.com/go-what-is-the-unsafe-package-1336|Go: What is the Unsafe Package?]]
- [[raw/snyk.io/go-security-cheatsheet-snyk-blog-1225|Go Security cheatsheet]]
- [[raw/blog.trailofbits.com/security-assessment-techniques-for-go-projects-trail-of-bits-blog-1213|Security assessment techniques for Go projects]]
- [[raw/rain-1.github.io/golang-aslr-rain-1-github-io-1098|Golang ASLR]]
- [[raw/arp242.net/statically-compiling-go-programs-1195|Statically compiling Go programs]]
- [[raw/devs.cloudimmunity.com/50-shades-of-go-traps-gotchas-and-common-mistakes-for-new-golang-devs-1102|50 Shades of Go: Traps, Gotchas, and Common Mistakes]]