1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package waffle.windows.auth.impl;
25
26 import com.sun.jna.platform.win32.Advapi32Util;
27 import com.sun.jna.platform.win32.Advapi32Util.Account;
28 import com.sun.jna.platform.win32.Kernel32;
29 import com.sun.jna.platform.win32.WinNT.HANDLE;
30 import com.sun.jna.platform.win32.WinNT.WELL_KNOWN_SID_TYPE;
31
32 import java.util.ArrayList;
33 import java.util.List;
34
35 import waffle.windows.auth.IWindowsAccount;
36 import waffle.windows.auth.IWindowsIdentity;
37 import waffle.windows.auth.IWindowsImpersonationContext;
38
39
40
41
42 public class WindowsIdentityImpl implements IWindowsIdentity {
43
44
45 private final HANDLE windowsIdentity;
46
47
48 private Account[] userGroups;
49
50
51 private Account windowsAccount;
52
53
54
55
56
57
58
59 public WindowsIdentityImpl(final HANDLE newWindowsIdentity) {
60 this.windowsIdentity = newWindowsIdentity;
61 }
62
63
64
65
66
67
68 private Account getWindowsAccount() {
69 if (this.windowsAccount == null) {
70 this.windowsAccount = Advapi32Util.getTokenAccount(this.windowsIdentity);
71 }
72 return this.windowsAccount;
73 }
74
75
76
77
78
79
80 private Account[] getUserGroups() {
81 if (this.userGroups == null) {
82 this.userGroups = Advapi32Util.getTokenGroups(this.windowsIdentity);
83 }
84 return this.userGroups.clone();
85 }
86
87 @Override
88 public String getFqn() {
89 return this.getWindowsAccount().fqn;
90 }
91
92 @Override
93 public IWindowsAccount[] getGroups() {
94
95 final Account[] groups = this.getUserGroups();
96
97 final List<IWindowsAccount> result = new ArrayList<>(groups.length);
98 for (final Account userGroup : groups) {
99 final WindowsAccountImpl account = new WindowsAccountImpl(userGroup);
100 result.add(account);
101 }
102
103 return result.toArray(new IWindowsAccount[0]);
104 }
105
106 @Override
107 public byte[] getSid() {
108 return this.getWindowsAccount().sid;
109 }
110
111 @Override
112 public String getSidString() {
113 return this.getWindowsAccount().sidString;
114 }
115
116 @Override
117 public void dispose() {
118 if (this.windowsIdentity != null) {
119 Kernel32.INSTANCE.CloseHandle(this.windowsIdentity);
120 }
121 }
122
123 @Override
124 public IWindowsImpersonationContext impersonate() {
125 return new WindowsIdentityImpersonationContextImpl(this.windowsIdentity);
126 }
127
128 @Override
129 public boolean isGuest() {
130 for (final Account userGroup : this.getUserGroups()) {
131 if (Advapi32Util.isWellKnownSid(userGroup.sid, WELL_KNOWN_SID_TYPE.WinBuiltinGuestsSid)) {
132 return true;
133 }
134 if (Advapi32Util.isWellKnownSid(userGroup.sid, WELL_KNOWN_SID_TYPE.WinAccountDomainGuestsSid)) {
135 return true;
136 }
137 if (Advapi32Util.isWellKnownSid(userGroup.sid, WELL_KNOWN_SID_TYPE.WinAccountGuestSid)) {
138 return true;
139 }
140 }
141 return Advapi32Util.isWellKnownSid(this.getSid(), WELL_KNOWN_SID_TYPE.WinAnonymousSid);
142 }
143 }