goldwarden/agent/bitwarden/crypto/encstring.go

268 lines
5.8 KiB
Go
Raw Normal View History

2023-07-17 04:23:26 +03:00
package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"errors"
"fmt"
"io"
"strconv"
2023-12-22 10:02:23 +03:00
"github.com/awnumar/memguard"
2023-07-17 04:23:26 +03:00
)
type EncString struct {
Type EncStringType
IV, CT, MAC []byte
}
type EncStringType int
const (
AesCbc256_B64 EncStringType = 0
AesCbc128_HmacSha256_B64 EncStringType = 1
AesCbc256_HmacSha256_B64 EncStringType = 2
Rsa2048_OaepSha256_B64 EncStringType = 3
Rsa2048_OaepSha1_B64 EncStringType = 4
Rsa2048_OaepSha256_HmacSha256_B64 EncStringType = 5
Rsa2048_OaepSha1_HmacSha256_B64 EncStringType = 6
)
func (t EncStringType) HasMAC() bool {
return t != AesCbc256_B64
}
func (s *EncString) UnmarshalText(data []byte) error {
if len(data) == 0 {
return nil
}
i := bytes.IndexByte(data, '.')
if i < 0 {
return errors.New("invalid cipher string format")
}
typStr := string(data[:i])
var err error
if t, err := strconv.Atoi(typStr); err != nil {
return errors.New("invalid cipher string type")
} else {
s.Type = EncStringType(t)
}
switch s.Type {
case AesCbc128_HmacSha256_B64, AesCbc256_HmacSha256_B64, AesCbc256_B64:
default:
return errors.New("invalid cipher string type")
}
data = data[i+1:]
parts := bytes.Split(data, []byte("|"))
if len(parts) != 3 {
return errors.New("invalid cipher string format")
}
if s.IV, err = b64decode(parts[0]); err != nil {
return err
}
if s.CT, err = b64decode(parts[1]); err != nil {
return err
}
if s.Type.HasMAC() {
if s.MAC, err = b64decode(parts[2]); err != nil {
return err
}
}
return nil
}
func (s EncString) MarshalText() ([]byte, error) {
if s.Type == 0 {
return nil, nil
}
var buf bytes.Buffer
buf.WriteString(strconv.Itoa(int(s.Type)))
buf.WriteByte('.')
buf.Write(b64encode(s.IV))
buf.WriteByte('|')
buf.Write(b64encode(s.CT))
if s.Type.HasMAC() {
buf.WriteByte('|')
buf.Write(b64encode(s.MAC))
}
return buf.Bytes(), nil
}
func (s EncString) IsNull() bool {
return len(s.IV) == 0 && len(s.CT) == 0 && len(s.MAC) == 0
}
func b64decode(src []byte) ([]byte, error) {
dst := make([]byte, b64enc.DecodedLen(len(src)))
n, err := b64enc.Decode(dst, src)
if err != nil {
return nil, err
}
dst = dst[:n]
return dst, nil
}
func b64encode(src []byte) []byte {
dst := make([]byte, b64enc.EncodedLen(len(src)))
b64enc.Encode(dst, src)
return dst
}
func DecryptWith(s EncString, key SymmetricEncryptionKey) ([]byte, error) {
2023-12-22 10:02:23 +03:00
encKeyData, err := key.MacKeyBytes()
macKeyData, err := key.MacKeyBytes()
2023-07-17 04:23:26 +03:00
if err != nil {
return nil, err
}
2023-12-22 10:02:23 +03:00
block, err := aes.NewCipher(encKeyData)
2023-07-17 04:23:26 +03:00
if err != nil {
return nil, err
}
switch s.Type {
case AesCbc256_B64, AesCbc256_HmacSha256_B64:
break
default:
return nil, fmt.Errorf("decrypt: unsupported cipher type %q", s.Type)
}
if s.Type == AesCbc256_HmacSha256_B64 {
2023-12-22 10:02:23 +03:00
if len(s.MAC) == 0 || len(macKeyData) == 0 {
2023-07-17 04:23:26 +03:00
return nil, fmt.Errorf("decrypt: cipher string type expects a MAC")
}
var msg []byte
msg = append(msg, s.IV...)
msg = append(msg, s.CT...)
2023-12-22 10:02:23 +03:00
if !isMacValid(msg, s.MAC, macKeyData) {
2023-07-17 04:23:26 +03:00
return nil, fmt.Errorf("decrypt: MAC mismatch")
}
}
mode := cipher.NewCBCDecrypter(block, s.IV)
dst := make([]byte, len(s.CT))
mode.CryptBlocks(dst, s.CT)
dst, err = unpadPKCS7(dst, aes.BlockSize)
if err != nil {
return nil, err
}
return dst, nil
}
func EncryptWith(data []byte, typ EncStringType, key SymmetricEncryptionKey) (EncString, error) {
2023-12-22 10:02:23 +03:00
encKeyData, err := key.EncryptionKeyBytes()
macKeyData, err := key.MacKeyBytes()
2023-07-17 04:23:26 +03:00
s := EncString{}
switch typ {
case AesCbc256_B64, AesCbc256_HmacSha256_B64:
default:
return s, fmt.Errorf("encrypt: unsupported cipher type %q", s.Type)
}
s.Type = typ
data = padPKCS7(data, aes.BlockSize)
2023-12-22 10:02:23 +03:00
block, err := aes.NewCipher(encKeyData)
2023-07-17 04:23:26 +03:00
if err != nil {
return s, err
}
s.IV = make([]byte, aes.BlockSize)
if _, err := io.ReadFull(cryptorand.Reader, s.IV); err != nil {
return s, err
}
s.CT = make([]byte, len(data))
mode := cipher.NewCBCEncrypter(block, s.IV)
mode.CryptBlocks(s.CT, data)
if typ == AesCbc256_HmacSha256_B64 {
2023-12-22 10:02:23 +03:00
if len(macKeyData) == 0 {
2023-07-17 04:23:26 +03:00
return s, fmt.Errorf("encrypt: cipher string type expects a MAC")
}
var macMessage []byte
macMessage = append(macMessage, s.IV...)
macMessage = append(macMessage, s.CT...)
2023-12-22 10:02:23 +03:00
mac := hmac.New(sha256.New, macKeyData)
2023-07-17 04:23:26 +03:00
mac.Write(macMessage)
s.MAC = mac.Sum(nil)
}
return s, nil
}
2023-12-22 10:02:23 +03:00
func GenerateAsymmetric(useMemguard bool) (AsymmetricEncryptionKey, error) {
2023-08-21 14:52:06 +03:00
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
2023-12-22 10:02:23 +03:00
return MemoryAsymmetricEncryptionKey{}, err
2023-08-21 14:52:06 +03:00
}
encKey, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
2023-12-22 10:02:23 +03:00
return MemoryAsymmetricEncryptionKey{}, err
2023-08-21 14:52:06 +03:00
}
2023-12-22 10:02:23 +03:00
if useMemguard {
return MemguardAsymmetricEncryptionKey{memguard.NewEnclave(encKey)}, nil
} else {
return MemoryAsymmetricEncryptionKey{encKey}, nil
}
2023-08-21 14:52:06 +03:00
}
2023-07-17 04:23:26 +03:00
func DecryptWithAsymmetric(s []byte, asymmetrickey AsymmetricEncryptionKey) ([]byte, error) {
2023-12-22 10:02:23 +03:00
key, err := asymmetrickey.PrivateBytes()
2023-07-17 04:23:26 +03:00
if err != nil {
return nil, err
}
2023-12-22 10:02:23 +03:00
parsedKey, err := x509.ParsePKCS8PrivateKey(key)
2023-07-17 04:23:26 +03:00
if err != nil {
return nil, err
}
rawKey, err := b64decode(s[2:])
if err != nil {
return nil, err
}
res, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, parsedKey.(*rsa.PrivateKey), rawKey, nil)
if err != nil {
return nil, err
}
return res, nil
}
func EncryptWithAsymmetric(s []byte, asymmbetrickey AsymmetricEncryptionKey) ([]byte, error) {
2023-12-22 10:02:23 +03:00
key, err := asymmbetrickey.PrivateBytes()
2023-07-17 04:23:26 +03:00
if err != nil {
return nil, err
}
2023-12-22 10:02:23 +03:00
parsedKey, err := x509.ParsePKIXPublicKey(key)
2023-07-17 04:23:26 +03:00
if err != nil {
return nil, err
}
res, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, parsedKey.(*rsa.PublicKey), s, nil)
if err != nil {
return nil, err
}
resB64 := b64encode(res)
res = append([]byte("4."), resB64...)
return res, nil
}