CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/encoders/cmd/base64.rb
Views: 1904
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
class MetasploitModule < Msf::Encoder
7
Rank = GoodRanking
8
9
BASE64_BYTES = [
10
'A'.ord...'Z'.ord,
11
'a'.ord...'z'.ord,
12
'0'.ord...'9'.ord
13
].map(&:to_a).flatten + '+/='.bytes
14
15
def initialize
16
super(
17
'Name' => 'Base64 Command Encoder',
18
'Description' => %q{
19
This encoder uses base64 encoding to avoid bad characters.
20
},
21
'Author' => 'Spencer McIntyre',
22
'Arch' => ARCH_CMD,
23
'Platform' => %w[bsd bsdi linux osx solaris unix],
24
'EncoderType' => Msf::Encoder::Type::CmdPosixBase64)
25
26
register_advanced_options(
27
[
28
OptString.new('Base64Decoder', [ false, 'The binary to use for base64 decoding', '', %w[base64 base64-long base64-short openssl] ])
29
],
30
self.class
31
)
32
end
33
34
#
35
# Encodes the payload
36
#
37
def encode_block(state, buf)
38
return buf if (buf.bytes & state.badchars.bytes).empty?
39
40
raise EncodingError if (state.badchars.bytes & BASE64_BYTES).any?
41
raise EncodingError if state.badchars.include?('-')
42
43
ifs_encode_spaces = state.badchars.include?(' ')
44
raise EncodingError if ifs_encode_spaces && (state.badchars.bytes & '${}'.bytes).any?
45
46
base64_buf = Base64.strict_encode64(buf)
47
case datastore['Base64Decoder']
48
when 'base64'
49
raise EncodingError if (state.badchars.bytes & '(|)'.bytes).any?
50
51
base64_decoder = '(base64 --decode || base64 -d)'
52
when 'base64-long'
53
base64_decoder = 'base64 --decode'
54
when 'base64-short'
55
base64_decoder = 'base64 -d'
56
when 'openssl'
57
base64_decoder = 'openssl enc -base64 -d'
58
else
59
# find a decoder at runtime if we can use the necessary characters
60
if (state.badchars.bytes & '(|)>/&'.bytes).empty?
61
base64_decoder = '((command -v base64 >/dev/null && (base64 --decode || base64 -d)) || (command -v openssl >/dev/null && openssl enc -base64 -d))'
62
elsif (state.badchars.bytes & '(|)'.bytes).empty?
63
base64_decoder = '(base64 --decode || base64 -d)'
64
else
65
base64_decoder = 'openssl enc -base64 -d'
66
end
67
end
68
69
if (state.badchars.bytes & '|'.bytes).empty?
70
buf = "echo #{base64_buf}|#{base64_decoder}|sh"
71
elsif (state.badchars.bytes & '<()'.bytes).empty?
72
buf = "sh < <(#{base64_decoder} < <(echo #{base64_buf}))"
73
elsif (state.badchars.bytes & '<`\''.bytes).empty?
74
buf = "sh<<<`#{base64_decoder}<<<'#{base64_buf}'`"
75
else
76
raise EncodingError
77
end
78
79
buf = buf.gsub(/ +/, '${IFS}') if ifs_encode_spaces
80
buf
81
end
82
end
83
84