| 1 | package guestos |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "github.com/google/uuid" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "regexp" |
| 14 | |
| 15 | "golang.org/x/crypto/ssh" |
| 16 | ) |
| 17 | |
| 18 | |
| 19 | type MacOSProfile struct { |
| 20 | Version int `json:"version"` |
| 21 | Instance string `json:"instance"` |
| 22 | User string `json:"user"` |
| 23 | MachineID string `json:"machineID"` |
| 24 | SetupID string `json:"initial_setup,omitempty"` |
| 25 | } |
| 26 | |
| 27 | var macUser = regexp.MustCompile(`^[a-z][a-z0-9_]{0,30}$`) |
| 28 | |
| 29 | |
| 30 | func ValidMacOSAccountName(name string) bool { |
| 31 | if !macUser.MatchString(name) { |
| 32 | return false |
| 33 | } |
| 34 | switch name { |
| 35 | case "root", "daemon", "nobody", "guest", "cageprovision", "cagesetup": |
| 36 | return false |
| 37 | } |
| 38 | return true |
| 39 | } |
| 40 | |
| 41 | func macMachineID(profile string) (string, error) { |
| 42 | path := filepath.Join(profile, "state", "lima", "mac", "vz-identifier") |
| 43 | info, err := os.Lstat(path) |
| 44 | if err != nil { |
| 45 | return "", err |
| 46 | } |
| 47 | if !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > 4096 { |
| 48 | return "", errors.New("invalid Apple virtual machine identifier") |
| 49 | } |
| 50 | data, err := os.ReadFile(path) |
| 51 | if err != nil { |
| 52 | return "", err |
| 53 | } |
| 54 | sum := sha256.Sum256(data) |
| 55 | return hex.EncodeToString(sum[:]), nil |
| 56 | } |
| 57 | |
| 58 | func LoadMacOSProfile(profile string) (*MacOSProfile, error) { |
| 59 | path := filepath.Join(profile, "macos-guest.json") |
| 60 | info, err := os.Lstat(path) |
| 61 | if errors.Is(err, os.ErrNotExist) { |
| 62 | return nil, nil |
| 63 | } |
| 64 | if err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | if !info.Mode().IsRegular() || info.Size() > 4096 { |
| 68 | return nil, errors.New("invalid macOS guest profile") |
| 69 | } |
| 70 | data, err := os.ReadFile(path) |
| 71 | if err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | var m MacOSProfile |
| 75 | if err := json.Unmarshal(data, &m); err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | if m.Version != 1 || m.Instance != "mac" || !macUser.MatchString(m.User) || m.User == "root" { |
| 79 | return nil, errors.New("invalid macOS guest profile or login") |
| 80 | } |
| 81 | if m.SetupID != "" && !validSetupID(m.SetupID) { |
| 82 | return nil, errors.New("invalid first setup identity") |
| 83 | } |
| 84 | id, err := macMachineID(profile) |
| 85 | if err != nil { |
| 86 | return nil, err |
| 87 | } |
| 88 | if id != m.MachineID { |
| 89 | return nil, errors.New("the macOS guest differs from the machine bound to this profile") |
| 90 | } |
| 91 | return &m, nil |
| 92 | } |
| 93 | |
| 94 | |
| 95 | |
| 96 | func BindMacOSProfile(profile, user string, hostKey []byte) error { |
| 97 | return bindMacOSProfile(profile, user, hostKey, "") |
| 98 | } |
| 99 | |
| 100 | |
| 101 | func BindNewMacOSProfile(profile, user string, hostKey []byte, id uuid.UUID) error { |
| 102 | install, err := LoadInstallation(profile) |
| 103 | if err != nil { |
| 104 | return err |
| 105 | } |
| 106 | if install == nil || id == uuid.Nil || install.ID != id || install.System != MacOS { |
| 107 | return errors.New("首次设置与当前安装记录不匹配") |
| 108 | } |
| 109 | return bindMacOSProfile(profile, user, hostKey, id.String()) |
| 110 | } |
| 111 | |
| 112 | func validSetupID(id string) bool { |
| 113 | value, err := uuid.Parse(id) |
| 114 | return err == nil && value != uuid.Nil && value.String() == id |
| 115 | } |
| 116 | |
| 117 | func bindMacOSProfile(profile, user string, hostKey []byte, setupID string) error { |
| 118 | if !macUser.MatchString(user) || user == "root" { |
| 119 | return errors.New("supply the short name of the ordinary macOS guest account") |
| 120 | } |
| 121 | key, _, options, rest, err := ssh.ParseAuthorizedKey(hostKey) |
| 122 | if err != nil || len(options) != 0 || len(bytes.TrimSpace(rest)) != 0 || key.Type() != ssh.KeyAlgoED25519 { |
| 123 | return errors.New("expected one Ed25519 guest SSH host public key") |
| 124 | } |
| 125 | id, err := macMachineID(profile) |
| 126 | if err != nil { |
| 127 | return err |
| 128 | } |
| 129 | m := MacOSProfile{Version: 1, Instance: "mac", User: user, MachineID: id, SetupID: setupID} |
| 130 | data, err := json.Marshal(m) |
| 131 | if err != nil { |
| 132 | return err |
| 133 | } |
| 134 | if current, err := LoadMacOSProfile(profile); err != nil { |
| 135 | return err |
| 136 | } else if current != nil && *current != m { |
| 137 | return errors.New("this profile is already bound to another macOS guest account") |
| 138 | } |
| 139 | if err := publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), ssh.MarshalAuthorizedKey(key)...)); err != nil { |
| 140 | return err |
| 141 | } |
| 142 | return publishBinding(profile, "macos-guest.json", append(data, '\n')) |
| 143 | } |
| 144 | |
| 145 | func publishBinding(profile, name string, data []byte) error { |
| 146 | temp, err := os.CreateTemp(profile, ".guest-binding-*") |
| 147 | if err != nil { |
| 148 | return err |
| 149 | } |
| 150 | defer os.Remove(temp.Name()) |
| 151 | _, writeErr := temp.Write(data) |
| 152 | if err := errors.Join(writeErr, temp.Close()); err != nil { |
| 153 | return err |
| 154 | } |
| 155 | path := filepath.Join(profile, name) |
| 156 | if err := os.Link(temp.Name(), path); !errors.Is(err, os.ErrExist) { |
| 157 | return err |
| 158 | } |
| 159 | info, err := os.Lstat(path) |
| 160 | if err != nil || !info.Mode().IsRegular() || info.Size() != int64(len(data)) { |
| 161 | return fmt.Errorf("unexpected existing %s", name) |
| 162 | } |
| 163 | prior, err := os.ReadFile(path) |
| 164 | if err != nil || !bytes.Equal(data, prior) { |
| 165 | return fmt.Errorf("refusing to replace existing %s", name) |
| 166 | } |
| 167 | return nil |
| 168 | } |
| 169 | |
| 170 | |
| 171 | func PinMacOSInstallHostKey(profile string) error { |
| 172 | key, err := MacOSInstallHostKey(profile) |
| 173 | if err != nil { |
| 174 | return err |
| 175 | } |
| 176 | return publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), key...)) |
| 177 | } |
| 178 | |
| 179 | |
| 180 | |
| 181 | func FinishMacOSSetup(profile, setupID string) error { |
| 182 | bound, err := LoadMacOSProfile(profile) |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | if bound == nil || !validSetupID(setupID) || bound.SetupID != setupID { |
| 187 | return errors.New("首次设置已关闭或安装实例已变更") |
| 188 | } |
| 189 | bound.SetupID = "" |
| 190 | data, err := json.Marshal(bound) |
| 191 | if err != nil { |
| 192 | return err |
| 193 | } |
| 194 | f, err := os.CreateTemp(profile, ".finish-guest-setup-*") |
| 195 | if err != nil { |
| 196 | return err |
| 197 | } |
| 198 | defer os.Remove(f.Name()) |
| 199 | _, writeErr := f.Write(append(data, '\n')) |
| 200 | if err = errors.Join(writeErr, f.Sync(), f.Close()); err != nil { |
| 201 | return err |
| 202 | } |
| 203 | if err = os.Rename(f.Name(), filepath.Join(profile, "macos-guest.json")); err != nil { |
| 204 | return err |
| 205 | } |
| 206 | dir, err := os.Open(profile) |
| 207 | if err != nil { |
| 208 | return err |
| 209 | } |
| 210 | defer dir.Close() |
| 211 | return dir.Sync() |
| 212 | } |