2020-03-28 06:10:39 +00:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
|
|
|
|
2021-03-13 05:06:19 +00:00
|
|
|
"github.com/fasthttp/session/v2"
|
2020-04-05 12:37:21 +00:00
|
|
|
|
2021-08-11 01:04:35 +00:00
|
|
|
"github.com/authelia/authelia/v4/internal/utils"
|
2020-03-28 06:10:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// EncryptingSerializer a serializer encrypting the data with AES-GCM with 256-bit keys.
|
|
|
|
type EncryptingSerializer struct {
|
|
|
|
key [32]byte
|
|
|
|
}
|
|
|
|
|
2020-05-02 05:06:39 +00:00
|
|
|
// NewEncryptingSerializer return new encrypt instance.
|
2020-03-28 06:10:39 +00:00
|
|
|
func NewEncryptingSerializer(secret string) *EncryptingSerializer {
|
|
|
|
key := sha256.Sum256([]byte(secret))
|
|
|
|
return &EncryptingSerializer{key}
|
|
|
|
}
|
|
|
|
|
2020-05-02 05:06:39 +00:00
|
|
|
// Encode encode and encrypt session.
|
2020-03-28 06:10:39 +00: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 01:33:22 +00:00
|
|
|
return nil, fmt.Errorf("unable to marshal session: %v", err)
|
2020-03-28 06:10:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
encryptedDst, err := utils.Encrypt(dst, &e.key)
|
|
|
|
if err != nil {
|
2021-07-08 01:33:22 +00:00
|
|
|
return nil, fmt.Errorf("unable to encrypt session: %v", err)
|
2020-03-28 06:10:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return encryptedDst, nil
|
|
|
|
}
|
|
|
|
|
2020-05-02 05:06:39 +00:00
|
|
|
// Decode decrypt and decode session.
|
2020-03-28 06:10:39 +00:00
|
|
|
func (e *EncryptingSerializer) Decode(dst *session.Dict, src []byte) error {
|
|
|
|
if len(src) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
dst.Reset()
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2020-03-28 06:10:39 +00:00
|
|
|
decryptedSrc, err := utils.Decrypt(src, &e.key)
|
|
|
|
if err != nil {
|
2021-08-26 11:48:14 +00:00
|
|
|
return fmt.Errorf("unable to decrypt session: %s", err)
|
2020-03-28 06:10:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
_, err = dst.UnmarshalMsg(decryptedSrc)
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2020-03-28 06:10:39 +00:00
|
|
|
return err
|
|
|
|
}
|