2019-11-11 22:18:26 +00:00
|
|
|
package cluster
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha1"
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"strings"
|
|
|
|
|
2022-09-01 17:20:32 +00:00
|
|
|
"github.com/k3s-io/k3s/pkg/util"
|
2019-11-11 22:18:26 +00:00
|
|
|
"golang.org/x/crypto/pbkdf2"
|
|
|
|
)
|
|
|
|
|
2020-09-24 06:29:25 +00:00
|
|
|
// storageKey returns the etcd key for storing bootstrap data for a given passphrase.
|
|
|
|
// The key is derived from the sha256 hash of the passphrase.
|
2019-11-11 22:18:26 +00:00
|
|
|
func storageKey(passphrase string) string {
|
2023-10-10 01:06:32 +00:00
|
|
|
return "/bootstrap/" + util.ShortHash(passphrase, 12)
|
2019-11-11 22:18:26 +00:00
|
|
|
}
|
|
|
|
|
2020-09-24 06:29:25 +00:00
|
|
|
// encrypt encrypts a byte slice using aes+gcm with a pbkdf2 key derived from the passphrase and a random salt.
|
2021-07-01 17:33:40 +00:00
|
|
|
// It returns a byte slice containing the salt and base64-encoded ciphertext.
|
2019-11-11 22:18:26 +00:00
|
|
|
func encrypt(passphrase string, plaintext []byte) ([]byte, error) {
|
2022-09-01 17:20:32 +00:00
|
|
|
salt, err := util.Random(8)
|
2019-11-11 22:18:26 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
clearKey := pbkdf2.Key([]byte(passphrase), []byte(salt), 4096, 32, sha1.New)
|
|
|
|
key, err := aes.NewCipher(clearKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
gcm, err := cipher.NewGCM(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
|
|
_, err = io.ReadFull(rand.Reader, nonce)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
sealed := gcm.Seal(nonce, nonce, plaintext, nil)
|
|
|
|
return []byte(salt + ":" + base64.StdEncoding.EncodeToString(sealed)), nil
|
|
|
|
}
|
|
|
|
|
2020-09-24 06:29:25 +00:00
|
|
|
// decrypt attempts to decrypt the byte slice using the supplied passphrase.
|
2021-07-01 17:33:40 +00:00
|
|
|
// The input byte slice should be the ciphertext output from the encrypt function.
|
2019-11-11 22:18:26 +00:00
|
|
|
func decrypt(passphrase string, ciphertext []byte) ([]byte, error) {
|
|
|
|
parts := strings.SplitN(string(ciphertext), ":", 2)
|
|
|
|
if len(parts) != 2 {
|
|
|
|
return nil, fmt.Errorf("invalid cipher text, not : delimited")
|
|
|
|
}
|
|
|
|
|
|
|
|
clearKey := pbkdf2.Key([]byte(passphrase), []byte(parts[0]), 4096, 32, sha1.New)
|
|
|
|
key, err := aes.NewCipher(clearKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
gcm, err := cipher.NewGCM(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := base64.StdEncoding.DecodeString(parts[1])
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return gcm.Open(nil, data[:gcm.NonceSize()], data[gcm.NonceSize():], nil)
|
|
|
|
}
|