diff options
author | Alessio Caiazza <acaiazza@gitlab.com> | 2018-11-14 15:07:00 +0300 |
---|---|---|
committer | Alessio Caiazza <acaiazza@gitlab.com> | 2018-11-19 12:35:52 +0300 |
commit | 3d9bb831cd4eb931ced1780c88790dbee6297b74 (patch) | |
tree | e0beeddb074401ebfe7b157d464faff991c44ed3 | |
parent | 4e04c013fba8e0c1294904b52bcb2cbaad27cb52 (diff) |
Fix TOCTOU race condition when serving files
-rw-r--r-- | internal/domain/domain.go | 10 | ||||
-rw-r--r-- | internal/domain/domain_test.go | 23 |
2 files changed, 31 insertions, 2 deletions
diff --git a/internal/domain/domain.go b/internal/domain/domain.go index 261707cf..2c4f4e29 100644 --- a/internal/domain/domain.go +++ b/internal/domain/domain.go @@ -15,6 +15,8 @@ import ( "sync" "time" + "golang.org/x/sys/unix" + "gitlab.com/gitlab-org/gitlab-pages/internal/httperrors" "gitlab.com/gitlab-org/gitlab-pages/internal/httputil" ) @@ -231,7 +233,7 @@ func (d *D) HasProject(r *http.Request) bool { func (d *D) serveFile(w http.ResponseWriter, r *http.Request, origPath string) error { fullPath := handleGZip(w, r, origPath) - file, err := os.Open(fullPath) + file, err := openNoFollow(fullPath) if err != nil { return err } @@ -257,7 +259,7 @@ func (d *D) serveCustomFile(w http.ResponseWriter, r *http.Request, code int, or fullPath := handleGZip(w, r, origPath) // Open and serve content of file - file, err := os.Open(fullPath) + file, err := openNoFollow(fullPath) if err != nil { return err } @@ -455,3 +457,7 @@ func (d *D) ServeNotFoundHTTP(w http.ResponseWriter, r *http.Request) { func endsWithSlash(path string) bool { return strings.HasSuffix(path, "/") } + +func openNoFollow(path string) (*os.File, error) { + return os.OpenFile(path, os.O_RDONLY|unix.O_NOFOLLOW, 0) +} diff --git a/internal/domain/domain_test.go b/internal/domain/domain_test.go index 890bc6af..7544f501 100644 --- a/internal/domain/domain_test.go +++ b/internal/domain/domain_test.go @@ -397,6 +397,29 @@ func TestCacheControlHeaders(t *testing.T) { assert.WithinDuration(t, now.UTC().Add(10*time.Minute), expiresTime.UTC(), time.Minute) } +func TestOpenNoFollow(t *testing.T) { + tmpfile, err := ioutil.TempFile("", "link-test") + require.NoError(t, err) + defer tmpfile.Close() + + orig := tmpfile.Name() + softLink := orig + ".link" + defer os.Remove(orig) + + source, err := openNoFollow(orig) + require.NoError(t, err) + require.NotNil(t, source) + defer source.Close() + + err = os.Symlink(orig, softLink) + require.NoError(t, err) + defer os.Remove(softLink) + + link, err := openNoFollow(softLink) + require.Error(t, err) + require.Nil(t, link) +} + var chdirSet = false func setUpTests() { |