Debian Codegraph @

content/file/utils.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package file
17
18 import (
19 "archive/tar"
20 "compress/gzip"
21 "context"
22 "errors"
23 "fmt"
24 "io"
25 "io/fs"
26 "os"
27 "path/filepath"
28 "strings"
29 "time"
30
31 "github.com/opencontainers/go-digest"
32 )
33
34 // tarDirectory walks the directory specified by path, and tar those files with a new
35 // path prefix.
36 func tarDirectory(ctx context.Context, root, prefix string, w io.Writer, removeTimes bool, buf []byte) (err error) {
37 tw := tar.NewWriter(w)
38 defer func() {
39 closeErr := tw.Close()
40 if err == nil {
41 err = closeErr
42 }
43 }()
44
45 return filepath.Walk(root, func(path string, info os.FileInfo, err error) (returnErr error) {
46 if err != nil {
47 return err
48 }
49
50 select {
51 case <-ctx.Done():
52 return ctx.Err()
53 default:
54 }
55
56 // Rename path
57 name, err := filepath.Rel(root, path)
58 if err != nil {
59 return err
60 }
61 name = filepath.Join(prefix, name)
62 name = filepath.ToSlash(name)
63
64 // Generate header
65 // NOTE: We don't support hard links and treat it as regular files
66 var link string
67 mode := info.Mode()
68 if mode&os.ModeSymlink != 0 {
69 if link, err = os.Readlink(path); err != nil {
70 return err
71 }
72 }
73 header, err := tar.FileInfoHeader(info, link)
74 if err != nil {
75 return fmt.Errorf("%s: %w", path, err)
76 }
77 header.Name = name
78 header.Uid = 0
79 header.Gid = 0
80 header.Uname = ""
81 header.Gname = ""
82
83 if removeTimes {
84 header.ModTime = time.Time{}
85 header.AccessTime = time.Time{}
86 header.ChangeTime = time.Time{}
87 }
88
89 // Write file
90 if err := tw.WriteHeader(header); err != nil {
91 return fmt.Errorf("tar: %w", err)
92 }
93 if mode.IsRegular() {
94 fp, err := os.Open(path)
95 if err != nil {
96 return err
97 }
98 defer func() {
99 closeErr := fp.Close()
100 if returnErr == nil {
101 returnErr = closeErr
102 }
103 }()
104
105 if _, err := io.CopyBuffer(tw, fp, buf); err != nil {
106 return fmt.Errorf("failed to copy to %s: %w", path, err)
107 }
108 }
109
110 return nil
111 })
112 }
113
114 // extractTarGzip decompresses the gzip
115 // and extracts tar file to a directory specified by the `dir` parameter.
116 func extractTarGzip(dirPath, dirName, gzPath, checksum string, buf []byte, preservePermissions bool) (err error) {
117 fp, err := os.Open(gzPath)
118 if err != nil {
119 return err
120 }
121 defer func() {
122 closeErr := fp.Close()
123 if err == nil {
124 err = closeErr
125 }
126 }()
127
128 gzr, err := gzip.NewReader(fp)
129 if err != nil {
130 return err
131 }
132 defer func() {
133 closeErr := gzr.Close()
134 if err == nil {
135 err = closeErr
136 }
137 }()
138
139 var r io.Reader = gzr
140 var verifier digest.Verifier
141 if checksum != "" {
142 if digest, err := digest.Parse(checksum); err == nil {
143 verifier = digest.Verifier()
144 r = io.TeeReader(r, verifier)
145 }
146 }
147 if err := extractTarDirectory(dirPath, dirName, r, buf, preservePermissions); err != nil {
148 return err
149 }
150 if verifier != nil && !verifier.Verified() {
151 return errors.New("content digest mismatch")
152 }
153 return nil
154 }
155
156 // extractTarDirectory extracts tar file to a directory specified by the `dir`
157 // parameter. The file name prefix is ensured to be the string specified by the
158 // `prefix` parameter and is trimmed.
159 func extractTarDirectory(dirPath, dirName string, r io.Reader, buf []byte, preservePermissions bool) error {
160 tr := tar.NewReader(r)
161 for {
162 header, err := tr.Next()
163 if err != nil {
164 if err == io.EOF {
165 return nil
166 }
167 return err
168 }
169
170 // Name check
171 filename := header.Name
172 filePathRel, err := resolveRelToBase(dirPath, dirName, filename)
173 if err != nil {
174 return err
175 }
176 filePath := filepath.Join(dirPath, filePathRel)
177
178 // resolveRelToBase only performs lexical and per-component Lstat checks,
179 // which a chain of previously-extracted symlinks can bypass. Re-verify
180 // containment with symlinks fully resolved before mutating the
181 // filesystem, matching the check on the pushFile path.
182 // (GHSA-m37j-52j7-pjw7)
183 if err := checkSymlinkEscape(dirPath, filePath); err != nil {
184 return err
185 }
186
187 // Create content
188 switch header.Typeflag {
189 case tar.TypeReg:
190 err = writeFile(filePath, tr, header.FileInfo().Mode(), buf)
191 case tar.TypeDir:
192 err = os.MkdirAll(filePath, header.FileInfo().Mode())
193 case tar.TypeLink:
194 // NOTE: ORAS does not generate hard links when creating tarballs.
195 // If a hard link is found in the tarball, it will be extracted.
196 // If the target link already exists, os.Link will throw an error.
197 // This is a known limitation and will not be addressed.
198 var target string
199 if target, err = ensureLinkPath(dirPath, dirName, filePath, header.Linkname); err == nil {
200 if !filepath.IsAbs(target) {
201 // link(2) resolves relative paths against the process CWD, not
202 // the link file's directory. Resolve explicitly to prevent escape.
203 target = filepath.Join(filepath.Dir(filePath), target)
204 }
205 err = os.Link(target, filePath)
206 }
207 case tar.TypeSymlink:
208 var target string
209 target, err = ensureLinkPath(dirPath, dirName, filePath, header.Linkname)
210 if err != nil {
211 return err
212 }
213 if err = os.Symlink(target, filePath); err != nil {
214 if !errors.Is(err, fs.ErrExist) {
215 return err
216 }
217 // link already exists, remove the old one and try again
218 if err := os.Remove(filePath); err != nil {
219 return err
220 }
221 err = os.Symlink(target, filePath)
222 }
223 default:
224 continue // Non-regular files are skipped
225 }
226 if err != nil {
227 return err
228 }
229
230 // Change access time and modification time if possible (error ignored)
231 _ = os.Chtimes(filePath, header.AccessTime, header.ModTime)
232
233 // Restore full mode bits
234 if preservePermissions && (header.Typeflag == tar.TypeReg || header.Typeflag == tar.TypeDir) {
235 if err := os.Chmod(filePath, os.FileMode(header.Mode)); err != nil {
236 return err
237 }
238 }
239 }
240 }
241
242 // resolveRelToBase ensures the target path is in the base path,
243 // returning its relative path to the base path.
244 // target can be either an absolute path or a relative path.
245 func resolveRelToBase(baseAbs, baseRel, target string) (string, error) {
246 base := baseRel
247 if filepath.IsAbs(target) {
248 // ensure base and target are consistent
249 base = baseAbs
250 }
251 path, err := filepath.Rel(base, target)
252 if err != nil {
253 return "", err
254 }
255 cleanPath := filepath.ToSlash(filepath.Clean(path))
256 if cleanPath == ".." || strings.HasPrefix(cleanPath, "../") {
257 return "", fmt.Errorf("%q is outside of %q", target, baseRel)
258 }
259
260 // No symbolic link allowed in the relative path
261 dir := filepath.Dir(path)
262 for dir != "." {
263 if info, err := os.Lstat(filepath.Join(baseAbs, dir)); err != nil {
264 if !os.IsNotExist(err) {
265 return "", err
266 }
267 } else if info.Mode()&os.ModeSymlink != 0 {
268 return "", fmt.Errorf("no symbolic link allowed between %q and %q", baseRel, target)
269 }
270 dir = filepath.Dir(dir)
271 }
272
273 return path, nil
274 }
275
276 // ensureLinkPath ensures the target path pointed by the link is in the base
277 // path. It returns target path if validated.
278 func ensureLinkPath(baseAbs, baseRel, link, target string) (string, error) {
279 // resolve link
280 path := target
281 if !filepath.IsAbs(target) {
282 path = filepath.Join(filepath.Dir(link), target)
283 }
284 // ensure path is under baseAbs or baseRel
285 if _, err := resolveRelToBase(baseAbs, baseRel, path); err != nil {
286 return "", err
287 }
288 return target, nil
289 }
290
291 // writeFile writes content to the file specified by the `path` parameter.
292 func writeFile(path string, r io.Reader, perm os.FileMode, buf []byte) (err error) {
293 // os.OpenFile follows a terminal symlink, so a regular-file entry whose
294 // path was already created as a symlink by an earlier archive entry would
295 // be written through that link, landing outside the extraction root
296 // (GHSA-m37j-52j7-pjw7). Remove any such symlink first so the content is
297 // written to a regular file at path itself.
298 if fi, err := os.Lstat(path); err == nil && fi.Mode()&os.ModeSymlink != 0 {
299 if err := os.Remove(path); err != nil {
300 return err
301 }
302 }
303 file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
304 if err != nil {
305 return err
306 }
307 defer func() {
308 closeErr := file.Close()
309 if err == nil {
310 err = closeErr
311 }
312 }()
313
314 _, err = io.CopyBuffer(file, r, buf)
315 return err
316 }