-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathuploadlayer.go
More file actions
99 lines (87 loc) · 2.66 KB
/
uploadlayer.go
File metadata and controls
99 lines (87 loc) · 2.66 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package httpserver
import (
"errors"
"io"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/simplehttpserver/pkg/unit"
)
// uploadlayer handles PUT requests and save the file to disk
func (t *HTTPServer) uploadlayer(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Handles file write if enabled
if EnableUpload && r.Method == http.MethodPut {
// sandbox - calcolate absolute path
if t.options.Sandbox {
absPath, err := filepath.Abs(filepath.Join(t.options.Folder, r.URL.Path))
if err != nil {
gologger.Print().Msgf("%s\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
// check if the path is within the configured folder
pattern := t.options.Folder + string(filepath.Separator) + "*"
matched, err := filepath.Match(pattern, absPath)
if err != nil {
gologger.Print().Msgf("%s\n", err)
w.WriteHeader(http.StatusBadRequest)
return
} else if !matched {
gologger.Print().Msg("pointing to unauthorized directory")
w.WriteHeader(http.StatusBadRequest)
return
}
}
var (
data []byte
err error
)
if t.options.Sandbox {
maxFileSize := unit.ToMb(t.options.MaxFileSize)
// check header content length
if r.ContentLength > maxFileSize {
gologger.Print().Msg("request too large")
return
}
// body max length
r.Body = http.MaxBytesReader(w, r.Body, maxFileSize)
}
data, err = io.ReadAll(r.Body)
if err != nil {
gologger.Print().Msgf("%s\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
sanitizedPath := filepath.FromSlash(path.Clean("/" + strings.Trim(r.URL.Path, "/")))
err = handleUpload(t.options.Folder, sanitizedPath, data)
if err != nil {
gologger.Print().Msgf("%s\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
} else {
w.WriteHeader(http.StatusCreated)
return
}
}
handler.ServeHTTP(w, r)
})
}
func handleUpload(base, file string, data []byte) error {
// rejects all paths containing a non exhaustive list of invalid characters - This is only a best effort as the tool is meant for development
if strings.ContainsAny(file, "\\`\"':") {
return errors.New("invalid character")
}
untrustedPath := filepath.Clean(filepath.Join(base, file))
if !strings.HasPrefix(untrustedPath, filepath.Clean(base)) {
return errors.New("invalid path")
}
trustedPath := untrustedPath
if _, err := os.Stat(filepath.Dir(trustedPath)); os.IsNotExist(err) {
return errors.New("invalid path")
}
return os.WriteFile(trustedPath, data, 0655)
}