forked from java-native-access/jna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Advapi32Util.java
executable file
·3417 lines (3165 loc) · 126 KB
/
Advapi32Util.java
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 (c) 2010 Daniel Doubrovkine, All Rights Reserved
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna.platform.win32;
import static com.sun.jna.platform.win32.WinBase.CREATE_FOR_DIR;
import static com.sun.jna.platform.win32.WinBase.CREATE_FOR_IMPORT;
import static com.sun.jna.platform.win32.WinNT.DACL_SECURITY_INFORMATION;
import static com.sun.jna.platform.win32.WinNT.FILE_ALL_ACCESS;
import static com.sun.jna.platform.win32.WinNT.FILE_GENERIC_EXECUTE;
import static com.sun.jna.platform.win32.WinNT.FILE_GENERIC_READ;
import static com.sun.jna.platform.win32.WinNT.FILE_GENERIC_WRITE;
import static com.sun.jna.platform.win32.WinNT.GENERIC_EXECUTE;
import static com.sun.jna.platform.win32.WinNT.GENERIC_READ;
import static com.sun.jna.platform.win32.WinNT.GENERIC_WRITE;
import static com.sun.jna.platform.win32.WinNT.GROUP_SECURITY_INFORMATION;
import static com.sun.jna.platform.win32.WinNT.OWNER_SECURITY_INFORMATION;
import static com.sun.jna.platform.win32.WinNT.PROTECTED_DACL_SECURITY_INFORMATION;
import static com.sun.jna.platform.win32.WinNT.PROTECTED_SACL_SECURITY_INFORMATION;
import static com.sun.jna.platform.win32.WinNT.SACL_SECURITY_INFORMATION;
import static com.sun.jna.platform.win32.WinNT.SE_DACL_PROTECTED;
import static com.sun.jna.platform.win32.WinNT.SE_SACL_PROTECTED;
import static com.sun.jna.platform.win32.WinNT.STANDARD_RIGHTS_READ;
import static com.sun.jna.platform.win32.WinNT.TOKEN_ADJUST_PRIVILEGES;
import static com.sun.jna.platform.win32.WinNT.TOKEN_DUPLICATE;
import static com.sun.jna.platform.win32.WinNT.TOKEN_IMPERSONATE;
import static com.sun.jna.platform.win32.WinNT.TOKEN_QUERY;
import static com.sun.jna.platform.win32.WinNT.UNPROTECTED_DACL_SECURITY_INFORMATION;
import static com.sun.jna.platform.win32.WinNT.UNPROTECTED_SACL_SECURITY_INFORMATION;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinBase.FE_EXPORT_FUNC;
import com.sun.jna.platform.win32.WinBase.FE_IMPORT_FUNC;
import com.sun.jna.platform.win32.WinBase.FILETIME;
import com.sun.jna.platform.win32.WinDef.BOOLByReference;
import com.sun.jna.platform.win32.WinDef.DWORD;
import com.sun.jna.platform.win32.WinDef.DWORDByReference;
import com.sun.jna.platform.win32.WinDef.ULONG;
import com.sun.jna.platform.win32.WinDef.ULONGByReference;
import com.sun.jna.platform.win32.WinNT.ACCESS_ACEStructure;
import com.sun.jna.platform.win32.WinNT.ACCESS_ALLOWED_ACE;
import com.sun.jna.platform.win32.WinNT.ACE_HEADER;
import com.sun.jna.platform.win32.WinNT.ACL;
import com.sun.jna.platform.win32.WinNT.EVENTLOGRECORD;
import com.sun.jna.platform.win32.WinNT.GENERIC_MAPPING;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.platform.win32.WinNT.HANDLEByReference;
import com.sun.jna.platform.win32.WinNT.PRIVILEGE_SET;
import com.sun.jna.platform.win32.WinNT.PSID;
import com.sun.jna.platform.win32.WinNT.PSIDByReference;
import com.sun.jna.platform.win32.WinNT.SECURITY_DESCRIPTOR_RELATIVE;
import com.sun.jna.platform.win32.WinNT.SECURITY_IMPERSONATION_LEVEL;
import com.sun.jna.platform.win32.WinNT.SID_AND_ATTRIBUTES;
import com.sun.jna.platform.win32.WinNT.SID_NAME_USE;
import com.sun.jna.platform.win32.WinNT.TOKEN_TYPE;
import com.sun.jna.platform.win32.WinReg.HKEY;
import com.sun.jna.platform.win32.WinReg.HKEYByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.LongByReference;
import com.sun.jna.ptr.PointerByReference;
import com.sun.jna.win32.W32APITypeMapper;
/**
* Advapi32 utility API.
*
* @author dblock[at]dblock.org
*/
public abstract class Advapi32Util {
/**
* An account.
*/
public static class Account {
/**
* Account name.
*/
public String name;
/**
* Account domain.
*/
public String domain;
/**
* Account SID.
*/
public byte[] sid;
/**
* String representation of the account SID.
*/
public String sidString;
/**
* Account type, one of SID_NAME_USE.
*/
public int accountType;
/**
* Fully qualified account name.
*/
public String fqn;
}
/**
* Retrieves the name of the user associated with the current thread.
*
* @return A user name.
*/
public static String getUserName() {
char[] buffer = new char[128];
IntByReference len = new IntByReference(buffer.length);
boolean result = Advapi32.INSTANCE.GetUserNameW(buffer, len);
if (!result) {
switch (Kernel32.INSTANCE.GetLastError()) {
case W32Errors.ERROR_INSUFFICIENT_BUFFER:
buffer = new char[len.getValue()];
break;
default:
throw new Win32Exception(Native.getLastError());
}
result = Advapi32.INSTANCE.GetUserNameW(buffer, len);
}
if (!result) {
throw new Win32Exception(Native.getLastError());
}
return Native.toString(buffer);
}
/**
* Retrieves a security identifier (SID) for the account on the current
* system.
*
* @param accountName
* Specifies the account name.
* @return A structure containing the account SID;
*/
public static Account getAccountByName(String accountName) {
return getAccountByName(null, accountName);
}
/**
* Retrieves a security identifier (SID) for a given account.
*
* @param systemName
* Name of the system.
* @param accountName
* Account name.
* @return A structure containing the account SID.
*/
public static Account getAccountByName(String systemName, String accountName) {
IntByReference pSid = new IntByReference(0);
IntByReference cchDomainName = new IntByReference(0);
PointerByReference peUse = new PointerByReference();
if (Advapi32.INSTANCE.LookupAccountName(systemName, accountName, null,
pSid, null, cchDomainName, peUse)) {
throw new RuntimeException(
"LookupAccountNameW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (pSid.getValue() == 0 || rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
Memory sidMemory = new Memory(pSid.getValue());
PSID result = new PSID(sidMemory);
char[] referencedDomainName = new char[cchDomainName.getValue() + 1];
if (!Advapi32.INSTANCE.LookupAccountName(systemName, accountName,
result, pSid, referencedDomainName, cchDomainName, peUse)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
Account account = new Account();
account.accountType = peUse.getPointer().getInt(0);
String[] accountNamePartsBs = accountName.split("\\\\", 2);
String[] accountNamePartsAt = accountName.split("@", 2);
if (accountNamePartsBs.length == 2) {
account.name = accountNamePartsBs[1];
} else if (accountNamePartsAt.length == 2) {
account.name = accountNamePartsAt[0];
} else {
account.name = accountName;
}
if (cchDomainName.getValue() > 0) {
account.domain = Native.toString(referencedDomainName);
account.fqn = account.domain + "\\" + account.name;
} else {
account.fqn = account.name;
}
account.sid = result.getBytes();
account.sidString = convertSidToStringSid(new PSID(account.sid));
return account;
}
/**
* Get the account by SID on the local system.
*
* @param sid SID.
*
* @return Account.
*/
public static Account getAccountBySid(PSID sid) {
return getAccountBySid(null, sid);
}
/**
* Get the account by SID.
*
* @param systemName
* Name of the system.
* @param sid
* SID.
* @return Account.
*/
public static Account getAccountBySid(String systemName, PSID sid) {
// Max username length (UNLEN) is 256, add space for null
IntByReference cchName = new IntByReference(257);
// Max fully qualified domain name is 255, add space for null
IntByReference cchDomainName = new IntByReference(256);
PointerByReference peUse = new PointerByReference();
char[] domainName = new char[cchDomainName.getValue()];
char[] name = new char[cchName.getValue()];
int rc = WinError.ERROR_SUCCESS;
if (!Advapi32.INSTANCE.LookupAccountSid(systemName, sid, name, cchName,
domainName, cchDomainName, peUse)) {
rc = Kernel32.INSTANCE.GetLastError();
if (rc != WinError.ERROR_NONE_MAPPED) {
throw new Win32Exception(rc);
}
}
Account account = new Account();
if (rc == WinError.ERROR_NONE_MAPPED) {
account.accountType = SID_NAME_USE.SidTypeUnknown;
account.name = "NONE_MAPPED";
} else {
account.accountType = peUse.getPointer().getInt(0);
account.name = Native.toString(name);
}
account.domain = Native.toString(domainName);
if (account.domain.isEmpty()) {
account.fqn = account.name;
} else {
account.fqn = account.domain + "\\" + account.name;
}
account.sid = sid.getBytes();
account.sidString = convertSidToStringSid(sid);
return account;
}
/**
* Convert a security identifier (SID) to a string format suitable for
* display, storage, or transmission.
*
* @param sid
* SID bytes.
* @return String SID.
*/
public static String convertSidToStringSid(PSID sid) {
PointerByReference stringSid = new PointerByReference();
if (!Advapi32.INSTANCE.ConvertSidToStringSid(sid, stringSid)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
Pointer ptr = stringSid.getValue();
try {
return ptr.getWideString(0);
} finally {
Kernel32Util.freeLocalMemory(ptr);
}
}
/**
* Convert a string representation of a security identifier (SID) to a
* binary format.
*
* @param sidString
* String SID.
* @return SID bytes.
*/
public static byte[] convertStringSidToSid(String sidString) {
PSIDByReference pSID = new PSIDByReference();
if (!Advapi32.INSTANCE.ConvertStringSidToSid(sidString, pSID)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
PSID value = pSID.getValue();
try {
return value.getBytes();
} finally {
Kernel32Util.freeLocalMemory(value.getPointer());
}
}
/**
* Compares a SID to a well known SID and returns TRUE if they match.
*
* @param sidString
* String representation of a SID.
* @param wellKnownSidType
* Member of the WELL_KNOWN_SID_TYPE enumeration to compare with
* the SID at pSid.
* @return True if the SID is of the well-known type, false otherwise.
*/
public static boolean isWellKnownSid(String sidString, int wellKnownSidType) {
PSIDByReference pSID = new PSIDByReference();
if (!Advapi32.INSTANCE.ConvertStringSidToSid(sidString, pSID)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
PSID value = pSID.getValue();
try {
return Advapi32.INSTANCE.IsWellKnownSid(value, wellKnownSidType);
} finally {
Kernel32Util.freeLocalMemory(value.getPointer());
}
}
/**
* Compares a SID to a well known SID and returns TRUE if they match.
*
* @param sidBytes
* Byte representation of a SID.
* @param wellKnownSidType
* Member of the WELL_KNOWN_SID_TYPE enumeration to compare with
* the SID at pSid.
* @return True if the SID is of the well-known type, false otherwise.
*/
public static boolean isWellKnownSid(byte[] sidBytes, int wellKnownSidType) {
PSID pSID = new PSID(sidBytes);
return Advapi32.INSTANCE.IsWellKnownSid(pSID, wellKnownSidType);
}
/**
* Align cbAcl on a DWORD
* @param cbAcl size to align
* @return the aligned size
*/
public static int alignOnDWORD(int cbAcl) {
return (cbAcl + (DWORD.SIZE - 1)) & 0xfffffffc;
}
/**
* Helper function to calculate the size of an ACE for a given PSID size
* @param sidLength length of the sid
* @return size of the ACE
*/
public static int getAceSize(int sidLength) {
return Native.getNativeSize(ACCESS_ALLOWED_ACE.class, null)
+ sidLength
- DWORD.SIZE;
}
/**
* Get an account name from a string SID on the local machine.
*
* @param sidString
* SID.
* @return Account.
*/
public static Account getAccountBySid(String sidString) {
return getAccountBySid(null, sidString);
}
/**
* Get an account name from a string SID.
*
* @param systemName
* System name.
* @param sidString
* SID.
* @return Account.
*/
public static Account getAccountBySid(String systemName, String sidString) {
return getAccountBySid(systemName, new PSID(convertStringSidToSid(sidString)));
}
/**
* This function returns the groups associated with a security token, such
* as a user token.
*
* @param hToken
* Token.
* @return Token groups.
*/
public static Account[] getTokenGroups(HANDLE hToken) {
// get token group information size
IntByReference tokenInformationLength = new IntByReference();
if (Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, null, 0,
tokenInformationLength)) {
throw new RuntimeException(
"Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
// get token group information
WinNT.TOKEN_GROUPS groups = new WinNT.TOKEN_GROUPS(
tokenInformationLength.getValue());
if (!Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, groups,
tokenInformationLength.getValue(), tokenInformationLength)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
ArrayList<Account> userGroups = new ArrayList<Account>();
// make array of names
for (SID_AND_ATTRIBUTES sidAndAttribute : groups.getGroups()) {
Account group;
try {
group = Advapi32Util.getAccountBySid(sidAndAttribute.Sid);
} catch (Exception e) {
group = new Account();
group.sid = sidAndAttribute.Sid.getBytes();
group.sidString = Advapi32Util
.convertSidToStringSid(sidAndAttribute.Sid);
group.name = group.sidString;
group.fqn = group.sidString;
group.accountType = SID_NAME_USE.SidTypeGroup;
}
userGroups.add(group);
}
return userGroups.toArray(new Account[0]);
}
/**
* This function returns the primary group associated with a security token,
* such as a user token.
*
* @param hToken
* Token.
* @return Token primary group.
*/
public static Account getTokenPrimaryGroup(HANDLE hToken) {
// get token group information size
IntByReference tokenInformationLength = new IntByReference();
if (Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenPrimaryGroup, null, 0,
tokenInformationLength)) {
throw new RuntimeException("Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
// get token group information
WinNT.TOKEN_PRIMARY_GROUP primaryGroup = new WinNT.TOKEN_PRIMARY_GROUP(tokenInformationLength.getValue());
if (!Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenPrimaryGroup,
primaryGroup, tokenInformationLength.getValue(), tokenInformationLength)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
Account group;
try {
group = Advapi32Util.getAccountBySid(primaryGroup.PrimaryGroup);
} catch (Exception e) {
group = new Account();
group.sid = primaryGroup.PrimaryGroup.getBytes();
group.sidString = Advapi32Util.convertSidToStringSid(primaryGroup.PrimaryGroup);
group.name = group.sidString;
group.fqn = group.sidString;
group.accountType = SID_NAME_USE.SidTypeGroup;
}
return group;
}
/**
* This function returns the information about the user who owns a security
* token,
*
* @param hToken
* Token.
* @return Token user.
*/
public static Account getTokenAccount(HANDLE hToken) {
// get token group information size
IntByReference tokenInformationLength = new IntByReference();
if (Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenUser, null, 0,
tokenInformationLength)) {
throw new RuntimeException(
"Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
// get token user information
WinNT.TOKEN_USER user = new WinNT.TOKEN_USER(
tokenInformationLength.getValue());
if (!Advapi32.INSTANCE.GetTokenInformation(hToken,
WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user,
tokenInformationLength.getValue(), tokenInformationLength)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return getAccountBySid(user.User.Sid);
}
/**
* Return the group memberships of the currently logged on user.
*
* @return An array of groups.
*/
public static Account[] getCurrentUserGroups() {
HANDLEByReference phToken = new HANDLEByReference();
Win32Exception err = null;
try {
// open thread or process token
HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread();
if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle,
TOKEN_DUPLICATE | TOKEN_QUERY, true, phToken)) {
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != W32Errors.ERROR_NO_TOKEN) {
throw new Win32Exception(rc);
}
HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess();
if (!Advapi32.INSTANCE.OpenProcessToken(processHandle,
TOKEN_DUPLICATE | TOKEN_QUERY, phToken)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
}
return getTokenGroups(phToken.getValue());
} catch(Win32Exception e) {
err = e;
throw err; // re-throw in order to invoke finally block
} finally {
HANDLE hToken = phToken.getValue();
if (!WinBase.INVALID_HANDLE_VALUE.equals(hToken)) {
try {
Kernel32Util.closeHandle(hToken);
} catch(Win32Exception e) {
if (err == null) {
err = e;
} else {
err.addSuppressedReflected(e);
}
}
}
if (err != null) {
throw err;
}
}
}
/**
* Checks whether a registry key exists.
*
* @param root
* HKEY_LOCAL_MACHINE, etc.
* @param key
* Path to the registry key.
* @return True if the key exists.
*/
public static boolean registryKeyExists(HKEY root, String key) {
return registryKeyExists(root, key, 0);
}
/**
* Checks whether a registry key exists.
*
* @param root
* HKEY_LOCAL_MACHINE, etc.
* @param key
* Path to the registry key.
* @param samDesiredExtra
* Registry key security and access rights to be requested in addition to WinNT.KEY_READ.
* (e.g WinNT.KEY_WOW64_32KEY or WinNT.KEY_WOW64_64KEY to force 32bit or 64bit registry access.)
* @return True if the key exists.
*/
public static boolean registryKeyExists(HKEY root, String key, int samDesiredExtra) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | samDesiredExtra,
phkKey);
switch (rc) {
case W32Errors.ERROR_SUCCESS:
Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
return true;
case W32Errors.ERROR_FILE_NOT_FOUND:
return false;
default:
throw new Win32Exception(rc);
}
}
/**
* Checks whether a registry value exists.
*
* @param root
* HKEY_LOCAL_MACHINE, etc.
* @param key
* Registry key path.
* @param value
* Value name.
* @return True if the value exists.
*/
public static boolean registryValueExists(HKEY root, String key, String value) {
return registryValueExists(root, key, value, 0);
}
/**
* Checks whether a registry value exists.
*
* @param root
* HKEY_LOCAL_MACHINE, etc.
* @param key
* Registry key path.
* @param value
* Value name.
* @param samDesiredExtra
* Registry key security and access rights to be requested in addition to WinNT.KEY_READ.
* (e.g WinNT.KEY_WOW64_32KEY or WinNT.KEY_WOW64_64KEY to force 32bit or 64bit registry access.)
* @return True if the value exists.
*/
public static boolean registryValueExists(HKEY root, String key,
String value, int samDesiredExtra) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | samDesiredExtra,
phkKey);
switch (rc) {
case W32Errors.ERROR_SUCCESS:
break;
case W32Errors.ERROR_FILE_NOT_FOUND:
return false;
default:
throw new Win32Exception(rc);
}
try {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
rc = Advapi32.INSTANCE.RegQueryValueEx(phkKey.getValue(), value, 0,
lpType, (Pointer) null, lpcbData);
switch (rc) {
case W32Errors.ERROR_SUCCESS:
case W32Errors.ERROR_MORE_DATA:
case W32Errors.ERROR_INSUFFICIENT_BUFFER:
return true;
case W32Errors.ERROR_FILE_NOT_FOUND:
return false;
default:
throw new Win32Exception(rc);
}
} finally {
if (phkKey.getValue() != WinBase.INVALID_HANDLE_VALUE) {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
}
/**
* Get a registry REG_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetStringValue(HKEY root, String key,
String value) {
return registryGetStringValue(root, key, value, 0);
}
/**
* Get a registry REG_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @param samDesiredExtra
* Registry key security and access rights to be requested in addition to WinNT.KEY_READ.
* (e.g WinNT.KEY_WOW64_32KEY or WinNT.KEY_WOW64_64KEY to force 32bit or 64bit registry access.)
* @return String value.
*/
public static String registryGetStringValue(HKEY root, String key,
String value, int samDesiredExtra) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | samDesiredExtra ,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetStringValue(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry REG_SZ value.
*
* @param hKey
* Parent Key.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetStringValue(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (Pointer) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_SZ
&& lpType.getValue() != WinNT.REG_EXPAND_SZ) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue()
+ ", expected REG_SZ or REG_EXPAND_SZ");
}
if (lpcbData.getValue() == 0) {
return "";
}
// See comment in #registryGetValue
Memory mem = new Memory(lpcbData.getValue() + Native.WCHAR_SIZE);
mem.clear();
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, mem, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (W32APITypeMapper.DEFAULT == W32APITypeMapper.UNICODE) {
return mem.getWideString(0);
} else {
return mem.getString(0);
}
}
/**
* Get a registry REG_EXPAND_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetExpandableStringValue(HKEY root,
String key, String value) {
return registryGetExpandableStringValue(root, key, value, 0);
}
/**
* Get a registry REG_EXPAND_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @param samDesiredExtra
* Registry key security and access rights to be requested in addition to WinNT.KEY_READ.
* (e.g WinNT.KEY_WOW64_32KEY or WinNT.KEY_WOW64_64KEY to force 32bit or 64bit registry access.)
* @return String value.
*/
public static String registryGetExpandableStringValue(HKEY root,
String key, String value, int samDesiredExtra) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | samDesiredExtra,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetExpandableStringValue(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry REG_EXPAND_SZ value.
*
* @param hKey
* Parent Key.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String registryGetExpandableStringValue(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_EXPAND_SZ) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue() + ", expected REG_SZ");
}
if (lpcbData.getValue() == 0) {
return "";
}
// See comment in #registryGetValue
Memory mem = new Memory(lpcbData.getValue() + Native.WCHAR_SIZE);
mem.clear();
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, mem, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (W32APITypeMapper.DEFAULT == W32APITypeMapper.UNICODE) {
return mem.getWideString(0);
} else {
return mem.getString(0);
}
}
/**
* Get a registry REG_MULTI_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String[] registryGetStringArray(HKEY root, String key,
String value) {
return registryGetStringArray(root, key, value, 0);
}
/**
* Get a registry REG_MULTI_SZ value.
*
* @param root
* Root key.
* @param key
* Registry path.
* @param value
* Name of the value to retrieve.
* @param samDesiredExtra
* Registry key security and access rights to be requested in addition to WinNT.KEY_READ.
* (e.g WinNT.KEY_WOW64_32KEY or WinNT.KEY_WOW64_64KEY to force 32bit or 64bit registry access.)
* @return String value.
*/
public static String[] registryGetStringArray(HKEY root, String key,
String value, int samDesiredExtra) {
HKEYByReference phkKey = new HKEYByReference();
int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | samDesiredExtra,
phkKey);
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
try {
return registryGetStringArray(phkKey.getValue(), value);
} finally {
rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue());
if (rc != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(rc);
}
}
}
/**
* Get a registry REG_MULTI_SZ value.
*
* @param hKey
* Parent Key.
* @param value
* Name of the value to retrieve.
* @return String value.
*/
public static String[] registryGetStringArray(HKEY hKey, String value) {
IntByReference lpcbData = new IntByReference();
IntByReference lpType = new IntByReference();
int rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, (char[]) null, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
if (lpType.getValue() != WinNT.REG_MULTI_SZ) {
throw new RuntimeException("Unexpected registry type "
+ lpType.getValue() + ", expected REG_SZ");
}
// Allocate enougth memroy to hold value and ensure terminating
// double NULL chars are present
Memory data = new Memory(lpcbData.getValue() + 2 * Native.WCHAR_SIZE);
data.clear();
rc = Advapi32.INSTANCE.RegQueryValueEx(hKey, value, 0,
lpType, data, lpcbData);
if (rc != W32Errors.ERROR_SUCCESS
&& rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
return regMultiSzBufferToStringArray(data);
}
/**
* Convert the null-delimited buffer of strings returned from registry values of
* type {@link WinNT#REG_MULTI_SZ} to an array of strings.
*
* @param data
* A buffer containing strings delimited by a null character, ending
* with two null characters.
* @return An array of strings corresponding to the strings in the buffer.
*/
static String[] regMultiSzBufferToStringArray(Memory data) {
ArrayList<String> result = new ArrayList<String>();
int offset = 0;
while (offset < data.size()) {
String s;
if (W32APITypeMapper.DEFAULT == W32APITypeMapper.UNICODE) {
s = data.getWideString(offset);
offset += s.length() * Native.WCHAR_SIZE;
offset += Native.WCHAR_SIZE;
} else {
s = data.getString(offset);
offset += s.length();
offset += 1;
}
if (s.length() == 0) {
// A sequence of null-terminated strings,
// terminated by an empty string (\0).
// => The first empty string terminates the
break;
} else {
result.add(s);
}
}
return result.toArray(new String[0]);