Skip to content

Commit

Permalink
session: fix security issue with path attack
Browse files Browse the repository at this point in the history
* Fix #60.
  • Loading branch information
yookoala committed Feb 5, 2021
1 parent bd30ad8 commit 8c6159f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
14 changes: 11 additions & 3 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ type FileSystemRouter struct {
//
func (fs *FileSystemRouter) Router() Middleware {
pathinfoRe := regexp.MustCompile(`^(.+\.php)(/?.+)$`)
docroot := filepath.Join(fs.DocRoot) // converts to absolute path
return func(inner SessionHandler) SessionHandler {
return func(client Client, req *Request) (*ResponsePipe, error) {

Expand All @@ -213,11 +214,18 @@ func (fs *FileSystemRouter) Router() Middleware {
}

req.Params["PATH_INFO"] = fastcgiPathInfo
req.Params["PATH_TRANSLATED"] = filepath.Join(fs.DocRoot, fastcgiPathInfo)
req.Params["PATH_TRANSLATED"] = filepath.Join(docroot, fastcgiPathInfo)
req.Params["SCRIPT_NAME"] = fastcgiScriptName
req.Params["SCRIPT_FILENAME"] = filepath.Join(fs.DocRoot, fastcgiScriptName)
req.Params["SCRIPT_FILENAME"] = filepath.Join(docroot, fastcgiScriptName)
req.Params["DOCUMENT_URI"] = r.URL.Path
req.Params["DOCUMENT_ROOT"] = fs.DocRoot
req.Params["DOCUMENT_ROOT"] = docroot

// check if the script filename is within docroot.
// triggers error if not.
if !strings.HasPrefix(req.Params["SCRIPT_FILENAME"], docroot) {
err := fmt.Errorf("error: access path outside of filesystem docroot")
return nil, err
}

// handle directory index
urlPath := r.URL.Path
Expand Down
32 changes: 32 additions & 0 deletions session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,35 @@ func TestMapFilterRequest(t *testing.T) {
return
}
}

func TestFileSystemRouter(t *testing.T) {
fs := &gofast.FileSystemRouter{
DocRoot: "/non-exists/folder/structure",
Exts: []string{"php"},
DirIndex: []string{"index.php"},
}

h := gofast.Chain(
gofast.BasicParamsMap,
fs.Router(),
)(func(client gofast.Client, req *gofast.Request) (resp *gofast.ResponsePipe, err error) {
t.Logf("SCRIPT_FILENAME: %s", req.Params["SCRIPT_FILENAME"])
return
})

r, err := http.NewRequest("GET", "http://foobar.com/", nil)
if err != nil {
t.Errorf("unexpected error: %s", err)
}
r.URL.Path = "/../../hello-escape"

_, err = h(nil, gofast.NewRequest(r))
if err == nil {
t.Errorf("expected error, got nil")
return
}

if want, have := "error: access path outside of filesystem docroot", err.Error(); want != have {
t.Errorf("expected \"%s\", got \"%s\"", want, have)
}
}

0 comments on commit 8c6159f

Please sign in to comment.