CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/rex/proto/proxy/socks5/server.rb
Views: 11766
1
# -*- coding: binary -*-
2
3
require 'thread'
4
require 'rex/socket'
5
6
module Rex
7
module Proto
8
module Proxy
9
10
module Socks5
11
#
12
# A SOCKS5 proxy server.
13
#
14
class Server
15
#
16
# Create a new SOCKS5 server.
17
#
18
def initialize(opts={})
19
@opts = { 'ServerHost' => '0.0.0.0', 'ServerPort' => 1080 }
20
@opts = @opts.merge(opts)
21
@server = nil
22
@clients = ::Array.new
23
@running = false
24
@server_thread = nil
25
end
26
27
#
28
# Check if the server is running.
29
#
30
def is_running?
31
return @running
32
end
33
34
#
35
# Start the SOCKS5 server.
36
#
37
def start
38
begin
39
# create the servers main socket (ignore the context here because we don't want a remote bind)
40
@server = Rex::Socket::TcpServer.create(
41
'LocalHost' => @opts['ServerHost'],
42
'LocalPort' => @opts['ServerPort'],
43
'Comm' => @opts['Comm']
44
)
45
# signal we are now running
46
@running = true
47
# start the servers main thread to pick up new clients
48
@server_thread = Rex::ThreadFactory.spawn("SOCKS5ProxyServer", false) do
49
while @running
50
begin
51
# accept the client connection
52
sock = @server.accept
53
# and fire off a new client instance to handle it
54
ServerClient.new(self, sock, @opts).start
55
rescue
56
wlog("SOCKS5.start - server_thread - #{$!}")
57
end
58
end
59
end
60
rescue
61
wlog("SOCKS5.start - #{$!}")
62
return false
63
end
64
return true
65
end
66
67
#
68
# Block while the server is running.
69
#
70
def join
71
@server_thread.join if @server_thread
72
end
73
74
#
75
# Stop the SOCKS5 server.
76
#
77
def stop
78
if @running
79
# signal we are no longer running
80
@running = false
81
# stop any clients we have (create a new client array as client.stop will delete from @clients)
82
clients = @clients.dup
83
clients.each do | client |
84
client.stop
85
end
86
# close the server socket
87
@server.close if @server
88
# if the server thread did not terminate gracefully, kill it.
89
@server_thread.kill if @server_thread and @server_thread.alive?
90
end
91
return !@running
92
end
93
94
def add_client(client)
95
@clients << client
96
end
97
98
def remove_client(client)
99
@clients.delete(client)
100
end
101
102
attr_reader :opts
103
end
104
end
105
end
106
end
107
end
108
109