forked from projectdiscovery/simplehttpserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsandboxfs.go
More file actions
57 lines (49 loc) · 1.26 KB
/
sandboxfs.go
File metadata and controls
57 lines (49 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package httpserver
import (
"errors"
"net/http"
"path/filepath"
)
// SandboxFileSystem implements superbasic security checks
type SandboxFileSystem struct {
fs http.FileSystem
RootFolder string
}
// Open performs basic security checks before providing folder/file content
func (sbfs SandboxFileSystem) Open(path string) (http.File, error) {
abspath, err := filepath.Abs(filepath.Join(sbfs.RootFolder, path))
if err != nil {
return nil, err
}
filename := filepath.Base(abspath)
// rejects names starting with a dot like .file
dotmatch, err := filepath.Match(".*", filename)
if err != nil {
return nil, err
} else if dotmatch {
return nil, errors.New("invalid file")
}
// reject symlinks
symlinkCheck, err := filepath.EvalSymlinks(abspath)
if err != nil {
return nil, err
}
if symlinkCheck != abspath {
return nil, errors.New("symlinks not allowed")
}
// check if the path is within the configured folder
if sbfs.RootFolder != abspath {
pattern := sbfs.RootFolder + string(filepath.Separator) + "*"
matched, err := filepath.Match(pattern, abspath)
if err != nil {
return nil, err
} else if !matched {
return nil, errors.New("invalid file")
}
}
f, err := sbfs.fs.Open(path)
if err != nil {
return nil, err
}
return f, nil
}