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
|
|
|
)
|
|
|
|
|
2023-01-12 10:57:44 +00:00
|
|
|
// Serializer is a function that can serialize session information.
|
|
|
|
type Serializer interface {
|
|
|
|
Encode(src session.Dict) (data []byte, err error)
|
|
|
|
Decode(dst *session.Dict, src []byte) (err error)
|
|
|
|
}
|
|
|
|
|
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.
|
2023-01-12 10:57:44 +00:00
|
|
|
func (e *EncryptingSerializer) Encode(src session.Dict) (data []byte, err error) {
|
2023-01-09 04:57:40 +00:00
|
|
|
if len(src.KV) == 0 {
|
2020-03-28 06:10:39 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2023-01-12 10:57:44 +00:00
|
|
|
if data, err = utils.Encrypt(dst, &e.key); 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
|
|
|
}
|
|
|
|
|
2023-01-12 10:57:44 +00:00
|
|
|
return data, nil
|
2020-03-28 06:10:39 +00:00
|
|
|
}
|
|
|
|
|
2020-05-02 05:06:39 +00:00
|
|
|
// Decode decrypt and decode session.
|
2023-01-12 10:57:44 +00:00
|
|
|
func (e *EncryptingSerializer) Decode(dst *session.Dict, src []byte) (err error) {
|
2020-03-28 06:10:39 +00:00
|
|
|
if len(src) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-01-09 04:57:40 +00:00
|
|
|
for k := range dst.KV {
|
|
|
|
delete(dst.KV, k)
|
|
|
|
}
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2023-01-12 10:57:44 +00:00
|
|
|
var data []byte
|
|
|
|
|
|
|
|
if data, err = utils.Decrypt(src, &e.key); 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
|
|
|
}
|
|
|
|
|
2023-01-12 10:57:44 +00:00
|
|
|
_, err = dst.UnmarshalMsg(data)
|
2020-05-05 19:35:32 +00:00
|
|
|
|
2020-03-28 06:10:39 +00:00
|
|
|
return err
|
|
|
|
}
|