简体   繁体   中英

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.

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, eg:

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.

No one said the linter was smart . Looking at the function in isolation, it's impossible to say if there's a security issue. If the function is called with a filePath that's user-supplied and insufficiently validated, and it runs in a context where it can read files that the user would not be able to otherwise (eg in a program with elevated privileges, or on a remote server), then there is a probably issue. Otherwise, the only thing to do about the warning is to suppress or ignore it.

If you specify the file path with a variable, there is a risk that an unintended file path will be specified. Therefore, you should use filepath.Clean() to clean up possible bad paths.

an easy solution:

f,err := os.Open(filepath.Clean(fname))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM