-
Notifications
You must be signed in to change notification settings - Fork 29
/
util.go
91 lines (71 loc) · 1.87 KB
/
util.go
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 provision
import (
"bytes"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"github.com/choria-io/go-choria/build"
"github.com/choria-io/go-choria/choria"
"github.com/choria-io/go-choria/providers/agent/mcorpc"
)
func abort(msg string, reply *mcorpc.Reply) {
reply.Statuscode = mcorpc.Aborted
reply.Statusmsg = msg
}
func checkToken(token string, reply *mcorpc.Reply) bool {
if build.ProvisionToken == "" {
return true
}
if token != build.ProvisionToken {
log.Errorf("Incorrect Provisioning Token %s given", token)
abort("Incorrect provision token supplied", reply)
return false
}
return true
}
func updateECDHLocked() error {
var err error
ecdhPrivate, ecdhPublic, err = choria.ECDHKeyPair()
return err
}
func ecdhSharedSecretLocked(provisionerPub string) ([]byte, error) {
pb, err := hex.DecodeString(provisionerPub)
if err != nil {
return nil, err
}
if len(ecdhPrivate) == 0 {
return nil, fmt.Errorf("private key not set")
}
return choria.ECDHSharedSecret(ecdhPrivate, pb)
}
func decryptPrivateKey(privateKey string, ecdhPublic string) ([]byte, error) {
if len(ecdhPublic) == 0 {
return nil, fmt.Errorf("no ECDH Public Key")
}
if len(privateKey) == 0 {
return nil, fmt.Errorf("no Private Key")
}
secret, err := ecdhSharedSecretLocked(ecdhPublic)
if err != nil {
return nil, err
}
block, _ := pem.Decode([]byte(privateKey))
if block == nil {
return nil, fmt.Errorf("bad key received")
}
//lint:ignore SA1019 there is no alternative
if !x509.IsEncryptedPEMBlock(block) {
return nil, fmt.Errorf("key is not encrypted")
}
decBlock, err := x509.DecryptPEMBlock(block, secret) //lint:ignore SA1019 there is no alternative
if err != nil {
return nil, err
}
out := &bytes.Buffer{}
err = pem.Encode(out, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: decBlock})
if err != nil {
return nil, err
}
return out.Bytes(), nil
}