From f9827f958bc943472bfa562957a6dd07b5e92e4d Mon Sep 17 00:00:00 2001 From: Nicola Murino Date: Mon, 5 Oct 2020 14:16:57 +0200 Subject: [PATCH] sftpd auto host keys: try to auto-create parent dir if missing --- sftpd/server.go | 6 ++++++ utils/utils.go | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/sftpd/server.go b/sftpd/server.go index a386af5b..9891d322 100644 --- a/sftpd/server.go +++ b/sftpd/server.go @@ -482,6 +482,8 @@ func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error { logger.InfoToConsole("try to create non-existent host key %#v", k) err = utils.GenerateRSAKeys(k) if err != nil { + logger.Warn(logSender, "", "error creating host key %#v: %v", k, err) + logger.WarnToConsole("error creating host key %#v: %v", k, err) return err } case defaultPrivateECDSAKeyName: @@ -489,6 +491,8 @@ func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error { logger.InfoToConsole("try to create non-existent host key %#v", k) err = utils.GenerateECDSAKeys(k) if err != nil { + logger.Warn(logSender, "", "error creating host key %#v: %v", k, err) + logger.WarnToConsole("error creating host key %#v: %v", k, err) return err } default: @@ -511,6 +515,8 @@ func (c *Configuration) checkHostKeyAutoGeneration(configDir string) error { err = utils.GenerateECDSAKeys(autoFile) } if err != nil { + logger.Warn(logSender, "", "error creating host key %#v: %v", autoFile, err) + logger.WarnToConsole("error creating host key %#v: %v", autoFile, err) return err } } diff --git a/utils/utils.go b/utils/utils.go index cbe26c19..cf0e19c5 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -188,6 +188,9 @@ func DecryptData(data string) (string, error) { // private key to specified file and the public key to the specified // file adding the .pub suffix func GenerateRSAKeys(file string) error { + if err := createDirPathIfMissing(file, 0700); err != nil { + return err + } key, err := rsa.GenerateKey(rand.Reader, 4096) if err != nil { return err @@ -219,6 +222,9 @@ func GenerateRSAKeys(file string) error { // private key to specified file and the public key to the specified // file adding the .pub suffix func GenerateECDSAKeys(file string) error { + if err := createDirPathIfMissing(file, 0700); err != nil { + return err + } key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return err @@ -312,3 +318,14 @@ func CleanDirInput(dirInput string) string { } return filepath.Clean(dirInput) } + +func createDirPathIfMissing(file string, perm os.FileMode) error { + dirPath := filepath.Dir(file) + if _, err := os.Stat(dirPath); os.IsNotExist(err) { + err = os.MkdirAll(dirPath, perm) + if err != nil { + return err + } + } + return nil +}