Avoid Native Calls
ID |
go.avoid_native_calls |
Severity |
low |
Resource |
Api |
Language |
Go |
Tags |
CWE:246, NIST.SP.800-53, PCI-DSS:6.5.6 |
Description
This rule highlights the risks associated with calling native functions directly in Go applications due to the potential for security vulnerabilities and decreased portability.
Rationale
Calling native functions, particularly using packages like cgo
in Go, can introduce security vulnerabilities such as buffer overflows, memory corruption, and can make code less portable and harder to maintain.
package main
/*
#include <stdlib.h>
// Potentially unsafe C function
int unsafeOperation(int* p) {
// Unsafe memory operations
return *p;
}
*/
import "C"
import "unsafe"
func main() {
var num C.int = 10
unsafePointer := unsafe.Pointer(&num)
// Calling C function with potential unsafe behavior
result := C.unsafeOperation((*C.int)(unsafePointer))
println(result)
}
The above code snippet highlights the direct use of a C function via cgo, which can lead to unsafe memory operations. Such calls bypass Go’s memory safety features, increasing the risk of vulnerabilities.
Remediation
To address these risks, carefully evaluate the necessity of native calls. Prefer Go implementations when feasible, and ensure proper validation and error handling if native code is indispensable.
-
Alternative Go Implementation: Whenever possible, replace native calls with pure Go implementations to leverage the language’s safety features.
-
Error Handling: Implement comprehensive error handling when native calls are unavoidable.
-
Security Reviews: Conduct detailed security reviews of the C code being integrated.
package main
func safeOperation(val int) int {
// Safe Go implementation
return val
}
func main() {
// Using Go's safe function
result := safeOperation(10)
println(result)
}
By using a Go native implementation, you maintain memory safety, reduce complexity, and enhance maintainability and portability of the code. Additionally, ensure all integrated C code is thoroughly reviewed for potential security vulnerabilities.