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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
|
package config
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"sync"
"golang.org/x/crypto/scrypt"
)
const encryptedFileEnding = ".enc"
type encryptedData struct {
Params EncryptionParameters
Data string
}
// We will generate a new nonce every time we encrypt, but we will keep the salt the same. This way we can cache the scrypted password
// EncryptionParameters contains the parameters used for scrypting the password and encrypting the configuration file
type EncryptionParameters struct {
Nonce string
Salt string
N int
R int
P int
nonceInternal []byte `json:"-"`
saltInternal []byte `json:"-"`
}
func genRand(size int) []byte {
buf := make([]byte, size)
if _, err := rand.Reader.Read(buf[:]); err != nil {
panic("Failed to read random bytes: " + err.Error())
}
return buf
}
func (p *EncryptionParameters) regenerateNonce() {
p.nonceInternal = genRand(nonceLen)
}
func newEncryptionParameters() EncryptionParameters {
res := EncryptionParameters{
N: 262144, // 2 ** 18
R: 8,
P: 1,
}
res.regenerateNonce()
res.saltInternal = genRand(saltLen)
return res
}
const aesKeyLen = 32
const macKeyLen = 16
const nonceLen = 12
const saltLen = 16
// GenerateKeys takes a password and encryption parameters and generates an AES key and a MAC key using SCrypt
func GenerateKeys(password string, params EncryptionParameters) ([]byte, []byte) {
res, _ := scrypt.Key([]byte(password), params.saltInternal, params.N, params.R, params.P, aesKeyLen+macKeyLen)
return res[0:aesKeyLen], res[aesKeyLen:]
}
func encryptData(key, macKey, nonce []byte, plain string) []byte {
c, _ := aes.NewCipher(key)
block, _ := cipher.NewGCM(c)
return block.Seal(nil, nonce, []byte(plain), macKey)
}
func decryptData(key, macKey, nonce, cipherText []byte) ([]byte, error) {
c, _ := aes.NewCipher(key)
block, _ := cipher.NewGCM(c)
res, e := block.Open(nil, nonce, cipherText, macKey)
if e != nil {
return nil, errDecryptionFailed
}
return res, nil
}
func (p *EncryptionParameters) deserialize() (e error) {
p.nonceInternal, e = hex.DecodeString(p.Nonce)
if e != nil {
return
}
p.saltInternal, e = hex.DecodeString(p.Salt)
if e != nil {
return
}
if len(p.nonceInternal) == 0 || len(p.saltInternal) == 0 {
return errDecryptionParamsEmpty
}
return nil
}
func (p *EncryptionParameters) serialize() {
p.Nonce = hex.EncodeToString(p.nonceInternal)
p.Salt = hex.EncodeToString(p.saltInternal)
}
func parseEncryptedData(content []byte) (ed *encryptedData, e error) {
data := new(encryptedData)
e = json.Unmarshal(content, data)
if e != nil {
return
}
e = data.Params.deserialize()
return data, e
}
var errNoPasswordSupplied = errors.New("no password supplied, aborting")
var errDecryptionFailed = errors.New("decryption failed")
var errDecryptionParamsEmpty = errors.New("decryption params are empty")
func decryptConfiguration(content []byte, ks KeySupplier) ([]byte, *EncryptionParameters, error) {
data, err := parseEncryptedData(content)
if err != nil {
return nil, nil, err
}
key, macKey, ok := ks.GenerateKey(data.Params)
if !ok {
return nil, nil, errNoPasswordSupplied
}
ctext, err := hex.DecodeString(data.Data)
if err != nil {
return nil, nil, err
}
res, err := decryptData(key, macKey, data.Params.nonceInternal, ctext)
return res, &data.Params, err
}
func encryptConfiguration(content string, params *EncryptionParameters, ks KeySupplier) ([]byte, error) {
key, macKey, ok := ks.GenerateKey(*params)
if !ok {
return nil, errors.New("no password supplied, aborting")
}
ctext := encryptData(key, macKey, params.nonceInternal, content)
params.serialize()
dd := encryptedData{
Params: *params,
Data: hex.EncodeToString(ctext),
}
return json.MarshalIndent(dd, "", "\t")
}
// KeySupplier is a function that can be used to get key data from a user
type KeySupplier interface {
GenerateKey(params EncryptionParameters) ([]byte, []byte, bool)
Invalidate()
LastAttemptFailed()
}
type functionKeySupplier struct {
getKeys func(params EncryptionParameters, lastAttemptFailed bool) ([]byte, []byte, bool)
lastAttemptFailed bool
}
// FunctionKeySupplier is a key supplier that wraps a function to ask for the password
func FunctionKeySupplier(getKeys func(params EncryptionParameters, lastAttemptFailed bool) ([]byte, []byte, bool)) KeySupplier {
return &functionKeySupplier{getKeys, false}
}
func (fk *functionKeySupplier) Invalidate() {
}
func (fk *functionKeySupplier) LastAttemptFailed() {
fk.lastAttemptFailed = true
}
func (fk *functionKeySupplier) GenerateKey(params EncryptionParameters) ([]byte, []byte, bool) {
laf := fk.lastAttemptFailed
fk.lastAttemptFailed = false
return fk.getKeys(params, laf)
}
type cachingKeySupplier struct {
sync.Mutex
haveKeys bool
key, macKey []byte
getKeys func(params EncryptionParameters, lastAttemptFailed bool) ([]byte, []byte, bool)
lastAttemptFailed bool
}
func (ck *cachingKeySupplier) LastAttemptFailed() {
ck.lastAttemptFailed = true
}
func (ck *cachingKeySupplier) Invalidate() {
ck.Lock()
defer ck.Unlock()
ck.haveKeys = false
ck.key = []byte{}
ck.macKey = []byte{}
}
func (ck *cachingKeySupplier) GenerateKey(params EncryptionParameters) ([]byte, []byte, bool) {
var ok bool
ck.Lock()
defer ck.Unlock()
if !ck.haveKeys {
laf := ck.lastAttemptFailed
ck.lastAttemptFailed = false
ck.key, ck.macKey, ok = ck.getKeys(params, laf)
if !ok {
return nil, nil, false
}
ck.haveKeys = true
}
return ck.key, ck.macKey, true
}
// CachingKeySupplier is a key supplier that only asks the user for a password if it doesn't already have the key material
func CachingKeySupplier(getKeys func(params EncryptionParameters, lastAttemptFailed bool) ([]byte, []byte, bool)) KeySupplier {
return &cachingKeySupplier{
getKeys: getKeys,
}
}
|