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/http/response.rb
Views: 11704
1
# -*- coding: binary -*-
2
require 'cgi'
3
require 'uri'
4
5
require 'nokogiri'
6
require 'rkelly'
7
8
module Rex
9
module Proto
10
module Http
11
12
###
13
#
14
# HTTP response class.
15
#
16
###
17
class Response < Packet
18
19
##
20
#
21
# Builtin response class wrappers.
22
#
23
##
24
25
#
26
# HTTP 200/OK response class wrapper.
27
#
28
class OK < Response
29
def initialize(message = 'OK', proto = DefaultProtocol)
30
super(200, message, proto)
31
end
32
end
33
34
#
35
# HTTP 404/File not found response class wrapper.
36
#
37
class E404 < Response
38
def initialize(message = 'File not found', proto = DefaultProtocol)
39
super(404, message, proto)
40
end
41
end
42
43
#
44
# Constructage of the HTTP response with the supplied code, message, and
45
# protocol.
46
#
47
def initialize(code = 200, message = 'OK', proto = DefaultProtocol)
48
super()
49
50
self.code = code.to_i
51
self.message = message
52
self.proto = proto
53
54
# Default responses to auto content length on
55
self.auto_cl = true
56
57
# default chunk sizes (if chunked is used)
58
self.chunk_min_size = 1
59
self.chunk_max_size = 10
60
61
# 100 continue counter
62
self.count_100 = 0
63
end
64
65
#
66
# Gets cookies from the Set-Cookie header in a format to be used
67
# in the 'cookie' send_request field
68
#
69
def get_cookies
70
cookies = ""
71
if (self.headers.include?('Set-Cookie'))
72
set_cookies = self.headers['Set-Cookie']
73
key_vals = set_cookies.scan(/\s?([^, ;]+?)=([^, ;]*?)[;,]/)
74
key_vals.each do |k, v|
75
# Dont downcase actual cookie name as may be case sensitive
76
name = k.downcase
77
next if name == 'path'
78
next if name == 'expires'
79
next if name == 'domain'
80
next if name == 'max-age'
81
cookies << "#{k}=#{v}; "
82
end
83
end
84
85
return cookies.strip
86
end
87
88
#
89
# Gets cookies from the Set-Cookie header in a parsed format
90
#
91
def get_cookies_parsed
92
if (self.headers.include?('Set-Cookie'))
93
ret = CGI::Cookie::parse(self.headers['Set-Cookie'])
94
else
95
ret = {}
96
end
97
ret
98
end
99
100
101
# Returns a parsed HTML document.
102
# Instead of using regexes to parse the HTML body, you should use this and use the Nokogiri API.
103
#
104
# @see http://www.nokogiri.org/
105
# @return [Nokogiri::HTML::Document]
106
def get_html_document
107
Nokogiri::HTML(self.body)
108
end
109
110
# Returns a parsed XML document.
111
# Instead of using regexes to parse the XML body, you should use this and use the Nokogiri API.
112
#
113
# @see http://www.nokogiri.org/
114
# @return [Nokogiri::XML::Document]
115
def get_xml_document
116
Nokogiri::XML(self.body)
117
end
118
119
# Returns a parsed json document.
120
# Instead of using regexes to parse the JSON body, you should use this.
121
#
122
# @return [Hash]
123
def get_json_document
124
json = {}
125
126
begin
127
json = JSON.parse(self.body)
128
rescue JSON::ParserError => e
129
elog(e)
130
end
131
132
json
133
end
134
135
# Returns meta tags.
136
# You will probably want to use this the web app's version info (or other stuff) can be found
137
# in the metadata.
138
#
139
# @return [Array<Nokogiri::XML::Element>]
140
def get_html_meta_elements
141
n = get_html_document
142
n.search('//meta')
143
end
144
145
# Returns parsed JavaScript blocks.
146
# The parsed version is a RKelly object that allows you to be able do advanced parsing.
147
#
148
# @see https://github.com/tenderlove/rkelly
149
# @return [Array<RKelly::Nodes::SourceElementsNode>]
150
def get_html_scripts
151
n = get_html_document
152
rkelly = RKelly::Parser.new
153
n.search('//script').map { |s| rkelly.parse(s.text) }
154
end
155
156
157
# Returns a collection of found hidden inputs
158
#
159
# @return [Array<Hash>] An array, each element represents a form that contains a hash of found hidden inputs
160
# * 'name' [String] The hidden input's original name. The value is the hidden input's original value.
161
# @example
162
# res = send_request_cgi('uri'=>'/')
163
# inputs = res.get_hidden_inputs
164
# session_id = inputs[0]['sessionid'] # The first form's 'sessionid' hidden input
165
def get_hidden_inputs
166
forms = []
167
noko = get_html_document
168
noko.search("form").each_entry do |form|
169
found_inputs = {}
170
form.search("input").each_entry do |input|
171
input_type = input.attributes['type'] ? input.attributes['type'].value : ''
172
next if input_type !~ /hidden/i
173
174
input_name = input.attributes['name'] ? input.attributes['name'].value : ''
175
input_value = input.attributes['value'] ? input.attributes['value'].value : ''
176
found_inputs[input_name] = input_value unless input_name.empty?
177
end
178
forms << found_inputs unless found_inputs.empty?
179
end
180
181
forms
182
end
183
184
#
185
# Updates the various parts of the HTTP response command string.
186
#
187
def update_cmd_parts(str)
188
if (md = str.match(/HTTP\/(.+?)\s+(\d+)\s?(.+?)\r?\n?$/))
189
self.message = md[3].gsub(/\r/, '')
190
self.code = md[2].to_i
191
self.proto = md[1]
192
else
193
raise RuntimeError, "Invalid response command string", caller
194
end
195
196
check_100()
197
end
198
199
#
200
# Allow 100 Continues to be ignored by the caller
201
#
202
def check_100
203
# If this was a 100 continue with no data, reset
204
if self.code == 100 and (self.body_bytes_left == -1 or self.body_bytes_left == 0) and self.count_100 < 5
205
self.reset_except_queue
206
self.count_100 += 1
207
end
208
end
209
210
# Answers if the response is a redirection one.
211
#
212
# @return [Boolean] true if the response is a redirection, false otherwise.
213
def redirect?
214
[301, 302, 303, 307, 308].include?(code)
215
end
216
217
# Provides the uri of the redirection location.
218
#
219
# @return [URI] the uri of the redirection location.
220
# @return [nil] if the response hasn't a Location header or it isn't a valid uri.
221
def redirection
222
URI(headers['Location'])
223
rescue ArgumentError, ::URI::InvalidURIError
224
nil
225
end
226
227
#
228
# Returns the response based command string.
229
#
230
def cmd_string
231
"HTTP\/#{proto} #{code}#{(message and message.length > 0) ? ' ' + message : ''}\r\n"
232
end
233
234
#
235
# Used to store a copy of the original request
236
#
237
attr_accessor :request
238
239
#
240
# Host address:port associated with this request/response
241
#
242
attr_accessor :peerinfo
243
244
attr_accessor :code
245
attr_accessor :message
246
attr_accessor :proto
247
attr_accessor :count_100
248
end
249
250
end
251
end
252
end
253
254