| 1 | package guestos |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | |
| 12 | "golang.org/x/crypto/ssh" |
| 13 | ) |
| 14 | |
| 15 | |
| 16 | |
| 17 | func MacOSInstallHostKey(profile string) ([]byte, error) { |
| 18 | path := filepath.Join(profile, "state", "lima", "mac", "serialv.log") |
| 19 | info, err := os.Lstat(path) |
| 20 | if err != nil { |
| 21 | return nil, err |
| 22 | } |
| 23 | if !info.Mode().IsRegular() || info.Size() > 8<<20 { |
| 24 | return nil, errors.New("无效的 macOS 客机首次启动串口记录") |
| 25 | } |
| 26 | file, err := os.Open(path) |
| 27 | if err != nil { |
| 28 | return nil, err |
| 29 | } |
| 30 | defer file.Close() |
| 31 | return parseInstallHostKey(io.LimitReader(file, info.Size())) |
| 32 | } |
| 33 | |
| 34 | func parseInstallHostKey(input io.Reader) ([]byte, error) { |
| 35 | const prefix = "CAGE-GUEST-HOST-KEY " |
| 36 | scanner := bufio.NewScanner(input) |
| 37 | var found []byte |
| 38 | for scanner.Scan() { |
| 39 | line := strings.TrimSuffix(scanner.Text(), "\r") |
| 40 | keyLine, ok := strings.CutPrefix(line, prefix) |
| 41 | if !ok { |
| 42 | continue |
| 43 | } |
| 44 | key, _, opts, rest, err := ssh.ParseAuthorizedKey([]byte(keyLine)) |
| 45 | if err != nil || key.Type() != ssh.KeyAlgoED25519 || len(opts) != 0 || len(rest) != 0 { |
| 46 | return nil, errors.New("虚拟 Mac 首次启动返回了无效的主机公钥") |
| 47 | } |
| 48 | candidate := ssh.MarshalAuthorizedKey(key) |
| 49 | if found != nil && !bytes.Equal(found, candidate) { |
| 50 | return nil, errors.New("虚拟 Mac 首次启动返回了不同的主机公钥") |
| 51 | } |
| 52 | found = candidate |
| 53 | } |
| 54 | if err := scanner.Err(); err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | if found == nil { |
| 58 | return nil, errors.New("尚未从这台虚拟 Mac 的串口取得主机公钥") |
| 59 | } |
| 60 | return found, nil |
| 61 | } |