Avoid using the unsafe package


ID: go-security/no-unsafe

Language: Go

Severity: Info

Category: Security


The unsafe package in Go provides access to low-level operations that can bypass the type safety and memory safety guarantees of the language. It allows direct manipulation of memory addresses, pointers, and data representation. While there are valid use cases for the unsafe package, it should generally be avoided unless absolutely necessary due to the following reasons:

  1. Safety: Go is designed to prioritize memory safety and type safety. By using the unsafe package, you give up these guarantees and introduce the potential for undefined behavior, memory corruption, data races, and security vulnerabilities. Incorrect usage of the unsafe package can lead to crashes, unpredictable behavior, or vulnerabilities that may be difficult to debug and fix.
  2. Portability: Code that uses the unsafe package is not guaranteed to be portable across different platforms or architectures. The behavior of memory operations may differ, and assumptions made based on one platform may not hold on another. This can lead to code that is difficult to maintain and may not work as expected when deployed on different systems.
  3. Readability and Maintainability: Code that relies on the unsafe package can be harder to understand, reason about, and maintain. Low-level operations obscure the intent of the code and can introduce obscure bugs. This can make it harder for fellow developers to comprehend and collaborate on the code, potentially leading to reduced maintainability and increased development time.
  4. Compatibility: The unsafe package is not part of the stable Go API, and its behavior can change between different versions of the language. Relying on undocumented or unstable behavior can lead to code that becomes broken or deprecated in future Go releases. By avoiding the unsafe package, you ensure better compatibility with future versions of Go.

In most cases, it is possible to achieve the desired functionality without using the unsafe package by leveraging the idiomatic features of the Go language. If you find yourself considering the use of the unsafe package, it is recommended to carefully evaluate the reasons for doing so and explore alternative approaches or workarounds that adhere to the safety guarantees and conventions of the language.

It is worth noting that there are rare cases where the unsafe package is necessary, such as when interfacing with low-level system APIs or performing advanced optimizations. However, such usage should be approached with caution and avoided unless the benefits clearly outweigh the risks, and thorough testing and review have been conducted.

Non-Compliant Code Examples

func main (){