request.rb 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. require 'uri'
  2. module Msf
  3. class Plugin::Requests < Msf::Plugin
  4. class ConsoleCommandDispatcher
  5. include Msf::Ui::Console::CommandDispatcher
  6. HELP_REGEX = /^-?-h(?:elp)?$/.freeze
  7. def name
  8. 'Request'
  9. end
  10. def commands
  11. {
  12. 'request' => "Make a request of the specified type (#{types.join(', ')})"
  13. }
  14. end
  15. # Dynamically determine the types of requests that are supported based on
  16. # methods prefixed with "parse_args".
  17. #
  18. # @return [Array<String>] The supported request types.
  19. def types
  20. parse_methods = public_methods.select { |m| m.to_s =~ /^parse_args_/ }
  21. parse_methods.collect { |m| m.to_s.split('_').slice(2..-1).join('_') }
  22. end
  23. # The main handler for the request command.
  24. #
  25. # @param args [Array<String>] The array of arguments provided by the user.
  26. # @return [nil]
  27. def cmd_request(*args)
  28. # short circuit the whole deal if they need help
  29. return help if args.empty?
  30. return help if args.length == 1 && args.first =~ HELP_REGEX
  31. # detect the request type from the uri which must be the last arg given
  32. uri = args.last
  33. if uri && uri =~ %r{^[A-Za-z]{3,5}://}
  34. type = uri.split('://', 2).first
  35. else
  36. print_error('The last argument must be a valid and supported URI')
  37. return help
  38. end
  39. # parse options
  40. opts, opt_parser = parse_args(args, type)
  41. if opts && opt_parser
  42. # handle any "global" options
  43. if opts[:output_file]
  44. begin
  45. opts[:output_file] = File.new(opts[:output_file], 'w')
  46. rescue ::Errno::EACCES, Errno::EISDIR, Errno::ENOTDIR
  47. return help(opt_parser, 'Failed to open the specified file for output')
  48. end
  49. end
  50. # hand off the actual request to the appropriate request handler
  51. handler_method = "handle_request_#{type}".to_sym
  52. if respond_to?(handler_method)
  53. # call the appropriate request handler
  54. send(handler_method, opts, opt_parser)
  55. else
  56. # this should be dead code if parse_args is doing it's job correctly
  57. help(opt_parser, "No request handler found for type (#{type}).")
  58. end
  59. elsif types.include? type
  60. help(opt_parser)
  61. else
  62. help
  63. end
  64. end
  65. # Parse the provided arguments by dispatching to the correct method based
  66. # on the specified type.
  67. #
  68. # @param args [Array<String>] The command line arguments to parse.
  69. # @param type [String] The protocol type that the request is for such as
  70. # HTTP.
  71. # @return [Array<Hash, Rex::Parser::Arguments>] An array with the options
  72. # hash and the argument parser.
  73. def parse_args(args, type = 'http')
  74. type.downcase!
  75. parse_method = "parse_args_#{type}".to_sym
  76. if respond_to?(parse_method)
  77. send(parse_method, args, type)
  78. else
  79. print_error("Unsupported URI type: #{type}")
  80. end
  81. end
  82. # Parse the provided arguments for making HTTPS requests. The argument flags
  83. # are intended to be similar to the curl utility.
  84. #
  85. # @param args [Array<String>] The command line arguments to parse.
  86. # @param type [String] The protocol type that the request is for.
  87. # @return [Array<Hash, Rex::Parser::Arguments>] An array with the options
  88. # hash and the argument parser.
  89. def parse_args_https(args = [], type = 'https')
  90. # just let http do it
  91. parse_args_http(args, type)
  92. end
  93. # Parse the provided arguments for making HTTP requests. The argument flags
  94. # are intended to be similar to the curl utility.
  95. #
  96. # @param args [Array<String>] The command line arguments to parse.
  97. # @param type [String] The protocol type that the request is for.
  98. # @return [Array<Hash>, Rex::Parser::Arguments>] An array with the options
  99. # hash and the argument parser.
  100. def parse_args_http(args = [], _type = 'http')
  101. opt_parser = Rex::Parser::Arguments.new(
  102. '-0' => [ false, 'Use HTTP 1.0' ],
  103. '-1' => [ false, 'Use TLSv1 (SSL)' ],
  104. '-2' => [ false, 'Use SSLv2 (SSL)' ],
  105. '-3' => [ false, 'Use SSLv3 (SSL)' ],
  106. '-A' => [ true, 'User-Agent to send to server' ],
  107. '-d' => [ true, 'HTTP POST data' ],
  108. '-G' => [ false, 'Send the -d data with an HTTP GET' ],
  109. '-h' => [ false, 'This help text' ],
  110. '-H' => [ true, 'Custom header to pass to server' ],
  111. '-i' => [ false, 'Include headers in the output' ],
  112. '-I' => [ false, 'Show document info only' ],
  113. '-o' => [ true, 'Write output to <file> instead of stdout' ],
  114. '-u' => [ true, 'Server user and password' ],
  115. '-X' => [ true, 'Request method to use' ]
  116. # '-x' => [ true, 'Proxy to use, format: [proto://][user:pass@]host[:port]' +
  117. # ' Proto defaults to http:// and port to 1080'],
  118. )
  119. options = {
  120. headers: {},
  121. print_body: true,
  122. print_headers: false,
  123. ssl_version: 'Auto',
  124. user_agent: Rex::UserAgent.session_agent,
  125. version: '1.1'
  126. }
  127. opt_parser.parse(args) do |opt, _idx, val|
  128. case opt
  129. when '-0'
  130. options[:version] = '1.0'
  131. when '-1'
  132. options[:ssl_version] = 'TLS1'
  133. when '-2'
  134. options[:ssl_version] = 'SSL2'
  135. when '-3'
  136. options[:ssl_version] = 'SSL3'
  137. when '-A'
  138. options[:user_agent] = val
  139. when '-d'
  140. options[:data] = val
  141. options[:method] ||= 'POST'
  142. when '-G'
  143. options[:method] = 'GET'
  144. when HELP_REGEX
  145. # help(opt_parser)
  146. # guard to prevent further option processing & stymie request handling
  147. return [nil, opt_parser]
  148. when '-H'
  149. name, value = val.split(':', 2)
  150. options[:headers][name] = value.to_s.strip
  151. when '-i'
  152. options[:print_headers] = true
  153. when '-I'
  154. options[:print_headers] = true
  155. options[:print_body] = false
  156. options[:method] ||= 'HEAD'
  157. when '-o'
  158. options[:output_file] = File.expand_path(val)
  159. when '-u'
  160. val = val.split(':', 2) # only split on first ':' as per curl:
  161. # from curl man page: "The user name and passwords are split up on the
  162. # first colon, which makes it impossible to use a colon in the user
  163. # name with this option. The password can, still.
  164. options[:auth_username] = val.first
  165. options[:auth_password] = val.last
  166. when '-p'
  167. options[:auth_password] = val
  168. when '-X'
  169. options[:method] = val
  170. # when '-x'
  171. # @TODO proxy
  172. else
  173. options[:uri] = val
  174. end
  175. end
  176. unless options[:uri]
  177. help(opt_parser)
  178. end
  179. options[:method] ||= 'GET'
  180. options[:uri] = URI(options[:uri])
  181. [options, opt_parser]
  182. end
  183. # Perform an HTTPS request based on the user specified options.
  184. #
  185. # @param opts [Hash] The options to use for making the HTTPS request.
  186. # @option opts [String] :auth_username An optional username to use with
  187. # basic authentication.
  188. # @option opts [String] :auth_password An optional password to use with
  189. # basic authentication. This is only used when :auth_username is
  190. # specified.
  191. # @option opts [String] :data Any data to include within the body of the
  192. # request. Often used with the POST HTTP method.
  193. # @option opts [Hash] :headers A hash of additional headers to include in
  194. # the request.
  195. # @option opts [String] :method The HTTP method to use in the request.
  196. # @option opts [#write] :output_file A file to write the response data to.
  197. # @option opts [Boolean] :print_body Whether or not to print the body of the
  198. # response.
  199. # @option opts [Boolean] :print_headers Whether or not to print the headers
  200. # of the response.
  201. # @option opts [String] :ssl_version The version of SSL to use if the
  202. # request scheme is HTTPS.
  203. # @option opts [String] :uri The target uri to request.
  204. # @option opts [String] :user_agent The value to use in the User-Agent
  205. # header of the request.
  206. # @param opt_parser [Rex::Parser::Arguments] the argument parser for the
  207. # request type.
  208. # @return [nil]
  209. def handle_request_https(opts, opt_parser)
  210. # let http do it
  211. handle_request_http(opts, opt_parser)
  212. end
  213. # Perform an HTTP request based on the user specified options.
  214. #
  215. # @param opts [Hash] The options to use for making the HTTP request.
  216. # @option opts [String] :auth_username An optional username to use with
  217. # basic authentication.
  218. # @option opts [String] :auth_password An optional password to use with
  219. # basic authentication. This is only used when :auth_username is
  220. # specified.
  221. # @option opts [String] :data Any data to include within the body of the
  222. # request. Often used with the POST HTTP method.
  223. # @option opts [Hash] :headers A hash of additional headers to include in
  224. # the request.
  225. # @option opts [String] :method The HTTP method to use in the request.
  226. # @option opts [#write] :output_file A file to write the response data to.
  227. # @option opts [Boolean] :print_body Whether or not to print the body of the
  228. # response.
  229. # @option opts [Boolean] :print_headers Whether or not to print the headers
  230. # of the response.
  231. # @option opts [String] :ssl_version The version of SSL to use if the
  232. # request scheme is HTTPS.
  233. # @option opts [String] :uri The target uri to request.
  234. # @option opts [String] :user_agent The value to use in the User-Agent
  235. # header of the request.
  236. # @param opt_parser [Rex::Parser::Arguments] the argument parser for the
  237. # request type.
  238. # @return [nil]
  239. def handle_request_http(opts, _opt_parser)
  240. uri = opts[:uri]
  241. http_client = Rex::Proto::Http::Client.new(
  242. uri.host,
  243. uri.port,
  244. { 'Msf' => framework },
  245. uri.scheme == 'https',
  246. opts[:ssl_version]
  247. )
  248. if opts[:auth_username]
  249. auth_str = opts[:auth_username] + ':' + opts[:auth_password]
  250. auth_str = 'Basic ' + Rex::Text.encode_base64(auth_str)
  251. opts[:headers]['Authorization'] = auth_str
  252. end
  253. uri.path = '/' if uri.path.empty?
  254. begin
  255. http_client.connect
  256. req = http_client.request_cgi(
  257. 'agent' => opts[:user_agent],
  258. 'data' => opts[:data],
  259. 'headers' => opts[:headers],
  260. 'method' => opts[:method],
  261. 'password' => opts[:auth_password],
  262. 'query' => uri.query,
  263. 'uri' => uri.path,
  264. 'username' => opts[:auth_username],
  265. 'version' => opts[:version]
  266. )
  267. response = http_client.send_recv(req)
  268. rescue ::OpenSSL::SSL::SSLError
  269. print_error('Encountered an SSL error')
  270. rescue ::Errno::ECONNRESET
  271. print_error('The connection was reset by the peer')
  272. rescue ::EOFError, Errno::ETIMEDOUT, Rex::ConnectionError, ::Timeout::Error
  273. print_error('Encountered an error')
  274. ensure
  275. http_client.close
  276. end
  277. unless response
  278. opts[:output_file].close if opts[:output_file]
  279. return nil
  280. end
  281. if opts[:print_headers]
  282. output_line(opts, response.cmd_string)
  283. output_line(opts, response.headers.to_s)
  284. end
  285. output_line(opts, response.body) if opts[:print_body]
  286. if opts[:output_file]
  287. print_status("Wrote #{opts[:output_file].tell} bytes to #{opts[:output_file].path}")
  288. opts[:output_file].close
  289. end
  290. end
  291. # Output lines based on the provided options. Data is either printed to the
  292. # console or written to a file. Trailing new lines are removed.
  293. #
  294. # @param opts [Hash] The options as parsed from parse_args.
  295. # @option opts [#write, nil] :output_file An optional file to write the
  296. # output to.
  297. # @param line [String] The string to output.
  298. # @return [nil]
  299. def output_line(opts, line)
  300. if opts[:output_file].nil?
  301. if line[-2..] == "\r\n"
  302. print_line(line[0..-3])
  303. elsif line[-1] == "\n"
  304. print_line(line[0..-2])
  305. else
  306. print_line(line)
  307. end
  308. else
  309. opts[:output_file].write(line)
  310. end
  311. end
  312. # Print the appropriate help text depending on an optional option parser.
  313. #
  314. # @param opt_parser [Rex::Parser::Arguments] the argument parser for the
  315. # request type.
  316. # @param msg [String] the first line of the help text to display to the
  317. # user.
  318. # @return [nil]
  319. def help(opt_parser = nil, msg = 'Usage: request [options] uri')
  320. print_line(msg)
  321. if opt_parser
  322. print_line(opt_parser.usage)
  323. else
  324. print_line("Supported uri types are: #{types.collect { |t| t + '://' }.join(', ')}")
  325. print_line('To see usage for a specific uri type, use request -h uri')
  326. end
  327. end
  328. end
  329. def initialize(framework, opts)
  330. super
  331. add_console_dispatcher(ConsoleCommandDispatcher)
  332. end
  333. def cleanup
  334. remove_console_dispatcher('Request')
  335. end
  336. def name
  337. 'Request'
  338. end
  339. def desc
  340. 'Make requests from within Metasploit using various protocols.'
  341. end
  342. end
  343. end