Skip to content

G104 false positive crypto/rand rand.Read() #1445

@oittaa

Description

@oittaa

From the documentation: https://pkg.go.dev/crypto/rand#Read

Read fills b with cryptographically secure random bytes. It never returns an error, and always fills b entirely.

Read calls io.ReadFull on Reader and crashes the program irrecoverably if an error is returned. The default Reader uses operating system APIs that are documented to never return an error on all but legacy Linux systems.

The example code snippet from the page

package main

import (
	"crypto/rand"
	"fmt"
)

func main() {
	// Note that no error handling is necessary, as Read always succeeds.
	key := make([]byte, 32)
	rand.Read(key)
	// The key can contain any byte value, print the key in hex.
	fmt.Printf("% x\n", key)
}

Running the latest dev version of gosec against the provided example produces:

[gosec] 2025/12/31 01:35:44 Including rules: default
[gosec] 2025/12/31 01:35:44 Excluding rules: default
[gosec] 2025/12/31 01:35:44 Including analyzers: default
[gosec] 2025/12/31 01:35:44 Excluding analyzers: default
[gosec] 2025/12/31 01:35:44 Import directory: /tmp/lol
[gosec] 2025/12/31 01:35:44 Checking package: main
[gosec] 2025/12/31 01:35:44 Checking file: /tmp/lol/main.go
Results:


[/tmp/lol/main.go:11] - G104 (CWE-703): Errors unhandled (Confidence: HIGH, Severity: LOW)
    10:         key := make([]byte, 32)
  > 11:         rand.Read(key)
    12:         // The key can contain any byte value, print the key in hex.

Autofix:

Summary:
  Gosec  : dev
  Files  : 1
  Lines  : 14
  Nosec  : 0
  Issues : 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions