Debian Codegraph @

cmd/sddl/main_windows.go

raw
1 //go:build windows
2
3 package main
4
5 import (
6 "encoding/base64"
7 "fmt"
8 "os"
9
10 "syscall"
11 "unsafe"
12
13 "golang.org/x/sys/windows"
14 )
15
16 var (
17 advapi32 = windows.NewLazyDLL("advapi32.dll")
18 convertSecurityDescriptorToStringSecurityDescriptorW = advapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW")
19 convertStringSecurityDescriptorToSecurityDescriptorW = advapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW")
20 getSecurityInfo = advapi32.NewProc("GetSecurityInfo")
21 getSecurityDescriptorLength = advapi32.NewProc("GetSecurityDescriptorLength")
22 getSecurityDescriptorControl = advapi32.NewProc("GetSecurityDescriptorControl")
23 makeSelfRelativeSD = advapi32.NewProc("MakeSelfRelativeSD")
24 openProcessToken = advapi32.NewProc("OpenProcessToken")
25 lookupPrivilegeValueW = advapi32.NewProc("LookupPrivilegeValueW")
26 adjustTokenPrivileges = advapi32.NewProc("AdjustTokenPrivileges")
27 )
28
29 const (
30 OWNER_SECURITY_INFORMATION = 0x00000001
31 GROUP_SECURITY_INFORMATION = 0x00000002
32 DACL_SECURITY_INFORMATION = 0x00000004
33 SACL_SECURITY_INFORMATION = 0x00000008
34
35 SE_SECURITY_NAME = "SeSecurityPrivilege"
36 TOKEN_ADJUST_PRIVILEGES = 0x0020
37 TOKEN_QUERY = 0x0008
38
39 // Adding missing constants
40 READ_CONTROL = 0x00020000
41 ACCESS_SYSTEM_SECURITY = 0x01000000
42
43 // Security descriptor control flags
44 SE_SELF_RELATIVE = 0x8000
45 )
46
47 type LUID struct {
48 LowPart uint32
49 HighPart int32
50 }
51
52 type LUID_AND_ATTRIBUTES struct {
53 Luid LUID
54 Attributes uint32
55 }
56
57 type TOKEN_PRIVILEGES struct {
58 PrivilegeCount uint32
59 Privileges [1]LUID_AND_ATTRIBUTES
60 }
61
62 func enableSecurityPrivilege() error {
63
64 var token windows.Token
65 currentProcess := windows.CurrentProcess()
66
67 // Get process token
68 ret, _, err := openProcessToken.Call(
69 uintptr(currentProcess),
70 uintptr(TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY),
71 uintptr(unsafe.Pointer(&token)),
72 )
73 if ret == 0 {
74 return fmt.Errorf("OpenProcessToken failed: %v", err)
75 }
76 defer token.Close()
77
78 // Lookup the privilege value
79 var luid LUID
80 privName, err := syscall.UTF16PtrFromString(SE_SECURITY_NAME)
81 if err != nil {
82 return fmt.Errorf("UTF16PtrFromString failed: %v", err)
83 }
84
85 ret, _, err = lookupPrivilegeValueW.Call(
86 0,
87 uintptr(unsafe.Pointer(privName)),
88 uintptr(unsafe.Pointer(&luid)),
89 )
90 if ret == 0 {
91 return fmt.Errorf("LookupPrivilegeValue failed: %v", err)
92 }
93
94 // Prepare token privileges
95 var tp TOKEN_PRIVILEGES
96 tp.PrivilegeCount = 1
97 tp.Privileges[0].Luid = luid
98 tp.Privileges[0].Attributes = 0x00000002 // SE_PRIVILEGE_ENABLED
99
100 // Adjust token privileges
101 ret, _, err = adjustTokenPrivileges.Call(
102 uintptr(token),
103 0,
104 uintptr(unsafe.Pointer(&tp)),
105 0,
106 0,
107 0,
108 )
109 if ret == 0 {
110 return fmt.Errorf("AdjustTokenPrivileges failed: %v", err)
111 }
112
113 return nil
114 }
115
116 func getSecurityDescriptorPointerAndInfo(filename string) (uintptr, int, error) {
117
118 // Open the file to get a handle
119 pathPtr, err := syscall.UTF16PtrFromString(filename)
120 if err != nil {
121 return 0, 0, fmt.Errorf("Error converting filename: %w", err)
122 }
123
124 // Check if path is a directory
125 attrs, err := syscall.GetFileAttributes(pathPtr)
126 if err != nil {
127 return 0, 0, fmt.Errorf("Error getting file attributes: %w", err)
128 }
129
130 var fileFlags uint32 = syscall.FILE_ATTRIBUTE_NORMAL
131 if attrs&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
132 fileFlags = syscall.FILE_FLAG_BACKUP_SEMANTICS
133 }
134
135 handle, err := syscall.CreateFile(
136 pathPtr,
137 READ_CONTROL|ACCESS_SYSTEM_SECURITY,
138 syscall.FILE_SHARE_READ,
139 nil,
140 syscall.OPEN_EXISTING,
141 fileFlags,
142 0,
143 )
144 if err != nil {
145 return 0, 0, fmt.Errorf("Error opening file: %w", err)
146 }
147 defer syscall.CloseHandle(handle)
148
149 // Get the security descriptor
150 var pSD, pOwner, pGroup, pDacl, pSacl uintptr
151 secInfo := OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION
152
153 ret, _, err := getSecurityInfo.Call(
154 uintptr(handle),
155 uintptr(1), // SE_FILE_OBJECT
156 uintptr(secInfo),
157 uintptr(unsafe.Pointer(&pOwner)),
158 uintptr(unsafe.Pointer(&pGroup)),
159 uintptr(unsafe.Pointer(&pDacl)),
160 uintptr(unsafe.Pointer(&pSacl)),
161 uintptr(unsafe.Pointer(&pSD)),
162 )
163
164 // If failed, try without SACL
165 if ret != 0 {
166 fmt.Fprintf(os.Stderr, "Warning: Could not get full security info, trying without SACL...\n")
167 secInfo = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
168 ret, _, err = getSecurityInfo.Call(
169 uintptr(handle),
170 uintptr(1), // SE_FILE_OBJECT
171 uintptr(secInfo),
172 uintptr(unsafe.Pointer(&pOwner)),
173 uintptr(unsafe.Pointer(&pGroup)),
174 uintptr(unsafe.Pointer(&pDacl)),
175 0,
176 uintptr(unsafe.Pointer(&pSD)),
177 )
178 if ret != 0 {
179 return 0, 0, fmt.Errorf("GetSecurityInfo failed: %w", err)
180 }
181 }
182
183 return pSD, secInfo, nil
184 }
185
186 // GetFileSDBytes retrieves a file's security descriptor in binary form.
187 // It uses direct Windows API calls to get the raw SD bytes.
188 func GetFileSDBytes(filename string) ([]byte, error) {
189 // Try to enable security privilege
190 err := enableSecurityPrivilege()
191 if err != nil {
192 fmt.Fprintf(os.Stderr, "Warning: Could not enable security privilege: %v\n", err)
193 fmt.Fprintf(os.Stderr, "Will try to continue with reduced privileges...\n")
194 }
195
196 pSD, _, err := getSecurityDescriptorPointerAndInfo(filename)
197 if err != nil {
198 return nil, err
199 }
200
201 // Check if the security descriptor is already self-relative
202 var control uint16
203 var revision uint32
204 ret, _, err := getSecurityDescriptorControl.Call(
205 pSD,
206 uintptr(unsafe.Pointer(&control)),
207 uintptr(unsafe.Pointer(&revision)),
208 )
209 if ret == 0 {
210 return nil, fmt.Errorf("GetSecurityDescriptorControl failed: %w", err)
211 }
212
213 var finalSD uintptr
214 var sdSize uint32
215
216 if control&SE_SELF_RELATIVE == 0 {
217 // First acll to get required buffer size
218 ret, _, err = makeSelfRelativeSD.Call(
219 pSD,
220 0,
221 uintptr(unsafe.Pointer(&sdSize)),
222 )
223 if ret == 0 {
224 return nil, fmt.Errorf("MakeSelfRelativeSD failed: %v", err)
225 }
226
227 // Allocate buffer
228 finalSD, err := windows.LocalAlloc(0, sdSize)
229 if finalSD == 0 {
230 return nil, fmt.Errorf("LocalAlloc failed: %v", err)
231 }
232 defer windows.LocalFree(windows.Handle(finalSD))
233
234 // Second call to actually convert
235 ret, _, err = makeSelfRelativeSD.Call(
236 pSD,
237 finalSD,
238 uintptr(unsafe.Pointer(&sdSize)),
239 )
240 if ret == 0 {
241 return nil, fmt.Errorf("MakeSelfRelativeSD failed (2): %v", err)
242 }
243 } else {
244 finalSD = pSD
245 length, _, _ := getSecurityDescriptorLength.Call(pSD)
246 sdSize = uint32(length)
247 }
248
249 // Copy to byte slice and encode
250 sdBytes := make([]byte, sdSize)
251 for i := uint32(0); i < sdSize; i++ {
252 sdBytes[i] = *(*byte)(unsafe.Pointer(finalSD + uintptr(i)))
253 }
254
255 return sdBytes, nil
256 }
257
258 // GetFileSDString retrieves a file's security descriptor as a SDDL string.
259 // It tries to use the ConvertSecurityDescriptorToStringSecurityDescriptor API
260 // first for accuracy, but falls back to our SDDL package if that fails.
261 func GetFileSDString(filename string) (string, error) {
262
263 // Try to enable security privilege
264 err := enableSecurityPrivilege()
265 if err != nil {
266 fmt.Fprintf(os.Stderr, "Warning: Could not enable security privilege: %v\n", err)
267 fmt.Fprintf(os.Stderr, "Will try to continue with reduced privileges...\n")
268 }
269
270 pSD, secInfo, err := getSecurityDescriptorPointerAndInfo(filename)
271 if err != nil {
272 return "", err
273 }
274
275 // Convert to string format (SDDL)
276 var strPtr *uint16
277 ret, _, err := convertSecurityDescriptorToStringSecurityDescriptorW.Call(
278 pSD,
279 uintptr(1),
280 uintptr(secInfo),
281 uintptr(unsafe.Pointer(&strPtr)),
282 0,
283 )
284 if ret == 0 {
285 return "", fmt.Errorf("ConvertSecurityDescriptorToString failed: %v", err)
286 }
287 defer windows.LocalFree(windows.Handle(unsafe.Pointer(strPtr)))
288
289 // Convert UTF16 to string and print SDDL
290 sddl := windows.UTF16PtrToString(strPtr)
291
292 return sddl, nil
293 }
294
295 // GetFileSecurityBase64 retrieves a file's security descriptor in base64-encoded format.
296 func GetFileSecurityBase64(filename string) (string, error) {
297 sd, err := GetFileSDBytes(filename)
298 if err != nil {
299 return "", err
300 }
301 return base64.StdEncoding.EncodeToString(sd), nil
302 }