Skip to content
Permalink
Browse files Browse the repository at this point in the history
v1: Prevent directory path traversal in FileHandler (#2388)
* Add check for attempted path traversal.

* Re-work check for attempted path traversal.

* Fix linting errors.
  • Loading branch information
christi3k authored and raphael committed Dec 4, 2019
1 parent 4f2e802 commit 70b5a19
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions service.go
Expand Up @@ -372,6 +372,10 @@ func (ctrl *Controller) FileHandler(path, filename string) Handler {
}
}
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
// prevent path traversal
if attemptsPathTraversal(req.URL.Path, path) {
return ErrNotFound(req.URL.Path)
}
fname := filename
if len(wc) > 0 {
if m, ok := ContextRequest(ctx).Params[wc]; ok {
Expand Down Expand Up @@ -415,6 +419,32 @@ func (ctrl *Controller) FileHandler(path, filename string) Handler {
}
}

func attemptsPathTraversal(req string, path string) bool {
if !strings.Contains(req, "..") {
return false
}

currentPathIdx := 0
if idx := strings.LastIndex(path, "/*"); idx > -1 && idx < len(path)-1 {
req = req[idx+1:]
}
for _, runeValue := range strings.FieldsFunc(req, isSlashRune) {
if runeValue == ".." {
currentPathIdx--
if currentPathIdx < 0 {
return true
}
} else {
currentPathIdx++
}
}
return false
}

func isSlashRune(r rune) bool {
return os.IsPathSeparator(uint8(r))
}

var replacer = strings.NewReplacer(
"&", "&amp;",
"<", "&lt;",
Expand Down

0 comments on commit 70b5a19

Please sign in to comment.