Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better defer and subpath checks for unpack #630

Merged
merged 1 commit into from
Nov 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions pkg/cmd/unpack/unpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ func unpackLayer(ctx context.Context, store content.Storage, desc ocispec.Descri
return nil
}

func extractTar(tr *tar.Reader, dir string, overwrite bool, logger *output.ProgressLogger) error {
func extractTar(tr *tar.Reader, dir string, overwrite bool, logger *output.ProgressLogger) (err error) {
for {
header, err := tr.Next()
if err == io.EOF {
Expand All @@ -247,6 +247,11 @@ func extractTar(tr *tar.Reader, dir string, overwrite bool, logger *output.Progr
return err
}
outPath := filepath.Join(dir, header.Name)
// Check if the outPath is within the target directory
_, _, err = filesystem.VerifySubpath(dir, outPath)
if err != nil {
return fmt.Errorf("illegal file path: %s: %w", outPath, err)
}

switch header.Typeflag {
case tar.TypeDir:
Expand Down Expand Up @@ -276,8 +281,15 @@ func extractTar(tr *tar.Reader, dir string, overwrite bool, logger *output.Progr
if err != nil {
return fmt.Errorf("failed to create file %s: %w", outPath, err)
}
defer file.Close()

defer func() {
if errClose := file.Close(); errClose != nil {
if err == nil {
err = fmt.Errorf("failed to close log file: %w", errClose)
} else {
err = fmt.Errorf("%v; failed to close log file: %w", err, errClose)
}
}
}()
written, err := io.Copy(file, tr)
if err != nil {
return fmt.Errorf("failed to write file %s: %w", outPath, err)
Expand Down