go.lang.security.audit.unsafe.use-of-unsafe-block
Community Favorite

Author
48,043
Download Count*
License
Using the unsafe package in Go gives you low-level memory management and many of the strengths of the C language, but also steps around the type safety of Go and can lead to buffer overflows and possible arbitrary code execution by an attacker. Only use this package if you absolutely know what you're doing.
Run Locally
Run in CI
Defintion
rules:
- id: use-of-unsafe-block
message: Using the unsafe package in Go gives you low-level memory management
and many of the strengths of the C language, but also steps around the
type safety of Go and can lead to buffer overflows and possible arbitrary
code execution by an attacker. Only use this package if you absolutely
know what you're doing.
languages:
- go
severity: WARNING
metadata:
cwe:
- "CWE-242: Use of Inherently Dangerous Function"
source_rule_url: https://github.com/securego/gosec/blob/master/rules/unsafe.go
category: security
technology:
- go
confidence: LOW
references:
- https://cwe.mitre.org/data/definitions/242.html
subcategory:
- audit
likelihood: LOW
impact: LOW
license: Commons Clause License Condition v1.0[LGPL-2.1-only]
pattern: unsafe.$FUNC(...)
Examples
unsafe.go
package main
import (
"fmt"
"unsafe"
foobarbaz "unsafe"
)
type Fake struct{}
func (Fake) Good() {}
func main() {
unsafeM := Fake{}
unsafeM.Good()
intArray := [...]int{1, 2}
fmt.Printf("\nintArray: %v\n", intArray)
intPtr := &intArray[0]
fmt.Printf("\nintPtr=%p, *intPtr=%d.\n", intPtr, *intPtr)
// ruleid: use-of-unsafe-block
addressHolder := uintptr(foobarbaz.Pointer(intPtr)) + unsafe.Sizeof(intArray[0])
// ruleid: use-of-unsafe-block
intPtr = (*int)(foobarbaz.Pointer(addressHolder))
fmt.Printf("\nintPtr=%p, *intPtr=%d.\n\n", intPtr, *intPtr)
}
Short Link: https://sg.run/qxEx