Skip to content

Commit

Permalink
fix: use rand no for temp file
Browse files Browse the repository at this point in the history
  • Loading branch information
bhoopesh369 committed Oct 25, 2024
1 parent 501e683 commit bdf1dc2
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions sztp-agent/pkg/secureagent/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"fmt"
"io"
"log"
"math/rand"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -90,8 +91,8 @@ func calculateSHA256File(filePath string) (string, error) {
}

func saveToFile(data interface{}, filePath string) error {
tempPath := filePath + ".tmp"
tempPath = filepath.Clean(tempPath)
filePath = filepath.Clean(filePath)
tempPath := fmt.Sprintf("%s.%d.tmp", filePath, rand.Intn(100000)) // rand number to avoid conflicts when multiple agents are running

Check failure on line 95 in sztp-agent/pkg/secureagent/utils.go

View workflow job for this annotation

GitHub Actions / golangci

G404: Use of weak random number generator (math/rand or math/rand/v2 instead of crypto/rand) (gosec)
file, err := os.Create(tempPath)

Check failure on line 96 in sztp-agent/pkg/secureagent/utils.go

View workflow job for this annotation

GitHub Actions / golangci

G304: Potential file inclusion via variable (gosec)
if err != nil {
return err
Expand All @@ -108,7 +109,11 @@ func saveToFile(data interface{}, filePath string) error {
}

// Atomic move of temp file to replace the original.
return os.Rename(tempPath, filePath)
if err := os.Rename(tempPath, filePath); err != nil {
return fmt.Errorf("failed to rename %s to %s: %v", tempPath, filePath, err)
}

return nil
}

func ensureDirExists(dir string) error {
Expand All @@ -127,11 +132,13 @@ func ensureFileExists(filePath string) error {
return err
}

fmt.Printf("Checking if file %s exists...\n", filePath)

if _, err := os.Stat(filePath); os.IsNotExist(err) {
filePath = filepath.Clean(filePath)
file, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("failed to create file %s: %v", filePath, err)
return fmt.Errorf("[ERROR] failed to create file %s: %v", filePath, err)
}
defer func() {
if err := file.Close(); err != nil {
Expand All @@ -157,7 +164,7 @@ func createSymlink(targetFile, linkFile string) error {
// Check if linkFile exists and is a symlink to targetFile
if existingTarget, err := os.Readlink(linkFile); err == nil {
if existingTarget == targetFile {
return nil // Symlink already points to the target; skip creation
return nil // Symlink already points to the target -> skip creation
}
// Remove the existing file (even if it's a wrong symlink or regular file)
if err := os.Remove(linkFile); err != nil {
Expand Down

0 comments on commit bdf1dc2

Please sign in to comment.