~nilium/mtar

4983050f189a7e7a32af0628d9b641e50e5baa78 — Noel Cower 6 years ago 3730d69
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
1 files changed, 15 insertions(+), 2 deletions(-)

M mtar.go
M mtar.go => mtar.go +15 -2
@@ 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))