Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle gosec linter warning: Potential file inclusion via variable

Tags:

go

How do I solve the following warning from gosec linter:

::warning: Potential file inclusion via variable,MEDIUM,HIGH (gosec)

The linter is warning me on the first line of this function:

func File2lines(filePath string) ([]string, error) {
    f, err := os.Open(filePath) //Warning here
    if err != nil {
        return nil, err
    }
    defer f.Close()
    return linesFromReader(f)
}

I have tried reading up on local file inclusion, but cannot see how that would be applicable here.

like image 544
saidaspen Avatar asked Sep 13 '18 19:09

saidaspen


1 Answers

Where does the path come from? If you’re not absolutely sure it can never have user input, best to clean it before use and use a known prefix, e.g.:

filePath = filepath.Join(basePath,filepath.Clean(filePath))
f, err := os.Open(filePath)

That should fix the complaint. This is a reasonable precaution anyway even if you think it is safe now, in case later someone uses your function with user data.

like image 154
Kenny Grant Avatar answered Sep 22 '22 10:09

Kenny Grant