mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 03:26:37 +08:00
feat: verify license responses with public key
This commit is contained in:
@@ -46,6 +46,7 @@ type licenseServerSignedResp struct {
|
||||
DaysRemaining *int `json:"days_remaining"`
|
||||
NextHeartbeat string `json:"next_heartbeat"`
|
||||
Signature string `json:"signature"`
|
||||
SignatureAlg string `json:"signature_alg"`
|
||||
LegacySignature bool `json:"-"`
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,11 @@ package handler
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -18,9 +21,10 @@ import (
|
||||
)
|
||||
|
||||
type licenseClient struct {
|
||||
baseURL string
|
||||
hmacSecret string
|
||||
httpClient *http.Client
|
||||
baseURL string
|
||||
hmacSecret string
|
||||
ed25519PublicKey ed25519.PublicKey
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func newLicenseClient(ctx context.Context, svc *service.Container) (*licenseClient, error) {
|
||||
@@ -32,18 +36,27 @@ func newLicenseClient(ctx context.Context, svc *service.Container) (*licenseClie
|
||||
if strings.TrimSpace(secret) == "" {
|
||||
secret = svc.Cfg.License.HMACSecret
|
||||
}
|
||||
publicKeyRaw, _ := svc.Repo.Setting.Get(ctx, "license.public_key")
|
||||
if strings.TrimSpace(publicKeyRaw) == "" {
|
||||
publicKeyRaw = svc.Cfg.License.PublicKey
|
||||
}
|
||||
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if baseURL == "" {
|
||||
return nil, errors.New("license server url not configured")
|
||||
}
|
||||
secret = strings.TrimSpace(secret)
|
||||
if secret == "" {
|
||||
return nil, errors.New("license hmac secret not configured")
|
||||
publicKey, err := parseLicenseEd25519PublicKey(publicKeyRaw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if secret == "" && len(publicKey) == 0 {
|
||||
return nil, errors.New("license public key or hmac secret not configured")
|
||||
}
|
||||
return &licenseClient{
|
||||
baseURL: baseURL,
|
||||
hmacSecret: secret,
|
||||
httpClient: &http.Client{Timeout: 15 * time.Second},
|
||||
baseURL: baseURL,
|
||||
hmacSecret: secret,
|
||||
ed25519PublicKey: publicKey,
|
||||
httpClient: &http.Client{Timeout: 15 * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -96,30 +109,42 @@ func (c *licenseClient) do(req *http.Request, out any) error {
|
||||
}
|
||||
|
||||
func (c *licenseClient) verifySigned(resp *licenseServerSignedResp) error {
|
||||
if c.hmacSecret == "" {
|
||||
return errors.New("license hmac secret not configured")
|
||||
}
|
||||
if strings.TrimSpace(resp.Signature) == "" {
|
||||
return errors.New("license server signature missing")
|
||||
}
|
||||
unsigned := struct {
|
||||
Valid bool `json:"valid"`
|
||||
LicenseType string `json:"license_type"`
|
||||
ExpiryDate *string `json:"expiry_date"`
|
||||
MaxDevices int `json:"max_devices"`
|
||||
MaxUsers *int `json:"max_users"`
|
||||
DaysRemaining *int `json:"days_remaining"`
|
||||
NextHeartbeat string `json:"next_heartbeat"`
|
||||
}{
|
||||
Valid: resp.Valid,
|
||||
LicenseType: resp.LicenseType,
|
||||
ExpiryDate: resp.ExpiryDate,
|
||||
MaxDevices: resp.MaxDevices,
|
||||
MaxUsers: resp.MaxUsers,
|
||||
DaysRemaining: resp.DaysRemaining,
|
||||
NextHeartbeat: resp.NextHeartbeat,
|
||||
switch strings.ToLower(strings.TrimSpace(resp.SignatureAlg)) {
|
||||
case "ed25519":
|
||||
return c.verifyEd25519Signed(*resp)
|
||||
case "", "hmac", "hmac-sha256":
|
||||
return c.verifyHMACSigned(resp)
|
||||
default:
|
||||
return fmt.Errorf("unsupported license signature algorithm %q", resp.SignatureAlg)
|
||||
}
|
||||
payload, err := json.Marshal(unsigned)
|
||||
}
|
||||
|
||||
func (c *licenseClient) verifyEd25519Signed(resp licenseServerSignedResp) error {
|
||||
if len(c.ed25519PublicKey) != ed25519.PublicKeySize {
|
||||
return errors.New("license Ed25519 public key not configured")
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(resp.Signature))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
payload, err := json.Marshal(licenseSignedPayload(resp))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ed25519.Verify(c.ed25519PublicKey, payload, signature) {
|
||||
return errors.New("license server signature verification failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *licenseClient) verifyHMACSigned(resp *licenseServerSignedResp) error {
|
||||
if c.hmacSecret == "" {
|
||||
return errors.New("license hmac secret not configured")
|
||||
}
|
||||
payload, err := json.Marshal(licenseSignedPayload(*resp))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -161,3 +186,44 @@ func (c *licenseClient) verifyLegacySigned(resp licenseServerSignedResp) bool {
|
||||
expected := hex.EncodeToString(mac.Sum(nil))
|
||||
return hmac.Equal([]byte(expected), []byte(resp.Signature))
|
||||
}
|
||||
|
||||
func parseLicenseEd25519PublicKey(encoded string) (ed25519.PublicKey, error) {
|
||||
encoded = strings.TrimSpace(encoded)
|
||||
if encoded == "" {
|
||||
return nil, nil
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode license Ed25519 public key: %w", err)
|
||||
}
|
||||
if key, err := x509.ParsePKIXPublicKey(raw); err == nil {
|
||||
if publicKey, ok := key.(ed25519.PublicKey); ok && len(publicKey) == ed25519.PublicKeySize {
|
||||
return publicKey, nil
|
||||
}
|
||||
return nil, errors.New("license public key is not an Ed25519 PKIX public key")
|
||||
}
|
||||
if len(raw) == ed25519.PublicKeySize {
|
||||
return ed25519.PublicKey(raw), nil
|
||||
}
|
||||
return nil, errors.New("license public key must be base64 PKIX or raw 32-byte Ed25519 public key")
|
||||
}
|
||||
|
||||
func licenseSignedPayload(resp licenseServerSignedResp) any {
|
||||
return struct {
|
||||
Valid bool `json:"valid"`
|
||||
LicenseType string `json:"license_type"`
|
||||
ExpiryDate *string `json:"expiry_date"`
|
||||
MaxDevices int `json:"max_devices"`
|
||||
MaxUsers *int `json:"max_users"`
|
||||
DaysRemaining *int `json:"days_remaining"`
|
||||
NextHeartbeat string `json:"next_heartbeat"`
|
||||
}{
|
||||
Valid: resp.Valid,
|
||||
LicenseType: resp.LicenseType,
|
||||
ExpiryDate: resp.ExpiryDate,
|
||||
MaxDevices: resp.MaxDevices,
|
||||
MaxUsers: resp.MaxUsers,
|
||||
DaysRemaining: resp.DaysRemaining,
|
||||
NextHeartbeat: resp.NextHeartbeat,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
@@ -142,6 +145,46 @@ func TestLicenseHeartbeatPayloadIncludesStoredLicenseKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseClientVerifiesEd25519Signature(t *testing.T) {
|
||||
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := licenseServerSignedResp{
|
||||
Valid: true,
|
||||
LicenseType: "subscription",
|
||||
MaxDevices: 2,
|
||||
NextHeartbeat: time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
SignatureAlg: "ed25519",
|
||||
}
|
||||
resp.Signature = signLicenseTestPayloadEd25519(privateKey, resp)
|
||||
|
||||
client := &licenseClient{ed25519PublicKey: publicKey}
|
||||
if err := client.verifySigned(&resp); err != nil {
|
||||
t.Fatalf("verify ed25519 signature: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseClientRejectsEd25519WithoutPublicKey(t *testing.T) {
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := licenseServerSignedResp{
|
||||
Valid: true,
|
||||
LicenseType: "subscription",
|
||||
MaxDevices: 2,
|
||||
NextHeartbeat: time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
SignatureAlg: "ed25519",
|
||||
}
|
||||
resp.Signature = signLicenseTestPayloadEd25519(privateKey, resp)
|
||||
|
||||
client := &licenseClient{}
|
||||
if err := client.verifySigned(&resp); err == nil || !strings.Contains(err.Error(), "public key") {
|
||||
t.Fatalf("expected missing public key error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseHeartbeatDueUsesTwelveHourWindow(t *testing.T) {
|
||||
state := service.LicenseActivationState{
|
||||
Valid: true,
|
||||
@@ -347,13 +390,13 @@ func TestLicenseActivateBindsServerInstanceNotBrowserFingerprint(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLicenseClientRequiresHMACSecret(t *testing.T) {
|
||||
func TestNewLicenseClientRequiresSignatureVerifier(t *testing.T) {
|
||||
svc := newLicenseHandlerTestService(t)
|
||||
if err := svc.Repo.Setting.Set(t.Context(), licenseServerURLSetting, "http://127.0.0.1:8001"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := newLicenseClient(t.Context(), svc); err == nil || !strings.Contains(err.Error(), "hmac secret") {
|
||||
t.Fatalf("expected missing hmac secret error, got %v", err)
|
||||
if _, err := newLicenseClient(t.Context(), svc); err == nil || !strings.Contains(err.Error(), "public key or hmac secret") {
|
||||
t.Fatalf("expected missing signature verifier error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,3 +438,8 @@ func signLicenseTestPayload(secret string, resp licenseServerSignedResp) string
|
||||
_, _ = mac.Write(payload)
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func signLicenseTestPayloadEd25519(privateKey ed25519.PrivateKey, resp licenseServerSignedResp) string {
|
||||
payload, _ := json.Marshal(licenseSignedPayload(resp))
|
||||
return base64.StdEncoding.EncodeToString(ed25519.Sign(privateKey, payload))
|
||||
}
|
||||
|
||||
@@ -127,7 +127,8 @@ func schemaHandler(_ *service.Container) gin.HandlerFunc {
|
||||
"label": "授权服务",
|
||||
"items": []gin.H{
|
||||
{"key": "license.server_url", "type": "text", "label": "License Server 地址"},
|
||||
{"key": "license.hmac_secret", "type": "text", "label": "HMAC 签名密钥"},
|
||||
{"key": "license.public_key", "type": "text", "label": "Ed25519 验签公钥"},
|
||||
{"key": "license.hmac_secret", "type": "text", "label": "HMAC 签名密钥(旧版兼容)"},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user