| 1 | |
| 2 | |
| 3 | package maclogin |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | import "C" |
| 9 | |
| 10 | import ( |
| 11 | "bufio" |
| 12 | "bytes" |
| 13 | "context" |
| 14 | "crypto/rand" |
| 15 | "crypto/subtle" |
| 16 | "encoding/json" |
| 17 | "errors" |
| 18 | "io" |
| 19 | "os/exec" |
| 20 | "time" |
| 21 | |
| 22 | "al.essio.dev/pkg/shellescape" |
| 23 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 24 | ) |
| 25 | |
| 26 | func (s *loginSession) maintenanceCommand(ctx context.Context, operation string) (*exec.Cmd, string, error) { |
| 27 | open := operation == "--maintenance-open" |
| 28 | if !guestos.ValidMacMaintenancePurpose(s.maintenance) { |
| 29 | return nil, "", errors.New("维护用途无效") |
| 30 | } |
| 31 | bound, err := guestos.LoadMacOSProfile(s.profile) |
| 32 | if err != nil || bound == nil || bound.SetupID != "" { |
| 33 | return nil, "", errors.New("请先完成虚拟 Mac 的首次设置") |
| 34 | } |
| 35 | if open { |
| 36 | s.maintenanceMachineID = bound.MachineID |
| 37 | } else if s.maintenanceMachineID != bound.MachineID { |
| 38 | return nil, "", errors.New("虚拟 Mac 身份已变化,请重新打开维护画面") |
| 39 | } |
| 40 | user, err := guestos.MacOSProvisionUser(s.profile) |
| 41 | if err != nil { |
| 42 | return nil, "", err |
| 43 | } |
| 44 | if open { |
| 45 | s.maintenanceAdministrator = user |
| 46 | } else if s.maintenanceAdministrator != user { |
| 47 | return nil, "", errors.New("客机安装身份已变化,请重新打开维护画面") |
| 48 | } |
| 49 | cmd, err := guestGUIProbeCommand(ctx, s.profile, user, bound.User, operation, s.maintenance) |
| 50 | return cmd, bound.User, err |
| 51 | } |
| 52 | |
| 53 | func (s *loginSession) maintenanceProbe(open bool) (maintenanceWindow, error) { |
| 54 | var result maintenanceWindow |
| 55 | operation := "--maintenance-probe" |
| 56 | if open { |
| 57 | operation = "--maintenance-open" |
| 58 | } |
| 59 | ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) |
| 60 | defer cancel() |
| 61 | cmd, user, err := s.maintenanceCommand(ctx, operation) |
| 62 | if err != nil { |
| 63 | return result, err |
| 64 | } |
| 65 | pipe, err := cmd.StdoutPipe() |
| 66 | if err != nil || cmd.Start() != nil { |
| 67 | result.Error = "component_update_required" |
| 68 | return result, errors.New("客机维护组件尚未连接,请更新环境组件后重试") |
| 69 | } |
| 70 | data, readErr := io.ReadAll(io.LimitReader(pipe, 8193)) |
| 71 | if readErr != nil || len(data) > 8192 { |
| 72 | cancel() |
| 73 | } |
| 74 | if err = cmd.Wait(); err != nil { |
| 75 | var exit *exec.ExitError |
| 76 | if errors.As(err, &exit) && exit.ExitCode() == 73 { |
| 77 | result.Error = "requires_gui_login" |
| 78 | return result, errors.New("请先登录并解锁虚拟 Mac 的客机账户") |
| 79 | } |
| 80 | result.Error = "component_update_required" |
| 81 | return result, errors.New("客机维护组件需要更新,请在环境设置中更新组件") |
| 82 | } |
| 83 | if readErr != nil || len(data) > 8192 || json.Unmarshal(data, &result) != nil { |
| 84 | result.Error = "component_update_required" |
| 85 | return result, errors.New("客机维护组件需要更新,请在环境设置中更新组件") |
| 86 | } |
| 87 | if result.Error != "" { |
| 88 | return result, errors.New(result.probeMessage()) |
| 89 | } |
| 90 | if !open && !result.valid(user) { |
| 91 | return result, errors.New("客机授权窗口身份无法确认,请重新打开维护画面") |
| 92 | } |
| 93 | return result, nil |
| 94 | } |
| 95 | |
| 96 | func maintenanceFailure(surface maintenanceWindow, err error, closed bool) reply { |
| 97 | result := reply{Closed: closed, Error: err.Error()} |
| 98 | if surface.Error == "component_update_required" { |
| 99 | result.Recovery = "environment-update" |
| 100 | } else if surface.Error == "requires_gui_login" { |
| 101 | result.Recovery = "guest-login" |
| 102 | } |
| 103 | return result |
| 104 | } |
| 105 | |
| 106 | func (s *loginSession) handleMaintenance(in request) (result reply) { |
| 107 | defer func() { result.MaintenanceVersion = 1 }() |
| 108 | if in.Setup || !guestos.ValidMacMaintenancePurpose(in.Maintenance) || len(in.Geometry) > 64 { |
| 109 | return reply{Closed: true, Error: "维护用途无效"} |
| 110 | } |
| 111 | if in.Action == "open" { |
| 112 | s.close() |
| 113 | s.maintenance = in.Maintenance |
| 114 | surface, err := s.maintenanceProbe(true) |
| 115 | if err != nil { |
| 116 | s.close() |
| 117 | return maintenanceFailure(surface, err, true) |
| 118 | } |
| 119 | deadline := time.Now().Add(3 * time.Second) |
| 120 | for { |
| 121 | surface, err = s.maintenanceProbe(false) |
| 122 | if err == nil || time.Now().After(deadline) { |
| 123 | break |
| 124 | } |
| 125 | time.Sleep(100 * time.Millisecond) |
| 126 | } |
| 127 | if err != nil { |
| 128 | s.close() |
| 129 | return maintenanceFailure(surface, err, true) |
| 130 | } |
| 131 | s.token, s.screenID = rand.Text(), "maintenance-"+surface.Session |
| 132 | s.expires = time.Now().Add(5 * time.Minute) |
| 133 | C.cageLoginEnable(true) |
| 134 | return reply{Session: s.token, Administrator: s.maintenanceAdministrator} |
| 135 | } |
| 136 | if s.token == "" || s.maintenance != in.Maintenance || subtle.ConstantTimeCompare([]byte(in.Session), []byte(s.token)) != 1 { |
| 137 | return reply{Closed: true} |
| 138 | } |
| 139 | if in.Action == "close" || time.Now().After(s.expires) { |
| 140 | s.close() |
| 141 | return reply{Closed: true} |
| 142 | } |
| 143 | surface, err := s.maintenanceProbe(false) |
| 144 | if err != nil || s.screenID != "maintenance-"+surface.Session { |
| 145 | s.close() |
| 146 | if err == nil { |
| 147 | err = errors.New("客机登录会话已变化,请重新打开维护画面") |
| 148 | } |
| 149 | return maintenanceFailure(surface, err, true) |
| 150 | } |
| 151 | if in.Action == "frame" { |
| 152 | region := surface.region() |
| 153 | var size C.int |
| 154 | data := C.cageLoginImageRegion(C.int(region[0]), C.int(region[1]), C.int(region[2]), C.int(region[3]), &size) |
| 155 | if data == nil { |
| 156 | return reply{Error: "正在等待系统设置窗口画面"} |
| 157 | } |
| 158 | defer C.free(data) |
| 159 | after, err := s.maintenanceProbe(false) |
| 160 | if err != nil { |
| 161 | s.close() |
| 162 | return maintenanceFailure(after, err, true) |
| 163 | } |
| 164 | if after != surface { |
| 165 | return reply{Error: "授权窗口已变化,正在刷新画面"} |
| 166 | } |
| 167 | s.maintenanceFrame = surface.geometry() |
| 168 | return reply{Image: C.GoBytes(data, size), MIME: "image/jpeg", Geometry: s.maintenanceFrame, Region: region[:]} |
| 169 | } |
| 170 | if in.Geometry == "" || in.Geometry != s.maintenanceFrame || in.Geometry != surface.geometry() { |
| 171 | return reply{Error: "授权窗口已变化,请等待新画面后重试"} |
| 172 | } |
| 173 | switch in.Action { |
| 174 | case "fill-password": |
| 175 | if err := s.fillMaintenancePassword(surface); err != nil { |
| 176 | return reply{Closed: s.token == "", Error: err.Error()} |
| 177 | } |
| 178 | case "select-all": |
| 179 | s.passwordSelection = passwordSelection{} |
| 180 | if !bool(C.cageLoginSelectAll()) { |
| 181 | return reply{Error: "授权窗口尚未准备好"} |
| 182 | } |
| 183 | case "click": |
| 184 | s.passwordSelection = passwordSelection{} |
| 185 | if !surface.contains(in.X, in.Y) || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) { |
| 186 | return reply{Error: "点击位置超出当前授权窗口"} |
| 187 | } |
| 188 | if probe, err := s.openMaintenancePasswordProbe(); err == nil { |
| 189 | target, err := probe.target() |
| 190 | if err == nil { |
| 191 | s.passwordSelection.selectMaintenance(surface, target, probe.user, in.X, in.Y, time.Now()) |
| 192 | } |
| 193 | probe.close() |
| 194 | } |
| 195 | case "key": |
| 196 | s.passwordSelection = passwordSelection{} |
| 197 | navigation := in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121 |
| 198 | if in.Code < 0 || (in.Code > 53 && !navigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) { |
| 199 | return reply{Error: "此按键不能用于授权窗口"} |
| 200 | } |
| 201 | case "scroll": |
| 202 | s.passwordSelection = passwordSelection{} |
| 203 | if !surface.contains(in.X, in.Y) || in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 || |
| 204 | !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) { |
| 205 | return reply{Error: "滚动位置超出当前授权窗口"} |
| 206 | } |
| 207 | default: |
| 208 | return reply{Error: "维护操作无效"} |
| 209 | } |
| 210 | return reply{} |
| 211 | } |
| 212 | |
| 213 | func (s *loginSession) openMaintenancePasswordProbe() (*passwordProbe, error) { |
| 214 | ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second) |
| 215 | command, user, err := s.maintenanceCommand(ctx, "--maintenance-password-probe") |
| 216 | if err != nil { |
| 217 | cancel() |
| 218 | return nil, err |
| 219 | } |
| 220 | input, err := command.StdinPipe() |
| 221 | if err != nil { |
| 222 | cancel() |
| 223 | return nil, err |
| 224 | } |
| 225 | output, err := command.StdoutPipe() |
| 226 | if err != nil { |
| 227 | input.Close() |
| 228 | cancel() |
| 229 | return nil, err |
| 230 | } |
| 231 | if err = command.Start(); err != nil { |
| 232 | input.Close() |
| 233 | output.Close() |
| 234 | cancel() |
| 235 | return nil, err |
| 236 | } |
| 237 | scanner := bufio.NewScanner(output) |
| 238 | scanner.Buffer(make([]byte, 4096), 32<<10) |
| 239 | return &passwordProbe{command: command, input: input, output: output, scanner: scanner, cancel: cancel, user: user}, nil |
| 240 | } |
| 241 | |
| 242 | func (s *loginSession) fillMaintenancePassword(window maintenanceWindow) error { |
| 243 | selected := s.passwordSelection |
| 244 | s.passwordSelection = passwordSelection{} |
| 245 | probe, err := s.openMaintenancePasswordProbe() |
| 246 | if err != nil { |
| 247 | return err |
| 248 | } |
| 249 | defer probe.close() |
| 250 | target, err := probe.target() |
| 251 | if err != nil { |
| 252 | return err |
| 253 | } |
| 254 | selection, permitted := selected.consumeMaintenance(window, target, probe.user, time.Now()) |
| 255 | if !permitted { |
| 256 | return errors.New("请先选中系统授权窗口的密码框,再点击填写管理员密码") |
| 257 | } |
| 258 | password, err := s.maintenancePassword() |
| 259 | if err != nil { |
| 260 | return err |
| 261 | } |
| 262 | defer func() { clear(password) }() |
| 263 | sequence, valid := passwordKeys(string(bytes.TrimRight(password, "\r\n"))) |
| 264 | if !valid { |
| 265 | return errors.New("安装管理员凭据格式无效,请检查安装记录") |
| 266 | } |
| 267 | check := func() error { |
| 268 | current, err := probe.target() |
| 269 | if err != nil { |
| 270 | return err |
| 271 | } |
| 272 | if time.Now().After(s.expires) || s.screenID != "maintenance-"+current.Session { |
| 273 | s.close() |
| 274 | return errors.New("客机授权会话已结束,请重新打开维护画面") |
| 275 | } |
| 276 | if !window.permitsPassword(current, selection, probe.user, time.Now()) { |
| 277 | return errors.New("系统授权窗口或密码框已变化,填写已停止,请重新选中密码框") |
| 278 | } |
| 279 | return nil |
| 280 | } |
| 281 | if err = check(); err != nil { |
| 282 | return err |
| 283 | } |
| 284 | if !target.Accessibility && !bool(C.cageLoginClick(C.int(selection.X), C.int(selection.Y))) { |
| 285 | return errors.New("所选密码框已变化,请重新点选") |
| 286 | } |
| 287 | if err = check(); err != nil { |
| 288 | return err |
| 289 | } |
| 290 | if !bool(C.cageLoginSelectAll()) { |
| 291 | return errors.New("系统密码框尚未准备好,请重试") |
| 292 | } |
| 293 | for _, key := range sequence { |
| 294 | if err = check(); err != nil { |
| 295 | return err |
| 296 | } |
| 297 | if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) { |
| 298 | return errors.New("管理员密码未能填写,请重新选中密码框后重试") |
| 299 | } |
| 300 | } |
| 301 | return nil |
| 302 | } |
| 303 | |
| 304 | func (s *loginSession) maintenancePassword() ([]byte, error) { |
| 305 | user, err := guestos.MacOSProvisionUser(s.profile) |
| 306 | if err != nil || user != s.maintenanceAdministrator { |
| 307 | return nil, errors.New("客机安装身份已变化,请重新打开维护画面") |
| 308 | } |
| 309 | args, err := guestos.MacOSSSHArgs(s.profile, user) |
| 310 | if err != nil { |
| 311 | return nil, err |
| 312 | } |
| 313 | script := `set -eu; p=` + shellescape.Quote("/Users/"+user+"/password") + ` |
| 314 | test ! -L "$p" && test "$(/usr/bin/stat -f %u "$p")" = "$(/usr/bin/id -u)" |
| 315 | mode=$(/usr/bin/stat -f %Lp "$p"); test "$((0$mode & 077))" = 0 |
| 316 | exec /bin/cat "$p"` |
| 317 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 318 | defer cancel() |
| 319 | cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", "exec /bin/sh -c "+shellescape.Quote(script))...) |
| 320 | cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"} |
| 321 | pipe, err := cmd.StdoutPipe() |
| 322 | if err != nil || cmd.Start() != nil { |
| 323 | return nil, errors.New("安装管理员凭据暂时不可用") |
| 324 | } |
| 325 | data, readErr := io.ReadAll(io.LimitReader(pipe, 1025)) |
| 326 | if readErr != nil || len(data) > 1024 { |
| 327 | cancel() |
| 328 | } |
| 329 | if err = cmd.Wait(); err != nil || readErr != nil || len(data) == 0 || len(data) > 1024 { |
| 330 | clear(data) |
| 331 | return nil, errors.New("安装管理员凭据不可用,请核对安装记录") |
| 332 | } |
| 333 | return data, nil |
| 334 | } |