summaryrefslogtreecommitdiff
path: root/internal/ssh/server/hostkey.go
blob: 131535135c8ecec5d038a8562a5c1abdf8a84499 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package server

import (
	"errors"
	iofs "io/fs"

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

const (
	defaultHostKeyBits = 4096
	defaultHostKeyFile = "./cache/ssh_host_key"
)

// PrivateHostKey retrieves the private server RSA host key.
func PrivateHostKey(hostKeyFile string, hostKeyBits int) []byte {
	if hostKeyFile == "" {
		hostKeyFile = defaultHostKeyFile
	}
	if hostKeyBits <= 0 {
		hostKeyBits = defaultHostKeyBits
	}
	if config.Env("DTAIL_INTEGRATION_TEST_RUN_MODE") {
		hostKeyFile = "./ssh_host_key"
	}
	hostKeyPath, err := fs.NewRootedPath(hostKeyFile)
	if err != nil {
		dlog.Server.FatalPanic("Invalid private server RSA host key path", hostKeyFile, err)
	}

	_, err = hostKeyPath.Stat()
	if err != nil {
		// os.IsNotExist does not unwrap fmt.Errorf chains from RootedPath.Stat; use errors.Is.
		if errors.Is(err, iofs.ErrNotExist) {
			dlog.Server.Info("Generating private server RSA host key")
			pem, genErr := generatePrivateHostKey(hostKeyBits)
			if genErr != nil {
				dlog.Server.FatalPanic("Failed to generate private server RSA host key", genErr)
			}
			if storeErr := storePrivateHostKey(hostKeyPath, pem); storeErr != nil {
				dlog.Server.Error("Unable to write private server RSA host key to file",
					hostKeyFile, storeErr)
			}
			return pem
		}
		dlog.Server.FatalPanic("Cannot stat private server RSA host key path", hostKeyFile, err)
	}

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

func generatePrivateHostKey(hostKeyBits int) ([]byte, error) {
	privateKey, err := ssh.GeneratePrivateRSAKey(hostKeyBits)
	if err != nil {
		return nil, err
	}

	return ssh.EncodePrivateKeyToPEM(privateKey), nil
}

func storePrivateHostKey(hostKeyPath fs.RootedPath, pem []byte) error {
	return hostKeyPath.WriteFile(pem, 0o600)
}

func readPrivateHostKey(hostKeyPath fs.RootedPath) ([]byte, error) {
	return hostKeyPath.ReadFile()
}