설명
다운로드, 업로드, 압축 해제에 사용하는 경로는 고정된 루트 아래에서 여세요. 정규화한 경로가 안에 있어도 심볼릭 링크는 밖을 가리킬 수 있습니다.
잠재적 영향
프로세스가 읽을 수 있는 설정이나 자격 증명이 노출될 수 있습니다. 쓰기 작업은 파일을 손상시키거나 나중에 실행할 내용을 바꿀 수 있습니다.
해결 방법
- 파일명만 필요하면 단일 구성 요소만 허용하세요. 상대 경로를 받으면
filepath.Rel로 루트 밖을 가리키는 경로를 거부하세요. - Go 1.24 이상에서는
os.OpenRoot로 연 루트에서 파일을 여세요.filepath.Clean이나EvalSymlinks검사 뒤 일반 경로로 다시 열면 그 사이에 대상이 바뀔 수 있습니다. - 파일별 접근 권한과 필요한 확장자·크기·깊이 제한을 적용하고 검사에 실패하면 중단하세요.
예시
이 예시에서는 관리자가 /var/app/data와 그 아래 경로를 관리하며 외부를 가리키는 링크가 없어야 합니다. 실제 서비스에서는 사용자 인증, 파일별 권한과 디렉터리 목록 공개 여부도 확인하세요.
변경 전
go
package main
import (
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func download(c *gin.Context) {
// BAD: 사용자 입력을 경로에 직접 사용
// 예: ?file=../../etc/passwd
file := c.Query("file")
baseDir := "/var/app/data"
// Join만으로는 우회 가능: Join은 Clean을 수행하며 상위로 탈출할 수 있음
fullPath := filepath.Join(baseDir, file)
if _, err := os.Stat(fullPath); err != nil {
c.String(http.StatusNotFound, "not found")
return
}
http.ServeFile(c.Writer, c.Request, fullPath)
}
func main() {
r := gin.Default()
r.GET("/download", download)
r.Run()
}
변경 후
go
package main
import (
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/gin-gonic/gin"
)
func isUnderBase(base, target string) bool {
// 경로 정규화 후 구분자도 함께 비교하여 base 하위 여부 확인
b := filepath.Clean(base)
t := filepath.Clean(target)
sep := string(os.PathSeparator)
if runtime.GOOS == "windows" {
b = strings.ToLower(b)
t = strings.ToLower(t)
}
return strings.HasPrefix(t+sep, b+sep)
}
func safeDownload(c *gin.Context) {
file := c.Query("file")
baseDir := "/var/app/data" // 고정 루트 디렉터리
// 1) 절대경로, 상위 이동을 포함하더라도 baseDir 내부만 허용
target := filepath.Join(baseDir, file)
if !isUnderBase(baseDir, target) {
c.String(http.StatusBadRequest, "invalid path")
return
}
// 2) 필요 시 확장자 화이트리스트 예시
// if !strings.HasSuffix(strings.ToLower(target), ".txt") { ... }
// 3) 파일 제공
if _, err := os.Stat(target); err != nil {
c.String(http.StatusNotFound, "not found")
return
}
http.ServeFile(c.Writer, c.Request, target)
}
func main() {
r := gin.Default()
r.GET("/download", safeDownload)
r.Run()
}
isUnderBase는 구분자를 포함해 경로 문자열을 비교합니다. ServeFile에 넘기는 대상은 쿼리에서 왔으므로 URL 경로 검사만으로는 충분하지 않습니다.