Skip to content

Commit b667174

Browse files
committed
Make strings.Replacer.Replace a sanitizer for log injection
1 parent 50b9f5b commit b667174

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

go/ql/lib/semmle/go/security/LogInjectionCustomizations.qll

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,16 @@ module LogInjection {
5959
}
6060
}
6161

62+
/**
63+
* A call to `strings.Replacer.Replace`, considered as a sanitizer for log
64+
* injection.
65+
*/
66+
class ReplacerReplaceSanitizer extends Sanitizer {
67+
ReplacerReplaceSanitizer() {
68+
this.(DataFlow::MethodCallNode).getTarget().hasQualifiedName("strings", "Replacer", "Replace")
69+
}
70+
}
71+
6272
/**
6373
* An argument that is formatted using the `%q` directive, considered as a sanitizer
6474
* for log injection.

go/ql/test/query-tests/Security/CWE-117/LogInjection.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,28 @@ func handlerGood2(req *http.Request) {
378378
log.Printf("user %s logged in.\n", escapedUsername)
379379
}
380380

381+
// GOOD: The user-provided value is escaped before being written to the log.
382+
func handlerGood3(req *http.Request) {
383+
username := req.URL.Query()["username"][0]
384+
replacer := strings.NewReplacer("\n", "", "\r", "")
385+
log.Printf("user %s logged in.\n", replacer.Replace(username))
386+
log.Printf("user %s logged in.\n", replacerLocal1(username))
387+
log.Printf("user %s logged in.\n", replacerGlobal1(username))
388+
}
389+
390+
func replacerLocal1(s string) string {
391+
replacer := strings.NewReplacer("\n", "", "\r", "")
392+
return replacer.Replace(s)
393+
}
394+
395+
var globalReplacer = strings.NewReplacer("\n", "", "\r", "")
396+
397+
func replacerGlobal1(s string) string {
398+
return globalReplacer.Replace(s)
399+
}
400+
381401
// GOOD: User-provided values formatted using a %q directive, which escapes newlines
382-
func handlerGood3(req *http.Request, ctx *goproxy.ProxyCtx) {
402+
func handlerGood4(req *http.Request, ctx *goproxy.ProxyCtx) {
383403
username := req.URL.Query()["username"][0]
384404
testFlag := req.URL.Query()["testFlag"][0]
385405
log.Printf("user %q logged in.\n", username)

0 commit comments

Comments
 (0)