Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

G304: Issue when passing in perm or flag as variable to os.OpenFile() #1318

Open
eest opened this issue Mar 10, 2025 · 0 comments
Open

G304: Issue when passing in perm or flag as variable to os.OpenFile() #1318

eest opened this issue Mar 10, 2025 · 0 comments

Comments

@eest
Copy link

eest commented Mar 10, 2025

For some reason gosec is happy with this code:

package main

import (
	"os"
	"path/filepath"
)

func open(fn string) {
	fh, err := os.OpenFile(filepath.Clean(fn), os.O_RDONLY, 0o600)
	if err != nil {
		panic(err)
	}
	defer fh.Close()
}

func main() {
	fn := "filename"
	open(fn)
}

while if it is changed to this I get a G304 error:

package main

import (
	"os"
	"path/filepath"
)

func open(fn string, perm os.FileMode) {
	fh, err := os.OpenFile(filepath.Clean(fn), os.O_RDONLY, perm)
	if err != nil {
		panic(err)
	}
	defer fh.Close()
}

func main() {
	fn := "filename"
	open(fn, 0o600)
}

The error:

[.../main.go:9] - G304 (CWE-22): Potential file inclusion via variable (Confidence: HIGH, Severity: MEDIUM)
    8: func open(fn string, perm os.FileMode) {
  > 9: 	fh, err := os.OpenFile(filepath.Clean(fn), os.O_RDONLY, perm)
    10: 	if err != nil {

There seems to be the same problem if passing in the flag:

package main

import (
	"os"
	"path/filepath"
)

func open(fn string, flag int) {
	fh, err := os.OpenFile(filepath.Clean(fn), flag, 0o600)
	if err != nil {
		panic(err)
	}
	defer fh.Close()
}

func main() {
	fn := "filename"
	open(fn, os.O_RDONLY)
}
[.../main.go:9] - G304 (CWE-22): Potential file inclusion via variable (Confidence: HIGH, Severity: MEDIUM)
    8: func open(fn string, flag int) {
  > 9: 	fh, err := os.OpenFile(filepath.Clean(fn), flag, 0o600)
    10: 	if err != nil {

Some additional information:

$ go version
go version go1.24.1 darwin/arm64

Probably not very helpful -version output (updated via go install github.com/securego/gosec/v2/cmd/gosec@latest just before opening the ticket)

$ gosec -version
Version: dev
Git tag:
Build date:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants