From 0da96f7e4e35839600ac605684ca4dbac1faa143 Mon Sep 17 00:00:00 2001 From: ShukeBta <272197458+ShukeBta@users.noreply.github.com> Date: Thu, 25 Jun 2026 14:46:28 +0800 Subject: [PATCH] feat: verify license responses with public key --- .env.example | 3 +- Makefile | 8 +- config.example.yaml | 3 +- internal/config/config.go | 6 +- internal/config/config_test.go | 9 +- internal/handler/license.go | 1 + internal/handler/license_client.go | 122 ++++++++++++++++++++------ internal/handler/license_test.go | 54 +++++++++++- internal/handler/system_extra.go | 3 +- internal/service/runtime_settings.go | 2 + scripts/build-protected.ps1 | 20 +++++ web/src/pages/settingsGroupGeneral.ts | 13 ++- 12 files changed, 200 insertions(+), 44 deletions(-) create mode 100644 scripts/build-protected.ps1 diff --git a/.env.example b/.env.example index a7f37f3..0780c3c 100644 --- a/.env.example +++ b/.env.example @@ -18,7 +18,8 @@ ADMIN_INITIAL_PASSWORD=admin123 # Built-in license server bridge; override only when using a private MgoSever. # MEDIASTATION_LICENSE_SERVER_URL=https://mgosever.3jzs.com -# MEDIASTATION_LICENSE_HMAC_SECRET=ms-shared-hmac-secret-key-Mgo-testing +# MEDIASTATION_LICENSE_PUBLIC_KEY=MCowBQYDK2VwAyEABRXnXy+urjrbKit6Yu/HiezWgP0NdsZW3tsegJWRrtI= +# MEDIASTATION_LICENSE_HMAC_SECRET= # 3rd-party scrape providers. # MEDIASTATION_SECRETS_TMDB_API_KEY= diff --git a/Makefile b/Makefile index 09308d9..911894a 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all build build-server build-web dev dev-web run deploy docker docker-update docker-stop docker-push clean install-web tidy test vet smoke +.PHONY: all build build-server build-protected build-protected-garble build-web dev dev-web run deploy docker docker-update docker-stop docker-push clean install-web tidy test vet smoke # ---- 默认目标 ---- all: build @@ -11,6 +11,12 @@ build: build-web build-server build-server: CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o bin/mediastation-go ./cmd/server +build-protected: + CGO_ENABLED=0 go build -trimpath -buildvcs=false -ldflags="-s -w -buildid=" -o bin/mediastation-go-protected ./cmd/server + +build-protected-garble: + CGO_ENABLED=0 garble -literals -tiny build -trimpath -ldflags="-s -w -buildid=" -o bin/mediastation-go-protected ./cmd/server + # ---- 前端构建 ---- build-web: cd web && npm install --silent && npm run build diff --git a/config.example.yaml b/config.example.yaml index f604bac..5802d1e 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -112,7 +112,8 @@ license: # Built-in MediaStationGo license server bridge. # Open-source mode works without this and is limited to 20 users. server_url: "https://mgosever.3jzs.com" - hmac_secret: "ms-shared-hmac-secret-key-Mgo-testing" # must match LICENSE_HMAC_SECRET on the license server + public_key: "MCowBQYDK2VwAyEABRXnXy+urjrbKit6Yu/HiezWgP0NdsZW3tsegJWRrtI=" # Ed25519 public key for protected license responses + hmac_secret: "" # legacy fallback only; prefer Ed25519 public_key # FlareSolverr 配置(用于绕过 Cloudflare/WAF 保护) flaresolverr: diff --git a/internal/config/config.go b/internal/config/config.go index 322f832..3dab0cf 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -25,7 +25,7 @@ const ( defaultDatabaseMaxOpenConns = 4 defaultDatabaseMaxIdleConns = 2 defaultLicenseServerURL = "https://mgosever.3jzs.com" - defaultLicenseHMACSecret = "ms-shared-hmac-secret-key-Mgo-testing" // #nosec G101 -- shared response-signature key for the bundled license bridge. + defaultLicensePublicKey = "MCowBQYDK2VwAyEABRXnXy+urjrbKit6Yu/HiezWgP0NdsZW3tsegJWRrtI=" ) // Config 是根配置聚合。 @@ -172,6 +172,7 @@ type AIConfig struct { type LicenseConfig struct { ServerURL string `mapstructure:"server_url"` HMACSecret string `mapstructure:"hmac_secret"` + PublicKey string `mapstructure:"public_key"` } // OrganizerConfig 配置媒体文件智能分类整理。 @@ -333,7 +334,8 @@ func setDefaults(v *viper.Viper) { v.SetDefault("api_config.default_timeout", 30) v.SetDefault("license.server_url", defaultLicenseServerURL) - v.SetDefault("license.hmac_secret", defaultLicenseHMACSecret) + v.SetDefault("license.hmac_secret", "") + v.SetDefault("license.public_key", defaultLicensePublicKey) } // normalize 填充派生默认值并自愈空的关键字段。 diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 2ee072d..93d7342 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -58,8 +58,8 @@ func TestLoadDefaults(t *testing.T) { if !cfg.Organizer.SmartClassify { t.Fatalf("expected organizer smart classify enabled by default") } - if cfg.License.ServerURL != defaultLicenseServerURL || cfg.License.HMACSecret != defaultLicenseHMACSecret { - t.Fatalf("expected bundled license bridge defaults, got url=%q secret=%q", cfg.License.ServerURL, cfg.License.HMACSecret) + if cfg.License.ServerURL != defaultLicenseServerURL || cfg.License.PublicKey != defaultLicensePublicKey || cfg.License.HMACSecret != "" { + t.Fatalf("expected bundled license bridge defaults, got url=%q public_key=%q hmac=%q", cfg.License.ServerURL, cfg.License.PublicKey, cfg.License.HMACSecret) } // Re-loading must reuse the persisted secret on disk. cfg2, err := Load() @@ -92,6 +92,7 @@ func TestEnvOverride(t *testing.T) { t.Setenv("MEDIASTATION_SEARCH_OPENSEARCH_URL", "http://opensearch:9200") t.Setenv("MEDIASTATION_LICENSE_SERVER_URL", "https://license.example.com") t.Setenv("MEDIASTATION_LICENSE_HMAC_SECRET", "override-secret") + t.Setenv("MEDIASTATION_LICENSE_PUBLIC_KEY", "override-public-key") cfg, err := Load() if err != nil { t.Fatalf("Load() error: %v", err) @@ -108,8 +109,8 @@ func TestEnvOverride(t *testing.T) { if cfg.Search.Backend != "opensearch" || cfg.Search.OpenSearchURL != "http://opensearch:9200" { t.Fatalf("expected opensearch config from env, got backend=%q url=%q", cfg.Search.Backend, cfg.Search.OpenSearchURL) } - if cfg.License.ServerURL != "https://license.example.com" || cfg.License.HMACSecret != "override-secret" { - t.Fatalf("expected license config from env, got url=%q secret=%q", cfg.License.ServerURL, cfg.License.HMACSecret) + if cfg.License.ServerURL != "https://license.example.com" || cfg.License.HMACSecret != "override-secret" || cfg.License.PublicKey != "override-public-key" { + t.Fatalf("expected license config from env, got url=%q secret=%q public_key=%q", cfg.License.ServerURL, cfg.License.HMACSecret, cfg.License.PublicKey) } } diff --git a/internal/handler/license.go b/internal/handler/license.go index 5f03a9b..7cc027d 100644 --- a/internal/handler/license.go +++ b/internal/handler/license.go @@ -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:"-"` } diff --git a/internal/handler/license_client.go b/internal/handler/license_client.go index 1046659..64ade37 100644 --- a/internal/handler/license_client.go +++ b/internal/handler/license_client.go @@ -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, + } +} diff --git a/internal/handler/license_test.go b/internal/handler/license_test.go index 8eaf63d..658b4e2 100644 --- a/internal/handler/license_test.go +++ b/internal/handler/license_test.go @@ -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)) +} diff --git a/internal/handler/system_extra.go b/internal/handler/system_extra.go index 80d97ed..9eec159 100644 --- a/internal/handler/system_extra.go +++ b/internal/handler/system_extra.go @@ -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 签名密钥(旧版兼容)"}, }, }, }, diff --git a/internal/service/runtime_settings.go b/internal/service/runtime_settings.go index 7f83d5e..91cdffe 100644 --- a/internal/service/runtime_settings.go +++ b/internal/service/runtime_settings.go @@ -104,6 +104,8 @@ func ApplyRuntimeSetting(cfg *config.Config, key, value string) { cfg.License.ServerURL = value case "license.hmac_secret": cfg.License.HMACSecret = value + case "license.public_key": + cfg.License.PublicKey = value } } diff --git a/scripts/build-protected.ps1 b/scripts/build-protected.ps1 new file mode 100644 index 0000000..cabc3bc --- /dev/null +++ b/scripts/build-protected.ps1 @@ -0,0 +1,20 @@ +param( + [string]$Output = "bin/mediastation-go-protected.exe", + [switch]$Garble +) + +$ErrorActionPreference = "Stop" +$env:CGO_ENABLED = "0" + +New-Item -ItemType Directory -Force -Path (Split-Path -Parent $Output) | Out-Null + +if ($Garble) { + if (-not (Get-Command garble -ErrorAction SilentlyContinue)) { + throw "garble is not installed. Run: go install mvdan.cc/garble@latest" + } + garble -literals -tiny build -trimpath -ldflags="-s -w -buildid=" -o $Output ./cmd/server + exit $LASTEXITCODE +} + +go build -trimpath -buildvcs=false -ldflags="-s -w -buildid=" -o $Output ./cmd/server +exit $LASTEXITCODE diff --git a/web/src/pages/settingsGroupGeneral.ts b/web/src/pages/settingsGroupGeneral.ts index cdb8d03..7c0c8c2 100644 --- a/web/src/pages/settingsGroupGeneral.ts +++ b/web/src/pages/settingsGroupGeneral.ts @@ -119,10 +119,17 @@ export const licenseSettingsGroup: SettingGroup = { placeholder: 'https://mgosever.3jzs.com', }, { - key: 'license.hmac_secret', - label: 'HMAC 签名密钥', + key: 'license.public_key', + label: 'Ed25519 验签公钥', type: 'text', - hint: '必须与 License Server 的 LICENSE_HMAC_SECRET 保持一致;用于校验多用户授权响应签名。', + hint: '优先使用。客户端只保存公钥,无法伪造授权服务响应;自建 MgoSever 时填写私钥对应的公钥。', + placeholder: 'MCowBQYDK2VwAyEA...', + }, + { + key: 'license.hmac_secret', + label: 'HMAC 签名密钥(旧版兼容)', + type: 'text', + hint: '仅兼容旧版授权服务。新版本应使用 Ed25519 公钥,避免把共享密钥编译进客户端。', }, ], }