This repository has been archived by the owner on Feb 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
plat_windows.go
879 lines (805 loc) · 27.2 KB
/
plat_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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
stdlibruntime "runtime"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
"github.com/dchest/uniuri"
"github.com/taskcluster/generic-worker/process"
"github.com/taskcluster/generic-worker/runtime"
"github.com/taskcluster/generic-worker/win32"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
var sidsThatCanControlDesktopAndWindowsStation map[string]bool = map[string]bool{}
type TaskContext struct {
TaskDir string
LogonSession *process.LogonSession
}
func platformFeatures() []Feature {
return []Feature{
&RDPFeature{},
&RunAsAdministratorFeature{}, // depends on (must appear later in list than) OSGroups feature
}
}
func immediateReboot() {
log.Println("Immediate reboot being issued...")
cmd := exec.Command("C:\\Windows\\System32\\shutdown.exe", "/r", "/t", "3", "/c", "generic-worker requested reboot")
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}
func immediateShutdown(cause string) {
log.Println("Immediate shutdown being issued...")
log.Println(cause)
cmd := exec.Command("C:\\Windows\\System32\\shutdown.exe", "/s", "/t", "3", "/c", cause)
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}
func exceptionOrFailure(errCommand error) *CommandExecutionError {
switch errCommand.(type) {
case *exec.ExitError:
return &CommandExecutionError{
Cause: errCommand,
TaskStatus: failed,
}
}
panic(errCommand)
}
func processCommandOutput(callback func(line string), prog string, options ...string) error {
out, err := exec.Command(prog, options...).Output()
if err != nil {
log.Printf("%v", err)
return err
}
for _, line := range strings.Split(string(out), "\r\n") {
trimmedLine := strings.Trim(line, "\r\n ")
callback(trimmedLine)
}
return nil
}
func deleteTaskDir(path string) error {
log.Print("Trying to remove directory '" + path + "' via os.RemoveAll(path) call as GenericWorker user...")
err := os.RemoveAll(path)
if err == nil {
return nil
}
log.Print("WARNING: could not delete directory '" + path + "' with os.RemoveAll(path) method")
log.Printf("%v", err)
log.Print("Trying to remove directory '" + path + "' via del command as GenericWorker user...")
err = runtime.RunCommands(
false,
[]string{
"cmd", "/c", "del", "/s", "/q", "/f", path,
},
)
if err != nil {
log.Printf("%#v", err)
}
return err
}
func prepareTaskUser(userName string) (reboot bool) {
taskContext.LogonSession = &process.LogonSession{
User: &runtime.OSUser{
Name: userName,
},
}
if autoLogonUser, _ := AutoLogonCredentials(); userName == autoLogonUser {
// make sure user has completed logon before doing anything else
// timeout of 3 minutes should be plenty - note, this function will
// return as soon as user has logged in *and* user profile directory
// has been created - the timeout just sets an upper cap
hToken, err := win32.InteractiveUserToken(3 * time.Minute)
if err != nil {
panic(err)
}
loginInfo := &process.LoginInfo{
HUser: hToken,
}
// At this point, we know we have already booted into the new task user, and the user
// is logged in.
// Note we don't create task directory before logging in, since
// if the task directory is also the user profile home, this
// would mess up the windows logon process.
err = os.MkdirAll(taskContext.TaskDir, 0777)
if err != nil {
panic(err)
}
if script := config.RunAfterUserCreation; script != "" {
command, err := process.NewCommand([]string{script}, taskContext.TaskDir, nil, loginInfo)
if err != nil {
panic(err)
}
command.DirectOutput(os.Stdout)
result := command.Execute()
log.Printf("%v", result)
switch {
case result.Failed():
panic(result.FailureCause())
case result.Crashed():
panic(result.CrashCause())
}
}
return false
}
// create user
user := &runtime.OSUser{
Name: userName,
Password: generatePassword(),
}
err := user.CreateNew()
if err != nil {
panic(err)
}
// set APPDATA
var loginInfo *process.LoginInfo
loginInfo, err = process.NewLoginInfo(user.Name, user.Password)
if err != nil {
panic(err)
}
err = RedirectAppData(loginInfo.HUser, filepath.Join(taskContext.TaskDir, "AppData"))
if err != nil {
panic(err)
}
err = loginInfo.Logout()
if err != nil {
panic(err)
}
// configure worker to auto-login to this newly generated user account
err = SetAutoLogin(user)
if err != nil {
panic(err)
}
log.Print("Exiting worker so it can reboot...")
return true
}
// Uses [A-Za-z0-9] characters (default set) to avoid strange escaping problems
// that could potentially affect security. Prefixed with `pWd0_` to ensure
// password contains a special character (_), lowercase and uppercase letters,
// and a number. This is useful if the OS has a strict password policy
// requiring all of these. The total password length is 29 characters (24 of
// which are random). 29 characters should not be too long for the OS. The 24
// random characters of [A-Za-z0-9] provide (26+26+10)^24 possible permutations
// (approx 143 bits of randomness). Randomisation is not seeded, so results
// should not be reproducible.
func generatePassword() string {
return "pWd0_" + uniuri.NewLen(24)
}
func deleteExistingOSUsers() {
log.Print("Looking for existing task users to delete...")
err := processCommandOutput(deleteOSUserAccount, "wmic", "useraccount", "get", "name")
if err != nil {
log.Print("WARNING: could not list existing Windows user accounts")
log.Printf("%v", err)
}
}
func deleteOSUserAccount(line string) {
if strings.HasPrefix(line, "task_") {
if autoLogonUser, _ := AutoLogonCredentials(); line != autoLogonUser {
user := line
log.Print("Attempting to remove Windows user " + user + "...")
err := runtime.RunCommands(false, []string{"net", "user", user, "/delete"})
if err != nil {
log.Print("WARNING: Could not remove Windows user account " + user)
log.Printf("%v", err)
}
}
}
}
func (task *TaskRun) generateCommand(index int) error {
commandName := fmt.Sprintf("command_%06d", index)
wrapper := filepath.Join(taskContext.TaskDir, commandName+"_wrapper.bat")
log.Printf("Creating wrapper script: %v", wrapper)
loginInfo := task.LoginInfo
command, err := process.NewCommand([]string{wrapper}, taskContext.TaskDir, nil, loginInfo)
if err != nil {
return err
}
task.logMux.RLock()
defer task.logMux.RUnlock()
command.DirectOutput(task.logWriter)
task.Commands[index] = command
return nil
}
func (task *TaskRun) prepareCommand(index int) *CommandExecutionError {
// In order that capturing of log files works, create a custom .bat file
// for the task which redirects output to a log file...
env := filepath.Join(taskContext.TaskDir, "env.txt")
dir := filepath.Join(taskContext.TaskDir, "dir.txt")
commandName := fmt.Sprintf("command_%06d", index)
wrapper := filepath.Join(taskContext.TaskDir, commandName+"_wrapper.bat")
script := filepath.Join(taskContext.TaskDir, commandName+".bat")
contents := ":: This script runs command " + strconv.Itoa(index) + " defined in TaskId " + task.TaskID + "..." + "\r\n"
// contents += "@echo off\r\n"
// At the end of each command we export all the env vars, and import them
// at the start of the next command. Otherwise env variable changes would
// be lost. Similarly, we store the current directory at the end of each
// command, and cd into it at the beginning of the subsequent command. The
// very first command takes the env settings from the payload, and the
// current directory is set to the home directory of the newly created
// user.
// If this is first command, take env from task payload, and cd into home
// directory
if index == 0 {
envVars := map[string]string{}
for k, v := range task.Payload.Env {
envVars[k] = v
}
for envVar, envValue := range envVars {
// log.Printf("Setting env var: %v=%v", envVar, envValue)
contents += "set " + envVar + "=" + envValue + "\r\n"
}
contents += "set TASK_ID=" + task.TaskID + "\r\n"
contents += "cd \"" + taskContext.TaskDir + "\"" + "\r\n"
// Otherwise get the env from the previous command
} else {
for _, x := range [2][2]string{{env, "set "}, {dir, "cd "}} {
file, err := os.Open(x[0])
if err != nil {
panic(fmt.Errorf("Could not read from file %v\n%v", x[0], err))
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
contents += x[1] + scanner.Text() + "\r\n"
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
}
// see http://blogs.msdn.com/b/oldnewthing/archive/2008/09/26/8965755.aspx
// need to explicitly unset as we rely on it later
contents += "set errorlevel=\r\n"
// now make sure output is enabled again
// now call the actual script that runs the command
// ******************************
// old version that WROTE TO A FILE:
// contents += "call " + script + " > " + absLogFile + " 2>&1" + "\r\n"
// ******************************
contents += "call " + script + " 2>&1" + "\r\n"
// contents += "@echo off" + "\r\n"
// store exit code
contents += "set tcexitcode=%errorlevel%\r\n"
// now store env for next command, unless this is the last command
if index != len(task.Payload.Command)-1 {
contents += "set > " + env + "\r\n"
contents += "cd > " + dir + "\r\n"
}
// exit with stored exit code
contents += "exit /b %tcexitcode%\r\n"
// now generate the .bat script that runs all of this
err := ioutil.WriteFile(
wrapper,
[]byte(contents),
0755,
)
if err != nil {
panic(err)
}
// Now make the actual task a .bat script
fileContents := []byte(strings.Join([]string{
"@echo on",
task.Payload.Command[index],
}, "\r\n"))
err = ioutil.WriteFile(
script,
fileContents,
0755,
)
// log.Printf("Script %q:", script)
// log.Print("Contents:")
// log.Print(string(fileContents))
// log.Printf("Wrapper script %q:", wrapper)
// log.Print("Contents:")
// log.Print(contents)
if err != nil {
panic(err)
}
ccc := exec.Command("icacls", wrapper)
ccc.Stdout = os.Stdout
ccc.Stderr = os.Stderr
err = ccc.Run()
log.Printf("icacls error: %v", err)
ccc = exec.Command("wmic", "useraccount", "get", "name,sid")
ccc.Stdout = os.Stdout
ccc.Stderr = os.Stderr
err = ccc.Run()
log.Printf("wmic error: %v", err)
return nil
}
func taskCleanup() error {
if config.CleanUpTaskDirs {
deleteTaskDirs()
}
// note if this fails, we carry on without throwing an error
if !config.RunTasksAsCurrentUser {
deleteExistingOSUsers()
}
return nil
}
func install(arguments map[string]interface{}) (err error) {
exePath, err := ExePath()
if err != nil {
return err
}
configFile := convertNilToEmptyString(arguments["--config"])
switch {
case arguments["service"]:
nssm := convertNilToEmptyString(arguments["--nssm"])
serviceName := convertNilToEmptyString(arguments["--service-name"])
dir := filepath.Dir(exePath)
return deployService(configFile, nssm, serviceName, exePath, dir)
}
log.Fatal("Unknown install target - only 'service' is allowed")
return nil
}
func CreateRunGenericWorkerBatScript(batScriptFilePath string) error {
batScriptContents := []byte(strings.Join([]string{
`:: Run generic-worker`,
``,
`:: step inside folder containing this script`,
`pushd %~dp0`,
``,
`.\generic-worker.exe run --configure-for-aws > .\generic-worker.log 2>&1`,
``,
`:: Possible exit codes:`,
`:: 0: all tasks completed - only occurs when numberOfTasksToRun > 0`,
`:: 67: rebooting - system reboot has been triggered`,
`:: 68: idle timeout - system shutdown has been triggered if shutdownMachineOnIdle=true`,
`:: 69: internal error - system shutdown has been triggered if shutdownMachineOnInternalError=true`,
`:: 70: deployment ID changed - system shutdown has been triggered`,
``,
}, "\r\n"))
err := ioutil.WriteFile(batScriptFilePath, batScriptContents, 0755)
if err != nil {
return fmt.Errorf("Was not able to create file %q with access permissions 0755 due to %s", batScriptFilePath, err)
}
return nil
}
func SetAutoLogin(user *runtime.OSUser) error {
k, _, err := registry.CreateKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`, registry.WRITE)
if err != nil {
return fmt.Errorf(`Was not able to create registry key 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' due to %s`, err)
}
defer k.Close()
err = k.SetDWordValue("AutoAdminLogon", 1)
if err != nil {
return fmt.Errorf(`Was not able to set registry entry 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoAdminLogon' to 1 due to %s`, err)
}
err = k.SetStringValue("DefaultUserName", user.Name)
if err != nil {
return fmt.Errorf(`Was not able to set registry entry 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName' to %q due to %s`, user.Name, err)
}
err = k.SetStringValue("DefaultPassword", user.Password)
if err != nil {
return fmt.Errorf(`Was not able to set registry entry 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultPassword' to %q due to %s`, user.Password, err)
}
return nil
}
// deploys the generic worker as a windows service, running under the windows
// user specified with username/password, such that the generic worker runs
// with the given configuration file configFile. the http://nssm.cc/ executable
// is required to install the service, specified as a file system path. The
// serviceName is the service name given to the newly created service. if the
// service already exists, it is simply updated.
func deployService(configFile, nssm, serviceName, exePath, dir string) error {
targetScript := filepath.Join(filepath.Dir(exePath), "run-generic-worker.bat")
err := CreateRunGenericWorkerBatScript(targetScript)
if err != nil {
return err
}
return runtime.RunCommands(
false,
[]string{nssm, "install", serviceName, targetScript},
[]string{nssm, "set", serviceName, "AppDirectory", dir},
[]string{nssm, "set", serviceName, "DisplayName", serviceName},
[]string{nssm, "set", serviceName, "Description", "A taskcluster worker that runs on all mainstream platforms"},
[]string{nssm, "set", serviceName, "Start", "SERVICE_AUTO_START"},
// By default, NSSM installs as LocalSystem, which we need since we call WTSQueryUserToken.
// So let's not set it.
// []string{nssm, "set", serviceName, "ObjectName", ".\\" + user.Name, user.Password},
[]string{nssm, "set", serviceName, "Type", "SERVICE_WIN32_OWN_PROCESS"},
[]string{nssm, "set", serviceName, "AppPriority", "NORMAL_PRIORITY_CLASS"},
[]string{nssm, "set", serviceName, "AppNoConsole", "1"},
[]string{nssm, "set", serviceName, "AppAffinity", "All"},
[]string{nssm, "set", serviceName, "AppStopMethodSkip", "0"},
[]string{nssm, "set", serviceName, "AppStopMethodConsole", "1500"},
[]string{nssm, "set", serviceName, "AppStopMethodWindow", "1500"},
[]string{nssm, "set", serviceName, "AppStopMethodThreads", "1500"},
[]string{nssm, "set", serviceName, "AppThrottle", "1500"},
[]string{nssm, "set", serviceName, "AppExit", "Default", "Exit"},
[]string{nssm, "set", serviceName, "AppRestartDelay", "0"},
[]string{nssm, "set", serviceName, "AppStdout", filepath.Join(dir, "generic-worker-service.log")},
[]string{nssm, "set", serviceName, "AppStderr", filepath.Join(dir, "generic-worker-service.log")},
[]string{nssm, "set", serviceName, "AppStdoutCreationDisposition", "4"},
[]string{nssm, "set", serviceName, "AppStderrCreationDisposition", "4"},
[]string{nssm, "set", serviceName, "AppRotateFiles", "1"},
[]string{nssm, "set", serviceName, "AppRotateOnline", "1"},
[]string{nssm, "set", serviceName, "AppRotateSeconds", "3600"},
[]string{nssm, "set", serviceName, "AppRotateBytes", "0"},
)
}
func ExePath() (string, error) {
log.Printf("Command args: %#v", os.Args)
prog := os.Args[0]
p, err := filepath.Abs(prog)
if err != nil {
return "", err
}
fi, err := os.Stat(p)
if err == nil {
if !fi.Mode().IsDir() {
return p, nil
}
err = fmt.Errorf("%s is directory", p)
}
if filepath.Ext(p) == "" {
p += ".exe"
fi, err = os.Stat(p)
if err == nil {
if !fi.Mode().IsDir() {
return p, nil
}
err = fmt.Errorf("%s is directory", p)
}
}
return "", err
}
func (task *TaskRun) formatCommand(index int) string {
return task.Payload.Command[index]
}
// see http://ss64.com/nt/icacls.html
func makeDirReadableForTaskUser(task *TaskRun, dir string) error {
if config.RunTasksAsCurrentUser {
return nil
}
task.Infof("[mounts] Granting %v full control of '%v'", taskContext.LogonSession.User.Name, dir)
err := runtime.RunCommands(
false,
[]string{"icacls", dir, "/grant:r", taskContext.LogonSession.User.Name + ":(OI)(CI)F"},
)
if err != nil {
return fmt.Errorf("[mounts] Not able to make directory %v writable for %v: %v", dir, taskContext.LogonSession.User.Name, err)
}
return nil
}
// see http://ss64.com/nt/icacls.html
func makeDirUnreadableForTaskUser(task *TaskRun, dir string) error {
if config.RunTasksAsCurrentUser {
return nil
}
task.Infof("[mounts] Denying %v access to '%v'", taskContext.LogonSession.User.Name, dir)
err := runtime.RunCommands(
false,
[]string{"icacls", dir, "/remove:g", taskContext.LogonSession.User.Name},
)
if err != nil {
return fmt.Errorf("[mounts] Not able to make directory %v unreadable for %v: %v", dir, taskContext.LogonSession.User.Name, err)
}
return nil
}
// The windows implementation of os.Rename(...) doesn't allow renaming files
// across drives (i.e. copy and delete semantics) - this alternative
// implementation is identical to the os.Rename(...) implementation, but
// additionally sets the flag windows.MOVEFILE_COPY_ALLOWED in order to cater
// for oldpath and newpath being on different drives. See:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365240(v=vs.85).aspx
func RenameCrossDevice(oldpath, newpath string) (err error) {
var to, from *uint16
from, err = syscall.UTF16PtrFromString(oldpath)
if err != nil {
return
}
to, err = syscall.UTF16PtrFromString(newpath)
if err != nil {
return
}
// this will work for files and directories on same drive, and even for
// files on different drives, but not for directories on different drives
err = windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_COPY_ALLOWED)
// if we fail, could be a folder that needs to be moved to a different
// drive - however, check it really is a folder, since otherwise we could
// end up infinitely recursing between RenameCrossDevice and
// RenameFolderCrossDevice, since they both call into each other
if err != nil {
var fi os.FileInfo
fi, err = os.Stat(oldpath)
if err != nil {
return
}
if fi.IsDir() {
err = RenameFolderCrossDevice(oldpath, newpath)
}
}
return
}
func RenameFolderCrossDevice(oldpath, newpath string) (err error) {
// recursively move files
moveFile := func(path string, info os.FileInfo, inErr error) (outErr error) {
if inErr != nil {
return inErr
}
var relPath string
relPath, outErr = filepath.Rel(oldpath, path)
if outErr != nil {
return
}
targetPath := filepath.Join(newpath, relPath)
if info.IsDir() {
outErr = os.Mkdir(targetPath, info.Mode())
} else {
outErr = RenameCrossDevice(path, targetPath)
}
return
}
err = filepath.Walk(oldpath, moveFile)
if err != nil {
return
}
err = os.RemoveAll(oldpath)
return
}
func (task *TaskRun) addUserToGroups(groups []string) (updatedGroups []string, notUpdatedGroups []string) {
if len(groups) == 0 {
return []string{}, []string{}
}
for _, group := range groups {
err := runtime.RunCommands(false, []string{"net", "localgroup", group, "/add", taskContext.LogonSession.User.Name})
if err == nil {
updatedGroups = append(updatedGroups, group)
} else {
notUpdatedGroups = append(notUpdatedGroups, group)
}
}
return
}
func (task *TaskRun) removeUserFromGroups(groups []string) (updatedGroups []string, notUpdatedGroups []string) {
if len(groups) == 0 {
return []string{}, []string{}
}
for _, group := range groups {
err := runtime.RunCommands(false, []string{"net", "localgroup", group, "/delete", taskContext.LogonSession.User.Name})
if err == nil {
updatedGroups = append(updatedGroups, group)
} else {
notUpdatedGroups = append(notUpdatedGroups, group)
}
}
return
}
func RedirectAppData(hUser syscall.Token, folder string) (err error) {
err = win32.SetAndCreateFolder(hUser, &win32.FOLDERID_RoamingAppData, filepath.Join(folder, "Roaming"))
if err != nil {
return
}
return win32.SetAndCreateFolder(hUser, &win32.FOLDERID_LocalAppData, filepath.Join(folder, "Local"))
}
func defaultTasksDir() string {
return win32.ProfilesDirectory()
}
func UACEnabled() bool {
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System`, registry.QUERY_VALUE)
if err != nil {
return false
}
defer k.Close()
var enableLUA uint64
enableLUA, _, err = k.GetIntegerValue("EnableLUA")
if err != nil {
return false
}
return enableLUA == 1
}
func AutoLogonCredentials() (username, password string) {
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon`, registry.QUERY_VALUE)
if err != nil {
log.Printf("Hit error reading Winlogon registry key - assume no autologon set: %v", err)
return
}
defer k.Close()
username, _, err = k.GetStringValue("DefaultUserName")
if err != nil {
log.Printf("Hit error reading winlogon DefaultUserName registry value - assume no autologon set: %v", err)
return "", ""
}
password, _, err = k.GetStringValue("DefaultPassword")
if err != nil {
log.Printf("Hit error reading winlogon DefaultPassword registry value - assume no autologon set: %v", err)
return "", ""
}
return
}
func chooseTaskDirName() string {
taskDirName, _ := AutoLogonCredentials()
if taskDirName == "" {
return "task_" + strconv.Itoa(int(time.Now().Unix()))
}
return taskDirName
}
func unsetAutoLogon() {
err := SetAutoLogin(
&runtime.OSUser{},
)
if err != nil {
panic(err)
}
}
func deleteTaskDirs() {
removeTaskDirs(win32.ProfilesDirectory())
removeTaskDirs(config.TasksDir)
}
func (task *TaskRun) SetLoginInfo() (err error) {
task.LoginInfo = &process.LoginInfo{}
if !config.RunTasksAsCurrentUser {
var hToken syscall.Token
hToken, err = win32.InteractiveUserToken(time.Minute)
if err != nil {
return
}
task.LoginInfo.HUser = hToken
}
return
}
func (task *TaskRun) RefreshLoginSession() {
// On Windows we need to call LogonUser to get new access token with the group changes
if task.LoginInfo != nil && task.LoginInfo.HUser != 0 {
DumpTokenInfo(task.LoginInfo.HUser)
sid := "S-1-1-0"
// no need to grant if already granted
if sidsThatCanControlDesktopAndWindowsStation[sid] {
log.Printf("SID %v found in %#v - no need to grant access!", sid, sidsThatCanControlDesktopAndWindowsStation)
} else {
log.Printf("SID %v NOT found in %#v - granting access...", sid, sidsThatCanControlDesktopAndWindowsStation)
// We want to run generic-worker exe, which is os.Args[0] if we are running generic-worker, but if
// we are running tests, os.Args[0] will be the test executable, so then we use relative path to
// installed binary. This hack will go if we can use ImpersonateLoggedOnUser / RevertToSelf instead.
var exe string
if filepath.Base(os.Args[0]) == "generic-worker.exe" {
exe = os.Args[0]
} else {
exe = `..\..\..\..\bin\generic-worker.exe`
}
cmd, err := process.NewCommand([]string{exe, "grant-winsta-access", "--sid", sid}, cwd, []string{}, task.LoginInfo)
cmd.DirectOutput(os.Stdout)
log.Printf("About to run command: %#v", *(cmd.Cmd))
if err != nil {
panic(err)
}
result := cmd.Execute()
if !result.Succeeded() {
panic(fmt.Sprintf("Failed to grant everyone access to windows station and desktop:\n%v", result))
}
log.Printf("Granted %v full control of interactive windows station and desktop", sid)
sidsThatCanControlDesktopAndWindowsStation[sid] = true
}
// logoutError := task.LoginInfo.Logout()
// if logoutError != nil {
// panic(logoutError)
// }
}
user, pass := AutoLogonCredentials()
loginInfo, logonError := process.NewLoginInfo(user, pass)
if logonError != nil {
// implies a serious bug
panic(logonError)
}
DumpTokenInfo(loginInfo.HUser)
err := loginInfo.SetActiveConsoleSessionId()
if err != nil {
// implies a serious bug
panic(fmt.Sprintf("Could not set token session information: %v", err))
}
DumpTokenInfo(loginInfo.HUser)
task.LoginInfo = loginInfo
}
func DumpTokenInfo(token syscall.Token) {
log.Print("==================================================")
primaryGroup, err := token.GetTokenPrimaryGroup()
if err != nil {
panic(err)
}
account, domain, accType, err := primaryGroup.PrimaryGroup.LookupAccount("")
if err != nil {
panic(err)
}
primaryGroupSid, err := primaryGroup.PrimaryGroup.String()
if err != nil {
panic(err)
}
log.Printf("Token Primary Group (%v): %v/%v (%#x)", primaryGroupSid, account, domain, accType)
tokenUser, err := token.GetTokenUser()
if err != nil {
panic(err)
}
tokenUserSid, err := tokenUser.User.Sid.String()
if err != nil {
panic(err)
}
account, domain, accType, err = tokenUser.User.Sid.LookupAccount("")
if err != nil {
panic(err)
}
log.Printf("Token User (%v): %v/%v (%#x) - with attributes: %#x", tokenUserSid, account, domain, accType, tokenUser.User.Attributes)
tokenSessionID, err := win32.GetTokenSessionID(token)
if err != nil {
panic(err)
}
log.Printf("Token Session ID: %#x", tokenSessionID)
tokenUIAccess, err := win32.GetTokenUIAccess(token)
if err != nil {
panic(err)
}
log.Printf("Token UI Access: %#x", tokenUIAccess)
wt := windows.Token(token)
tokenGroups, err := wt.GetTokenGroups()
if err != nil {
panic(err)
}
groups := make([]windows.SIDAndAttributes, tokenGroups.GroupCount, tokenGroups.GroupCount)
for i := uint32(0); i < tokenGroups.GroupCount; i++ {
groups[i] = *(*windows.SIDAndAttributes)(unsafe.Pointer(uintptr(unsafe.Pointer(&tokenGroups.Groups[0])) + uintptr(i)*unsafe.Sizeof(tokenGroups.Groups[0])))
groupSid, err := groups[i].Sid.String()
if err != nil {
panic(fmt.Errorf("WEIRD: got error: %v", err))
}
account, domain, accType, err := groups[i].Sid.LookupAccount("")
if err != nil {
log.Printf("Token Group (%v): <<NO_SID>> - with attributes: %#x", groupSid, groups[i].Attributes)
} else {
log.Printf("Token Group (%v): %v/%v (%#x) - with attributes: %#x", groupSid, account, domain, accType, groups[i].Attributes)
}
}
log.Print("==================================================")
}
func GrantSIDFullControlOfInteractiveWindowsStationAndDesktop(sid string) (err error) {
stdlibruntime.LockOSThread()
defer stdlibruntime.UnlockOSThread()
var winsta win32.Hwinsta
if winsta, err = win32.GetProcessWindowStation(); err != nil {
return
}
var winstaName string
winstaName, err = win32.GetUserObjectName(syscall.Handle(winsta))
if err != nil {
return
}
var desktop win32.Hdesk
desktop, err = win32.GetThreadDesktop(win32.GetCurrentThreadId())
if err != nil {
return
}
var desktopName string
desktopName, err = win32.GetUserObjectName(syscall.Handle(desktop))
if err != nil {
return
}
fmt.Printf("Windows Station: %v\n", winstaName)
fmt.Printf("Desktop: %v\n", desktopName)
var everyone *syscall.SID
everyone, err = syscall.StringToSid(sid)
if err != nil {
return
}
err = win32.AddAceToWindowStation(winsta, everyone)
if err != nil {
return
}
err = win32.AddAceToDesktop(desktop, everyone)
if err != nil {
return
}
return
}