summaryrefslogtreecommitdiff
path: root/internal/ssh/client/clientkeypair.go
blob: b35b25d9ec6a8541885c646c7addd84504d67ba6 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package client

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/mimecast/dtail/internal/io/dlog"
	"golang.org/x/crypto/ssh"
)

// GeneratePrivatePublicKeyPairIfNotExists generates a SSH key pair (used by the integration tests)
func GeneratePrivatePublicKeyPairIfNotExists(keyPath string, bitSize int) {
	if _, err := os.Stat(keyPath); err == nil {
		dlog.Client.Debug("Private/public key pair already exists", keyPath)
		return
	}
	GeneratePrivatePublicKeyPair(keyPath, bitSize)
}

// GeneratePrivatePublicKeyPair generates a SSH key pair (used by the integration tests)
func GeneratePrivatePublicKeyPair(keyPath string, bitSize int) {
	privateKeyPath := keyPath
	publicKeyPath := fmt.Sprintf("%s.pub", keyPath)

	dlog.Client.Debug("Generating private/public key pair", privateKeyPath, publicKeyPath)

	privateKey, err := generatePrivateKey(bitSize)
	if err != nil {
		dlog.Client.FatalPanic(err)
	}
	publicKeyBytes, err := generatePublicKey(&privateKey.PublicKey)
	if err != nil {
		dlog.Client.FatalPanic(err)
	}
	privateKeyBytes := encodePrivateKeyToPEM(privateKey)
	err = writeKey(privateKeyBytes, privateKeyPath)
	if err != nil {
		dlog.Client.FatalPanic(err)
	}
	err = writeKey([]byte(publicKeyBytes), publicKeyPath)
	if err != nil {
		dlog.Client.FatalPanic(err)
	}

	dlog.Client.Debug("Done generating private/public key pair", privateKeyPath, publicKeyPath)
}

func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
	if err != nil {
		return nil, err
	}
	err = privateKey.Validate()
	if err != nil {
		return nil, err
	}
	return privateKey, nil
}

func encodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
	privDER := x509.MarshalPKCS1PrivateKey(privateKey)
	privBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privDER,
	}
	privatePEM := pem.EncodeToMemory(&privBlock)
	return privatePEM
}

func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {
	publicRsaKey, err := ssh.NewPublicKey(privatekey)
	if err != nil {
		return nil, err
	}
	pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
	return pubKeyBytes, nil
}

func writeKey(keyBytes []byte, saveFileTo string) error {
	err := ioutil.WriteFile(saveFileTo, keyBytes, 0600)
	if err != nil {
		return err
	}
	return nil
}