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/plugins/socket_logger.rb
Views: 11704
1
module Msf
2
###
3
#
4
# This class hooks all sockets created by a running exploit
5
#
6
###
7
8
class Plugin::SocketLogger < Msf::Plugin
9
10
###
11
#
12
# This class implements a socket communication logger
13
#
14
###
15
class MySocketEventHandler
16
include Rex::Socket::Comm::Events
17
18
def initialize(path, prefix)
19
@path = path
20
@prefix = prefix
21
end
22
23
def on_before_socket_create(comm, param); end
24
25
def on_socket_created(_comm, sock, param)
26
# Sockets created by the exploit have MsfExploit set and MsfPayload not set
27
if param.context && param.context['MsfExploit'] && !param.context['MsfPayload']
28
sock.extend(SocketLogger::SocketTracer)
29
sock.context = param.context
30
sock.params = param
31
sock.initlog(@path, @prefix)
32
end
33
end
34
end
35
36
def initialize(framework, opts)
37
log_path = opts['path'] || Msf::Config.log_directory
38
log_prefix = opts['prefix'] || 'socket_'
39
40
super
41
@eh = MySocketEventHandler.new(log_path, log_prefix)
42
Rex::Socket::Comm::Local.register_event_handler(@eh)
43
end
44
45
def cleanup
46
Rex::Socket::Comm::Local.deregister_event_handler(@eh)
47
end
48
49
def name
50
'socket_logger'
51
end
52
53
def desc
54
'Log socket operations to a directory as individual files'
55
end
56
57
end
58
end
59
60
# This module extends the captured socket instance
61
module SocketLogger
62
module SocketTracer
63
@@last_id = 0
64
65
attr_accessor :context, :params
66
67
# Hook the write method
68
def write(buf, opts = {})
69
@fd.puts "WRITE\t#{buf.length}\t#{Rex::Text.encode_base64(buf)}"
70
@fd.flush
71
super(buf, opts)
72
end
73
74
# Hook the read method
75
def read(length = nil, opts = {})
76
r = super(length, opts)
77
@fd.puts "READ\t#{r ? r.length : 0}\t#{Rex::Text.encode_base64(r.to_s)}"
78
@fd.flush
79
return r
80
end
81
82
def close(*args)
83
super(*args)
84
@fd.close
85
end
86
87
def format_socket_conn
88
"#{params.proto.upcase} #{params.localhost}:#{params.localport} > #{params.peerhost}:#{params.peerport}"
89
end
90
91
def format_module_info
92
return '' unless params.context && params.context['MsfExploit']
93
if params.context['MsfExploit'].respond_to? :fullname
94
return 'via ' + params.context['MsfExploit'].fullname
95
end
96
97
'via ' + params.context['MsfExploit'].to_s
98
end
99
100
def initlog(path, prefix)
101
@log_path = path
102
@log_prefix = prefix
103
@log_id = @@last_id
104
@@last_id += 1
105
@fd = File.open(File.join(@log_path, "#{@log_prefix}#{@log_id}.log"), 'w')
106
@fd.puts "Socket created at #{Time.now} (#{Time.now.to_i})"
107
@fd.puts "Info: #{format_socket_conn} #{format_module_info}"
108
@fd.puts ''
109
@fd.flush
110
end
111
end
112
end
113
114