Skip to content

Commit

Permalink
Refactor: createSshDirectoryUnderHome also returns a cleanup function
Browse files Browse the repository at this point in the history
Signed-off-by: GLVS Kiriti <[email protected]>
  • Loading branch information
GLVSKiriti authored and poiana committed Apr 2, 2024
1 parent 47cb7b1 commit cb4f3c9
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
7 changes: 3 additions & 4 deletions events/syscall/read_ssh_information.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ var _ = events.Register(
)

func ReadSshInformation(h events.Helper) error {
// Also creates .ssh directory inside tempDirectory
tempDirectoryName, err := createSshDirectoryUnderHome()
// Creates .ssh directory inside tempDirectory
sshDir, cleanup, err := createSshDirectoryUnderHome()
if err != nil {
return err
}
sshDir := filepath.Join(tempDirectoryName, ".ssh")
defer os.RemoveAll(tempDirectoryName)
defer cleanup() // Cleanup after function return

// Create known_hosts file. os.Create is enough to trigger the rule
filename := filepath.Join(sshDir, "known_hosts")
Expand Down
8 changes: 4 additions & 4 deletions events/syscall/utils_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,22 +95,22 @@ func runAsUser(h events.Helper, username string, cmdName string, cmdArgs ...stri
}

// Creates a temp directory and .ssh directory inside it.
func createSshDirectoryUnderHome() (string, error) {
func createSshDirectoryUnderHome() (string, func(), error) {
// Creates temporary data for testing.
var (
tempDirectoryName string
err error
)
// Loop until a unique temporary directory is successfully created
if tempDirectoryName, err = os.MkdirTemp("/home", "falco-event-generator-"); err != nil {
return "", err
return "", func() {}, err
}

// Create the SSH directory
sshDir := filepath.Join(tempDirectoryName, ".ssh")
if err := os.Mkdir(sshDir, 0755); err != nil {
return "", err
return "", func() { _ = os.RemoveAll(tempDirectoryName) }, err
}

return tempDirectoryName, nil
return sshDir, func() { _ = os.RemoveAll(tempDirectoryName) }, nil
}

0 comments on commit cb4f3c9

Please sign in to comment.