diff --git a/README.md b/README.md index 3bc7203..48789dd 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,21 @@ client.Check("module.x") // (bool, Reason)——GRACE/EXPIRED/REVO 状态机:`UNVERIFIED → ACTIVE → GRACE(断连宽限)→ EXPIRED / REVOKED(终态)`。 +## 机器绑定 + +license payload 带 `bind.fp` 时,SDK 默认自动采集本机指纹并校验,不一致或采集失败即拒绝(fail-closed)。可用 `sdk.MachineFingerprint()` 查看本机值,或用 `WithFingerprint` / `WithFingerprintFunc` 显式注入: + +```go +fp, err := sdk.MachineFingerprint() // "sha256:…" +client, err := sdk.New(sdk.WithLicenseFile("license.eflic"), ...) // 自动校验 bind.fp +client, err := sdk.New(..., sdk.WithFingerprint(fp)) // 显式覆盖 +client, err := sdk.New(..., sdk.WithFingerprintFunc(func() (string, error) { + return readHostMachineID() // 容器内读取挂载的宿主 ID +})) +``` + +Linux 采集 machine-id + DMI product_uuid;macOS 采集 IOPlatformUUID;容器内默认拒绝自动采集(容器自身 ID 不稳定),需挂载宿主 `/etc/machine-id` 并注入自定义采集器,或显式指定指纹。 + ## 包结构 | 包 | 职责 | diff --git a/license/fingerprint.go b/license/fingerprint.go new file mode 100644 index 0000000..858ae6a --- /dev/null +++ b/license/fingerprint.go @@ -0,0 +1,23 @@ +package license + +import ( + "errors" + "regexp" + "strings" +) + +// fingerprintPattern 是 bind.fp 的协议形态:sha256:<64 位十六进制>。 +var fingerprintPattern = regexp.MustCompile(`(?i)^sha256:[0-9a-f]{64}$`) + +// NormalizeFingerprint 校验并归一化机器指纹(统一为小写 sha256:)。 +// 空字符串表示不绑定,返回空值且无错误。 +func NormalizeFingerprint(fp string) (string, error) { + fp = strings.TrimSpace(fp) + if fp == "" { + return "", nil + } + if !fingerprintPattern.MatchString(fp) { + return "", errors.New("机器指纹必须形如 sha256:<64 位十六进制>") + } + return "sha256:" + strings.ToLower(fp[len("sha256:"):]), nil +} diff --git a/license/fingerprint_test.go b/license/fingerprint_test.go new file mode 100644 index 0000000..1d07fb1 --- /dev/null +++ b/license/fingerprint_test.go @@ -0,0 +1,32 @@ +package license + +import ( + "strings" + "testing" +) + +func TestNormalizeFingerprint(t *testing.T) { + valid := "sha256:" + strings.Repeat("a", 64) + cases := []struct { + input string + want string + wantErr bool + }{ + {"", "", false}, + {valid, valid, false}, + {" " + strings.ToUpper(valid) + " ", valid, false}, + {"not-a-fingerprint", "", true}, + {"sha256:xyz", "", true}, + {"sha256:" + strings.Repeat("g", 64), "", true}, + } + for _, tc := range cases { + got, err := NormalizeFingerprint(tc.input) + if (err != nil) != tc.wantErr { + t.Errorf("%q: err=%v wantErr=%v", tc.input, err, tc.wantErr) + continue + } + if got != tc.want { + t.Errorf("%q: got %q want %q", tc.input, got, tc.want) + } + } +} diff --git a/sdk/client.go b/sdk/client.go index 745c3dc..b978672 100644 --- a/sdk/client.go +++ b/sdk/client.go @@ -53,17 +53,18 @@ func (wallClock) Now() int64 { return time.Now().Unix() } var defaultTierOrder = []string{"free", "starter", "pro", "business", "enterprise", "ultimate"} type options struct { - licenseFile string - remoteServer string - licenseKey string - productKey string - fingerprint string - trust *crypto.TrustChain - tierOrder []string - clock Clock - logger *slog.Logger - onState func(from, to State) - pollInterval time.Duration + licenseFile string + remoteServer string + licenseKey string + productKey string + fingerprint string + fingerprintFn func() (string, error) + trust *crypto.TrustChain + tierOrder []string + clock Clock + logger *slog.Logger + onState func(from, to State) + pollInterval time.Duration // Proxy 模式(docs/design/08-k8s-proxy.md §4) proxyAddr string @@ -74,11 +75,19 @@ type options struct { // Option 配置项(docs/design/07-sdk.md §3.1)。 type Option func(*options) -func WithLicenseFile(path string) Option { return func(o *options) { o.licenseFile = path } } -func WithRemoteServer(baseURL string) Option { return func(o *options) { o.remoteServer = baseURL } } -func WithLicenseKey(key string) Option { return func(o *options) { o.licenseKey = key } } -func WithProductKey(pk string) Option { return func(o *options) { o.productKey = pk } } -func WithFingerprint(fp string) Option { return func(o *options) { o.fingerprint = fp } } +func WithLicenseFile(path string) Option { return func(o *options) { o.licenseFile = path } } +func WithRemoteServer(baseURL string) Option { return func(o *options) { o.remoteServer = baseURL } } +func WithLicenseKey(key string) Option { return func(o *options) { o.licenseKey = key } } +func WithProductKey(pk string) Option { return func(o *options) { o.productKey = pk } } + +// WithFingerprint 显式指定机器指纹;省略时 SDK 自动采集(见 MachineFingerprint)。 +// 自定义采集(如容器内读取挂载的宿主 machine-id)使用 WithFingerprintFunc。 +func WithFingerprint(fp string) Option { return func(o *options) { o.fingerprint = fp } } + +// WithFingerprintFunc 自定义机器指纹采集器;仅在未显式 WithFingerprint 时生效。 +func WithFingerprintFunc(fn func() (string, error)) Option { + return func(o *options) { o.fingerprintFn = fn } +} func WithTrustChain(tc *crypto.TrustChain) Option { return func(o *options) { o.trust = tc } } func WithTierOrder(order []string) Option { return func(o *options) { o.tierOrder = order } } func WithClock(c Clock) Option { return func(o *options) { o.clock = c } } @@ -226,8 +235,15 @@ func (c *Client) verifyToken(token string) (*license.Payload, error) { if p.Prod != c.opts.productKey { return nil, fmt.Errorf("sdk: 产品不符(license=%s, 期望=%s)", p.Prod, c.opts.productKey) } - if c.opts.fingerprint != "" && p.Bind != nil && p.Bind.FP != "" && p.Bind.FP != c.opts.fingerprint { - return nil, errors.New("sdk: 机器指纹绑定不符") + // bind.fp 存在时必须校验:显式指纹 > 自定义采集器 > 默认机器采集;采集失败 fail-closed。 + if p.Bind != nil && p.Bind.FP != "" { + fp, err := c.effectiveFingerprint() + if err != nil { + return nil, err + } + if fp != p.Bind.FP { + return nil, errors.New("sdk: 机器指纹绑定不符") + } } return p, nil } diff --git a/sdk/fingerprint.go b/sdk/fingerprint.go new file mode 100644 index 0000000..67e04bb --- /dev/null +++ b/sdk/fingerprint.go @@ -0,0 +1,59 @@ +package sdk + +import ( + "errors" + "fmt" + "strings" + + "git.wxccs.org/EntitleForge/EntitleForge-SDK-go/crypto" +) + +// machineFingerprintProvider 是默认采集器,测试可替换。 +var machineFingerprintProvider = MachineFingerprint + +// MachineFingerprint 采集本机稳定标识并返回 "sha256:" 前缀摘要。 +// +// 采集原则见 docs/design/04-crypto.md §5: +// - Linux:/etc/machine-id(或 /var/lib/dbus/machine-id)+ DMI product_uuid; +// - macOS:IOPlatformUUID(ioreg); +// - 容器:禁止使用容器自身 ID;需显式 WithFingerprint 或 WithFingerprintFunc +// 读取挂载的宿主 machine-id(设置 EF_FINGERPRINT_ALLOW_CONTAINER=1 可放行, +// 仅当你确认 /etc/machine-id 来自宿主)。 +// +// 原始字段仅在本地参与哈希,返回值不包含任何原始硬件信息。 +func MachineFingerprint() (string, error) { + fields, err := machineFields() + if err != nil { + return "", err + } + if len(fields) == 0 { + return "", errors.New("sdk: 无法采集稳定的机器标识字段") + } + return crypto.Fingerprint(fields...), nil +} + +// effectiveFingerprint 解析本次校验应使用的指纹: +// 显式 WithFingerprint 优先,其次自定义采集器,最后默认采集器。 +func (c *Client) effectiveFingerprint() (string, error) { + if c.opts.fingerprint != "" { + return c.opts.fingerprint, nil + } + if c.opts.fingerprintFn != nil { + fp, err := c.opts.fingerprintFn() + if err != nil { + return "", fmt.Errorf("sdk: 机器指纹采集失败(自定义采集器): %w", err) + } + if strings.TrimSpace(fp) == "" { + return "", errors.New("sdk: 自定义指纹采集器返回空值") + } + return fp, nil + } + fp, err := machineFingerprintProvider() + if err != nil { + return "", fmt.Errorf("sdk: 机器指纹采集失败: %w", err) + } + if strings.TrimSpace(fp) == "" { + return "", errors.New("sdk: 机器指纹采集结果为空") + } + return fp, nil +} diff --git a/sdk/fingerprint_darwin.go b/sdk/fingerprint_darwin.go new file mode 100644 index 0000000..422c23f --- /dev/null +++ b/sdk/fingerprint_darwin.go @@ -0,0 +1,26 @@ +//go:build darwin + +package sdk + +import ( + "errors" + "os/exec" + "regexp" + "strings" +) + +var ioPlatformUUIDPattern = regexp.MustCompile(`"IOPlatformUUID"\s*=\s*"([^"]+)"`) + +// machineFields macOS 采集:IOPlatformUUID(硬件平台 UUID), +// ioreg 不可用时退回 hostname(稳定性较弱,但至少可用于普通拷贝防护)。 +func machineFields() ([]string, error) { + if out, err := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").Output(); err == nil { + if m := ioPlatformUUIDPattern.FindStringSubmatch(string(out)); len(m) == 2 && strings.TrimSpace(m[1]) != "" { + return []string{"io-platform-uuid:" + strings.ToLower(strings.TrimSpace(m[1]))}, nil + } + } + if h := hostname(); h != "" && h != "unknown" { + return []string{"hostname:" + h}, nil + } + return nil, errors.New("sdk: macOS 上未取得 IOPlatformUUID 或 hostname") +} diff --git a/sdk/fingerprint_linux.go b/sdk/fingerprint_linux.go new file mode 100644 index 0000000..a460d59 --- /dev/null +++ b/sdk/fingerprint_linux.go @@ -0,0 +1,104 @@ +//go:build linux + +package sdk + +import ( + "errors" + "net" + "os" + "strings" +) + +// machineFields Linux 采集:machine-id + DMI product_uuid; +// 两者都不可用时退回首个物理网卡 MAC,最后退回 hostname。 +func machineFields() ([]string, error) { + if inContainer() { + return nil, errors.New("sdk: 检测到容器环境,容器自身 ID 不稳定;请显式 WithFingerprint,或用 WithFingerprintFunc 读取挂载的宿主 /etc/machine-id(若已挂载宿主 ID,可设置 EF_FINGERPRINT_ALLOW_CONTAINER=1 放行)") + } + + var fields []string + if v := readTrimmed("/etc/machine-id"); v != "" { + fields = append(fields, "machine-id:"+v) + } else if v := readTrimmed("/var/lib/dbus/machine-id"); v != "" { + fields = append(fields, "machine-id:"+v) + } + if v := readTrimmed("/sys/class/dmi/id/product_uuid"); v != "" && !junkUUID(v) { + fields = append(fields, "product-uuid:"+strings.ToLower(v)) + } + if len(fields) == 0 { + if mac := firstPhysicalMAC(); mac != "" { + fields = append(fields, "mac:"+mac) + } + } + if len(fields) == 0 { + if h := hostname(); h != "" && h != "unknown" { + fields = append(fields, "hostname:"+h) + } + } + if len(fields) == 0 { + return nil, errors.New("sdk: Linux 上未找到 machine-id/DMI/MAC/hostname 任一稳定标识") + } + return fields, nil +} + +// inContainer 判断常见容器运行时;显式放行环境变量供"宿主 machine-id 已挂载"场景使用。 +func inContainer() bool { + if os.Getenv("EF_FINGERPRINT_ALLOW_CONTAINER") == "1" { + return false + } + if _, err := os.Stat("/.dockerenv"); err == nil { + return true + } + if _, err := os.Stat("/run/.containerenv"); err == nil { + return true + } + if data, err := os.ReadFile("/proc/1/cgroup"); err == nil { + text := string(data) + for _, marker := range []string{"docker", "kubepods", "containerd", "libpod"} { + if strings.Contains(text, marker) { + return true + } + } + } + return false +} + +// junkUUID 过滤全零/全 F 一类无效 DMI UUID。 +func junkUUID(v string) bool { + s := strings.ReplaceAll(strings.ToLower(v), "-", "") + if len(s) < 16 { + return true + } + return strings.Trim(s, "0") == "" || strings.Trim(s, "f") == "" +} + +// firstPhysicalMAC 返回首个非回环、非全零的 MAC(小写,带冒号)。 +func firstPhysicalMAC() string { + ifaces, err := net.Interfaces() + if err != nil { + return "" + } + for _, iface := range ifaces { + if iface.Flags&net.FlagLoopback != 0 { + continue + } + mac := iface.HardwareAddr.String() + if mac == "" { + continue + } + compact := strings.ReplaceAll(mac, ":", "") + if strings.Trim(compact, "0") == "" { + continue + } + return strings.ToLower(mac) + } + return "" +} + +func readTrimmed(path string) string { + data, err := os.ReadFile(path) + if err != nil { + return "" + } + return strings.TrimSpace(string(data)) +} diff --git a/sdk/fingerprint_other.go b/sdk/fingerprint_other.go new file mode 100644 index 0000000..86f404a --- /dev/null +++ b/sdk/fingerprint_other.go @@ -0,0 +1,14 @@ +//go:build !linux && !darwin + +package sdk + +import "errors" + +// machineFields 其他平台暂无稳定硬件标识采集实现:仅使用 hostname 兜底。 +// 生产接入应通过 WithFingerprint 或 WithFingerprintFunc 注入平台特定标识。 +func machineFields() ([]string, error) { + if h := hostname(); h != "" && h != "unknown" { + return []string{"hostname:" + h}, nil + } + return nil, errors.New("sdk: 当前平台无法采集机器标识") +} diff --git a/sdk/fingerprint_test.go b/sdk/fingerprint_test.go new file mode 100644 index 0000000..2b4b2d5 --- /dev/null +++ b/sdk/fingerprint_test.go @@ -0,0 +1,118 @@ +package sdk + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license" +) + +func writeLicense(t *testing.T, token string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "license.eflic") + if err := os.WriteFile(path, []byte(token), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +// TestFileMode_AutoFingerprintBinding 验证 bind.fp 在未显式传入指纹时也会自动校验。 +func TestFileMode_AutoFingerprintBinding(t *testing.T) { + e := newEnv(t) + const bound = "sha256:bound-value" + token := e.sign(func(p *license.Payload) { + p.Bind = &license.Bindings{FP: bound} + }) + path := writeLicense(t, token) + + cases := []struct { + name string + opt Option + wantErr string + }{ + {"自动采集匹配", WithFingerprintFunc(func() (string, error) { return bound, nil }), ""}, + {"自动采集不符", WithFingerprintFunc(func() (string, error) { return "sha256:other", nil }), "指纹绑定不符"}, + {"自动采集失败", WithFingerprintFunc(func() (string, error) { return "", errors.New("无稳定硬件标识") }), "指纹采集失败"}, + {"显式指纹覆盖自动采集", WithFingerprint(bound), ""}, + {"显式指纹不符", WithFingerprint("sha256:explicit-other"), "指纹绑定不符"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + client, err := New(WithLicenseFile(path), WithProductKey("prod_test"), + WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now}), tc.opt) + if tc.wantErr != "" { + if err == nil { + t.Fatalf("应拒绝,实际通过(状态 %s)", client.State()) + } + if !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("错误应包含 %q: %v", tc.wantErr, err) + } + return + } + if err != nil { + t.Fatalf("应通过: %v", err) + } + defer client.Close() + if client.State() != StateActive { + t.Fatalf("状态: %s", client.State()) + } + }) + } +} + +// TestFileMode_DefaultProviderInvoked 验证默认路径确实调用了机器指纹采集器。 +func TestFileMode_DefaultProviderInvoked(t *testing.T) { + e := newEnv(t) + token := e.sign(func(p *license.Payload) { + p.Bind = &license.Bindings{FP: "sha256:auto-collected"} + }) + path := writeLicense(t, token) + + old := machineFingerprintProvider + machineFingerprintProvider = func() (string, error) { return "sha256:auto-collected", nil } + defer func() { machineFingerprintProvider = old }() + + client, err := New(WithLicenseFile(path), WithProductKey("prod_test"), + WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now})) + if err != nil { + t.Fatalf("默认自动采集应通过: %v", err) + } + defer client.Close() + if client.State() != StateActive { + t.Fatalf("状态: %s", client.State()) + } +} + +// TestFileMode_UnboundLicenseSkipsCollector 无绑定 license 不应因采集失败而不可用。 +func TestFileMode_UnboundLicenseSkipsCollector(t *testing.T) { + e := newEnv(t) + path := writeLicense(t, e.sign(nil)) + + old := machineFingerprintProvider + machineFingerprintProvider = func() (string, error) { return "", errors.New("采集失败") } + defer func() { machineFingerprintProvider = old }() + + client, err := New(WithLicenseFile(path), WithProductKey("prod_test"), + WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now})) + if err != nil { + t.Fatalf("无绑定 license 不应触发指纹采集: %v", err) + } + defer client.Close() + if client.State() != StateActive { + t.Fatalf("状态: %s", client.State()) + } +} + +// TestMachineFingerprint_Shape 验证公开采集 API 的形态;容器内无法采集时跳过。 +func TestMachineFingerprint_Shape(t *testing.T) { + fp, err := MachineFingerprint() + if err != nil { + t.Skipf("当前环境无法自动采集(预期于容器内): %v", err) + } + if !strings.HasPrefix(fp, "sha256:") || len(fp) != len("sha256:")+64 { + t.Fatalf("指纹形态非法: %q", fp) + } +} diff --git a/sdk/remote.go b/sdk/remote.go index 5716b8f..61c54b3 100644 --- a/sdk/remote.go +++ b/sdk/remote.go @@ -28,8 +28,12 @@ func defaultHTTPClient() *http.Client { // Activate 用 license key 换取租约并进入 ACTIVE(docs/design/09-api-spec.md §2.1)。 func (c *Client) Activate(ctx context.Context, licenseKey string) error { const logField = "pkg.sdk.Client.Activate" - fp := c.opts.fingerprint - if fp == "" { + // 指纹:显式注入 > 自定义采集器 > 自动采集;自动采集失败时退回 hostname 席位标识 + // (若 license 绑定了机器,服务端会以指纹不符拒绝,不会误放行)。 + fp, fpErr := c.effectiveFingerprint() + if fpErr != nil { + c.opts.logger.Warn("自动指纹采集失败,激活仅使用 hostname 席位标识", + "logger", logField, "error", fpErr) fp = defaultFingerprint() } body := map[string]any{ @@ -282,7 +286,8 @@ func (c *Client) postJSON(ctx context.Context, path, bearer string, body any, ou const sdkVersion = "0.1.0" -// defaultFingerprint 默认机器指纹采集(v1:hostname;生产版接 internal/crypto.Fingerprint 采集器)。 +// defaultFingerprint 是自动采集失败时的最后退路(仅 hostname),用于无绑定 license 的席位标识。 +// 有 bind.fp 的 license 在文件模式会 fail-closed(见 MachineFingerprint / verifyToken)。 func defaultFingerprint() string { return "sha256:host:" + hostname() }