Files
Reims-Go/internal/macos/opencore/smbios.go
T
Nwflower 6eca802ddd Merge pull request #47 from yfl520/feat/smbios-rotate
feat(opencore,ui): 新增 OpenCore 设备身份 (SMBIOS) 一键换码功能
2026-12-01 04:26:03 -07:00

448 lines
12 KiB
Go

package opencore
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"math/big"
"strings"
)
// SMBIOSIdentity holds the Mac identity fields stored in OpenCore's
// PlatformInfo > Generic dictionary. ROM is populated on read for reference and
// preserved untouched when patching so it stays aligned with the VM's NIC MAC.
type SMBIOSIdentity struct {
Model string `json:"model"`
Serial string `json:"serial"`
MLB string `json:"mlb"`
UUID string `json:"uuid"`
ROM string `json:"rom,omitempty"`
}
type smbiosModelSpec struct {
name string
location string
years []int
modelCode string
boardCode string
}
var smbiosModels = []smbiosModelSpec{
{
name: "iMac20,1",
location: "C02",
years: []int{2020, 2021, 2022},
modelCode: "PN5T",
boardCode: "PHC1",
},
{
name: "iMacPro1,1",
location: "C02",
years: []int{2017, 2018, 2019, 2020, 2021},
modelCode: "HX87",
boardCode: "JG36",
},
}
const (
smbiosBase34 = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"
smbiosYearCodes = "CDFGHJKLMNPQRSTVWXYZ"
smbiosWeekCodes = "0123456789CDFGHJKLMNPQRTVWX123456789CDFGHJKLMNPQRTVWXY"
smbiosWeekLookup = "123456789CDFGHJKLMNPQRSTVWXYZ"
smbiosSecondHalf = "DGJLNQSVXZ"
smbiosLineReprMx = 1155
smbiosLineMax = 3399
)
var (
mlbBlock1 = []string{
"200", "600", "403", "404", "405", "303", "108", "207", "609", "501", "306", "102", "701",
"301", "501", "101", "300", "130", "100", "270", "310", "902", "104", "401", "902", "500",
"700", "802",
}
mlbBlock2 = []string{"GU", "4N", "J9", "QX", "OP", "CD", "GU"}
mlbBlock3 = []string{"1H", "1M", "AD", "1F", "A8", "UE", "JA", "JC", "8C", "CB", "FB"}
)
func lookupSMBIOSModel(name string) smbiosModelSpec {
trimmed := strings.TrimSpace(name)
for _, m := range smbiosModels {
if strings.EqualFold(m.name, trimmed) {
return m
}
}
return smbiosModels[0]
}
func cryptoRandInt(max int) (int, error) {
if max <= 1 {
return 0, nil
}
n, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err != nil {
return 0, err
}
return int(n.Int64()), nil
}
func formatAppleSerial(m smbiosModelSpec, year, week, line int) (string, error) {
if year < 2010 || year > 2030 {
return "", fmt.Errorf("year %d out of range", year)
}
if week < 1 || week > 53 {
return "", fmt.Errorf("week %d out of range", week)
}
if line < 0 || line > smbiosLineMax {
return "", fmt.Errorf("line %d out of range", line)
}
base := 2010
if year >= 2020 {
base = 2020
}
half := 0
if week >= 27 {
half = 1
}
yearCode := smbiosYearCodes[(year-base)*2+half]
weekCode := smbiosWeekCodes[week]
rmin := 0
if line > smbiosLineReprMx {
rmin = (line - smbiosLineReprMx + 67) / 68
}
rest := line - rmin*68
var b strings.Builder
b.Grow(12)
b.WriteString(m.location)
b.WriteByte(yearCode)
b.WriteByte(weekCode)
b.WriteByte(smbiosBase34[rmin])
b.WriteByte(smbiosBase34[rest/34])
b.WriteByte(smbiosBase34[rest%34])
b.WriteString(m.modelCode)
return b.String(), nil
}
// MLBChecksumOK verifies the 17-character Apple MLB base-34 weighted checksum.
func MLBChecksumOK(mlb string) bool {
if len(mlb) == 0 {
return false
}
n := len(mlb)
sum := 0
for i := 0; i < n; i++ {
v := strings.IndexByte(smbiosBase34, mlb[i])
if v < 0 {
return false
}
weight := 1
if (i & 1) == (n & 1) {
weight = 3
}
sum += weight * v
}
return sum%34 == 0
}
func generateMLBForSerial(m smbiosModelSpec, serial string) (string, error) {
if len(serial) != 12 {
return "", fmt.Errorf("12-character serial required for MLB")
}
yearCode := serial[3]
weekCode := serial[4]
year := 0
if idx := strings.IndexByte(smbiosYearCodes, yearCode); idx >= 0 {
year = idx / 2
}
week := 0
if strings.IndexByte(smbiosSecondHalf, yearCode) >= 0 {
week = 27
}
if idx := strings.IndexByte(smbiosWeekLookup, weekCode); idx >= 0 {
week += idx + 1
}
if week < 1 {
return "", fmt.Errorf("serial has no valid week")
}
week--
if week == 0 {
week = 53
if year == 0 {
year = 9
} else {
year--
}
}
for attempt := 0; attempt < 100000; attempt++ {
i1, err := cryptoRandInt(len(mlbBlock1))
if err != nil {
return "", err
}
i2, err := cryptoRandInt(len(mlbBlock2))
if err != nil {
return "", err
}
i3, err := cryptoRandInt(len(mlbBlock3))
if err != nil {
return "", err
}
cand := fmt.Sprintf("%s%d%02d%s%s%s%s",
m.location, year, week, mlbBlock1[i1], mlbBlock2[i2], m.boardCode, mlbBlock3[i3],
)
if MLBChecksumOK(cand) {
return cand, nil
}
}
return "", errors.New("could not generate MLB with valid checksum")
}
func generateUUIDv4() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
h := strings.ToUpper(hex.EncodeToString(b[:]))
return fmt.Sprintf("%s-%s-%s-%s-%s", h[0:8], h[8:12], h[12:16], h[16:20], h[20:32]), nil
}
// GenerateSMBIOS produces a fresh, cryptographically random SMBIOS identity
// (SystemSerialNumber, matching checksummed MLB, and UUID v4) for model
// ("iMac20,1" or "iMacPro1,1"; defaults to "iMac20,1").
func GenerateSMBIOS(model string) (SMBIOSIdentity, error) {
m := lookupSMBIOSModel(model)
yi, err := cryptoRandInt(len(m.years))
if err != nil {
return SMBIOSIdentity{}, err
}
wi, err := cryptoRandInt(52)
if err != nil {
return SMBIOSIdentity{}, err
}
li, err := cryptoRandInt(smbiosLineMax + 1)
if err != nil {
return SMBIOSIdentity{}, err
}
serial, err := formatAppleSerial(m, m.years[yi], 1+wi, li)
if err != nil {
return SMBIOSIdentity{}, err
}
mlb, err := generateMLBForSerial(m, serial)
if err != nil {
return SMBIOSIdentity{}, err
}
uuid, err := generateUUIDv4()
if err != nil {
return SMBIOSIdentity{}, err
}
return SMBIOSIdentity{
Model: m.name,
Serial: serial,
MLB: mlb,
UUID: uuid,
}, nil
}
// NormalizeAndValidateSMBIOS trims, uppercases, and validates user-supplied
// SMBIOS fields before writing them into OpenCore's config.plist.
func NormalizeAndValidateSMBIOS(in SMBIOSIdentity) (SMBIOSIdentity, error) {
out := SMBIOSIdentity{
Model: strings.TrimSpace(in.Model),
Serial: strings.ToUpper(strings.TrimSpace(in.Serial)),
MLB: strings.ToUpper(strings.TrimSpace(in.MLB)),
}
if len(out.Serial) != 12 || !isASCIIAlphaNum(out.Serial) {
return SMBIOSIdentity{}, fmt.Errorf("serial number must be 12 alphanumeric characters")
}
if (len(out.MLB) != 17 && len(out.MLB) != 13) || !isASCIIAlphaNum(out.MLB) {
return SMBIOSIdentity{}, fmt.Errorf("MLB must be 13 or 17 alphanumeric characters")
}
rawUUID := strings.ReplaceAll(strings.TrimSpace(in.UUID), "-", "")
if len(rawUUID) != 32 || !isASCIIHex(rawUUID) {
return SMBIOSIdentity{}, fmt.Errorf("SystemUUID must be a valid 32-hex UUID")
}
h := strings.ToUpper(rawUUID)
out.UUID = fmt.Sprintf("%s-%s-%s-%s-%s", h[0:8], h[8:12], h[12:16], h[16:20], h[20:32])
if out.Model != "" && strings.ContainsAny(out.Model, "<>&\"'\r\n\t ") {
return SMBIOSIdentity{}, fmt.Errorf("invalid Mac model %q", out.Model)
}
return out, nil
}
func isASCIIAlphaNum(s string) bool {
for i := 0; i < len(s); i++ {
c := s[i]
if !((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
return false
}
}
return true
}
func isASCIIHex(s string) bool {
for i := 0; i < len(s); i++ {
c := s[i]
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
return false
}
}
return true
}
func findPlatformGenericDict(root *xmlElem) *xmlElem {
top := findRootDict(root)
_, pi := dictLookup(top, "PlatformInfo")
_, gen := dictLookup(pi, "Generic")
if gen != nil && gen.name == "dict" {
return gen
}
return nil
}
// ReadSMBIOS reads PlatformInfo > Generic identity fields from an OpenCore
// XML config.plist.
func ReadSMBIOS(src []byte) (SMBIOSIdentity, bool) {
root, err := parsePlistTree(src)
if err != nil {
return SMBIOSIdentity{}, false
}
gen := findPlatformGenericDict(root)
if gen == nil {
return SMBIOSIdentity{}, false
}
var id SMBIOSIdentity
if _, v := dictLookup(gen, "SystemProductName"); v != nil && v.name == "string" {
id.Model = strings.TrimSpace(v.text)
}
if _, v := dictLookup(gen, "SystemSerialNumber"); v != nil && v.name == "string" {
id.Serial = strings.TrimSpace(v.text)
}
if _, v := dictLookup(gen, "MLB"); v != nil && v.name == "string" {
id.MLB = strings.TrimSpace(v.text)
}
if _, v := dictLookup(gen, "SystemUUID"); v != nil && v.name == "string" {
id.UUID = strings.TrimSpace(v.text)
}
if _, v := dictLookup(gen, "ROM"); v != nil && v.name == "data" {
cleaned := strings.Join(strings.Fields(v.text), "")
if raw, decErr := base64.StdEncoding.DecodeString(cleaned); decErr == nil && len(raw) == 6 {
id.ROM = fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X",
raw[0], raw[1], raw[2], raw[3], raw[4], raw[5])
}
}
ok := id.Serial != "" || id.MLB != "" || id.UUID != "" || id.Model != ""
return id, ok
}
// PatchSMBIOS returns a modified copy of an OpenCore XML config.plist with
// PlatformInfo > Generic > SystemSerialNumber, MLB, SystemUUID (and optionally
// SystemProductName if non-empty) replaced in place. ROM and all other keys
// are preserved byte-for-byte.
func PatchSMBIOS(src []byte, in SMBIOSIdentity) ([]byte, error) {
id, err := NormalizeAndValidateSMBIOS(in)
if err != nil {
return nil, err
}
root, err := parsePlistTree(src)
if err != nil {
return nil, err
}
gen := findPlatformGenericDict(root)
if gen == nil {
return nil, errors.New("config.plist missing PlatformInfo > Generic")
}
updates := []struct {
key string
val string
}{
{"SystemSerialNumber", id.Serial},
{"MLB", id.MLB},
{"SystemUUID", id.UUID},
}
if id.Model != "" {
updates = append(updates, struct {
key string
val string
}{"SystemProductName", id.Model})
}
var patches []bytePatch
nl := "\n"
if bytes.Contains(src, []byte("\r\n")) {
nl = "\r\n"
}
var inserts strings.Builder
closeIndent := lineIndent(src, gen.contentEnd)
entryIndent := closeIndent + "\t"
if len(gen.children) > 0 {
entryIndent = lineIndent(src, gen.children[0].start)
}
for _, u := range updates {
if keyEl, valEl := dictLookup(gen, u.key); keyEl != nil && valEl != nil {
repl := fmt.Sprintf("<string>%s</string>", u.val)
patches = append(patches, bytePatch{start: valEl.start, end: valEl.end, repl: []byte(repl)})
} else {
fmt.Fprintf(&inserts, "%s<key>%s</key>%s%s<string>%s</string>%s",
entryIndent, u.key, nl, entryIndent, u.val, nl)
}
}
if inserts.Len() > 0 {
insertPos := gen.contentEnd
for insertPos > gen.contentStart && (src[insertPos-1] == ' ' || src[insertPos-1] == '\t') {
insertPos--
}
patches = append(patches, bytePatch{
start: insertPos,
end: gen.contentEnd,
repl: []byte(inserts.String() + closeIndent),
})
}
return applyBytePatches(src, patches), nil
}
// ReadImageSMBIOS reads PlatformInfo > Generic SMBIOS identity from an OpenCore
// disk image (opencore.qcow2 or raw).
func ReadImageSMBIOS(imagePath string) (SMBIOSIdentity, error) {
cfg, err := ReadConfigPlist(imagePath)
if err != nil {
return SMBIOSIdentity{}, err
}
id, ok := ReadSMBIOS(cfg)
if !ok {
return SMBIOSIdentity{}, errors.New("config.plist does not contain PlatformInfo > Generic SMBIOS")
}
return id, nil
}
// PatchImageSMBIOS updates PlatformInfo > Generic (SystemSerialNumber, MLB,
// SystemUUID, and optional SystemProductName) inside imagePath while keeping
// ROM, kexts, and NVRAM intact.
func PatchImageSMBIOS(ctx context.Context, imagePath string, id SMBIOSIdentity, qemuImgPath string, env []string) (bool, error) {
norm, err := NormalizeAndValidateSMBIOS(id)
if err != nil {
return false, err
}
return patchImageConfigPlist(ctx, imagePath, qemuImgPath, env, func(orig []byte) ([]byte, bool, error) {
if cur, ok := ReadSMBIOS(orig); ok {
sameModel := norm.Model == "" || cur.Model == norm.Model
if sameModel && cur.Serial == norm.Serial && cur.MLB == norm.MLB && cur.UUID == norm.UUID {
return nil, false, nil
}
}
patched, err := PatchSMBIOS(orig, norm)
if err != nil {
return nil, false, err
}
return patched, true, nil
})
}