Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions docs/rules/g304_file-path_provided_as_taint_input.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: G304: File path provided as taint input
Trying to open a file provided as an input in a variable. The content of this variable might be controlled by an attacker who could change it to hold unauthorised file paths from the system. In this way, it is possible to exfiltrate confidential information or such.

## Example problematic code:

This code lets an attacker read a `/private/path`
```
package main
Expand All @@ -17,7 +17,10 @@ import (
)
func main() {
repoFile := "path_of_file"
repoFile := "/safe/path/../../private/path"
if !strings.HasPrefix(repoFile, "/safe/path/") {
panic(fmt.Errorf("Unsafe input"))
}
byContext, err := ioutil.ReadFile(repoFile)
if err != nil {
panic(err)
Expand All @@ -34,7 +37,7 @@ func main() {
```

## The right way

This code panics if `/safe/path` was removed by an attacker
```
package main
Expand All @@ -46,15 +49,18 @@ import (
)
func main() {
repoFile := "path_of_file"
byContext, err := ioutil.ReadFile(filepath.Clean(repoFile))
repoFile := "/safe/path/../../private/path"
repoFile = filepath.Clean(repoFile)
if !strings.HasPrefix(repoFile, "/safe/path/") {
panic(fmt.Errorf("Unsafe input"))
}
byContext, err := ioutil.ReadFile(repoFile)
if err != nil {
panic(err)
}
fmt.Printf("%s", string(byContext))
}
fmt.Printf("%s", string(byContext))}
```

## See also

* https://pkg.go.dev/path/filepath?tab=doc#Clean
* https://pkg.go.dev/path/filepath?tab=doc#Clean