Safe Tar Extraction With Path Checks
Extraction validates every entry name before touching disk: absolute paths and .. components are rejected so archives cannot write outside the target.
Code
package main
import (
"archive/tar"
"bytes"
"fmt"
"path/filepath"
"strings"
)
func buildArchive() []byte {
var buf bytes.Buffer
w := tar.NewWriter(&buf)
for _, name := range []string{"docs/readme.txt", "../evil.txt", "/abs/path.txt"} {
if err := w.WriteHeader(&tar.Header{
Name: name,
Mode: 0o644,
Size: int64(len("content of " + name)),
}); err != nil {
panic(err)
}
if _, err := w.Write([]byte("content of " + name)); err != nil {
panic(err)
}
}
if err := w.Close(); err != nil {
panic(err)
}
return buf.Bytes()
}
// isSafePath 拒绝绝对路径;Clean 后仍以 .. 开头的条目会逃出目标目录
func isSafePath(name string) bool {
if filepath.IsAbs(name) {
return false
}
return !strings.HasPrefix(filepath.Clean(name), "..")
}
func main() {
r := tar.NewReader(bytes.NewReader(buildArchive()))
for {
hdr, err := r.Next()
if err != nil {
break // io.EOF:条目读完
}
if !isSafePath(hdr.Name) {
fmt.Println("rejected:", hdr.Name)
continue
}
fmt.Println("accepted:", filepath.Clean(hdr.Name))
}
}Line-by-line reading
Count the functions buildArchive, isSafePath and main as the entire surface area of Safe Tar Extraction With Path Checks.
One loop does the cycling here: for _, name := range []string{"docs/readme.txt", "../evil.txt", "/abs/path.txt"}. Every err != nil branch (3 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.
What to watch for
- Nothing needs adding to the project ahead of the run.
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Using it
Signature: func buildArchive() []byte
Output lines are prefixed (rejected:, accepted:), so the outcome of every step stays visible.
The entry point wires buildArchive and isSafePath together — run it once and the whole demo flows.
Key statements
for _, name := range []string{"docs/readme.txt", "../evil.txt", "/abs/path.txt"} {
if err := w.WriteHeader(&tar.Header{
Name: name,
Mode: 0o644,
Size: int64(len("content of " + name)),
}); err != nil {
panic(err)
}
if _, err := w.Write([]byte("content of " + name)); err != nil {
panic(err)
}
}
func isSafePath(name string) bool {
if filepath.IsAbs(name) {
return false
}
return !strings.HasPrefix(filepath.Clean(name), "..")
}
if err != nil {
break // io.EOF:条目读完
}
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- Through `panic(err)` — the 3 checkpoints test `err` and abort the run on the first non-nil one.
- What does Safe Tar Extraction With Path Checks print when run?
- Invoke the file as-is — the `rejected:`, `accepted:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.