Skip to content

Golang Misconfigured Errors Check

What does this mean ?

A really useful feature of Golang is the ability to return a tuple of a result and an error value from a function. There is an unspoken rule in Golang that the result of a function is unsafe until you make check the error value. Many security exploits can be performed when the error value is not checked.

What can happen ?

If you have written any Go code you have probably encountered the built-in error type. Go code uses error values to indicate an abnormal state. For example, the os.Open function returns a non-nil error value when it fails to open a file.A caller passing a negative argument to Sqrt receives a non-nil error value (whose concrete representation is an errors.errorString value). The caller can access the error string (“math: square root of…") by calling the error’s Error method, or by just printing it.

Recommendation

The fmt package formats an error value by calling its Error() string method.It is the error implementation’s responsibility to summarize the context. The error returned by os.Open formats as “open /etc/passwd: permission denied,” not just “permission denied.” The error returned by our Sqrt is missing information about the invalid argument.To add that information, a useful function is the fmt package’s Errorf. It formats a string according to Printf’s rules and returns it as an error created by errors.New.

Sample Code

Vulnerable :

package main
import "fmt"

func test() (int,error) {
    return 0, nil
}

func main() {
    v, _ := test()
    fmt.Println(v)
}

References