Skip to content

Commit

Permalink
g304: use a more convincing example
Browse files Browse the repository at this point in the history
With this change, the tweaked example shows how an attacker can make the code read from an unsafe path by adding `..` to their path.

Signed-off-by: Dan Kenigsberg <[email protected]>
  • Loading branch information
dankenigsberg authored Dec 29, 2020
1 parent b4b40a2 commit 5eba943
Showing 1 changed file with 14 additions and 8 deletions.
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

0 comments on commit 5eba943

Please sign in to comment.