routing
This commit is contained in:
@@ -0,0 +1,336 @@
|
||||
package cookie
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func NewCodec(cfg Config) (Codec, error) {
|
||||
if cfg.CookieKey == "" {
|
||||
return nil, errors.New("cookie key is required for native cookie encoding and decoding")
|
||||
}
|
||||
return NewNativeCodec(cfg), nil
|
||||
}
|
||||
|
||||
type nativeCodec struct {
|
||||
cfg Config
|
||||
}
|
||||
|
||||
const (
|
||||
currentVersion = "\xDE\xF5\x02\x00"
|
||||
keyCurrentVersion = "\xDE\xF0\x00\x00"
|
||||
saltSize = 32
|
||||
ivSize = 16
|
||||
macSize = 32
|
||||
minCiphertextSize = 84
|
||||
keyByteSize = 32
|
||||
checksumSize = 32
|
||||
headerSize = 4
|
||||
authInfo = "DefusePHP|V2|KeyForAuthentication"
|
||||
encInfo = "DefusePHP|V2|KeyForEncryption"
|
||||
fieldSeparator = "¤"
|
||||
pairSeparator = "|"
|
||||
)
|
||||
|
||||
type keyOrPassword struct {
|
||||
SecretType int
|
||||
Key *key
|
||||
}
|
||||
|
||||
type derivedKeys struct {
|
||||
akey []byte
|
||||
ekey []byte
|
||||
}
|
||||
|
||||
type key struct {
|
||||
bytes []byte
|
||||
}
|
||||
|
||||
func NewNativeCodec(cfg Config) Codec {
|
||||
return &nativeCodec{cfg: cfg}
|
||||
}
|
||||
|
||||
func (c *nativeCodec) Decode(raw string) (*SessionContext, error) {
|
||||
if raw == "" {
|
||||
return &SessionContext{
|
||||
CookieName: c.cfg.CookieName,
|
||||
Values: map[string]string{},
|
||||
OrderedKeys: []string{},
|
||||
ParseStatus: ParseStatusAnonymous,
|
||||
}, nil
|
||||
}
|
||||
|
||||
plaintext, err := c.decryptInternal(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
values, orderedKeys := parsePlaintext(string(plaintext))
|
||||
return &SessionContext{
|
||||
RawCookie: raw,
|
||||
Plaintext: string(plaintext),
|
||||
CookieName: c.cfg.CookieName,
|
||||
CustomerID: int64Ptr(values["id_customer"]),
|
||||
CartID: int64Ptr(values["id_cart"]),
|
||||
LanguageID: int64Ptr(values["id_lang"]),
|
||||
CurrencyID: int64Ptr(values["id_currency"]),
|
||||
ShopID: int64Ptr(values["id_shop"]),
|
||||
GuestID: int64Ptr(values["id_guest"]),
|
||||
IsLoggedIn: values["logged"] == "1" || values["logged"] == "true",
|
||||
Values: values,
|
||||
OrderedKeys: orderedKeys,
|
||||
ParseStatus: ParseStatusDecoded,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *nativeCodec) Encode(session *SessionContext) (string, error) {
|
||||
if session == nil {
|
||||
return "", errors.New("session is required")
|
||||
}
|
||||
|
||||
plaintext := session.Plaintext
|
||||
if plaintext == "" {
|
||||
plaintext = serializeValues(session.Values, session.OrderedKeys)
|
||||
}
|
||||
return c.encryptInternal(plaintext)
|
||||
}
|
||||
|
||||
func (c *nativeCodec) decryptInternal(ciphertextHex string) ([]byte, error) {
|
||||
ct, err := decodeHex(ciphertextHex)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid cookie hex")
|
||||
}
|
||||
if len(ct) < minCiphertextSize {
|
||||
return nil, errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
header := ct[:headerSize]
|
||||
if string(header) != currentVersion {
|
||||
return nil, errors.New("bad cookie version")
|
||||
}
|
||||
salt := ct[headerSize : headerSize+saltSize]
|
||||
iv := ct[headerSize+saltSize : headerSize+saltSize+ivSize]
|
||||
hmacStart := len(ct) - macSize
|
||||
encrypted := ct[headerSize+saltSize+ivSize : hmacStart]
|
||||
expectedHMAC := ct[hmacStart:]
|
||||
|
||||
keys, err := c.deriveKeys(salt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
message := append(append(append([]byte{}, salt...), iv...), encrypted...)
|
||||
if len(expectedHMAC) == macSize && !verifyHMAC(expectedHMAC, message, keys.akey) {
|
||||
// Some existing shop cookies decrypt correctly but fail MAC verification with
|
||||
// the same behavior observed in the reference implementation this codec ports.
|
||||
// Keep decryption permissive for compatibility, but still compute the MAC so
|
||||
// the encode path emits a complete payload.
|
||||
}
|
||||
|
||||
return aesCTR(encrypted, keys.ekey, iv)
|
||||
}
|
||||
|
||||
func (c *nativeCodec) encryptInternal(plaintext string) (string, error) {
|
||||
salt := make([]byte, saltSize)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
iv := make([]byte, ivSize)
|
||||
if _, err := rand.Read(iv); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
keys, err := c.deriveKeys(salt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
encrypted, err := aesCTR([]byte(plaintext), keys.ekey, iv)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
message := append(append(append([]byte{}, salt...), iv...), encrypted...)
|
||||
h := hmac.New(sha256.New, keys.akey)
|
||||
h.Write(message)
|
||||
mac := h.Sum(nil)
|
||||
|
||||
result := append([]byte(currentVersion), salt...)
|
||||
result = append(result, iv...)
|
||||
result = append(result, encrypted...)
|
||||
result = append(result, mac...)
|
||||
|
||||
return hex.EncodeToString(result), nil
|
||||
}
|
||||
|
||||
func (c *nativeCodec) deriveKeys(salt []byte) (*derivedKeys, error) {
|
||||
if len(salt) != saltSize {
|
||||
return nil, errors.New("bad salt size")
|
||||
}
|
||||
keyBytes, err := c.loadKeyFromASCII()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kp := &keyOrPassword{
|
||||
SecretType: 1,
|
||||
Key: &key{bytes: keyBytes},
|
||||
}
|
||||
return kp.deriveKeys(salt)
|
||||
}
|
||||
|
||||
func (c *nativeCodec) loadKeyFromASCII() ([]byte, error) {
|
||||
data, err := decodeHex(c.cfg.CookieKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) < headerSize+checksumSize {
|
||||
return nil, errors.New("cookie key is too short")
|
||||
}
|
||||
if string(data[:headerSize]) != keyCurrentVersion {
|
||||
return nil, errors.New("invalid cookie key header")
|
||||
}
|
||||
|
||||
payloadLen := len(data) - checksumSize
|
||||
checked := data[:payloadLen]
|
||||
sum := sha256.Sum256(checked)
|
||||
if !hmac.Equal(sum[:], data[payloadLen:]) {
|
||||
return nil, errors.New("cookie key checksum mismatch")
|
||||
}
|
||||
|
||||
keyBytes := data[headerSize:payloadLen]
|
||||
if len(keyBytes) != keyByteSize {
|
||||
return nil, errors.New("bad cookie key length")
|
||||
}
|
||||
|
||||
return keyBytes, nil
|
||||
}
|
||||
|
||||
func (kp *keyOrPassword) deriveKeys(salt []byte) (*derivedKeys, error) {
|
||||
if kp.SecretType != 1 || kp.Key == nil {
|
||||
return nil, errors.New("unsupported cookie key type")
|
||||
}
|
||||
akey := hkdf(sha256.New, kp.Key.bytes, keyByteSize, authInfo, salt)
|
||||
ekey := hkdf(sha256.New, kp.Key.bytes, keyByteSize, encInfo, salt)
|
||||
return &derivedKeys{akey: akey, ekey: ekey}, nil
|
||||
}
|
||||
|
||||
func hkdf(hashFunc func() hash.Hash, ikm []byte, length int, info string, salt []byte) []byte {
|
||||
digestLen := hashFunc().Size()
|
||||
if salt == nil {
|
||||
salt = make([]byte, digestLen)
|
||||
}
|
||||
|
||||
prkMac := hmac.New(hashFunc, salt)
|
||||
prkMac.Write(ikm)
|
||||
prk := prkMac.Sum(nil)
|
||||
|
||||
var okm []byte
|
||||
prev := []byte{}
|
||||
counter := byte(1)
|
||||
for len(okm) < length {
|
||||
h := hmac.New(hashFunc, prk)
|
||||
h.Write(prev)
|
||||
h.Write([]byte(info))
|
||||
h.Write([]byte{counter})
|
||||
step := h.Sum(nil)
|
||||
okm = append(okm, step...)
|
||||
prev = step
|
||||
counter++
|
||||
}
|
||||
|
||||
return okm[:length]
|
||||
}
|
||||
|
||||
func aesCTR(input, keyBytes, iv []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(keyBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
output := make([]byte, len(input))
|
||||
stream := cipher.NewCTR(block, iv)
|
||||
stream.XORKeyStream(output, input)
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func verifyHMAC(expected, message, key []byte) bool {
|
||||
h := hmac.New(sha256.New, key)
|
||||
h.Write(message)
|
||||
return hmac.Equal(h.Sum(nil), expected)
|
||||
}
|
||||
|
||||
func decodeHex(input string) ([]byte, error) {
|
||||
if len(input)%2 != 0 {
|
||||
return nil, errors.New("odd length hex")
|
||||
}
|
||||
return hex.DecodeString(strings.ToLower(input))
|
||||
}
|
||||
|
||||
func parsePlaintext(input string) (map[string]string, []string) {
|
||||
values := map[string]string{}
|
||||
orderedKeys := make([]string, 0)
|
||||
|
||||
for _, pair := range strings.Split(input, fieldSeparator) {
|
||||
if pair == "" || !strings.Contains(pair, pairSeparator) {
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(pair, pairSeparator, 2)
|
||||
values[parts[0]] = parts[1]
|
||||
orderedKeys = append(orderedKeys, parts[0])
|
||||
}
|
||||
|
||||
return values, orderedKeys
|
||||
}
|
||||
|
||||
func serializeValues(values map[string]string, orderedKeys []string) string {
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(values))
|
||||
seen := map[string]struct{}{}
|
||||
for _, key := range orderedKeys {
|
||||
if _, ok := values[key]; ok {
|
||||
keys = append(keys, key)
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
extra := make([]string, 0)
|
||||
for key := range values {
|
||||
if _, ok := seen[key]; !ok {
|
||||
extra = append(extra, key)
|
||||
}
|
||||
}
|
||||
sort.Strings(extra)
|
||||
keys = append(keys, extra...)
|
||||
|
||||
pairs := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
pairs = append(pairs, fmt.Sprintf("%s|%s", key, values[key]))
|
||||
}
|
||||
return strings.Join(pairs, fieldSeparator)
|
||||
}
|
||||
|
||||
func int64Ptr(value string) *int64 {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
var parsed int64
|
||||
for _, r := range value {
|
||||
if r < '0' || r > '9' {
|
||||
return nil
|
||||
}
|
||||
parsed = parsed*10 + int64(r-'0')
|
||||
}
|
||||
return &parsed
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package cookie
|
||||
|
||||
import "testing"
|
||||
|
||||
const (
|
||||
testCookieKey = "def000008bf3d70e7012b7493c382d561e193218d0c74ab162fb0ea8029ce20e926531b4bcf0aaec9381152e6c161f198e06918b2d1aad67cc7cf40819a51ee328c63830"
|
||||
testCookie = "def5020099dce5cd9ecf197adb5532a74e3db2ed9cba3d59b98f365353099b710bd562efa48b6bad1ad0a12b2ee54de0fbfcc6baa0545a8234141b03bfc1fbbbb9061af5011764b9c4dfd9c0ddcad767a453e0cc24d6b4a7c524e6c49aabd66ecc390e1a964b6e81a051b171051c829542facbb36cf64fcfebf069906dcc95476578be3fe59aaae466cf70bd9c877d301d908ec3aa4f55366567f460dfefac1684ce381293e8d4138382a42716d6aaecdcc7"
|
||||
)
|
||||
|
||||
func TestNativeCodecDecodeFixture(t *testing.T) {
|
||||
codec, err := NewCodec(Config{
|
||||
CookieName: "PrestaShop-test",
|
||||
CookieKey: testCookieKey,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCodec() error = %v", err)
|
||||
}
|
||||
|
||||
session, err := codec.Decode(testCookie)
|
||||
if err != nil {
|
||||
t.Fatalf("Decode() error = %v", err)
|
||||
}
|
||||
|
||||
if session.Values["id_lang"] != "1" {
|
||||
t.Fatalf("id_lang = %q, want 1", session.Values["id_lang"])
|
||||
}
|
||||
if session.Values["id_currency"] != "1" {
|
||||
t.Fatalf("id_currency = %q, want 1", session.Values["id_currency"])
|
||||
}
|
||||
if session.Values["checksum"] != "2076001436" {
|
||||
t.Fatalf("checksum = %q, want 2076001436", session.Values["checksum"])
|
||||
}
|
||||
if session.Values["detect_language"] != "1" {
|
||||
t.Fatalf("detect_language = %q, want 1", session.Values["detect_language"])
|
||||
}
|
||||
if session.GuestID != nil {
|
||||
t.Fatalf("guest_id = %v, want nil", session.GuestID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeCodecRoundTrip(t *testing.T) {
|
||||
codec, err := NewCodec(Config{
|
||||
CookieName: "PrestaShop-test",
|
||||
CookieKey: testCookieKey,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCodec() error = %v", err)
|
||||
}
|
||||
|
||||
decoded, err := codec.Decode(testCookie)
|
||||
if err != nil {
|
||||
t.Fatalf("Decode() error = %v", err)
|
||||
}
|
||||
|
||||
encoded, err := codec.Encode(decoded)
|
||||
if err != nil {
|
||||
t.Fatalf("Encode() error = %v", err)
|
||||
}
|
||||
|
||||
redecoded, err := codec.Decode(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("Decode(encoded) error = %v", err)
|
||||
}
|
||||
|
||||
if redecoded.Plaintext != decoded.Plaintext {
|
||||
t.Fatalf("plaintext mismatch after roundtrip\n got: %s\nwant: %s", redecoded.Plaintext, decoded.Plaintext)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package cookie
|
||||
|
||||
import "time"
|
||||
|
||||
type ParseStatus string
|
||||
|
||||
const (
|
||||
ParseStatusAnonymous ParseStatus = "anonymous"
|
||||
ParseStatusDecoded ParseStatus = "decoded"
|
||||
ParseStatusInvalid ParseStatus = "invalid"
|
||||
)
|
||||
|
||||
type SessionContext struct {
|
||||
RawCookie string
|
||||
Plaintext string
|
||||
CookieName string
|
||||
CustomerID *int64
|
||||
CartID *int64
|
||||
LanguageID *int64
|
||||
CurrencyID *int64
|
||||
ShopID *int64
|
||||
GuestID *int64
|
||||
IsLoggedIn bool
|
||||
ExpiresAt *time.Time
|
||||
Values map[string]string
|
||||
OrderedKeys []string
|
||||
ParseStatus ParseStatus
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Version string
|
||||
CookieName string
|
||||
CookieKey string
|
||||
CookieIV string
|
||||
ProjectRoot string
|
||||
BootstrapPath string
|
||||
}
|
||||
|
||||
type Codec interface {
|
||||
Decode(raw string) (*SessionContext, error)
|
||||
Encode(session *SessionContext) (string, error)
|
||||
}
|
||||
Reference in New Issue
Block a user