From 4983050f189a7e7a32af0628d9b641e50e5baa78 Mon Sep 17 00:00:00 2001 From: Noel Cower Date: Sat, 10 Mar 2018 13:25:17 -0800 Subject: [PATCH] Add a few general sanitization checks - When replacing the prefix on a directory (added recursively), use a prefix with a trailing slash to only replace directory components. - Omit files named './', '.', '..', and '/' in archive. Change-Id: Id19bbcd3656d158629de9e5b839ae7e0904dbfe7 --- mtar.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/mtar.go b/mtar.go index 3c447ab..c528afd 100644 --- a/mtar.go +++ b/mtar.go @@ -308,6 +308,7 @@ func addFile(w *tar.Writer, src, dest string, opts *FileOpts, allowRecursive boo return } + var r io.Reader var needBuffer bool var st os.FileInfo var err error @@ -381,8 +382,15 @@ func addFile(w *tar.Writer, src, dest string, opts *FileOpts, allowRecursive boo opts.setHeaderFields(hdr) + switch path.Clean(hdr.Name) { + case "./", ".", "..", "/": + if hdr.Typeflag == tar.TypeDir { + goto addDirOnly + } + return + } + // Buffer input file if it's not a regular file - var r io.Reader if needBuffer && hdr.Typeflag == tar.TypeReg { var file *os.File if src == "-" { @@ -405,6 +413,7 @@ func addFile(w *tar.Writer, src, dest string, opts *FileOpts, allowRecursive boo failOnError("write header: "+hdr.Name, w.WriteHeader(hdr)) +addDirOnly: if st.Mode().IsDir() { if allowRecursive && opts.allowRecursive() { addRecursive(w, src, dest, opts) @@ -433,8 +442,12 @@ func addFile(w *tar.Writer, src, dest string, opts *FileOpts, allowRecursive boo func addRecursive(w *tar.Writer, src, prefix string, opts *FileOpts) { src = strings.TrimRight(src, "/") + src = filepath.Clean(src) + "/" filepath.Walk(src, func(p string, info os.FileInfo, err error) error { - if filepath.Clean(p) == filepath.Clean(src) || shouldSkip(skipSrcGlobs, p) { + if info.IsDir() { + p += "/" + } + if p == src || shouldSkip(skipSrcGlobs, p) { return nil } dest := path.Join(prefix, strings.TrimPrefix(p, src)) -- 2.45.2