简体   繁体   English

如何处理 gosec linter 警告:可能通过变量包含文件

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

How do I solve the following warning from gosec linter:如何解决来自gosec linter的以下警告:

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

The linter is warning me on the first line of this function: linter 在此函数的第一行警告我:

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 .没有人说 linter 很聪明 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.如果使用用户提供filePath充分验证的文件路径调用该函数,并且它在可以读取用户无法以其他方式读取的文件的上下文中运行(例如,在具有提升权限的程序中,或在远程服务器上),可能存在问题。 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.因此,您应该使用filepath.Clean()来清理可能的错误路径。

an easy solution:一个简单的解决方案:

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

How do I solve the following warning from gosec linter:如何解决来自gosec linter的以下警告:

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

The linter is warning me on the first line of this function: linter 在这个函数的第一行警告我:

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.我曾尝试阅读本地文件包含,但不知道这将如何适用于这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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