From 5eba9430c6c5ca26c06d5d14a11f0312a2619899 Mon Sep 17 00:00:00 2001 From: Dan Kenigsberg Date: Tue, 29 Dec 2020 15:42:41 +0200 Subject: [PATCH] g304: use a more convincing example 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 --- .../g304_file-path_provided_as_taint_input.md | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/rules/g304_file-path_provided_as_taint_input.md b/docs/rules/g304_file-path_provided_as_taint_input.md index 7a5423c..6bf8bbd 100644 --- a/docs/rules/g304_file-path_provided_as_taint_input.md +++ b/docs/rules/g304_file-path_provided_as_taint_input.md @@ -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 @@ -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) @@ -34,7 +37,7 @@ func main() { ``` ## The right way - +This code panics if `/safe/path` was removed by an attacker ``` package main @@ -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 \ No newline at end of file +* https://pkg.go.dev/path/filepath?tab=doc#Clean