Skip to content

Commit 62918df

Browse files
app: write zipped archive 0600, flush before deleting (#4833)
* app: write zipped archive 0600, flush before deleting `charon create cluster --zipped` and `charon dkg --zipped` created the archive with os.Create (usually world-readable 0644), although it holds validator key shares and the ENR private key. It is now 0600, including an archive left from an earlier run. BundleOutput also closed the tar and gzip writers only in defers, after deleting the originals and ignoring their errors, so a failed flush (e.g. a full disk) could lose key shares. The archive is now flushed, synced and closed before anything is deleted. category: bug ticket: none * app: write the zipped archive to a temporary file and rename it BundleOutput now writes to a 0600 temporary file in the target directory and renames it into place once it is flushed, synced and closed, so the archive name never holds a partial archive. A failed run removes the temporary file and leaves the originals. An archive left by an earlier run is replaced rather than archived into the new one. * app: fix zipped archive in relative dirs, stricter tests * testutil: move archive test helpers out of app --------- Co-authored-by: kalo <24719519+KaloyanTanev@users.noreply.github.com>
1 parent 2ed171c commit 62918df

7 files changed

Lines changed: 562 additions & 334 deletions

File tree

‎KNOWN_ISSUES.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ If you believe you have found a new, distinct issue, report it to the Obol Secur
1616
* **Legacy lock formats are retained for compatibility.** Charon must keep loading the existing cluster locks of running clusters. Some lock formats from before v1.7 carry fewer signatures than current ones.
1717
* **`--no-verify` is out of scope.** This flag disables cluster definition and lock verification. Findings that depend on an operator running with it are not eligible.
1818
* **Operators control their own node and its inputs.** Operators choose their own beacon node, validator client, configuration, and cluster lock file. Findings that depend on an operator running a lock, configuration, or binary they did not produce or verify themselves are not eligible.
19-
* **Access to the operator's host is out of scope.** Findings that require reading files, archives, logs, or command output on the operator's machine assume the host is already compromised and are not eligible. Examples include the file permissions of cluster or DKG archives created with `--zipped`, and secrets visible in local logs or test output. Since v1.11.3, Charon redacts credentials and API keys in configured endpoint URLs before logging them.
19+
* **Access to the operator's host is out of scope.** Findings that require reading files, archives, logs, or command output on the operator's machine assume the host is already compromised and are not eligible. Examples include secrets visible in local logs or test output. Since v2.0.0, cluster and DKG archives created with `--zipped` are readable only by their owner. Since v1.11.3, Charon redacts credentials and API keys in configured endpoint URLs before logging them.
2020

2121
## Cluster Definition & Lock
2222

‎app/utils.go‎

Lines changed: 49 additions & 158 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ package app
44

55
import (
66
"archive/tar"
7-
"bytes"
87
"compress/gzip"
98
"encoding/hex"
109
"io"
@@ -27,20 +26,32 @@ func Hex7(input []byte) string {
2726
}
2827

2928
// BundleOutput archives targetDir into a gzipped tarball named filename in targetDir.
30-
// After successfully creating the archive, it deletes the original files from disk.
31-
func BundleOutput(targetDir string, filename string) error {
32-
// Create output file
33-
file, err := os.Create(filepath.Join(targetDir, filename))
29+
// The archive contains private key material, so it is only readable and writable by its owner.
30+
// It is written to a temporary file and renamed into place once complete, so filename is
31+
// never a partial archive. The original files are deleted only once the archive is in place,
32+
// so a failure before that leaves them untouched.
33+
func BundleOutput(targetDir string, filename string) (err error) {
34+
archivePath := filepath.Join(targetDir, filename)
35+
tempPrefix := filename + ".tmp-"
36+
37+
// CreateTemp creates the tempFile with mode 0600.
38+
tempFile, err := os.CreateTemp(targetDir, tempPrefix+"*")
3439
if err != nil {
3540
return errors.Wrap(err, "create .tar.gz file")
3641
}
37-
defer file.Close()
3842

39-
gzw := gzip.NewWriter(file)
40-
defer gzw.Close()
43+
// CreateTemp does not clean its path while filepath.Walk does, e.g. for the default "./" directory.
44+
tempPath := filepath.Clean(tempFile.Name())
4145

46+
defer func() {
47+
if err != nil {
48+
_ = tempFile.Close()
49+
_ = os.Remove(tempFile.Name())
50+
}
51+
}()
52+
53+
gzw := gzip.NewWriter(tempFile)
4254
tw := tar.NewWriter(gzw)
43-
defer tw.Close()
4455

4556
// Files to be deleted
4657
dirsToDelete := make([]string, 0)
@@ -61,8 +72,15 @@ func BundleOutput(targetDir string, filename string) error {
6172
return nil
6273
}
6374

64-
// Don't delete output file
65-
if path == file.Name() {
75+
// Don't archive or delete the output file, nor an archive left by a previous run (it is replaced).
76+
if path == tempPath || path == archivePath {
77+
return nil
78+
}
79+
80+
// Don't archive a temporary file left by an interrupted run, but do delete it.
81+
if strings.HasPrefix(info.Name(), tempPrefix) {
82+
filesToDelete = append(filesToDelete, path)
83+
6684
return nil
6785
}
6886

@@ -100,168 +118,41 @@ func BundleOutput(targetDir string, filename string) error {
100118
return errors.Wrap(err, "filepath walk")
101119
}
102120

103-
// Delete files/folders
104-
for _, path := range filesToDelete {
105-
err := os.RemoveAll(path)
106-
if err != nil {
107-
return errors.Wrap(err, "remove file", z.Str("filename", path))
108-
}
121+
// Flush the archive to disk and move it into place before deleting the originals,
122+
// so a failed write never loses them.
123+
if err := tw.Close(); err != nil {
124+
return errors.Wrap(err, "close tar writer")
109125
}
110126

111-
for _, path := range dirsToDelete {
112-
err := os.RemoveAll(path)
113-
if err != nil {
114-
return errors.Wrap(err, "remove dir", z.Str("filename", path))
115-
}
127+
if err := gzw.Close(); err != nil {
128+
return errors.Wrap(err, "close gzip writer")
116129
}
117130

118-
return nil
119-
}
120-
121-
// ExtractArchive extracts a .tar.gz archive to the target directory.
122-
func ExtractArchive(archivePath, targetDir string) error {
123-
file, err := os.Open(archivePath)
124-
if err != nil {
125-
return errors.Wrap(err, "open archive file")
131+
if err := tempFile.Sync(); err != nil {
132+
return errors.Wrap(err, "sync .tar.gz file")
126133
}
127-
defer file.Close()
128134

129-
gzr, err := gzip.NewReader(file)
130-
if err != nil {
131-
return errors.Wrap(err, "create gzip reader")
135+
if err := tempFile.Close(); err != nil {
136+
return errors.Wrap(err, "close .tar.gz file")
132137
}
133-
defer gzr.Close()
134-
135-
tr := tar.NewReader(gzr)
136-
137-
for {
138-
header, err := tr.Next()
139-
if errors.Is(err, io.EOF) {
140-
return nil // End of archive
141-
}
142-
143-
if err != nil {
144-
return errors.Wrap(err, "tar read error")
145-
}
146-
147-
cleanName := filepath.Clean(header.Name)
148-
// Disallow absolute paths and paths with ".." as first element
149-
if strings.HasPrefix(cleanName, "..") || filepath.IsAbs(cleanName) || strings.Contains(cleanName, ".."+string(os.PathSeparator)) {
150-
return errors.New("invalid archive entry path", z.Str("path", header.Name))
151-
}
152-
153-
target := filepath.Join(targetDir, cleanName)
154-
155-
absTargetDir, err := filepath.Abs(targetDir)
156-
if err != nil {
157-
return errors.Wrap(err, "get absolute target dir")
158-
}
159-
160-
absTarget, err := filepath.Abs(target)
161-
if err != nil {
162-
return errors.Wrap(err, "get absolute target path")
163-
}
164-
165-
if !strings.HasPrefix(absTarget, absTargetDir+string(os.PathSeparator)) && absTarget != absTargetDir {
166-
return errors.New("archive entry path escapes target directory", z.Str("path", header.Name))
167-
}
168-
169-
switch header.Typeflag {
170-
case tar.TypeDir:
171-
if err := os.MkdirAll(target, header.FileInfo().Mode()); err != nil {
172-
return errors.Wrap(err, "create directory")
173-
}
174-
case tar.TypeReg:
175-
// Check file size to prevent decompression bombs
176-
const maxFileSize = 100 * 1024 * 1024 // 100MB limit per file
177-
if header.Size > maxFileSize {
178-
return errors.New("file too large in archive", z.Str("path", header.Name), z.I64("size", header.Size))
179-
}
180138

181-
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
182-
return errors.Wrap(err, "create parent directory")
183-
}
184-
185-
f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY, header.FileInfo().Mode())
186-
if err != nil {
187-
return errors.Wrap(err, "create file")
188-
}
189-
190-
// Use limited reader to prevent decompression bombs
191-
limitedReader := io.LimitReader(tr, maxFileSize)
192-
193-
_, err = io.Copy(f, limitedReader)
194-
if err != nil {
195-
f.Close()
196-
return errors.Wrap(err, "copy file contents")
197-
}
198-
199-
if err := f.Close(); err != nil {
200-
return errors.Wrap(err, "close file")
201-
}
202-
default:
203-
// Skip other types (symlinks, etc.)
204-
}
139+
if err := os.Rename(tempFile.Name(), archivePath); err != nil {
140+
return errors.Wrap(err, "rename .tar.gz file")
205141
}
206-
}
207-
208-
// CompareDirectories recursively compares two directories and their contents.
209-
func CompareDirectories(originalDir, extractedDir string) error {
210-
err := filepath.Walk(originalDir, func(path string, info os.FileInfo, err error) error {
211-
if err != nil {
212-
return err
213-
}
214-
215-
relPath, err := filepath.Rel(originalDir, path)
216-
if err != nil {
217-
return errors.Wrap(err, "get relative path")
218-
}
219-
220-
extractedPath := filepath.Join(extractedDir, relPath)
221142

222-
if info.IsDir() {
223-
// Check if directory exists in extracted content
224-
extractedInfo, err := os.Stat(extractedPath)
225-
if err != nil {
226-
return errors.Wrap(err, "directory should exist in extracted content", z.Str("path", relPath))
227-
}
228-
229-
if !extractedInfo.IsDir() {
230-
return errors.New("path is not a directory", z.Str("path", relPath))
231-
}
232-
233-
return nil
234-
}
235-
236-
// Compare file contents
237-
extractedInfo, err := os.Stat(extractedPath)
238-
if err != nil {
239-
return errors.Wrap(err, "file should exist in extracted content", z.Str("path", relPath))
240-
}
241-
242-
if info.Size() != extractedInfo.Size() {
243-
return errors.New("file size mismatch", z.Str("path", relPath))
244-
}
245-
246-
// Read and compare file contents
247-
originalContent, err := os.ReadFile(path) //nolint:gosec // no TOCTOU condition as CompareDirectories is used only in CLI non-concurrent context.
143+
// Delete files/folders
144+
for _, path := range filesToDelete {
145+
err := os.RemoveAll(path)
248146
if err != nil {
249-
return errors.Wrap(err, "read original file", z.Str("path", path))
147+
return errors.Wrap(err, "remove file", z.Str("filename", path))
250148
}
149+
}
251150

252-
extractedContent, err := os.ReadFile(extractedPath)
151+
for _, path := range dirsToDelete {
152+
err := os.RemoveAll(path)
253153
if err != nil {
254-
return errors.Wrap(err, "read extracted file", z.Str("path", extractedPath))
255-
}
256-
257-
if !bytes.Equal(originalContent, extractedContent) {
258-
return errors.New("file content mismatch", z.Str("path", relPath))
154+
return errors.Wrap(err, "remove dir", z.Str("filename", path))
259155
}
260-
261-
return nil
262-
})
263-
if err != nil {
264-
return errors.Wrap(err, "walk directory tree")
265156
}
266157

267158
return nil

0 commit comments

Comments
 (0)