跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

main_windows.go

222 行 · 7.2 KB历史下载
1//go:build windows
2
3// cage-guest-boot runs only as a guest-local Windows service. Winlogon owns
4// authentication and its LSA secret. This service has no credential, network,
5// screen, keyboard or session-control interface.
6package main
7
8import (
9 "errors"
10 "os"
11 "strings"
12 "syscall"
13 "unsafe"
14
15 "github.com/google/uuid"
16 "golang.org/x/sys/windows"
17 "golang.org/x/sys/windows/registry"
18 "golang.org/x/sys/windows/svc"
19)
20
21const winlogon = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`
22const bootBase = `SOFTWARE\Cage\WorkbenchBoot\`
23
24var (
25 regCreate = windows.NewLazySystemDLL("advapi32.dll").NewProc("RegCreateKeyExW")
26 localGroups = windows.NewLazySystemDLL("netapi32.dll").NewProc("NetUserGetLocalGroups")
27 sessionInfo = windows.NewLazySystemDLL("wtsapi32.dll").NewProc("WTSQuerySessionInformationW")
28)
29
30type bootService struct {
31 vm uuid.UUID
32 user string
33}
34
35func read(key registry.Key, name string) string {
36 value, _, _ := key.GetStringValue(name)
37 return value
38}
39
40func (b bootService) boundSID() (string, error) {
41 vm, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters`, registry.QUERY_VALUE)
42 if err != nil {
43 return "", err
44 }
45 defer vm.Close()
46 id, err := uuid.Parse(read(vm, "VirtualMachineId"))
47 if err != nil || id != b.vm {
48 return "", errors.New("wrong guest")
49 }
50 key, err := registry.OpenKey(registry.LOCAL_MACHINE, bootBase+b.vm.String(), registry.QUERY_VALUE)
51 if err != nil {
52 return "", err
53 }
54 defer key.Close()
55 sid := read(key, "SID")
56 if read(key, "VM") != b.vm.String() || read(key, "User") != b.user || !strings.HasPrefix(sid, "S-1-5-21-") {
57 return "", errors.New("unbound guest user")
58 }
59 return sid, nil
60}
61
62// Require precisely the built-in Users group, including indirect memberships.
63// Never arm an account which was renamed, replaced or made an administrator.
64func (b bootService) standardUser(expected, host string) bool {
65 sid, _, kind, err := windows.LookupSID("", host+`\`+b.user)
66 if err != nil || kind != windows.SidTypeUser || sid.String() != expected {
67 return false
68 }
69 user, err := windows.UTF16PtrFromString(b.user)
70 if err != nil {
71 return false
72 }
73 var buffer *byte
74 var entries, total uint32
75 status, _, _ := localGroups.Call(0, uintptr(unsafe.Pointer(user)), 0, 1, uintptr(unsafe.Pointer(&buffer)), uintptr(0xffffffff), uintptr(unsafe.Pointer(&entries)), uintptr(unsafe.Pointer(&total)))
76 if buffer != nil {
77 defer windows.NetApiBufferFree(buffer)
78 }
79 if status != 0 || entries != 1 || total != 1 || buffer == nil {
80 return false
81 }
82 groupName := windows.UTF16PtrToString(*(**uint16)(unsafe.Pointer(buffer)))
83 groupSID, _, _, err := windows.LookupSID("", groupName)
84 return err == nil && groupSID.IsWellKnown(windows.WinBuiltinUsersSid)
85}
86
87func (b bootService) configure(enable bool) error {
88 expected, err := b.boundSID()
89 if err != nil {
90 return err
91 }
92 key, err := registry.OpenKey(registry.LOCAL_MACHINE, winlogon, registry.QUERY_VALUE|registry.SET_VALUE)
93 if err != nil {
94 return err
95 }
96 defer key.Close()
97 host, err := os.Hostname()
98 if err != nil {
99 return err
100 }
101 if read(key, "AutoAdminLogon") == "1" && (!strings.EqualFold(read(key, "DefaultUserName"), b.user) || !strings.EqualFold(read(key, "DefaultDomainName"), host)) {
102 return errors.New("another logon policy exists")
103 }
104 if !enable {
105 return key.SetStringValue("AutoAdminLogon", "0")
106 }
107 if _, _, err := key.GetValue("DefaultPassword", nil); !errors.Is(err, registry.ErrNotExist) {
108 return errors.New("existing Winlogon password value")
109 }
110 if force := read(key, "ForceAutoLogon"); force != "" && force != "0" {
111 return errors.New("existing forced logon policy")
112 }
113 if !b.standardUser(expected, host) {
114 if strings.EqualFold(read(key, "DefaultUserName"), b.user) {
115 _ = key.SetStringValue("AutoAdminLogon", "0")
116 }
117 return errors.New("ordinary account required")
118 }
119 if err = key.SetStringValue("DefaultUserName", b.user); err != nil {
120 return err
121 }
122 if err = key.SetStringValue("DefaultDomainName", host); err != nil {
123 return err
124 }
125 // Arming is the final write; Winlogon reads the protected password itself.
126 return key.SetStringValue("AutoAdminLogon", "1")
127}
128
129// The volatile key survives a service restart, but not a new boot. A service
130// restart after a manual lock or logoff must never rearm the current boot.
131func (b bootService) bootMarker() (registry.Key, error) {
132 path, _ := windows.UTF16PtrFromString(bootBase + b.vm.String() + `\CurrentBoot`)
133 var key windows.Handle
134 var disposition uint32
135 status, _, _ := regCreate.Call(uintptr(registry.LOCAL_MACHINE), uintptr(unsafe.Pointer(path)), 0, 0, 1, registry.QUERY_VALUE|registry.SET_VALUE, 0, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&disposition)))
136 if status != 0 {
137 return 0, syscall.Errno(status)
138 }
139 return registry.Key(key), nil
140}
141
142func signedIn() (bool, error) {
143 var sessions *windows.WTS_SESSION_INFO
144 var count uint32
145 if err := windows.WTSEnumerateSessions(0, 0, 1, &sessions, &count); err != nil {
146 return false, err
147 }
148 defer windows.WTSFreeMemory(uintptr(unsafe.Pointer(sessions)))
149 if count > 4096 {
150 return false, errors.New("invalid session count")
151 }
152 for _, s := range unsafe.Slice(sessions, count) {
153 if s.SessionID == 0 || s.State == windows.WTSListen || s.State == windows.WTSDown {
154 continue
155 }
156 var user *uint16
157 var size uint32
158 ok, _, err := sessionInfo.Call(0, uintptr(s.SessionID), 5, uintptr(unsafe.Pointer(&user)), uintptr(unsafe.Pointer(&size)))
159 if ok == 0 {
160 return false, err
161 }
162 present := user != nil && size >= 2 && *user != 0
163 windows.WTSFreeMemory(uintptr(unsafe.Pointer(user)))
164 if present {
165 return true, nil
166 }
167 }
168 return false, nil
169}
170
171func (b bootService) Execute(_ []string, requests <-chan svc.ChangeRequest, reports chan<- svc.Status) (bool, uint32) {
172 reports <- svc.Status{State: svc.StartPending}
173 marker, err := b.bootMarker()
174 if err != nil {
175 return false, 1
176 }
177 defer marker.Close()
178 status := svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptSessionChange | svc.AcceptPreShutdown}
179 reports <- status
180 used, _, markerErr := marker.GetIntegerValue("Consumed")
181 hasUser, probeError := signedIn()
182 if hasUser {
183 _ = marker.SetDWordValue("Consumed", 1)
184 }
185 _ = b.configure(used == 0 && (markerErr == nil || errors.Is(markerErr, registry.ErrNotExist)) && !hasUser && probeError == nil)
186 for request := range requests {
187 switch request.Cmd {
188 case svc.Interrogate:
189 reports <- status
190 case svc.SessionChange:
191 switch request.EventType {
192 case windows.WTS_SESSION_LOGON, windows.WTS_SESSION_LOGOFF, windows.WTS_SESSION_LOCK, windows.WTS_SESSION_UNLOCK:
193 _ = marker.SetDWordValue("Consumed", 1)
194 _ = b.configure(false)
195 }
196 case svc.PreShutdown:
197 // The SCM has committed to a real OS shutdown. Prepare the next
198 // boot before the registry hive is unloaded.
199 _ = b.configure(true)
200 reports <- svc.Status{State: svc.StopPending}
201 return false, 0
202 case svc.Stop:
203 _ = b.configure(false)
204 reports <- svc.Status{State: svc.StopPending}
205 return false, 0
206 }
207 }
208 return false, 0
209}
210func main() {
211 if len(os.Args) != 2 {
212 os.Exit(2)
213 }
214 id, err := uuid.Parse(os.Args[1])
215 if err != nil || id == uuid.Nil {
216 os.Exit(2)
217 }
218 b := bootService{vm: id, user: "Cage-" + strings.ReplaceAll(id.String(), "-", "")[:10]}
219 if err := svc.Run("Cage-Workbench-Boot-"+id.String(), b); err != nil {
220 os.Exit(1)
221 }
222}