-
Notifications
You must be signed in to change notification settings - Fork 0
/
tar.go
93 lines (77 loc) · 2.4 KB
/
tar.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package externalbuilder
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
// Untar takes a gzip-ed tar archive, and extracts it to dst.
// It returns an error if the tar contains any files which would escape to a
// parent of dst, or if the archive contains any files whose type is not
// a regular file or directory.
func Untar(buffer io.Reader, dst string) error {
gzr, err := gzip.NewReader(buffer)
if err != nil {
return err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
if err == io.EOF {
return nil
}
if err != nil {
return errors.WithMessage(err, "could not get next tar element")
}
if !ValidPath(header.Name) {
return errors.Errorf("tar contains the absolute or escaping path '%s'", header.Name)
}
target := filepath.Join(dst, header.Name)
switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(target, 0700); err != nil {
return errors.WithMessagef(err, "could not create directory '%s'", header.Name)
}
case tar.TypeReg:
if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil {
return errors.WithMessagef(err, "could not create directory '%s'", filepath.Dir(header.Name))
}
f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
return errors.WithMessagef(err, "could not create file '%s'", header.Name)
}
// copy over contents
if _, err := io.Copy(f, tr); err != nil {
return err
}
f.Close()
default:
return errors.Errorf("invalid file type '%v' contained in archive for file '%s'", header.Typeflag, header.Name)
}
}
}
// ValidPath checks to see if the path is absolute, or if it is a
// relative path higher in the tree. In these cases it returns false.
func ValidPath(uncleanPath string) bool {
// sanitizedPath will eliminate non-prefix instances of '..', as well
// as strip './'
sanitizedPath := filepath.Clean(uncleanPath)
switch {
case filepath.IsAbs(sanitizedPath):
return false
case strings.HasPrefix(sanitizedPath, ".."+string(filepath.Separator)) || sanitizedPath == "..":
// Path refers either to the parent, or a directory relative to the parent (but allows ..foo or ... for instance)
return false
default:
// Path appears to be relative without escaping higher
return true
}
}