2020-03-28 13:10:39 +07:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
|
|
|
|
2021-03-13 12:06:19 +07:00
|
|
|
"github.com/fasthttp/session/v2"
|
2020-04-05 19:37:21 +07:00
|
|
|
|
2021-08-11 08:04:35 +07:00
|
|
|
"github.com/authelia/authelia/v4/internal/utils"
|
2020-03-28 13:10:39 +07:00
|
|
|
)
|
|
|
|
|
|
|
|
// EncryptingSerializer a serializer encrypting the data with AES-GCM with 256-bit keys.
|
|
|
|
type EncryptingSerializer struct {
|
|
|
|
key [32]byte
|
|
|
|
}
|
|
|
|
|
2020-05-02 12:06:39 +07:00
|
|
|
// NewEncryptingSerializer return new encrypt instance.
|
2020-03-28 13:10:39 +07:00
|
|
|
func NewEncryptingSerializer(secret string) *EncryptingSerializer {
|
|
|
|
key := sha256.Sum256([]byte(secret))
|
|
|
|
return &EncryptingSerializer{key}
|
|
|
|
}
|
|
|
|
|
2020-05-02 12:06:39 +07:00
|
|
|
// Encode encode and encrypt session.
|
2020-03-28 13:10:39 +07:00
|
|
|
func (e *EncryptingSerializer) Encode(src session.Dict) ([]byte, error) {
|
|
|
|
if len(src.D) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
dst, err := src.MarshalMsg(nil)
|
|
|
|
if err != nil {
|
2021-07-08 08:33:22 +07:00
|
|
|
return nil, fmt.Errorf("unable to marshal session: %v", err)
|
2020-03-28 13:10:39 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
encryptedDst, err := utils.Encrypt(dst, &e.key)
|
|
|
|
if err != nil {
|
2021-07-08 08:33:22 +07:00
|
|
|
return nil, fmt.Errorf("unable to encrypt session: %v", err)
|
2020-03-28 13:10:39 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
return encryptedDst, nil
|
|
|
|
}
|
|
|
|
|
2020-05-02 12:06:39 +07:00
|
|
|
// Decode decrypt and decode session.
|
2020-03-28 13:10:39 +07:00
|
|
|
func (e *EncryptingSerializer) Decode(dst *session.Dict, src []byte) error {
|
|
|
|
if len(src) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
dst.Reset()
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-03-28 13:10:39 +07:00
|
|
|
decryptedSrc, err := utils.Decrypt(src, &e.key)
|
|
|
|
if err != nil {
|
|
|
|
// If an error is thrown while decrypting, it's probably an old unencrypted session
|
|
|
|
// so we just unmarshall it without decrypting. It's a way to avoid a breaking change
|
|
|
|
// requiring to flush redis.
|
|
|
|
// TODO(clems4ever): remove in few months
|
|
|
|
_, uerr := dst.UnmarshalMsg(src)
|
|
|
|
if uerr != nil {
|
2021-07-08 08:33:22 +07:00
|
|
|
return fmt.Errorf("unable to decrypt session: %s", err)
|
2020-03-28 13:10:39 +07:00
|
|
|
}
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-03-28 13:10:39 +07:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = dst.UnmarshalMsg(decryptedSrc)
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-03-28 13:10:39 +07:00
|
|
|
return err
|
|
|
|
}
|