go

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


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.


Solution

  • 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))
    if !strings.HasPrefix(filePath, basePath) {
      return nil, fmt.Errorf("invalid path")
    }
    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.

    EDIT - as rkfcccccc points out below, filepath.Clean is not sufficient in the case of directory traversal in the path (../), so answer above adjusted to check .