-
Notifications
You must be signed in to change notification settings - Fork 581
/
syscall_windows_test.go
1475 lines (1343 loc) · 45.5 KB
/
syscall_windows_test.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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows_test
import (
"bufio"
"bytes"
"debug/pe"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"testing"
"time"
"unicode/utf8"
"unsafe"
"golang.org/x/sys/windows"
)
func TestWin32finddata(t *testing.T) {
path := filepath.Join(t.TempDir(), "long_name.and_extension")
f, err := os.Create(path)
if err != nil {
t.Fatalf("failed to create %v: %v", path, err)
}
f.Close()
type X struct {
fd windows.Win32finddata
got byte
pad [10]byte // to protect ourselves
}
var want byte = 2 // it is unlikely to have this character in the filename
x := X{got: want}
pathp, _ := windows.UTF16PtrFromString(path)
h, err := windows.FindFirstFile(pathp, &(x.fd))
if err != nil {
t.Fatalf("FindFirstFile failed: %v", err)
}
err = windows.FindClose(h)
if err != nil {
t.Fatalf("FindClose failed: %v", err)
}
if x.got != want {
t.Fatalf("memory corruption: want=%d got=%d", want, x.got)
}
}
func TestFormatMessage(t *testing.T) {
dll := windows.MustLoadDLL("netevent.dll")
const TITLE_SC_MESSAGE_BOX uint32 = 0xC0001B75
const flags uint32 = syscall.FORMAT_MESSAGE_FROM_HMODULE | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS
buf := make([]uint16, 300)
_, err := windows.FormatMessage(flags, uintptr(dll.Handle), TITLE_SC_MESSAGE_BOX, 0, buf, nil)
if err != nil {
t.Fatalf("FormatMessage for handle=%x and errno=%x failed: %v", dll.Handle, TITLE_SC_MESSAGE_BOX, err)
}
}
func abort(funcname string, err error) {
panic(funcname + " failed: " + err.Error())
}
func ExampleLoadLibrary() {
h, err := windows.LoadLibrary("kernel32.dll")
if err != nil {
abort("LoadLibrary", err)
}
defer windows.FreeLibrary(h)
proc, err := windows.GetProcAddress(h, "GetVersion")
if err != nil {
abort("GetProcAddress", err)
}
r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0)
major := byte(r)
minor := uint8(r >> 8)
build := uint16(r >> 16)
print("windows version ", major, ".", minor, " (Build ", build, ")\n")
}
func TestTOKEN_ALL_ACCESS(t *testing.T) {
if windows.TOKEN_ALL_ACCESS != 0xF01FF {
t.Errorf("TOKEN_ALL_ACCESS = %x, want 0xF01FF", windows.TOKEN_ALL_ACCESS)
}
}
func TestCreateWellKnownSid(t *testing.T) {
sid, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
if err != nil {
t.Fatalf("Unable to create well known sid for administrators: %v", err)
}
if got, want := sid.String(), "S-1-5-32-544"; got != want {
t.Fatalf("Builtin Administrators SID = %s, want %s", got, want)
}
}
func TestPseudoTokens(t *testing.T) {
version, err := windows.GetVersion()
if err != nil {
t.Fatal(err)
}
if ((version&0xffff)>>8)|((version&0xff)<<8) < 0x0602 {
return
}
realProcessToken, err := windows.OpenCurrentProcessToken()
if err != nil {
t.Fatal(err)
}
defer realProcessToken.Close()
realProcessUser, err := realProcessToken.GetTokenUser()
if err != nil {
t.Fatal(err)
}
pseudoProcessToken := windows.GetCurrentProcessToken()
pseudoProcessUser, err := pseudoProcessToken.GetTokenUser()
if err != nil {
t.Fatal(err)
}
if !windows.EqualSid(realProcessUser.User.Sid, pseudoProcessUser.User.Sid) {
t.Fatal("The real process token does not have the same as the pseudo process token")
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
err = windows.RevertToSelf()
if err != nil {
t.Fatal(err)
}
pseudoThreadToken := windows.GetCurrentThreadToken()
_, err = pseudoThreadToken.GetTokenUser()
if err != windows.ERROR_NO_TOKEN {
t.Fatal("Expected an empty thread token")
}
pseudoThreadEffectiveToken := windows.GetCurrentThreadEffectiveToken()
pseudoThreadEffectiveUser, err := pseudoThreadEffectiveToken.GetTokenUser()
if err != nil {
t.Fatal(nil)
}
if !windows.EqualSid(realProcessUser.User.Sid, pseudoThreadEffectiveUser.User.Sid) {
t.Fatal("The real process token does not have the same as the pseudo thread effective token, even though we aren't impersonating")
}
err = windows.ImpersonateSelf(windows.SecurityImpersonation)
if err != nil {
t.Fatal(err)
}
defer windows.RevertToSelf()
pseudoThreadUser, err := pseudoThreadToken.GetTokenUser()
if err != nil {
t.Fatal(err)
}
if !windows.EqualSid(realProcessUser.User.Sid, pseudoThreadUser.User.Sid) {
t.Fatal("The real process token does not have the same as the pseudo thread token after impersonating self")
}
}
func TestGUID(t *testing.T) {
guid, err := windows.GenerateGUID()
if err != nil {
t.Fatal(err)
}
if guid.Data1 == 0 && guid.Data2 == 0 && guid.Data3 == 0 && guid.Data4 == [8]byte{} {
t.Fatal("Got an all zero GUID, which is overwhelmingly unlikely")
}
want := fmt.Sprintf("{%08X-%04X-%04X-%04X-%012X}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[:2], guid.Data4[2:])
got := guid.String()
if got != want {
t.Fatalf("String = %q; want %q", got, want)
}
guid2, err := windows.GUIDFromString(got)
if err != nil {
t.Fatal(err)
}
if guid2 != guid {
t.Fatalf("Did not parse string back to original GUID = %q; want %q", guid2, guid)
}
_, err = windows.GUIDFromString("not-a-real-guid")
if err != syscall.Errno(windows.CO_E_CLASSSTRING) {
t.Fatalf("Bad GUID string error = %v; want CO_E_CLASSSTRING", err)
}
}
func TestKnownFolderPath(t *testing.T) {
token, err := windows.OpenCurrentProcessToken()
if err != nil {
t.Fatal(err)
}
defer token.Close()
profileDir, err := token.GetUserProfileDirectory()
if err != nil {
t.Fatal(err)
}
want := filepath.Join(profileDir, "Desktop")
got, err := windows.KnownFolderPath(windows.FOLDERID_Desktop, windows.KF_FLAG_DEFAULT)
if err != nil {
t.Fatal(err)
}
if want != got {
t.Fatalf("Path = %q; want %q", got, want)
}
}
func TestRtlGetVersion(t *testing.T) {
version := windows.RtlGetVersion()
major, minor, build := windows.RtlGetNtVersionNumbers()
// Go is not explicitly added to the application compatibility database, so
// these two functions should return the same thing.
if version.MajorVersion != major || version.MinorVersion != minor || version.BuildNumber != build {
t.Fatalf("%d.%d.%d != %d.%d.%d", version.MajorVersion, version.MinorVersion, version.BuildNumber, major, minor, build)
}
}
func TestGetNamedSecurityInfo(t *testing.T) {
path, err := windows.GetSystemDirectory()
if err != nil {
t.Fatal(err)
}
sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION)
if err != nil {
t.Fatal(err)
}
if !sd.IsValid() {
t.Fatal("Invalid security descriptor")
}
sdOwner, _, err := sd.Owner()
if err != nil {
t.Fatal(err)
}
if !sdOwner.IsValid() {
t.Fatal("Invalid security descriptor owner")
}
}
func TestGetSecurityInfo(t *testing.T) {
sd, err := windows.GetSecurityInfo(windows.CurrentProcess(), windows.SE_KERNEL_OBJECT, windows.DACL_SECURITY_INFORMATION)
if err != nil {
t.Fatal(err)
}
if !sd.IsValid() {
t.Fatal("Invalid security descriptor")
}
sdStr := sd.String()
if !strings.HasPrefix(sdStr, "D:(A;") {
t.Fatalf("DACL = %q; want D:(A;...", sdStr)
}
}
func TestSddlConversion(t *testing.T) {
sd, err := windows.SecurityDescriptorFromString("O:BA")
if err != nil {
t.Fatal(err)
}
if !sd.IsValid() {
t.Fatal("Invalid security descriptor")
}
sdOwner, _, err := sd.Owner()
if err != nil {
t.Fatal(err)
}
if !sdOwner.IsValid() {
t.Fatal("Invalid security descriptor owner")
}
if !sdOwner.IsWellKnown(windows.WinBuiltinAdministratorsSid) {
t.Fatalf("Owner = %q; want S-1-5-32-544", sdOwner)
}
}
func TestBuildSecurityDescriptor(t *testing.T) {
const want = "O:SYD:(A;;GA;;;BA)"
adminSid, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid)
if err != nil {
t.Fatal(err)
}
systemSid, err := windows.CreateWellKnownSid(windows.WinLocalSystemSid)
if err != nil {
t.Fatal(err)
}
access := []windows.EXPLICIT_ACCESS{{
AccessPermissions: windows.GENERIC_ALL,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(adminSid),
},
}}
owner := &windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_USER,
TrusteeValue: windows.TrusteeValueFromSID(systemSid),
}
sd, err := windows.BuildSecurityDescriptor(owner, nil, access, nil, nil)
if err != nil {
t.Fatal(err)
}
sd, err = sd.ToAbsolute()
if err != nil {
t.Fatal(err)
}
err = sd.SetSACL(nil, false, false)
if err != nil {
t.Fatal(err)
}
if got := sd.String(); got != want {
t.Fatalf("SD = %q; want %q", got, want)
}
sd, err = sd.ToSelfRelative()
if err != nil {
t.Fatal(err)
}
if got := sd.String(); got != want {
t.Fatalf("SD = %q; want %q", got, want)
}
sd, err = windows.NewSecurityDescriptor()
if err != nil {
t.Fatal(err)
}
acl, err := windows.ACLFromEntries(access, nil)
if err != nil {
t.Fatal(err)
}
err = sd.SetDACL(acl, true, false)
if err != nil {
t.Fatal(err)
}
err = sd.SetOwner(systemSid, false)
if err != nil {
t.Fatal(err)
}
if got := sd.String(); got != want {
t.Fatalf("SD = %q; want %q", got, want)
}
sd, err = sd.ToSelfRelative()
if err != nil {
t.Fatal(err)
}
if got := sd.String(); got != want {
t.Fatalf("SD = %q; want %q", got, want)
}
}
// getEntriesFromACL returns a list of explicit access control entries associated with the given ACL.
func getEntriesFromACL(acl *windows.ACL) (aces []*windows.ACCESS_ALLOWED_ACE, err error) {
aces = make([]*windows.ACCESS_ALLOWED_ACE, acl.AceCount)
for i := uint16(0); i < acl.AceCount; i++ {
err = windows.GetAce(acl, uint32(i), &aces[i])
if err != nil {
return nil, err
}
}
return aces, nil
}
func TestGetACEsFromACL(t *testing.T) {
// Create a temporary file to set ACLs on and test getting the ACEs from the ACL.
f, err := os.CreateTemp("", "foo.lish")
defer os.Remove(f.Name())
if err = f.Close(); err != nil {
t.Fatal(err)
}
// Well-known SID Strings:
// https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems
ownerSid, err := windows.StringToSid("S-1-3-2")
if err != nil {
t.Fatal(err)
}
groupSid, err := windows.StringToSid("S-1-3-3")
if err != nil {
t.Fatal(err)
}
worldSid, err := windows.StringToSid("S-1-1-0")
if err != nil {
t.Fatal(err)
}
ownerPermissions := windows.ACCESS_MASK(windows.GENERIC_ALL)
groupPermissions := windows.ACCESS_MASK(windows.GENERIC_READ | windows.GENERIC_EXECUTE)
worldPermissions := windows.ACCESS_MASK(windows.GENERIC_READ)
access := []windows.EXPLICIT_ACCESS{
{
AccessPermissions: ownerPermissions,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeValue: windows.TrusteeValueFromSID(ownerSid),
},
},
{
AccessPermissions: groupPermissions,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(groupSid),
},
},
{
AccessPermissions: worldPermissions,
AccessMode: windows.GRANT_ACCESS,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(worldSid),
},
},
}
acl, err := windows.ACLFromEntries(access, nil)
if err != nil {
t.Fatal(err)
}
// Set new ACL.
err = windows.SetNamedSecurityInfo(
f.Name(),
windows.SE_FILE_OBJECT,
windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION,
nil,
nil,
acl,
nil,
)
if err != nil {
t.Fatal(err)
}
descriptor, err := windows.GetNamedSecurityInfo(
f.Name(),
windows.SE_FILE_OBJECT,
windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION|windows.OWNER_SECURITY_INFORMATION|windows.GROUP_SECURITY_INFORMATION,
)
if err != nil {
t.Fatal(err)
}
dacl, _, err := descriptor.DACL()
if err != nil {
t.Fatal(err)
}
owner, _, err := descriptor.Owner()
if err != nil {
t.Fatal(err)
}
group, _, err := descriptor.Group()
if err != nil {
t.Fatal(err)
}
entries, err := getEntriesFromACL(dacl)
if err != nil {
t.Fatal(err)
}
if len(entries) != 3 {
t.Fatalf("Expected newly set ACL to only have 3 entries.")
}
// https://docs.microsoft.com/en-us/windows/win32/fileio/file-access-rights-constants
read := uint32(windows.FILE_READ_DATA | windows.FILE_READ_ATTRIBUTES)
write := uint32(windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_ATTRIBUTES | windows.FILE_WRITE_EA)
execute := uint32(windows.FILE_READ_DATA | windows.FILE_EXECUTE)
// Check the set ACEs. We should have the equivalent of 754.
for _, entry := range entries {
mask := uint32(entry.Mask)
actual := 0
if mask&read == read {
actual |= 4
}
if mask&write == write {
actual |= 2
}
if mask&execute == execute {
actual |= 1
}
entrySid := (*windows.SID)(unsafe.Pointer(&entry.SidStart))
if owner.Equals(entrySid) {
if actual != 7 {
t.Fatalf("Expected owner to have FullAccess permissions.")
}
} else if group.Equals(entrySid) {
if actual != 5 {
t.Fatalf("Expected group to have only Read and Execute permissions.")
}
} else if worldSid.Equals(entrySid) {
if actual != 4 {
t.Fatalf("Expected the World to have only Read permissions.")
}
} else {
t.Fatalf("Unexpected SID in ACEs: %s", entrySid.String())
}
}
}
func TestGetDiskFreeSpaceEx(t *testing.T) {
cwd, err := windows.UTF16PtrFromString(".")
if err != nil {
t.Fatalf(`failed to call UTF16PtrFromString("."): %v`, err)
}
var freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes uint64
if err := windows.GetDiskFreeSpaceEx(cwd, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes); err != nil {
t.Fatalf("failed to call GetDiskFreeSpaceEx: %v", err)
}
if freeBytesAvailableToCaller == 0 {
t.Errorf("freeBytesAvailableToCaller: got 0; want > 0")
}
if totalNumberOfBytes == 0 {
t.Errorf("totalNumberOfBytes: got 0; want > 0")
}
if totalNumberOfFreeBytes == 0 {
t.Errorf("totalNumberOfFreeBytes: got 0; want > 0")
}
}
func TestGetPreferredUILanguages(t *testing.T) {
tab := map[string]func(flags uint32) ([]string, error){
"GetProcessPreferredUILanguages": windows.GetProcessPreferredUILanguages,
"GetThreadPreferredUILanguages": windows.GetThreadPreferredUILanguages,
"GetUserPreferredUILanguages": windows.GetUserPreferredUILanguages,
"GetSystemPreferredUILanguages": windows.GetSystemPreferredUILanguages,
}
for fName, f := range tab {
lang, err := f(windows.MUI_LANGUAGE_ID)
if err != nil {
t.Errorf(`failed to call %v(MUI_LANGUAGE_ID): %v`, fName, err)
}
for _, l := range lang {
_, err := strconv.ParseUint(l, 16, 16)
if err != nil {
t.Errorf(`%v(MUI_LANGUAGE_ID) returned unexpected LANGID: %v`, fName, l)
}
}
lang, err = f(windows.MUI_LANGUAGE_NAME)
if err != nil {
t.Errorf(`failed to call %v(MUI_LANGUAGE_NAME): %v`, fName, err)
}
}
}
func TestProcessWorkingSetSizeEx(t *testing.T) {
// Grab a handle to the current process
hProcess := windows.CurrentProcess()
// Allocate memory to store the result of the query
var minimumWorkingSetSize, maximumWorkingSetSize uintptr
// Make the system-call
var flag uint32
windows.GetProcessWorkingSetSizeEx(hProcess, &minimumWorkingSetSize, &maximumWorkingSetSize, &flag)
// Set the new limits to the current ones
if err := windows.SetProcessWorkingSetSizeEx(hProcess, minimumWorkingSetSize, maximumWorkingSetSize, flag); err != nil {
t.Error(err)
}
}
func TestJobObjectInfo(t *testing.T) {
jo, err := windows.CreateJobObject(nil, nil)
if err != nil {
t.Fatalf("CreateJobObject failed: %v", err)
}
defer windows.CloseHandle(jo)
var info windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION
err = windows.QueryInformationJobObject(jo, windows.JobObjectExtendedLimitInformation,
uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)), nil)
if err != nil {
t.Fatalf("QueryInformationJobObject failed: %v", err)
}
const wantMemLimit = 4 * 1024
info.BasicLimitInformation.LimitFlags |= windows.JOB_OBJECT_LIMIT_PROCESS_MEMORY
info.ProcessMemoryLimit = wantMemLimit
_, err = windows.SetInformationJobObject(jo, windows.JobObjectExtendedLimitInformation,
uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)))
if err != nil {
t.Fatalf("SetInformationJobObject failed: %v", err)
}
err = windows.QueryInformationJobObject(jo, windows.JobObjectExtendedLimitInformation,
uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)), nil)
if err != nil {
t.Fatalf("QueryInformationJobObject failed: %v", err)
}
if have := info.ProcessMemoryLimit; wantMemLimit != have {
t.Errorf("ProcessMemoryLimit is wrong: want %v have %v", wantMemLimit, have)
}
}
func TestIsWow64Process2(t *testing.T) {
var processMachine, nativeMachine uint16
err := windows.IsWow64Process2(windows.CurrentProcess(), &processMachine, &nativeMachine)
if errors.Is(err, windows.ERROR_PROC_NOT_FOUND) {
maj, min, build := windows.RtlGetNtVersionNumbers()
if maj < 10 || (maj == 10 && min == 0 && build < 17763) {
t.Skip("not available on older versions of Windows")
return
}
}
if err != nil {
t.Fatalf("IsWow64Process2 failed: %v", err)
}
if processMachine == pe.IMAGE_FILE_MACHINE_UNKNOWN {
processMachine = nativeMachine
}
switch {
case processMachine == pe.IMAGE_FILE_MACHINE_AMD64 && runtime.GOARCH == "amd64":
case processMachine == pe.IMAGE_FILE_MACHINE_I386 && runtime.GOARCH == "386":
case processMachine == pe.IMAGE_FILE_MACHINE_ARMNT && runtime.GOARCH == "arm":
case processMachine == pe.IMAGE_FILE_MACHINE_ARM64 && runtime.GOARCH == "arm64":
default:
t.Errorf("IsWow64Process2 is wrong: want %v have %v", runtime.GOARCH, processMachine)
}
}
func TestNTStatusString(t *testing.T) {
want := "The name limit for the local computer network adapter card was exceeded."
got := windows.STATUS_TOO_MANY_NAMES.Error()
if want != got {
t.Errorf("NTStatus.Error did not return an expected error string - want %q; got %q", want, got)
}
}
func TestNTStatusConversion(t *testing.T) {
want := windows.ERROR_TOO_MANY_NAMES
got := windows.STATUS_TOO_MANY_NAMES.Errno()
if want != got {
t.Errorf("NTStatus.Errno = %q (0x%x); want %q (0x%x)", got.Error(), got, want.Error(), want)
}
}
func TestPEBFilePath(t *testing.T) {
peb := windows.RtlGetCurrentPeb()
if peb == nil || peb.Ldr == nil {
t.Error("unable to retrieve PEB with valid Ldr")
}
var entry *windows.LDR_DATA_TABLE_ENTRY
for cur := peb.Ldr.InMemoryOrderModuleList.Flink; cur != &peb.Ldr.InMemoryOrderModuleList; cur = cur.Flink {
e := (*windows.LDR_DATA_TABLE_ENTRY)(unsafe.Pointer(uintptr(unsafe.Pointer(cur)) - unsafe.Offsetof(windows.LDR_DATA_TABLE_ENTRY{}.InMemoryOrderLinks)))
if e.DllBase == peb.ImageBaseAddress {
entry = e
break
}
}
if entry == nil {
t.Error("unable to find Ldr entry for current process")
}
osPath, err := os.Executable()
if err != nil {
t.Errorf("unable to get path to current executable: %v", err)
}
pebPath := entry.FullDllName.String()
if osPath != pebPath {
t.Errorf("peb.Ldr.{entry}.FullDllName = %#q; want %#q", pebPath, osPath)
}
paramPath := peb.ProcessParameters.ImagePathName.String()
if osPath != paramPath {
t.Errorf("peb.ProcessParameters.ImagePathName.{entry}.ImagePathName = %#q; want %#q", paramPath, osPath)
}
osCwd, err := os.Getwd()
if err != nil {
t.Errorf("unable to get working directory: %v", err)
}
osCwd = filepath.Clean(osCwd)
paramCwd := filepath.Clean(peb.ProcessParameters.CurrentDirectory.DosPath.String())
if paramCwd != osCwd {
t.Errorf("peb.ProcessParameters.CurrentDirectory.DosPath = %#q; want %#q", paramCwd, osCwd)
}
}
func TestResourceExtraction(t *testing.T) {
system32, err := windows.GetSystemDirectory()
if err != nil {
t.Errorf("unable to find system32 directory: %v", err)
}
cmd, err := windows.LoadLibrary(filepath.Join(system32, "cmd.exe"))
if err != nil {
t.Errorf("unable to load cmd.exe: %v", err)
}
defer windows.FreeLibrary(cmd)
rsrc, err := windows.FindResource(cmd, windows.CREATEPROCESS_MANIFEST_RESOURCE_ID, windows.RT_MANIFEST)
if err != nil {
t.Errorf("unable to find cmd.exe manifest resource: %v", err)
}
manifest, err := windows.LoadResourceData(cmd, rsrc)
if err != nil {
t.Errorf("unable to load cmd.exe manifest resource data: %v", err)
}
if !bytes.Contains(manifest, []byte("</assembly>")) {
t.Errorf("did not find </assembly> in manifest")
}
}
func FuzzComposeCommandLine(f *testing.F) {
f.Add(`C:\foo.exe /bar /baz "-bag qux"`)
f.Add(`"C:\Program Files\Go\bin\go.exe" env`)
f.Add(`C:\"Program Files"\Go\bin\go.exe env`)
f.Add(`C:\"Program Files"\Go\bin\go.exe env`)
f.Add(`C:\"Pro"gram Files\Go\bin\go.exe env`)
f.Add(``)
f.Add(` `)
f.Add(`W\"0`)
f.Add("\"\f")
f.Add("\f")
f.Add("\x16")
f.Add(`"" ` + strings.Repeat("a", 8193))
f.Add(strings.Repeat(`"" `, 8193))
f.Add("\x00abcd")
f.Add("ab\x00cd")
f.Add("abcd\x00")
f.Add("\x00abcd\x00")
f.Add("\x00ab\x00cd\x00")
f.Add("\x00\x00\x00")
f.Add("\x16\x00\x16")
f.Add(`C:\Program Files\Go\bin\go.exe` + "\x00env")
f.Add(`"C:\Program Files\Go\bin\go.exe"` + "\x00env")
f.Add(`C:\"Program Files"\Go\bin\go.exe` + "\x00env")
f.Add(`C:\"Pro"gram Files\Go\bin\go.exe` + "\x00env")
f.Add("\x00" + strings.Repeat("a", 8192))
f.Add("\x00" + strings.Repeat("a", 8193))
f.Add(strings.Repeat("\x00"+strings.Repeat("a", 8192), 4))
f.Fuzz(func(t *testing.T, s string) {
// DecomposeCommandLine is the “control” for our experiment:
// if it returns a particular list of arguments, then we know
// it must be possible to create an input string that produces
// exactly those arguments.
//
// However, DecomposeCommandLine returns an error if the string
// contains a NUL byte. In that case, we will fall back to
// strings.Split, and be a bit more permissive about the results.
args, err := windows.DecomposeCommandLine(s)
argsFromSplit := false
if err == nil {
if testing.Verbose() {
t.Logf("DecomposeCommandLine(%#q) = %#q", s, args)
}
} else {
t.Logf("DecomposeCommandLine: %v", err)
if !strings.Contains(s, "\x00") {
// The documentation for CommandLineToArgv takes for granted that
// the first argument is a valid file path, and doesn't describe any
// specific behavior for malformed arguments. Empirically it seems to
// tolerate anything we throw at it, but if we discover cases where it
// actually returns an error we might need to relax this check.
t.Fatal("(error unexpected)")
}
// Since DecomposeCommandLine can't handle this string,
// interpret it as the raw arguments to ComposeCommandLine.
args = strings.Split(s, "\x00")
argsFromSplit = true
for i, arg := range args {
if !utf8.ValidString(arg) {
// We need to encode the arguments as UTF-16 to pass them to
// CommandLineToArgvW, so skip inputs that are not valid: they might
// have one or more runes converted to replacement characters.
t.Skipf("skipping: input %d is not valid UTF-8", i)
}
}
if testing.Verbose() {
t.Logf("using input: %#q", args)
}
}
// It's ok if we compose a different command line than what was read.
// Just check that we are able to compose something that round-trips
// to the same results as the original.
commandLine := windows.ComposeCommandLine(args)
t.Logf("ComposeCommandLine(_) = %#q", commandLine)
got, err := windows.DecomposeCommandLine(commandLine)
if err != nil {
t.Fatalf("DecomposeCommandLine: unexpected error: %v", err)
}
if testing.Verbose() {
t.Logf("DecomposeCommandLine(_) = %#q", got)
}
var badMatches []int
for i := range args {
if i >= len(got) {
badMatches = append(badMatches, i)
continue
}
want := args[i]
if got[i] != want {
if i == 0 && argsFromSplit {
// It is possible that args[0] cannot be encoded exactly, because
// CommandLineToArgvW doesn't unescape that argument in the same way
// as the others: since the first argument is assumed to be the name
// of the program itself, we only have the option of quoted or not.
//
// If args[0] contains a space or control character, we must quote it
// to avoid it being split into multiple arguments.
// If args[0] already starts with a quote character, we have no way
// to indicate that character is part of the literal argument.
// In either case, if the string already contains a quote character
// we must avoid misinterpreting that character as the end of the
// quoted argument string.
//
// Unfortunately, ComposeCommandLine does not return an error, so we
// can't report existing quote characters as errors.
// Instead, we strip out the problematic quote characters from the
// argument, and quote the remainder.
// For paths like C:\"Program Files"\Go\bin\go.exe that is arguably
// what the caller intended anyway, and for other strings it seems
// less harmful than corrupting the subsequent arguments.
if got[i] == strings.ReplaceAll(want, `"`, ``) {
continue
}
}
badMatches = append(badMatches, i)
}
}
if len(badMatches) != 0 {
t.Errorf("Incorrect decomposition at indices: %v", badMatches)
}
})
}
func TestWinVerifyTrust(t *testing.T) {
evsignedfile := `.\testdata\ev-signed-file.exe`
evsignedfile16, err := windows.UTF16PtrFromString(evsignedfile)
if err != nil {
t.Fatalf("unable to get utf16 of %s: %v", evsignedfile, err)
}
data := &windows.WinTrustData{
Size: uint32(unsafe.Sizeof(windows.WinTrustData{})),
UIChoice: windows.WTD_UI_NONE,
RevocationChecks: windows.WTD_REVOKE_NONE, // No revocation checking, in case the tests don't have network connectivity.
UnionChoice: windows.WTD_CHOICE_FILE,
StateAction: windows.WTD_STATEACTION_VERIFY,
FileOrCatalogOrBlobOrSgnrOrCert: unsafe.Pointer(&windows.WinTrustFileInfo{
Size: uint32(unsafe.Sizeof(windows.WinTrustFileInfo{})),
FilePath: evsignedfile16,
}),
}
verifyErr := windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
data.StateAction = windows.WTD_STATEACTION_CLOSE
closeErr := windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
if verifyErr != nil {
t.Errorf("%s did not verify: %v", evsignedfile, verifyErr)
}
if closeErr != nil {
t.Errorf("unable to free verification resources: %v", closeErr)
}
// Now that we've verified the legitimate file verifies, let's corrupt it and see if it correctly fails.
corruptedEvsignedfile := filepath.Join(t.TempDir(), "corrupted-file")
evsignedfileBytes, err := os.ReadFile(evsignedfile)
if err != nil {
t.Fatalf("unable to read %s bytes: %v", evsignedfile, err)
}
if len(evsignedfileBytes) > 0 {
evsignedfileBytes[len(evsignedfileBytes)/2-1]++
}
err = os.WriteFile(corruptedEvsignedfile, evsignedfileBytes, 0755)
if err != nil {
t.Fatalf("unable to write corrupted ntoskrnl.exe bytes: %v", err)
}
evsignedfile16, err = windows.UTF16PtrFromString(corruptedEvsignedfile)
if err != nil {
t.Fatalf("unable to get utf16 of ntoskrnl.exe: %v", err)
}
data = &windows.WinTrustData{
Size: uint32(unsafe.Sizeof(windows.WinTrustData{})),
UIChoice: windows.WTD_UI_NONE,
RevocationChecks: windows.WTD_REVOKE_NONE, // No revocation checking, in case the tests don't have network connectivity.
UnionChoice: windows.WTD_CHOICE_FILE,
StateAction: windows.WTD_STATEACTION_VERIFY,
FileOrCatalogOrBlobOrSgnrOrCert: unsafe.Pointer(&windows.WinTrustFileInfo{
Size: uint32(unsafe.Sizeof(windows.WinTrustFileInfo{})),
FilePath: evsignedfile16,
}),
}
verifyErr = windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
data.StateAction = windows.WTD_STATEACTION_CLOSE
closeErr = windows.WinVerifyTrustEx(windows.InvalidHWND, &windows.WINTRUST_ACTION_GENERIC_VERIFY_V2, data)
if verifyErr != windows.Errno(windows.TRUST_E_BAD_DIGEST) {
t.Errorf("%s did not fail to verify as expected: %v", corruptedEvsignedfile, verifyErr)
}
if closeErr != nil {
t.Errorf("unable to free verification resources: %v", closeErr)
}
}
func TestEnumProcesses(t *testing.T) {
var (
pids [2]uint32
outSize uint32
)
err := windows.EnumProcesses(pids[:], &outSize)
if err != nil {
t.Fatalf("unable to enumerate processes: %v", err)
}
// Regression check for go.dev/issue/60223
if outSize != 8 {
t.Errorf("unexpected bytes returned: %d", outSize)
}
// Most likely, this should be [0, 4].
// 0 is the system idle pseudo-process. 4 is the initial system process ID.
// This test expects that at least one of the PIDs is not 0.
if pids[0] == 0 && pids[1] == 0 {
t.Errorf("all PIDs are 0")
}
}
func TestProcessModules(t *testing.T) {
process, err := windows.GetCurrentProcess()
if err != nil {
t.Fatalf("unable to get current process: %v", err)
}
// NB: Assume that we're always the first module. This technically isn't documented anywhere (that I could find), but seems to always hold.
var module windows.Handle
var cbNeeded uint32
err = windows.EnumProcessModules(process, &module, uint32(unsafe.Sizeof(module)), &cbNeeded)
if err != nil {
t.Fatalf("EnumProcessModules failed: %v", err)
}
var moduleEx windows.Handle
err = windows.EnumProcessModulesEx(process, &moduleEx, uint32(unsafe.Sizeof(moduleEx)), &cbNeeded, windows.LIST_MODULES_DEFAULT)
if err != nil {
t.Fatalf("EnumProcessModulesEx failed: %v", err)
}
if module != moduleEx {
t.Fatalf("module from EnumProcessModules does not match EnumProcessModulesEx: %v != %v", module, moduleEx)
}
exePath, err := os.Executable()
if err != nil {
t.Fatalf("unable to get current executable path: %v", err)
}
modulePathUTF16 := make([]uint16, len(exePath)+1)
err = windows.GetModuleFileNameEx(process, module, &modulePathUTF16[0], uint32(len(modulePathUTF16)))
if err != nil {
t.Fatalf("GetModuleFileNameEx failed: %v", err)
}
modulePath := windows.UTF16ToString(modulePathUTF16)
if modulePath != exePath {
t.Fatalf("module does not match executable for GetModuleFileNameEx: %s != %s", modulePath, exePath)
}
err = windows.GetModuleBaseName(process, module, &modulePathUTF16[0], uint32(len(modulePathUTF16)))
if err != nil {
t.Fatalf("GetModuleBaseName failed: %v", err)
}
modulePath = windows.UTF16ToString(modulePathUTF16)
baseExePath := filepath.Base(exePath)
if modulePath != baseExePath {
t.Fatalf("module does not match executable for GetModuleBaseName: %s != %s", modulePath, baseExePath)
}
var moduleInfo windows.ModuleInfo
err = windows.GetModuleInformation(process, module, &moduleInfo, uint32(unsafe.Sizeof(moduleInfo)))
if err != nil {
t.Fatalf("GetModuleInformation failed: %v", err)