Skip to content

Commit

Permalink
fix: enhance file path security
Browse files Browse the repository at this point in the history
- Add file path validation to prevent directory traversal attacks

- Clean and normalize file paths

- Convert relative paths to absolute paths

- Add better error messages for invalid paths

- Fix G304 (CWE-22) security issue
  • Loading branch information
davidhoo committed Jan 7, 2025
1 parent 6f7d9d0 commit 590656e
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion cmd/jp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"unicode"
Expand Down Expand Up @@ -379,7 +380,23 @@ func readInput(file string) (string, error) {
if file == "" {
input, err = io.ReadAll(os.Stdin)
} else {
input, err = os.ReadFile(file)
// 验证文件路径
cleanPath := filepath.Clean(file)
if !filepath.IsAbs(cleanPath) {
// 如果是相对路径,转换为绝对路径
cleanPath, err = filepath.Abs(cleanPath)
if err != nil {
return "", fmt.Errorf("%s: %v", errorColor("error processing file path"), err)
}
}

// 检查路径是否包含 .. 序列
if strings.Contains(cleanPath, "..") {
return "", fmt.Errorf("%s: path contains parent directory reference", errorColor("error: invalid path"))
}

// 读取文件
input, err = os.ReadFile(cleanPath)
}
if err != nil {
return "", fmt.Errorf("%s: %v", errorColor("error reading input"), err)
Expand Down

0 comments on commit 590656e

Please sign in to comment.