diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 3934986..0fb522d 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -63,6 +63,7 @@ type UploadInfo struct { Width int Height int CanResize bool + IsImage bool ModTime time.Time } @@ -687,12 +688,20 @@ func (s *Server) handleAdminBinDelete(w http.ResponseWriter, r *http.Request) { // ---- Upload helpers ---- -var validUploadRe = regexp.MustCompile(`^[0-9a-f]{32}\.(png|jpg|gif|webp)$`) +var validUploadRe = regexp.MustCompile(`^[0-9a-f]{32}\.[a-z0-9]{1,10}$`) func validUploadFilename(name string) bool { return validUploadRe.MatchString(name) } +var imageExts = map[string]bool{ + ".png": true, ".jpg": true, ".gif": true, ".webp": true, +} + +func isImageFile(name string) bool { + return imageExts[strings.ToLower(filepath.Ext(name))] +} + func formatBytes(n int64) string { switch { case n >= 1024*1024: @@ -749,6 +758,24 @@ func scaleImage(src image.Image, maxDim int) image.Image { return dst } +// handleUploadsServe serves files from the upload directory. For non-image +// files it forces Content-Disposition: attachment with an octet-stream type so +// that arbitrary uploads (e.g. HTML, SVG, JS) cannot be rendered in-browser +// from the same origin as the admin panel. +func (s *Server) handleUploadsServe(w http.ResponseWriter, r *http.Request) { + name := strings.TrimPrefix(r.URL.Path, "/uploads/") + if !validUploadFilename(name) { + http.NotFound(w, r) + return + } + path := filepath.Join(s.cfg.Upload.Dir, name) + if !isImageFile(name) { + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`) + } + http.ServeFile(w, r, path) +} + // ---- Upload management handlers ---- func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) { @@ -776,15 +803,18 @@ func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) { Size: info.Size(), SizeHuman: formatBytes(info.Size()), URL: "/uploads/" + name, + IsImage: isImageFile(name), ModTime: info.ModTime(), } ext := strings.ToLower(filepath.Ext(name)) - if f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, name)); err == nil { - if cfg, _, err := image.DecodeConfig(f); err == nil { - ui.Width = cfg.Width - ui.Height = cfg.Height + if ui.IsImage { + if f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, name)); err == nil { + if cfg, _, err := image.DecodeConfig(f); err == nil { + ui.Width = cfg.Width + ui.Height = cfg.Height + } + f.Close() } - f.Close() } if ext == ".png" || ext == ".jpg" { ui.CanResize = true @@ -981,6 +1011,100 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { }) } +// ---- File upload handler (any file, 5 MB max) ---- + +var validExtRe = regexp.MustCompile(`^[a-z0-9]{1,10}$`) + +func (s *Server) handleFileUpload(w http.ResponseWriter, r *http.Request) { + const maxFileBytes = 5 * 1024 * 1024 + r.Body = http.MaxBytesReader(w, r.Body, maxFileBytes+4096) + + rc := http.NewResponseController(w) + rc.SetReadDeadline(time.Now().Add(120 * time.Second)) + rc.SetWriteDeadline(time.Now().Add(120 * time.Second)) + + if !verifyCSRF(r) { + jsonError(w, "Invalid CSRF token", http.StatusForbidden) + return + } + + file, header, err := r.FormFile("file") + if err != nil { + if err.Error() == "http: request body too large" { + jsonError(w, "File too large (max 5 MB)", http.StatusRequestEntityTooLarge) + } else { + jsonError(w, "No file provided", http.StatusBadRequest) + } + return + } + defer file.Close() + + ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(header.Filename), ".")) + if ext == "" || !validExtRe.MatchString(ext) { + jsonError(w, "Invalid file extension", http.StatusBadRequest) + return + } + + randBytes := make([]byte, 16) + rand.Read(randBytes) + filename := hex.EncodeToString(randBytes) + "." + ext + + destPath := filepath.Join(s.cfg.Upload.Dir, filename) + out, err := os.Create(destPath) + if err != nil { + jsonError(w, "Failed to save file", http.StatusInternalServerError) + return + } + defer out.Close() + + written, err := io.Copy(out, file) + if err != nil { + os.Remove(destPath) + jsonError(w, "Failed to save file", http.StatusInternalServerError) + return + } + if written > maxFileBytes { + os.Remove(destPath) + jsonError(w, "File too large (max 5 MB)", http.StatusRequestEntityTooLarge) + return + } + + fileURL := "/uploads/" + filename + displayName := sanitizeDisplayFilename(header.Filename) + if displayName == "" { + displayName = filename + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{ + "url": fileURL, + "filename": displayName, + "markdown": "[" + displayName + "](" + fileURL + ")", + }) +} + +// sanitizeDisplayFilename strips path components, control chars, and +// markdown-significant characters from a user-supplied filename so that it +// can be safely embedded in a markdown link. +func sanitizeDisplayFilename(name string) string { + name = filepath.Base(name) + var b strings.Builder + for _, r := range name { + if r < 32 || r == 127 { + continue + } + switch r { + case '[', ']', '(', ')', '\\', '`', '*', '<', '>', '"', '\'': + continue + } + b.WriteRune(r) + } + s := strings.TrimSpace(b.String()) + if len(s) > 100 { + s = s[:100] + } + return s +} + var validPasteNameRe = strings.NewReplacer() // placeholder — use inline check below func validPasteName(name string) bool { if len(name) == 0 || len(name) > 64 { diff --git a/internal/server/server.go b/internal/server/server.go index b70db8c..8d7a60c 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -68,8 +68,9 @@ func (s *Server) Start() error { staticSub, _ := fs.Sub(staticFS, "static") mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub)))) - // Uploaded images (public — images appear in public pastes) - mux.Handle("GET /uploads/", http.StripPrefix("/uploads/", http.FileServer(http.Dir(s.cfg.Upload.Dir)))) + // Uploaded files (public — appear in public pastes). Non-image files are + // served as attachments to prevent same-origin XSS via HTML/SVG/JS uploads. + mux.HandleFunc("GET /uploads/", s.handleUploadsServe) // Public routes mux.HandleFunc("GET /{$}", s.handleIndex) @@ -96,6 +97,7 @@ func (s *Server) Start() error { mux.HandleFunc("POST /admin/bin/delete/{id}", s.requireAuth(s.requireCSRF(s.handleAdminBinDelete))) mux.HandleFunc("GET /admin/bin/qr/{name}", s.requireAuth(s.handleBinQR)) mux.HandleFunc("POST /admin/upload", s.requireAuth(s.handleUpload)) + mux.HandleFunc("POST /admin/upload-file", s.requireAuth(s.handleFileUpload)) mux.HandleFunc("GET /admin/uploads", s.requireAuth(s.handleAdminUploads)) mux.HandleFunc("POST /admin/uploads/delete/{filename}", s.requireAuth(s.requireCSRF(s.handleAdminUploadDelete))) mux.HandleFunc("POST /admin/uploads/resize/{filename}", s.requireAuth(s.handleAdminUploadResize)) diff --git a/internal/server/templates/admin_bin_edit.html b/internal/server/templates/admin_bin_edit.html index 23be9fa..5ee2954 100644 --- a/internal/server/templates/admin_bin_edit.html +++ b/internal/server/templates/admin_bin_edit.html @@ -80,8 +80,10 @@
- - + + + +
{{if .Paste}} @@ -148,7 +150,9 @@ (function() { var textarea = document.querySelector('textarea[name="content"]'); - var uploadBtn = document.getElementById('upload-btn'); + var uploadImgBtn = document.getElementById('upload-img-btn'); + var uploadFileBtn = document.getElementById('upload-file-btn'); + var imgInput = document.getElementById('img-input'); var fileInput = document.getElementById('file-input'); var status = document.getElementById('upload-status'); @@ -157,26 +161,39 @@ return match ? match[1] : ''; } - function uploadFile(file) { - if (!file || !file.type.startsWith('image/')) { - status.textContent = 'Not an image file'; - return; - } - if (file.size > 50 * 1024 * 1024) { - status.textContent = 'File too large (max 50 MB)'; - return; + function setButtonsDisabled(v) { + uploadImgBtn.disabled = v; + uploadFileBtn.disabled = v; + } + + function doUpload(file, isImage) { + if (isImage) { + if (!file || !file.type.startsWith('image/')) { + status.textContent = 'Not an image file'; + return; + } + if (file.size > 50 * 1024 * 1024) { + status.textContent = 'File too large (max 50 MB)'; + return; + } + } else { + if (file.size > 5 * 1024 * 1024) { + status.textContent = 'File too large (max 5 MB)'; + return; + } } status.textContent = 'Uploading\u2026'; - uploadBtn.disabled = true; + setButtonsDisabled(true); var fd = new FormData(); fd.append('file', file); fd.append('csrf_token', getCsrfToken()); + var endpoint = isImage ? '/admin/upload' : '/admin/upload-file'; - fetch('/admin/upload', { method: 'POST', body: fd, credentials: 'same-origin' }) + fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' }) .then(function(res) { return res.json(); }) .then(function(data) { - uploadBtn.disabled = false; + setButtonsDisabled(false); if (data.error) { status.textContent = 'Error: ' + data.error; return; @@ -186,7 +203,7 @@ setTimeout(function() { status.textContent = ''; }, 3000); }) .catch(function() { - uploadBtn.disabled = false; + setButtonsDisabled(false); status.textContent = 'Upload failed'; }); } @@ -201,9 +218,15 @@ textarea.focus(); } - uploadBtn.addEventListener('click', function() { fileInput.click(); }); + uploadImgBtn.addEventListener('click', function() { imgInput.click(); }); + uploadFileBtn.addEventListener('click', function() { fileInput.click(); }); + + imgInput.addEventListener('change', function() { + if (imgInput.files.length > 0) doUpload(imgInput.files[0], true); + imgInput.value = ''; + }); fileInput.addEventListener('change', function() { - if (fileInput.files.length > 0) uploadFile(fileInput.files[0]); + if (fileInput.files.length > 0) doUpload(fileInput.files[0], false); fileInput.value = ''; }); @@ -212,7 +235,7 @@ for (var i = 0; i < items.length; i++) { if (items[i].type.indexOf('image') !== -1) { e.preventDefault(); - uploadFile(items[i].getAsFile()); + doUpload(items[i].getAsFile(), true); return; } } diff --git a/internal/server/templates/admin_uploads.html b/internal/server/templates/admin_uploads.html index ca3e2a9..dafdf6e 100644 --- a/internal/server/templates/admin_uploads.html +++ b/internal/server/templates/admin_uploads.html @@ -35,11 +35,13 @@

Uploads

-

{{len .Uploads}} images

+

{{len .Uploads}} files

- - + + + +
@@ -58,16 +60,20 @@ {{range .Uploads}} - + + {{if .IsImage}} + {{else}}📄 + {{end}} + {{.Filename}} {{.SizeHuman}} {{if .Width}}{{.Width}}×{{.Height}}{{else}}—{{end}} {{.ModTime.Format "2006-01-02 15:04"}}
- + {{if .CanResize}}{{end}} -
+
@@ -78,8 +84,8 @@
- 🖼 -

No uploads yet. Use the button above to upload an image.

+ 📄 +

No uploads yet. Use the buttons above to upload an image or file.

@@ -117,8 +123,9 @@ return match ? match[1] : ''; } - function copyMarkdown(filename, btn) { - var md = '![](' + '/uploads/' + filename + ')'; + function copyMarkdown(filename, isImage, btn) { + var url = '/uploads/' + filename; + var md = isImage ? '![](' + url + ')' : '[' + filename + '](' + url + ')'; navigator.clipboard.writeText(md).then(function() { var orig = btn.textContent; btn.textContent = 'Copied!'; @@ -168,35 +175,53 @@ }); }); - // Upload button - var uploadBtn = document.getElementById('upload-btn'); + // Upload buttons + var uploadImgBtn = document.getElementById('upload-img-btn'); + var uploadFileBtn = document.getElementById('upload-file-btn'); + var imgInput = document.getElementById('img-input'); var fileInput = document.getElementById('file-input'); var uploadStatus = document.getElementById('upload-status'); - uploadBtn.addEventListener('click', function() { fileInput.click(); }); + uploadImgBtn.addEventListener('click', function() { imgInput.click(); }); + uploadFileBtn.addEventListener('click', function() { fileInput.click(); }); + + imgInput.addEventListener('change', function() { + if (imgInput.files.length > 0) doUpload(imgInput.files[0], true); + imgInput.value = ''; + }); fileInput.addEventListener('change', function() { - if (fileInput.files.length > 0) doUpload(fileInput.files[0]); + if (fileInput.files.length > 0) doUpload(fileInput.files[0], false); fileInput.value = ''; }); - function doUpload(file) { - if (!file || !file.type.startsWith('image/')) { - uploadStatus.textContent = 'Not an image file'; - return; - } - if (file.size > 50 * 1024 * 1024) { - uploadStatus.textContent = 'File too large (max 50 MB)'; - return; + function doUpload(file, isImage) { + if (isImage) { + if (!file || !file.type.startsWith('image/')) { + uploadStatus.textContent = 'Not an image file'; + return; + } + if (file.size > 50 * 1024 * 1024) { + uploadStatus.textContent = 'File too large (max 50 MB)'; + return; + } + } else { + if (file.size > 5 * 1024 * 1024) { + uploadStatus.textContent = 'File too large (max 5 MB)'; + return; + } } uploadStatus.textContent = 'Uploading\u2026'; - uploadBtn.disabled = true; + uploadImgBtn.disabled = true; + uploadFileBtn.disabled = true; var fd = new FormData(); fd.append('file', file); fd.append('csrf_token', getCsrfToken()); - fetch('/admin/upload', { method: 'POST', body: fd, credentials: 'same-origin' }) + var endpoint = isImage ? '/admin/upload' : '/admin/upload-file'; + fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' }) .then(function(r) { return r.json(); }) .then(function(data) { - uploadBtn.disabled = false; + uploadImgBtn.disabled = false; + uploadFileBtn.disabled = false; if (data.error) { uploadStatus.textContent = 'Error: ' + data.error; } else { @@ -204,7 +229,8 @@ } }) .catch(function() { - uploadBtn.disabled = false; + uploadImgBtn.disabled = false; + uploadFileBtn.disabled = false; uploadStatus.textContent = 'Upload failed'; }); }