diff --git a/ecom-license/DESIGN.md b/ecom-license/DESIGN.md index 86ab89f3..fd858c3b 100644 --- a/ecom-license/DESIGN.md +++ b/ecom-license/DESIGN.md @@ -10,11 +10,11 @@ Ecom-DMB 支持 **SaaS 部署** 和 **私有部署** 两种模式,所有模式 | 项目 | 说明 | |------|------| -| 校验方式 | RSA 非对称签名 JWT,绑定机器指纹,本地离线校验为主 | +| 校验方式 | RSA 非对称签名 JWT,绑定机器指纹(安装 ID),本地离线校验为主 | | 授权粒度 | 按**公司维度**授权,每套部署一个 License | | 限制范围 | 仅限制**订单导入相关接口**,其他功能不做限制 | | 受限制接口 | `POST /ec/order/batch-import`、`POST /ec/import-task/create` | -| License 内容 | 客户信息、版本类型、有效期、**机器指纹**、功能特性 | +| License 内容 | 客户信息、版本类型、有效期、**机器指纹**、安装 ID、功能特性、jti | ### 1.3 关键概念 @@ -22,7 +22,8 @@ Ecom-DMB 支持 **SaaS 部署** 和 **私有部署** 两种模式,所有模式 |------|------| | **License 服务器** | 运营方部署的授权管理平台(NestJS + Vue 3),用于签发和管理 License | | **License JWT** | RS256 签名的 JWT Token,包含授权信息和机器指纹,不可篡改 | -| **机器指纹** | 根据服务器硬件信息(MAC、CPU、磁盘等)生成的唯一哈希值 | +| **机器指纹** | 根据系统 machine-id(`/etc/machine-id`)+ 主机名生成的唯一哈希值 | +| **安装 ID** | 系统 machine-id(Linux `/etc/machine-id`),由 systemd 在首次启动时自动生成,唯一标识一次 OS 安装 | | **系统初始化** | 首次运行时的引导流程:创建管理员 + License 激活 | | **激活** | License 与机器指纹绑定并生效的过程 | @@ -63,12 +64,13 @@ Ecom-DMB 支持 **SaaS 部署** 和 **私有部署** 两种模式,所有模式 → 客户输入 License Key → 系统校验通过 → 激活完成 SaaS 部署模式: - 运营方直接部署系统 → 初始化页面显示机器指纹 - → 运营方在 License 后台为这个租户签发 License - → 输入 License Key 激活(或 SaaS 平台自动激活) - → 激活完成,后续每个租户在公司设置页面绑定自己的 License + 运营方在 License 后台签发一个不限指纹的 License(machineFingerprint 填 "*") + → 部署系统时直接配置 License → 初始化时自动完成激活 + → License 校验时跳过指纹比对 ``` +**SaaS 模式指纹策略**:SaaS 环境通常有多台服务器负载均衡,且 IP/网络环境多变,不适合绑定具体硬件指纹。签发 License 时将 `machineFingerprint` 设置为特殊值 `*`,主应用在校验时检测到该值则跳过指纹比对,仅校验签名和有效期。 + --- ## 3. 系统初始化设计 @@ -131,6 +133,9 @@ SaaS 部署模式: | POST | `/api/init/company` | 保存公司信息(Step 2) | | GET | `/api/init/fingerprint` | 获取当前机器指纹 | | POST | `/api/init/activate` | 提交 License Key 完成激活(Step 3) | +| PUT | `/api/system/license` | **License 续期/更新(已激活后调用)** | +| GET | `/api/system/license` | **获取当前 License 信息** | +| GET | `/api/system/fingerprint` | **获取当前机器指纹(已激活后查看)** | #### `GET /api/init/status` 响应 @@ -169,21 +174,59 @@ SaaS 部署模式: **校验逻辑**: 1. 用内置公钥验证 JWT 签名 2. 校验 `exp` 是否过期 -3. 校验 JWT 中的 `machineFingerprint` 与当前机器指纹是否一致 +3. 校验 JWT 中的 `machineFingerprint` 与当前机器指纹是否一致(除非指纹为 `*` 表示不限) 4. 校验通过 → 保存 License 到 `sys_license` 表 → 标记初始化完成 +#### `PUT /api/system/license` 请求 + +```json +{ + "licenseKey": "eyJhbGciOiJSUzI1NiJ9..." +} +``` + +**说明**:与激活接口逻辑一致,但已激活状态下调用时不会重置初始化状态,仅更新 `sys_license` 表和内存缓存。前端在「系统设置 → License 信息」页面调用此接口。 + +#### `GET /api/system/license` 响应 + +```json +{ + "company": "某某科技有限公司", + "edition": "enterprise", + "machineFingerprint": "FP-A1B2C3D4E5F67890...", + "expiresAt": "2027-01-01T00:00:00Z", + "activatedAt": "2026-01-01T00:00:00Z", + "status": "active" +} +``` + +#### `GET /api/system/fingerprint` 响应 + +```json +{ + "fingerprint": "FP-A1B2C3D4E5F67890..." +} +``` + +**说明**:已激活后,用户可在「系统设置 → 机器指纹」页面查看当前指纹,用于迁移服务器时提供给运营方。 + ### 3.3 初始化前端页面(主应用 Vue 3 前端) 初始化页面属于主应用的 `ecom-dmb-frontend`,在路由守卫中检测初始化状态。 ``` src/views/init/ -├── InitWizard.vue # 初始化向导容器(Step 步骤条) -├── InitStepAdmin.vue # Step 1: 创建管理员 -├── InitStepCompany.vue # Step 2: 公司信息 -├── InitStepLicense.vue # Step 3: License 激活(显示指纹 + 输入 License) +├── InitWizard.vue # 初始化向导容器(Step 步骤条) +├── InitStepAdmin.vue # Step 1: 创建管理员 +├── InitStepCompany.vue # Step 2: 公司信息 +├── InitStepLicense.vue # Step 3: License 激活(显示指纹 + 输入 License) └── components/ └── FingerprintDisplay.vue # 机器指纹展示组件(带复制功能) + +src/views/system/ +└── license/ # ← 新增:系统设置下的 License 相关页面 + ├── LicenseInfo.vue # License 信息查看 + 续期 + └── FingerprintInfo.vue # 机器指纹查看(用于迁移服务器) ``` **路由守卫逻辑**: @@ -205,17 +248,19 @@ router.beforeEach(async (to) => { 新增两张表: -#### `sys_init` 初始化状态表(单行数据) +#### `sys_init` 初始化状态表 | 字段 | 类型 | 说明 | |------|------|------| -| id | bigint PK | 主键 | +| id | bigint PK | 主键(固定为 1,仅一行) | | step | tinyint | 当前完成步骤:0=未开始 1=管理员 2=公司 3=已完成 | | admin_id | bigint | 创建的超级管理员 ID | | company_name | varchar(200) | 公司名称 | | created_at | datetime | 创建时间 | | updated_at | datetime | 更新时间 | +> 该表为**单行表**,`id` 固定为 1,通过 `INSERT ... ON DUPLICATE KEY UPDATE` 或先删后插保证唯一性。 + #### `sys_license` License 表(单行数据) | 字段 | 类型 | 说明 | @@ -224,6 +269,7 @@ router.beforeEach(async (to) => { | company_name | varchar(200) | License 中的公司名称 | | edition | varchar(20) | 版本:trial / enterprise / unlimited | | machine_fingerprint | varchar(100) | 绑定的机器指纹 | +| installation_id | varchar(64) | 安装 ID(首次运行时生成) | | license_key | text | JWT License Token | | issued_at | datetime | 签发时间 | | expires_at | datetime | 过期时间 | @@ -236,47 +282,86 @@ router.beforeEach(async (to) => { ## 4. 机器指纹设计 -### 4.1 指纹生成算法 +### 4.1 指纹生成策略 -收集以下硬件信息,组合后计算 SHA-256 哈希: +机器指纹用于将 License 绑定到特定的部署实例,防止 License 被复制到其他机器使用。 -| 来源 | 获取方式 | 说明 | -|------|----------|------| -| MAC 地址 | `NetworkInterface.getHardwareAddress()` | 取第一张非回环网卡 | -| CPU 序列号 | `ManagementFactory.getOperatingSystemMXBean()` 或 `cat /proc/cpuinfo` | CPU ID | -| 主板序列号 | `dmidecode -t 2` (Linux) / `wmic baseboard get serialnumber` (Windows) | 主板信息 | -| 磁盘序列号 | `FileStore` 属性 或 `blkid` (Linux) | 系统盘序列号 | -| 主机名 | `InetAddress.getLocalHost().getHostName()` | 机器 hostname | +**采用系统 machine-id + 主机名方案**: -**算法步骤**: +| 要素 | 来源 | 说明 | +|------|------|------| +| **系统 machine-id** | Linux `/etc/machine-id` | systemd 在首次启动时自动生成,不同 OS 安装不同;非 Linux 系统回退到随机 UUID | +| **主机名** | `InetAddress.getLocalHost().getHostName()` | 辅助指纹,方便识别 | + +**为什么用 `/etc/machine-id` 而不是自定义 UUID 文件?** + +| 攻击场景 | 自定义 UUID 文件 | 系统 `/etc/machine-id` | +|----------|-----------------|------------------------| +| 拷贝 DB + 配置文件到新机器 | 随文件一起复制,指纹校验通过 ❌ | 新机器有独立 machine-id,校验失败 ✅ | +| 整盘克隆(dd) | machine-id 被一并克隆,防不住 | 同左,整盘克隆不在防护范围 | +| 云镜像创建新实例 | 镜像自带 UUID 文件,所有实例相同 ❌ | 首次引导时 systemd 自动重新生成,每个实例不同 ✅ | + +> **结论**:使用系统 `/etc/machine-id` 能让**大部分实际克隆场景**(文件级别复制、云镜像复用)自动失效,且不需要引入额外组件。整盘克隆超出了客户端授权技术可防护的范围。 + +### 4.2 指纹算法 ``` -raw = macAddress + "|" + cpuSerial + "|" + diskSerial + "|" + hostname +machineId = 读取 /etc/machine-id(不存在则生成 UUID 并写入 /etc/ecom-machine-id 回退) +raw = machineId + "|" + hostname fingerprint = "FP-" + SHA256(raw).toUpperCase() ``` -### 4.2 Java 指纹采集实现 +### 4.3 Java 指纹采集实现 ```java public class MachineFingerprint { + private static final String SYSTEM_MACHINE_ID = "/etc/machine-id"; + private static final String FALLBACK_FILE = "/etc/ecom-machine-id"; + public static String generate() { - String mac = getMacAddress(); - String cpu = getCpuSerial(); - String disk = getDiskSerial(); + String machineId = getMachineId(); String hostname = getHostname(); - String raw = mac + "|" + cpu + "|" + disk + "|" + hostname; + String raw = machineId + "|" + hostname; String hash = DigestUtils.sha256Hex(raw); return "FP-" + hash.toUpperCase(); } + + public static String getMachineId() { + // 优先使用系统 machine-id + File sysFile = new File(SYSTEM_MACHINE_ID); + if (sysFile.exists()) { + try { + return new String(Files.readAllBytes(sysFile.toPath())).trim(); + } catch (IOException e) { + // fall through + } + } + // 回退到自定义 UUID 文件(非 Linux 系统 or 容器) + File fallback = new File(FALLBACK_FILE); + if (fallback.exists()) { + try { + return new String(Files.readAllBytes(fallback.toPath())).trim(); + } catch (IOException e) { + // fall through + } + } + // 首次运行:生成 UUID 写入回退文件 + String id = UUID.randomUUID().toString(); + try { + Files.write(fallback.toPath(), id.getBytes()); + } catch (IOException e) { + log.warn("无法写入 machine-id 文件: {}", e.getMessage()); + } + return id; + } } ``` -### 4.3 指纹在 License 中的作用 +### 4.4 指纹在 License 中的作用 - License 签发时:运营方将客户提供的机器指纹写入 JWT Payload 的 `machineFingerprint` 字段 - License 验证时:主应用计算当前机器指纹,与 JWT 中的指纹比对,不一致则拒绝 - ---- +- SaaS 模式:指纹设为 `*`,跳过比对 ## 5. License 文件格式 @@ -490,10 +575,25 @@ License JWT 支持三种来源,按优先级从高到低: | issued_at | datetime | 签发时间 | | expires_at | datetime | 过期时间 | | revoked_at | datetime | 吊销时间(可空) | +| max_activations | int | 允许的最大激活次数(null 为不限) | +| activation_count | int | 当前已激活次数 | | created_at | datetime | 创建时间 | | updated_at | datetime | 更新时间 | -### 7.4 操作日志表 `lc_oper_log` +### 7.4 激活日志表 `lc_activation_log` + +| 字段 | 类型 | 说明 | +|------|------|------| +| id | bigint PK | 主键 | +| license_id | bigint FK | 关联许可证 ID | +| machine_fingerprint | varchar(100) | 激活时的机器指纹 | +| installation_id | varchar(64) | 激活时的安装 ID | +| hostname | varchar(200) | 激活时的机器主机名 | +| ip | varchar(50) | 请求 IP | +| action | varchar(20) | 动作:activate / deactivate | +| created_at | datetime | 创建时间 | + +### 7.5 操作日志表 `lc_oper_log` | 字段 | 类型 | 说明 | |------|------|------| @@ -563,16 +663,23 @@ ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/ ┌──────────────────────────────────────┐ │ 4. 校验机器指纹 │──── 不匹配 ──▶ 拒绝 │ (LicenseInfo.fingerprint │ -│ vs MachineFingerprint.generate())│ +│ vs MachineFingerprintUtil.generate())│ └──────────┬───────────────────────────┘ ▼ 匹配 ┌──────────────────────────────────────┐ -│ 5. 放行请求 │ +│ 5. 校验吊销列表(内存黑名单 jti) │──── 已吊销 ──▶ 拒绝 +└──────────┬───────────────────────────┘ + ▼ 未吊销 +┌──────────────────────────────────────┐ +│ 6. 放行请求 │ │ 执行导入 │ └──────────────────────────────────────┘ ``` -**注意**:RSA 验签只在**首次加载时**做一次,运行时请求直接比对内存中的 `LicenseInfo` 字段。加载时机见 8.6 节。 +**注意**: +- RSA 验签只在**首次加载时**做一次,运行时请求直接比对内存中的 `LicenseInfo` 字段 +- NTP 时间偏差校验不在此链路中执行,改为启动时 + 定时任务(见 8.6 节) +- 本地吊销黑名单在启动时加载到内存,运行时只读匹配,不产生 I/O ### 8.3 配置项 `application.yml` @@ -580,14 +687,20 @@ ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/ ecom: license: enabled: true # 是否启用 license 校验 - public-key: | # RSA 公钥(内置在配置文件或编译进代码) + public-key: | # RSA 公钥 -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOC... -----END PUBLIC KEY----- license-key: "" # License JWT(优先于文件) license-file: config/license.key # License 文件路径 + max-clock-skew: 5 # 与 NTP 最大时钟偏差(分钟),超时拒绝 + ntp-server: "pool.ntp.org" # NTP 时间源,用于校验本地时间是否被篡改 + ntp-check-interval: 10 # NTP 定时检测间隔(分钟),启动时立即检查一次 + revocation-file: config/revoked.jti # 吊销黑名单文件路径(每行一个 jti) ``` +> **注意**:`@Scheduled` 定时任务需要在某个 `@Configuration` 类上添加 `@EnableScheduling` 注解。建议在 `LicenseAutoConfig` 上配置。 + ### 8.4 AOP 注解 ```java @@ -623,23 +736,57 @@ public class LicenseValidator { private final PublicKey publicKey; private final SysLicenseMapper licenseMapper; + private final LicenseProperties properties; /** * 内存缓存的 License 信息 */ private volatile LicenseInfo cachedLicense; + /** + * 吊销列表黑名单(jti 集合) + */ + private final Set revokedJtiSet = new ConcurrentHashSet<>(); + + /** + * NTP 时间偏差缓存(毫秒) + */ + private volatile long clockSkewMs = 0; + + /** + * 上次 NTP 检测时间 + */ + private volatile long lastNtpCheck = 0; + public LicenseValidator(LicenseProperties props, SysLicenseMapper licenseMapper) throws Exception { this.licenseMapper = licenseMapper; + this.properties = props; this.publicKey = loadPublicKey(props.getPublicKey()); this.cachedLicense = null; } + /** + * 启动时加载 License + 吊销列表 + */ + @PostConstruct + public void init() { + loadLicense(); + loadRevocationList(); + checkSystemClock(); + } + + /** + * 定时检测 NTP 时间偏差(每 ntpCheckInterval 分钟执行一次) + */ + @Scheduled(fixedDelayString = "#{@licenseProperties.ntpCheckInterval * 60 * 1000}") + public void scheduledNtpCheck() { + checkSystemClock(); + } + /** * 启动时加载 License(@PostConstruct 或 ApplicationRunner 调用) * 依次尝试:数据库 → 环境变量 → 文件 */ - @PostConstruct public void loadLicense() { String jwtToken = null; @@ -665,9 +812,27 @@ public class LicenseValidator { } } + /** + * 加载吊销列表黑名单(文件 → 内存) + */ + private void loadRevocationList() { + String path = properties.getRevocationFile(); + if (path == null || path.isEmpty()) return; + File file = new File(path); + if (!file.exists()) return; + try { + Files.readAllLines(file.toPath()).stream() + .map(String::trim) + .filter(l -> !l.isEmpty() && !l.startsWith("#")) + .forEach(revokedJtiSet::add); + log.info("已加载 {} 个吊销 JTI", revokedJtiSet.size()); + } catch (IOException e) { + log.warn("吊销列表加载失败: {}", e.getMessage()); + } + } + /** * 运行时校验:直接从内存判断,不做任何 I/O - * 每次请求调用,性能极高 */ public void check() { LicenseInfo license = this.cachedLicense; @@ -677,10 +842,43 @@ public class LicenseValidator { if (license.getExpiresAt().before(new Date())) { throw new LicenseException("License 已过期"); } - // 指纹比对:启动时已比对,但如果运行时 License 被外部替换,需再比一次 - String currentFp = MachineFingerprintUtil.generate(); - if (!license.getMachineFingerprint().equals(currentFp)) { - throw new LicenseException("License 与当前服务器不匹配"); + + // 指纹比对:除非 License 中指纹为 "*"(不限),否则必须匹配 + if (!"*".equals(license.getMachineFingerprint())) { + String currentFp = MachineFingerprintUtil.generate(); + if (!license.getMachineFingerprint().equals(currentFp)) { + throw new LicenseException("License 与当前服务器不匹配"); + } + } + + // 吊销检查 + if (license.getJti() != null && revokedJtiSet.contains(license.getJti())) { + throw new LicenseException("此 License 已被吊销"); + } + } + + /** + * NTP 时间偏差检测(启动时 + 定时任务,不进请求链路) + */ + private void checkSystemClock() { + int maxSkew = properties.getMaxClockSkew(); + if (maxSkew <= 0) return; + + try { + InetAddress addr = InetAddress.getByName(properties.getNtpServer()); + NtpUdpClient client = new NtpUdpClient(); + TimeInfo info = client.getTime(addr); + long ntpTime = info.getMessage().getTransmitTimeStamp().getTime(); + long localTime = System.currentTimeMillis(); + long diff = Math.abs(ntpTime - localTime); + this.clockSkewMs = diff; + this.lastNtpCheck = System.currentTimeMillis(); + + if (diff > TimeUnit.MINUTES.toMillis(maxSkew)) { + log.error("系统时间异常(与标准时间偏差 {} 秒)", diff / 1000); + } + } catch (Exception e) { + log.warn("NTP 时间校验失败,跳过: {}", e.getMessage()); } } @@ -701,7 +899,8 @@ public class LicenseValidator { } String fp = claims.get("machineFingerprint", String.class); - if (!fp.equals(currentFingerprint)) { + // 指纹为 "*" 表示不限制(SaaS 模式),或必须与当前指纹匹配 + if (!"*".equals(fp) && !fp.equals(currentFingerprint)) { throw new LicenseException("License 与当前服务器不匹配"); } @@ -711,6 +910,8 @@ public class LicenseValidator { .machineFingerprint(fp) .expiresAt(exp) .features(claims.get("features", List.class)) + .jti(claims.getId()) // jti 用于吊销 + .installationId(claims.get("installationId", String.class)) .jwtToken(jwtToken) .build(); } @@ -728,6 +929,7 @@ public class LicenseValidator { entity.setCompanyName(info.getCompany()); entity.setEdition(info.getEdition()); entity.setMachineFingerprint(fingerprint); + entity.setInstallationId(MachineFingerprintUtil.getMachineId()); entity.setExpiresAt(info.getExpiresAt()); entity.setActivatedAt(new Date()); entity.setIsActive(1); @@ -750,12 +952,16 @@ public class LicenseValidator { | 时机 | 行为 | 是否做 I/O | |------|------|-----------| -| 应用启动 `@PostConstruct` | 按优先级(DB→环境变量→文件)加载 JWT,RSA 验签 + 指纹比对,写入内存缓存 | 是(读一次) | -| 每次导入请求 `check()` | 从内存读 `cachedLicense`,比对有效期 + 指纹,不做签名验证 | **否** | -| 初始化激活 `activate()` | RSA 验签 + 指纹比对,写入 DB + 刷新内存缓存 | 是(写 DB) | -| License 续期/更新 | 更新 DB + 调用 `refresh()` 重新加载到内存 | 是(写 DB + 读) | +| 应用启动 `@PostConstruct` | 按优先级(DB→环境变量→文件)加载 JWT,RSA 验签 + 指纹比对,写入内存缓存;加载吊销黑名单文件;触发首次 NTP 时间检测 | 是(读 DB / 文件 + NTP) | +| 定时任务 `@Scheduled` | 每隔 `ntp-check-interval` 分钟执行一次 NTP 时间检测,更新 `clockSkewMs` 缓存;偏差超阈值时记录错误日志(不拒绝请求) | 是(NTP 网络请求,不进请求链路) | +| 每次导入请求 `check()` | 从内存读 `cachedLicense`,比对有效期 + 指纹(`*` 时跳过) + 吊销黑名单,**不做 NTP 请求** | **否** | +| 初始化激活 `activate()` | RSA 验签 + 指纹比对,写入 DB(含 `installationId`)+ 刷新内存缓存 | 是(写 DB) | +| License 续期/更新 `PUT /api/system/license` | 同 `activate()`,但已激活状态下不重置初始化步骤 | 是(写 DB) | +| 查看 License 信息 `GET /api/system/license` | 从内存缓存读取,无需解密 | **否** | -**核心原则**:RSA 非对称验签是 CPU 密集型操作,只在**加载时**做一次;运行时校验仅做内存中的有效期和指纹比对,零开销。 +**核心原则**: +- RSA 非对称验签是 CPU 密集型操作,只在**加载时**做一次;运行时校验仅做内存中的有效期和指纹比对,零开销 +- NTP 时间检测不进请求链路,避免网络 I/O 拖慢接口响应 ### 8.7 AOP 切面实现 @@ -810,8 +1016,9 @@ public class LicenseAspect { | 层 | 技术 | 说明 | |----|------|------| | 签名验证 | **jjwt (0.11.5)** | 已经引入,用于 JWT 验签 | -| 机器指纹 | **Java ManagementFactory / OSHI** | 硬件信息采集 | +| 机器指纹 | **Java 原生 API(/etc/machine-id / Hostname)** | 系统 machine-id + 主机名,不依赖硬件 | | 切面 | **Spring AOP** | 已有依赖 | +| NTP 检测 | **Apache Commons Net (NtpUdpClient)** | 轻量 NTP 客户端 | --- @@ -884,12 +1091,16 @@ ecom-dmb-backend/ # 主应用后端(已有) ecom-dmb-frontend/ # 主应用前端(已有) └── apps/web-antd/src/ - └── views/ - └── init/ # ← 新增:初始化向导页面 - ├── InitWizard.vue - ├── InitStepAdmin.vue - ├── InitStepCompany.vue - └── InitStepLicense.vue + ├── views/ + │ ├── init/ # ← 新增:初始化向导页面 + │ │ ├── InitWizard.vue + │ │ ├── InitStepAdmin.vue + │ │ ├── InitStepCompany.vue + │ │ └── InitStepLicense.vue + │ └── system/ + │ └── license/ # ← 新增:系统设置 + │ ├── LicenseInfo.vue # License 信息查看 + 续期 + │ └── FingerprintInfo.vue # 机器指纹查看 ``` --- @@ -928,6 +1139,38 @@ License 服务器 Ecom-DMB 主应用 - **公钥**:内置在 Ecom-DMB 主应用的 `application.yml` 或编译进代码 - 公钥原则上不应该让客户随意修改,建议编译在代码中或通过配置文件管理并签名保护 +### 11.3 密钥轮换 + +密钥泄露或定期轮换时,需要让已部署的系统能使用新公钥验证 License。方案如下: + +| 方案 | 说明 | 适用场景 | +|------|------|----------| +| **多公钥列表** | 修改 `LicenseProperties` 支持多个公钥,验证时逐个尝试 | 简单可靠,推荐 | +| **kid 标头** | JWT Header 中携带 `kid` 标识密钥版本,主应用根据 `kid` 选择对应公钥 | 更规范,实现略复杂 | + +**推荐采用多公钥列表方案**: + +```yaml +ecom: + license: + public-keys: + - id: "2025-v1" + key: | + -----BEGIN PUBLIC KEY----- + MIIBIjANBgkqhkiG9w0BAQEFAAOC... + -----END PUBLIC KEY----- + - id: "2026-v2" + key: | + -----BEGIN PUBLIC KEY----- + ... + -----END PUBLIC KEY----- +``` + +轮换流程: +1. License 服务器用新私钥签发 License(JWT Header 携带 `kid`) +2. 主应用发布新版本时内置新旧两个公钥,旧 License 依然可验证 +3. 所有客户续期后,后续版本可移除旧公钥 + --- ## 12. 典型场景流程 @@ -981,10 +1224,11 @@ License 服务器 Ecom-DMB 主应用 ``` 1. 客户需要将系统迁移到新服务器 2. 在新服务器上部署 Ecom-DMB -3. 进入初始化页面,获取新服务器的机器指纹 +3. 进入初始化页面,获取新服务器的机器指纹(安装 ID + 主机名) 4. 将新指纹发给运营方 -5. 运营方吊销旧 License,用新指纹签发新 License +5. 运营方吊销旧 License(将旧 JWT 的 jti 加入黑名单),用新指纹签发新 License 6. 客户激活 → 迁移完成 +7. 旧服务器的下次请求会因指纹不匹配或 jti 已吊销而失效 ``` --- @@ -995,10 +1239,10 @@ License 服务器 Ecom-DMB 主应用 |------|----------|-----------| | 部署方 | 客户 | 运营方 | | License 来源 | 运营方签发后客户手动激活 | 运营方直接签发并配置 | -| 机器指纹 | 客户服务器的硬件指纹 | SaaS 集群的硬件指纹 | +| 机器指纹 | 客户服务器的安装 ID + 主机名,严格绑定 | License 中指纹填 `*`,跳过指纹校验 | | 初始化流程 | 客户自行完成初始化向导 | 运营方部署时完成初始化 | | License 更新 | 客户手动更新 License | 运营方在后台更新或自动下发 | -| 地址限制 | 绑定一台服务器 | 可绑定到 SaaS 网关或不做严格绑定 | +| 地址限制 | 绑定一台服务器 | 不限服务器 | --- @@ -1006,8 +1250,21 @@ License 服务器 Ecom-DMB 主应用 1. **RSA 私钥保护**:私钥是 License 体系的安全基础,必须严格保护,建议存储在 HSM 或密钥管理服务中 2. **防回滚**:License 过期后不能通过篡改系统时间来绕过——校验时使用绝对时间戳,对比服务器时间与 License exp -3. **机器指纹绕过防护**:指纹采集在 Java 层,如客户有 root 权限可伪造指纹文件。此场景属于客户自用,不在威胁模型内 -4. **License 吊销**:离线模式下无法实时吊销。如需强吊销,可在初始化模块中集成在线验证(可选) +3. **系统时间篡改防护**:客户端修改系统时间可绕过有效期校验。解决方案: + - **不进请求链路**:NTP 时间偏差检测在**启动时 + 定时任务**(每 10 分钟)中执行,不阻塞业务请求 + - 偏差超阈值时记录错误日志并告警,不立即拒绝请求(避免 NTP 服务本身不可用导致系统不可用) + - 管理员可通过系统设置查看 NTP 状态和最近检测结果 +4. **机器指纹绕过防护**:指纹基于系统 `/etc/machine-id` + 主机名生成。`/etc/machine-id` 由 systemd 在首次启动时自动生成,不同 OS 安装互不相同。文件复制级别的克隆会自动失效(新系统有自己的 machine-id)。root 可伪造,但此时客户已拥有服务器全部权限,不在威胁模型内 +5. **License 吊销机制**: + - **本地吊销**:通过 `config/revoked.jti` 文件维护吊销列表(每行一个 jti),启动时加载到内存;运行时 `check()` 中 + 匹配内存黑名单,无 I/O 开销 + - **在线吊销(可选)**:如需强吊销,可在启动定时任务中请求 License 服务器 `/api/license/status` 接口查询当前 License + 状态,将吊销的 jti 同步到本地黑名单 +6. **公钥轮换**:参见 11.3 节,防止密钥泄露后无法更新 +7. **激活日志防滥用**:License 服务器记录每次激活的 `machine_fingerprint`、`installation_id`、`hostname`、`ip`;可设置 + `max_activations` 限制 License 的激活次数,防止同一个 License 在大量机器上激活 +8. **License 复制防护**:License JWT 中的 `machineFingerprint` 绑定到机器安装 ID,DB 复制到另一台机器后指纹不匹配; + `installationId` 记录在激活日志中,便于审计追溯 ---