High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(security): harden file writes, Slowloris protection, gosec CI (#24)
luigiagent96587a499bce
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6fad50c7..161211bc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -55,3 +55,30 @@ jobs:uses: golangci/golangci-lint-action@v7with:version: v2.9.0++ security:+ name: Security Scan+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-go@v5+ with:+ go-version: '1.26'++ - name: Install gosec+ run: go install github.com/securego/gosec/v2/cmd/gosec@latest++ - name: Run gosec+ run: gosec -exclude=G301,G302,G304,G306,G404,G107,G115,G703,G704,G705,G706 -fmt=json -out=gosec-results.json ./... || true++ - name: Check critical findings+ run: |+ # Fail on G112 (Slowloris), G204 (command injection)+ ISSUES=$(cat gosec-results.json | jq '[.Issues[] | select(.rule_id == "G112" or .rule_id == "G204")] | length')+ echo "Critical issues: $ISSUES"+ cat gosec-results.json | jq '.Stats'+ if [ "$ISSUES" -gt 0 ]; then+ cat gosec-results.json | jq '.Issues[] | select(.rule_id == "G112" or .rule_id == "G204")'+ exit 1+ fidiff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.goindex 63a6e986..1650fd0a 100644--- a/cmd/pinchtab/cmd_dashboard.go+++ b/cmd/pinchtab/cmd_dashboard.go@@ -92,7 +92,11 @@ func runDashboard(cfg *config.RuntimeConfig) {handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux))),)- srv := &http.Server{Addr: cfg.Bind + ":" + dashPort, Handler: handler}+ srv := &http.Server{+ Addr: cfg.Bind + ":" + dashPort,+ Handler: handler,+ ReadHeaderTimeout: 10 * time.Second,+ }autoLaunch := strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "1") ||strings.EqualFold(os.Getenv("PINCHTAB_AUTO_LAUNCH"), "true") ||diff --git a/cmd/pinchtab/main.go b/cmd/pinchtab/main.goindex cd48a99f..9041749a 100644--- a/cmd/pinchtab/main.go+++ b/cmd/pinchtab/main.go@@ -177,7 +177,11 @@ func main() {handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux))),)- srv := &http.Server{Addr: cfg.ListenAddr(), Handler: handler}+ srv := &http.Server{+ Addr: cfg.ListenAddr(),+ Handler: handler,+ ReadHeaderTimeout: 10 * time.Second,+ }setupSignalHandler(doShutdown, func() {orch.ForceShutdown()diff --git a/internal/handlers/download.go b/internal/handlers/download.goindex 34fa6b92..b56174e1 100644--- a/internal/handlers/download.go+++ b/internal/handlers/download.go@@ -119,11 +119,17 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {web.Error(w, 400, fmt.Errorf("path required when output=file"))return}- if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {+ safe, pathErr := web.SafePath(h.Config.StateDir, filePath)+ if pathErr != nil {+ web.Error(w, 400, fmt.Errorf("invalid path: %w", pathErr))+ return+ }+ filePath = safe+ if err := os.MkdirAll(filepath.Dir(filePath), 0750); err != nil {web.Error(w, 500, fmt.Errorf("failed to create directory: %w", err))return}- if err := os.WriteFile(filePath, body, 0644); err != nil {+ if err := os.WriteFile(filePath, body, 0600); err != nil {web.Error(w, 500, fmt.Errorf("failed to write file: %w", err))return}diff --git a/internal/handlers/media.go b/internal/handlers/media.goindex 3acfbb92..78d9fe49 100644--- a/internal/handlers/media.go+++ b/internal/handlers/media.go@@ -61,7 +61,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {if output == "file" {screenshotDir := filepath.Join(h.Config.StateDir, "screenshots")- if err := os.MkdirAll(screenshotDir, 0755); err != nil {+ if err := os.MkdirAll(screenshotDir, 0750); err != nil {web.Error(w, 500, fmt.Errorf("create screenshot dir: %w", err))return}@@ -70,7 +70,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {filename := fmt.Sprintf("screenshot-%s.jpg", timestamp)filePath := filepath.Join(screenshotDir, filename)- if err := os.WriteFile(filePath, buf, 0644); err != nil {+ if err := os.WriteFile(filePath, buf, 0600); err != nil {web.Error(w, 500, fmt.Errorf("write screenshot: %w", err))return}@@ -140,15 +140,26 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {savePath := r.URL.Query().Get("path")if savePath == "" {pdfDir := filepath.Join(h.Config.StateDir, "pdfs")- if err := os.MkdirAll(pdfDir, 0755); err != nil {+ if err := os.MkdirAll(pdfDir, 0750); err != nil {web.Error(w, 500, fmt.Errorf("create pdf dir: %w", err))return}timestamp := time.Now().Format("20060102-150405")savePath = filepath.Join(pdfDir, fmt.Sprintf("page-%s.pdf", timestamp))+ } else {+ safe, err := web.SafePath(h.Config.StateDir, savePath)+ if err != nil {+ web.Error(w, 400, fmt.Errorf("invalid path: %w", err))+ return+ }+ savePath = safe+ if err := os.MkdirAll(filepath.Dir(savePath), 0750); err != nil {+ web.Error(w, 500, fmt.Errorf("create dir: %w", err))+ return+ }}- if err := os.WriteFile(savePath, buf, 0644); err != nil {+ if err := os.WriteFile(savePath, buf, 0600); err != nil {web.Error(w, 500, fmt.Errorf("write pdf: %w", err))return}diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex 7722672e..767e2446 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -151,7 +151,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if output == "file" {snapshotDir := filepath.Join(h.Config.StateDir, "snapshots")- if err := os.MkdirAll(snapshotDir, 0755); err != nil {+ if err := os.MkdirAll(snapshotDir, 0750); err != nil {web.Error(w, 500, fmt.Errorf("create snapshot dir: %w", err))return}@@ -227,13 +227,18 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {filePath := filepath.Join(snapshotDir, filename)if outputPath != "" {- filePath = outputPath- if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {+ safe, err := web.SafePath(h.Config.StateDir, outputPath)+ if err != nil {+ web.Error(w, 400, fmt.Errorf("invalid path: %w", err))+ return+ }+ filePath = safe+ if err := os.MkdirAll(filepath.Dir(filePath), 0750); err != nil {web.Error(w, 500, fmt.Errorf("create output dir: %w", err))return}}- if err := os.WriteFile(filePath, content, 0644); err != nil {+ if err := os.WriteFile(filePath, content, 0600); err != nil {web.Error(w, 500, fmt.Errorf("write snapshot: %w", err))return}diff --git a/internal/profiles/copydir.go b/internal/profiles/copydir.gonew file mode 100644index 00000000..d35e8a2d--- /dev/null+++ b/internal/profiles/copydir.go@@ -0,0 +1,58 @@+package profiles++import (+ "fmt"+ "io"+ "io/fs"+ "os"+ "path/filepath"+)++// copyDir recursively copies src to dst, preserving permissions.+func copyDir(src, dst string) error {+ return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }++ rel, err := filepath.Rel(src, path)+ if err != nil {+ return err+ }+ target := filepath.Join(dst, rel)++ if d.IsDir() {+ info, err := d.Info()+ if err != nil {+ return err+ }+ return os.MkdirAll(target, info.Mode().Perm())+ }++ return copyFile(path, target)+ })+}++func copyFile(src, dst string) error {+ in, err := os.Open(src) // #nosec G304 — src is validated by caller+ if err != nil {+ return fmt.Errorf("open %s: %w", src, err)+ }+ defer func() { _ = in.Close() }()++ info, err := in.Stat()+ if err != nil {+ return err+ }++ out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, info.Mode().Perm())+ if err != nil {+ return fmt.Errorf("create %s: %w", dst, err)+ }+ defer func() { _ = out.Close() }()++ if _, err := io.Copy(out, in); err != nil {+ return fmt.Errorf("copy %s: %w", src, err)+ }+ return out.Close()+}diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.goindex 3a7d72c5..5fa3acdb 100644--- a/internal/profiles/profiles.go+++ b/internal/profiles/profiles.go@@ -7,7 +7,6 @@ import ("io/fs""log/slog""os"- "os/exec""path/filepath""sort""sync"@@ -155,12 +154,21 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {}}+ // Validate source path exists and is a directory+ srcInfo, err := os.Stat(sourcePath)+ if err != nil {+ return fmt.Errorf("source path invalid: %w", err)+ }+ if !srcInfo.IsDir() {+ return fmt.Errorf("source path must be a directory")+ }+slog.Info("importing profile", "name", name, "source", sourcePath)- if err := exec.Command("cp", "-a", sourcePath, dest).Run(); err != nil {+ if err := copyDir(sourcePath, dest); err != nil {return fmt.Errorf("copy failed: %w", err)}- if err := os.WriteFile(filepath.Join(dest, ".pinchtab-imported"), []byte(sourcePath), 0644); err != nil {+ if err := os.WriteFile(filepath.Join(dest, ".pinchtab-imported"), []byte(sourcePath), 0600); err != nil {slog.Warn("failed to write import marker", "err", err)}return nildiff --git a/internal/web/safepath.go b/internal/web/safepath.gonew file mode 100644index 00000000..b667f7ed--- /dev/null+++ b/internal/web/safepath.go@@ -0,0 +1,30 @@+package web++import (+ "fmt"+ "path/filepath"+ "strings"+)++// SafePath validates that the resolved path stays within the allowed base directory.+// Returns the cleaned absolute path or an error if traversal is detected.+func SafePath(base, userPath string) (string, error) {+ absBase, err := filepath.Abs(base)+ if err != nil {+ return "", fmt.Errorf("invalid base path: %w", err)+ }++ var resolved string+ if filepath.IsAbs(userPath) {+ resolved = filepath.Clean(userPath)+ } else {+ resolved = filepath.Clean(filepath.Join(absBase, userPath))+ }++ // Ensure resolved path is within or equal to base+ if !strings.HasPrefix(resolved, absBase+string(filepath.Separator)) && resolved != absBase {+ return "", fmt.Errorf("path %q escapes base directory %q", userPath, absBase)+ }++ return resolved, nil+}diff --git a/internal/web/safepath_test.go b/internal/web/safepath_test.gonew file mode 100644index 00000000..b21a0562--- /dev/null+++ b/internal/web/safepath_test.go@@ -0,0 +1,30 @@+package web++import (+ "testing"+)++func TestSafePath(t *testing.T) {+ tests := []struct {+ name string+ base string+ path string+ wantErr bool+ }{+ {"valid relative", "/tmp/state", "pdfs/out.pdf", false},+ {"valid absolute inside", "/tmp/state", "/tmp/state/pdfs/out.pdf", false},+ {"traversal dotdot", "/tmp/state", "../etc/passwd", true},+ {"traversal absolute", "/tmp/state", "/etc/passwd", true},+ {"traversal hidden", "/tmp/state", "pdfs/../../etc/passwd", true},+ {"base itself", "/tmp/state", "/tmp/state", false},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ _, err := SafePath(tt.base, tt.path)+ if (err != nil) != tt.wantErr {+ t.Errorf("SafePath(%q, %q) error = %v, wantErr %v", tt.base, tt.path, err, tt.wantErr)+ }+ })+ }+}