summaryrefslogtreecommitdiff
path: root/internal/ssh/server/hostkey.go
blob: 33bd4e827b5124b4fb5c33257e3a75124ea164a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package server

import (
	"io/ioutil"
	"os"

	"github.com/mimecast/dtail/internal/config"
	"github.com/mimecast/dtail/internal/io/dlog"
	"github.com/mimecast/dtail/internal/ssh"
)

// PrivateHostKey retrieves the private server RSA host key.
func PrivateHostKey() []byte {
	hostKeyFile := config.Server.HostKeyFile
	_, err := os.Stat(hostKeyFile)

	if os.IsNotExist(err) {
		dlog.Common.Info("Generating private server RSA host key")
		privateKey, err := ssh.GeneratePrivateRSAKey(config.Server.HostKeyBits)

		if err != nil {
			dlog.Common.FatalPanic("Failed to generate private server RSA host key", err)
		}

		pem := ssh.EncodePrivateKeyToPEM(privateKey)
		if err := ioutil.WriteFile(hostKeyFile, pem, 0600); err != nil {
			dlog.Common.Error("Unable to write private server RSA host key to file",
				hostKeyFile, err)
		}
		return pem
	}

	dlog.Common.Info("Reading private server RSA host key from file", hostKeyFile)
	pem, err := ioutil.ReadFile(hostKeyFile)
	if err != nil {
		dlog.Common.FatalPanic("Failed to load private server RSA host key", err)
	}
	return pem
}