Skip to content

Commit 539243b

Browse files
authored
s2sx: Clean symlink targets (#1163)
When self-extractor is extracting files from TAR validate that symlinks remains inside the destination. Executables are already expected to be trusted and since they are embedded with the archive, so there really is no breach of trust. This change is mainly to discourage false/pointless AI reports.
1 parent bd9228c commit 539243b

1 file changed

Lines changed: 26 additions & 2 deletions

File tree

‎s2/cmd/_s2sx/_unpack/main.go‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,16 @@ func untar(dst string, r io.Reader) error {
293293
f.Close()
294294
case tar.TypeSymlink:
295295
target = path.Clean(target)
296+
// A symlink target is resolved relative to the link's own
297+
// directory (or used as-is when absolute); reject any that
298+
// escape dst so the link cannot point outside the archive root.
299+
linkTarget := header.Linkname
300+
if !filepath.IsAbs(linkTarget) {
301+
linkTarget = filepath.Join(filepath.Dir(target), linkTarget)
302+
}
303+
if !within(dst, linkTarget) {
304+
return fmt.Errorf("illegal link target: %s", header.Linkname)
305+
}
296306
if !*quiet {
297307
fmt.Println(target)
298308
}
@@ -303,6 +313,10 @@ func untar(dst string, r io.Reader) error {
303313
}
304314
case tar.TypeLink:
305315
target = path.Clean(target)
316+
// Hardlink targets are relative to the archive root.
317+
if err := checkPath(dst, header.Linkname); err != nil {
318+
return err
319+
}
306320
if !*quiet {
307321
fmt.Println(target)
308322
}
@@ -318,14 +332,24 @@ func untar(dst string, r io.Reader) error {
318332
// Thanks to https://github.com/mholt/archiver for the following:
319333

320334
func checkPath(dst, filename string) error {
321-
dest := filepath.Join(dst, filename)
322335
//prevent path traversal attacks
323-
if !strings.HasPrefix(dest, dst) {
336+
if !within(dst, filepath.Join(dst, filename)) {
324337
return fmt.Errorf("illegal file path: %s", filename)
325338
}
326339
return nil
327340
}
328341

342+
// within reports whether target stays inside dst. A raw strings.HasPrefix
343+
// check is not separator-aware: dst "out" would wrongly accept the sibling
344+
// "out_evil". filepath.Rel collapses the path and a ".." result means escape.
345+
func within(dst, target string) bool {
346+
rel, err := filepath.Rel(dst, target)
347+
if err != nil {
348+
return false
349+
}
350+
return rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
351+
}
352+
329353
func writeNewSymbolicLink(fpath string, target string) error {
330354
err := os.MkdirAll(filepath.Dir(fpath), 0755)
331355
if err != nil {

0 commit comments

Comments
 (0)